main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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. getMut = sync.NewRWMutex()
  106. getLRUCache *lru.Cache
  107. postMut = sync.NewRWMutex()
  108. postLRUCache *lru.Cache
  109. requests = make(chan request, 10)
  110. mut = sync.NewRWMutex()
  111. knownRelays = make([]*relay, 0)
  112. permanentRelays = make([]*relay, 0)
  113. evictionTimers = make(map[string]*time.Timer)
  114. )
  115. const (
  116. httpStatusEnhanceYourCalm = 429
  117. )
  118. func main() {
  119. flag.StringVar(&listen, "listen", listen, "Listen address")
  120. flag.StringVar(&dir, "keys", dir, "Directory where http-cert.pem and http-key.pem is stored for TLS listening")
  121. flag.BoolVar(&debug, "debug", debug, "Enable debug output")
  122. flag.DurationVar(&evictionTime, "eviction", evictionTime, "After how long the relay is evicted")
  123. flag.IntVar(&getLRUSize, "get-limit-cache", getLRUSize, "Get request limiter cache size")
  124. flag.IntVar(&getLimitAvg, "get-limit-avg", getLimitAvg, "Allowed average get request rate, per 10 s")
  125. flag.IntVar(&getLimitBurst, "get-limit-burst", getLimitBurst, "Allowed burst get requests")
  126. flag.IntVar(&postLRUSize, "post-limit-cache", postLRUSize, "Post request limiter cache size")
  127. flag.IntVar(&postLimitAvg, "post-limit-avg", postLimitAvg, "Allowed average post request rate, per minute")
  128. flag.IntVar(&postLimitBurst, "post-limit-burst", postLimitBurst, "Allowed burst post requests")
  129. flag.StringVar(&permRelaysFile, "perm-relays", "", "Path to list of permanent relays")
  130. flag.StringVar(&ipHeader, "ip-header", "", "Name of header which holds clients ip:port. Only meaningful when running behind a reverse proxy.")
  131. flag.StringVar(&geoipPath, "geoip", "GeoLite2-City.mmdb", "Path to GeoLite2-City database")
  132. flag.StringVar(&proto, "protocol", "tcp", "Protocol used for listening. 'tcp' for IPv4 and IPv6, 'tcp4' for IPv4, 'tcp6' for IPv6")
  133. flag.DurationVar(&statsRefresh, "stats-refresh", statsRefresh, "Interval at which to refresh relay stats")
  134. flag.Parse()
  135. getLimit = 10 * time.Second / time.Duration(getLimitAvg)
  136. postLimit = time.Minute / time.Duration(postLimitAvg)
  137. getLRUCache = lru.New(getLRUSize)
  138. postLRUCache = lru.New(postLRUSize)
  139. var listener net.Listener
  140. var err error
  141. if permRelaysFile != "" {
  142. permanentRelays = loadRelays(permRelaysFile)
  143. }
  144. testCert = createTestCertificate()
  145. go requestProcessor()
  146. // Load relays from cache in the background.
  147. // Load them in a serial fashion to make sure any genuine requests
  148. // are not dropped.
  149. go func() {
  150. for _, relay := range loadRelays(knownRelaysFile) {
  151. resultChan := make(chan result)
  152. requests <- request{relay, resultChan, nil}
  153. result := <-resultChan
  154. if result.err != nil {
  155. relayTestsTotal.WithLabelValues("failed").Inc()
  156. } else {
  157. relayTestsTotal.WithLabelValues("success").Inc()
  158. }
  159. }
  160. // Run the the stats refresher once the relays are loaded.
  161. statsRefresher(statsRefresh)
  162. }()
  163. if dir != "" {
  164. if debug {
  165. log.Println("Starting TLS listener on", listen)
  166. }
  167. certFile, keyFile := filepath.Join(dir, "http-cert.pem"), filepath.Join(dir, "http-key.pem")
  168. var cert tls.Certificate
  169. cert, err = tls.LoadX509KeyPair(certFile, keyFile)
  170. if err != nil {
  171. log.Fatalln("Failed to load HTTP X509 key pair:", err)
  172. }
  173. tlsCfg := &tls.Config{
  174. Certificates: []tls.Certificate{cert},
  175. MinVersion: tls.VersionTLS10, // No SSLv3
  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. handler := http.NewServeMux()
  201. handler.HandleFunc("/", handleAssets)
  202. handler.HandleFunc("/endpoint", handleRequest)
  203. handler.HandleFunc("/metrics", handleMetrics)
  204. srv := http.Server{
  205. Handler: handler,
  206. ReadTimeout: 10 * time.Second,
  207. }
  208. err = srv.Serve(listener)
  209. if err != nil {
  210. log.Fatalln("serve:", err)
  211. }
  212. }
  213. func handleMetrics(w http.ResponseWriter, r *http.Request) {
  214. timer := prometheus.NewTimer(metricsRequestsSeconds)
  215. // Acquire the mutex just to make sure we're not caught mid-way stats collection
  216. mut.RLock()
  217. promhttp.Handler().ServeHTTP(w, r)
  218. mut.RUnlock()
  219. timer.ObserveDuration()
  220. }
  221. func handleAssets(w http.ResponseWriter, r *http.Request) {
  222. w.Header().Set("Cache-Control", "no-cache, must-revalidate")
  223. assets := auto.Assets()
  224. path := r.URL.Path[1:]
  225. if path == "" {
  226. path = "index.html"
  227. }
  228. bs, ok := assets[path]
  229. if !ok {
  230. w.WriteHeader(http.StatusNotFound)
  231. return
  232. }
  233. etag := fmt.Sprintf("%d", auto.Generated)
  234. modified := time.Unix(auto.Generated, 0).UTC()
  235. w.Header().Set("Last-Modified", modified.Format(http.TimeFormat))
  236. w.Header().Set("Etag", etag)
  237. mtype := mimeTypeForFile(path)
  238. if len(mtype) != 0 {
  239. w.Header().Set("Content-Type", mtype)
  240. }
  241. if t, err := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); err == nil && modified.Add(time.Second).After(t) {
  242. w.WriteHeader(http.StatusNotModified)
  243. return
  244. }
  245. if match := r.Header.Get("If-None-Match"); match != "" {
  246. if strings.Contains(match, etag) {
  247. w.WriteHeader(http.StatusNotModified)
  248. return
  249. }
  250. }
  251. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  252. w.Header().Set("Content-Encoding", "gzip")
  253. } else {
  254. // ungzip if browser not send gzip accepted header
  255. var gr *gzip.Reader
  256. gr, _ = gzip.NewReader(bytes.NewReader(bs))
  257. bs, _ = ioutil.ReadAll(gr)
  258. gr.Close()
  259. }
  260. w.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs)))
  261. w.Write(bs)
  262. }
  263. func mimeTypeForFile(file string) string {
  264. // We use a built in table of the common types since the system
  265. // TypeByExtension might be unreliable. But if we don't know, we delegate
  266. // to the system.
  267. ext := filepath.Ext(file)
  268. switch ext {
  269. case ".htm", ".html":
  270. return "text/html"
  271. case ".css":
  272. return "text/css"
  273. case ".js":
  274. return "application/javascript"
  275. case ".json":
  276. return "application/json"
  277. case ".png":
  278. return "image/png"
  279. case ".ttf":
  280. return "application/x-font-ttf"
  281. case ".woff":
  282. return "application/x-font-woff"
  283. case ".svg":
  284. return "image/svg+xml"
  285. default:
  286. return mime.TypeByExtension(ext)
  287. }
  288. }
  289. func handleRequest(w http.ResponseWriter, r *http.Request) {
  290. timer := prometheus.NewTimer(apiRequestsSeconds.WithLabelValues(r.Method))
  291. lw := NewLoggingResponseWriter(w)
  292. defer func() {
  293. timer.ObserveDuration()
  294. apiRequestsTotal.WithLabelValues(r.Method, strconv.Itoa(lw.statusCode)).Inc()
  295. }()
  296. if ipHeader != "" {
  297. r.RemoteAddr = r.Header.Get(ipHeader)
  298. }
  299. w.Header().Set("Access-Control-Allow-Origin", "*")
  300. switch r.Method {
  301. case "GET":
  302. if limit(r.RemoteAddr, getLRUCache, getMut, getLimit, getLimitBurst) {
  303. w.WriteHeader(httpStatusEnhanceYourCalm)
  304. return
  305. }
  306. handleGetRequest(w, r)
  307. case "POST":
  308. if limit(r.RemoteAddr, postLRUCache, postMut, postLimit, postLimitBurst) {
  309. w.WriteHeader(httpStatusEnhanceYourCalm)
  310. return
  311. }
  312. handlePostRequest(w, r)
  313. default:
  314. if debug {
  315. log.Println("Unhandled HTTP method", r.Method)
  316. }
  317. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  318. }
  319. }
  320. func handleGetRequest(rw http.ResponseWriter, r *http.Request) {
  321. rw.Header().Set("Content-Type", "application/json; charset=utf-8")
  322. mut.RLock()
  323. relays := append(permanentRelays, knownRelays...)
  324. mut.RUnlock()
  325. // Shuffle
  326. rand.Shuffle(relays)
  327. w := io.Writer(rw)
  328. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  329. rw.Header().Set("Content-Encoding", "gzip")
  330. gw := gzip.NewWriter(rw)
  331. defer gw.Close()
  332. w = gw
  333. }
  334. _ = json.NewEncoder(w).Encode(map[string][]*relay{
  335. "relays": relays,
  336. })
  337. }
  338. func handlePostRequest(w http.ResponseWriter, r *http.Request) {
  339. var newRelay relay
  340. err := json.NewDecoder(r.Body).Decode(&newRelay)
  341. r.Body.Close()
  342. if err != nil {
  343. if debug {
  344. log.Println("Failed to parse payload")
  345. }
  346. http.Error(w, err.Error(), 500)
  347. return
  348. }
  349. uri, err := url.Parse(newRelay.URL)
  350. if err != nil {
  351. if debug {
  352. log.Println("Failed to parse URI", newRelay.URL)
  353. }
  354. http.Error(w, err.Error(), 500)
  355. return
  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(), 500)
  363. return
  364. }
  365. // Get the IP address of the client
  366. rhost := r.RemoteAddr
  367. if host, _, err := net.SplitHostPort(rhost); err == nil {
  368. rhost = host
  369. }
  370. ip := net.ParseIP(host)
  371. // The client did not provide an IP address, use the IP address of the client.
  372. if ip == nil || ip.IsUnspecified() {
  373. uri.Host = net.JoinHostPort(rhost, port)
  374. newRelay.URL = uri.String()
  375. } else if host != rhost {
  376. if debug {
  377. log.Println("IP address advertised does not match client IP address", r.RemoteAddr, uri)
  378. }
  379. http.Error(w, fmt.Sprintf("IP advertised %s does not match client IP %s", host, rhost), http.StatusUnauthorized)
  380. return
  381. }
  382. newRelay.uri = uri
  383. for _, current := range permanentRelays {
  384. if current.uri.Host == newRelay.uri.Host {
  385. if debug {
  386. log.Println("Asked to add a relay", newRelay, "which exists in permanent list")
  387. }
  388. http.Error(w, "Invalid request", http.StatusBadRequest)
  389. return
  390. }
  391. }
  392. reschan := make(chan result)
  393. select {
  394. case requests <- request{&newRelay, reschan, prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("queue"))}:
  395. result := <-reschan
  396. if result.err != nil {
  397. relayTestsTotal.WithLabelValues("failed").Inc()
  398. http.Error(w, result.err.Error(), http.StatusBadRequest)
  399. return
  400. }
  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() {
  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)
  421. timer.ObserveDuration()
  422. }
  423. }
  424. func handleRelayTest(request request) {
  425. if debug {
  426. log.Println("Request for", request.relay)
  427. }
  428. if !client.TestRelay(context.TODO(), request.relay.uri, []tls.Certificate{testCert}, time.Second, 2*time.Second, 3) {
  429. if debug {
  430. log.Println("Test for relay", request.relay, "failed")
  431. }
  432. request.result <- result{fmt.Errorf("connection test failed"), 0}
  433. return
  434. }
  435. stats := fetchStats(request.relay)
  436. location := getLocation(request.relay.uri.Host)
  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()
  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 limit(addr string, cache *lru.Cache, lock sync.RWMutex, intv time.Duration, burst int) bool {
  497. if host, _, err := net.SplitHostPort(addr); err == nil {
  498. addr = host
  499. }
  500. lock.RLock()
  501. bkt, ok := cache.Get(addr)
  502. lock.RUnlock()
  503. if ok {
  504. bkt := bkt.(*rate.Limiter)
  505. if !bkt.Allow() {
  506. // Rate limit
  507. return true
  508. }
  509. } else {
  510. lock.Lock()
  511. cache.Add(addr, rate.NewLimiter(rate.Every(intv), burst))
  512. lock.Unlock()
  513. }
  514. return false
  515. }
  516. func loadRelays(file string) []*relay {
  517. content, err := ioutil.ReadFile(file)
  518. if err != nil {
  519. log.Println("Failed to load relays: " + err.Error())
  520. return nil
  521. }
  522. var relays []*relay
  523. for _, line := range strings.Split(string(content), "\n") {
  524. if len(line) == 0 {
  525. continue
  526. }
  527. uri, err := url.Parse(line)
  528. if err != nil {
  529. if debug {
  530. log.Println("Skipping relay", line, "due to parse error", err)
  531. }
  532. continue
  533. }
  534. relays = append(relays, &relay{
  535. URL: line,
  536. Location: getLocation(uri.Host),
  537. uri: uri,
  538. })
  539. if debug {
  540. log.Println("Adding relay", line)
  541. }
  542. }
  543. return relays
  544. }
  545. func saveRelays(file string, relays []*relay) error {
  546. var content string
  547. for _, relay := range relays {
  548. content += relay.uri.String() + "\n"
  549. }
  550. return ioutil.WriteFile(file, []byte(content), 0777)
  551. }
  552. func createTestCertificate() tls.Certificate {
  553. tmpDir, err := ioutil.TempDir("", "relaypoolsrv")
  554. if err != nil {
  555. log.Fatal(err)
  556. }
  557. certFile, keyFile := filepath.Join(tmpDir, "cert.pem"), filepath.Join(tmpDir, "key.pem")
  558. cert, err := tlsutil.NewCertificate(certFile, keyFile, "relaypoolsrv", 20*365)
  559. if err != nil {
  560. log.Fatalln("Failed to create test X509 key pair:", err)
  561. }
  562. return cert
  563. }
  564. func getLocation(host string) location {
  565. timer := prometheus.NewTimer(locationLookupSeconds)
  566. defer timer.ObserveDuration()
  567. db, err := geoip2.Open(geoipPath)
  568. if err != nil {
  569. return location{}
  570. }
  571. defer db.Close()
  572. addr, err := net.ResolveTCPAddr("tcp", host)
  573. if err != nil {
  574. return location{}
  575. }
  576. city, err := db.City(addr.IP)
  577. if err != nil {
  578. return location{}
  579. }
  580. return location{
  581. Longitude: city.Location.Longitude,
  582. Latitude: city.Location.Latitude,
  583. City: city.City.Names["en"],
  584. Country: city.Country.IsoCode,
  585. Continent: city.Continent.Code,
  586. }
  587. }
  588. type loggingResponseWriter struct {
  589. http.ResponseWriter
  590. statusCode int
  591. }
  592. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  593. return &loggingResponseWriter{w, http.StatusOK}
  594. }
  595. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  596. lrw.statusCode = code
  597. lrw.ResponseWriter.WriteHeader(code)
  598. }