broker.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. Broker acts as the HTTP signaling channel.
  3. It matches clients and snowflake proxies by passing corresponding
  4. SessionDescriptions in order to negotiate a WebRTC connection.
  5. */
  6. package main
  7. import (
  8. "container/heap"
  9. "crypto/tls"
  10. "flag"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "log"
  15. "net"
  16. "net/http"
  17. "os"
  18. "os/signal"
  19. "strings"
  20. "syscall"
  21. "time"
  22. "git.torproject.org/pluggable-transports/snowflake.git/common/safelog"
  23. "golang.org/x/crypto/acme/autocert"
  24. )
  25. const (
  26. ClientTimeout = 10
  27. ProxyTimeout = 10
  28. readLimit = 100000 //Maximum number of bytes to be read from an HTTP request
  29. )
  30. type BrokerContext struct {
  31. snowflakes *SnowflakeHeap
  32. // Map keeping track of snowflakeIDs required to match SDP answers from
  33. // the second http POST.
  34. idToSnowflake map[string]*Snowflake
  35. proxyPolls chan *ProxyPoll
  36. metrics *Metrics
  37. }
  38. func NewBrokerContext(metricsLogger *log.Logger) *BrokerContext {
  39. snowflakes := new(SnowflakeHeap)
  40. heap.Init(snowflakes)
  41. metrics, err := NewMetrics(metricsLogger)
  42. if err != nil {
  43. panic(err.Error())
  44. }
  45. if metrics == nil {
  46. panic("Failed to create metrics")
  47. }
  48. return &BrokerContext{
  49. snowflakes: snowflakes,
  50. idToSnowflake: make(map[string]*Snowflake),
  51. proxyPolls: make(chan *ProxyPoll),
  52. metrics: metrics,
  53. }
  54. }
  55. // Implements the http.Handler interface
  56. type SnowflakeHandler struct {
  57. *BrokerContext
  58. handle func(*BrokerContext, http.ResponseWriter, *http.Request)
  59. }
  60. func (sh SnowflakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  61. w.Header().Set("Access-Control-Allow-Origin", "*")
  62. w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Session-ID")
  63. // Return early if it's CORS preflight.
  64. if "OPTIONS" == r.Method {
  65. return
  66. }
  67. sh.handle(sh.BrokerContext, w, r)
  68. }
  69. // Proxies may poll for client offers concurrently.
  70. type ProxyPoll struct {
  71. id string
  72. offerChannel chan []byte
  73. }
  74. // Registers a Snowflake and waits for some Client to send an offer,
  75. // as part of the polling logic of the proxy handler.
  76. func (ctx *BrokerContext) RequestOffer(id string) []byte {
  77. request := new(ProxyPoll)
  78. request.id = id
  79. request.offerChannel = make(chan []byte)
  80. ctx.proxyPolls <- request
  81. // Block until an offer is available, or timeout which sends a nil offer.
  82. offer := <-request.offerChannel
  83. return offer
  84. }
  85. // goroutine which matches clients to proxies and sends SDP offers along.
  86. // Safely processes proxy requests, responding to them with either an available
  87. // client offer or nil on timeout / none are available.
  88. func (ctx *BrokerContext) Broker() {
  89. for request := range ctx.proxyPolls {
  90. snowflake := ctx.AddSnowflake(request.id)
  91. // Wait for a client to avail an offer to the snowflake.
  92. go func(request *ProxyPoll) {
  93. select {
  94. case offer := <-snowflake.offerChannel:
  95. log.Println("Passing client offer to snowflake proxy.")
  96. request.offerChannel <- offer
  97. case <-time.After(time.Second * ProxyTimeout):
  98. // This snowflake is no longer available to serve clients.
  99. // TODO: Fix race using a delete channel
  100. heap.Remove(ctx.snowflakes, snowflake.index)
  101. delete(ctx.idToSnowflake, snowflake.id)
  102. request.offerChannel <- nil
  103. }
  104. }(request)
  105. }
  106. }
  107. // Create and add a Snowflake to the heap.
  108. // Required to keep track of proxies between providing them
  109. // with an offer and awaiting their second POST with an answer.
  110. func (ctx *BrokerContext) AddSnowflake(id string) *Snowflake {
  111. snowflake := new(Snowflake)
  112. snowflake.id = id
  113. snowflake.clients = 0
  114. snowflake.offerChannel = make(chan []byte)
  115. snowflake.answerChannel = make(chan []byte)
  116. heap.Push(ctx.snowflakes, snowflake)
  117. ctx.idToSnowflake[id] = snowflake
  118. return snowflake
  119. }
  120. /*
  121. For snowflake proxies to request a client from the Broker.
  122. */
  123. func proxyPolls(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
  124. id := r.Header.Get("X-Session-ID")
  125. body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, readLimit))
  126. if nil != err {
  127. log.Println("Invalid data.")
  128. w.WriteHeader(http.StatusBadRequest)
  129. return
  130. }
  131. if string(body) != id {
  132. log.Println("Mismatched IDs!")
  133. w.WriteHeader(http.StatusBadRequest)
  134. return
  135. }
  136. log.Println("Received snowflake: ", id)
  137. // Log geoip stats
  138. remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
  139. if err != nil {
  140. log.Println("Error processing proxy IP: ", err.Error())
  141. } else {
  142. ctx.metrics.UpdateCountryStats(remoteIP)
  143. }
  144. // Wait for a client to avail an offer to the snowflake, or timeout if nil.
  145. offer := ctx.RequestOffer(id)
  146. if nil == offer {
  147. log.Println("Proxy " + id + " did not receive a Client offer.")
  148. ctx.metrics.proxyIdleCount++
  149. w.WriteHeader(http.StatusGatewayTimeout)
  150. return
  151. }
  152. log.Println("Passing client offer to snowflake.")
  153. w.Write(offer)
  154. }
  155. /*
  156. Expects a WebRTC SDP offer in the Request to give to an assigned
  157. snowflake proxy, which responds with the SDP answer to be sent in
  158. the HTTP response back to the client.
  159. */
  160. func clientOffers(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
  161. startTime := time.Now()
  162. offer, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, readLimit))
  163. if nil != err {
  164. log.Println("Invalid data.")
  165. w.WriteHeader(http.StatusBadRequest)
  166. return
  167. }
  168. // Immediately fail if there are no snowflakes available.
  169. if ctx.snowflakes.Len() <= 0 {
  170. log.Println("Client: No snowflake proxies available.")
  171. ctx.metrics.clientDeniedCount++
  172. w.WriteHeader(http.StatusServiceUnavailable)
  173. return
  174. }
  175. // Otherwise, find the most available snowflake proxy, and pass the offer to it.
  176. // Delete must be deferred in order to correctly process answer request later.
  177. snowflake := heap.Pop(ctx.snowflakes).(*Snowflake)
  178. defer delete(ctx.idToSnowflake, snowflake.id)
  179. snowflake.offerChannel <- offer
  180. // Wait for the answer to be returned on the channel or timeout.
  181. select {
  182. case answer := <-snowflake.answerChannel:
  183. log.Println("Client: Retrieving answer")
  184. ctx.metrics.clientProxyMatchCount++
  185. w.Write(answer)
  186. // Initial tracking of elapsed time.
  187. ctx.metrics.clientRoundtripEstimate = time.Since(startTime) /
  188. time.Millisecond
  189. case <-time.After(time.Second * ClientTimeout):
  190. log.Println("Client: Timed out.")
  191. w.WriteHeader(http.StatusGatewayTimeout)
  192. w.Write([]byte("timed out waiting for answer!"))
  193. }
  194. }
  195. /*
  196. Expects snowflake proxes which have previously successfully received
  197. an offer from proxyHandler to respond with an answer in an HTTP POST,
  198. which the broker will pass back to the original client.
  199. */
  200. func proxyAnswers(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
  201. id := r.Header.Get("X-Session-ID")
  202. snowflake, ok := ctx.idToSnowflake[id]
  203. if !ok || nil == snowflake {
  204. // The snowflake took too long to respond with an answer, so its client
  205. // disappeared / the snowflake is no longer recognized by the Broker.
  206. w.WriteHeader(http.StatusGone)
  207. return
  208. }
  209. body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, readLimit))
  210. if nil != err || nil == body || len(body) <= 0 {
  211. log.Println("Invalid data.")
  212. w.WriteHeader(http.StatusBadRequest)
  213. return
  214. }
  215. log.Println("Received answer.")
  216. snowflake.answerChannel <- body
  217. }
  218. func debugHandler(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
  219. s := fmt.Sprintf("current snowflakes available: %d\n", ctx.snowflakes.Len())
  220. for _, snowflake := range ctx.idToSnowflake {
  221. s += fmt.Sprintf("\nsnowflake %d: %s", snowflake.index, snowflake.id)
  222. }
  223. s += fmt.Sprintf("\n\nroundtrip avg: %d", ctx.metrics.clientRoundtripEstimate)
  224. w.Write([]byte(s))
  225. }
  226. func robotsTxtHandler(w http.ResponseWriter, r *http.Request) {
  227. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  228. w.Write([]byte("User-agent: *\nDisallow: /\n"))
  229. }
  230. func main() {
  231. var acmeEmail string
  232. var acmeHostnamesCommas string
  233. var acmeCertCacheDir string
  234. var addr string
  235. var geoipDatabase string
  236. var geoip6Database string
  237. var disableTLS bool
  238. var certFilename, keyFilename string
  239. var disableGeoip bool
  240. var metricsFilename string
  241. flag.StringVar(&acmeEmail, "acme-email", "", "optional contact email for Let's Encrypt notifications")
  242. flag.StringVar(&acmeHostnamesCommas, "acme-hostnames", "", "comma-separated hostnames for TLS certificate")
  243. flag.StringVar(&certFilename, "cert", "", "TLS certificate file")
  244. flag.StringVar(&keyFilename, "key", "", "TLS private key file")
  245. flag.StringVar(&acmeCertCacheDir, "acme-cert-cache", "acme-cert-cache", "directory in which certificates should be cached")
  246. flag.StringVar(&addr, "addr", ":443", "address to listen on")
  247. flag.StringVar(&geoipDatabase, "geoipdb", "/usr/share/tor/geoip", "path to correctly formatted geoip database mapping IPv4 address ranges to country codes")
  248. flag.StringVar(&geoip6Database, "geoip6db", "/usr/share/tor/geoip6", "path to correctly formatted geoip database mapping IPv6 address ranges to country codes")
  249. flag.BoolVar(&disableTLS, "disable-tls", false, "don't use HTTPS")
  250. flag.BoolVar(&disableGeoip, "disable-geoip", false, "don't use geoip for stats collection")
  251. flag.StringVar(&metricsFilename, "metrics-log", "", "path to metrics logging output")
  252. flag.Parse()
  253. var err error
  254. var metricsFile io.Writer = os.Stdout
  255. var logOutput io.Writer = os.Stderr
  256. //We want to send the log output through our scrubber first
  257. log.SetOutput(&safelog.LogScrubber{Output: logOutput})
  258. log.SetFlags(log.LstdFlags | log.LUTC)
  259. if metricsFilename != "" {
  260. metricsFile, err = os.OpenFile(metricsFilename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  261. if err != nil {
  262. log.Fatal(err.Error())
  263. }
  264. } else {
  265. metricsFile = os.Stdout
  266. }
  267. metricsLogger := log.New(metricsFile, "", 0)
  268. ctx := NewBrokerContext(metricsLogger)
  269. if !disableGeoip {
  270. err := ctx.metrics.LoadGeoipDatabases(geoipDatabase, geoip6Database)
  271. if err != nil {
  272. log.Fatal(err.Error())
  273. }
  274. }
  275. go ctx.Broker()
  276. http.HandleFunc("/robots.txt", robotsTxtHandler)
  277. http.Handle("/proxy", SnowflakeHandler{ctx, proxyPolls})
  278. http.Handle("/client", SnowflakeHandler{ctx, clientOffers})
  279. http.Handle("/answer", SnowflakeHandler{ctx, proxyAnswers})
  280. http.Handle("/debug", SnowflakeHandler{ctx, debugHandler})
  281. server := http.Server{
  282. Addr: addr,
  283. }
  284. sigChan := make(chan os.Signal, 1)
  285. signal.Notify(sigChan, syscall.SIGHUP)
  286. // go routine to handle a SIGHUP signal to allow the broker operator to send
  287. // a SIGHUP signal when the geoip database files are updated, without requiring
  288. // a restart of the broker
  289. go func() {
  290. for {
  291. signal := <-sigChan
  292. log.Println("Received signal:", signal, ". Reloading geoip databases.")
  293. ctx.metrics.LoadGeoipDatabases(geoipDatabase, geoip6Database)
  294. }
  295. }()
  296. // Handle the various ways of setting up TLS. The legal configurations
  297. // are:
  298. // --acme-hostnames (with optional --acme-email and/or --acme-cert-cache)
  299. // --cert and --key together
  300. // --disable-tls
  301. // The outputs of this block of code are the disableTLS,
  302. // needHTTP01Listener, certManager, and getCertificate variables.
  303. if acmeHostnamesCommas != "" {
  304. acmeHostnames := strings.Split(acmeHostnamesCommas, ",")
  305. log.Printf("ACME hostnames: %q", acmeHostnames)
  306. var cache autocert.Cache
  307. if err = os.MkdirAll(acmeCertCacheDir, 0700); err != nil {
  308. log.Printf("Warning: Couldn't create cache directory %q (reason: %s) so we're *not* using our certificate cache.", acmeCertCacheDir, err)
  309. } else {
  310. cache = autocert.DirCache(acmeCertCacheDir)
  311. }
  312. certManager := autocert.Manager{
  313. Cache: cache,
  314. Prompt: autocert.AcceptTOS,
  315. HostPolicy: autocert.HostWhitelist(acmeHostnames...),
  316. Email: acmeEmail,
  317. }
  318. go func() {
  319. log.Printf("Starting HTTP-01 listener")
  320. log.Fatal(http.ListenAndServe(":80", certManager.HTTPHandler(nil)))
  321. }()
  322. server.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate}
  323. err = server.ListenAndServeTLS("", "")
  324. } else if certFilename != "" && keyFilename != "" {
  325. if acmeEmail != "" || acmeHostnamesCommas != "" {
  326. log.Fatalf("The --cert and --key options are not allowed with --acme-email or --acme-hostnames.")
  327. }
  328. err = server.ListenAndServeTLS(certFilename, keyFilename)
  329. } else if disableTLS {
  330. err = server.ListenAndServe()
  331. } else {
  332. log.Fatal("the --acme-hostnames, --cert and --key, or --disable-tls option is required")
  333. }
  334. if err != nil {
  335. log.Fatal(err)
  336. }
  337. }