relay_listen.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // Copyright (C) 2016 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 connections
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "errors"
  11. "net/url"
  12. "sync"
  13. "time"
  14. "github.com/syncthing/syncthing/lib/config"
  15. "github.com/syncthing/syncthing/lib/connections/registry"
  16. "github.com/syncthing/syncthing/lib/dialer"
  17. "github.com/syncthing/syncthing/lib/nat"
  18. "github.com/syncthing/syncthing/lib/relay/client"
  19. "github.com/syncthing/syncthing/lib/svcutil"
  20. )
  21. func init() {
  22. factory := &relayListenerFactory{}
  23. listeners["relay"] = factory
  24. listeners["dynamic+http"] = factory
  25. listeners["dynamic+https"] = factory
  26. }
  27. type relayListener struct {
  28. svcutil.ServiceWithError
  29. onAddressesChangedNotifier
  30. uri *url.URL
  31. cfg config.Wrapper
  32. tlsCfg *tls.Config
  33. conns chan internalConn
  34. factory listenerFactory
  35. client client.RelayClient
  36. mut sync.RWMutex
  37. }
  38. func (t *relayListener) serve(ctx context.Context) error {
  39. clnt, err := client.NewClient(t.uri, t.tlsCfg.Certificates, 10*time.Second)
  40. if err != nil {
  41. l.Infoln("Listen (BEP/relay):", err)
  42. return err
  43. }
  44. t.mut.Lock()
  45. t.client = clnt
  46. t.mut.Unlock()
  47. l.Infof("Relay listener (%v) starting", t)
  48. defer l.Infof("Relay listener (%v) shutting down", t)
  49. defer t.clearAddresses(t)
  50. invitationCtx, cancel := context.WithCancel(ctx)
  51. defer cancel()
  52. go t.handleInvitations(invitationCtx, clnt)
  53. return clnt.Serve(ctx)
  54. }
  55. func (t *relayListener) handleInvitations(ctx context.Context, clnt client.RelayClient) {
  56. invitations := clnt.Invitations()
  57. // Start with nil, so that we send a addresses changed notification as soon as we connect somewhere.
  58. var oldURI *url.URL
  59. for {
  60. select {
  61. case inv := <-invitations:
  62. conn, err := client.JoinSession(ctx, inv)
  63. if err != nil {
  64. if !errors.Is(err, context.Canceled) {
  65. l.Infoln("Listen (BEP/relay): joining session:", err)
  66. }
  67. continue
  68. }
  69. err = dialer.SetTCPOptions(conn)
  70. if err != nil {
  71. l.Debugln("Listen (BEP/relay): setting tcp options:", err)
  72. }
  73. err = dialer.SetTrafficClass(conn, t.cfg.Options().TrafficClass)
  74. if err != nil {
  75. l.Debugln("Listen (BEP/relay): setting traffic class:", err)
  76. }
  77. var tc *tls.Conn
  78. if inv.ServerSocket {
  79. tc = tls.Server(conn, t.tlsCfg)
  80. } else {
  81. tc = tls.Client(conn, t.tlsCfg)
  82. }
  83. err = tlsTimedHandshake(tc)
  84. if err != nil {
  85. tc.Close()
  86. l.Infoln("Listen (BEP/relay): TLS handshake:", err)
  87. continue
  88. }
  89. t.conns <- newInternalConn(tc, connTypeRelayServer, false, t.cfg.Options().ConnectionPriorityRelay)
  90. // Poor mans notifier that informs the connection service that the
  91. // relay URI has changed. This can only happen when we connect to a
  92. // relay via dynamic+http(s) pool, which upon a relay failing/dropping
  93. // us, would pick a different one.
  94. case <-time.After(10 * time.Second):
  95. currentURI := clnt.URI()
  96. if currentURI != oldURI {
  97. oldURI = currentURI
  98. t.notifyAddressesChanged(t)
  99. }
  100. case <-ctx.Done():
  101. return
  102. }
  103. }
  104. }
  105. func (t *relayListener) URI() *url.URL {
  106. return t.uri
  107. }
  108. func (t *relayListener) WANAddresses() []*url.URL {
  109. t.mut.RLock()
  110. client := t.client
  111. t.mut.RUnlock()
  112. if client == nil {
  113. return nil
  114. }
  115. curi := client.URI()
  116. if curi == nil {
  117. return nil
  118. }
  119. return []*url.URL{curi}
  120. }
  121. func (t *relayListener) LANAddresses() []*url.URL {
  122. return t.WANAddresses()
  123. }
  124. func (t *relayListener) Error() error {
  125. err := t.ServiceWithError.Error()
  126. if err != nil {
  127. return err
  128. }
  129. t.mut.RLock()
  130. defer t.mut.RUnlock()
  131. if t.client != nil {
  132. return t.client.Error()
  133. }
  134. return nil
  135. }
  136. func (t *relayListener) Factory() listenerFactory {
  137. return t.factory
  138. }
  139. func (t *relayListener) String() string {
  140. return t.uri.String()
  141. }
  142. func (*relayListener) NATType() string {
  143. return "unknown"
  144. }
  145. type relayListenerFactory struct{}
  146. func (f *relayListenerFactory) New(uri *url.URL, cfg config.Wrapper, tlsCfg *tls.Config, conns chan internalConn, _ *nat.Service, _ *registry.Registry, _ *lanChecker) genericListener {
  147. t := &relayListener{
  148. uri: uri,
  149. cfg: cfg,
  150. tlsCfg: tlsCfg,
  151. conns: conns,
  152. factory: f,
  153. }
  154. t.ServiceWithError = svcutil.AsService(t.serve, t.String())
  155. return t
  156. }
  157. func (relayListenerFactory) Valid(cfg config.Configuration) error {
  158. if !cfg.Options.RelaysEnabled {
  159. return errDisabled
  160. }
  161. return nil
  162. }