httpDialer.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package transportcommon
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "sync"
  10. "time"
  11. "golang.org/x/net/http2"
  12. "github.com/v2fly/v2ray-core/v5/transport/internet/security"
  13. )
  14. type DialerFunc func(ctx context.Context, addr string) (net.Conn, error)
  15. // NewALPNAwareHTTPRoundTripper creates an instance of RoundTripper that dial to remote HTTPS endpoint with
  16. // an alternative version of TLS implementation.
  17. func NewALPNAwareHTTPRoundTripper(ctx context.Context, dialer DialerFunc,
  18. backdropTransport http.RoundTripper,
  19. ) http.RoundTripper {
  20. rtImpl := &alpnAwareHTTPRoundTripperImpl{
  21. connectWithH1: map[string]bool{},
  22. backdropTransport: backdropTransport,
  23. pendingConn: map[pendingConnKey]*unclaimedConnection{},
  24. dialer: dialer,
  25. ctx: ctx,
  26. }
  27. rtImpl.init()
  28. return rtImpl
  29. }
  30. type alpnAwareHTTPRoundTripperImpl struct {
  31. accessConnectWithH1 sync.Mutex
  32. connectWithH1 map[string]bool
  33. httpsH1Transport http.RoundTripper
  34. httpsH2Transport http.RoundTripper
  35. backdropTransport http.RoundTripper
  36. accessDialingConnection sync.Mutex
  37. pendingConn map[pendingConnKey]*unclaimedConnection
  38. ctx context.Context
  39. dialer DialerFunc
  40. }
  41. type pendingConnKey struct {
  42. isH2 bool
  43. dest string
  44. }
  45. var (
  46. errEAGAIN = errors.New("incorrect ALPN negotiated, try again with another ALPN")
  47. errEAGAINTooMany = errors.New("incorrect ALPN negotiated")
  48. errExpired = errors.New("connection have expired")
  49. )
  50. func (r *alpnAwareHTTPRoundTripperImpl) RoundTrip(req *http.Request) (*http.Response, error) {
  51. if req.URL.Scheme != "https" {
  52. return r.backdropTransport.RoundTrip(req)
  53. }
  54. for retryCount := 0; retryCount < 5; retryCount++ {
  55. effectivePort := req.URL.Port()
  56. if effectivePort == "" {
  57. effectivePort = "443"
  58. }
  59. if r.getShouldConnectWithH1(fmt.Sprintf("%v:%v", req.URL.Hostname(), effectivePort)) {
  60. resp, err := r.httpsH1Transport.RoundTrip(req)
  61. if errors.Is(err, errEAGAIN) {
  62. continue
  63. }
  64. return resp, err
  65. }
  66. resp, err := r.httpsH2Transport.RoundTrip(req)
  67. if errors.Is(err, errEAGAIN) {
  68. continue
  69. }
  70. return resp, err
  71. }
  72. return nil, errEAGAINTooMany
  73. }
  74. func (r *alpnAwareHTTPRoundTripperImpl) getShouldConnectWithH1(domainName string) bool {
  75. r.accessConnectWithH1.Lock()
  76. defer r.accessConnectWithH1.Unlock()
  77. if value, set := r.connectWithH1[domainName]; set {
  78. return value
  79. }
  80. return false
  81. }
  82. func (r *alpnAwareHTTPRoundTripperImpl) setShouldConnectWithH1(domainName string) {
  83. r.accessConnectWithH1.Lock()
  84. defer r.accessConnectWithH1.Unlock()
  85. r.connectWithH1[domainName] = true
  86. }
  87. func (r *alpnAwareHTTPRoundTripperImpl) clearShouldConnectWithH1(domainName string) {
  88. r.accessConnectWithH1.Lock()
  89. defer r.accessConnectWithH1.Unlock()
  90. r.connectWithH1[domainName] = false
  91. }
  92. func getPendingConnectionID(dest string, alpnIsH2 bool) pendingConnKey {
  93. return pendingConnKey{isH2: alpnIsH2, dest: dest}
  94. }
  95. func (r *alpnAwareHTTPRoundTripperImpl) putConn(addr string, alpnIsH2 bool, conn net.Conn) {
  96. connID := getPendingConnectionID(addr, alpnIsH2)
  97. r.pendingConn[connID] = NewUnclaimedConnection(conn, time.Minute)
  98. }
  99. func (r *alpnAwareHTTPRoundTripperImpl) getConn(addr string, alpnIsH2 bool) net.Conn {
  100. connID := getPendingConnectionID(addr, alpnIsH2)
  101. if conn, ok := r.pendingConn[connID]; ok {
  102. delete(r.pendingConn, connID)
  103. if claimedConnection, err := conn.claimConnection(); err == nil {
  104. return claimedConnection
  105. }
  106. }
  107. return nil
  108. }
  109. func (r *alpnAwareHTTPRoundTripperImpl) dialOrGetTLSWithExpectedALPN(ctx context.Context, addr string, expectedH2 bool) (net.Conn, error) {
  110. r.accessDialingConnection.Lock()
  111. defer r.accessDialingConnection.Unlock()
  112. if r.getShouldConnectWithH1(addr) == expectedH2 {
  113. return nil, errEAGAIN
  114. }
  115. // Get a cached connection if possible to reduce preflight connection closed without sending data
  116. if gconn := r.getConn(addr, expectedH2); gconn != nil {
  117. return gconn, nil
  118. }
  119. conn, err := r.dialTLS(ctx, addr)
  120. if err != nil {
  121. return nil, err
  122. }
  123. protocol := ""
  124. if connAPLNGetter, ok := conn.(security.ConnectionApplicationProtocol); ok {
  125. connectionALPN, err := connAPLNGetter.GetConnectionApplicationProtocol()
  126. if err != nil {
  127. return nil, newError("failed to get connection ALPN").Base(err).AtWarning()
  128. }
  129. protocol = connectionALPN
  130. }
  131. protocolIsH2 := protocol == http2.NextProtoTLS
  132. if protocolIsH2 == expectedH2 {
  133. return conn, err
  134. }
  135. r.putConn(addr, protocolIsH2, conn)
  136. if protocolIsH2 {
  137. r.clearShouldConnectWithH1(addr)
  138. } else {
  139. r.setShouldConnectWithH1(addr)
  140. }
  141. return nil, errEAGAIN
  142. }
  143. func (r *alpnAwareHTTPRoundTripperImpl) dialTLS(ctx context.Context, addr string) (net.Conn, error) {
  144. _ = ctx
  145. return r.dialer(r.ctx, addr)
  146. }
  147. func (r *alpnAwareHTTPRoundTripperImpl) init() {
  148. r.httpsH2Transport = &http2.Transport{
  149. DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
  150. return r.dialOrGetTLSWithExpectedALPN(context.Background(), addr, true)
  151. },
  152. }
  153. r.httpsH1Transport = &http.Transport{
  154. DialTLSContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
  155. return r.dialOrGetTLSWithExpectedALPN(ctx, addr, false)
  156. },
  157. }
  158. }
  159. func NewUnclaimedConnection(conn net.Conn, expireTime time.Duration) *unclaimedConnection {
  160. c := &unclaimedConnection{
  161. Conn: conn,
  162. }
  163. time.AfterFunc(expireTime, c.tick)
  164. return c
  165. }
  166. type unclaimedConnection struct {
  167. net.Conn
  168. claimed bool
  169. access sync.Mutex
  170. }
  171. func (c *unclaimedConnection) claimConnection() (net.Conn, error) {
  172. c.access.Lock()
  173. defer c.access.Unlock()
  174. if !c.claimed {
  175. c.claimed = true
  176. return c.Conn, nil
  177. }
  178. return nil, errExpired
  179. }
  180. func (c *unclaimedConnection) tick() {
  181. c.access.Lock()
  182. defer c.access.Unlock()
  183. if !c.claimed {
  184. c.claimed = true
  185. c.Conn.Close()
  186. c.Conn = nil
  187. }
  188. }