apisrv.go 12 KB

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