static.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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.Debugln("Relay connect:", 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.Infoln("Relay join:", 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.Debugln(c, "joined", c.conn.RemoteAddr(), "via", c.conn.LocalAddr())
  67. defer c.cleanup()
  68. c.mut.Lock()
  69. c.connected = true
  70. c.mut.Unlock()
  71. messages := make(chan interface{})
  72. errors := make(chan error, 1)
  73. go messageReader(c.conn, messages, errors)
  74. timeout := time.NewTimer(c.messageTimeout)
  75. for {
  76. select {
  77. case message := <-messages:
  78. timeout.Reset(c.messageTimeout)
  79. l.Debugf("%s received message %T", c, message)
  80. switch msg := message.(type) {
  81. case protocol.Ping:
  82. if err := protocol.WriteMessage(c.conn, protocol.Pong{}); err != nil {
  83. l.Infoln("Relay write:", err)
  84. return
  85. }
  86. l.Debugln(c, "sent pong")
  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.Infoln("Disconnected from relay due to it becoming full.")
  95. return
  96. default:
  97. l.Infoln("Relay: protocol error: unexpected message %v", msg)
  98. return
  99. }
  100. case <-c.stop:
  101. l.Debugln(c, "stopping")
  102. return
  103. case err := <-errors:
  104. l.Infoln("Relay received:", err)
  105. return
  106. case <-timeout.C:
  107. l.Debugln(c, "timed out")
  108. return
  109. }
  110. }
  111. }
  112. func (c *staticClient) Stop() {
  113. if c.stop == nil {
  114. return
  115. }
  116. close(c.stop)
  117. <-c.stopped
  118. }
  119. func (c *staticClient) StatusOK() bool {
  120. c.mut.RLock()
  121. con := c.connected
  122. c.mut.RUnlock()
  123. return con
  124. }
  125. func (c *staticClient) Latency() time.Duration {
  126. c.mut.RLock()
  127. lat := c.latency
  128. c.mut.RUnlock()
  129. return lat
  130. }
  131. func (c *staticClient) String() string {
  132. return fmt.Sprintf("StaticClient:%p@%s", c, c.URI())
  133. }
  134. func (c *staticClient) URI() *url.URL {
  135. return c.uri
  136. }
  137. func (c *staticClient) Invitations() chan protocol.SessionInvitation {
  138. c.mut.RLock()
  139. inv := c.invitations
  140. c.mut.RUnlock()
  141. return inv
  142. }
  143. func (c *staticClient) connect() error {
  144. if c.uri.Scheme != "relay" {
  145. return fmt.Errorf("Unsupported relay schema: %v", c.uri.Scheme)
  146. }
  147. t0 := time.Now()
  148. tcpConn, err := dialer.DialTimeout("tcp", c.uri.Host, c.connectTimeout)
  149. if err != nil {
  150. return err
  151. }
  152. c.mut.Lock()
  153. c.latency = time.Since(t0)
  154. c.mut.Unlock()
  155. conn := tls.Client(tcpConn, c.config)
  156. if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
  157. conn.Close()
  158. return err
  159. }
  160. if err := performHandshakeAndValidation(conn, c.uri); err != nil {
  161. conn.Close()
  162. return err
  163. }
  164. c.conn = conn
  165. return nil
  166. }
  167. func (c *staticClient) cleanup() {
  168. l.Debugln(c, "cleaning up")
  169. c.mut.Lock()
  170. if c.closeInvitationsOnFinish {
  171. close(c.invitations)
  172. c.invitations = make(chan protocol.SessionInvitation)
  173. }
  174. c.connected = false
  175. c.mut.Unlock()
  176. c.conn.Close()
  177. }
  178. func (c *staticClient) join() error {
  179. if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{}); err != nil {
  180. return err
  181. }
  182. message, err := protocol.ReadMessage(c.conn)
  183. if err != nil {
  184. return err
  185. }
  186. switch msg := message.(type) {
  187. case protocol.Response:
  188. if msg.Code != 0 {
  189. return fmt.Errorf("Incorrect response code %d: %s", msg.Code, msg.Message)
  190. }
  191. case protocol.RelayFull:
  192. return fmt.Errorf("relay full")
  193. default:
  194. return fmt.Errorf("protocol error: expecting response got %v", msg)
  195. }
  196. return nil
  197. }
  198. func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
  199. if err := conn.Handshake(); err != nil {
  200. return err
  201. }
  202. cs := conn.ConnectionState()
  203. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
  204. return fmt.Errorf("protocol negotiation error")
  205. }
  206. q := uri.Query()
  207. relayIDs := q.Get("id")
  208. if relayIDs != "" {
  209. relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
  210. if err != nil {
  211. return fmt.Errorf("relay address contains invalid verification id: %s", err)
  212. }
  213. certs := cs.PeerCertificates
  214. if cl := len(certs); cl != 1 {
  215. return fmt.Errorf("unexpected certificate count: %d", cl)
  216. }
  217. remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
  218. if remoteID != relayID {
  219. return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
  220. }
  221. }
  222. return nil
  223. }
  224. func messageReader(conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  225. for {
  226. msg, err := protocol.ReadMessage(conn)
  227. if err != nil {
  228. errors <- err
  229. return
  230. }
  231. messages <- msg
  232. }
  233. }