global.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Copyright (C) 2015 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 discover
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/tls"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "net/http"
  17. "net/url"
  18. "strconv"
  19. stdsync "sync"
  20. "time"
  21. "github.com/syncthing/syncthing/lib/connections/registry"
  22. "github.com/syncthing/syncthing/lib/dialer"
  23. "github.com/syncthing/syncthing/lib/events"
  24. "github.com/syncthing/syncthing/lib/protocol"
  25. "golang.org/x/net/http2"
  26. )
  27. type globalClient struct {
  28. server string
  29. addrList AddressLister
  30. announceClient httpClient
  31. queryClient httpClient
  32. noAnnounce bool
  33. noLookup bool
  34. evLogger events.Logger
  35. errorHolder
  36. }
  37. type httpClient interface {
  38. Get(ctx context.Context, url string) (*http.Response, error)
  39. Post(ctx context.Context, url, ctype string, data io.Reader) (*http.Response, error)
  40. }
  41. const (
  42. defaultReannounceInterval = 30 * time.Minute
  43. announceErrorRetryInterval = 5 * time.Minute
  44. requestTimeout = 30 * time.Second
  45. maxAddressChangesBetweenAnnouncements = 10
  46. )
  47. type announcement struct {
  48. Addresses []string `json:"addresses"`
  49. }
  50. func (a announcement) MarshalJSON() ([]byte, error) {
  51. type announcementCopy announcement
  52. a.Addresses = sanitizeRelayAddresses(a.Addresses)
  53. aCopy := announcementCopy(a)
  54. return json.Marshal(aCopy)
  55. }
  56. type serverOptions struct {
  57. insecure bool // don't check certificate
  58. noAnnounce bool // don't announce
  59. noLookup bool // don't use for lookups
  60. id string // expected server device ID
  61. }
  62. // A lookupError is any other error but with a cache validity time attached.
  63. type lookupError struct {
  64. msg string
  65. cacheFor time.Duration
  66. }
  67. func (e *lookupError) Error() string { return e.msg }
  68. func (e *lookupError) CacheFor() time.Duration {
  69. return e.cacheFor
  70. }
  71. func NewGlobal(server string, cert tls.Certificate, addrList AddressLister, evLogger events.Logger, registry *registry.Registry) (FinderService, error) {
  72. server, opts, err := parseOptions(server)
  73. if err != nil {
  74. return nil, err
  75. }
  76. var devID protocol.DeviceID
  77. if opts.id != "" {
  78. devID, err = protocol.DeviceIDFromString(opts.id)
  79. if err != nil {
  80. return nil, err
  81. }
  82. }
  83. // The http.Client used for announcements. It needs to have our
  84. // certificate to prove our identity, and may or may not verify the server
  85. // certificate depending on the insecure setting.
  86. var dialContext func(ctx context.Context, network, addr string) (net.Conn, error)
  87. if registry != nil {
  88. dialContext = dialer.DialContextReusePortFunc(registry)
  89. } else {
  90. dialContext = dialer.DialContext
  91. }
  92. var announceClient httpClient = &contextClient{&http.Client{
  93. Timeout: requestTimeout,
  94. Transport: http2EnabledTransport(&http.Transport{
  95. DialContext: dialContext,
  96. Proxy: http.ProxyFromEnvironment,
  97. DisableKeepAlives: true, // announcements are few and far between, so don't keep the connection open
  98. TLSClientConfig: &tls.Config{
  99. InsecureSkipVerify: opts.insecure,
  100. Certificates: []tls.Certificate{cert},
  101. MinVersion: tls.VersionTLS12,
  102. ClientSessionCache: tls.NewLRUClientSessionCache(0),
  103. },
  104. }),
  105. }}
  106. if opts.id != "" {
  107. announceClient = newIDCheckingHTTPClient(announceClient, devID)
  108. }
  109. // The http.Client used for queries. We don't need to present our
  110. // certificate here, so lets not include it. May be insecure if requested.
  111. var queryClient httpClient = &contextClient{&http.Client{
  112. Timeout: requestTimeout,
  113. Transport: http2EnabledTransport(&http.Transport{
  114. DialContext: dialer.DialContext,
  115. Proxy: http.ProxyFromEnvironment,
  116. IdleConnTimeout: time.Second,
  117. TLSClientConfig: &tls.Config{
  118. InsecureSkipVerify: opts.insecure,
  119. MinVersion: tls.VersionTLS12,
  120. ClientSessionCache: tls.NewLRUClientSessionCache(0),
  121. },
  122. }),
  123. }}
  124. if opts.id != "" {
  125. queryClient = newIDCheckingHTTPClient(queryClient, devID)
  126. }
  127. cl := &globalClient{
  128. server: server,
  129. addrList: addrList,
  130. announceClient: announceClient,
  131. queryClient: queryClient,
  132. noAnnounce: opts.noAnnounce,
  133. noLookup: opts.noLookup,
  134. evLogger: evLogger,
  135. }
  136. if !opts.noAnnounce {
  137. // If we are supposed to announce, it's an error until we've done so.
  138. cl.setError(errors.New("not announced"))
  139. }
  140. return cl, nil
  141. }
  142. // Lookup returns the list of addresses where the given device is available
  143. func (c *globalClient) Lookup(ctx context.Context, device protocol.DeviceID) (addresses []string, err error) {
  144. if c.noLookup {
  145. return nil, &lookupError{
  146. msg: "lookups not supported",
  147. cacheFor: time.Hour,
  148. }
  149. }
  150. qURL, err := url.Parse(c.server)
  151. if err != nil {
  152. return nil, err
  153. }
  154. q := qURL.Query()
  155. q.Set("device", device.String())
  156. qURL.RawQuery = q.Encode()
  157. resp, err := c.queryClient.Get(ctx, qURL.String())
  158. if err != nil {
  159. l.Debugln("globalClient.Lookup", qURL, err)
  160. return nil, err
  161. }
  162. if resp.StatusCode != http.StatusOK {
  163. resp.Body.Close()
  164. l.Debugln("globalClient.Lookup", qURL, resp.Status)
  165. err := errors.New(resp.Status)
  166. if secs, atoiErr := strconv.Atoi(resp.Header.Get("Retry-After")); atoiErr == nil && secs > 0 {
  167. err = &lookupError{
  168. msg: resp.Status,
  169. cacheFor: time.Duration(secs) * time.Second,
  170. }
  171. }
  172. return nil, err
  173. }
  174. bs, err := io.ReadAll(resp.Body)
  175. if err != nil {
  176. return nil, err
  177. }
  178. resp.Body.Close()
  179. var ann announcement
  180. err = json.Unmarshal(bs, &ann)
  181. return ann.Addresses, err
  182. }
  183. func (c *globalClient) String() string {
  184. return "global@" + c.server
  185. }
  186. func (c *globalClient) Serve(ctx context.Context) error {
  187. if c.noAnnounce {
  188. // We're configured to not do announcements, only lookups. To maintain
  189. // the same interface, we just pause here if Serve() is run.
  190. <-ctx.Done()
  191. return ctx.Err()
  192. }
  193. timer := time.NewTimer(5 * time.Second)
  194. defer timer.Stop()
  195. eventSub := c.evLogger.Subscribe(events.ListenAddressesChanged)
  196. defer eventSub.Unsubscribe()
  197. timerResetCount := 0
  198. for {
  199. select {
  200. case <-eventSub.C():
  201. if timerResetCount < maxAddressChangesBetweenAnnouncements {
  202. // Defer announcement by 2 seconds, essentially debouncing
  203. // if we have a stream of events incoming in quick succession.
  204. timer.Reset(2 * time.Second)
  205. } else if timerResetCount == maxAddressChangesBetweenAnnouncements {
  206. // Yet only do it if we haven't had to reset maxAddressChangesBetweenAnnouncements times in a row,
  207. // so if something is flip-flopping within 2 seconds, we don't end up in a permanent reset loop.
  208. l.Warnf("Detected a flip-flopping listener")
  209. c.setError(errors.New("flip flopping listener"))
  210. // Incrementing the count above 10 will prevent us from warning or setting the error again
  211. // It will also suppress event based resets until we've had a proper round after announceErrorRetryInterval
  212. timer.Reset(announceErrorRetryInterval)
  213. }
  214. timerResetCount++
  215. case <-timer.C:
  216. timerResetCount = 0
  217. c.sendAnnouncement(ctx, timer)
  218. case <-ctx.Done():
  219. return ctx.Err()
  220. }
  221. }
  222. }
  223. func (c *globalClient) sendAnnouncement(ctx context.Context, timer *time.Timer) {
  224. var ann announcement
  225. if c.addrList != nil {
  226. ann.Addresses = c.addrList.ExternalAddresses()
  227. }
  228. if len(ann.Addresses) == 0 {
  229. // There are legitimate cases for not having anything to announce,
  230. // yet still using global discovery for lookups. Do not error out
  231. // here.
  232. c.setError(nil)
  233. timer.Reset(announceErrorRetryInterval)
  234. return
  235. }
  236. // The marshal doesn't fail, I promise.
  237. postData, _ := json.Marshal(ann)
  238. l.Debugf("%s Announcement: %v", c, ann)
  239. resp, err := c.announceClient.Post(ctx, c.server, "application/json", bytes.NewReader(postData))
  240. if err != nil {
  241. l.Debugln(c, "announce POST:", err)
  242. c.setError(err)
  243. timer.Reset(announceErrorRetryInterval)
  244. return
  245. }
  246. l.Debugln(c, "announce POST:", resp.Status)
  247. resp.Body.Close()
  248. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  249. l.Debugln(c, "announce POST:", resp.Status)
  250. c.setError(errors.New(resp.Status))
  251. if h := resp.Header.Get("Retry-After"); h != "" {
  252. // The server has a recommendation on when we should
  253. // retry. Follow it.
  254. if secs, err := strconv.Atoi(h); err == nil && secs > 0 {
  255. l.Debugln(c, "announce Retry-After:", secs, err)
  256. timer.Reset(time.Duration(secs) * time.Second)
  257. return
  258. }
  259. }
  260. timer.Reset(announceErrorRetryInterval)
  261. return
  262. }
  263. c.setError(nil)
  264. if h := resp.Header.Get("Reannounce-After"); h != "" {
  265. // The server has a recommendation on when we should
  266. // reannounce. Follow it.
  267. if secs, err := strconv.Atoi(h); err == nil && secs > 0 {
  268. l.Debugln(c, "announce Reannounce-After:", secs, err)
  269. timer.Reset(time.Duration(secs) * time.Second)
  270. return
  271. }
  272. }
  273. timer.Reset(defaultReannounceInterval)
  274. }
  275. func (*globalClient) Cache() map[protocol.DeviceID]CacheEntry {
  276. // The globalClient doesn't do caching
  277. return nil
  278. }
  279. // parseOptions parses and strips away any ?query=val options, setting the
  280. // corresponding field in the serverOptions struct. Unknown query options are
  281. // ignored and removed.
  282. func parseOptions(dsn string) (server string, opts serverOptions, err error) {
  283. p, err := url.Parse(dsn)
  284. if err != nil {
  285. return "", serverOptions{}, err
  286. }
  287. // Grab known options from the query string
  288. q := p.Query()
  289. opts.id = q.Get("id")
  290. opts.insecure = opts.id != "" || queryBool(q, "insecure")
  291. opts.noAnnounce = queryBool(q, "noannounce")
  292. opts.noLookup = queryBool(q, "nolookup")
  293. // Check for disallowed combinations
  294. if p.Scheme == "http" {
  295. if !opts.insecure {
  296. return "", serverOptions{}, errors.New("http without insecure not supported")
  297. }
  298. if !opts.noAnnounce {
  299. return "", serverOptions{}, errors.New("http without noannounce not supported")
  300. }
  301. } else if p.Scheme != "https" {
  302. return "", serverOptions{}, errors.New("unsupported scheme " + p.Scheme)
  303. }
  304. // Remove the query string
  305. p.RawQuery = ""
  306. server = p.String()
  307. return
  308. }
  309. // queryBool returns the query parameter parsed as a boolean. An empty value
  310. // ("?foo") is considered true, as is any value string except false
  311. // ("?foo=false").
  312. func queryBool(q url.Values, key string) bool {
  313. if _, ok := q[key]; !ok {
  314. return false
  315. }
  316. return q.Get(key) != "false"
  317. }
  318. type idCheckingHTTPClient struct {
  319. httpClient
  320. id protocol.DeviceID
  321. }
  322. func newIDCheckingHTTPClient(client httpClient, id protocol.DeviceID) *idCheckingHTTPClient {
  323. return &idCheckingHTTPClient{
  324. httpClient: client,
  325. id: id,
  326. }
  327. }
  328. func (c *idCheckingHTTPClient) check(resp *http.Response) error {
  329. if resp.TLS == nil {
  330. return errors.New("security: not TLS")
  331. }
  332. if len(resp.TLS.PeerCertificates) == 0 {
  333. return errors.New("security: no certificates")
  334. }
  335. id := protocol.NewDeviceID(resp.TLS.PeerCertificates[0].Raw)
  336. if !id.Equals(c.id) {
  337. return errors.New("security: incorrect device id")
  338. }
  339. return nil
  340. }
  341. func (c *idCheckingHTTPClient) Get(ctx context.Context, url string) (*http.Response, error) {
  342. resp, err := c.httpClient.Get(ctx, url)
  343. if err != nil {
  344. return nil, err
  345. }
  346. if err := c.check(resp); err != nil {
  347. return nil, err
  348. }
  349. return resp, nil
  350. }
  351. func (c *idCheckingHTTPClient) Post(ctx context.Context, url, ctype string, data io.Reader) (*http.Response, error) {
  352. resp, err := c.httpClient.Post(ctx, url, ctype, data)
  353. if err != nil {
  354. return nil, err
  355. }
  356. if err := c.check(resp); err != nil {
  357. return nil, err
  358. }
  359. return resp, nil
  360. }
  361. type errorHolder struct {
  362. err error
  363. mut stdsync.Mutex // uses stdlib sync as I want this to be trivially embeddable, and there is no risk of blocking
  364. }
  365. func (e *errorHolder) setError(err error) {
  366. e.mut.Lock()
  367. e.err = err
  368. e.mut.Unlock()
  369. }
  370. func (e *errorHolder) Error() error {
  371. e.mut.Lock()
  372. err := e.err
  373. e.mut.Unlock()
  374. return err
  375. }
  376. type contextClient struct {
  377. *http.Client
  378. }
  379. func (c *contextClient) Get(ctx context.Context, url string) (*http.Response, error) {
  380. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  381. if err != nil {
  382. return nil, err
  383. }
  384. return c.Client.Do(req)
  385. }
  386. func (c *contextClient) Post(ctx context.Context, url, ctype string, data io.Reader) (*http.Response, error) {
  387. req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, data)
  388. if err != nil {
  389. return nil, err
  390. }
  391. req.Header.Set("Content-Type", ctype)
  392. return c.Client.Do(req)
  393. }
  394. func globalDiscoveryIdentity(addr string) string {
  395. return "global discovery server " + addr
  396. }
  397. func ipv4Identity(port int) string {
  398. return fmt.Sprintf("IPv4 local broadcast discovery on port %d", port)
  399. }
  400. func ipv6Identity(addr string) string {
  401. return fmt.Sprintf("IPv6 local multicast discovery on address %s", addr)
  402. }
  403. func http2EnabledTransport(t *http.Transport) *http.Transport {
  404. _ = http2.ConfigureTransport(t)
  405. return t
  406. }