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