main.go 12 KB

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