static.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package client
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. "net"
  8. "net/url"
  9. "time"
  10. "github.com/pkg/errors"
  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. conn := tls.Client(tcpConn, c.config)
  112. if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
  113. conn.Close()
  114. return err
  115. }
  116. if err := performHandshakeAndValidation(conn, c.uri); err != nil {
  117. conn.Close()
  118. return err
  119. }
  120. c.conn = conn
  121. return nil
  122. }
  123. func (c *staticClient) disconnect() {
  124. l.Debugln(c, "disconnecting")
  125. c.conn.Close()
  126. }
  127. func (c *staticClient) join() error {
  128. if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{}); err != nil {
  129. return err
  130. }
  131. message, err := protocol.ReadMessage(c.conn)
  132. if err != nil {
  133. return err
  134. }
  135. switch msg := message.(type) {
  136. case protocol.Response:
  137. if msg.Code != 0 {
  138. return &incorrectResponseCodeErr{msg.Code, msg.Message}
  139. }
  140. case protocol.RelayFull:
  141. return errors.New("relay full")
  142. default:
  143. return fmt.Errorf("protocol error: expecting response got %v", msg)
  144. }
  145. return nil
  146. }
  147. func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
  148. if err := conn.Handshake(); err != nil {
  149. return err
  150. }
  151. cs := conn.ConnectionState()
  152. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
  153. return errors.New("protocol negotiation error")
  154. }
  155. q := uri.Query()
  156. relayIDs := q.Get("id")
  157. if relayIDs != "" {
  158. relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
  159. if err != nil {
  160. return errors.Wrap(err, "relay address contains invalid verification id")
  161. }
  162. certs := cs.PeerCertificates
  163. if cl := len(certs); cl != 1 {
  164. return fmt.Errorf("unexpected certificate count: %d", cl)
  165. }
  166. remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
  167. if remoteID != relayID {
  168. return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
  169. }
  170. }
  171. return nil
  172. }
  173. func messageReader(ctx context.Context, conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  174. for {
  175. msg, err := protocol.ReadMessage(conn)
  176. if err != nil {
  177. errors <- err
  178. return
  179. }
  180. select {
  181. case messages <- msg:
  182. case <-ctx.Done():
  183. return
  184. }
  185. }
  186. }