apisrv.go 12 KB

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