global.go 9.1 KB

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