stream.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2019 Jigsaw Operations LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package net
  15. import (
  16. "io"
  17. "github.com/Jigsaw-Code/outline-sdk/transport"
  18. )
  19. type DuplexConn = transport.StreamConn
  20. func copyOneWay(leftConn, rightConn DuplexConn) (int64, error) {
  21. n, err := io.Copy(leftConn, rightConn)
  22. // Send FIN to indicate EOF
  23. leftConn.CloseWrite()
  24. // Release reader resources
  25. rightConn.CloseRead()
  26. return n, err
  27. }
  28. // Relay copies between left and right bidirectionally. Returns number of
  29. // bytes copied from right to left, from left to right, and any error occurred.
  30. // Relay allows for half-closed connections: if one side is done writing, it can
  31. // still read all remaining data from its peer.
  32. func Relay(leftConn, rightConn DuplexConn) (int64, int64, error) {
  33. type res struct {
  34. N int64
  35. Err error
  36. }
  37. ch := make(chan res)
  38. go func() {
  39. n, err := copyOneWay(rightConn, leftConn)
  40. ch <- res{n, err}
  41. }()
  42. n, err := copyOneWay(leftConn, rightConn)
  43. rs := <-ch
  44. if err == nil {
  45. err = rs.Err
  46. }
  47. return n, rs.N, err
  48. }