packet_handler_map.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. package quic
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "sync"
  8. "time"
  9. "v2ray.com/core/external/github.com/lucas-clemente/quic-go/internal/protocol"
  10. "v2ray.com/core/external/github.com/lucas-clemente/quic-go/internal/utils"
  11. "v2ray.com/core/external/github.com/lucas-clemente/quic-go/internal/wire"
  12. )
  13. type packetHandlerEntry struct {
  14. handler packetHandler
  15. resetToken *[16]byte
  16. }
  17. // The packetHandlerMap stores packetHandlers, identified by connection ID.
  18. // It is used:
  19. // * by the server to store sessions
  20. // * when multiplexing outgoing connections to store clients
  21. type packetHandlerMap struct {
  22. mutex sync.RWMutex
  23. conn net.PacketConn
  24. connIDLen int
  25. handlers map[string] /* string(ConnectionID)*/ packetHandlerEntry
  26. resetTokens map[[16]byte] /* stateless reset token */ packetHandler
  27. server unknownPacketHandler
  28. closed bool
  29. deleteRetiredSessionsAfter time.Duration
  30. logger utils.Logger
  31. }
  32. var _ packetHandlerManager = &packetHandlerMap{}
  33. func newPacketHandlerMap(conn net.PacketConn, connIDLen int, logger utils.Logger) packetHandlerManager {
  34. m := &packetHandlerMap{
  35. conn: conn,
  36. connIDLen: connIDLen,
  37. handlers: make(map[string]packetHandlerEntry),
  38. resetTokens: make(map[[16]byte]packetHandler),
  39. deleteRetiredSessionsAfter: protocol.RetiredConnectionIDDeleteTimeout,
  40. logger: logger,
  41. }
  42. go m.listen()
  43. return m
  44. }
  45. func (h *packetHandlerMap) Add(id protocol.ConnectionID, handler packetHandler) {
  46. h.mutex.Lock()
  47. h.handlers[string(id)] = packetHandlerEntry{handler: handler}
  48. h.mutex.Unlock()
  49. }
  50. func (h *packetHandlerMap) AddWithResetToken(id protocol.ConnectionID, handler packetHandler, token [16]byte) {
  51. h.mutex.Lock()
  52. h.handlers[string(id)] = packetHandlerEntry{handler: handler, resetToken: &token}
  53. h.resetTokens[token] = handler
  54. h.mutex.Unlock()
  55. }
  56. func (h *packetHandlerMap) Remove(id protocol.ConnectionID) {
  57. h.removeByConnectionIDAsString(string(id))
  58. }
  59. func (h *packetHandlerMap) removeByConnectionIDAsString(id string) {
  60. h.mutex.Lock()
  61. if handlerEntry, ok := h.handlers[id]; ok {
  62. if token := handlerEntry.resetToken; token != nil {
  63. delete(h.resetTokens, *token)
  64. }
  65. delete(h.handlers, id)
  66. }
  67. h.mutex.Unlock()
  68. }
  69. func (h *packetHandlerMap) Retire(id protocol.ConnectionID) {
  70. h.retireByConnectionIDAsString(string(id))
  71. }
  72. func (h *packetHandlerMap) retireByConnectionIDAsString(id string) {
  73. time.AfterFunc(h.deleteRetiredSessionsAfter, func() {
  74. h.removeByConnectionIDAsString(id)
  75. })
  76. }
  77. func (h *packetHandlerMap) SetServer(s unknownPacketHandler) {
  78. h.mutex.Lock()
  79. h.server = s
  80. h.mutex.Unlock()
  81. }
  82. func (h *packetHandlerMap) CloseServer() {
  83. h.mutex.Lock()
  84. h.server = nil
  85. var wg sync.WaitGroup
  86. for id, handlerEntry := range h.handlers {
  87. handler := handlerEntry.handler
  88. if handler.GetPerspective() == protocol.PerspectiveServer {
  89. wg.Add(1)
  90. go func(id string, handler packetHandler) {
  91. // session.Close() blocks until the CONNECTION_CLOSE has been sent and the run-loop has stopped
  92. _ = handler.Close()
  93. h.retireByConnectionIDAsString(id)
  94. wg.Done()
  95. }(id, handler)
  96. }
  97. }
  98. h.mutex.Unlock()
  99. wg.Wait()
  100. }
  101. func (h *packetHandlerMap) close(e error) error {
  102. h.mutex.Lock()
  103. if h.closed {
  104. h.mutex.Unlock()
  105. return nil
  106. }
  107. h.closed = true
  108. var wg sync.WaitGroup
  109. for _, handlerEntry := range h.handlers {
  110. wg.Add(1)
  111. go func(handlerEntry packetHandlerEntry) {
  112. handlerEntry.handler.destroy(e)
  113. wg.Done()
  114. }(handlerEntry)
  115. }
  116. if h.server != nil {
  117. h.server.closeWithError(e)
  118. }
  119. h.mutex.Unlock()
  120. wg.Wait()
  121. return getMultiplexer().RemoveConn(h.conn)
  122. }
  123. func (h *packetHandlerMap) listen() {
  124. for {
  125. buffer := getPacketBuffer()
  126. data := buffer.Slice
  127. // The packet size should not exceed protocol.MaxReceivePacketSize bytes
  128. // If it does, we only read a truncated packet, which will then end up undecryptable
  129. n, addr, err := h.conn.ReadFrom(data)
  130. if err != nil {
  131. h.close(err)
  132. return
  133. }
  134. h.handlePacket(addr, buffer, data[:n])
  135. }
  136. }
  137. func (h *packetHandlerMap) handlePacket(
  138. addr net.Addr,
  139. buffer *packetBuffer,
  140. data []byte,
  141. ) {
  142. packets, err := h.parsePacket(addr, buffer, data)
  143. if err != nil {
  144. h.logger.Debugf("error parsing packets from %s: %s", addr, err)
  145. // This is just the error from parsing the last packet.
  146. // We still need to process the packets that were successfully parsed before.
  147. }
  148. if len(packets) == 0 {
  149. buffer.Release()
  150. return
  151. }
  152. h.handleParsedPackets(packets)
  153. }
  154. func (h *packetHandlerMap) parsePacket(
  155. addr net.Addr,
  156. buffer *packetBuffer,
  157. data []byte,
  158. ) ([]*receivedPacket, error) {
  159. rcvTime := time.Now()
  160. packets := make([]*receivedPacket, 0, 1)
  161. var counter int
  162. var lastConnID protocol.ConnectionID
  163. for len(data) > 0 {
  164. hdr, err := wire.ParseHeader(bytes.NewReader(data), h.connIDLen)
  165. // drop the packet if we can't parse the header
  166. if err != nil {
  167. return packets, fmt.Errorf("error parsing header: %s", err)
  168. }
  169. if counter > 0 && !hdr.DestConnectionID.Equal(lastConnID) {
  170. return packets, fmt.Errorf("coalesced packet has different destination connection ID: %s, expected %s", hdr.DestConnectionID, lastConnID)
  171. }
  172. lastConnID = hdr.DestConnectionID
  173. var rest []byte
  174. if hdr.IsLongHeader {
  175. if protocol.ByteCount(len(data)) < hdr.ParsedLen()+hdr.Length {
  176. return packets, fmt.Errorf("packet length (%d bytes) is smaller than the expected length (%d bytes)", len(data)-int(hdr.ParsedLen()), hdr.Length)
  177. }
  178. packetLen := int(hdr.ParsedLen() + hdr.Length)
  179. rest = data[packetLen:]
  180. data = data[:packetLen]
  181. }
  182. if counter > 0 {
  183. buffer.Split()
  184. }
  185. counter++
  186. packets = append(packets, &receivedPacket{
  187. remoteAddr: addr,
  188. hdr: hdr,
  189. rcvTime: rcvTime,
  190. data: data,
  191. buffer: buffer,
  192. })
  193. // only log if this actually a coalesced packet
  194. if h.logger.Debug() && (counter > 1 || len(rest) > 0) {
  195. h.logger.Debugf("Parsed a coalesced packet. Part %d: %d bytes. Remaining: %d bytes.", counter, len(packets[counter-1].data), len(rest))
  196. }
  197. data = rest
  198. }
  199. return packets, nil
  200. }
  201. func (h *packetHandlerMap) handleParsedPackets(packets []*receivedPacket) {
  202. h.mutex.RLock()
  203. defer h.mutex.RUnlock()
  204. // coalesced packets all have the same destination connection ID
  205. handlerEntry, handlerFound := h.handlers[string(packets[0].hdr.DestConnectionID)]
  206. for _, p := range packets {
  207. if handlerFound { // existing session
  208. handlerEntry.handler.handlePacket(p)
  209. continue
  210. }
  211. // No session found.
  212. // This might be a stateless reset.
  213. if !p.hdr.IsLongHeader {
  214. if len(p.data) >= protocol.MinStatelessResetSize {
  215. var token [16]byte
  216. copy(token[:], p.data[len(p.data)-16:])
  217. if sess, ok := h.resetTokens[token]; ok {
  218. sess.destroy(errors.New("received a stateless reset"))
  219. continue
  220. }
  221. }
  222. // TODO(#943): send a stateless reset
  223. h.logger.Debugf("received a short header packet with an unexpected connection ID %s", p.hdr.DestConnectionID)
  224. break // a short header packet is always the last in a coalesced packet
  225. }
  226. if h.server == nil { // no server set
  227. h.logger.Debugf("received a packet with an unexpected connection ID %s", p.hdr.DestConnectionID)
  228. continue
  229. }
  230. h.server.handlePacket(p)
  231. }
  232. }