static.go 5.5 KB

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