protocol.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. awaiting []chan asyncResult
  76. awaitingMut sync.Mutex
  77. idxSent map[string]map[string]uint64
  78. idxMut sync.Mutex // ensures serialization of Index calls
  79. nextID chan int
  80. outbox chan []encodable
  81. closed chan struct{}
  82. once sync.Once
  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. idxSent: 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. var msgType int
  133. if c.idxSent[repo] == nil {
  134. // This is the first time we send an index.
  135. msgType = messageTypeIndex
  136. c.idxSent[repo] = make(map[string]uint64)
  137. for _, f := range idx {
  138. c.idxSent[repo][f.Name] = f.Version
  139. }
  140. } else {
  141. // We have sent one full index. Only send updates now.
  142. msgType = messageTypeIndexUpdate
  143. var diff []FileInfo
  144. for _, f := range idx {
  145. if vs, ok := c.idxSent[repo][f.Name]; !ok || f.Version != vs {
  146. diff = append(diff, f)
  147. c.idxSent[repo][f.Name] = f.Version
  148. }
  149. }
  150. idx = diff
  151. }
  152. if msgType == messageTypeIndex || len(idx) > 0 {
  153. c.send(header{0, -1, msgType}, IndexMessage{repo, idx})
  154. }
  155. }
  156. // Request returns the bytes for the specified block after fetching them from the connected peer.
  157. func (c *rawConnection) Request(repo string, name string, offset int64, size int) ([]byte, error) {
  158. var id int
  159. select {
  160. case id = <-c.nextID:
  161. case <-c.closed:
  162. return nil, ErrClosed
  163. }
  164. c.awaitingMut.Lock()
  165. if ch := c.awaiting[id]; ch != nil {
  166. panic("id taken")
  167. }
  168. rc := make(chan asyncResult, 1)
  169. c.awaiting[id] = rc
  170. c.awaitingMut.Unlock()
  171. ok := c.send(header{0, id, messageTypeRequest},
  172. RequestMessage{repo, name, uint64(offset), uint32(size)})
  173. if !ok {
  174. return nil, ErrClosed
  175. }
  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.send(header{0, -1, messageTypeClusterConfig}, config)
  185. }
  186. func (c *rawConnection) ping() bool {
  187. var id int
  188. select {
  189. case id = <-c.nextID:
  190. case <-c.closed:
  191. return false
  192. }
  193. rc := make(chan asyncResult, 1)
  194. c.awaitingMut.Lock()
  195. c.awaiting[id] = rc
  196. c.awaitingMut.Unlock()
  197. ok := c.send(header{0, id, messageTypePing})
  198. if !ok {
  199. return false
  200. }
  201. res, ok := <-rc
  202. return ok && res.err == nil
  203. }
  204. func (c *rawConnection) readerLoop() (err error) {
  205. defer func() {
  206. c.close(err)
  207. }()
  208. for {
  209. select {
  210. case <-c.closed:
  211. return ErrClosed
  212. default:
  213. }
  214. var hdr header
  215. hdr.decodeXDR(c.xr)
  216. if err := c.xr.Error(); err != nil {
  217. return err
  218. }
  219. if hdr.version != 0 {
  220. return fmt.Errorf("protocol error: %s: unknown message version %#x", c.id, hdr.version)
  221. }
  222. switch hdr.msgType {
  223. case messageTypeIndex:
  224. if c.state < stateCCRcvd {
  225. return fmt.Errorf("protocol error: index message in state %d", c.state)
  226. }
  227. if err := c.handleIndex(); err != nil {
  228. return err
  229. }
  230. c.state = stateIdxRcvd
  231. case messageTypeIndexUpdate:
  232. if c.state < stateIdxRcvd {
  233. return fmt.Errorf("protocol error: index update message in state %d", c.state)
  234. }
  235. if err := c.handleIndexUpdate(); err != nil {
  236. return err
  237. }
  238. case messageTypeRequest:
  239. if c.state < stateIdxRcvd {
  240. return fmt.Errorf("protocol error: request message in state %d", c.state)
  241. }
  242. if err := c.handleRequest(hdr); err != nil {
  243. return err
  244. }
  245. case messageTypeResponse:
  246. if c.state < stateIdxRcvd {
  247. return fmt.Errorf("protocol error: response message in state %d", c.state)
  248. }
  249. if err := c.handleResponse(hdr); err != nil {
  250. return err
  251. }
  252. case messageTypePing:
  253. c.send(header{0, hdr.msgID, messageTypePong})
  254. case messageTypePong:
  255. c.handlePong(hdr)
  256. case messageTypeClusterConfig:
  257. if c.state != stateInitial {
  258. return fmt.Errorf("protocol error: cluster config message in state %d", c.state)
  259. }
  260. if err := c.handleClusterConfig(); err != nil {
  261. return err
  262. }
  263. c.state = stateCCRcvd
  264. default:
  265. return fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  266. }
  267. }
  268. }
  269. type incomingIndex struct {
  270. update bool
  271. id string
  272. repo string
  273. files []FileInfo
  274. }
  275. var incomingIndexes = make(chan incomingIndex, 100) // should be enough for anyone, right?
  276. func (c *rawConnection) indexSerializerLoop() {
  277. // We must avoid blocking the reader loop when processing large indexes.
  278. // There is otherwise a potential deadlock where both sides has the model
  279. // locked because it's sending a large index update and can't receive the
  280. // large index update from the other side. But we must also ensure to
  281. // process the indexes in the order they are received, hence the separate
  282. // routine and buffered channel.
  283. for {
  284. select {
  285. case ii := <-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. case <-c.closed:
  292. return
  293. }
  294. }
  295. }
  296. func (c *rawConnection) handleIndex() error {
  297. var im IndexMessage
  298. im.decodeXDR(c.xr)
  299. if err := c.xr.Error(); err != nil {
  300. return err
  301. } else {
  302. // We run this (and the corresponding one for update, below)
  303. // in a separate goroutine to avoid blocking the read loop.
  304. // There is otherwise a potential deadlock where both sides
  305. // has the model locked because it's sending a large index
  306. // update and can't receive the large index update from the
  307. // other side.
  308. incomingIndexes <- incomingIndex{false, c.id, im.Repository, im.Files}
  309. }
  310. return nil
  311. }
  312. func (c *rawConnection) handleIndexUpdate() error {
  313. var im IndexMessage
  314. im.decodeXDR(c.xr)
  315. if err := c.xr.Error(); err != nil {
  316. return err
  317. } else {
  318. incomingIndexes <- incomingIndex{true, c.id, im.Repository, im.Files}
  319. }
  320. return nil
  321. }
  322. func (c *rawConnection) handleRequest(hdr header) error {
  323. var req RequestMessage
  324. req.decodeXDR(c.xr)
  325. if err := c.xr.Error(); err != nil {
  326. return err
  327. }
  328. go c.processRequest(hdr.msgID, req)
  329. return nil
  330. }
  331. func (c *rawConnection) handleResponse(hdr header) error {
  332. data := c.xr.ReadBytesMax(256 * 1024) // Sufficiently larger than max expected block size
  333. if err := c.xr.Error(); err != nil {
  334. return err
  335. }
  336. c.awaitingMut.Lock()
  337. if rc := c.awaiting[hdr.msgID]; rc != nil {
  338. c.awaiting[hdr.msgID] = nil
  339. rc <- asyncResult{data, nil}
  340. close(rc)
  341. }
  342. c.awaitingMut.Unlock()
  343. return nil
  344. }
  345. func (c *rawConnection) handlePong(hdr header) {
  346. c.awaitingMut.Lock()
  347. if rc := c.awaiting[hdr.msgID]; rc != nil {
  348. c.awaiting[hdr.msgID] = nil
  349. rc <- asyncResult{}
  350. close(rc)
  351. }
  352. c.awaitingMut.Unlock()
  353. }
  354. func (c *rawConnection) handleClusterConfig() error {
  355. var cm ClusterConfigMessage
  356. cm.decodeXDR(c.xr)
  357. if err := c.xr.Error(); err != nil {
  358. return err
  359. } else {
  360. go c.receiver.ClusterConfig(c.id, cm)
  361. }
  362. return nil
  363. }
  364. type encodable interface {
  365. encodeXDR(*xdr.Writer) (int, error)
  366. }
  367. type encodableBytes []byte
  368. func (e encodableBytes) encodeXDR(xw *xdr.Writer) (int, error) {
  369. return xw.WriteBytes(e)
  370. }
  371. func (c *rawConnection) send(h header, es ...encodable) bool {
  372. if h.msgID < 0 {
  373. select {
  374. case id := <-c.nextID:
  375. h.msgID = id
  376. case <-c.closed:
  377. return false
  378. }
  379. }
  380. msg := append([]encodable{h}, es...)
  381. select {
  382. case c.outbox <- msg:
  383. return true
  384. case <-c.closed:
  385. return false
  386. }
  387. }
  388. func (c *rawConnection) writerLoop() {
  389. var err error
  390. for {
  391. select {
  392. case es := <-c.outbox:
  393. for _, e := range es {
  394. e.encodeXDR(c.xw)
  395. }
  396. if err = c.flush(); err != nil {
  397. c.close(err)
  398. return
  399. }
  400. case <-c.closed:
  401. return
  402. }
  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.once.Do(func() {
  422. close(c.closed)
  423. c.awaitingMut.Lock()
  424. for i, ch := range c.awaiting {
  425. if ch != nil {
  426. close(ch)
  427. c.awaiting[i] = nil
  428. }
  429. }
  430. c.awaitingMut.Unlock()
  431. go c.receiver.Close(c.id, err)
  432. })
  433. }
  434. func (c *rawConnection) idGenerator() {
  435. nextID := 0
  436. for {
  437. nextID = (nextID + 1) & 0xfff
  438. select {
  439. case c.nextID <- nextID:
  440. case <-c.closed:
  441. return
  442. }
  443. }
  444. }
  445. func (c *rawConnection) pingerLoop() {
  446. var rc = make(chan bool, 1)
  447. ticker := time.Tick(pingIdleTime / 2)
  448. for {
  449. select {
  450. case <-ticker:
  451. if d := time.Since(c.xr.LastRead()); d < pingIdleTime {
  452. if debug {
  453. l.Debugln(c.id, "ping skipped after rd", d)
  454. }
  455. continue
  456. }
  457. if d := time.Since(c.xw.LastWrite()); d < pingIdleTime {
  458. if debug {
  459. l.Debugln(c.id, "ping skipped after wr", d)
  460. }
  461. continue
  462. }
  463. go func() {
  464. if debug {
  465. l.Debugln(c.id, "ping ->")
  466. }
  467. rc <- c.ping()
  468. }()
  469. select {
  470. case ok := <-rc:
  471. if debug {
  472. l.Debugln(c.id, "<- pong")
  473. }
  474. if !ok {
  475. c.close(fmt.Errorf("ping failure"))
  476. }
  477. case <-time.After(pingTimeout):
  478. c.close(fmt.Errorf("ping timeout"))
  479. case <-c.closed:
  480. return
  481. }
  482. case <-c.closed:
  483. return
  484. }
  485. }
  486. }
  487. func (c *rawConnection) processRequest(msgID int, req RequestMessage) {
  488. data, _ := c.receiver.Request(c.id, req.Repository, req.Name, int64(req.Offset), int(req.Size))
  489. c.send(header{0, msgID, messageTypeResponse}, encodableBytes(data))
  490. }
  491. type Statistics struct {
  492. At time.Time
  493. InBytesTotal uint64
  494. OutBytesTotal uint64
  495. }
  496. func (c *rawConnection) Statistics() Statistics {
  497. return Statistics{
  498. At: time.Now(),
  499. InBytesTotal: c.cr.Tot(),
  500. OutBytesTotal: c.cw.Tot(),
  501. }
  502. }
  503. func IsDeleted(bits uint32) bool {
  504. return bits&FlagDeleted != 0
  505. }
  506. func IsInvalid(bits uint32) bool {
  507. return bits&FlagInvalid != 0
  508. }
  509. func IsDirectory(bits uint32) bool {
  510. return bits&FlagDirectory != 0
  511. }
  512. func HasPermissionBits(bits uint32) bool {
  513. return bits&FlagNoPermBits == 0
  514. }