global.go 12 KB

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