broker.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. // Wait for a client to avail an offer to the snowflake, or timeout if nil.
  138. offer := ctx.RequestOffer(id)
  139. if nil == offer {
  140. log.Println("Proxy " + id + " did not receive a Client offer.")
  141. w.WriteHeader(http.StatusGatewayTimeout)
  142. return
  143. }
  144. log.Println("Passing client offer to snowflake.")
  145. w.Write(offer)
  146. }
  147. /*
  148. Expects a WebRTC SDP offer in the Request to give to an assigned
  149. snowflake proxy, which responds with the SDP answer to be sent in
  150. the HTTP response back to the client.
  151. */
  152. func clientOffers(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
  153. startTime := time.Now()
  154. offer, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, readLimit))
  155. if nil != err {
  156. log.Println("Invalid data.")
  157. w.WriteHeader(http.StatusBadRequest)
  158. return
  159. }
  160. // Immediately fail if there are no snowflakes available.
  161. if ctx.snowflakes.Len() <= 0 {
  162. log.Println("Client: No snowflake proxies available.")
  163. w.WriteHeader(http.StatusServiceUnavailable)
  164. return
  165. }
  166. // Otherwise, find the most available snowflake proxy, and pass the offer to it.
  167. // Delete must be deferred in order to correctly process answer request later.
  168. snowflake := heap.Pop(ctx.snowflakes).(*Snowflake)
  169. defer delete(ctx.idToSnowflake, snowflake.id)
  170. snowflake.offerChannel <- offer
  171. // Wait for the answer to be returned on the channel or timeout.
  172. select {
  173. case answer := <-snowflake.answerChannel:
  174. log.Println("Client: Retrieving answer")
  175. w.Write(answer)
  176. // Initial tracking of elapsed time.
  177. ctx.metrics.clientRoundtripEstimate = time.Since(startTime) /
  178. time.Millisecond
  179. case <-time.After(time.Second * ClientTimeout):
  180. log.Println("Client: Timed out.")
  181. w.WriteHeader(http.StatusGatewayTimeout)
  182. w.Write([]byte("timed out waiting for answer!"))
  183. }
  184. }
  185. /*
  186. Expects snowflake proxes which have previously successfully received
  187. an offer from proxyHandler to respond with an answer in an HTTP POST,
  188. which the broker will pass back to the original client.
  189. */
  190. func proxyAnswers(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
  191. id := r.Header.Get("X-Session-ID")
  192. snowflake, ok := ctx.idToSnowflake[id]
  193. if !ok || nil == snowflake {
  194. // The snowflake took too long to respond with an answer, so its client
  195. // disappeared / the snowflake is no longer recognized by the Broker.
  196. w.WriteHeader(http.StatusGone)
  197. return
  198. }
  199. body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, readLimit))
  200. if nil != err || nil == body || len(body) <= 0 {
  201. log.Println("Invalid data.")
  202. w.WriteHeader(http.StatusBadRequest)
  203. return
  204. }
  205. // Get proxy country stats
  206. remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
  207. if err != nil {
  208. log.Println("Error processing proxy IP: ", err.Error())
  209. } else {
  210. ctx.metrics.UpdateCountryStats(remoteIP)
  211. }
  212. log.Println("Received answer.")
  213. snowflake.answerChannel <- body
  214. }
  215. func debugHandler(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
  216. s := fmt.Sprintf("current snowflakes available: %d\n", ctx.snowflakes.Len())
  217. for _, snowflake := range ctx.idToSnowflake {
  218. s += fmt.Sprintf("\nsnowflake %d: %s", snowflake.index, snowflake.id)
  219. }
  220. s += fmt.Sprintf("\n\nroundtrip avg: %d", ctx.metrics.clientRoundtripEstimate)
  221. w.Write([]byte(s))
  222. }
  223. func robotsTxtHandler(w http.ResponseWriter, r *http.Request) {
  224. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  225. w.Write([]byte("User-agent: *\nDisallow: /\n"))
  226. }
  227. func main() {
  228. var acmeEmail string
  229. var acmeHostnamesCommas string
  230. var acmeCertCacheDir string
  231. var addr string
  232. var geoipDatabase string
  233. var geoip6Database string
  234. var disableTLS bool
  235. var certFilename, keyFilename string
  236. var disableGeoip bool
  237. var metricsFilename string
  238. flag.StringVar(&acmeEmail, "acme-email", "", "optional contact email for Let's Encrypt notifications")
  239. flag.StringVar(&acmeHostnamesCommas, "acme-hostnames", "", "comma-separated hostnames for TLS certificate")
  240. flag.StringVar(&certFilename, "cert", "", "TLS certificate file")
  241. flag.StringVar(&keyFilename, "key", "", "TLS private key file")
  242. flag.StringVar(&acmeCertCacheDir, "acme-cert-cache", "acme-cert-cache", "directory in which certificates should be cached")
  243. flag.StringVar(&addr, "addr", ":443", "address to listen on")
  244. flag.StringVar(&geoipDatabase, "geoipdb", "/usr/share/tor/geoip", "path to correctly formatted geoip database mapping IPv4 address ranges to country codes")
  245. flag.StringVar(&geoip6Database, "geoip6db", "/usr/share/tor/geoip6", "path to correctly formatted geoip database mapping IPv6 address ranges to country codes")
  246. flag.BoolVar(&disableTLS, "disable-tls", false, "don't use HTTPS")
  247. flag.BoolVar(&disableGeoip, "disable-geoip", false, "don't use geoip for stats collection")
  248. flag.StringVar(&metricsFilename, "metrics-log", "", "path to metrics logging output")
  249. flag.Parse()
  250. var err error
  251. var metricsFile io.Writer = os.Stdout
  252. var logOutput io.Writer = os.Stderr
  253. //We want to send the log output through our scrubber first
  254. log.SetOutput(&safelog.LogScrubber{Output: logOutput})
  255. log.SetFlags(log.LstdFlags | log.LUTC)
  256. if metricsFilename != "" {
  257. metricsFile, err = os.OpenFile(metricsFilename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  258. if err != nil {
  259. log.Fatal(err.Error())
  260. }
  261. } else {
  262. metricsFile = os.Stdout
  263. }
  264. metricsLogger := log.New(metricsFile, "", log.LstdFlags|log.LUTC)
  265. ctx := NewBrokerContext(metricsLogger)
  266. if !disableGeoip {
  267. err := ctx.metrics.LoadGeoipDatabases(geoipDatabase, geoip6Database)
  268. if err != nil {
  269. log.Fatal(err.Error())
  270. }
  271. }
  272. go ctx.Broker()
  273. http.HandleFunc("/robots.txt", robotsTxtHandler)
  274. http.Handle("/proxy", SnowflakeHandler{ctx, proxyPolls})
  275. http.Handle("/client", SnowflakeHandler{ctx, clientOffers})
  276. http.Handle("/answer", SnowflakeHandler{ctx, proxyAnswers})
  277. http.Handle("/debug", SnowflakeHandler{ctx, debugHandler})
  278. server := http.Server{
  279. Addr: addr,
  280. }
  281. sigChan := make(chan os.Signal, 1)
  282. signal.Notify(sigChan, syscall.SIGHUP)
  283. // go routine to handle a SIGHUP signal to allow the broker operator to send
  284. // a SIGHUP signal when the geoip database files are updated, without requiring
  285. // a restart of the broker
  286. go func() {
  287. for {
  288. signal := <-sigChan
  289. log.Println("Received signal:", signal, ". Reloading geoip databases.")
  290. ctx.metrics.LoadGeoipDatabases(geoipDatabase, geoip6Database)
  291. }
  292. }()
  293. // Handle the various ways of setting up TLS. The legal configurations
  294. // are:
  295. // --acme-hostnames (with optional --acme-email and/or --acme-cert-cache)
  296. // --cert and --key together
  297. // --disable-tls
  298. // The outputs of this block of code are the disableTLS,
  299. // needHTTP01Listener, certManager, and getCertificate variables.
  300. if acmeHostnamesCommas != "" {
  301. acmeHostnames := strings.Split(acmeHostnamesCommas, ",")
  302. log.Printf("ACME hostnames: %q", acmeHostnames)
  303. var cache autocert.Cache
  304. if err = os.MkdirAll(acmeCertCacheDir, 0700); err != nil {
  305. log.Printf("Warning: Couldn't create cache directory %q (reason: %s) so we're *not* using our certificate cache.", acmeCertCacheDir, err)
  306. } else {
  307. cache = autocert.DirCache(acmeCertCacheDir)
  308. }
  309. certManager := autocert.Manager{
  310. Cache: cache,
  311. Prompt: autocert.AcceptTOS,
  312. HostPolicy: autocert.HostWhitelist(acmeHostnames...),
  313. Email: acmeEmail,
  314. }
  315. go func() {
  316. log.Printf("Starting HTTP-01 listener")
  317. log.Fatal(http.ListenAndServe(":80", certManager.HTTPHandler(nil)))
  318. }()
  319. server.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate}
  320. err = server.ListenAndServeTLS("", "")
  321. } else if certFilename != "" && keyFilename != "" {
  322. if acmeEmail != "" || acmeHostnamesCommas != "" {
  323. log.Fatalf("The --cert and --key options are not allowed with --acme-email or --acme-hostnames.")
  324. }
  325. err = server.ListenAndServeTLS(certFilename, keyFilename)
  326. } else if disableTLS {
  327. err = server.ListenAndServe()
  328. } else {
  329. log.Fatal("the --acme-hostnames, --cert and --key, or --disable-tls option is required")
  330. }
  331. if err != nil {
  332. log.Fatal(err)
  333. }
  334. }