listener.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors.
  2. package main
  3. import (
  4. "crypto/tls"
  5. "encoding/hex"
  6. "log"
  7. "net"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
  12. "github.com/syncthing/syncthing/lib/tlsutil"
  13. "github.com/syncthing/syncthing/lib/relay/protocol"
  14. )
  15. var (
  16. outboxesMut = sync.RWMutex{}
  17. outboxes = make(map[syncthingprotocol.DeviceID]chan interface{})
  18. numConnections int64
  19. )
  20. func listener(_, addr string, config *tls.Config, token string) {
  21. tcpListener, err := net.Listen("tcp", addr)
  22. if err != nil {
  23. log.Fatalln(err)
  24. }
  25. listener := tlsutil.DowngradingListener{
  26. Listener: tcpListener,
  27. }
  28. for {
  29. conn, isTLS, err := listener.AcceptNoWrapTLS()
  30. if err != nil {
  31. if debug {
  32. log.Println("Listener failed to accept connection from", conn.RemoteAddr(), ". Possibly a TCP Ping.")
  33. }
  34. continue
  35. }
  36. setTCPOptions(conn)
  37. if debug {
  38. log.Println("Listener accepted connection from", conn.RemoteAddr(), "tls", isTLS)
  39. }
  40. if isTLS {
  41. go protocolConnectionHandler(conn, config, token)
  42. } else {
  43. go sessionConnectionHandler(conn)
  44. }
  45. }
  46. }
  47. func protocolConnectionHandler(tcpConn net.Conn, config *tls.Config, token string) {
  48. conn := tls.Server(tcpConn, config)
  49. if err := conn.SetDeadline(time.Now().Add(messageTimeout)); err != nil {
  50. if debug {
  51. log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
  52. }
  53. conn.Close()
  54. return
  55. }
  56. err := conn.Handshake()
  57. if err != nil {
  58. if debug {
  59. log.Println("Protocol connection TLS handshake:", conn.RemoteAddr(), err)
  60. }
  61. conn.Close()
  62. return
  63. }
  64. state := conn.ConnectionState()
  65. if debug && state.NegotiatedProtocol != protocol.ProtocolName {
  66. log.Println("Protocol negotiation error")
  67. }
  68. certs := state.PeerCertificates
  69. if len(certs) != 1 {
  70. if debug {
  71. log.Println("Certificate list error")
  72. }
  73. conn.Close()
  74. return
  75. }
  76. conn.SetDeadline(time.Time{})
  77. id := syncthingprotocol.NewDeviceID(certs[0].Raw)
  78. messages := make(chan interface{})
  79. errors := make(chan error, 1)
  80. outbox := make(chan interface{})
  81. // Read messages from the connection and send them on the messages
  82. // channel. When there is an error, send it on the error channel and
  83. // return. Applies also when the connection gets closed, so the pattern
  84. // below is to close the connection on error, then wait for the error
  85. // signal from messageReader to exit.
  86. go messageReader(conn, messages, errors)
  87. pingTicker := time.NewTicker(pingInterval)
  88. defer pingTicker.Stop()
  89. timeoutTicker := time.NewTimer(networkTimeout)
  90. defer timeoutTicker.Stop()
  91. joined := false
  92. for {
  93. select {
  94. case message := <-messages:
  95. timeoutTicker.Reset(networkTimeout)
  96. if debug {
  97. log.Printf("Message %T from %s", message, id)
  98. }
  99. switch msg := message.(type) {
  100. case protocol.JoinRelayRequest:
  101. if token != "" && msg.Token != token {
  102. if debug {
  103. log.Printf("invalid token %s\n", msg.Token)
  104. }
  105. protocol.WriteMessage(conn, protocol.ResponseWrongToken)
  106. conn.Close()
  107. continue
  108. }
  109. if atomic.LoadInt32(&overLimit) > 0 {
  110. protocol.WriteMessage(conn, protocol.RelayFull{})
  111. if debug {
  112. log.Println("Refusing join request from", id, "due to being over limits")
  113. }
  114. conn.Close()
  115. limitCheckTimer.Reset(time.Second)
  116. continue
  117. }
  118. outboxesMut.RLock()
  119. _, ok := outboxes[id]
  120. outboxesMut.RUnlock()
  121. if ok {
  122. protocol.WriteMessage(conn, protocol.ResponseAlreadyConnected)
  123. if debug {
  124. log.Println("Already have a peer with the same ID", id, conn.RemoteAddr())
  125. }
  126. conn.Close()
  127. continue
  128. }
  129. outboxesMut.Lock()
  130. outboxes[id] = outbox
  131. outboxesMut.Unlock()
  132. joined = true
  133. protocol.WriteMessage(conn, protocol.ResponseSuccess)
  134. case protocol.ConnectRequest:
  135. requestedPeer, err := syncthingprotocol.DeviceIDFromBytes(msg.ID)
  136. if err != nil {
  137. if debug {
  138. log.Println(id, "is looking for an invalid peer ID")
  139. }
  140. protocol.WriteMessage(conn, protocol.ResponseNotFound)
  141. conn.Close()
  142. continue
  143. }
  144. outboxesMut.RLock()
  145. peerOutbox, ok := outboxes[requestedPeer]
  146. outboxesMut.RUnlock()
  147. if !ok {
  148. if debug {
  149. log.Println(id, "is looking for", requestedPeer, "which does not exist")
  150. }
  151. protocol.WriteMessage(conn, protocol.ResponseNotFound)
  152. conn.Close()
  153. continue
  154. }
  155. // requestedPeer is the server, id is the client
  156. ses := newSession(requestedPeer, id, sessionLimiter, globalLimiter)
  157. go ses.Serve()
  158. clientInvitation := ses.GetClientInvitationMessage()
  159. serverInvitation := ses.GetServerInvitationMessage()
  160. if err := protocol.WriteMessage(conn, clientInvitation); err != nil {
  161. if debug {
  162. log.Printf("Error sending invitation from %s to client: %s", id, err)
  163. }
  164. conn.Close()
  165. continue
  166. }
  167. select {
  168. case peerOutbox <- serverInvitation:
  169. if debug {
  170. log.Println("Sent invitation from", id, "to", requestedPeer)
  171. }
  172. case <-time.After(time.Second):
  173. if debug {
  174. log.Println("Could not send invitation from", id, "to", requestedPeer, "as peer disconnected")
  175. }
  176. }
  177. conn.Close()
  178. case protocol.Ping:
  179. if err := protocol.WriteMessage(conn, protocol.Pong{}); err != nil {
  180. if debug {
  181. log.Println("Error writing pong:", err)
  182. }
  183. conn.Close()
  184. continue
  185. }
  186. case protocol.Pong:
  187. // Nothing
  188. default:
  189. if debug {
  190. log.Printf("Unknown message %s: %T", id, message)
  191. }
  192. protocol.WriteMessage(conn, protocol.ResponseUnexpectedMessage)
  193. conn.Close()
  194. }
  195. case err := <-errors:
  196. if debug {
  197. log.Printf("Closing connection %s: %s", id, err)
  198. }
  199. // Potentially closing a second time.
  200. conn.Close()
  201. if joined {
  202. // Only delete the outbox if the client is joined, as it might be
  203. // a lookup request coming from the same client.
  204. outboxesMut.Lock()
  205. delete(outboxes, id)
  206. outboxesMut.Unlock()
  207. // Also, kill all sessions related to this node, as it probably
  208. // went offline. This is for the other end to realize the client
  209. // is no longer there faster. This also helps resolve
  210. // 'already connected' errors when one of the sides is
  211. // restarting, and connecting to the other peer before the other
  212. // peer even realised that the node has gone away.
  213. dropSessions(id)
  214. }
  215. return
  216. case <-pingTicker.C:
  217. if !joined {
  218. if debug {
  219. log.Println(id, "didn't join within", pingInterval)
  220. }
  221. conn.Close()
  222. continue
  223. }
  224. if err := protocol.WriteMessage(conn, protocol.Ping{}); err != nil {
  225. if debug {
  226. log.Println(id, err)
  227. }
  228. conn.Close()
  229. }
  230. if atomic.LoadInt32(&overLimit) > 0 && !hasSessions(id) {
  231. if debug {
  232. log.Println("Dropping", id, "as it has no sessions and we are over our limits")
  233. }
  234. protocol.WriteMessage(conn, protocol.RelayFull{})
  235. conn.Close()
  236. limitCheckTimer.Reset(time.Second)
  237. }
  238. case <-timeoutTicker.C:
  239. // We should receive a error from the reader loop, which will cause
  240. // us to quit this loop.
  241. if debug {
  242. log.Printf("%s timed out", id)
  243. }
  244. conn.Close()
  245. case msg := <-outbox:
  246. if debug {
  247. log.Printf("Sending message %T to %s", msg, id)
  248. }
  249. if err := protocol.WriteMessage(conn, msg); err != nil {
  250. if debug {
  251. log.Println(id, err)
  252. }
  253. conn.Close()
  254. }
  255. }
  256. }
  257. }
  258. func sessionConnectionHandler(conn net.Conn) {
  259. if err := conn.SetDeadline(time.Now().Add(messageTimeout)); err != nil {
  260. if debug {
  261. log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
  262. }
  263. conn.Close()
  264. return
  265. }
  266. message, err := protocol.ReadMessage(conn)
  267. if err != nil {
  268. return
  269. }
  270. switch msg := message.(type) {
  271. case protocol.JoinSessionRequest:
  272. ses := findSession(string(msg.Key))
  273. if debug {
  274. log.Println(conn.RemoteAddr(), "session lookup", ses, hex.EncodeToString(msg.Key)[:5])
  275. }
  276. if ses == nil {
  277. protocol.WriteMessage(conn, protocol.ResponseNotFound)
  278. conn.Close()
  279. return
  280. }
  281. if !ses.AddConnection(conn) {
  282. if debug {
  283. log.Println("Failed to add", conn.RemoteAddr(), "to session", ses)
  284. }
  285. protocol.WriteMessage(conn, protocol.ResponseAlreadyConnected)
  286. conn.Close()
  287. return
  288. }
  289. if err := protocol.WriteMessage(conn, protocol.ResponseSuccess); err != nil {
  290. if debug {
  291. log.Println("Failed to send session join response to ", conn.RemoteAddr(), "for", ses)
  292. }
  293. return
  294. }
  295. if err := conn.SetDeadline(time.Time{}); err != nil {
  296. if debug {
  297. log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
  298. }
  299. conn.Close()
  300. return
  301. }
  302. default:
  303. if debug {
  304. log.Println("Unexpected message from", conn.RemoteAddr(), message)
  305. }
  306. protocol.WriteMessage(conn, protocol.ResponseUnexpectedMessage)
  307. conn.Close()
  308. }
  309. }
  310. func messageReader(conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  311. atomic.AddInt64(&numConnections, 1)
  312. defer atomic.AddInt64(&numConnections, -1)
  313. for {
  314. msg, err := protocol.ReadMessage(conn)
  315. if err != nil {
  316. errors <- err
  317. return
  318. }
  319. messages <- msg
  320. }
  321. }