dialer.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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/signal/done"
  10. "v2ray.com/core/common/task"
  11. "v2ray.com/core/transport/internet"
  12. "v2ray.com/core/transport/internet/tls"
  13. )
  14. type sessionContext struct {
  15. access sync.Mutex
  16. done *done.Instance
  17. rawConn *sysConn
  18. session quic.Session
  19. interConns []*interConn
  20. }
  21. var errSessionClosed = newError("session closed")
  22. func (c *sessionContext) openStream(destAddr net.Addr) (*interConn, error) {
  23. c.access.Lock()
  24. defer c.access.Unlock()
  25. if c.done.Done() {
  26. return nil, errSessionClosed
  27. }
  28. stream, err := c.session.OpenStream()
  29. if err != nil {
  30. return nil, err
  31. }
  32. conn := &interConn{
  33. stream: stream,
  34. done: done.New(),
  35. local: c.session.LocalAddr(),
  36. remote: destAddr,
  37. context: c,
  38. }
  39. c.interConns = append(c.interConns, conn)
  40. return conn, nil
  41. }
  42. func (c *sessionContext) onInterConnClose() {
  43. c.access.Lock()
  44. defer c.access.Unlock()
  45. if c.done.Done() {
  46. return
  47. }
  48. activeConns := 0
  49. for _, conn := range c.interConns {
  50. if !conn.done.Done() {
  51. activeConns++
  52. }
  53. }
  54. if activeConns > 0 {
  55. return
  56. }
  57. c.done.Close()
  58. c.session.Close()
  59. c.rawConn.Close()
  60. }
  61. type clientSessions struct {
  62. access sync.Mutex
  63. sessions map[net.Destination][]*sessionContext
  64. cleanup *task.Periodic
  65. }
  66. func isActive(s quic.Session) bool {
  67. select {
  68. case <-s.Context().Done():
  69. return false
  70. default:
  71. return true
  72. }
  73. }
  74. func removeInactiveSessions(sessions []*sessionContext) []*sessionContext {
  75. activeSessions := make([]*sessionContext, 0, len(sessions))
  76. for _, s := range sessions {
  77. if isActive(s.session) {
  78. activeSessions = append(activeSessions, s)
  79. continue
  80. }
  81. if err := s.session.Close(); err != nil {
  82. newError("failed to close session").Base(err).AtWarning().WriteToLog()
  83. }
  84. if err := s.rawConn.Close(); err != nil {
  85. newError("failed to close raw connection").Base(err).AtWarning().WriteToLog()
  86. }
  87. }
  88. if len(activeSessions) < len(sessions) {
  89. return activeSessions
  90. }
  91. return sessions
  92. }
  93. func openStream(sessions []*sessionContext, destAddr net.Addr) *interConn {
  94. for _, s := range sessions {
  95. if !isActive(s.session) {
  96. continue
  97. }
  98. conn, err := s.openStream(destAddr)
  99. if err != nil {
  100. continue
  101. }
  102. return conn
  103. }
  104. return nil
  105. }
  106. func (s *clientSessions) cleanSessions() error {
  107. s.access.Lock()
  108. defer s.access.Unlock()
  109. if len(s.sessions) == 0 {
  110. return nil
  111. }
  112. newSessionMap := make(map[net.Destination][]*sessionContext)
  113. for dest, sessions := range s.sessions {
  114. sessions = removeInactiveSessions(sessions)
  115. if len(sessions) > 0 {
  116. newSessionMap[dest] = sessions
  117. }
  118. }
  119. s.sessions = newSessionMap
  120. return nil
  121. }
  122. func (s *clientSessions) openConnection(destAddr net.Addr, config *Config, tlsConfig *tls.Config, sockopt *internet.SocketConfig) (internet.Connection, error) {
  123. s.access.Lock()
  124. defer s.access.Unlock()
  125. if s.sessions == nil {
  126. s.sessions = make(map[net.Destination][]*sessionContext)
  127. }
  128. dest := net.DestinationFromAddr(destAddr)
  129. var sessions []*sessionContext
  130. if s, found := s.sessions[dest]; found {
  131. sessions = s
  132. }
  133. if true {
  134. conn := openStream(sessions, destAddr)
  135. if conn != nil {
  136. return conn, nil
  137. }
  138. }
  139. sessions = removeInactiveSessions(sessions)
  140. rawConn, err := internet.ListenSystemPacket(context.Background(), &net.UDPAddr{
  141. IP: []byte{0, 0, 0, 0},
  142. Port: 0,
  143. }, sockopt)
  144. if err != nil {
  145. return nil, err
  146. }
  147. quicConfig := &quic.Config{
  148. ConnectionIDLength: 12,
  149. HandshakeTimeout: time.Second * 8,
  150. IdleTimeout: time.Second * 30,
  151. MaxIncomingUniStreams: -1,
  152. MaxIncomingStreams: -1,
  153. }
  154. conn, err := wrapSysConn(rawConn, config)
  155. if err != nil {
  156. rawConn.Close()
  157. return nil, err
  158. }
  159. session, err := quic.DialContext(context.Background(), conn, destAddr, "", tlsConfig.GetTLSConfig(tls.WithDestination(dest)), quicConfig)
  160. if err != nil {
  161. conn.Close()
  162. return nil, err
  163. }
  164. context := &sessionContext{
  165. session: session,
  166. rawConn: conn,
  167. done: done.New(),
  168. }
  169. s.sessions[dest] = append(sessions, context)
  170. return context.openStream(destAddr)
  171. }
  172. var client clientSessions
  173. func init() {
  174. client.sessions = make(map[net.Destination][]*sessionContext)
  175. client.cleanup = &task.Periodic{
  176. Interval: time.Minute,
  177. Execute: client.cleanSessions,
  178. }
  179. common.Must(client.cleanup.Start())
  180. }
  181. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
  182. tlsConfig := tls.ConfigFromStreamSettings(streamSettings)
  183. if tlsConfig == nil {
  184. tlsConfig = &tls.Config{
  185. ServerName: internalDomain,
  186. AllowInsecure: true,
  187. }
  188. }
  189. var destAddr *net.UDPAddr
  190. if dest.Address.Family().IsIP() {
  191. destAddr = &net.UDPAddr{
  192. IP: dest.Address.IP(),
  193. Port: int(dest.Port),
  194. }
  195. } else {
  196. addr, err := net.ResolveUDPAddr("udp", dest.NetAddr())
  197. if err != nil {
  198. return nil, err
  199. }
  200. destAddr = addr
  201. }
  202. config := streamSettings.ProtocolSettings.(*Config)
  203. return client.openConnection(destAddr, config, tlsConfig, streamSettings.SocketSettings)
  204. }
  205. func init() {
  206. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  207. }