global.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 http://mozilla.org/MPL/2.0/.
  6. package discover
  7. import (
  8. "bytes"
  9. "crypto/tls"
  10. "encoding/json"
  11. "errors"
  12. "io"
  13. "io/ioutil"
  14. "net/http"
  15. "net/url"
  16. "strconv"
  17. stdsync "sync"
  18. "time"
  19. "github.com/syncthing/syncthing/lib/dialer"
  20. "github.com/syncthing/syncthing/lib/events"
  21. "github.com/syncthing/syncthing/lib/protocol"
  22. )
  23. type globalClient struct {
  24. server string
  25. addrList AddressLister
  26. announceClient httpClient
  27. queryClient httpClient
  28. noAnnounce bool
  29. stop chan struct{}
  30. errorHolder
  31. }
  32. type httpClient interface {
  33. Get(url string) (*http.Response, error)
  34. Post(url, ctype string, data io.Reader) (*http.Response, error)
  35. }
  36. const (
  37. defaultReannounceInterval = 30 * time.Minute
  38. announceErrorRetryInterval = 5 * time.Minute
  39. requestTimeout = 5 * time.Second
  40. )
  41. type announcement struct {
  42. Addresses []string `json:"addresses"`
  43. }
  44. type serverOptions struct {
  45. insecure bool // don't check certificate
  46. noAnnounce bool // don't announce
  47. id string // expected server device ID
  48. }
  49. // A lookupError is any other error but with a cache validity time attached.
  50. type lookupError struct {
  51. error
  52. cacheFor time.Duration
  53. }
  54. func (e lookupError) CacheFor() time.Duration {
  55. return e.cacheFor
  56. }
  57. func NewGlobal(server string, cert tls.Certificate, addrList AddressLister) (FinderService, error) {
  58. server, opts, err := parseOptions(server)
  59. if err != nil {
  60. return nil, err
  61. }
  62. var devID protocol.DeviceID
  63. if opts.id != "" {
  64. devID, err = protocol.DeviceIDFromString(opts.id)
  65. if err != nil {
  66. return nil, err
  67. }
  68. }
  69. // The http.Client used for announcements. It needs to have our
  70. // certificate to prove our identity, and may or may not verify the server
  71. // certificate depending on the insecure setting.
  72. var announceClient httpClient = &http.Client{
  73. Timeout: requestTimeout,
  74. Transport: &http.Transport{
  75. Dial: dialer.Dial,
  76. Proxy: http.ProxyFromEnvironment,
  77. TLSClientConfig: &tls.Config{
  78. InsecureSkipVerify: opts.insecure,
  79. Certificates: []tls.Certificate{cert},
  80. },
  81. },
  82. }
  83. if opts.id != "" {
  84. announceClient = newIDCheckingHTTPClient(announceClient, devID)
  85. }
  86. // The http.Client used for queries. We don't need to present our
  87. // certificate here, so lets not include it. May be insecure if requested.
  88. var queryClient httpClient = &http.Client{
  89. Timeout: requestTimeout,
  90. Transport: &http.Transport{
  91. Dial: dialer.Dial,
  92. Proxy: http.ProxyFromEnvironment,
  93. TLSClientConfig: &tls.Config{
  94. InsecureSkipVerify: opts.insecure,
  95. },
  96. },
  97. }
  98. if opts.id != "" {
  99. queryClient = newIDCheckingHTTPClient(queryClient, devID)
  100. }
  101. cl := &globalClient{
  102. server: server,
  103. addrList: addrList,
  104. announceClient: announceClient,
  105. queryClient: queryClient,
  106. noAnnounce: opts.noAnnounce,
  107. stop: make(chan struct{}),
  108. }
  109. cl.setError(errors.New("not announced"))
  110. return cl, nil
  111. }
  112. // Lookup returns the list of addresses where the given device is available
  113. func (c *globalClient) Lookup(device protocol.DeviceID) (addresses []string, err error) {
  114. qURL, err := url.Parse(c.server)
  115. if err != nil {
  116. return nil, err
  117. }
  118. q := qURL.Query()
  119. q.Set("device", device.String())
  120. qURL.RawQuery = q.Encode()
  121. resp, err := c.queryClient.Get(qURL.String())
  122. if err != nil {
  123. l.Debugln("globalClient.Lookup", qURL, err)
  124. return nil, err
  125. }
  126. if resp.StatusCode != 200 {
  127. resp.Body.Close()
  128. l.Debugln("globalClient.Lookup", qURL, resp.Status)
  129. err := errors.New(resp.Status)
  130. if secs, atoiErr := strconv.Atoi(resp.Header.Get("Retry-After")); atoiErr == nil && secs > 0 {
  131. err = lookupError{
  132. error: err,
  133. cacheFor: time.Duration(secs) * time.Second,
  134. }
  135. }
  136. return nil, err
  137. }
  138. bs, err := ioutil.ReadAll(resp.Body)
  139. if err != nil {
  140. return nil, err
  141. }
  142. resp.Body.Close()
  143. var ann announcement
  144. err = json.Unmarshal(bs, &ann)
  145. return ann.Addresses, err
  146. }
  147. func (c *globalClient) String() string {
  148. return "global@" + c.server
  149. }
  150. func (c *globalClient) Serve() {
  151. if c.noAnnounce {
  152. // We're configured to not do announcements, only lookups. To maintain
  153. // the same interface, we just pause here if Serve() is run.
  154. <-c.stop
  155. return
  156. }
  157. timer := time.NewTimer(0)
  158. defer timer.Stop()
  159. eventSub := events.Default.Subscribe(events.ListenAddressesChanged)
  160. defer events.Default.Unsubscribe(eventSub)
  161. for {
  162. select {
  163. case <-eventSub.C():
  164. // Defer announcement by 2 seconds, essentially debouncing
  165. // if we have a stream of events incoming in quick succession.
  166. timer.Reset(2 * time.Second)
  167. case <-timer.C:
  168. c.sendAnnouncement(timer)
  169. case <-c.stop:
  170. return
  171. }
  172. }
  173. }
  174. func (c *globalClient) sendAnnouncement(timer *time.Timer) {
  175. var ann announcement
  176. if c.addrList != nil {
  177. ann.Addresses = c.addrList.ExternalAddresses()
  178. }
  179. if len(ann.Addresses) == 0 {
  180. c.setError(errors.New("nothing to announce"))
  181. l.Debugln("Nothing to announce")
  182. timer.Reset(announceErrorRetryInterval)
  183. return
  184. }
  185. // The marshal doesn't fail, I promise.
  186. postData, _ := json.Marshal(ann)
  187. l.Debugf("Announcement: %s", postData)
  188. resp, err := c.announceClient.Post(c.server, "application/json", bytes.NewReader(postData))
  189. if err != nil {
  190. l.Debugln("announce POST:", err)
  191. c.setError(err)
  192. timer.Reset(announceErrorRetryInterval)
  193. return
  194. }
  195. l.Debugln("announce POST:", resp.Status)
  196. resp.Body.Close()
  197. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  198. l.Debugln("announce POST:", resp.Status)
  199. c.setError(errors.New(resp.Status))
  200. if h := resp.Header.Get("Retry-After"); h != "" {
  201. // The server has a recommendation on when we should
  202. // retry. Follow it.
  203. if secs, err := strconv.Atoi(h); err == nil && secs > 0 {
  204. l.Debugln("announce Retry-After:", secs, err)
  205. timer.Reset(time.Duration(secs) * time.Second)
  206. return
  207. }
  208. }
  209. timer.Reset(announceErrorRetryInterval)
  210. return
  211. }
  212. c.setError(nil)
  213. if h := resp.Header.Get("Reannounce-After"); h != "" {
  214. // The server has a recommendation on when we should
  215. // reannounce. Follow it.
  216. if secs, err := strconv.Atoi(h); err == nil && secs > 0 {
  217. l.Debugln("announce Reannounce-After:", secs, err)
  218. timer.Reset(time.Duration(secs) * time.Second)
  219. return
  220. }
  221. }
  222. timer.Reset(defaultReannounceInterval)
  223. }
  224. func (c *globalClient) Stop() {
  225. close(c.stop)
  226. }
  227. func (c *globalClient) Cache() map[protocol.DeviceID]CacheEntry {
  228. // The globalClient doesn't do caching
  229. return nil
  230. }
  231. // parseOptions parses and strips away any ?query=val options, setting the
  232. // corresponding field in the serverOptions struct. Unknown query options are
  233. // ignored and removed.
  234. func parseOptions(dsn string) (server string, opts serverOptions, err error) {
  235. p, err := url.Parse(dsn)
  236. if err != nil {
  237. return "", serverOptions{}, err
  238. }
  239. // Grab known options from the query string
  240. q := p.Query()
  241. opts.id = q.Get("id")
  242. opts.insecure = opts.id != "" || queryBool(q, "insecure")
  243. opts.noAnnounce = queryBool(q, "noannounce")
  244. // Check for disallowed combinations
  245. if p.Scheme == "http" {
  246. if !opts.insecure {
  247. return "", serverOptions{}, errors.New("http without insecure not supported")
  248. }
  249. if !opts.noAnnounce {
  250. return "", serverOptions{}, errors.New("http without noannounce not supported")
  251. }
  252. } else if p.Scheme != "https" {
  253. return "", serverOptions{}, errors.New("unsupported scheme " + p.Scheme)
  254. }
  255. // Remove the query string
  256. p.RawQuery = ""
  257. server = p.String()
  258. return
  259. }
  260. // queryBool returns the query parameter parsed as a boolean. An empty value
  261. // ("?foo") is considered true, as is any value string except false
  262. // ("?foo=false").
  263. func queryBool(q url.Values, key string) bool {
  264. if _, ok := q[key]; !ok {
  265. return false
  266. }
  267. return q.Get(key) != "false"
  268. }
  269. type idCheckingHTTPClient struct {
  270. httpClient
  271. id protocol.DeviceID
  272. }
  273. func newIDCheckingHTTPClient(client httpClient, id protocol.DeviceID) *idCheckingHTTPClient {
  274. return &idCheckingHTTPClient{
  275. httpClient: client,
  276. id: id,
  277. }
  278. }
  279. func (c *idCheckingHTTPClient) check(resp *http.Response) error {
  280. if resp.TLS == nil {
  281. return errors.New("security: not TLS")
  282. }
  283. if len(resp.TLS.PeerCertificates) == 0 {
  284. return errors.New("security: no certificates")
  285. }
  286. id := protocol.NewDeviceID(resp.TLS.PeerCertificates[0].Raw)
  287. if !id.Equals(c.id) {
  288. return errors.New("security: incorrect device id")
  289. }
  290. return nil
  291. }
  292. func (c *idCheckingHTTPClient) Get(url string) (*http.Response, error) {
  293. resp, err := c.httpClient.Get(url)
  294. if err != nil {
  295. return nil, err
  296. }
  297. if err := c.check(resp); err != nil {
  298. return nil, err
  299. }
  300. return resp, nil
  301. }
  302. func (c *idCheckingHTTPClient) Post(url, ctype string, data io.Reader) (*http.Response, error) {
  303. resp, err := c.httpClient.Post(url, ctype, data)
  304. if err != nil {
  305. return nil, err
  306. }
  307. if err := c.check(resp); err != nil {
  308. return nil, err
  309. }
  310. return resp, nil
  311. }
  312. type errorHolder struct {
  313. err error
  314. mut stdsync.Mutex // uses stdlib sync as I want this to be trivially embeddable, and there is no risk of blocking
  315. }
  316. func (e *errorHolder) setError(err error) {
  317. e.mut.Lock()
  318. e.err = err
  319. e.mut.Unlock()
  320. }
  321. func (e *errorHolder) Error() error {
  322. e.mut.Lock()
  323. err := e.err
  324. e.mut.Unlock()
  325. return err
  326. }