protocol.go 13 KB

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