protocol.go 9.7 KB

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