static.go 5.5 KB

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