protocol.go 10 KB

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