dialer.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package quic
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. "github.com/quic-go/quic-go"
  7. "github.com/v2fly/v2ray-core/v5/common"
  8. "github.com/v2fly/v2ray-core/v5/common/net"
  9. "github.com/v2fly/v2ray-core/v5/common/task"
  10. "github.com/v2fly/v2ray-core/v5/transport/internet"
  11. "github.com/v2fly/v2ray-core/v5/transport/internet/tls"
  12. )
  13. type connectionContext struct {
  14. rawConn *sysConn
  15. conn quic.Connection
  16. }
  17. var errConnectionClosed = newError("connection closed")
  18. func (c *connectionContext) openStream(destAddr net.Addr) (*interConn, error) {
  19. if !isActive(c.conn) {
  20. return nil, errConnectionClosed
  21. }
  22. stream, err := c.conn.OpenStream()
  23. if err != nil {
  24. return nil, err
  25. }
  26. conn := &interConn{
  27. stream: stream,
  28. local: c.conn.LocalAddr(),
  29. remote: destAddr,
  30. }
  31. return conn, nil
  32. }
  33. type clientConnections struct {
  34. access sync.Mutex
  35. conns map[net.Destination][]*connectionContext
  36. cleanup *task.Periodic
  37. }
  38. func isActive(s quic.Connection) bool {
  39. select {
  40. case <-s.Context().Done():
  41. return false
  42. default:
  43. return true
  44. }
  45. }
  46. func removeInactiveConnections(conns []*connectionContext) []*connectionContext {
  47. activeConnections := make([]*connectionContext, 0, len(conns))
  48. for _, s := range conns {
  49. if isActive(s.conn) {
  50. activeConnections = append(activeConnections, s)
  51. continue
  52. }
  53. if err := s.conn.CloseWithError(0, ""); err != nil {
  54. newError("failed to close connection").Base(err).WriteToLog()
  55. }
  56. if err := s.rawConn.Close(); err != nil {
  57. newError("failed to close raw connection").Base(err).WriteToLog()
  58. }
  59. }
  60. if len(activeConnections) < len(conns) {
  61. return activeConnections
  62. }
  63. return conns
  64. }
  65. func openStream(conns []*connectionContext, destAddr net.Addr) *interConn {
  66. for _, s := range conns {
  67. if !isActive(s.conn) {
  68. continue
  69. }
  70. conn, err := s.openStream(destAddr)
  71. if err != nil {
  72. continue
  73. }
  74. return conn
  75. }
  76. return nil
  77. }
  78. func (s *clientConnections) cleanConnections() error {
  79. s.access.Lock()
  80. defer s.access.Unlock()
  81. if len(s.conns) == 0 {
  82. return nil
  83. }
  84. newConnMap := make(map[net.Destination][]*connectionContext)
  85. for dest, conns := range s.conns {
  86. conns = removeInactiveConnections(conns)
  87. if len(conns) > 0 {
  88. newConnMap[dest] = conns
  89. }
  90. }
  91. s.conns = newConnMap
  92. return nil
  93. }
  94. func (s *clientConnections) openConnection(destAddr net.Addr, config *Config, tlsConfig *tls.Config, sockopt *internet.SocketConfig) (internet.Connection, error) {
  95. s.access.Lock()
  96. defer s.access.Unlock()
  97. if s.conns == nil {
  98. s.conns = make(map[net.Destination][]*connectionContext)
  99. }
  100. dest := net.DestinationFromAddr(destAddr)
  101. var conns []*connectionContext
  102. if s, found := s.conns[dest]; found {
  103. conns = s
  104. }
  105. {
  106. conn := openStream(conns, destAddr)
  107. if conn != nil {
  108. return conn, nil
  109. }
  110. }
  111. conns = removeInactiveConnections(conns)
  112. newError("dialing QUIC to ", dest).WriteToLog()
  113. rawConn, err := internet.ListenSystemPacket(context.Background(), &net.UDPAddr{
  114. IP: []byte{0, 0, 0, 0},
  115. Port: 0,
  116. }, sockopt)
  117. if err != nil {
  118. return nil, err
  119. }
  120. quicConfig := &quic.Config{
  121. ConnectionIDLength: 12,
  122. HandshakeIdleTimeout: time.Second * 8,
  123. MaxIdleTimeout: time.Second * 30,
  124. KeepAlivePeriod: time.Second * 15,
  125. }
  126. sysConn, err := wrapSysConn(rawConn.(*net.UDPConn), config)
  127. if err != nil {
  128. rawConn.Close()
  129. return nil, err
  130. }
  131. conn, err := quic.DialContext(context.Background(), sysConn, destAddr, "", tlsConfig.GetTLSConfig(tls.WithDestination(dest)), quicConfig)
  132. if err != nil {
  133. sysConn.Close()
  134. return nil, err
  135. }
  136. context := &connectionContext{
  137. conn: conn,
  138. rawConn: sysConn,
  139. }
  140. s.conns[dest] = append(conns, context)
  141. return context.openStream(destAddr)
  142. }
  143. var client clientConnections
  144. func init() {
  145. client.conns = make(map[net.Destination][]*connectionContext)
  146. client.cleanup = &task.Periodic{
  147. Interval: time.Minute,
  148. Execute: client.cleanConnections,
  149. }
  150. common.Must(client.cleanup.Start())
  151. }
  152. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
  153. tlsConfig := tls.ConfigFromStreamSettings(streamSettings)
  154. if tlsConfig == nil {
  155. tlsConfig = &tls.Config{
  156. ServerName: internalDomain,
  157. AllowInsecure: true,
  158. }
  159. }
  160. var destAddr *net.UDPAddr
  161. if dest.Address.Family().IsIP() {
  162. destAddr = &net.UDPAddr{
  163. IP: dest.Address.IP(),
  164. Port: int(dest.Port),
  165. }
  166. } else {
  167. addr, err := net.ResolveUDPAddr("udp", dest.NetAddr())
  168. if err != nil {
  169. return nil, err
  170. }
  171. destAddr = addr
  172. }
  173. config := streamSettings.ProtocolSettings.(*Config)
  174. return client.openConnection(destAddr, config, tlsConfig, streamSettings.SocketSettings)
  175. }
  176. func init() {
  177. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  178. }