protocol.go 12 KB

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