File
Blob: spec/tun/pipe.go
| 1 | package tun |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net" |
| 8 | "sync" |
| 9 | |
| 10 | pool "github.com/libp2p/go-buffer-pool" |
| 11 | ) |
| 12 | |
| 13 | const ( |
| 14 | BufferSize = 1024 * 16 |
| 15 | ) |
| 16 | |
| 17 | func IsTimeout(err error) bool { |
| 18 | t := errors.Is(err, context.DeadlineExceeded) |
| 19 | if t { |
| 20 | return t |
| 21 | } |
| 22 | if e, ok := err.(net.Error); ok { |
| 23 | return e.Timeout() |
| 24 | } |
| 25 | return false |
| 26 | } |
| 27 | |
| 28 | func Pipe(a, b io.ReadWriteCloser) <-chan error { |
| 29 | errChan := make(chan error, 2) |
| 30 | var wg sync.WaitGroup |
| 31 | var closeOnce sync.Once |
| 32 | |
| 33 | copyOneWay := func(src, dst io.ReadWriteCloser) { |
| 34 | defer wg.Done() |
| 35 | |
| 36 | buf := pool.Get(BufferSize) |
| 37 | defer pool.Put(buf) |
| 38 | |
| 39 | _, err := io.CopyBuffer(dst, src, buf) |
| 40 | |
| 41 | // The first completion owns teardown. In particular, the reverse copy's |
| 42 | // cancellation must not abort a successfully completed destination write. |
| 43 | closeOnce.Do(func() { |
| 44 | if conn, ok := dst.(interface{ CloseGracefully() error }); ok && err == nil { |
| 45 | conn.CloseGracefully() |
| 46 | } else { |
| 47 | dst.Close() |
| 48 | } |
| 49 | src.Close() |
| 50 | }) |
| 51 | |
| 52 | if err != nil { |
| 53 | errChan <- err |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | wg.Add(2) |
| 58 | go copyOneWay(a, b) |
| 59 | go copyOneWay(b, a) |
| 60 | go func() { |
| 61 | wg.Wait() |
| 62 | close(errChan) |
| 63 | }() |
| 64 | |
| 65 | return errChan |
| 66 | } |