protocol.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package protocol
  2. import (
  3. "compress/flate"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log"
  8. "sync"
  9. "time"
  10. "github.com/calmh/syncthing/buffers"
  11. "github.com/calmh/syncthing/xdr"
  12. )
  13. const BlockSize = 128 * 1024
  14. const (
  15. messageTypeIndex = 1
  16. messageTypeRequest = 2
  17. messageTypeResponse = 3
  18. messageTypePing = 4
  19. messageTypePong = 5
  20. messageTypeIndexUpdate = 6
  21. messageTypeOptions = 7
  22. )
  23. const (
  24. FlagDeleted uint32 = 1 << 12
  25. FlagInvalid = 1 << 13
  26. )
  27. var (
  28. ErrClusterHash = fmt.Errorf("configuration error: mismatched cluster hash")
  29. ErrClosed = errors.New("connection closed")
  30. )
  31. type Model interface {
  32. // An index was received from the peer node
  33. Index(nodeID string, files []FileInfo)
  34. // An index update was received from the peer node
  35. IndexUpdate(nodeID string, files []FileInfo)
  36. // A request was made by the peer node
  37. Request(nodeID, repo string, name string, offset int64, size int) ([]byte, error)
  38. // The peer node closed the connection
  39. Close(nodeID string, err error)
  40. }
  41. type Connection struct {
  42. sync.RWMutex
  43. id string
  44. receiver Model
  45. reader io.Reader
  46. xr *xdr.Reader
  47. writer io.Writer
  48. xw *xdr.Writer
  49. closed bool
  50. awaiting map[int]chan asyncResult
  51. nextID int
  52. indexSent map[string]map[string][2]int64
  53. peerOptions map[string]string
  54. myOptions map[string]string
  55. optionsLock sync.Mutex
  56. hasSentIndex bool
  57. hasRecvdIndex bool
  58. statisticsLock sync.Mutex
  59. }
  60. type asyncResult struct {
  61. val []byte
  62. err error
  63. }
  64. const (
  65. pingTimeout = 2 * time.Minute
  66. pingIdleTime = 5 * time.Minute
  67. )
  68. func NewConnection(nodeID string, reader io.Reader, writer io.Writer, receiver Model, options map[string]string) *Connection {
  69. flrd := flate.NewReader(reader)
  70. flwr, err := flate.NewWriter(writer, flate.BestSpeed)
  71. if err != nil {
  72. panic(err)
  73. }
  74. c := Connection{
  75. id: nodeID,
  76. receiver: receiver,
  77. reader: flrd,
  78. xr: xdr.NewReader(flrd),
  79. writer: flwr,
  80. xw: xdr.NewWriter(flwr),
  81. awaiting: make(map[int]chan asyncResult),
  82. indexSent: make(map[string]map[string][2]int64),
  83. }
  84. go c.readerLoop()
  85. go c.pingerLoop()
  86. if options != nil {
  87. c.myOptions = options
  88. go func() {
  89. c.Lock()
  90. header{0, c.nextID, messageTypeOptions}.encodeXDR(c.xw)
  91. var om OptionsMessage
  92. for k, v := range options {
  93. om.Options = append(om.Options, Option{k, v})
  94. }
  95. om.encodeXDR(c.xw)
  96. err := c.xw.Error()
  97. if err == nil {
  98. err = c.flush()
  99. }
  100. if err != nil {
  101. log.Println("Warning: Write error during initial handshake:", err)
  102. }
  103. c.nextID++
  104. c.Unlock()
  105. }()
  106. }
  107. return &c
  108. }
  109. func (c *Connection) ID() string {
  110. return c.id
  111. }
  112. // Index writes the list of file information to the connected peer node
  113. func (c *Connection) Index(repo string, idx []FileInfo) {
  114. c.Lock()
  115. var msgType int
  116. if c.indexSent[repo] == nil {
  117. // This is the first time we send an index.
  118. msgType = messageTypeIndex
  119. c.indexSent[repo] = make(map[string][2]int64)
  120. for _, f := range idx {
  121. c.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}
  122. }
  123. } else {
  124. // We have sent one full index. Only send updates now.
  125. msgType = messageTypeIndexUpdate
  126. var diff []FileInfo
  127. for _, f := range idx {
  128. if vs, ok := c.indexSent[repo][f.Name]; !ok || f.Modified != vs[0] || int64(f.Version) != vs[1] {
  129. diff = append(diff, f)
  130. c.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}
  131. }
  132. }
  133. idx = diff
  134. }
  135. header{0, c.nextID, msgType}.encodeXDR(c.xw)
  136. _, err := IndexMessage{repo, idx}.encodeXDR(c.xw)
  137. if err == nil {
  138. err = c.flush()
  139. }
  140. c.nextID = (c.nextID + 1) & 0xfff
  141. c.hasSentIndex = true
  142. c.Unlock()
  143. if err != nil {
  144. c.close(err)
  145. return
  146. }
  147. }
  148. // Request returns the bytes for the specified block after fetching them from the connected peer.
  149. func (c *Connection) Request(repo string, name string, offset int64, size int) ([]byte, error) {
  150. c.Lock()
  151. if c.closed {
  152. c.Unlock()
  153. return nil, ErrClosed
  154. }
  155. rc := make(chan asyncResult)
  156. if _, ok := c.awaiting[c.nextID]; ok {
  157. panic("id taken")
  158. }
  159. c.awaiting[c.nextID] = rc
  160. header{0, c.nextID, messageTypeRequest}.encodeXDR(c.xw)
  161. _, err := RequestMessage{repo, name, uint64(offset), uint32(size)}.encodeXDR(c.xw)
  162. if err == nil {
  163. err = c.flush()
  164. }
  165. if err != nil {
  166. c.Unlock()
  167. c.close(err)
  168. return nil, err
  169. }
  170. c.nextID = (c.nextID + 1) & 0xfff
  171. c.Unlock()
  172. res, ok := <-rc
  173. if !ok {
  174. return nil, ErrClosed
  175. }
  176. return res.val, res.err
  177. }
  178. func (c *Connection) ping() bool {
  179. c.Lock()
  180. if c.closed {
  181. c.Unlock()
  182. return false
  183. }
  184. rc := make(chan asyncResult, 1)
  185. c.awaiting[c.nextID] = rc
  186. header{0, c.nextID, messageTypePing}.encodeXDR(c.xw)
  187. err := c.flush()
  188. if err != nil {
  189. c.Unlock()
  190. c.close(err)
  191. return false
  192. } else if c.xw.Error() != nil {
  193. c.Unlock()
  194. c.close(c.xw.Error())
  195. return false
  196. }
  197. c.nextID = (c.nextID + 1) & 0xfff
  198. c.Unlock()
  199. res, ok := <-rc
  200. return ok && res.err == nil
  201. }
  202. type flusher interface {
  203. Flush() error
  204. }
  205. func (c *Connection) flush() error {
  206. if f, ok := c.writer.(flusher); ok {
  207. return f.Flush()
  208. }
  209. return nil
  210. }
  211. func (c *Connection) close(err error) {
  212. c.Lock()
  213. if c.closed {
  214. c.Unlock()
  215. return
  216. }
  217. c.closed = true
  218. for _, ch := range c.awaiting {
  219. close(ch)
  220. }
  221. c.awaiting = nil
  222. c.Unlock()
  223. c.receiver.Close(c.id, err)
  224. }
  225. func (c *Connection) isClosed() bool {
  226. c.RLock()
  227. defer c.RUnlock()
  228. return c.closed
  229. }
  230. func (c *Connection) readerLoop() {
  231. loop:
  232. for {
  233. var hdr header
  234. hdr.decodeXDR(c.xr)
  235. if c.xr.Error() != nil {
  236. c.close(c.xr.Error())
  237. break loop
  238. }
  239. if hdr.version != 0 {
  240. c.close(fmt.Errorf("protocol error: %s: unknown message version %#x", c.id, hdr.version))
  241. break loop
  242. }
  243. switch hdr.msgType {
  244. case messageTypeIndex:
  245. var im IndexMessage
  246. im.decodeXDR(c.xr)
  247. if c.xr.Error() != nil {
  248. c.close(c.xr.Error())
  249. break loop
  250. } else {
  251. c.receiver.Index(c.id, im.Files)
  252. }
  253. c.Lock()
  254. c.hasRecvdIndex = true
  255. c.Unlock()
  256. case messageTypeIndexUpdate:
  257. var im IndexMessage
  258. im.decodeXDR(c.xr)
  259. if c.xr.Error() != nil {
  260. c.close(c.xr.Error())
  261. break loop
  262. } else {
  263. c.receiver.IndexUpdate(c.id, im.Files)
  264. }
  265. case messageTypeRequest:
  266. var req RequestMessage
  267. req.decodeXDR(c.xr)
  268. if c.xr.Error() != nil {
  269. c.close(c.xr.Error())
  270. break loop
  271. }
  272. go c.processRequest(hdr.msgID, req)
  273. case messageTypeResponse:
  274. data := c.xr.ReadBytesMax(256 * 1024) // Sufficiently larger than max expected block size
  275. if c.xr.Error() != nil {
  276. c.close(c.xr.Error())
  277. break loop
  278. }
  279. go func(hdr header, err error) {
  280. c.Lock()
  281. rc, ok := c.awaiting[hdr.msgID]
  282. delete(c.awaiting, hdr.msgID)
  283. c.Unlock()
  284. if ok {
  285. rc <- asyncResult{data, err}
  286. close(rc)
  287. }
  288. }(hdr, c.xr.Error())
  289. case messageTypePing:
  290. c.Lock()
  291. header{0, hdr.msgID, messageTypePong}.encodeXDR(c.xw)
  292. err := c.flush()
  293. c.Unlock()
  294. if err != nil {
  295. c.close(err)
  296. break loop
  297. } else if c.xw.Error() != nil {
  298. c.close(c.xw.Error())
  299. break loop
  300. }
  301. case messageTypePong:
  302. c.RLock()
  303. rc, ok := c.awaiting[hdr.msgID]
  304. c.RUnlock()
  305. if ok {
  306. rc <- asyncResult{}
  307. close(rc)
  308. c.Lock()
  309. delete(c.awaiting, hdr.msgID)
  310. c.Unlock()
  311. }
  312. case messageTypeOptions:
  313. var om OptionsMessage
  314. om.decodeXDR(c.xr)
  315. if c.xr.Error() != nil {
  316. c.close(c.xr.Error())
  317. break loop
  318. }
  319. c.optionsLock.Lock()
  320. c.peerOptions = make(map[string]string, len(om.Options))
  321. for _, opt := range om.Options {
  322. c.peerOptions[opt.Key] = opt.Value
  323. }
  324. c.optionsLock.Unlock()
  325. if mh, rh := c.myOptions["clusterHash"], c.peerOptions["clusterHash"]; len(mh) > 0 && len(rh) > 0 && mh != rh {
  326. c.close(ErrClusterHash)
  327. break loop
  328. }
  329. default:
  330. c.close(fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType))
  331. break loop
  332. }
  333. }
  334. }
  335. func (c *Connection) processRequest(msgID int, req RequestMessage) {
  336. data, _ := c.receiver.Request(c.id, req.Repository, req.Name, int64(req.Offset), int(req.Size))
  337. c.Lock()
  338. header{0, msgID, messageTypeResponse}.encodeXDR(c.xw)
  339. _, err := c.xw.WriteBytes(data)
  340. if err == nil {
  341. err = c.flush()
  342. }
  343. c.Unlock()
  344. buffers.Put(data)
  345. if err != nil {
  346. c.close(err)
  347. }
  348. }
  349. func (c *Connection) pingerLoop() {
  350. var rc = make(chan bool, 1)
  351. for {
  352. time.Sleep(pingIdleTime / 2)
  353. c.RLock()
  354. ready := c.hasRecvdIndex && c.hasSentIndex
  355. c.RUnlock()
  356. if ready {
  357. go func() {
  358. rc <- c.ping()
  359. }()
  360. select {
  361. case ok := <-rc:
  362. if !ok {
  363. c.close(fmt.Errorf("ping failure"))
  364. }
  365. case <-time.After(pingTimeout):
  366. c.close(fmt.Errorf("ping timeout"))
  367. }
  368. }
  369. }
  370. }
  371. type Statistics struct {
  372. At time.Time
  373. InBytesTotal int
  374. OutBytesTotal int
  375. }
  376. func (c *Connection) Statistics() Statistics {
  377. c.statisticsLock.Lock()
  378. defer c.statisticsLock.Unlock()
  379. stats := Statistics{
  380. At: time.Now(),
  381. InBytesTotal: int(c.xr.Tot()),
  382. OutBytesTotal: int(c.xw.Tot()),
  383. }
  384. return stats
  385. }
  386. func (c *Connection) Option(key string) string {
  387. c.optionsLock.Lock()
  388. defer c.optionsLock.Unlock()
  389. return c.peerOptions[key]
  390. }