protocol.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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"
  12. // edgeH2muxTLSServerName is the server name to establish h2mux connection with edge (unused, but kept for legacy reference).
  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. // SRV and TXT record resolution TTL
  20. ResolveTTL = time.Hour
  21. )
  22. var (
  23. // ProtocolList represents a list of supported protocols for communication with the edge
  24. // in order of precedence for remote percentage fetcher.
  25. ProtocolList = []Protocol{QUIC, HTTP2}
  26. )
  27. type Protocol int64
  28. const (
  29. // HTTP2 using golang HTTP2 library for edge connections.
  30. HTTP2 Protocol = iota
  31. // QUIC using quic-go for edge connections.
  32. QUIC
  33. )
  34. // Fallback returns the fallback protocol and whether the protocol has a fallback
  35. func (p Protocol) fallback() (Protocol, bool) {
  36. switch p {
  37. case HTTP2:
  38. return 0, false
  39. case QUIC:
  40. return HTTP2, true
  41. default:
  42. return 0, false
  43. }
  44. }
  45. func (p Protocol) String() string {
  46. switch p {
  47. case HTTP2:
  48. return "http2"
  49. case QUIC:
  50. return "quic"
  51. default:
  52. return fmt.Sprintf("unknown protocol")
  53. }
  54. }
  55. func (p Protocol) TLSSettings() *TLSSettings {
  56. switch p {
  57. case HTTP2:
  58. return &TLSSettings{
  59. ServerName: edgeH2TLSServerName,
  60. }
  61. case QUIC:
  62. return &TLSSettings{
  63. ServerName: edgeQUICServerName,
  64. NextProtos: []string{"argotunnel"},
  65. }
  66. default:
  67. return nil
  68. }
  69. }
  70. type TLSSettings struct {
  71. ServerName string
  72. NextProtos []string
  73. }
  74. type ProtocolSelector interface {
  75. Current() Protocol
  76. Fallback() (Protocol, bool)
  77. }
  78. // staticProtocolSelector will not provide a different protocol for Fallback
  79. type staticProtocolSelector struct {
  80. current Protocol
  81. }
  82. func (s *staticProtocolSelector) Current() Protocol {
  83. return s.current
  84. }
  85. func (s *staticProtocolSelector) Fallback() (Protocol, bool) {
  86. return s.current, false
  87. }
  88. // remoteProtocolSelector will fetch a list of remote protocols to provide for edge discovery
  89. type remoteProtocolSelector struct {
  90. lock sync.RWMutex
  91. current Protocol
  92. // protocolPool is desired protocols in the order of priority they should be picked in.
  93. protocolPool []Protocol
  94. switchThreshold int32
  95. fetchFunc edgediscovery.PercentageFetcher
  96. refreshAfter time.Time
  97. ttl time.Duration
  98. log *zerolog.Logger
  99. }
  100. func newRemoteProtocolSelector(
  101. current Protocol,
  102. protocolPool []Protocol,
  103. switchThreshold int32,
  104. fetchFunc edgediscovery.PercentageFetcher,
  105. ttl time.Duration,
  106. log *zerolog.Logger,
  107. ) *remoteProtocolSelector {
  108. return &remoteProtocolSelector{
  109. current: current,
  110. protocolPool: protocolPool,
  111. switchThreshold: switchThreshold,
  112. fetchFunc: fetchFunc,
  113. refreshAfter: time.Now().Add(ttl),
  114. ttl: ttl,
  115. log: log,
  116. }
  117. }
  118. func (s *remoteProtocolSelector) Current() Protocol {
  119. s.lock.Lock()
  120. defer s.lock.Unlock()
  121. if time.Now().Before(s.refreshAfter) {
  122. return s.current
  123. }
  124. protocol, err := getProtocol(s.protocolPool, s.fetchFunc, s.switchThreshold)
  125. if err != nil {
  126. s.log.Err(err).Msg("Failed to refresh protocol")
  127. return s.current
  128. }
  129. s.current = protocol
  130. s.refreshAfter = time.Now().Add(s.ttl)
  131. return s.current
  132. }
  133. func (s *remoteProtocolSelector) Fallback() (Protocol, bool) {
  134. s.lock.RLock()
  135. defer s.lock.RUnlock()
  136. return s.current.fallback()
  137. }
  138. func getProtocol(protocolPool []Protocol, fetchFunc edgediscovery.PercentageFetcher, switchThreshold int32) (Protocol, error) {
  139. protocolPercentages, err := fetchFunc()
  140. if err != nil {
  141. return 0, err
  142. }
  143. for _, protocol := range protocolPool {
  144. protocolPercentage := protocolPercentages.GetPercentage(protocol.String())
  145. if protocolPercentage > switchThreshold {
  146. return protocol, nil
  147. }
  148. }
  149. // Default to first index in protocolPool list
  150. return protocolPool[0], nil
  151. }
  152. // defaultProtocolSelector will allow for a protocol to have a fallback
  153. type defaultProtocolSelector struct {
  154. lock sync.RWMutex
  155. current Protocol
  156. }
  157. func newDefaultProtocolSelector(
  158. current Protocol,
  159. ) *defaultProtocolSelector {
  160. return &defaultProtocolSelector{
  161. current: current,
  162. }
  163. }
  164. func (s *defaultProtocolSelector) Current() Protocol {
  165. s.lock.Lock()
  166. defer s.lock.Unlock()
  167. return s.current
  168. }
  169. func (s *defaultProtocolSelector) Fallback() (Protocol, bool) {
  170. s.lock.RLock()
  171. defer s.lock.RUnlock()
  172. return s.current.fallback()
  173. }
  174. func NewProtocolSelector(
  175. protocolFlag string,
  176. accountTag string,
  177. tunnelTokenProvided bool,
  178. needPQ bool,
  179. protocolFetcher edgediscovery.PercentageFetcher,
  180. resolveTTL time.Duration,
  181. log *zerolog.Logger,
  182. ) (ProtocolSelector, error) {
  183. // With --post-quantum, we force quic
  184. if needPQ {
  185. return &staticProtocolSelector{
  186. current: QUIC,
  187. }, nil
  188. }
  189. threshold := switchThreshold(accountTag)
  190. fetchedProtocol, err := getProtocol(ProtocolList, protocolFetcher, threshold)
  191. log.Debug().Msgf("Fetched protocol: %s", fetchedProtocol)
  192. if err != nil {
  193. log.Warn().Msg("Unable to lookup protocol percentage.")
  194. // Falling through here since 'auto' is handled in the switch and failing
  195. // to do the protocol lookup isn't a failure since it can be triggered again
  196. // after the TTL.
  197. }
  198. // If the user picks a protocol, then we stick to it no matter what.
  199. switch protocolFlag {
  200. case "h2mux":
  201. // Any users still requesting h2mux will be upgraded to http2 instead
  202. log.Warn().Msg("h2mux is no longer a supported protocol: upgrading edge connection to http2. Please remove '--protocol h2mux' from runtime arguments to remove this warning.")
  203. return &staticProtocolSelector{current: HTTP2}, nil
  204. case QUIC.String():
  205. return &staticProtocolSelector{current: QUIC}, nil
  206. case HTTP2.String():
  207. return &staticProtocolSelector{current: HTTP2}, nil
  208. case AutoSelectFlag:
  209. // When a --token is provided, we want to start with QUIC but have fallback to HTTP2
  210. if tunnelTokenProvided {
  211. return newDefaultProtocolSelector(QUIC), nil
  212. }
  213. return newRemoteProtocolSelector(fetchedProtocol, ProtocolList, threshold, protocolFetcher, resolveTTL, log), nil
  214. }
  215. return nil, fmt.Errorf("Unknown protocol %s, %s", protocolFlag, AvailableProtocolFlagMessage)
  216. }
  217. func switchThreshold(accountTag string) int32 {
  218. h := fnv.New32a()
  219. _, _ = h.Write([]byte(accountTag))
  220. return int32(h.Sum32() % 100)
  221. }