main.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package main
  3. import (
  4. "compress/gzip"
  5. "context"
  6. "crypto/tls"
  7. "encoding/json"
  8. "flag"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "log"
  13. "net"
  14. "net/http"
  15. "net/url"
  16. "os"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/golang/groupcache/lru"
  22. "github.com/oschwald/geoip2-golang"
  23. "github.com/prometheus/client_golang/prometheus"
  24. "github.com/prometheus/client_golang/prometheus/promhttp"
  25. "github.com/syncthing/syncthing/cmd/strelaypoolsrv/auto"
  26. "github.com/syncthing/syncthing/lib/assets"
  27. "github.com/syncthing/syncthing/lib/rand"
  28. "github.com/syncthing/syncthing/lib/relay/client"
  29. "github.com/syncthing/syncthing/lib/sync"
  30. "github.com/syncthing/syncthing/lib/tlsutil"
  31. "golang.org/x/time/rate"
  32. )
  33. type location struct {
  34. Latitude float64 `json:"latitude"`
  35. Longitude float64 `json:"longitude"`
  36. City string `json:"city"`
  37. Country string `json:"country"`
  38. Continent string `json:"continent"`
  39. }
  40. type relay struct {
  41. URL string `json:"url"`
  42. Location location `json:"location"`
  43. uri *url.URL
  44. Stats *stats `json:"stats"`
  45. StatsRetrieved time.Time `json:"statsRetrieved"`
  46. }
  47. type stats struct {
  48. StartTime time.Time `json:"startTime"`
  49. UptimeSeconds int `json:"uptimeSeconds"`
  50. PendingSessionKeys int `json:"numPendingSessionKeys"`
  51. ActiveSessions int `json:"numActiveSessions"`
  52. Connections int `json:"numConnections"`
  53. Proxies int `json:"numProxies"`
  54. BytesProxied int `json:"bytesProxied"`
  55. GoVersion string `json:"goVersion"`
  56. GoOS string `json:"goOS"`
  57. GoArch string `json:"goArch"`
  58. GoMaxProcs int `json:"goMaxProcs"`
  59. GoRoutines int `json:"goNumRoutine"`
  60. Rates []int64 `json:"kbps10s1m5m15m30m60m"`
  61. Options struct {
  62. NetworkTimeout int `json:"network-timeout"`
  63. PintInterval int `json:"ping-interval"`
  64. MessageTimeout int `json:"message-timeout"`
  65. SessionRate int `json:"per-session-rate"`
  66. GlobalRate int `json:"global-rate"`
  67. Pools []string `json:"pools"`
  68. ProvidedBy string `json:"provided-by"`
  69. } `json:"options"`
  70. }
  71. func (r relay) String() string {
  72. return r.URL
  73. }
  74. type request struct {
  75. relay *relay
  76. result chan result
  77. queueTimer *prometheus.Timer
  78. }
  79. type result struct {
  80. err error
  81. eviction time.Duration
  82. }
  83. var (
  84. testCert tls.Certificate
  85. knownRelaysFile = filepath.Join(os.TempDir(), "strelaypoolsrv_known_relays")
  86. listen = ":80"
  87. dir string
  88. evictionTime = time.Hour
  89. debug bool
  90. getLRUSize = 10 << 10
  91. getLimitBurst = 10
  92. getLimitAvg = 2
  93. postLRUSize = 1 << 10
  94. postLimitBurst = 2
  95. postLimitAvg = 2
  96. getLimit time.Duration
  97. postLimit time.Duration
  98. permRelaysFile string
  99. ipHeader string
  100. geoipPath string
  101. proto string
  102. statsRefresh = time.Minute / 2
  103. requestQueueLen = 10
  104. requestProcessors = 1
  105. getMut = sync.NewMutex()
  106. getLRUCache *lru.Cache
  107. postMut = sync.NewMutex()
  108. postLRUCache *lru.Cache
  109. requests chan request
  110. mut = sync.NewRWMutex()
  111. knownRelays = make([]*relay, 0)
  112. permanentRelays = make([]*relay, 0)
  113. evictionTimers = make(map[string]*time.Timer)
  114. )
  115. const (
  116. httpStatusEnhanceYourCalm = 429
  117. )
  118. func main() {
  119. log.SetOutput(os.Stdout)
  120. log.SetFlags(log.Lshortfile)
  121. flag.StringVar(&listen, "listen", listen, "Listen address")
  122. flag.StringVar(&dir, "keys", dir, "Directory where http-cert.pem and http-key.pem is stored for TLS listening")
  123. flag.BoolVar(&debug, "debug", debug, "Enable debug output")
  124. flag.DurationVar(&evictionTime, "eviction", evictionTime, "After how long the relay is evicted")
  125. flag.IntVar(&getLRUSize, "get-limit-cache", getLRUSize, "Get request limiter cache size")
  126. flag.IntVar(&getLimitAvg, "get-limit-avg", getLimitAvg, "Allowed average get request rate, per 10 s")
  127. flag.IntVar(&getLimitBurst, "get-limit-burst", getLimitBurst, "Allowed burst get requests")
  128. flag.IntVar(&postLRUSize, "post-limit-cache", postLRUSize, "Post request limiter cache size")
  129. flag.IntVar(&postLimitAvg, "post-limit-avg", postLimitAvg, "Allowed average post request rate, per minute")
  130. flag.IntVar(&postLimitBurst, "post-limit-burst", postLimitBurst, "Allowed burst post requests")
  131. flag.StringVar(&permRelaysFile, "perm-relays", "", "Path to list of permanent relays")
  132. flag.StringVar(&ipHeader, "ip-header", "", "Name of header which holds clients ip:port. Only meaningful when running behind a reverse proxy.")
  133. flag.StringVar(&geoipPath, "geoip", "GeoLite2-City.mmdb", "Path to GeoLite2-City database")
  134. flag.StringVar(&proto, "protocol", "tcp", "Protocol used for listening. 'tcp' for IPv4 and IPv6, 'tcp4' for IPv4, 'tcp6' for IPv6")
  135. flag.DurationVar(&statsRefresh, "stats-refresh", statsRefresh, "Interval at which to refresh relay stats")
  136. flag.IntVar(&requestQueueLen, "request-queue", requestQueueLen, "Queue length for incoming test requests")
  137. flag.IntVar(&requestProcessors, "request-processors", requestProcessors, "Number of request processor routines")
  138. flag.Parse()
  139. requests = make(chan request, requestQueueLen)
  140. getLimit = 10 * time.Second / time.Duration(getLimitAvg)
  141. postLimit = time.Minute / time.Duration(postLimitAvg)
  142. getLRUCache = lru.New(getLRUSize)
  143. postLRUCache = lru.New(postLRUSize)
  144. var listener net.Listener
  145. var err error
  146. if permRelaysFile != "" {
  147. permanentRelays = loadRelays(permRelaysFile)
  148. }
  149. testCert = createTestCertificate()
  150. for i := 0; i < requestProcessors; i++ {
  151. go requestProcessor()
  152. }
  153. // Load relays from cache in the background.
  154. // Load them in a serial fashion to make sure any genuine requests
  155. // are not dropped.
  156. go func() {
  157. for _, relay := range loadRelays(knownRelaysFile) {
  158. resultChan := make(chan result)
  159. requests <- request{relay, resultChan, nil}
  160. result := <-resultChan
  161. if result.err != nil {
  162. relayTestsTotal.WithLabelValues("failed").Inc()
  163. } else {
  164. relayTestsTotal.WithLabelValues("success").Inc()
  165. }
  166. }
  167. // Run the the stats refresher once the relays are loaded.
  168. statsRefresher(statsRefresh)
  169. }()
  170. if dir != "" {
  171. if debug {
  172. log.Println("Starting TLS listener on", listen)
  173. }
  174. certFile, keyFile := filepath.Join(dir, "http-cert.pem"), filepath.Join(dir, "http-key.pem")
  175. var cert tls.Certificate
  176. cert, err = tls.LoadX509KeyPair(certFile, keyFile)
  177. if err != nil {
  178. log.Fatalln("Failed to load HTTP X509 key pair:", err)
  179. }
  180. tlsCfg := &tls.Config{
  181. Certificates: []tls.Certificate{cert},
  182. MinVersion: tls.VersionTLS10, // No SSLv3
  183. CipherSuites: []uint16{
  184. // No RC4
  185. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  186. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  187. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  188. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  189. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  190. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  191. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  192. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  193. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  194. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  195. },
  196. }
  197. listener, err = tls.Listen(proto, listen, tlsCfg)
  198. } else {
  199. if debug {
  200. log.Println("Starting plain listener on", listen)
  201. }
  202. listener, err = net.Listen(proto, listen)
  203. }
  204. if err != nil {
  205. log.Fatalln("listen:", err)
  206. }
  207. handler := http.NewServeMux()
  208. handler.HandleFunc("/", handleAssets)
  209. handler.HandleFunc("/endpoint", handleRequest)
  210. handler.HandleFunc("/metrics", handleMetrics)
  211. srv := http.Server{
  212. Handler: handler,
  213. ReadTimeout: 10 * time.Second,
  214. }
  215. err = srv.Serve(listener)
  216. if err != nil {
  217. log.Fatalln("serve:", err)
  218. }
  219. }
  220. func handleMetrics(w http.ResponseWriter, r *http.Request) {
  221. timer := prometheus.NewTimer(metricsRequestsSeconds)
  222. // Acquire the mutex just to make sure we're not caught mid-way stats collection
  223. mut.RLock()
  224. promhttp.Handler().ServeHTTP(w, r)
  225. mut.RUnlock()
  226. timer.ObserveDuration()
  227. }
  228. func handleAssets(w http.ResponseWriter, r *http.Request) {
  229. w.Header().Set("Cache-Control", "no-cache, must-revalidate")
  230. path := r.URL.Path[1:]
  231. if path == "" {
  232. path = "index.html"
  233. }
  234. as, ok := auto.Assets()[path]
  235. if !ok {
  236. w.WriteHeader(http.StatusNotFound)
  237. return
  238. }
  239. assets.Serve(w, r, as)
  240. }
  241. func handleRequest(w http.ResponseWriter, r *http.Request) {
  242. timer := prometheus.NewTimer(apiRequestsSeconds.WithLabelValues(r.Method))
  243. w = NewLoggingResponseWriter(w)
  244. defer func() {
  245. timer.ObserveDuration()
  246. lw := w.(*loggingResponseWriter)
  247. apiRequestsTotal.WithLabelValues(r.Method, strconv.Itoa(lw.statusCode)).Inc()
  248. }()
  249. if ipHeader != "" {
  250. r.RemoteAddr = r.Header.Get(ipHeader)
  251. }
  252. w.Header().Set("Access-Control-Allow-Origin", "*")
  253. switch r.Method {
  254. case "GET":
  255. if limit(r.RemoteAddr, getLRUCache, getMut, getLimit, getLimitBurst) {
  256. w.WriteHeader(httpStatusEnhanceYourCalm)
  257. return
  258. }
  259. handleGetRequest(w, r)
  260. case "POST":
  261. if limit(r.RemoteAddr, postLRUCache, postMut, postLimit, postLimitBurst) {
  262. w.WriteHeader(httpStatusEnhanceYourCalm)
  263. return
  264. }
  265. handlePostRequest(w, r)
  266. default:
  267. if debug {
  268. log.Println("Unhandled HTTP method", r.Method)
  269. }
  270. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  271. }
  272. }
  273. func handleGetRequest(rw http.ResponseWriter, r *http.Request) {
  274. rw.Header().Set("Content-Type", "application/json; charset=utf-8")
  275. mut.RLock()
  276. relays := append(permanentRelays, knownRelays...)
  277. mut.RUnlock()
  278. // Shuffle
  279. rand.Shuffle(relays)
  280. w := io.Writer(rw)
  281. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  282. rw.Header().Set("Content-Encoding", "gzip")
  283. gw := gzip.NewWriter(rw)
  284. defer gw.Close()
  285. w = gw
  286. }
  287. _ = json.NewEncoder(w).Encode(map[string][]*relay{
  288. "relays": relays,
  289. })
  290. }
  291. func handlePostRequest(w http.ResponseWriter, r *http.Request) {
  292. var newRelay relay
  293. err := json.NewDecoder(r.Body).Decode(&newRelay)
  294. r.Body.Close()
  295. if err != nil {
  296. if debug {
  297. log.Println("Failed to parse payload")
  298. }
  299. http.Error(w, err.Error(), http.StatusBadRequest)
  300. return
  301. }
  302. uri, err := url.Parse(newRelay.URL)
  303. if err != nil {
  304. if debug {
  305. log.Println("Failed to parse URI", newRelay.URL)
  306. }
  307. http.Error(w, err.Error(), http.StatusBadRequest)
  308. return
  309. }
  310. host, port, err := net.SplitHostPort(uri.Host)
  311. if err != nil {
  312. if debug {
  313. log.Println("Failed to split URI", newRelay.URL)
  314. }
  315. http.Error(w, err.Error(), http.StatusBadRequest)
  316. return
  317. }
  318. // Get the IP address of the client
  319. rhost := r.RemoteAddr
  320. if host, _, err := net.SplitHostPort(rhost); err == nil {
  321. rhost = host
  322. }
  323. ip := net.ParseIP(host)
  324. // The client did not provide an IP address, use the IP address of the client.
  325. if ip == nil || ip.IsUnspecified() {
  326. uri.Host = net.JoinHostPort(rhost, port)
  327. newRelay.URL = uri.String()
  328. } else if host != rhost {
  329. if debug {
  330. log.Println("IP address advertised does not match client IP address", r.RemoteAddr, uri)
  331. }
  332. http.Error(w, fmt.Sprintf("IP advertised %s does not match client IP %s", host, rhost), http.StatusUnauthorized)
  333. return
  334. }
  335. newRelay.uri = uri
  336. for _, current := range permanentRelays {
  337. if current.uri.Host == newRelay.uri.Host {
  338. if debug {
  339. log.Println("Asked to add a relay", newRelay, "which exists in permanent list")
  340. }
  341. http.Error(w, "Invalid request", http.StatusBadRequest)
  342. return
  343. }
  344. }
  345. reschan := make(chan result)
  346. select {
  347. case requests <- request{&newRelay, reschan, prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("queue"))}:
  348. result := <-reschan
  349. if result.err != nil {
  350. relayTestsTotal.WithLabelValues("failed").Inc()
  351. http.Error(w, result.err.Error(), http.StatusBadRequest)
  352. return
  353. }
  354. relayTestsTotal.WithLabelValues("success").Inc()
  355. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  356. json.NewEncoder(w).Encode(map[string]time.Duration{
  357. "evictionIn": result.eviction,
  358. })
  359. default:
  360. relayTestsTotal.WithLabelValues("dropped").Inc()
  361. if debug {
  362. log.Println("Dropping request")
  363. }
  364. w.WriteHeader(httpStatusEnhanceYourCalm)
  365. }
  366. }
  367. func requestProcessor() {
  368. for request := range requests {
  369. if request.queueTimer != nil {
  370. request.queueTimer.ObserveDuration()
  371. }
  372. timer := prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("test"))
  373. handleRelayTest(request)
  374. timer.ObserveDuration()
  375. }
  376. }
  377. func handleRelayTest(request request) {
  378. if debug {
  379. log.Println("Request for", request.relay)
  380. }
  381. if err := client.TestRelay(context.TODO(), request.relay.uri, []tls.Certificate{testCert}, time.Second, 2*time.Second, 3); err != nil {
  382. if debug {
  383. log.Println("Test for relay", request.relay, "failed:", err)
  384. }
  385. request.result <- result{err, 0}
  386. return
  387. }
  388. stats := fetchStats(request.relay)
  389. location := getLocation(request.relay.uri.Host)
  390. mut.Lock()
  391. if stats != nil {
  392. updateMetrics(request.relay.uri.Host, *stats, location)
  393. }
  394. request.relay.Stats = stats
  395. request.relay.StatsRetrieved = time.Now()
  396. request.relay.Location = location
  397. timer, ok := evictionTimers[request.relay.uri.Host]
  398. if ok {
  399. if debug {
  400. log.Println("Stopping existing timer for", request.relay)
  401. }
  402. timer.Stop()
  403. }
  404. for i, current := range knownRelays {
  405. if current.uri.Host == request.relay.uri.Host {
  406. if debug {
  407. log.Println("Relay", request.relay, "already exists")
  408. }
  409. // Evict the old entry anyway, as configuration might have changed.
  410. last := len(knownRelays) - 1
  411. knownRelays[i] = knownRelays[last]
  412. knownRelays = knownRelays[:last]
  413. goto found
  414. }
  415. }
  416. if debug {
  417. log.Println("Adding new relay", request.relay)
  418. }
  419. found:
  420. knownRelays = append(knownRelays, request.relay)
  421. evictionTimers[request.relay.uri.Host] = time.AfterFunc(evictionTime, evict(request.relay))
  422. mut.Unlock()
  423. if err := saveRelays(knownRelaysFile, knownRelays); err != nil {
  424. log.Println("Failed to write known relays: " + err.Error())
  425. }
  426. request.result <- result{nil, evictionTime}
  427. }
  428. func evict(relay *relay) func() {
  429. return func() {
  430. mut.Lock()
  431. defer mut.Unlock()
  432. if debug {
  433. log.Println("Evicting", relay)
  434. }
  435. for i, current := range knownRelays {
  436. if current.uri.Host == relay.uri.Host {
  437. if debug {
  438. log.Println("Evicted", relay)
  439. }
  440. last := len(knownRelays) - 1
  441. knownRelays[i] = knownRelays[last]
  442. knownRelays = knownRelays[:last]
  443. deleteMetrics(current.uri.Host)
  444. }
  445. }
  446. delete(evictionTimers, relay.uri.Host)
  447. }
  448. }
  449. func limit(addr string, cache *lru.Cache, lock sync.Mutex, intv time.Duration, burst int) bool {
  450. if host, _, err := net.SplitHostPort(addr); err == nil {
  451. addr = host
  452. }
  453. lock.Lock()
  454. v, _ := cache.Get(addr)
  455. bkt, ok := v.(*rate.Limiter)
  456. if !ok {
  457. bkt = rate.NewLimiter(rate.Every(intv), burst)
  458. cache.Add(addr, bkt)
  459. }
  460. lock.Unlock()
  461. return !bkt.Allow()
  462. }
  463. func loadRelays(file string) []*relay {
  464. content, err := ioutil.ReadFile(file)
  465. if err != nil {
  466. log.Println("Failed to load relays: " + err.Error())
  467. return nil
  468. }
  469. var relays []*relay
  470. for _, line := range strings.Split(string(content), "\n") {
  471. if len(line) == 0 {
  472. continue
  473. }
  474. uri, err := url.Parse(line)
  475. if err != nil {
  476. if debug {
  477. log.Println("Skipping relay", line, "due to parse error", err)
  478. }
  479. continue
  480. }
  481. relays = append(relays, &relay{
  482. URL: line,
  483. Location: getLocation(uri.Host),
  484. uri: uri,
  485. })
  486. if debug {
  487. log.Println("Adding relay", line)
  488. }
  489. }
  490. return relays
  491. }
  492. func saveRelays(file string, relays []*relay) error {
  493. var content string
  494. for _, relay := range relays {
  495. content += relay.uri.String() + "\n"
  496. }
  497. return ioutil.WriteFile(file, []byte(content), 0777)
  498. }
  499. func createTestCertificate() tls.Certificate {
  500. tmpDir, err := ioutil.TempDir("", "relaypoolsrv")
  501. if err != nil {
  502. log.Fatal(err)
  503. }
  504. certFile, keyFile := filepath.Join(tmpDir, "cert.pem"), filepath.Join(tmpDir, "key.pem")
  505. cert, err := tlsutil.NewCertificate(certFile, keyFile, "relaypoolsrv", 20*365)
  506. if err != nil {
  507. log.Fatalln("Failed to create test X509 key pair:", err)
  508. }
  509. return cert
  510. }
  511. func getLocation(host string) location {
  512. timer := prometheus.NewTimer(locationLookupSeconds)
  513. defer timer.ObserveDuration()
  514. db, err := geoip2.Open(geoipPath)
  515. if err != nil {
  516. return location{}
  517. }
  518. defer db.Close()
  519. addr, err := net.ResolveTCPAddr("tcp", host)
  520. if err != nil {
  521. return location{}
  522. }
  523. city, err := db.City(addr.IP)
  524. if err != nil {
  525. return location{}
  526. }
  527. return location{
  528. Longitude: city.Location.Longitude,
  529. Latitude: city.Location.Latitude,
  530. City: city.City.Names["en"],
  531. Country: city.Country.IsoCode,
  532. Continent: city.Continent.Code,
  533. }
  534. }
  535. type loggingResponseWriter struct {
  536. http.ResponseWriter
  537. statusCode int
  538. }
  539. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  540. return &loggingResponseWriter{w, http.StatusOK}
  541. }
  542. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  543. lrw.statusCode = code
  544. lrw.ResponseWriter.WriteHeader(code)
  545. }