listener.go 9.1 KB

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