|
| 1 | +package stream |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/hex" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "runtime/debug" |
| 8 | + "sync/atomic" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/getsentry/raven-go" |
| 12 | + "github.com/pkg/errors" |
| 13 | + "github.com/rs/zerolog" |
| 14 | + |
| 15 | + "github.com/cloudflare/cloudflared/cfio" |
| 16 | +) |
| 17 | + |
| 18 | +type bidirectionalStreamStatus struct { |
| 19 | + doneChan chan struct{} |
| 20 | + anyDone uint32 |
| 21 | +} |
| 22 | + |
| 23 | +func newBiStreamStatus() *bidirectionalStreamStatus { |
| 24 | + return &bidirectionalStreamStatus{ |
| 25 | + doneChan: make(chan struct{}, 2), |
| 26 | + anyDone: 0, |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func (s *bidirectionalStreamStatus) markUniStreamDone() { |
| 31 | + atomic.StoreUint32(&s.anyDone, 1) |
| 32 | + s.doneChan <- struct{}{} |
| 33 | +} |
| 34 | + |
| 35 | +func (s *bidirectionalStreamStatus) waitAnyDone() { |
| 36 | + <-s.doneChan |
| 37 | +} |
| 38 | +func (s *bidirectionalStreamStatus) isAnyDone() bool { |
| 39 | + return atomic.LoadUint32(&s.anyDone) > 0 |
| 40 | +} |
| 41 | + |
| 42 | +// Pipe copies copy data to & from provided io.ReadWriters. |
| 43 | +func Pipe(tunnelConn, originConn io.ReadWriter, log *zerolog.Logger) { |
| 44 | + status := newBiStreamStatus() |
| 45 | + |
| 46 | + go unidirectionalStream(tunnelConn, originConn, "origin->tunnel", status, log) |
| 47 | + go unidirectionalStream(originConn, tunnelConn, "tunnel->origin", status, log) |
| 48 | + |
| 49 | + // If one side is done, we are done. |
| 50 | + status.waitAnyDone() |
| 51 | +} |
| 52 | + |
| 53 | +func unidirectionalStream(dst io.Writer, src io.Reader, dir string, status *bidirectionalStreamStatus, log *zerolog.Logger) { |
| 54 | + defer func() { |
| 55 | + // The bidirectional streaming spawns 2 goroutines to stream each direction. |
| 56 | + // If any ends, the callstack returns, meaning the Tunnel request/stream (depending on http2 vs quic) will |
| 57 | + // close. In such case, if the other direction did not stop (due to application level stopping, e.g., if a |
| 58 | + // server/origin listens forever until closure), it may read/write from the underlying ReadWriter (backed by |
| 59 | + // the Edge<->cloudflared transport) in an unexpected state. |
| 60 | + // Because of this, we set this recover() logic. |
| 61 | + if r := recover(); r != nil { |
| 62 | + if status.isAnyDone() { |
| 63 | + // We handle such unexpected errors only when we detect that one side of the streaming is done. |
| 64 | + log.Debug().Msgf("Gracefully handled error %v in Streaming for %s, error %s", r, dir, debug.Stack()) |
| 65 | + } else { |
| 66 | + // Otherwise, this is unexpected, but we prevent the program from crashing anyway. |
| 67 | + log.Warn().Msgf("Gracefully handled unexpected error %v in Streaming for %s, error %s", r, dir, debug.Stack()) |
| 68 | + |
| 69 | + tags := make(map[string]string) |
| 70 | + tags["root"] = "websocket.stream" |
| 71 | + tags["dir"] = dir |
| 72 | + switch rval := r.(type) { |
| 73 | + case error: |
| 74 | + raven.CaptureError(rval, tags) |
| 75 | + default: |
| 76 | + rvalStr := fmt.Sprint(rval) |
| 77 | + raven.CaptureMessage(rvalStr, tags) |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + }() |
| 82 | + |
| 83 | + _, err := copyData(dst, src, dir) |
| 84 | + if err != nil { |
| 85 | + log.Debug().Msgf("%s copy: %v", dir, err) |
| 86 | + } |
| 87 | + status.markUniStreamDone() |
| 88 | +} |
| 89 | + |
| 90 | +// when set to true, enables logging of content copied to/from origin and tunnel |
| 91 | +const debugCopy = false |
| 92 | + |
| 93 | +func copyData(dst io.Writer, src io.Reader, dir string) (written int64, err error) { |
| 94 | + if debugCopy { |
| 95 | + // copyBuffer is based on stdio Copy implementation but shows copied data |
| 96 | + copyBuffer := func(dst io.Writer, src io.Reader, dir string) (written int64, err error) { |
| 97 | + var buf []byte |
| 98 | + size := 32 * 1024 |
| 99 | + buf = make([]byte, size) |
| 100 | + for { |
| 101 | + t := time.Now() |
| 102 | + nr, er := src.Read(buf) |
| 103 | + if nr > 0 { |
| 104 | + fmt.Println(dir, t.UnixNano(), "\n"+hex.Dump(buf[0:nr])) |
| 105 | + nw, ew := dst.Write(buf[0:nr]) |
| 106 | + if nw < 0 || nr < nw { |
| 107 | + nw = 0 |
| 108 | + if ew == nil { |
| 109 | + ew = errors.New("invalid write") |
| 110 | + } |
| 111 | + } |
| 112 | + written += int64(nw) |
| 113 | + if ew != nil { |
| 114 | + err = ew |
| 115 | + break |
| 116 | + } |
| 117 | + if nr != nw { |
| 118 | + err = io.ErrShortWrite |
| 119 | + break |
| 120 | + } |
| 121 | + } |
| 122 | + if er != nil { |
| 123 | + if er != io.EOF { |
| 124 | + err = er |
| 125 | + } |
| 126 | + break |
| 127 | + } |
| 128 | + } |
| 129 | + return written, err |
| 130 | + } |
| 131 | + return copyBuffer(dst, src, dir) |
| 132 | + } else { |
| 133 | + return cfio.Copy(dst, src) |
| 134 | + } |
| 135 | +} |
0 commit comments