apisrv.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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() {
  58. if s.useHTTP {
  59. listener, err := net.Listen("tcp", s.addr)
  60. if err != nil {
  61. log.Println("Listen:", err)
  62. return
  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
  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. if err := srv.Serve(s.listener); err != nil {
  95. log.Println("Serve:", err)
  96. }
  97. }
  98. var topCtx = context.Background()
  99. func (s *apiSrv) handler(w http.ResponseWriter, req *http.Request) {
  100. t0 := time.Now()
  101. lw := NewLoggingResponseWriter(w)
  102. defer func() {
  103. diff := time.Since(t0)
  104. apiRequestsSeconds.WithLabelValues(req.Method).Observe(diff.Seconds())
  105. apiRequestsTotal.WithLabelValues(req.Method, strconv.Itoa(lw.statusCode)).Inc()
  106. }()
  107. reqID := requestID(rand.Int63())
  108. ctx := context.WithValue(topCtx, idKey, reqID)
  109. if debug {
  110. log.Println(reqID, req.Method, req.URL)
  111. }
  112. var remoteIP net.IP
  113. if s.useHTTP {
  114. remoteIP = net.ParseIP(req.Header.Get("X-Forwarded-For"))
  115. } else {
  116. addr, err := net.ResolveTCPAddr("tcp", req.RemoteAddr)
  117. if err != nil {
  118. log.Println("remoteAddr:", err)
  119. lw.Header().Set("Retry-After", errorRetryAfterString())
  120. http.Error(lw, "Internal Server Error", http.StatusInternalServerError)
  121. apiRequestsTotal.WithLabelValues("no_remote_addr").Inc()
  122. return
  123. }
  124. remoteIP = addr.IP
  125. }
  126. switch req.Method {
  127. case "GET":
  128. s.handleGET(ctx, lw, req)
  129. case "POST":
  130. s.handlePOST(ctx, remoteIP, lw, req)
  131. default:
  132. http.Error(lw, "Method Not Allowed", http.StatusMethodNotAllowed)
  133. }
  134. }
  135. func (s *apiSrv) handleGET(ctx context.Context, w http.ResponseWriter, req *http.Request) {
  136. reqID := ctx.Value(idKey).(requestID)
  137. deviceID, err := protocol.DeviceIDFromString(req.URL.Query().Get("device"))
  138. if err != nil {
  139. if debug {
  140. log.Println(reqID, "bad device param")
  141. }
  142. lookupRequestsTotal.WithLabelValues("bad_request").Inc()
  143. w.Header().Set("Retry-After", errorRetryAfterString())
  144. http.Error(w, "Bad Request", http.StatusBadRequest)
  145. return
  146. }
  147. key := deviceID.String()
  148. rec, err := s.db.get(key)
  149. if err != nil {
  150. // some sort of internal error
  151. lookupRequestsTotal.WithLabelValues("internal_error").Inc()
  152. w.Header().Set("Retry-After", errorRetryAfterString())
  153. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  154. return
  155. }
  156. if len(rec.Addresses) == 0 {
  157. lookupRequestsTotal.WithLabelValues("not_found").Inc()
  158. s.mapsMut.Lock()
  159. misses := s.misses[key]
  160. if misses < rec.Misses {
  161. misses = rec.Misses + 1
  162. } else {
  163. misses++
  164. }
  165. s.misses[key] = misses
  166. s.mapsMut.Unlock()
  167. if misses%notFoundMissesWriteInterval == 0 {
  168. rec.Misses = misses
  169. rec.Missed = time.Now().UnixNano()
  170. rec.Addresses = nil
  171. // rec.Seen retained from get
  172. s.db.put(key, rec)
  173. }
  174. w.Header().Set("Retry-After", notFoundRetryAfterString(int(misses)))
  175. http.Error(w, "Not Found", http.StatusNotFound)
  176. return
  177. }
  178. lookupRequestsTotal.WithLabelValues("success").Inc()
  179. bs, _ := json.Marshal(announcement{
  180. Seen: time.Unix(0, rec.Seen),
  181. Addresses: addressStrs(rec.Addresses),
  182. })
  183. w.Header().Set("Content-Type", "application/json")
  184. w.Write(bs)
  185. }
  186. func (s *apiSrv) handlePOST(ctx context.Context, remoteIP net.IP, w http.ResponseWriter, req *http.Request) {
  187. reqID := ctx.Value(idKey).(requestID)
  188. rawCert := certificateBytes(req)
  189. if rawCert == nil {
  190. if debug {
  191. log.Println(reqID, "no certificates")
  192. }
  193. announceRequestsTotal.WithLabelValues("no_certificate").Inc()
  194. w.Header().Set("Retry-After", errorRetryAfterString())
  195. http.Error(w, "Forbidden", http.StatusForbidden)
  196. return
  197. }
  198. var ann announcement
  199. if err := json.NewDecoder(req.Body).Decode(&ann); err != nil {
  200. if debug {
  201. log.Println(reqID, "decode:", err)
  202. }
  203. announceRequestsTotal.WithLabelValues("bad_request").Inc()
  204. w.Header().Set("Retry-After", errorRetryAfterString())
  205. http.Error(w, "Bad Request", http.StatusBadRequest)
  206. return
  207. }
  208. deviceID := protocol.NewDeviceID(rawCert)
  209. addresses := fixupAddresses(remoteIP, ann.Addresses)
  210. if len(addresses) == 0 {
  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. if err := s.handleAnnounce(remoteIP, deviceID, addresses); err != nil {
  217. announceRequestsTotal.WithLabelValues("internal_error").Inc()
  218. w.Header().Set("Retry-After", errorRetryAfterString())
  219. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  220. return
  221. }
  222. announceRequestsTotal.WithLabelValues("success").Inc()
  223. w.Header().Set("Reannounce-After", reannounceAfterString())
  224. w.WriteHeader(http.StatusNoContent)
  225. }
  226. func (s *apiSrv) Stop() {
  227. s.listener.Close()
  228. }
  229. func (s *apiSrv) handleAnnounce(remote net.IP, deviceID protocol.DeviceID, addresses []string) error {
  230. key := deviceID.String()
  231. now := time.Now()
  232. expire := now.Add(addressExpiryTime).UnixNano()
  233. dbAddrs := make([]DatabaseAddress, len(addresses))
  234. for i := range addresses {
  235. dbAddrs[i].Address = addresses[i]
  236. dbAddrs[i].Expires = expire
  237. }
  238. // The address slice must always be sorted for database merges to work
  239. // properly.
  240. sort.Sort(databaseAddressOrder(dbAddrs))
  241. seen := now.UnixNano()
  242. if s.repl != nil {
  243. s.repl.send(key, dbAddrs, seen)
  244. }
  245. return s.db.merge(key, dbAddrs, seen)
  246. }
  247. func handlePing(w http.ResponseWriter, r *http.Request) {
  248. w.WriteHeader(204)
  249. }
  250. func certificateBytes(req *http.Request) []byte {
  251. if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
  252. return req.TLS.PeerCertificates[0].Raw
  253. }
  254. var bs []byte
  255. if hdr := req.Header.Get("X-SSL-Cert"); hdr != "" {
  256. if strings.Contains(hdr, "%") {
  257. // Nginx using $ssl_client_escaped_cert
  258. // The certificate is in PEM format with url encoding.
  259. // We need to decode for the PEM decoder
  260. hdr, err := url.QueryUnescape(hdr)
  261. if err != nil {
  262. // Decoding failed
  263. return nil
  264. }
  265. bs = []byte(hdr)
  266. } else {
  267. // Nginx using $ssl_client_cert
  268. // The certificate is in PEM format but with spaces for newlines. We
  269. // need to reinstate the newlines for the PEM decoder. But we need to
  270. // leave the spaces in the BEGIN and END lines - the first and last
  271. // space - alone.
  272. bs = []byte(hdr)
  273. firstSpace := bytes.Index(bs, []byte(" "))
  274. lastSpace := bytes.LastIndex(bs, []byte(" "))
  275. for i := firstSpace + 1; i < lastSpace; i++ {
  276. if bs[i] == ' ' {
  277. bs[i] = '\n'
  278. }
  279. }
  280. }
  281. } else if hdr := req.Header.Get("X-Forwarded-Tls-Client-Cert"); hdr != "" {
  282. // Traefik 2 passtlsclientcert
  283. // The certificate is in PEM format with url encoding but without newlines
  284. // and start/end statements. We need to decode, reinstate the newlines every 64
  285. // character and add statements for the PEM decoder
  286. hdr, err := url.QueryUnescape(hdr)
  287. if err != nil {
  288. // Decoding failed
  289. return nil
  290. }
  291. for i := 64; i < len(hdr); i += 65 {
  292. hdr = hdr[:i] + "\n" + hdr[i:]
  293. }
  294. hdr = "-----BEGIN CERTIFICATE-----\n" + hdr
  295. hdr = hdr + "\n-----END CERTIFICATE-----\n"
  296. bs = []byte(hdr)
  297. }
  298. if bs == nil {
  299. return nil
  300. }
  301. block, _ := pem.Decode(bs)
  302. if block == nil {
  303. // Decoding failed
  304. return nil
  305. }
  306. return block.Bytes
  307. }
  308. // fixupAddresses checks the list of addresses, removing invalid ones and
  309. // replacing unspecified IPs with the given remote IP.
  310. func fixupAddresses(remote net.IP, addresses []string) []string {
  311. fixed := make([]string, 0, len(addresses))
  312. for _, annAddr := range addresses {
  313. uri, err := url.Parse(annAddr)
  314. if err != nil {
  315. continue
  316. }
  317. host, port, err := net.SplitHostPort(uri.Host)
  318. if err != nil {
  319. continue
  320. }
  321. ip := net.ParseIP(host)
  322. // Some classes of IP are no-go.
  323. if ip.IsLoopback() || ip.IsMulticast() {
  324. continue
  325. }
  326. if host == "" || ip.IsUnspecified() {
  327. // Replace the unspecified IP with the request source.
  328. // ... unless the request source is the loopback address or
  329. // multicast/unspecified (can't happen, really).
  330. if remote.IsLoopback() || remote.IsMulticast() || remote.IsUnspecified() {
  331. continue
  332. }
  333. // Do not use IPv6 remote address if requested scheme is ...4
  334. // (i.e., tcp4, etc.)
  335. if strings.HasSuffix(uri.Scheme, "4") && remote.To4() == nil {
  336. continue
  337. }
  338. // Do not use IPv4 remote address if requested scheme is ...6
  339. if strings.HasSuffix(uri.Scheme, "6") && remote.To4() != nil {
  340. continue
  341. }
  342. host = remote.String()
  343. }
  344. uri.Host = net.JoinHostPort(host, port)
  345. fixed = append(fixed, uri.String())
  346. }
  347. return fixed
  348. }
  349. type loggingResponseWriter struct {
  350. http.ResponseWriter
  351. statusCode int
  352. }
  353. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  354. return &loggingResponseWriter{w, http.StatusOK}
  355. }
  356. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  357. lrw.statusCode = code
  358. lrw.ResponseWriter.WriteHeader(code)
  359. }
  360. func addressStrs(dbAddrs []DatabaseAddress) []string {
  361. res := make([]string, len(dbAddrs))
  362. for i, a := range dbAddrs {
  363. res[i] = a.Address
  364. }
  365. return res
  366. }
  367. func errorRetryAfterString() string {
  368. return strconv.Itoa(errorRetryAfterSeconds + rand.Intn(errorRetryFuzzSeconds))
  369. }
  370. func notFoundRetryAfterString(misses int) string {
  371. retryAfterS := notFoundRetryMinSeconds + notFoundRetryIncSeconds*misses
  372. if retryAfterS > notFoundRetryMaxSeconds {
  373. retryAfterS = notFoundRetryMaxSeconds
  374. }
  375. retryAfterS += rand.Intn(notFoundRetryFuzzSeconds)
  376. return strconv.Itoa(retryAfterS)
  377. }
  378. func reannounceAfterString() string {
  379. return strconv.Itoa(reannounceAfterSeconds + rand.Intn(reannounzeFuzzSeconds))
  380. }