protocol.go 13 KB

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