apisrv.go 15 KB

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