static.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package client
  3. import (
  4. "crypto/tls"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "time"
  9. "github.com/syncthing/syncthing/lib/dialer"
  10. syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
  11. "github.com/syncthing/syncthing/lib/relay/protocol"
  12. "github.com/syncthing/syncthing/lib/sync"
  13. )
  14. type staticClient struct {
  15. uri *url.URL
  16. invitations chan protocol.SessionInvitation
  17. closeInvitationsOnFinish bool
  18. config *tls.Config
  19. messageTimeout time.Duration
  20. connectTimeout time.Duration
  21. stop chan struct{}
  22. stopped chan struct{}
  23. conn *tls.Conn
  24. mut sync.RWMutex
  25. connected bool
  26. latency time.Duration
  27. }
  28. func newStaticClient(uri *url.URL, certs []tls.Certificate, invitations chan protocol.SessionInvitation, timeout time.Duration) RelayClient {
  29. closeInvitationsOnFinish := false
  30. if invitations == nil {
  31. closeInvitationsOnFinish = true
  32. invitations = make(chan protocol.SessionInvitation)
  33. }
  34. return &staticClient{
  35. uri: uri,
  36. invitations: invitations,
  37. closeInvitationsOnFinish: closeInvitationsOnFinish,
  38. config: configForCerts(certs),
  39. messageTimeout: time.Minute * 2,
  40. connectTimeout: timeout,
  41. stop: make(chan struct{}),
  42. stopped: make(chan struct{}),
  43. mut: sync.NewRWMutex(),
  44. connected: false,
  45. }
  46. }
  47. func (c *staticClient) Serve() {
  48. c.stop = make(chan struct{})
  49. c.stopped = make(chan struct{})
  50. defer close(c.stopped)
  51. if err := c.connect(); err != nil {
  52. l.Infof("Could not connect to relay %s: %s", c.uri, err)
  53. return
  54. }
  55. l.Debugln(c, "connected", c.conn.RemoteAddr())
  56. if err := c.join(); err != nil {
  57. c.conn.Close()
  58. l.Infof("Could not join relay %s: %s", c.uri, err)
  59. return
  60. }
  61. if err := c.conn.SetDeadline(time.Time{}); err != nil {
  62. c.conn.Close()
  63. l.Infoln("Relay set deadline:", err)
  64. return
  65. }
  66. l.Infoln("Joined relay", c.uri)
  67. c.mut.Lock()
  68. c.connected = true
  69. c.mut.Unlock()
  70. messages := make(chan interface{})
  71. errors := make(chan error, 1)
  72. go messageReader(c.conn, messages, errors)
  73. timeout := time.NewTimer(c.messageTimeout)
  74. for {
  75. select {
  76. case message := <-messages:
  77. timeout.Reset(c.messageTimeout)
  78. l.Debugf("%s received message %T", c, message)
  79. switch msg := message.(type) {
  80. case protocol.Ping:
  81. if err := protocol.WriteMessage(c.conn, protocol.Pong{}); err != nil {
  82. l.Infoln("Relay write:", err)
  83. c.disconnect()
  84. } else {
  85. l.Debugln(c, "sent pong")
  86. }
  87. case protocol.SessionInvitation:
  88. ip := net.IP(msg.Address)
  89. if len(ip) == 0 || ip.IsUnspecified() {
  90. msg.Address = c.conn.RemoteAddr().(*net.TCPAddr).IP[:]
  91. }
  92. c.invitations <- msg
  93. case protocol.RelayFull:
  94. l.Infof("Disconnected from relay %s due to it becoming full.", c.uri)
  95. c.disconnect()
  96. default:
  97. l.Infoln("Relay: protocol error: unexpected message %v", msg)
  98. c.disconnect()
  99. }
  100. case <-c.stop:
  101. l.Debugln(c, "stopping")
  102. c.disconnect()
  103. // We always exit via this branch of the select, to make sure the
  104. // the reader routine exits.
  105. case err := <-errors:
  106. close(errors)
  107. close(messages)
  108. c.mut.Lock()
  109. if c.connected {
  110. c.conn.Close()
  111. c.connected = false
  112. l.Infof("Disconnecting from relay %s due to error: %s", c.uri, err)
  113. }
  114. if c.closeInvitationsOnFinish {
  115. close(c.invitations)
  116. c.invitations = make(chan protocol.SessionInvitation)
  117. }
  118. c.mut.Unlock()
  119. return
  120. case <-timeout.C:
  121. l.Debugln(c, "timed out")
  122. c.disconnect()
  123. }
  124. }
  125. }
  126. func (c *staticClient) Stop() {
  127. if c.stop == nil {
  128. return
  129. }
  130. close(c.stop)
  131. <-c.stopped
  132. }
  133. func (c *staticClient) StatusOK() bool {
  134. c.mut.RLock()
  135. con := c.connected
  136. c.mut.RUnlock()
  137. return con
  138. }
  139. func (c *staticClient) Latency() time.Duration {
  140. c.mut.RLock()
  141. lat := c.latency
  142. c.mut.RUnlock()
  143. return lat
  144. }
  145. func (c *staticClient) String() string {
  146. return fmt.Sprintf("StaticClient:%p@%s", c, c.URI())
  147. }
  148. func (c *staticClient) URI() *url.URL {
  149. return c.uri
  150. }
  151. func (c *staticClient) Invitations() chan protocol.SessionInvitation {
  152. c.mut.RLock()
  153. inv := c.invitations
  154. c.mut.RUnlock()
  155. return inv
  156. }
  157. func (c *staticClient) connect() error {
  158. if c.uri.Scheme != "relay" {
  159. return fmt.Errorf("Unsupported relay schema: %v", c.uri.Scheme)
  160. }
  161. t0 := time.Now()
  162. tcpConn, err := dialer.DialTimeout("tcp", c.uri.Host, c.connectTimeout)
  163. if err != nil {
  164. return err
  165. }
  166. c.mut.Lock()
  167. c.latency = time.Since(t0)
  168. c.mut.Unlock()
  169. conn := tls.Client(tcpConn, c.config)
  170. if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
  171. conn.Close()
  172. return err
  173. }
  174. if err := performHandshakeAndValidation(conn, c.uri); err != nil {
  175. conn.Close()
  176. return err
  177. }
  178. c.conn = conn
  179. return nil
  180. }
  181. func (c *staticClient) disconnect() {
  182. l.Debugln(c, "disconnecting")
  183. c.mut.Lock()
  184. c.connected = false
  185. c.mut.Unlock()
  186. c.conn.Close()
  187. }
  188. func (c *staticClient) join() error {
  189. if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{}); err != nil {
  190. return err
  191. }
  192. message, err := protocol.ReadMessage(c.conn)
  193. if err != nil {
  194. return err
  195. }
  196. switch msg := message.(type) {
  197. case protocol.Response:
  198. if msg.Code != 0 {
  199. return fmt.Errorf("Incorrect response code %d: %s", msg.Code, msg.Message)
  200. }
  201. case protocol.RelayFull:
  202. return fmt.Errorf("relay full")
  203. default:
  204. return fmt.Errorf("protocol error: expecting response got %v", msg)
  205. }
  206. return nil
  207. }
  208. func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
  209. if err := conn.Handshake(); err != nil {
  210. return err
  211. }
  212. cs := conn.ConnectionState()
  213. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
  214. return fmt.Errorf("protocol negotiation error")
  215. }
  216. q := uri.Query()
  217. relayIDs := q.Get("id")
  218. if relayIDs != "" {
  219. relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
  220. if err != nil {
  221. return fmt.Errorf("relay address contains invalid verification id: %s", err)
  222. }
  223. certs := cs.PeerCertificates
  224. if cl := len(certs); cl != 1 {
  225. return fmt.Errorf("unexpected certificate count: %d", cl)
  226. }
  227. remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
  228. if remoteID != relayID {
  229. return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
  230. }
  231. }
  232. return nil
  233. }
  234. func messageReader(conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  235. for {
  236. msg, err := protocol.ReadMessage(conn)
  237. if err != nil {
  238. errors <- err
  239. return
  240. }
  241. messages <- msg
  242. }
  243. }