static.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package client
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "net"
  10. "net/url"
  11. "time"
  12. "github.com/syncthing/syncthing/internal/slogutil"
  13. "github.com/syncthing/syncthing/lib/dialer"
  14. "github.com/syncthing/syncthing/lib/osutil"
  15. syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
  16. "github.com/syncthing/syncthing/lib/relay/protocol"
  17. )
  18. type staticClient struct {
  19. commonClient
  20. uri *url.URL
  21. config *tls.Config
  22. messageTimeout time.Duration
  23. connectTimeout time.Duration
  24. conn *tls.Conn
  25. token string
  26. }
  27. func newStaticClient(uri *url.URL, certs []tls.Certificate, invitations chan protocol.SessionInvitation, timeout time.Duration) *staticClient {
  28. c := &staticClient{
  29. uri: uri,
  30. config: configForCerts(certs),
  31. messageTimeout: time.Minute * 2,
  32. connectTimeout: timeout,
  33. token: uri.Query().Get("token"),
  34. }
  35. c.commonClient = newCommonClient(invitations, c.serve, c.String())
  36. return c
  37. }
  38. func (c *staticClient) serve(ctx context.Context) error {
  39. if err := c.connect(ctx); err != nil {
  40. l.Debugf("Could not connect to relay %s: %s", c.uri, err)
  41. return err
  42. }
  43. l.Debugln(c, "connected", c.conn.RemoteAddr())
  44. defer c.disconnect()
  45. if err := c.join(); err != nil {
  46. l.Debugf("Could not join relay %s: %s", c.uri, err)
  47. return err
  48. }
  49. if err := c.conn.SetDeadline(time.Time{}); err != nil {
  50. l.Debugln("Relay set deadline:", err)
  51. return err
  52. }
  53. slog.InfoContext(ctx, "Joined relay", slogutil.URI(fmt.Sprintf("%s://%s", c.uri.Scheme, c.uri.Host)))
  54. messages := make(chan interface{})
  55. errorsc := make(chan error, 1)
  56. go messageReader(ctx, c.conn, messages, errorsc)
  57. timeout := time.NewTimer(c.messageTimeout)
  58. for {
  59. select {
  60. case message := <-messages:
  61. timeout.Reset(c.messageTimeout)
  62. l.Debugf("%s received message %T", c, message)
  63. switch msg := message.(type) {
  64. case protocol.Ping:
  65. if err := protocol.WriteMessage(c.conn, protocol.Pong{}); err != nil {
  66. l.Debugln("Relay write:", err)
  67. return err
  68. }
  69. l.Debugln(c, "sent pong")
  70. case protocol.SessionInvitation:
  71. ip := net.IP(msg.Address)
  72. if len(ip) == 0 || ip.IsUnspecified() {
  73. msg.Address, _ = osutil.IPFromAddr(c.conn.RemoteAddr())
  74. }
  75. select {
  76. case c.invitations <- msg:
  77. case <-ctx.Done():
  78. l.Debugln(c, "stopping")
  79. return ctx.Err()
  80. }
  81. case protocol.RelayFull:
  82. l.Debugf("Disconnected from relay %s due to it becoming full.", c.uri)
  83. return errors.New("relay full")
  84. default:
  85. l.Debugf("Relay: protocol error: unexpected message %v", msg)
  86. return fmt.Errorf("protocol error: unexpected message %v", msg)
  87. }
  88. case <-ctx.Done():
  89. l.Debugln(c, "stopping")
  90. return ctx.Err()
  91. case err := <-errorsc:
  92. l.Debugf("Disconnecting from relay %s due to error: %s", c.uri, err)
  93. return err
  94. case <-timeout.C:
  95. l.Debugln(c, "timed out")
  96. return errors.New("timed out")
  97. }
  98. }
  99. }
  100. func (c *staticClient) String() string {
  101. return fmt.Sprintf("StaticClient:%p@%s", c, c.URI())
  102. }
  103. func (c *staticClient) URI() *url.URL {
  104. return c.uri
  105. }
  106. func (c *staticClient) connect(ctx context.Context) error {
  107. if c.uri.Scheme != "relay" {
  108. return fmt.Errorf("unsupported relay scheme: %v", c.uri.Scheme)
  109. }
  110. timeoutCtx, cancel := context.WithTimeout(ctx, c.connectTimeout)
  111. defer cancel()
  112. tcpConn, err := dialer.DialContext(timeoutCtx, "tcp", c.uri.Host)
  113. if err != nil {
  114. return err
  115. }
  116. // Copy the TLS config and set the server name we're connecting to. In
  117. // many cases this will be an IP address, in which case it's a no-op. In
  118. // other cases it will be a hostname, which will cause the TLS stack to
  119. // send SNI.
  120. cfg := c.config
  121. if host, _, err := net.SplitHostPort(c.uri.Host); err == nil {
  122. cfg = cfg.Clone()
  123. cfg.ServerName = host
  124. }
  125. conn := tls.Client(tcpConn, cfg)
  126. if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
  127. conn.Close()
  128. return err
  129. }
  130. if err := performHandshakeAndValidation(conn, c.uri); err != nil {
  131. conn.Close()
  132. return err
  133. }
  134. c.conn = conn
  135. return nil
  136. }
  137. func (c *staticClient) disconnect() {
  138. l.Debugln(c, "disconnecting")
  139. c.conn.Close()
  140. }
  141. func (c *staticClient) join() error {
  142. if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{Token: c.token}); err != nil {
  143. return err
  144. }
  145. message, err := protocol.ReadMessage(c.conn)
  146. if err != nil {
  147. return err
  148. }
  149. switch msg := message.(type) {
  150. case protocol.Response:
  151. if msg.Code != 0 {
  152. return &incorrectResponseCodeErr{msg.Code, msg.Message}
  153. }
  154. case protocol.RelayFull:
  155. return errors.New("relay full")
  156. default:
  157. return fmt.Errorf("protocol error: expecting response got %v", msg)
  158. }
  159. return nil
  160. }
  161. func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
  162. if err := conn.Handshake(); err != nil {
  163. return err
  164. }
  165. cs := conn.ConnectionState()
  166. if cs.NegotiatedProtocol != protocol.ProtocolName {
  167. return errors.New("protocol negotiation error")
  168. }
  169. q := uri.Query()
  170. relayIDs := q.Get("id")
  171. if relayIDs != "" {
  172. relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
  173. if err != nil {
  174. return fmt.Errorf("relay address contains invalid verification id: %w", err)
  175. }
  176. certs := cs.PeerCertificates
  177. if cl := len(certs); cl != 1 {
  178. return fmt.Errorf("unexpected certificate count: %d", cl)
  179. }
  180. remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
  181. if remoteID != relayID {
  182. return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
  183. }
  184. }
  185. return nil
  186. }
  187. func messageReader(ctx context.Context, conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  188. for {
  189. msg, err := protocol.ReadMessage(conn)
  190. if err != nil {
  191. errors <- err
  192. return
  193. }
  194. select {
  195. case messages <- msg:
  196. case <-ctx.Done():
  197. return
  198. }
  199. }
  200. }