apisrv.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. // Copyright (C) 2018 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package main
  7. import (
  8. "bytes"
  9. "compress/gzip"
  10. "context"
  11. "crypto/tls"
  12. "encoding/base64"
  13. "encoding/json"
  14. "encoding/pem"
  15. "errors"
  16. "fmt"
  17. io "io"
  18. "log"
  19. "math/rand"
  20. "net"
  21. "net/http"
  22. "net/url"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. "github.com/syncthing/syncthing/lib/protocol"
  29. "github.com/syncthing/syncthing/lib/stringutil"
  30. )
  31. // announcement is the format received from and sent to clients
  32. type announcement struct {
  33. Seen time.Time `json:"seen"`
  34. Addresses []string `json:"addresses"`
  35. }
  36. type apiSrv struct {
  37. addr string
  38. cert tls.Certificate
  39. db database
  40. listener net.Listener
  41. repl replicator // optional
  42. useHTTP bool
  43. compression bool
  44. gzipWriters sync.Pool
  45. seenTracker *retryAfterTracker
  46. notSeenTracker *retryAfterTracker
  47. }
  48. type requestID int64
  49. func (i requestID) String() string {
  50. return fmt.Sprintf("%016x", int64(i))
  51. }
  52. type contextKey int
  53. const idKey contextKey = iota
  54. func newAPISrv(addr string, cert tls.Certificate, db database, repl replicator, useHTTP, compression bool) *apiSrv {
  55. return &apiSrv{
  56. addr: addr,
  57. cert: cert,
  58. db: db,
  59. repl: repl,
  60. useHTTP: useHTTP,
  61. compression: compression,
  62. seenTracker: &retryAfterTracker{
  63. name: "seenTracker",
  64. bucketStarts: time.Now(),
  65. desiredRate: 250,
  66. currentDelay: notFoundRetryUnknownMinSeconds,
  67. },
  68. notSeenTracker: &retryAfterTracker{
  69. name: "notSeenTracker",
  70. bucketStarts: time.Now(),
  71. desiredRate: 250,
  72. currentDelay: notFoundRetryUnknownMaxSeconds / 2,
  73. },
  74. }
  75. }
  76. func (s *apiSrv) Serve(ctx context.Context) error {
  77. if s.useHTTP {
  78. listener, err := net.Listen("tcp", s.addr)
  79. if err != nil {
  80. log.Println("Listen:", err)
  81. return err
  82. }
  83. s.listener = listener
  84. } else {
  85. tlsCfg := &tls.Config{
  86. Certificates: []tls.Certificate{s.cert},
  87. ClientAuth: tls.RequestClientCert,
  88. MinVersion: tls.VersionTLS12,
  89. NextProtos: []string{"h2", "http/1.1"},
  90. }
  91. tlsListener, err := tls.Listen("tcp", s.addr, tlsCfg)
  92. if err != nil {
  93. log.Println("Listen:", err)
  94. return err
  95. }
  96. s.listener = tlsListener
  97. }
  98. http.HandleFunc("/", s.handler)
  99. http.HandleFunc("/ping", handlePing)
  100. srv := &http.Server{
  101. ReadTimeout: httpReadTimeout,
  102. WriteTimeout: httpWriteTimeout,
  103. MaxHeaderBytes: httpMaxHeaderBytes,
  104. ErrorLog: log.New(io.Discard, "", 0),
  105. }
  106. go func() {
  107. <-ctx.Done()
  108. srv.Shutdown(context.Background())
  109. }()
  110. err := srv.Serve(s.listener)
  111. if err != nil {
  112. log.Println("Serve:", err)
  113. }
  114. return err
  115. }
  116. func (s *apiSrv) handler(w http.ResponseWriter, req *http.Request) {
  117. t0 := time.Now()
  118. lw := NewLoggingResponseWriter(w)
  119. defer func() {
  120. diff := time.Since(t0)
  121. apiRequestsSeconds.WithLabelValues(req.Method).Observe(diff.Seconds())
  122. apiRequestsTotal.WithLabelValues(req.Method, strconv.Itoa(lw.statusCode)).Inc()
  123. }()
  124. reqID := requestID(rand.Int63())
  125. req = req.WithContext(context.WithValue(req.Context(), idKey, reqID))
  126. if debug {
  127. log.Println(reqID, req.Method, req.URL, req.Proto)
  128. }
  129. remoteAddr := &net.TCPAddr{
  130. IP: nil,
  131. Port: -1,
  132. }
  133. if s.useHTTP {
  134. // X-Forwarded-For can have multiple client IPs; split using the comma separator
  135. forwardIP, _, _ := strings.Cut(req.Header.Get("X-Forwarded-For"), ",")
  136. // net.ParseIP will return nil if leading/trailing whitespace exists; use strings.TrimSpace()
  137. remoteAddr.IP = net.ParseIP(strings.TrimSpace(forwardIP))
  138. if parsedPort, err := strconv.ParseInt(req.Header.Get("X-Client-Port"), 10, 0); err == nil {
  139. remoteAddr.Port = int(parsedPort)
  140. }
  141. } else {
  142. var err error
  143. remoteAddr, err = net.ResolveTCPAddr("tcp", req.RemoteAddr)
  144. if err != nil {
  145. log.Println("remoteAddr:", err)
  146. lw.Header().Set("Retry-After", errorRetryAfterString())
  147. http.Error(lw, "Internal Server Error", http.StatusInternalServerError)
  148. apiRequestsTotal.WithLabelValues("no_remote_addr").Inc()
  149. return
  150. }
  151. }
  152. switch req.Method {
  153. case http.MethodGet:
  154. s.handleGET(lw, req)
  155. case http.MethodPost:
  156. s.handlePOST(remoteAddr, lw, req)
  157. default:
  158. http.Error(lw, "Method Not Allowed", http.StatusMethodNotAllowed)
  159. }
  160. }
  161. func (s *apiSrv) handleGET(w http.ResponseWriter, req *http.Request) {
  162. reqID := req.Context().Value(idKey).(requestID)
  163. deviceID, err := protocol.DeviceIDFromString(req.URL.Query().Get("device"))
  164. if err != nil {
  165. if debug {
  166. log.Println(reqID, "bad device param")
  167. }
  168. lookupRequestsTotal.WithLabelValues("bad_request").Inc()
  169. w.Header().Set("Retry-After", errorRetryAfterString())
  170. http.Error(w, "Bad Request", http.StatusBadRequest)
  171. return
  172. }
  173. rec, err := s.db.get(&deviceID)
  174. if err != nil {
  175. // some sort of internal error
  176. lookupRequestsTotal.WithLabelValues("internal_error").Inc()
  177. w.Header().Set("Retry-After", errorRetryAfterString())
  178. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  179. return
  180. }
  181. if len(rec.Addresses) == 0 {
  182. var afterS int
  183. if rec.Seen == 0 {
  184. afterS = s.notSeenTracker.retryAfterS()
  185. lookupRequestsTotal.WithLabelValues("not_found_ever").Inc()
  186. } else {
  187. afterS = s.seenTracker.retryAfterS()
  188. lookupRequestsTotal.WithLabelValues("not_found_recent").Inc()
  189. }
  190. w.Header().Set("Retry-After", strconv.Itoa(afterS))
  191. http.Error(w, "Not Found", http.StatusNotFound)
  192. return
  193. }
  194. lookupRequestsTotal.WithLabelValues("success").Inc()
  195. w.Header().Set("Content-Type", "application/json")
  196. var bw io.Writer = w
  197. // Use compression if the client asks for it
  198. if s.compression && strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
  199. gw, ok := s.gzipWriters.Get().(*gzip.Writer)
  200. if ok {
  201. gw.Reset(w)
  202. } else {
  203. gw = gzip.NewWriter(w)
  204. }
  205. w.Header().Set("Content-Encoding", "gzip")
  206. defer gw.Close()
  207. defer s.gzipWriters.Put(gw)
  208. bw = gw
  209. }
  210. json.NewEncoder(bw).Encode(announcement{
  211. Seen: time.Unix(0, rec.Seen).Truncate(time.Second),
  212. Addresses: addressStrs(rec.Addresses),
  213. })
  214. }
  215. func (s *apiSrv) handlePOST(remoteAddr *net.TCPAddr, w http.ResponseWriter, req *http.Request) {
  216. reqID := req.Context().Value(idKey).(requestID)
  217. rawCert, err := certificateBytes(req)
  218. if err != nil {
  219. if debug {
  220. log.Println(reqID, "no certificates:", err)
  221. }
  222. announceRequestsTotal.WithLabelValues("no_certificate").Inc()
  223. w.Header().Set("Retry-After", errorRetryAfterString())
  224. http.Error(w, "Forbidden", http.StatusForbidden)
  225. return
  226. }
  227. var ann announcement
  228. if err := json.NewDecoder(req.Body).Decode(&ann); err != nil {
  229. if debug {
  230. log.Println(reqID, "decode:", err)
  231. }
  232. announceRequestsTotal.WithLabelValues("bad_request").Inc()
  233. w.Header().Set("Retry-After", errorRetryAfterString())
  234. http.Error(w, "Bad Request", http.StatusBadRequest)
  235. return
  236. }
  237. deviceID := protocol.NewDeviceID(rawCert)
  238. addresses := fixupAddresses(remoteAddr, ann.Addresses)
  239. if len(addresses) == 0 {
  240. announceRequestsTotal.WithLabelValues("bad_request").Inc()
  241. w.Header().Set("Retry-After", errorRetryAfterString())
  242. http.Error(w, "Bad Request", http.StatusBadRequest)
  243. return
  244. }
  245. if err := s.handleAnnounce(deviceID, addresses); err != nil {
  246. announceRequestsTotal.WithLabelValues("internal_error").Inc()
  247. w.Header().Set("Retry-After", errorRetryAfterString())
  248. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  249. return
  250. }
  251. announceRequestsTotal.WithLabelValues("success").Inc()
  252. w.Header().Set("Reannounce-After", reannounceAfterString())
  253. w.WriteHeader(http.StatusNoContent)
  254. }
  255. func (s *apiSrv) Stop() {
  256. s.listener.Close()
  257. }
  258. func (s *apiSrv) handleAnnounce(deviceID protocol.DeviceID, addresses []string) error {
  259. now := time.Now()
  260. expire := now.Add(addressExpiryTime).UnixNano()
  261. dbAddrs := make([]DatabaseAddress, len(addresses))
  262. for i := range addresses {
  263. dbAddrs[i].Address = addresses[i]
  264. dbAddrs[i].Expires = expire
  265. }
  266. // The address slice must always be sorted for database merges to work
  267. // properly.
  268. sort.Sort(databaseAddressOrder(dbAddrs))
  269. seen := now.UnixNano()
  270. if s.repl != nil {
  271. s.repl.send(&deviceID, dbAddrs, seen)
  272. }
  273. return s.db.merge(&deviceID, dbAddrs, seen)
  274. }
  275. func handlePing(w http.ResponseWriter, _ *http.Request) {
  276. w.WriteHeader(204)
  277. }
  278. func certificateBytes(req *http.Request) ([]byte, error) {
  279. if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
  280. return req.TLS.PeerCertificates[0].Raw, nil
  281. }
  282. var bs []byte
  283. if hdr := req.Header.Get("X-SSL-Cert"); hdr != "" {
  284. if strings.Contains(hdr, "%") {
  285. // Nginx using $ssl_client_escaped_cert
  286. // The certificate is in PEM format with url encoding.
  287. // We need to decode for the PEM decoder
  288. hdr, err := url.QueryUnescape(hdr)
  289. if err != nil {
  290. // Decoding failed
  291. return nil, err
  292. }
  293. bs = []byte(hdr)
  294. } else {
  295. // Nginx using $ssl_client_cert
  296. // The certificate is in PEM format but with spaces for newlines. We
  297. // need to reinstate the newlines for the PEM decoder. But we need to
  298. // leave the spaces in the BEGIN and END lines - the first and last
  299. // space - alone.
  300. bs = []byte(hdr)
  301. firstSpace := bytes.Index(bs, []byte(" "))
  302. lastSpace := bytes.LastIndex(bs, []byte(" "))
  303. for i := firstSpace + 1; i < lastSpace; i++ {
  304. if bs[i] == ' ' {
  305. bs[i] = '\n'
  306. }
  307. }
  308. }
  309. } else if hdr := req.Header.Get("X-Tls-Client-Cert-Der-Base64"); hdr != "" {
  310. // Caddy {tls_client_certificate_der_base64}
  311. hdr, err := base64.StdEncoding.DecodeString(hdr)
  312. if err != nil {
  313. // Decoding failed
  314. return nil, err
  315. }
  316. bs = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: hdr})
  317. } else if hdr := req.Header.Get("X-Forwarded-Tls-Client-Cert"); hdr != "" {
  318. // Traefik 2 passtlsclientcert
  319. //
  320. // The certificate is in PEM format, maybe with URL encoding
  321. // (depends on Traefik version) but without newlines and start/end
  322. // statements. We need to decode, reinstate the newlines every 64
  323. // character and add statements for the PEM decoder
  324. if strings.Contains(hdr, "%") {
  325. if unesc, err := url.QueryUnescape(hdr); err == nil {
  326. hdr = unesc
  327. }
  328. }
  329. for i := 64; i < len(hdr); i += 65 {
  330. hdr = hdr[:i] + "\n" + hdr[i:]
  331. }
  332. hdr = "-----BEGIN CERTIFICATE-----\n" + hdr
  333. hdr += "\n-----END CERTIFICATE-----\n"
  334. bs = []byte(hdr)
  335. }
  336. if bs == nil {
  337. return nil, errors.New("empty certificate header")
  338. }
  339. block, _ := pem.Decode(bs)
  340. if block == nil {
  341. // Decoding failed
  342. return nil, errors.New("certificate decode result is empty")
  343. }
  344. return block.Bytes, nil
  345. }
  346. // fixupAddresses checks the list of addresses, removing invalid ones and
  347. // replacing unspecified IPs with the given remote IP.
  348. func fixupAddresses(remote *net.TCPAddr, addresses []string) []string {
  349. fixed := make([]string, 0, len(addresses))
  350. for _, annAddr := range addresses {
  351. uri, err := url.Parse(annAddr)
  352. if err != nil {
  353. continue
  354. }
  355. host, port, err := net.SplitHostPort(uri.Host)
  356. if err != nil {
  357. continue
  358. }
  359. ip := net.ParseIP(host)
  360. // Some classes of IP are no-go.
  361. if ip.IsLoopback() || ip.IsMulticast() {
  362. continue
  363. }
  364. if host == "" || ip.IsUnspecified() {
  365. if remote != nil {
  366. // Replace the unspecified IP with the request source.
  367. // ... unless the request source is the loopback address or
  368. // multicast/unspecified (can't happen, really).
  369. if remote.IP == nil || remote.IP.IsLoopback() || remote.IP.IsMulticast() || remote.IP.IsUnspecified() {
  370. continue
  371. }
  372. // Do not use IPv6 remote address if requested scheme is ...4
  373. // (i.e., tcp4, etc.)
  374. if strings.HasSuffix(uri.Scheme, "4") && remote.IP.To4() == nil {
  375. continue
  376. }
  377. // Do not use IPv4 remote address if requested scheme is ...6
  378. if strings.HasSuffix(uri.Scheme, "6") && remote.IP.To4() != nil {
  379. continue
  380. }
  381. host = remote.IP.String()
  382. } else {
  383. // remote is nil, unable to determine host IP
  384. continue
  385. }
  386. }
  387. // If zero port was specified, use remote port.
  388. if port == "0" {
  389. if remote != nil && remote.Port > 0 {
  390. // use remote port
  391. port = strconv.Itoa(remote.Port)
  392. } else {
  393. // unable to determine remote port
  394. continue
  395. }
  396. }
  397. uri.Host = net.JoinHostPort(host, port)
  398. fixed = append(fixed, uri.String())
  399. }
  400. // Remove duplicate addresses
  401. fixed = stringutil.UniqueTrimmedStrings(fixed)
  402. return fixed
  403. }
  404. type loggingResponseWriter struct {
  405. http.ResponseWriter
  406. statusCode int
  407. }
  408. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  409. return &loggingResponseWriter{w, http.StatusOK}
  410. }
  411. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  412. lrw.statusCode = code
  413. lrw.ResponseWriter.WriteHeader(code)
  414. }
  415. func addressStrs(dbAddrs []DatabaseAddress) []string {
  416. res := make([]string, len(dbAddrs))
  417. for i, a := range dbAddrs {
  418. res[i] = a.Address
  419. }
  420. return res
  421. }
  422. func errorRetryAfterString() string {
  423. return strconv.Itoa(errorRetryAfterSeconds + rand.Intn(errorRetryFuzzSeconds))
  424. }
  425. func reannounceAfterString() string {
  426. return strconv.Itoa(reannounceAfterSeconds + rand.Intn(reannounzeFuzzSeconds))
  427. }
  428. type retryAfterTracker struct {
  429. name string
  430. desiredRate float64 // requests per second
  431. mut sync.Mutex
  432. lastCount int // requests in the last bucket
  433. curCount int // requests in the current bucket
  434. bucketStarts time.Time // start of the current bucket
  435. currentDelay int // current delay in seconds
  436. }
  437. func (t *retryAfterTracker) retryAfterS() int {
  438. now := time.Now()
  439. t.mut.Lock()
  440. if durS := now.Sub(t.bucketStarts).Seconds(); durS > float64(t.currentDelay) {
  441. t.bucketStarts = now
  442. t.lastCount = t.curCount
  443. lastRate := float64(t.lastCount) / durS
  444. switch {
  445. case t.currentDelay > notFoundRetryUnknownMinSeconds &&
  446. lastRate < 0.75*t.desiredRate:
  447. t.currentDelay = max(8*t.currentDelay/10, notFoundRetryUnknownMinSeconds)
  448. case t.currentDelay < notFoundRetryUnknownMaxSeconds &&
  449. lastRate > 1.25*t.desiredRate:
  450. t.currentDelay = min(3*t.currentDelay/2, notFoundRetryUnknownMaxSeconds)
  451. }
  452. t.curCount = 0
  453. }
  454. if t.curCount == 0 {
  455. retryAfterLevel.WithLabelValues(t.name).Set(float64(t.currentDelay))
  456. }
  457. t.curCount++
  458. t.mut.Unlock()
  459. return t.currentDelay + rand.Intn(t.currentDelay/4)
  460. }