protocol.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package protocol
  5. import (
  6. "bufio"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "sync"
  11. "time"
  12. "github.com/calmh/syncthing/xdr"
  13. )
  14. const BlockSize = 128 * 1024
  15. const (
  16. messageTypeClusterConfig = 0
  17. messageTypeIndex = 1
  18. messageTypeRequest = 2
  19. messageTypeResponse = 3
  20. messageTypePing = 4
  21. messageTypePong = 5
  22. messageTypeIndexUpdate = 6
  23. )
  24. const (
  25. stateInitial = iota
  26. stateCCRcvd
  27. stateIdxRcvd
  28. )
  29. const (
  30. FlagDeleted uint32 = 1 << 12
  31. FlagInvalid = 1 << 13
  32. FlagDirectory = 1 << 14
  33. FlagNoPermBits = 1 << 15
  34. )
  35. const (
  36. FlagShareTrusted uint32 = 1 << 0
  37. FlagShareReadOnly = 1 << 1
  38. FlagShareBits = 0x000000ff
  39. )
  40. var (
  41. ErrClusterHash = fmt.Errorf("configuration error: mismatched cluster hash")
  42. ErrClosed = errors.New("connection closed")
  43. )
  44. type Model interface {
  45. // An index was received from the peer node
  46. Index(nodeID NodeID, repo string, files []FileInfo)
  47. // An index update was received from the peer node
  48. IndexUpdate(nodeID NodeID, repo string, files []FileInfo)
  49. // A request was made by the peer node
  50. Request(nodeID NodeID, repo string, name string, offset int64, size int) ([]byte, error)
  51. // A cluster configuration message was received
  52. ClusterConfig(nodeID NodeID, config ClusterConfigMessage)
  53. // The peer node closed the connection
  54. Close(nodeID NodeID, err error)
  55. }
  56. type Connection interface {
  57. ID() NodeID
  58. Name() string
  59. Index(repo string, files []FileInfo) error
  60. IndexUpdate(repo string, files []FileInfo) error
  61. Request(repo string, name string, offset int64, size int) ([]byte, error)
  62. ClusterConfig(config ClusterConfigMessage)
  63. Statistics() Statistics
  64. }
  65. type rawConnection struct {
  66. id NodeID
  67. name string
  68. receiver Model
  69. state int
  70. cr *countingReader
  71. xr *xdr.Reader
  72. cw *countingWriter
  73. wb *bufio.Writer
  74. xw *xdr.Writer
  75. awaiting []chan asyncResult
  76. awaitingMut sync.Mutex
  77. idxMut sync.Mutex // ensures serialization of Index calls
  78. nextID chan int
  79. outbox chan []encodable
  80. closed chan struct{}
  81. once sync.Once
  82. incomingIndexes chan incomingIndex
  83. }
  84. type incomingIndex struct {
  85. update bool
  86. id NodeID
  87. repo string
  88. files []FileInfo
  89. }
  90. type asyncResult struct {
  91. val []byte
  92. err error
  93. }
  94. const (
  95. pingTimeout = 30 * time.Second
  96. pingIdleTime = 60 * time.Second
  97. )
  98. func NewConnection(nodeID NodeID, reader io.Reader, writer io.Writer, receiver Model, name string) Connection {
  99. cr := &countingReader{Reader: reader}
  100. cw := &countingWriter{Writer: writer}
  101. rb := bufio.NewReader(cr)
  102. wb := bufio.NewWriterSize(cw, 65536)
  103. c := rawConnection{
  104. id: nodeID,
  105. name: name,
  106. receiver: nativeModel{receiver},
  107. state: stateInitial,
  108. cr: cr,
  109. xr: xdr.NewReader(rb),
  110. cw: cw,
  111. wb: wb,
  112. xw: xdr.NewWriter(wb),
  113. awaiting: make([]chan asyncResult, 0x1000),
  114. outbox: make(chan []encodable),
  115. nextID: make(chan int),
  116. closed: make(chan struct{}),
  117. incomingIndexes: make(chan incomingIndex, 100), // should be enough for anyone, right?
  118. }
  119. go c.indexSerializerLoop()
  120. go c.readerLoop()
  121. go c.writerLoop()
  122. go c.pingerLoop()
  123. go c.idGenerator()
  124. return wireFormatConnection{&c}
  125. }
  126. func (c *rawConnection) ID() NodeID {
  127. return c.id
  128. }
  129. func (c *rawConnection) Name() string {
  130. return c.name
  131. }
  132. // Index writes the list of file information to the connected peer node
  133. func (c *rawConnection) Index(repo string, idx []FileInfo) error {
  134. select {
  135. case <-c.closed:
  136. return ErrClosed
  137. default:
  138. }
  139. c.idxMut.Lock()
  140. c.send(header{0, -1, messageTypeIndex}, IndexMessage{repo, idx})
  141. c.idxMut.Unlock()
  142. return nil
  143. }
  144. // IndexUpdate writes the list of file information to the connected peer node as an update
  145. func (c *rawConnection) IndexUpdate(repo string, idx []FileInfo) error {
  146. select {
  147. case <-c.closed:
  148. return ErrClosed
  149. default:
  150. }
  151. c.idxMut.Lock()
  152. c.send(header{0, -1, messageTypeIndexUpdate}, IndexMessage{repo, idx})
  153. c.idxMut.Unlock()
  154. return nil
  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. func (c *rawConnection) indexSerializerLoop() {
  270. // We must avoid blocking the reader loop when processing large indexes.
  271. // There is otherwise a potential deadlock where both sides has the model
  272. // locked because it's sending a large index update and can't receive the
  273. // large index update from the other side. But we must also ensure to
  274. // process the indexes in the order they are received, hence the separate
  275. // routine and buffered channel.
  276. for {
  277. select {
  278. case ii := <-c.incomingIndexes:
  279. if ii.update {
  280. if debug {
  281. l.Debugf("calling IndexUpdate(%v, %v, %d files)", ii.id, ii.repo, len(ii.files))
  282. }
  283. c.receiver.IndexUpdate(ii.id, ii.repo, ii.files)
  284. } else {
  285. if debug {
  286. l.Debugf("calling Index(%v, %v, %d files)", ii.id, ii.repo, len(ii.files))
  287. }
  288. c.receiver.Index(ii.id, ii.repo, ii.files)
  289. }
  290. case <-c.closed:
  291. return
  292. }
  293. }
  294. }
  295. func (c *rawConnection) handleIndex() error {
  296. var im IndexMessage
  297. im.decodeXDR(c.xr)
  298. if err := c.xr.Error(); err != nil {
  299. return err
  300. } else {
  301. // We run this (and the corresponding one for update, below)
  302. // in a separate goroutine to avoid blocking the read loop.
  303. // There is otherwise a potential deadlock where both sides
  304. // has the model locked because it's sending a large index
  305. // update and can't receive the large index update from the
  306. // other side.
  307. if debug {
  308. l.Debugf("queueing Index(%v, %v, %d files)", c.id, im.Repository, len(im.Files))
  309. }
  310. c.incomingIndexes <- incomingIndex{false, c.id, im.Repository, im.Files}
  311. }
  312. return nil
  313. }
  314. func (c *rawConnection) handleIndexUpdate() error {
  315. var im IndexMessage
  316. im.decodeXDR(c.xr)
  317. if err := c.xr.Error(); err != nil {
  318. return err
  319. } else {
  320. if debug {
  321. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Repository, len(im.Files))
  322. }
  323. c.incomingIndexes <- incomingIndex{true, c.id, im.Repository, im.Files}
  324. }
  325. return nil
  326. }
  327. func (c *rawConnection) handleRequest(hdr header) error {
  328. var req RequestMessage
  329. req.decodeXDR(c.xr)
  330. if err := c.xr.Error(); err != nil {
  331. return err
  332. }
  333. go c.processRequest(hdr.msgID, req)
  334. return nil
  335. }
  336. func (c *rawConnection) handleResponse(hdr header) error {
  337. data := c.xr.ReadBytesMax(256 * 1024) // Sufficiently larger than max expected block size
  338. if err := c.xr.Error(); err != nil {
  339. return err
  340. }
  341. c.awaitingMut.Lock()
  342. if rc := c.awaiting[hdr.msgID]; rc != nil {
  343. c.awaiting[hdr.msgID] = nil
  344. rc <- asyncResult{data, nil}
  345. close(rc)
  346. }
  347. c.awaitingMut.Unlock()
  348. return nil
  349. }
  350. func (c *rawConnection) handlePong(hdr header) {
  351. c.awaitingMut.Lock()
  352. if rc := c.awaiting[hdr.msgID]; rc != nil {
  353. c.awaiting[hdr.msgID] = nil
  354. rc <- asyncResult{}
  355. close(rc)
  356. }
  357. c.awaitingMut.Unlock()
  358. }
  359. func (c *rawConnection) handleClusterConfig() error {
  360. var cm ClusterConfigMessage
  361. cm.decodeXDR(c.xr)
  362. if err := c.xr.Error(); err != nil {
  363. return err
  364. } else {
  365. go c.receiver.ClusterConfig(c.id, cm)
  366. }
  367. return nil
  368. }
  369. type encodable interface {
  370. encodeXDR(*xdr.Writer) (int, error)
  371. }
  372. type encodableBytes []byte
  373. func (e encodableBytes) encodeXDR(xw *xdr.Writer) (int, error) {
  374. return xw.WriteBytes(e)
  375. }
  376. func (c *rawConnection) send(h header, es ...encodable) bool {
  377. if h.msgID < 0 {
  378. select {
  379. case id := <-c.nextID:
  380. h.msgID = id
  381. case <-c.closed:
  382. return false
  383. }
  384. }
  385. msg := append([]encodable{h}, es...)
  386. select {
  387. case c.outbox <- msg:
  388. return true
  389. case <-c.closed:
  390. return false
  391. }
  392. }
  393. func (c *rawConnection) writerLoop() {
  394. for {
  395. select {
  396. case es := <-c.outbox:
  397. for _, e := range es {
  398. e.encodeXDR(c.xw)
  399. }
  400. if err := c.flush(); err != nil {
  401. c.close(err)
  402. return
  403. }
  404. case <-c.closed:
  405. return
  406. }
  407. }
  408. }
  409. type flusher interface {
  410. Flush() error
  411. }
  412. func (c *rawConnection) flush() error {
  413. if err := c.xw.Error(); err != nil {
  414. return err
  415. }
  416. if err := c.wb.Flush(); err != nil {
  417. return err
  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. }