main.go 18 KB

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