relay.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 relay
  7. import (
  8. "crypto/tls"
  9. "net/url"
  10. "sort"
  11. "time"
  12. "github.com/syncthing/syncthing/lib/config"
  13. "github.com/syncthing/syncthing/lib/events"
  14. "github.com/syncthing/syncthing/lib/relay/client"
  15. "github.com/syncthing/syncthing/lib/relay/protocol"
  16. "github.com/syncthing/syncthing/lib/sync"
  17. "github.com/thejerf/suture"
  18. )
  19. const (
  20. eventBroadcasterCheckInterval = 10 * time.Second
  21. )
  22. type Svc struct {
  23. *suture.Supervisor
  24. cfg *config.Wrapper
  25. tlsCfg *tls.Config
  26. tokens map[string]suture.ServiceToken
  27. clients map[string]client.RelayClient
  28. mut sync.RWMutex
  29. invitations chan protocol.SessionInvitation
  30. conns chan *tls.Conn
  31. }
  32. func NewSvc(cfg *config.Wrapper, tlsCfg *tls.Config) *Svc {
  33. conns := make(chan *tls.Conn)
  34. svc := &Svc{
  35. Supervisor: suture.New("Svc", suture.Spec{
  36. Log: func(log string) {
  37. l.Debugln(log)
  38. },
  39. FailureBackoff: 5 * time.Minute,
  40. FailureDecay: float64((10 * time.Minute) / time.Second),
  41. FailureThreshold: 5,
  42. }),
  43. cfg: cfg,
  44. tlsCfg: tlsCfg,
  45. tokens: make(map[string]suture.ServiceToken),
  46. clients: make(map[string]client.RelayClient),
  47. mut: sync.NewRWMutex(),
  48. invitations: make(chan protocol.SessionInvitation),
  49. conns: conns,
  50. }
  51. rcfg := cfg.Raw()
  52. svc.CommitConfiguration(rcfg, rcfg)
  53. cfg.Subscribe(svc)
  54. receiver := &invitationReceiver{
  55. tlsCfg: tlsCfg,
  56. conns: conns,
  57. invitations: svc.invitations,
  58. stop: make(chan struct{}),
  59. }
  60. eventBc := &eventBroadcaster{
  61. svc: svc,
  62. stop: make(chan struct{}),
  63. }
  64. svc.Add(receiver)
  65. svc.Add(eventBc)
  66. return svc
  67. }
  68. func (s *Svc) VerifyConfiguration(from, to config.Configuration) error {
  69. for _, addr := range to.Options.RelayServers {
  70. _, err := url.Parse(addr)
  71. if err != nil {
  72. return err
  73. }
  74. }
  75. return nil
  76. }
  77. func (s *Svc) CommitConfiguration(from, to config.Configuration) bool {
  78. existing := make(map[string]*url.URL, len(to.Options.RelayServers))
  79. for _, addr := range to.Options.RelayServers {
  80. uri, err := url.Parse(addr)
  81. if err != nil {
  82. l.Debugln("Failed to parse relay address", addr, err)
  83. continue
  84. }
  85. existing[uri.String()] = uri
  86. }
  87. s.mut.Lock()
  88. for key, uri := range existing {
  89. _, ok := s.tokens[key]
  90. if !ok {
  91. l.Debugln("Connecting to relay", uri)
  92. c, err := client.NewClient(uri, s.tlsCfg.Certificates, s.invitations, 10*time.Second)
  93. if err != nil {
  94. l.Debugln("Failed to connect to relay", uri, err)
  95. continue
  96. }
  97. s.tokens[key] = s.Add(c)
  98. s.clients[key] = c
  99. }
  100. }
  101. for key, token := range s.tokens {
  102. _, ok := existing[key]
  103. if !ok {
  104. err := s.Remove(token)
  105. delete(s.tokens, key)
  106. delete(s.clients, key)
  107. l.Debugln("Disconnecting from relay", key, err)
  108. }
  109. }
  110. s.mut.Unlock()
  111. return true
  112. }
  113. type Status struct {
  114. URL string
  115. OK bool
  116. Latency int
  117. }
  118. // Relays return the list of relays that currently have an OK status.
  119. func (s *Svc) Relays() []string {
  120. if s == nil {
  121. // A nil client does not have a status, really. Yet we may be called
  122. // this way, for raisins...
  123. return nil
  124. }
  125. s.mut.RLock()
  126. relays := make([]string, 0, len(s.clients))
  127. for _, client := range s.clients {
  128. relays = append(relays, client.URI().String())
  129. }
  130. s.mut.RUnlock()
  131. sort.Strings(relays)
  132. return relays
  133. }
  134. // RelayStatus returns the latency and OK status for a given relay.
  135. func (s *Svc) RelayStatus(uri string) (time.Duration, bool) {
  136. if s == nil {
  137. // A nil client does not have a status, really. Yet we may be called
  138. // this way, for raisins...
  139. return time.Hour, false
  140. }
  141. s.mut.RLock()
  142. defer s.mut.RUnlock()
  143. for _, client := range s.clients {
  144. if client.URI().String() == uri {
  145. return client.Latency(), client.StatusOK()
  146. }
  147. }
  148. return time.Hour, false
  149. }
  150. // Accept returns a new *tls.Conn. The connection is already handshaken.
  151. func (s *Svc) Accept() *tls.Conn {
  152. return <-s.conns
  153. }
  154. type invitationReceiver struct {
  155. invitations chan protocol.SessionInvitation
  156. tlsCfg *tls.Config
  157. conns chan<- *tls.Conn
  158. stop chan struct{}
  159. }
  160. func (r *invitationReceiver) Serve() {
  161. for {
  162. select {
  163. case inv := <-r.invitations:
  164. l.Debugln("Received relay invitation", inv)
  165. conn, err := client.JoinSession(inv)
  166. if err != nil {
  167. l.Debugf("Failed to join relay session %s: %v", inv, err)
  168. continue
  169. }
  170. var tc *tls.Conn
  171. if inv.ServerSocket {
  172. tc = tls.Server(conn, r.tlsCfg)
  173. } else {
  174. tc = tls.Client(conn, r.tlsCfg)
  175. }
  176. err = tc.Handshake()
  177. if err != nil {
  178. l.Infof("TLS handshake (BEP/relay %s): %v", inv, err)
  179. tc.Close()
  180. continue
  181. }
  182. r.conns <- tc
  183. case <-r.stop:
  184. return
  185. }
  186. }
  187. }
  188. func (r *invitationReceiver) Stop() {
  189. close(r.stop)
  190. }
  191. // The eventBroadcaster sends a RelayStateChanged event when the relay status
  192. // changes. We need this somewhat ugly polling mechanism as there's currently
  193. // no way to get the event feed directly from the relay lib. This may be
  194. // something to revisit later, possibly.
  195. type eventBroadcaster struct {
  196. svc *Svc
  197. stop chan struct{}
  198. }
  199. func (e *eventBroadcaster) Serve() {
  200. timer := time.NewTicker(eventBroadcasterCheckInterval)
  201. defer timer.Stop()
  202. var prevOKRelays []string
  203. for {
  204. select {
  205. case <-timer.C:
  206. curOKRelays := e.svc.Relays()
  207. changed := len(curOKRelays) != len(prevOKRelays)
  208. if !changed {
  209. for i := range curOKRelays {
  210. if curOKRelays[i] != prevOKRelays[i] {
  211. changed = true
  212. break
  213. }
  214. }
  215. }
  216. if changed {
  217. events.Default.Log(events.RelayStateChanged, map[string][]string{
  218. "old": prevOKRelays,
  219. "new": curOKRelays,
  220. })
  221. }
  222. prevOKRelays = curOKRelays
  223. case <-e.stop:
  224. return
  225. }
  226. }
  227. }
  228. func (e *eventBroadcaster) Stop() {
  229. close(e.stop)
  230. }