cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
datagramsession/session.go
70lines · modecode
| 1 | package datagramsession |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | |
| 7 | "github.com/google/uuid" |
| 8 | ) |
| 9 | |
| 10 | // Each Session is a bidirectional pipe of datagrams between transport and dstConn |
| 11 | // Currently the only implementation of transport is quic DatagramMuxer |
| 12 | // Destination can be a connection with origin or with eyeball |
| 13 | // When the destination is origin: |
| 14 | // - Datagrams from edge are read by Manager from the transport. Manager finds the corresponding Session and calls the |
| 15 | // write method of the Session to send to origin |
| 16 | // - Datagrams from origin are read from conn and SentTo transport. Transport will return them to eyeball |
| 17 | // When the destination is eyeball: |
| 18 | // - Datagrams from eyeball are read from conn and SentTo transport. Transport will send them to cloudflared |
| 19 | // - Datagrams from cloudflared are read by Manager from the transport. Manager finds the corresponding Session and calls the |
| 20 | // write method of the Session to send to eyeball |
| 21 | type Session struct { |
| 22 | id uuid.UUID |
| 23 | transport transport |
| 24 | dstConn io.ReadWriteCloser |
| 25 | doneChan chan struct{} |
| 26 | } |
| 27 | |
| 28 | func newSession(id uuid.UUID, transport transport, dstConn io.ReadWriteCloser) *Session { |
| 29 | return &Session{ |
| 30 | id: id, |
| 31 | transport: transport, |
| 32 | dstConn: dstConn, |
| 33 | doneChan: make(chan struct{}), |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | func (s *Session) Serve(ctx context.Context) error { |
| 38 | serveCtx, cancel := context.WithCancel(ctx) |
| 39 | defer cancel() |
| 40 | go func() { |
| 41 | select { |
| 42 | case <-serveCtx.Done(): |
| 43 | case <-s.doneChan: |
| 44 | } |
| 45 | s.dstConn.Close() |
| 46 | }() |
| 47 | // QUIC implementation copies data to another buffer before returning https://github.com/lucas-clemente/quic-go/blob/v0.24.0/session.go#L1967-L1975 |
| 48 | // This makes it safe to share readBuffer between iterations |
| 49 | readBuffer := make([]byte, 1280) |
| 50 | for { |
| 51 | // TODO: TUN-5303: origin proxy should determine the buffer size |
| 52 | n, err := s.dstConn.Read(readBuffer) |
| 53 | if n > 0 { |
| 54 | if err := s.transport.SendTo(s.id, readBuffer[:n]); err != nil { |
| 55 | return err |
| 56 | } |
| 57 | } |
| 58 | if err != nil { |
| 59 | return err |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | func (s *Session) writeToDst(payload []byte) (int, error) { |
| 65 | return s.dstConn.Write(payload) |
| 66 | } |
| 67 | |
| 68 | func (s *Session) close() { |
| 69 | close(s.doneChan) |
| 70 | } |
| 71 | |