global.go 12 KB

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