dialer.go 4.5 KB

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