listener.go 8.5 KB

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