main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. "crypto/tls"
  8. "encoding/json"
  9. "flag"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "math/rand"
  14. "mime"
  15. "net"
  16. "net/http"
  17. "net/url"
  18. "path/filepath"
  19. "strings"
  20. "time"
  21. "github.com/golang/groupcache/lru"
  22. "github.com/oschwald/geoip2-golang"
  23. "github.com/syncthing/syncthing/cmd/strelaypoolsrv/auto"
  24. "github.com/syncthing/syncthing/lib/relay/client"
  25. "github.com/syncthing/syncthing/lib/sync"
  26. "github.com/syncthing/syncthing/lib/tlsutil"
  27. "golang.org/x/time/rate"
  28. )
  29. type location struct {
  30. Latitude float64 `json:"latitude"`
  31. Longitude float64 `json:"longitude"`
  32. }
  33. type relay struct {
  34. URL string `json:"url"`
  35. Location location `json:"location"`
  36. uri *url.URL
  37. }
  38. func (r relay) String() string {
  39. return r.URL
  40. }
  41. type request struct {
  42. relay relay
  43. uri *url.URL
  44. result chan result
  45. }
  46. type result struct {
  47. err error
  48. eviction time.Duration
  49. }
  50. var (
  51. testCert tls.Certificate
  52. listen = ":80"
  53. dir string
  54. evictionTime = time.Hour
  55. debug bool
  56. getLRUSize = 10 << 10
  57. getLimitBurst = 10
  58. getLimitAvg = 1
  59. postLRUSize = 1 << 10
  60. postLimitBurst = 2
  61. postLimitAvg = 1
  62. getLimit time.Duration
  63. postLimit time.Duration
  64. permRelaysFile string
  65. ipHeader string
  66. geoipPath string
  67. proto string
  68. getMut = sync.NewRWMutex()
  69. getLRUCache *lru.Cache
  70. postMut = sync.NewRWMutex()
  71. postLRUCache *lru.Cache
  72. requests = make(chan request, 10)
  73. mut = sync.NewRWMutex()
  74. knownRelays = make([]relay, 0)
  75. permanentRelays = make([]relay, 0)
  76. evictionTimers = make(map[string]*time.Timer)
  77. )
  78. const (
  79. httpStatusEnhanceYourCalm = 429
  80. )
  81. func main() {
  82. flag.StringVar(&listen, "listen", listen, "Listen address")
  83. flag.StringVar(&dir, "keys", dir, "Directory where http-cert.pem and http-key.pem is stored for TLS listening")
  84. flag.BoolVar(&debug, "debug", debug, "Enable debug output")
  85. flag.DurationVar(&evictionTime, "eviction", evictionTime, "After how long the relay is evicted")
  86. flag.IntVar(&getLRUSize, "get-limit-cache", getLRUSize, "Get request limiter cache size")
  87. flag.IntVar(&getLimitAvg, "get-limit-avg", 2, "Allowed average get request rate, per 10 s")
  88. flag.IntVar(&getLimitBurst, "get-limit-burst", getLimitBurst, "Allowed burst get requests")
  89. flag.IntVar(&postLRUSize, "post-limit-cache", postLRUSize, "Post request limiter cache size")
  90. flag.IntVar(&postLimitAvg, "post-limit-avg", 2, "Allowed average post request rate, per minute")
  91. flag.IntVar(&postLimitBurst, "post-limit-burst", postLimitBurst, "Allowed burst post requests")
  92. flag.StringVar(&permRelaysFile, "perm-relays", "", "Path to list of permanent relays")
  93. flag.StringVar(&ipHeader, "ip-header", "", "Name of header which holds clients ip:port. Only meaningful when running behind a reverse proxy.")
  94. flag.StringVar(&geoipPath, "geoip", "GeoLite2-City.mmdb", "Path to GeoLite2-City database")
  95. flag.StringVar(&proto, "protocol", "tcp", "Protocol used for listening. 'tcp' for IPv4 and IPv6, 'tcp4' for IPv4, 'tcp6' for IPv6")
  96. flag.Parse()
  97. getLimit = 10 * time.Second / time.Duration(getLimitAvg)
  98. postLimit = time.Minute / time.Duration(postLimitAvg)
  99. getLRUCache = lru.New(getLRUSize)
  100. postLRUCache = lru.New(postLRUSize)
  101. var listener net.Listener
  102. var err error
  103. if permRelaysFile != "" {
  104. loadPermanentRelays(permRelaysFile)
  105. }
  106. testCert = createTestCertificate()
  107. go requestProcessor()
  108. if dir != "" {
  109. if debug {
  110. log.Println("Starting TLS listener on", listen)
  111. }
  112. certFile, keyFile := filepath.Join(dir, "http-cert.pem"), filepath.Join(dir, "http-key.pem")
  113. var cert tls.Certificate
  114. cert, err = tls.LoadX509KeyPair(certFile, keyFile)
  115. if err != nil {
  116. log.Fatalln("Failed to load HTTP X509 key pair:", err)
  117. }
  118. tlsCfg := &tls.Config{
  119. Certificates: []tls.Certificate{cert},
  120. MinVersion: tls.VersionTLS10, // No SSLv3
  121. CipherSuites: []uint16{
  122. // No RC4
  123. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  124. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  125. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  126. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  127. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  128. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  129. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  130. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  131. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  132. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  133. },
  134. }
  135. listener, err = tls.Listen(proto, listen, tlsCfg)
  136. } else {
  137. if debug {
  138. log.Println("Starting plain listener on", listen)
  139. }
  140. listener, err = net.Listen(proto, listen)
  141. }
  142. if err != nil {
  143. log.Fatalln("listen:", err)
  144. }
  145. handler := http.NewServeMux()
  146. handler.HandleFunc("/", handleAssets)
  147. handler.HandleFunc("/endpoint", handleRequest)
  148. srv := http.Server{
  149. Handler: handler,
  150. ReadTimeout: 10 * time.Second,
  151. }
  152. err = srv.Serve(listener)
  153. if err != nil {
  154. log.Fatalln("serve:", err)
  155. }
  156. }
  157. func handleAssets(w http.ResponseWriter, r *http.Request) {
  158. assets := auto.Assets()
  159. path := r.URL.Path[1:]
  160. if path == "" {
  161. path = "index.html"
  162. }
  163. bs, ok := assets[path]
  164. if !ok {
  165. w.WriteHeader(http.StatusNotFound)
  166. return
  167. }
  168. mtype := mimeTypeForFile(path)
  169. if len(mtype) != 0 {
  170. w.Header().Set("Content-Type", mtype)
  171. }
  172. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  173. w.Header().Set("Content-Encoding", "gzip")
  174. } else {
  175. // ungzip if browser not send gzip accepted header
  176. var gr *gzip.Reader
  177. gr, _ = gzip.NewReader(bytes.NewReader(bs))
  178. bs, _ = ioutil.ReadAll(gr)
  179. gr.Close()
  180. }
  181. w.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs)))
  182. w.Write(bs)
  183. }
  184. func mimeTypeForFile(file string) string {
  185. // We use a built in table of the common types since the system
  186. // TypeByExtension might be unreliable. But if we don't know, we delegate
  187. // to the system.
  188. ext := filepath.Ext(file)
  189. switch ext {
  190. case ".htm", ".html":
  191. return "text/html"
  192. case ".css":
  193. return "text/css"
  194. case ".js":
  195. return "application/javascript"
  196. case ".json":
  197. return "application/json"
  198. case ".png":
  199. return "image/png"
  200. case ".ttf":
  201. return "application/x-font-ttf"
  202. case ".woff":
  203. return "application/x-font-woff"
  204. case ".svg":
  205. return "image/svg+xml"
  206. default:
  207. return mime.TypeByExtension(ext)
  208. }
  209. }
  210. func handleRequest(w http.ResponseWriter, r *http.Request) {
  211. if ipHeader != "" {
  212. r.RemoteAddr = r.Header.Get(ipHeader)
  213. }
  214. w.Header().Set("Access-Control-Allow-Origin", "*")
  215. switch r.Method {
  216. case "GET":
  217. if limit(r.RemoteAddr, getLRUCache, getMut, getLimit, getLimitBurst) {
  218. w.WriteHeader(429)
  219. return
  220. }
  221. handleGetRequest(w, r)
  222. case "POST":
  223. if limit(r.RemoteAddr, postLRUCache, postMut, postLimit, postLimitBurst) {
  224. w.WriteHeader(429)
  225. return
  226. }
  227. handlePostRequest(w, r)
  228. default:
  229. if debug {
  230. log.Println("Unhandled HTTP method", r.Method)
  231. }
  232. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  233. }
  234. }
  235. func handleGetRequest(w http.ResponseWriter, r *http.Request) {
  236. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  237. mut.RLock()
  238. relays := append(permanentRelays, knownRelays...)
  239. mut.RUnlock()
  240. // Shuffle
  241. for i := range relays {
  242. j := rand.Intn(i + 1)
  243. relays[i], relays[j] = relays[j], relays[i]
  244. }
  245. json.NewEncoder(w).Encode(map[string][]relay{
  246. "relays": relays,
  247. })
  248. }
  249. func handlePostRequest(w http.ResponseWriter, r *http.Request) {
  250. var newRelay relay
  251. err := json.NewDecoder(r.Body).Decode(&newRelay)
  252. r.Body.Close()
  253. if err != nil {
  254. if debug {
  255. log.Println("Failed to parse payload")
  256. }
  257. http.Error(w, err.Error(), 500)
  258. return
  259. }
  260. uri, err := url.Parse(newRelay.URL)
  261. if err != nil {
  262. if debug {
  263. log.Println("Failed to parse URI", newRelay.URL)
  264. }
  265. http.Error(w, err.Error(), 500)
  266. return
  267. }
  268. host, port, err := net.SplitHostPort(uri.Host)
  269. if err != nil {
  270. if debug {
  271. log.Println("Failed to split URI", newRelay.URL)
  272. }
  273. http.Error(w, err.Error(), 500)
  274. return
  275. }
  276. // Get the IP address of the client
  277. rhost, _, err := net.SplitHostPort(r.RemoteAddr)
  278. if err != nil {
  279. if debug {
  280. log.Println("Failed to split remote address", r.RemoteAddr)
  281. }
  282. http.Error(w, err.Error(), 500)
  283. return
  284. }
  285. ip := net.ParseIP(host)
  286. // The client did not provide an IP address, use the IP address of the client.
  287. if ip == nil || ip.IsUnspecified() {
  288. uri.Host = net.JoinHostPort(rhost, port)
  289. newRelay.URL = uri.String()
  290. } else if host != rhost {
  291. if debug {
  292. log.Println("IP address advertised does not match client IP address", r.RemoteAddr, uri)
  293. }
  294. http.Error(w, "IP address does not match client IP", http.StatusUnauthorized)
  295. return
  296. }
  297. newRelay.uri = uri
  298. newRelay.Location = getLocation(uri.Host)
  299. for _, current := range permanentRelays {
  300. if current.uri.Host == newRelay.uri.Host {
  301. if debug {
  302. log.Println("Asked to add a relay", newRelay, "which exists in permanent list")
  303. }
  304. http.Error(w, "Invalid request", http.StatusBadRequest)
  305. return
  306. }
  307. }
  308. reschan := make(chan result)
  309. select {
  310. case requests <- request{newRelay, uri, reschan}:
  311. result := <-reschan
  312. if result.err != nil {
  313. http.Error(w, result.err.Error(), http.StatusBadRequest)
  314. return
  315. }
  316. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  317. json.NewEncoder(w).Encode(map[string]time.Duration{
  318. "evictionIn": result.eviction,
  319. })
  320. default:
  321. if debug {
  322. log.Println("Dropping request")
  323. }
  324. w.WriteHeader(httpStatusEnhanceYourCalm)
  325. }
  326. }
  327. func requestProcessor() {
  328. for request := range requests {
  329. if debug {
  330. log.Println("Request for", request.relay)
  331. }
  332. if !client.TestRelay(request.uri, []tls.Certificate{testCert}, time.Second, 2*time.Second, 3) {
  333. if debug {
  334. log.Println("Test for relay", request.relay, "failed")
  335. }
  336. request.result <- result{fmt.Errorf("connection test failed"), 0}
  337. continue
  338. }
  339. mut.Lock()
  340. timer, ok := evictionTimers[request.relay.uri.Host]
  341. if ok {
  342. if debug {
  343. log.Println("Stopping existing timer for", request.relay)
  344. }
  345. timer.Stop()
  346. }
  347. for i, current := range knownRelays {
  348. if current.uri.Host == request.relay.uri.Host {
  349. if debug {
  350. log.Println("Relay", request.relay, "already exists")
  351. }
  352. // Evict the old entry anyway, as configuration might have changed.
  353. last := len(knownRelays) - 1
  354. knownRelays[i] = knownRelays[last]
  355. knownRelays = knownRelays[:last]
  356. goto found
  357. }
  358. }
  359. if debug {
  360. log.Println("Adding new relay", request.relay)
  361. }
  362. found:
  363. knownRelays = append(knownRelays, request.relay)
  364. evictionTimers[request.relay.uri.Host] = time.AfterFunc(evictionTime, evict(request.relay))
  365. mut.Unlock()
  366. request.result <- result{nil, evictionTime}
  367. }
  368. }
  369. func evict(relay relay) func() {
  370. return func() {
  371. mut.Lock()
  372. defer mut.Unlock()
  373. if debug {
  374. log.Println("Evicting", relay)
  375. }
  376. for i, current := range knownRelays {
  377. if current.uri.Host == relay.uri.Host {
  378. if debug {
  379. log.Println("Evicted", relay)
  380. }
  381. last := len(knownRelays) - 1
  382. knownRelays[i] = knownRelays[last]
  383. knownRelays = knownRelays[:last]
  384. }
  385. }
  386. delete(evictionTimers, relay.uri.Host)
  387. }
  388. }
  389. func limit(addr string, cache *lru.Cache, lock sync.RWMutex, intv time.Duration, burst int) bool {
  390. host, _, err := net.SplitHostPort(addr)
  391. if err != nil {
  392. return false
  393. }
  394. lock.RLock()
  395. bkt, ok := cache.Get(host)
  396. lock.RUnlock()
  397. if ok {
  398. bkt := bkt.(*rate.Limiter)
  399. if !bkt.Allow() {
  400. // Rate limit
  401. return true
  402. }
  403. } else {
  404. lock.Lock()
  405. cache.Add(host, rate.NewLimiter(rate.Every(intv), burst))
  406. lock.Unlock()
  407. }
  408. return false
  409. }
  410. func loadPermanentRelays(file string) {
  411. content, err := ioutil.ReadFile(file)
  412. if err != nil {
  413. log.Fatal(err)
  414. }
  415. for _, line := range strings.Split(string(content), "\n") {
  416. if len(line) == 0 {
  417. continue
  418. }
  419. uri, err := url.Parse(line)
  420. if err != nil {
  421. if debug {
  422. log.Println("Skipping permanent relay", line, "due to parse error", err)
  423. }
  424. continue
  425. }
  426. permanentRelays = append(permanentRelays, relay{
  427. URL: line,
  428. Location: getLocation(uri.Host),
  429. uri: uri,
  430. })
  431. if debug {
  432. log.Println("Adding permanent relay", line)
  433. }
  434. }
  435. }
  436. func createTestCertificate() tls.Certificate {
  437. tmpDir, err := ioutil.TempDir("", "relaypoolsrv")
  438. if err != nil {
  439. log.Fatal(err)
  440. }
  441. certFile, keyFile := filepath.Join(tmpDir, "cert.pem"), filepath.Join(tmpDir, "key.pem")
  442. cert, err := tlsutil.NewCertificate(certFile, keyFile, "relaypoolsrv", 3072)
  443. if err != nil {
  444. log.Fatalln("Failed to create test X509 key pair:", err)
  445. }
  446. return cert
  447. }
  448. func getLocation(host string) location {
  449. db, err := geoip2.Open(geoipPath)
  450. if err != nil {
  451. return location{}
  452. }
  453. defer db.Close()
  454. addr, err := net.ResolveTCPAddr("tcp", host)
  455. if err != nil {
  456. return location{}
  457. }
  458. city, err := db.City(addr.IP)
  459. if err != nil {
  460. return location{}
  461. }
  462. return location{
  463. Latitude: city.Location.Latitude,
  464. Longitude: city.Location.Longitude,
  465. }
  466. }