listener.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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(proto, addr string, config *tls.Config) {
  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)
  42. } else {
  43. go sessionConnectionHandler(conn)
  44. }
  45. }
  46. }
  47. func protocolConnectionHandler(tcpConn net.Conn, config *tls.Config) {
  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 (!state.NegotiatedProtocolIsMutual || state.NegotiatedProtocol != protocol.ProtocolName) && debug {
  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 atomic.LoadInt32(&overLimit) > 0 {
  102. protocol.WriteMessage(conn, protocol.RelayFull{})
  103. if debug {
  104. log.Println("Refusing join request from", id, "due to being over limits")
  105. }
  106. conn.Close()
  107. limitCheckTimer.Reset(time.Second)
  108. continue
  109. }
  110. outboxesMut.RLock()
  111. _, ok := outboxes[id]
  112. outboxesMut.RUnlock()
  113. if ok {
  114. protocol.WriteMessage(conn, protocol.ResponseAlreadyConnected)
  115. if debug {
  116. log.Println("Already have a peer with the same ID", id, conn.RemoteAddr())
  117. }
  118. conn.Close()
  119. continue
  120. }
  121. outboxesMut.Lock()
  122. outboxes[id] = outbox
  123. outboxesMut.Unlock()
  124. joined = true
  125. protocol.WriteMessage(conn, protocol.ResponseSuccess)
  126. case protocol.ConnectRequest:
  127. requestedPeer, err := syncthingprotocol.DeviceIDFromBytes(msg.ID)
  128. if err != nil {
  129. if debug {
  130. log.Println(id, "is looking for an invalid peer ID")
  131. }
  132. protocol.WriteMessage(conn, protocol.ResponseNotFound)
  133. conn.Close()
  134. continue
  135. }
  136. outboxesMut.RLock()
  137. peerOutbox, ok := outboxes[requestedPeer]
  138. outboxesMut.RUnlock()
  139. if !ok {
  140. if debug {
  141. log.Println(id, "is looking for", requestedPeer, "which does not exist")
  142. }
  143. protocol.WriteMessage(conn, protocol.ResponseNotFound)
  144. conn.Close()
  145. continue
  146. }
  147. // requestedPeer is the server, id is the client
  148. ses := newSession(requestedPeer, id, sessionLimiter, globalLimiter)
  149. go ses.Serve()
  150. clientInvitation := ses.GetClientInvitationMessage()
  151. serverInvitation := ses.GetServerInvitationMessage()
  152. if err := protocol.WriteMessage(conn, clientInvitation); err != nil {
  153. if debug {
  154. log.Printf("Error sending invitation from %s to client: %s", id, err)
  155. }
  156. conn.Close()
  157. continue
  158. }
  159. select {
  160. case peerOutbox <- serverInvitation:
  161. if debug {
  162. log.Println("Sent invitation from", id, "to", requestedPeer)
  163. }
  164. case <-time.After(time.Second):
  165. if debug {
  166. log.Println("Could not send invitation from", id, "to", requestedPeer, "as peer disconnected")
  167. }
  168. }
  169. conn.Close()
  170. case protocol.Ping:
  171. if err := protocol.WriteMessage(conn, protocol.Pong{}); err != nil {
  172. if debug {
  173. log.Println("Error writing pong:", err)
  174. }
  175. conn.Close()
  176. continue
  177. }
  178. case protocol.Pong:
  179. // Nothing
  180. default:
  181. if debug {
  182. log.Printf("Unknown message %s: %T", id, message)
  183. }
  184. protocol.WriteMessage(conn, protocol.ResponseUnexpectedMessage)
  185. conn.Close()
  186. }
  187. case err := <-errors:
  188. if debug {
  189. log.Printf("Closing connection %s: %s", id, err)
  190. }
  191. // Potentially closing a second time.
  192. conn.Close()
  193. if joined {
  194. // Only delete the outbox if the client is joined, as it might be
  195. // a lookup request coming from the same client.
  196. outboxesMut.Lock()
  197. delete(outboxes, id)
  198. outboxesMut.Unlock()
  199. // Also, kill all sessions related to this node, as it probably
  200. // went offline. This is for the other end to realize the client
  201. // is no longer there faster. This also helps resolve
  202. // 'already connected' errors when one of the sides is
  203. // restarting, and connecting to the other peer before the other
  204. // peer even realised that the node has gone away.
  205. dropSessions(id)
  206. }
  207. return
  208. case <-pingTicker.C:
  209. if !joined {
  210. if debug {
  211. log.Println(id, "didn't join within", pingInterval)
  212. }
  213. conn.Close()
  214. continue
  215. }
  216. if err := protocol.WriteMessage(conn, protocol.Ping{}); err != nil {
  217. if debug {
  218. log.Println(id, err)
  219. }
  220. conn.Close()
  221. }
  222. if atomic.LoadInt32(&overLimit) > 0 && !hasSessions(id) {
  223. if debug {
  224. log.Println("Dropping", id, "as it has no sessions and we are over our limits")
  225. }
  226. protocol.WriteMessage(conn, protocol.RelayFull{})
  227. conn.Close()
  228. limitCheckTimer.Reset(time.Second)
  229. }
  230. case <-timeoutTicker.C:
  231. // We should receive a error from the reader loop, which will cause
  232. // us to quit this loop.
  233. if debug {
  234. log.Printf("%s timed out", id)
  235. }
  236. conn.Close()
  237. case msg := <-outbox:
  238. if debug {
  239. log.Printf("Sending message %T to %s", msg, id)
  240. }
  241. if err := protocol.WriteMessage(conn, msg); err != nil {
  242. if debug {
  243. log.Println(id, err)
  244. }
  245. conn.Close()
  246. }
  247. }
  248. }
  249. }
  250. func sessionConnectionHandler(conn net.Conn) {
  251. if err := conn.SetDeadline(time.Now().Add(messageTimeout)); err != nil {
  252. if debug {
  253. log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
  254. }
  255. conn.Close()
  256. return
  257. }
  258. message, err := protocol.ReadMessage(conn)
  259. if err != nil {
  260. return
  261. }
  262. switch msg := message.(type) {
  263. case protocol.JoinSessionRequest:
  264. ses := findSession(string(msg.Key))
  265. if debug {
  266. log.Println(conn.RemoteAddr(), "session lookup", ses, hex.EncodeToString(msg.Key)[:5])
  267. }
  268. if ses == nil {
  269. protocol.WriteMessage(conn, protocol.ResponseNotFound)
  270. conn.Close()
  271. return
  272. }
  273. if !ses.AddConnection(conn) {
  274. if debug {
  275. log.Println("Failed to add", conn.RemoteAddr(), "to session", ses)
  276. }
  277. protocol.WriteMessage(conn, protocol.ResponseAlreadyConnected)
  278. conn.Close()
  279. return
  280. }
  281. if err := protocol.WriteMessage(conn, protocol.ResponseSuccess); err != nil {
  282. if debug {
  283. log.Println("Failed to send session join response to ", conn.RemoteAddr(), "for", ses)
  284. }
  285. return
  286. }
  287. if err := conn.SetDeadline(time.Time{}); err != nil {
  288. if debug {
  289. log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
  290. }
  291. conn.Close()
  292. return
  293. }
  294. default:
  295. if debug {
  296. log.Println("Unexpected message from", conn.RemoteAddr(), message)
  297. }
  298. protocol.WriteMessage(conn, protocol.ResponseUnexpectedMessage)
  299. conn.Close()
  300. }
  301. }
  302. func messageReader(conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  303. atomic.AddInt64(&numConnections, 1)
  304. defer atomic.AddInt64(&numConnections, -1)
  305. for {
  306. msg, err := protocol.ReadMessage(conn)
  307. if err != nil {
  308. errors <- err
  309. return
  310. }
  311. messages <- msg
  312. }
  313. }