ipc.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package main
  2. import (
  3. "container/heap"
  4. "encoding/hex"
  5. "fmt"
  6. "log"
  7. "time"
  8. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/bridgefingerprint"
  9. "github.com/prometheus/client_golang/prometheus"
  10. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages"
  11. )
  12. const (
  13. ClientTimeout = 10
  14. ProxyTimeout = 10
  15. NATUnknown = "unknown"
  16. NATRestricted = "restricted"
  17. NATUnrestricted = "unrestricted"
  18. )
  19. type IPC struct {
  20. ctx *BrokerContext
  21. }
  22. func (i *IPC) Debug(_ interface{}, response *string) error {
  23. var unknowns int
  24. var natRestricted, natUnrestricted, natUnknown int
  25. proxyTypes := make(map[string]int)
  26. i.ctx.snowflakeLock.Lock()
  27. s := fmt.Sprintf("current snowflakes available: %d\n", len(i.ctx.idToSnowflake))
  28. for _, snowflake := range i.ctx.idToSnowflake {
  29. if messages.KnownProxyTypes[snowflake.proxyType] {
  30. proxyTypes[snowflake.proxyType]++
  31. } else {
  32. unknowns++
  33. }
  34. switch snowflake.natType {
  35. case NATRestricted:
  36. natRestricted++
  37. case NATUnrestricted:
  38. natUnrestricted++
  39. default:
  40. natUnknown++
  41. }
  42. }
  43. i.ctx.snowflakeLock.Unlock()
  44. for pType, num := range proxyTypes {
  45. s += fmt.Sprintf("\t%s proxies: %d\n", pType, num)
  46. }
  47. s += fmt.Sprintf("\tunknown proxies: %d", unknowns)
  48. s += fmt.Sprintf("\nNAT Types available:")
  49. s += fmt.Sprintf("\n\trestricted: %d", natRestricted)
  50. s += fmt.Sprintf("\n\tunrestricted: %d", natUnrestricted)
  51. s += fmt.Sprintf("\n\tunknown: %d", natUnknown)
  52. *response = s
  53. return nil
  54. }
  55. func (i *IPC) ProxyPolls(arg messages.Arg, response *[]byte) error {
  56. sid, proxyType, natType, clients, relayPattern, relayPatternSupported, err := messages.DecodeProxyPollRequestWithRelayPrefix(arg.Body)
  57. if err != nil {
  58. return messages.ErrBadRequest
  59. }
  60. if !relayPatternSupported {
  61. i.ctx.metrics.lock.Lock()
  62. i.ctx.metrics.proxyPollWithoutRelayURLExtension++
  63. i.ctx.metrics.promMetrics.ProxyPollWithoutRelayURLExtensionTotal.With(prometheus.Labels{"nat": natType, "type": proxyType}).Inc()
  64. i.ctx.metrics.lock.Unlock()
  65. } else {
  66. i.ctx.metrics.lock.Lock()
  67. i.ctx.metrics.proxyPollWithRelayURLExtension++
  68. i.ctx.metrics.promMetrics.ProxyPollWithRelayURLExtensionTotal.With(prometheus.Labels{"nat": natType, "type": proxyType}).Inc()
  69. i.ctx.metrics.lock.Unlock()
  70. }
  71. if !i.ctx.CheckProxyRelayPattern(relayPattern, !relayPatternSupported) {
  72. i.ctx.metrics.lock.Lock()
  73. i.ctx.metrics.proxyPollRejectedWithRelayURLExtension++
  74. i.ctx.metrics.promMetrics.ProxyPollRejectedForRelayURLExtensionTotal.With(prometheus.Labels{"nat": natType, "type": proxyType}).Inc()
  75. i.ctx.metrics.lock.Unlock()
  76. log.Printf("bad request: rejected relay pattern from proxy = %v", messages.ErrBadRequest)
  77. b, err := messages.EncodePollResponseWithRelayURL("", false, "", "", "incorrect relay pattern")
  78. *response = b
  79. if err != nil {
  80. return messages.ErrInternal
  81. }
  82. return nil
  83. }
  84. // Log geoip stats
  85. remoteIP := arg.RemoteAddr
  86. if err != nil {
  87. log.Println("Warning: cannot process proxy IP: ", err.Error())
  88. } else {
  89. i.ctx.metrics.lock.Lock()
  90. i.ctx.metrics.UpdateCountryStats(remoteIP, proxyType, natType)
  91. i.ctx.metrics.lock.Unlock()
  92. }
  93. var b []byte
  94. // Wait for a client to avail an offer to the snowflake, or timeout if nil.
  95. offer := i.ctx.RequestOffer(sid, proxyType, natType, clients)
  96. if offer == nil {
  97. i.ctx.metrics.lock.Lock()
  98. i.ctx.metrics.proxyIdleCount++
  99. i.ctx.metrics.promMetrics.ProxyPollTotal.With(prometheus.Labels{"nat": natType, "status": "idle"}).Inc()
  100. i.ctx.metrics.lock.Unlock()
  101. b, err = messages.EncodePollResponse("", false, "")
  102. if err != nil {
  103. return messages.ErrInternal
  104. }
  105. *response = b
  106. return nil
  107. }
  108. i.ctx.metrics.promMetrics.ProxyPollTotal.With(prometheus.Labels{"nat": natType, "status": "matched"}).Inc()
  109. var relayURL string
  110. bridgeFingerprint, err := bridgefingerprint.FingerprintFromBytes(offer.fingerprint)
  111. if err != nil {
  112. return messages.ErrBadRequest
  113. }
  114. if info, err := i.ctx.bridgeList.GetBridgeInfo(bridgeFingerprint); err != nil {
  115. return err
  116. } else {
  117. relayURL = info.WebSocketAddress
  118. }
  119. b, err = messages.EncodePollResponseWithRelayURL(string(offer.sdp), true, offer.natType, relayURL, "")
  120. if err != nil {
  121. return messages.ErrInternal
  122. }
  123. *response = b
  124. return nil
  125. }
  126. func sendClientResponse(resp *messages.ClientPollResponse, response *[]byte) error {
  127. data, err := resp.EncodePollResponse()
  128. if err != nil {
  129. log.Printf("error encoding answer")
  130. return messages.ErrInternal
  131. } else {
  132. *response = []byte(data)
  133. return nil
  134. }
  135. }
  136. func (i *IPC) ClientOffers(arg messages.Arg, response *[]byte) error {
  137. startTime := time.Now()
  138. req, err := messages.DecodeClientPollRequest(arg.Body)
  139. if err != nil {
  140. return sendClientResponse(&messages.ClientPollResponse{Error: err.Error()}, response)
  141. }
  142. offer := &ClientOffer{
  143. natType: req.NAT,
  144. sdp: []byte(req.Offer),
  145. }
  146. fingerprint, err := hex.DecodeString(req.Fingerprint)
  147. if err != nil {
  148. return sendClientResponse(&messages.ClientPollResponse{Error: err.Error()}, response)
  149. }
  150. BridgeFingerprint, err := bridgefingerprint.FingerprintFromBytes(fingerprint)
  151. if err != nil {
  152. return sendClientResponse(&messages.ClientPollResponse{Error: err.Error()}, response)
  153. }
  154. if _, err := i.ctx.GetBridgeInfo(BridgeFingerprint); err != nil {
  155. return err
  156. }
  157. offer.fingerprint = BridgeFingerprint.ToBytes()
  158. snowflake := i.matchSnowflake(offer.natType)
  159. if snowflake != nil {
  160. snowflake.offerChannel <- offer
  161. } else {
  162. i.ctx.metrics.lock.Lock()
  163. i.ctx.metrics.UpdateRendezvousStats(arg.RemoteAddr, arg.RendezvousMethod, offer.natType, false)
  164. i.ctx.metrics.lock.Unlock()
  165. resp := &messages.ClientPollResponse{Error: messages.StrNoProxies}
  166. return sendClientResponse(resp, response)
  167. }
  168. // Wait for the answer to be returned on the channel or timeout.
  169. select {
  170. case answer := <-snowflake.answerChannel:
  171. i.ctx.metrics.lock.Lock()
  172. i.ctx.metrics.UpdateRendezvousStats(arg.RemoteAddr, arg.RendezvousMethod, offer.natType, true)
  173. i.ctx.metrics.lock.Unlock()
  174. resp := &messages.ClientPollResponse{Answer: answer}
  175. err = sendClientResponse(resp, response)
  176. // Initial tracking of elapsed time.
  177. i.ctx.metrics.clientRoundtripEstimate = time.Since(startTime) / time.Millisecond
  178. case <-time.After(time.Second * ClientTimeout):
  179. log.Println("Client: Timed out.")
  180. resp := &messages.ClientPollResponse{Error: messages.StrTimedOut}
  181. err = sendClientResponse(resp, response)
  182. }
  183. i.ctx.snowflakeLock.Lock()
  184. i.ctx.metrics.promMetrics.AvailableProxies.With(prometheus.Labels{"nat": snowflake.natType, "type": snowflake.proxyType}).Dec()
  185. delete(i.ctx.idToSnowflake, snowflake.id)
  186. i.ctx.snowflakeLock.Unlock()
  187. return err
  188. }
  189. func (i *IPC) matchSnowflake(natType string) *Snowflake {
  190. i.ctx.snowflakeLock.Lock()
  191. defer i.ctx.snowflakeLock.Unlock()
  192. // Proiritize known restricted snowflakes for unrestricted clients
  193. if natType == NATUnrestricted && i.ctx.restrictedSnowflakes.Len() > 0 {
  194. return heap.Pop(i.ctx.restrictedSnowflakes).(*Snowflake)
  195. }
  196. if i.ctx.snowflakes.Len() > 0 {
  197. return heap.Pop(i.ctx.snowflakes).(*Snowflake)
  198. }
  199. return nil
  200. }
  201. func (i *IPC) ProxyAnswers(arg messages.Arg, response *[]byte) error {
  202. answer, id, err := messages.DecodeAnswerRequest(arg.Body)
  203. if err != nil || answer == "" {
  204. return messages.ErrBadRequest
  205. }
  206. var success = true
  207. i.ctx.snowflakeLock.Lock()
  208. snowflake, ok := i.ctx.idToSnowflake[id]
  209. i.ctx.snowflakeLock.Unlock()
  210. if !ok || snowflake == nil {
  211. // The snowflake took too long to respond with an answer, so its client
  212. // disappeared / the snowflake is no longer recognized by the Broker.
  213. success = false
  214. log.Printf("Warning: matching with snowflake client failed")
  215. }
  216. b, err := messages.EncodeAnswerResponse(success)
  217. if err != nil {
  218. log.Printf("Error encoding answer: %s", err.Error())
  219. return messages.ErrInternal
  220. }
  221. *response = b
  222. if success {
  223. snowflake.answerChannel <- answer
  224. }
  225. return nil
  226. }