apisrv.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. mapsMut sync.Mutex
  44. misses map[string]int32
  45. }
  46. type requestID int64
  47. func (i requestID) String() string {
  48. return fmt.Sprintf("%016x", int64(i))
  49. }
  50. type contextKey int
  51. const idKey contextKey = iota
  52. func newAPISrv(addr string, cert tls.Certificate, db database, repl replicator, useHTTP bool) *apiSrv {
  53. return &apiSrv{
  54. addr: addr,
  55. cert: cert,
  56. db: db,
  57. repl: repl,
  58. useHTTP: useHTTP,
  59. misses: make(map[string]int32),
  60. }
  61. }
  62. func (s *apiSrv) Serve(_ context.Context) error {
  63. if s.useHTTP {
  64. listener, err := net.Listen("tcp", s.addr)
  65. if err != nil {
  66. log.Println("Listen:", err)
  67. return err
  68. }
  69. s.listener = listener
  70. } else {
  71. tlsCfg := &tls.Config{
  72. Certificates: []tls.Certificate{s.cert},
  73. ClientAuth: tls.RequestClientCert,
  74. MinVersion: tls.VersionTLS12,
  75. NextProtos: []string{"h2", "http/1.1"},
  76. }
  77. tlsListener, err := tls.Listen("tcp", s.addr, tlsCfg)
  78. if err != nil {
  79. log.Println("Listen:", err)
  80. return err
  81. }
  82. s.listener = tlsListener
  83. }
  84. http.HandleFunc("/", s.handler)
  85. http.HandleFunc("/ping", handlePing)
  86. srv := &http.Server{
  87. ReadTimeout: httpReadTimeout,
  88. WriteTimeout: httpWriteTimeout,
  89. MaxHeaderBytes: httpMaxHeaderBytes,
  90. ErrorLog: log.New(io.Discard, "", 0),
  91. }
  92. err := srv.Serve(s.listener)
  93. if err != nil {
  94. log.Println("Serve:", err)
  95. }
  96. return err
  97. }
  98. func (s *apiSrv) handler(w http.ResponseWriter, req *http.Request) {
  99. t0 := time.Now()
  100. lw := NewLoggingResponseWriter(w)
  101. defer func() {
  102. diff := time.Since(t0)
  103. apiRequestsSeconds.WithLabelValues(req.Method).Observe(diff.Seconds())
  104. apiRequestsTotal.WithLabelValues(req.Method, strconv.Itoa(lw.statusCode)).Inc()
  105. }()
  106. reqID := requestID(rand.Int63())
  107. req = req.WithContext(context.WithValue(req.Context(), idKey, reqID))
  108. if debug {
  109. log.Println(reqID, req.Method, req.URL, req.Proto)
  110. }
  111. remoteAddr := &net.TCPAddr{
  112. IP: nil,
  113. Port: -1,
  114. }
  115. if s.useHTTP {
  116. remoteAddr.IP = net.ParseIP(req.Header.Get("X-Forwarded-For"))
  117. if parsedPort, err := strconv.ParseInt(req.Header.Get("X-Client-Port"), 10, 0); err == nil {
  118. remoteAddr.Port = int(parsedPort)
  119. }
  120. } else {
  121. var err error
  122. remoteAddr, err = net.ResolveTCPAddr("tcp", req.RemoteAddr)
  123. if err != nil {
  124. log.Println("remoteAddr:", err)
  125. lw.Header().Set("Retry-After", errorRetryAfterString())
  126. http.Error(lw, "Internal Server Error", http.StatusInternalServerError)
  127. apiRequestsTotal.WithLabelValues("no_remote_addr").Inc()
  128. return
  129. }
  130. }
  131. switch req.Method {
  132. case http.MethodGet:
  133. s.handleGET(lw, req)
  134. case http.MethodPost:
  135. s.handlePOST(remoteAddr, lw, req)
  136. default:
  137. http.Error(lw, "Method Not Allowed", http.StatusMethodNotAllowed)
  138. }
  139. }
  140. func (s *apiSrv) handleGET(w http.ResponseWriter, req *http.Request) {
  141. reqID := req.Context().Value(idKey).(requestID)
  142. deviceID, err := protocol.DeviceIDFromString(req.URL.Query().Get("device"))
  143. if err != nil {
  144. if debug {
  145. log.Println(reqID, "bad device param")
  146. }
  147. lookupRequestsTotal.WithLabelValues("bad_request").Inc()
  148. w.Header().Set("Retry-After", errorRetryAfterString())
  149. http.Error(w, "Bad Request", http.StatusBadRequest)
  150. return
  151. }
  152. key := deviceID.String()
  153. rec, err := s.db.get(key)
  154. if err != nil {
  155. // some sort of internal error
  156. lookupRequestsTotal.WithLabelValues("internal_error").Inc()
  157. w.Header().Set("Retry-After", errorRetryAfterString())
  158. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  159. return
  160. }
  161. if len(rec.Addresses) == 0 {
  162. lookupRequestsTotal.WithLabelValues("not_found").Inc()
  163. s.mapsMut.Lock()
  164. misses := s.misses[key]
  165. if misses < rec.Misses {
  166. misses = rec.Misses + 1
  167. } else {
  168. misses++
  169. }
  170. s.misses[key] = misses
  171. s.mapsMut.Unlock()
  172. if misses%notFoundMissesWriteInterval == 0 {
  173. rec.Misses = misses
  174. rec.Missed = time.Now().UnixNano()
  175. rec.Addresses = nil
  176. // rec.Seen retained from get
  177. s.db.put(key, rec)
  178. }
  179. w.Header().Set("Retry-After", notFoundRetryAfterString(int(misses)))
  180. http.Error(w, "Not Found", http.StatusNotFound)
  181. return
  182. }
  183. lookupRequestsTotal.WithLabelValues("success").Inc()
  184. w.Header().Set("Content-Type", "application/json")
  185. var bw io.Writer = w
  186. // Use compression if the client asks for it
  187. if strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
  188. w.Header().Set("Content-Encoding", "gzip")
  189. gw := gzip.NewWriter(bw)
  190. defer gw.Close()
  191. bw = gw
  192. }
  193. json.NewEncoder(bw).Encode(announcement{
  194. Seen: time.Unix(0, rec.Seen).Truncate(time.Second),
  195. Addresses: addressStrs(rec.Addresses),
  196. })
  197. }
  198. func (s *apiSrv) handlePOST(remoteAddr *net.TCPAddr, w http.ResponseWriter, req *http.Request) {
  199. reqID := req.Context().Value(idKey).(requestID)
  200. rawCert, err := certificateBytes(req)
  201. if err != nil {
  202. if debug {
  203. log.Println(reqID, "no certificates:", err)
  204. }
  205. announceRequestsTotal.WithLabelValues("no_certificate").Inc()
  206. w.Header().Set("Retry-After", errorRetryAfterString())
  207. http.Error(w, "Forbidden", http.StatusForbidden)
  208. return
  209. }
  210. var ann announcement
  211. if err := json.NewDecoder(req.Body).Decode(&ann); err != nil {
  212. if debug {
  213. log.Println(reqID, "decode:", err)
  214. }
  215. announceRequestsTotal.WithLabelValues("bad_request").Inc()
  216. w.Header().Set("Retry-After", errorRetryAfterString())
  217. http.Error(w, "Bad Request", http.StatusBadRequest)
  218. return
  219. }
  220. deviceID := protocol.NewDeviceID(rawCert)
  221. addresses := fixupAddresses(remoteAddr, ann.Addresses)
  222. if len(addresses) == 0 {
  223. announceRequestsTotal.WithLabelValues("bad_request").Inc()
  224. w.Header().Set("Retry-After", errorRetryAfterString())
  225. http.Error(w, "Bad Request", http.StatusBadRequest)
  226. return
  227. }
  228. if err := s.handleAnnounce(deviceID, addresses); err != nil {
  229. announceRequestsTotal.WithLabelValues("internal_error").Inc()
  230. w.Header().Set("Retry-After", errorRetryAfterString())
  231. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  232. return
  233. }
  234. announceRequestsTotal.WithLabelValues("success").Inc()
  235. w.Header().Set("Reannounce-After", reannounceAfterString())
  236. w.WriteHeader(http.StatusNoContent)
  237. }
  238. func (s *apiSrv) Stop() {
  239. s.listener.Close()
  240. }
  241. func (s *apiSrv) handleAnnounce(deviceID protocol.DeviceID, addresses []string) error {
  242. key := deviceID.String()
  243. now := time.Now()
  244. expire := now.Add(addressExpiryTime).UnixNano()
  245. dbAddrs := make([]DatabaseAddress, len(addresses))
  246. for i := range addresses {
  247. dbAddrs[i].Address = addresses[i]
  248. dbAddrs[i].Expires = expire
  249. }
  250. // The address slice must always be sorted for database merges to work
  251. // properly.
  252. sort.Sort(databaseAddressOrder(dbAddrs))
  253. seen := now.UnixNano()
  254. if s.repl != nil {
  255. s.repl.send(key, dbAddrs, seen)
  256. }
  257. return s.db.merge(key, dbAddrs, seen)
  258. }
  259. func handlePing(w http.ResponseWriter, _ *http.Request) {
  260. w.WriteHeader(204)
  261. }
  262. func certificateBytes(req *http.Request) ([]byte, error) {
  263. if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
  264. return req.TLS.PeerCertificates[0].Raw, nil
  265. }
  266. var bs []byte
  267. if hdr := req.Header.Get("X-SSL-Cert"); hdr != "" {
  268. if strings.Contains(hdr, "%") {
  269. // Nginx using $ssl_client_escaped_cert
  270. // The certificate is in PEM format with url encoding.
  271. // We need to decode for the PEM decoder
  272. hdr, err := url.QueryUnescape(hdr)
  273. if err != nil {
  274. // Decoding failed
  275. return nil, err
  276. }
  277. bs = []byte(hdr)
  278. } else {
  279. // Nginx using $ssl_client_cert
  280. // The certificate is in PEM format but with spaces for newlines. We
  281. // need to reinstate the newlines for the PEM decoder. But we need to
  282. // leave the spaces in the BEGIN and END lines - the first and last
  283. // space - alone.
  284. bs = []byte(hdr)
  285. firstSpace := bytes.Index(bs, []byte(" "))
  286. lastSpace := bytes.LastIndex(bs, []byte(" "))
  287. for i := firstSpace + 1; i < lastSpace; i++ {
  288. if bs[i] == ' ' {
  289. bs[i] = '\n'
  290. }
  291. }
  292. }
  293. } else if hdr := req.Header.Get("X-Tls-Client-Cert-Der-Base64"); hdr != "" {
  294. // Caddy {tls_client_certificate_der_base64}
  295. hdr, err := base64.StdEncoding.DecodeString(hdr)
  296. if err != nil {
  297. // Decoding failed
  298. return nil, err
  299. }
  300. bs = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: hdr})
  301. } else if hdr := req.Header.Get("X-Forwarded-Tls-Client-Cert"); hdr != "" {
  302. // Traefik 2 passtlsclientcert
  303. //
  304. // The certificate is in PEM format, maybe with URL encoding
  305. // (depends on Traefik version) but without newlines and start/end
  306. // statements. We need to decode, reinstate the newlines every 64
  307. // character and add statements for the PEM decoder
  308. if strings.Contains(hdr, "%") {
  309. if unesc, err := url.QueryUnescape(hdr); err == nil {
  310. hdr = unesc
  311. }
  312. }
  313. for i := 64; i < len(hdr); i += 65 {
  314. hdr = hdr[:i] + "\n" + hdr[i:]
  315. }
  316. hdr = "-----BEGIN CERTIFICATE-----\n" + hdr
  317. hdr += "\n-----END CERTIFICATE-----\n"
  318. bs = []byte(hdr)
  319. }
  320. if bs == nil {
  321. return nil, errors.New("empty certificate header")
  322. }
  323. block, _ := pem.Decode(bs)
  324. if block == nil {
  325. // Decoding failed
  326. return nil, errors.New("certificate decode result is empty")
  327. }
  328. return block.Bytes, nil
  329. }
  330. // fixupAddresses checks the list of addresses, removing invalid ones and
  331. // replacing unspecified IPs with the given remote IP.
  332. func fixupAddresses(remote *net.TCPAddr, addresses []string) []string {
  333. fixed := make([]string, 0, len(addresses))
  334. for _, annAddr := range addresses {
  335. uri, err := url.Parse(annAddr)
  336. if err != nil {
  337. continue
  338. }
  339. host, port, err := net.SplitHostPort(uri.Host)
  340. if err != nil {
  341. continue
  342. }
  343. ip := net.ParseIP(host)
  344. // Some classes of IP are no-go.
  345. if ip.IsLoopback() || ip.IsMulticast() {
  346. continue
  347. }
  348. if remote != nil {
  349. if host == "" || ip.IsUnspecified() {
  350. // Replace the unspecified IP with the request source.
  351. // ... unless the request source is the loopback address or
  352. // multicast/unspecified (can't happen, really).
  353. if remote.IP.IsLoopback() || remote.IP.IsMulticast() || remote.IP.IsUnspecified() {
  354. continue
  355. }
  356. // Do not use IPv6 remote address if requested scheme is ...4
  357. // (i.e., tcp4, etc.)
  358. if strings.HasSuffix(uri.Scheme, "4") && remote.IP.To4() == nil {
  359. continue
  360. }
  361. // Do not use IPv4 remote address if requested scheme is ...6
  362. if strings.HasSuffix(uri.Scheme, "6") && remote.IP.To4() != nil {
  363. continue
  364. }
  365. host = remote.IP.String()
  366. }
  367. // If zero port was specified, use remote port.
  368. if port == "0" && remote.Port > 0 {
  369. port = strconv.Itoa(remote.Port)
  370. }
  371. }
  372. uri.Host = net.JoinHostPort(host, port)
  373. fixed = append(fixed, uri.String())
  374. }
  375. // Remove duplicate addresses
  376. fixed = stringutil.UniqueTrimmedStrings(fixed)
  377. return fixed
  378. }
  379. type loggingResponseWriter struct {
  380. http.ResponseWriter
  381. statusCode int
  382. }
  383. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  384. return &loggingResponseWriter{w, http.StatusOK}
  385. }
  386. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  387. lrw.statusCode = code
  388. lrw.ResponseWriter.WriteHeader(code)
  389. }
  390. func addressStrs(dbAddrs []DatabaseAddress) []string {
  391. res := make([]string, len(dbAddrs))
  392. for i, a := range dbAddrs {
  393. res[i] = a.Address
  394. }
  395. return res
  396. }
  397. func errorRetryAfterString() string {
  398. return strconv.Itoa(errorRetryAfterSeconds + rand.Intn(errorRetryFuzzSeconds))
  399. }
  400. func notFoundRetryAfterString(misses int) string {
  401. retryAfterS := notFoundRetryMinSeconds + notFoundRetryIncSeconds*misses
  402. if retryAfterS > notFoundRetryMaxSeconds {
  403. retryAfterS = notFoundRetryMaxSeconds
  404. }
  405. retryAfterS += rand.Intn(notFoundRetryFuzzSeconds)
  406. return strconv.Itoa(retryAfterS)
  407. }
  408. func reannounceAfterString() string {
  409. return strconv.Itoa(reannounceAfterSeconds + rand.Intn(reannounzeFuzzSeconds))
  410. }