static.go 5.6 KB

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