protocol.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package connection
  2. import (
  3. "fmt"
  4. "hash/fnv"
  5. "sync"
  6. "time"
  7. "github.com/rs/zerolog"
  8. "github.com/cloudflare/cloudflared/edgediscovery"
  9. )
  10. const (
  11. AvailableProtocolFlagMessage = "Available protocols: 'auto' - automatically chooses the best protocol over time (the default; and also the recommended one); 'quic' - based on QUIC, relying on UDP egress to Cloudflare edge; 'http2' - using Go's HTTP2 library, relying on TCP egress to Cloudflare edge; 'h2mux' - Cloudflare's implementation of HTTP/2, deprecated"
  12. // edgeH2muxTLSServerName is the server name to establish h2mux connection with edge
  13. edgeH2muxTLSServerName = "cftunnel.com"
  14. // edgeH2TLSServerName is the server name to establish http2 connection with edge
  15. edgeH2TLSServerName = "h2.cftunnel.com"
  16. // edgeQUICServerName is the server name to establish quic connection with edge.
  17. edgeQUICServerName = "quic.cftunnel.com"
  18. autoSelectFlag = "auto"
  19. )
  20. var (
  21. // ProtocolList represents a list of supported protocols for communication with the edge.
  22. ProtocolList = []Protocol{H2mux, HTTP2, HTTP2Warp, QUIC, QUICWarp}
  23. )
  24. type Protocol int64
  25. const (
  26. // H2mux protocol can be used both with Classic and Named Tunnels. .
  27. H2mux Protocol = iota
  28. // HTTP2 is used only with named tunnels. It's more efficient than H2mux for L4 proxying.
  29. HTTP2
  30. // QUIC is used only with named tunnels.
  31. QUIC
  32. // HTTP2Warp is used only with named tunnels. It's useful for warp-routing where we don't want to fallback to
  33. // H2mux on HTTP2 failure to connect.
  34. HTTP2Warp
  35. //QUICWarp is used only with named tunnels. It's useful for warp-routing where we want to fallback to HTTP2 but
  36. // don't want HTTP2 to fallback to H2mux
  37. QUICWarp
  38. )
  39. // Fallback returns the fallback protocol and whether the protocol has a fallback
  40. func (p Protocol) fallback() (Protocol, bool) {
  41. switch p {
  42. case H2mux:
  43. return 0, false
  44. case HTTP2:
  45. return H2mux, true
  46. case HTTP2Warp:
  47. return 0, false
  48. case QUIC:
  49. return HTTP2, true
  50. case QUICWarp:
  51. return HTTP2Warp, true
  52. default:
  53. return 0, false
  54. }
  55. }
  56. func (p Protocol) String() string {
  57. switch p {
  58. case H2mux:
  59. return "h2mux"
  60. case HTTP2, HTTP2Warp:
  61. return "http2"
  62. case QUIC, QUICWarp:
  63. return "quic"
  64. default:
  65. return fmt.Sprintf("unknown protocol")
  66. }
  67. }
  68. func (p Protocol) TLSSettings() *TLSSettings {
  69. switch p {
  70. case H2mux:
  71. return &TLSSettings{
  72. ServerName: edgeH2muxTLSServerName,
  73. }
  74. case HTTP2, HTTP2Warp:
  75. return &TLSSettings{
  76. ServerName: edgeH2TLSServerName,
  77. }
  78. case QUIC, QUICWarp:
  79. return &TLSSettings{
  80. ServerName: edgeQUICServerName,
  81. NextProtos: []string{"argotunnel"},
  82. }
  83. default:
  84. return nil
  85. }
  86. }
  87. type TLSSettings struct {
  88. ServerName string
  89. NextProtos []string
  90. }
  91. type ProtocolSelector interface {
  92. Current() Protocol
  93. Fallback() (Protocol, bool)
  94. }
  95. type staticProtocolSelector struct {
  96. current Protocol
  97. }
  98. func (s *staticProtocolSelector) Current() Protocol {
  99. return s.current
  100. }
  101. func (s *staticProtocolSelector) Fallback() (Protocol, bool) {
  102. return 0, false
  103. }
  104. type autoProtocolSelector struct {
  105. lock sync.RWMutex
  106. current Protocol
  107. // protocolPool is desired protocols in the order of priority they should be picked in.
  108. protocolPool []Protocol
  109. switchThreshold int32
  110. fetchFunc PercentageFetcher
  111. refreshAfter time.Time
  112. ttl time.Duration
  113. log *zerolog.Logger
  114. }
  115. func newAutoProtocolSelector(
  116. current Protocol,
  117. protocolPool []Protocol,
  118. switchThreshold int32,
  119. fetchFunc PercentageFetcher,
  120. ttl time.Duration,
  121. log *zerolog.Logger,
  122. ) *autoProtocolSelector {
  123. return &autoProtocolSelector{
  124. current: current,
  125. protocolPool: protocolPool,
  126. switchThreshold: switchThreshold,
  127. fetchFunc: fetchFunc,
  128. refreshAfter: time.Now().Add(ttl),
  129. ttl: ttl,
  130. log: log,
  131. }
  132. }
  133. func (s *autoProtocolSelector) Current() Protocol {
  134. s.lock.Lock()
  135. defer s.lock.Unlock()
  136. if time.Now().Before(s.refreshAfter) {
  137. return s.current
  138. }
  139. protocol, err := getProtocol(s.protocolPool, s.fetchFunc, s.switchThreshold)
  140. if err != nil {
  141. s.log.Err(err).Msg("Failed to refresh protocol")
  142. return s.current
  143. }
  144. s.current = protocol
  145. s.refreshAfter = time.Now().Add(s.ttl)
  146. return s.current
  147. }
  148. func getProtocol(protocolPool []Protocol, fetchFunc PercentageFetcher, switchThreshold int32) (Protocol, error) {
  149. protocolPercentages, err := fetchFunc()
  150. if err != nil {
  151. return 0, err
  152. }
  153. for _, protocol := range protocolPool {
  154. protocolPercentage := protocolPercentages.GetPercentage(protocol.String())
  155. if protocolPercentage > switchThreshold {
  156. return protocol, nil
  157. }
  158. }
  159. return protocolPool[len(protocolPool)-1], nil
  160. }
  161. func (s *autoProtocolSelector) Fallback() (Protocol, bool) {
  162. s.lock.RLock()
  163. defer s.lock.RUnlock()
  164. return s.current.fallback()
  165. }
  166. type PercentageFetcher func() (edgediscovery.ProtocolPercents, error)
  167. func NewProtocolSelector(
  168. protocolFlag string,
  169. warpRoutingEnabled bool,
  170. namedTunnel *NamedTunnelProperties,
  171. fetchFunc PercentageFetcher,
  172. ttl time.Duration,
  173. log *zerolog.Logger,
  174. ) (ProtocolSelector, error) {
  175. // Classic tunnel is only supported with h2mux
  176. if namedTunnel == nil {
  177. return &staticProtocolSelector{
  178. current: H2mux,
  179. }, nil
  180. }
  181. threshold := switchThreshold(namedTunnel.Credentials.AccountTag)
  182. fetchedProtocol, err := getProtocol([]Protocol{QUIC, HTTP2}, fetchFunc, threshold)
  183. if err != nil {
  184. log.Err(err).Msg("Unable to lookup protocol. Defaulting to `http2`. If this fails, you can set `--protocol h2mux` in your cloudflared command.")
  185. return &staticProtocolSelector{
  186. current: HTTP2,
  187. }, nil
  188. }
  189. if warpRoutingEnabled {
  190. if protocolFlag == H2mux.String() || fetchedProtocol == H2mux {
  191. log.Warn().Msg("Warp routing is not supported in h2mux protocol. Upgrading to http2 to allow it.")
  192. protocolFlag = HTTP2.String()
  193. fetchedProtocol = HTTP2Warp
  194. }
  195. return selectWarpRoutingProtocols(protocolFlag, fetchFunc, ttl, log, threshold, fetchedProtocol)
  196. }
  197. return selectNamedTunnelProtocols(protocolFlag, fetchFunc, ttl, log, threshold, fetchedProtocol)
  198. }
  199. func selectNamedTunnelProtocols(
  200. protocolFlag string,
  201. fetchFunc PercentageFetcher,
  202. ttl time.Duration,
  203. log *zerolog.Logger,
  204. threshold int32,
  205. protocol Protocol,
  206. ) (ProtocolSelector, error) {
  207. // If the user picks a protocol, then we stick to it no matter what.
  208. switch protocolFlag {
  209. case H2mux.String():
  210. return &staticProtocolSelector{current: H2mux}, nil
  211. case QUIC.String():
  212. return &staticProtocolSelector{current: QUIC}, nil
  213. case HTTP2.String():
  214. return &staticProtocolSelector{current: HTTP2}, nil
  215. }
  216. // If the user does not pick (hopefully the majority) then we use the one derived from the TXT DNS record and
  217. // fallback on failures.
  218. if protocolFlag == autoSelectFlag {
  219. return newAutoProtocolSelector(protocol, []Protocol{QUIC, HTTP2, H2mux}, threshold, fetchFunc, ttl, log), nil
  220. }
  221. return nil, fmt.Errorf("Unknown protocol %s, %s", protocolFlag, AvailableProtocolFlagMessage)
  222. }
  223. func selectWarpRoutingProtocols(
  224. protocolFlag string,
  225. fetchFunc PercentageFetcher,
  226. ttl time.Duration,
  227. log *zerolog.Logger,
  228. threshold int32,
  229. protocol Protocol,
  230. ) (ProtocolSelector, error) {
  231. // If the user picks a protocol, then we stick to it no matter what.
  232. switch protocolFlag {
  233. case QUIC.String():
  234. return &staticProtocolSelector{current: QUICWarp}, nil
  235. case HTTP2.String():
  236. return &staticProtocolSelector{current: HTTP2Warp}, nil
  237. }
  238. // If the user does not pick (hopefully the majority) then we use the one derived from the TXT DNS record and
  239. // fallback on failures.
  240. if protocolFlag == autoSelectFlag {
  241. return newAutoProtocolSelector(protocol, []Protocol{QUICWarp, HTTP2Warp}, threshold, fetchFunc, ttl, log), nil
  242. }
  243. return nil, fmt.Errorf("Unknown protocol %s, %s", protocolFlag, AvailableProtocolFlagMessage)
  244. }
  245. func switchThreshold(accountTag string) int32 {
  246. h := fnv.New32a()
  247. _, _ = h.Write([]byte(accountTag))
  248. return int32(h.Sum32() % 100)
  249. }