dialer.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // +build !confonly
  2. package quic
  3. import (
  4. "context"
  5. "sync"
  6. "time"
  7. "github.com/lucas-clemente/quic-go"
  8. "github.com/v2fly/v2ray-core/v4/common"
  9. "github.com/v2fly/v2ray-core/v4/common/net"
  10. "github.com/v2fly/v2ray-core/v4/common/task"
  11. "github.com/v2fly/v2ray-core/v4/transport/internet"
  12. "github.com/v2fly/v2ray-core/v4/transport/internet/tls"
  13. )
  14. type sessionContext struct {
  15. rawConn *sysConn
  16. session quic.Session
  17. }
  18. var errSessionClosed = newError("session closed")
  19. func (c *sessionContext) openStream(destAddr net.Addr) (*interConn, error) {
  20. if !isActive(c.session) {
  21. return nil, errSessionClosed
  22. }
  23. stream, err := c.session.OpenStream()
  24. if err != nil {
  25. return nil, err
  26. }
  27. conn := &interConn{
  28. stream: stream,
  29. local: c.session.LocalAddr(),
  30. remote: destAddr,
  31. }
  32. return conn, nil
  33. }
  34. type clientSessions struct {
  35. access sync.Mutex
  36. sessions map[net.Destination][]*sessionContext
  37. cleanup *task.Periodic
  38. }
  39. func isActive(s quic.Session) bool {
  40. select {
  41. case <-s.Context().Done():
  42. return false
  43. default:
  44. return true
  45. }
  46. }
  47. func removeInactiveSessions(sessions []*sessionContext) []*sessionContext {
  48. activeSessions := make([]*sessionContext, 0, len(sessions))
  49. for _, s := range sessions {
  50. if isActive(s.session) {
  51. activeSessions = append(activeSessions, s)
  52. continue
  53. }
  54. if err := s.session.CloseWithError(0, ""); err != nil {
  55. newError("failed to close session").Base(err).WriteToLog()
  56. }
  57. if err := s.rawConn.Close(); err != nil {
  58. newError("failed to close raw connection").Base(err).WriteToLog()
  59. }
  60. }
  61. if len(activeSessions) < len(sessions) {
  62. return activeSessions
  63. }
  64. return sessions
  65. }
  66. func openStream(sessions []*sessionContext, destAddr net.Addr) *interConn {
  67. for _, s := range sessions {
  68. if !isActive(s.session) {
  69. continue
  70. }
  71. conn, err := s.openStream(destAddr)
  72. if err != nil {
  73. continue
  74. }
  75. return conn
  76. }
  77. return nil
  78. }
  79. func (s *clientSessions) cleanSessions() error {
  80. s.access.Lock()
  81. defer s.access.Unlock()
  82. if len(s.sessions) == 0 {
  83. return nil
  84. }
  85. newSessionMap := make(map[net.Destination][]*sessionContext)
  86. for dest, sessions := range s.sessions {
  87. sessions = removeInactiveSessions(sessions)
  88. if len(sessions) > 0 {
  89. newSessionMap[dest] = sessions
  90. }
  91. }
  92. s.sessions = newSessionMap
  93. return nil
  94. }
  95. func (s *clientSessions) openConnection(destAddr net.Addr, config *Config, tlsConfig *tls.Config, sockopt *internet.SocketConfig) (internet.Connection, error) {
  96. s.access.Lock()
  97. defer s.access.Unlock()
  98. if s.sessions == nil {
  99. s.sessions = make(map[net.Destination][]*sessionContext)
  100. }
  101. dest := net.DestinationFromAddr(destAddr)
  102. var sessions []*sessionContext
  103. if s, found := s.sessions[dest]; found {
  104. sessions = s
  105. }
  106. if true {
  107. conn := openStream(sessions, destAddr)
  108. if conn != nil {
  109. return conn, nil
  110. }
  111. }
  112. sessions = removeInactiveSessions(sessions)
  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. KeepAlive: true,
  125. }
  126. conn, err := wrapSysConn(rawConn, config)
  127. if err != nil {
  128. rawConn.Close()
  129. return nil, err
  130. }
  131. session, err := quic.DialContext(context.Background(), conn, destAddr, "", tlsConfig.GetTLSConfig(tls.WithDestination(dest)), quicConfig)
  132. if err != nil {
  133. conn.Close()
  134. return nil, err
  135. }
  136. context := &sessionContext{
  137. session: session,
  138. rawConn: conn,
  139. }
  140. s.sessions[dest] = append(sessions, context)
  141. return context.openStream(destAddr)
  142. }
  143. var client clientSessions
  144. func init() {
  145. client.sessions = make(map[net.Destination][]*sessionContext)
  146. client.cleanup = &task.Periodic{
  147. Interval: time.Minute,
  148. Execute: client.cleanSessions,
  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. }