main.go 19 KB

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