protocol.go 9.5 KB

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