main.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package main
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/json"
  8. "flag"
  9. "fmt"
  10. "log"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "sync/atomic"
  20. "time"
  21. lru "github.com/hashicorp/golang-lru/v2"
  22. "github.com/prometheus/client_golang/prometheus"
  23. "github.com/prometheus/client_golang/prometheus/promhttp"
  24. "github.com/syncthing/syncthing/cmd/infra/strelaypoolsrv/auto"
  25. "github.com/syncthing/syncthing/lib/assets"
  26. "github.com/syncthing/syncthing/lib/geoip"
  27. "github.com/syncthing/syncthing/lib/protocol"
  28. "github.com/syncthing/syncthing/lib/rand"
  29. "github.com/syncthing/syncthing/lib/relay/client"
  30. "github.com/syncthing/syncthing/lib/tlsutil"
  31. )
  32. type location struct {
  33. Latitude float64 `json:"latitude"`
  34. Longitude float64 `json:"longitude"`
  35. City string `json:"city"`
  36. Country string `json:"country"`
  37. Continent string `json:"continent"`
  38. }
  39. type relay struct {
  40. URL string `json:"url"`
  41. Location location `json:"location"`
  42. uri *url.URL
  43. Stats *stats `json:"stats"`
  44. StatsRetrieved time.Time `json:"statsRetrieved"`
  45. }
  46. type relayShort struct {
  47. URL string `json:"url"`
  48. }
  49. type stats struct {
  50. StartTime time.Time `json:"startTime"`
  51. UptimeSeconds int `json:"uptimeSeconds"`
  52. PendingSessionKeys int `json:"numPendingSessionKeys"`
  53. ActiveSessions int `json:"numActiveSessions"`
  54. Connections int `json:"numConnections"`
  55. Proxies int `json:"numProxies"`
  56. BytesProxied int `json:"bytesProxied"`
  57. GoVersion string `json:"goVersion"`
  58. GoOS string `json:"goOS"`
  59. GoArch string `json:"goArch"`
  60. GoMaxProcs int `json:"goMaxProcs"`
  61. GoRoutines int `json:"goNumRoutine"`
  62. Rates []int64 `json:"kbps10s1m5m15m30m60m"`
  63. Options struct {
  64. NetworkTimeout int `json:"network-timeout"`
  65. PintInterval int `json:"ping-interval"`
  66. MessageTimeout int `json:"message-timeout"`
  67. SessionRate int `json:"per-session-rate"`
  68. GlobalRate int `json:"global-rate"`
  69. Pools []string `json:"pools"`
  70. ProvidedBy string `json:"provided-by"`
  71. } `json:"options"`
  72. }
  73. func (r relay) String() string {
  74. return r.URL
  75. }
  76. type request struct {
  77. relay *relay
  78. result chan result
  79. queueTimer *prometheus.Timer
  80. }
  81. type result struct {
  82. err error
  83. eviction time.Duration
  84. }
  85. var (
  86. testCert tls.Certificate
  87. knownRelaysFile = filepath.Join(os.TempDir(), "strelaypoolsrv_known_relays")
  88. listen = ":80"
  89. metricsListen = ":8081"
  90. dir string
  91. evictionTime = time.Hour
  92. debug bool
  93. permRelaysFile string
  94. ipHeader string
  95. proto string
  96. statsRefresh = time.Minute
  97. requestQueueLen = 64
  98. requestProcessors = 8
  99. geoipLicenseKey = os.Getenv("GEOIP_LICENSE_KEY")
  100. geoipAccountID, _ = strconv.Atoi(os.Getenv("GEOIP_ACCOUNT_ID"))
  101. maxRelaysReturned = 100
  102. requests chan request
  103. mut sync.RWMutex
  104. knownRelays = make([]*relay, 0)
  105. permanentRelays = make([]*relay, 0)
  106. evictionTimers = make(map[string]*time.Timer)
  107. globalBlocklist = newErrorTracker(1000)
  108. )
  109. const (
  110. httpStatusEnhanceYourCalm = 429
  111. )
  112. func main() {
  113. log.SetOutput(os.Stdout)
  114. log.SetFlags(log.Lshortfile)
  115. flag.StringVar(&listen, "listen", listen, "Listen address")
  116. flag.StringVar(&metricsListen, "metrics-listen", metricsListen, "Metrics listen address")
  117. flag.StringVar(&dir, "keys", dir, "Directory where http-cert.pem and http-key.pem is stored for TLS listening")
  118. flag.BoolVar(&debug, "debug", debug, "Enable debug output")
  119. flag.DurationVar(&evictionTime, "eviction", evictionTime, "After how long the relay is evicted")
  120. flag.StringVar(&permRelaysFile, "perm-relays", "", "Path to list of permanent relays")
  121. flag.StringVar(&knownRelaysFile, "known-relays", knownRelaysFile, "Path to list of current relays")
  122. flag.StringVar(&ipHeader, "ip-header", "", "Name of header which holds clients ip:port. Only meaningful when running behind a reverse proxy.")
  123. flag.StringVar(&proto, "protocol", "tcp", "Protocol used for listening. 'tcp' for IPv4 and IPv6, 'tcp4' for IPv4, 'tcp6' for IPv6")
  124. flag.DurationVar(&statsRefresh, "stats-refresh", statsRefresh, "Interval at which to refresh relay stats")
  125. flag.IntVar(&requestQueueLen, "request-queue", requestQueueLen, "Queue length for incoming test requests")
  126. flag.IntVar(&requestProcessors, "request-processors", requestProcessors, "Number of request processor routines")
  127. flag.StringVar(&geoipLicenseKey, "geoip-license-key", geoipLicenseKey, "License key for GeoIP database")
  128. flag.IntVar(&maxRelaysReturned, "max-relays-returned", maxRelaysReturned, "Maximum number of relays returned for a normal endpoint query")
  129. flag.Parse()
  130. requests = make(chan request, requestQueueLen)
  131. geoip, err := geoip.NewGeoLite2CityProvider(context.Background(), geoipAccountID, geoipLicenseKey, os.TempDir())
  132. if err != nil {
  133. log.Fatalln("Failed to create GeoIP provider:", err)
  134. }
  135. go geoip.Serve(context.TODO())
  136. var listener net.Listener
  137. if permRelaysFile != "" {
  138. permanentRelays = loadRelays(permRelaysFile, geoip)
  139. }
  140. testCert = createTestCertificate()
  141. for range requestProcessors {
  142. go requestProcessor(geoip)
  143. }
  144. // Load relays from cache in the background.
  145. // Load them in a serial fashion to make sure any genuine requests
  146. // are not dropped.
  147. go func() {
  148. for _, relay := range loadRelays(knownRelaysFile, geoip) {
  149. resultChan := make(chan result)
  150. requests <- request{relay, resultChan, nil}
  151. result := <-resultChan
  152. if result.err != nil {
  153. relayTestsTotal.WithLabelValues("failed").Inc()
  154. } else {
  155. relayTestsTotal.WithLabelValues("success").Inc()
  156. }
  157. }
  158. // Run the stats refresher once the relays are loaded.
  159. statsRefresher(statsRefresh)
  160. }()
  161. if dir != "" {
  162. if debug {
  163. log.Println("Starting TLS listener on", listen)
  164. }
  165. certFile, keyFile := filepath.Join(dir, "http-cert.pem"), filepath.Join(dir, "http-key.pem")
  166. var cert tls.Certificate
  167. cert, err = tls.LoadX509KeyPair(certFile, keyFile)
  168. if err != nil {
  169. log.Fatalln("Failed to load HTTP X509 key pair:", err)
  170. }
  171. tlsCfg := &tls.Config{
  172. Certificates: []tls.Certificate{cert},
  173. MinVersion: tls.VersionTLS10, // No SSLv3
  174. ClientAuth: tls.RequestClientCert,
  175. CipherSuites: []uint16{
  176. // No RC4
  177. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  178. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  179. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  180. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  181. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  182. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  183. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  184. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  185. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  186. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  187. },
  188. }
  189. listener, err = tls.Listen(proto, listen, tlsCfg)
  190. } else {
  191. if debug {
  192. log.Println("Starting plain listener on", listen)
  193. }
  194. listener, err = net.Listen(proto, listen)
  195. }
  196. if err != nil {
  197. log.Fatalln("listen:", err)
  198. }
  199. if metricsListen != "" {
  200. mmux := http.NewServeMux()
  201. mmux.HandleFunc("/metrics", handleMetrics)
  202. go func() {
  203. if err := http.ListenAndServe(metricsListen, mmux); err != nil {
  204. log.Fatalln("HTTP serve metrics:", err)
  205. }
  206. }()
  207. }
  208. getMux := http.NewServeMux()
  209. getMux.HandleFunc("/", handleAssets)
  210. getMux.HandleFunc("/endpoint", withAPIMetrics(handleEndpointShort))
  211. getMux.HandleFunc("/endpoint/full", withAPIMetrics(handleEndpointFull))
  212. postMux := http.NewServeMux()
  213. postMux.HandleFunc("/endpoint", withAPIMetrics(handleRegister))
  214. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  215. switch r.Method {
  216. case http.MethodGet, http.MethodHead, http.MethodOptions:
  217. getMux.ServeHTTP(w, r)
  218. case http.MethodPost:
  219. postMux.ServeHTTP(w, r)
  220. default:
  221. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  222. }
  223. })
  224. srv := http.Server{
  225. Handler: handler,
  226. ReadTimeout: 10 * time.Second,
  227. }
  228. srv.SetKeepAlivesEnabled(false)
  229. err = srv.Serve(listener)
  230. if err != nil {
  231. log.Fatalln("serve:", err)
  232. }
  233. }
  234. func handleMetrics(w http.ResponseWriter, r *http.Request) {
  235. timer := prometheus.NewTimer(metricsRequestsSeconds)
  236. // Acquire the mutex just to make sure we're not caught mid-way stats collection
  237. mut.RLock()
  238. promhttp.Handler().ServeHTTP(w, r)
  239. mut.RUnlock()
  240. timer.ObserveDuration()
  241. }
  242. func handleAssets(w http.ResponseWriter, r *http.Request) {
  243. w.Header().Set("Cache-Control", "no-cache, must-revalidate")
  244. path := r.URL.Path[1:]
  245. if path == "" {
  246. path = "index.html"
  247. }
  248. as, ok := auto.Assets()[path]
  249. if !ok {
  250. w.WriteHeader(http.StatusNotFound)
  251. return
  252. }
  253. assets.Serve(w, r, as)
  254. }
  255. func withAPIMetrics(next http.HandlerFunc) http.HandlerFunc {
  256. return func(w http.ResponseWriter, r *http.Request) {
  257. timer := prometheus.NewTimer(apiRequestsSeconds.WithLabelValues(r.Method))
  258. w = NewLoggingResponseWriter(w)
  259. defer func() {
  260. timer.ObserveDuration()
  261. lw := w.(*loggingResponseWriter)
  262. apiRequestsTotal.WithLabelValues(r.Method, strconv.Itoa(lw.statusCode)).Inc()
  263. }()
  264. next(w, r)
  265. }
  266. }
  267. // handleEndpointFull returns the relay list with full metadata and
  268. // statistics. Large, and expensive.
  269. func handleEndpointFull(rw http.ResponseWriter, r *http.Request) {
  270. rw.Header().Set("Content-Type", "application/json; charset=utf-8")
  271. rw.Header().Set("Access-Control-Allow-Origin", "*")
  272. mut.RLock()
  273. relays := make([]*relay, len(permanentRelays)+len(knownRelays))
  274. n := copy(relays, permanentRelays)
  275. copy(relays[n:], knownRelays)
  276. mut.RUnlock()
  277. _ = json.NewEncoder(rw).Encode(map[string][]*relay{
  278. "relays": relays,
  279. })
  280. }
  281. // handleEndpointShort returns the relay list with only the URL.
  282. func handleEndpointShort(rw http.ResponseWriter, r *http.Request) {
  283. rw.Header().Set("Content-Type", "application/json; charset=utf-8")
  284. rw.Header().Set("Access-Control-Allow-Origin", "*")
  285. mut.RLock()
  286. relays := make([]relayShort, 0, len(permanentRelays)+len(knownRelays))
  287. for _, r := range append(permanentRelays, knownRelays...) {
  288. relays = append(relays, relayShort{URL: slimURL(r.URL)})
  289. }
  290. mut.RUnlock()
  291. if len(relays) > maxRelaysReturned {
  292. rand.Shuffle(relays)
  293. relays = relays[:maxRelaysReturned]
  294. }
  295. _ = json.NewEncoder(rw).Encode(map[string][]relayShort{
  296. "relays": relays,
  297. })
  298. }
  299. func handleRegister(w http.ResponseWriter, r *http.Request) {
  300. // Get the IP address of the client
  301. rhost := r.RemoteAddr
  302. if ipHeader != "" {
  303. hdr := r.Header.Get(ipHeader)
  304. fields := strings.Split(hdr, ",")
  305. if len(fields) > 0 {
  306. rhost = strings.TrimSpace(fields[len(fields)-1])
  307. }
  308. }
  309. if host, _, err := net.SplitHostPort(rhost); err == nil {
  310. rhost = host
  311. }
  312. // Check the black list. A client is blacklisted if their last 10
  313. // attempts to join have all failed. The "Unauthorized" status return
  314. // causes strelaysrv to cease attempting to join.
  315. if globalBlocklist.IsBlocked(rhost) {
  316. log.Println("Rejected blocked client", rhost)
  317. http.Error(w, "Too many errors", http.StatusUnauthorized)
  318. globalBlocklist.ClearErrors(rhost)
  319. return
  320. }
  321. var relayCert *x509.Certificate
  322. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  323. relayCert = r.TLS.PeerCertificates[0]
  324. log.Printf("Got TLS cert from relay server")
  325. }
  326. var newRelay relay
  327. err := json.NewDecoder(r.Body).Decode(&newRelay)
  328. r.Body.Close()
  329. if err != nil {
  330. if debug {
  331. log.Println("Failed to parse payload")
  332. }
  333. http.Error(w, err.Error(), http.StatusBadRequest)
  334. return
  335. }
  336. uri, err := url.Parse(newRelay.URL)
  337. if err != nil {
  338. if debug {
  339. log.Println("Failed to parse URI", newRelay.URL)
  340. }
  341. http.Error(w, err.Error(), http.StatusBadRequest)
  342. return
  343. }
  344. // Canonicalize the URL. In particular, parse and re-encode the query
  345. // string so that it's guaranteed to be valid.
  346. uri.RawQuery = uri.Query().Encode()
  347. newRelay.URL = uri.String()
  348. if relayCert != nil {
  349. advertisedId := uri.Query().Get("id")
  350. idFromCert := protocol.NewDeviceID(relayCert.Raw).String()
  351. if advertisedId != idFromCert {
  352. log.Println("Warning: Relay server requested to join with an ID different from the join request, rejecting")
  353. http.Error(w, "mismatched advertised id and join request cert", http.StatusBadRequest)
  354. return
  355. }
  356. }
  357. host, port, err := net.SplitHostPort(uri.Host)
  358. if err != nil {
  359. if debug {
  360. log.Println("Failed to split URI", newRelay.URL)
  361. }
  362. http.Error(w, err.Error(), http.StatusBadRequest)
  363. return
  364. }
  365. ip := net.ParseIP(host)
  366. // The client did not provide an IP address, use the IP address of the client.
  367. if ip == nil || ip.IsUnspecified() {
  368. uri.Host = net.JoinHostPort(rhost, port)
  369. newRelay.URL = uri.String()
  370. } else if host != rhost && relayCert == nil {
  371. if debug {
  372. log.Println("IP address advertised does not match client IP address", r.RemoteAddr, uri)
  373. }
  374. http.Error(w, fmt.Sprintf("IP advertised %s does not match client IP %s", host, rhost), http.StatusUnauthorized)
  375. return
  376. }
  377. newRelay.uri = uri
  378. for _, current := range permanentRelays {
  379. if current.uri.Host == newRelay.uri.Host {
  380. if debug {
  381. log.Println("Asked to add a relay", newRelay, "which exists in permanent list")
  382. }
  383. http.Error(w, "Invalid request", http.StatusBadRequest)
  384. return
  385. }
  386. }
  387. reschan := make(chan result)
  388. select {
  389. case requests <- request{&newRelay, reschan, prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("queue"))}:
  390. result := <-reschan
  391. if result.err != nil {
  392. log.Println("Join from", r.RemoteAddr, "failed:", result.err)
  393. globalBlocklist.AddError(rhost)
  394. relayTestsTotal.WithLabelValues("failed").Inc()
  395. http.Error(w, result.err.Error(), http.StatusBadRequest)
  396. return
  397. }
  398. log.Println("Join from", r.RemoteAddr, "succeeded")
  399. globalBlocklist.ClearErrors(rhost)
  400. relayTestsTotal.WithLabelValues("success").Inc()
  401. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  402. json.NewEncoder(w).Encode(map[string]time.Duration{
  403. "evictionIn": result.eviction,
  404. })
  405. default:
  406. relayTestsTotal.WithLabelValues("dropped").Inc()
  407. if debug {
  408. log.Println("Dropping request")
  409. }
  410. w.WriteHeader(httpStatusEnhanceYourCalm)
  411. }
  412. }
  413. func requestProcessor(geoip *geoip.Provider) {
  414. for request := range requests {
  415. if request.queueTimer != nil {
  416. request.queueTimer.ObserveDuration()
  417. }
  418. timer := prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("test"))
  419. handleRelayTest(request, geoip)
  420. timer.ObserveDuration()
  421. }
  422. }
  423. func handleRelayTest(request request, geoip *geoip.Provider) {
  424. if debug {
  425. log.Println("Request for", request.relay)
  426. }
  427. if err := client.TestRelay(context.TODO(), request.relay.uri, []tls.Certificate{testCert}, time.Second, 2*time.Second, 3); err != nil {
  428. if debug {
  429. log.Println("Test for relay", request.relay, "failed:", err)
  430. }
  431. request.result <- result{err, 0}
  432. return
  433. }
  434. stats := fetchStats(request.relay)
  435. location := getLocation(request.relay.uri.Host, geoip)
  436. mut.Lock()
  437. if stats != nil {
  438. updateMetrics(request.relay.uri.Host, *stats, location)
  439. }
  440. request.relay.Stats = stats
  441. request.relay.StatsRetrieved = time.Now().Truncate(time.Second)
  442. request.relay.Location = location
  443. timer, ok := evictionTimers[request.relay.uri.Host]
  444. if ok {
  445. if debug {
  446. log.Println("Stopping existing timer for", request.relay)
  447. }
  448. timer.Stop()
  449. }
  450. for i, current := range knownRelays {
  451. if current.uri.Host == request.relay.uri.Host {
  452. if debug {
  453. log.Println("Relay", request.relay, "already exists")
  454. }
  455. // Evict the old entry anyway, as configuration might have changed.
  456. last := len(knownRelays) - 1
  457. knownRelays[i] = knownRelays[last]
  458. knownRelays = knownRelays[:last]
  459. goto found
  460. }
  461. }
  462. if debug {
  463. log.Println("Adding new relay", request.relay)
  464. }
  465. found:
  466. knownRelays = append(knownRelays, request.relay)
  467. evictionTimers[request.relay.uri.Host] = time.AfterFunc(evictionTime, evict(request.relay))
  468. mut.Unlock()
  469. if err := saveRelays(knownRelaysFile, knownRelays); err != nil {
  470. log.Println("Failed to write known relays: " + err.Error())
  471. }
  472. request.result <- result{nil, evictionTime}
  473. }
  474. func evict(relay *relay) func() {
  475. return func() {
  476. mut.Lock()
  477. defer mut.Unlock()
  478. if debug {
  479. log.Println("Evicting", relay)
  480. }
  481. for i, current := range knownRelays {
  482. if current.uri.Host == relay.uri.Host {
  483. if debug {
  484. log.Println("Evicted", relay)
  485. }
  486. last := len(knownRelays) - 1
  487. knownRelays[i] = knownRelays[last]
  488. knownRelays = knownRelays[:last]
  489. deleteMetrics(current.uri.Host)
  490. }
  491. }
  492. delete(evictionTimers, relay.uri.Host)
  493. }
  494. }
  495. func loadRelays(file string, geoip *geoip.Provider) []*relay {
  496. content, err := os.ReadFile(file)
  497. if err != nil {
  498. log.Println("Failed to load relays: " + err.Error())
  499. return nil
  500. }
  501. var relays []*relay
  502. for _, line := range strings.Split(string(content), "\n") {
  503. if line == "" {
  504. continue
  505. }
  506. uri, err := url.Parse(line)
  507. if err != nil {
  508. if debug {
  509. log.Println("Skipping relay", line, "due to parse error", err)
  510. }
  511. continue
  512. }
  513. relays = append(relays, &relay{
  514. URL: line,
  515. Location: getLocation(uri.Host, geoip),
  516. uri: uri,
  517. })
  518. if debug {
  519. log.Println("Adding relay", line)
  520. }
  521. }
  522. return relays
  523. }
  524. func saveRelays(file string, relays []*relay) error {
  525. var content string
  526. for _, relay := range relays {
  527. content += relay.uri.String() + "\n"
  528. }
  529. return os.WriteFile(file, []byte(content), 0o777)
  530. }
  531. func createTestCertificate() tls.Certificate {
  532. tmpDir, err := os.MkdirTemp("", "relaypoolsrv")
  533. if err != nil {
  534. log.Fatal(err)
  535. }
  536. certFile, keyFile := filepath.Join(tmpDir, "cert.pem"), filepath.Join(tmpDir, "key.pem")
  537. cert, err := tlsutil.NewCertificate(certFile, keyFile, "relaypoolsrv", 20*365, false)
  538. if err != nil {
  539. log.Fatalln("Failed to create test X509 key pair:", err)
  540. }
  541. return cert
  542. }
  543. func getLocation(host string, geoip *geoip.Provider) location {
  544. timer := prometheus.NewTimer(locationLookupSeconds)
  545. defer timer.ObserveDuration()
  546. addr, err := net.ResolveTCPAddr("tcp", host)
  547. if err != nil {
  548. return location{}
  549. }
  550. city, err := geoip.City(addr.IP)
  551. if err != nil {
  552. return location{}
  553. }
  554. return location{
  555. Longitude: city.Location.Longitude,
  556. Latitude: city.Location.Latitude,
  557. City: city.City.Names["en"],
  558. Country: city.Country.IsoCode,
  559. Continent: city.Continent.Code,
  560. }
  561. }
  562. type loggingResponseWriter struct {
  563. http.ResponseWriter
  564. statusCode int
  565. }
  566. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  567. return &loggingResponseWriter{w, http.StatusOK}
  568. }
  569. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  570. lrw.statusCode = code
  571. lrw.ResponseWriter.WriteHeader(code)
  572. }
  573. type errorTracker struct {
  574. errors *lru.TwoQueueCache[string, *errorCounter]
  575. }
  576. type errorCounter struct {
  577. count atomic.Int32
  578. }
  579. func newErrorTracker(size int) *errorTracker {
  580. cache, err := lru.New2Q[string, *errorCounter](size)
  581. if err != nil {
  582. panic(err)
  583. }
  584. return &errorTracker{
  585. errors: cache,
  586. }
  587. }
  588. func (b *errorTracker) AddError(host string) {
  589. entry, ok := b.errors.Get(host)
  590. if !ok {
  591. entry = &errorCounter{}
  592. b.errors.Add(host, entry)
  593. }
  594. c := entry.count.Add(1)
  595. log.Printf("Error count for %s is now %d", host, c)
  596. }
  597. func (b *errorTracker) ClearErrors(host string) {
  598. b.errors.Remove(host)
  599. }
  600. func (b *errorTracker) IsBlocked(host string) bool {
  601. if be, ok := b.errors.Get(host); ok {
  602. return be.count.Load() > 10
  603. }
  604. return false
  605. }
  606. func slimURL(u string) string {
  607. p, err := url.Parse(u)
  608. if err != nil {
  609. return u
  610. }
  611. newQuery := url.Values{}
  612. if id := p.Query().Get("id"); id != "" {
  613. newQuery.Set("id", id)
  614. }
  615. p.RawQuery = newQuery.Encode()
  616. return p.String()
  617. }