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. }
  83. type asyncResult struct {
  84. val []byte
  85. err error
  86. }
  87. const (
  88. pingTimeout = 30 * time.Second
  89. pingIdleTime = 60 * time.Second
  90. )
  91. func NewConnection(nodeID NodeID, reader io.Reader, writer io.Writer, receiver Model, name string) Connection {
  92. cr := &countingReader{Reader: reader}
  93. cw := &countingWriter{Writer: writer}
  94. rb := bufio.NewReader(cr)
  95. wb := bufio.NewWriterSize(cw, 65536)
  96. c := rawConnection{
  97. id: nodeID,
  98. name: name,
  99. receiver: nativeModel{receiver},
  100. state: stateInitial,
  101. cr: cr,
  102. xr: xdr.NewReader(rb),
  103. cw: cw,
  104. wb: wb,
  105. xw: xdr.NewWriter(wb),
  106. awaiting: make([]chan asyncResult, 0x1000),
  107. outbox: make(chan []encodable),
  108. nextID: make(chan int),
  109. closed: make(chan struct{}),
  110. }
  111. go c.indexSerializerLoop()
  112. go c.readerLoop()
  113. go c.writerLoop()
  114. go c.pingerLoop()
  115. go c.idGenerator()
  116. return wireFormatConnection{&c}
  117. }
  118. func (c *rawConnection) ID() NodeID {
  119. return c.id
  120. }
  121. func (c *rawConnection) Name() string {
  122. return c.name
  123. }
  124. // Index writes the list of file information to the connected peer node
  125. func (c *rawConnection) Index(repo string, idx []FileInfo) error {
  126. select {
  127. case <-c.closed:
  128. return ErrClosed
  129. default:
  130. }
  131. c.idxMut.Lock()
  132. c.send(header{0, -1, messageTypeIndex}, IndexMessage{repo, idx})
  133. c.idxMut.Unlock()
  134. return nil
  135. }
  136. // IndexUpdate writes the list of file information to the connected peer node as an update
  137. func (c *rawConnection) IndexUpdate(repo string, idx []FileInfo) error {
  138. select {
  139. case <-c.closed:
  140. return ErrClosed
  141. default:
  142. }
  143. c.idxMut.Lock()
  144. c.send(header{0, -1, messageTypeIndexUpdate}, IndexMessage{repo, idx})
  145. c.idxMut.Unlock()
  146. return nil
  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.awaitingMut.Lock()
  157. if ch := c.awaiting[id]; ch != nil {
  158. panic("id taken")
  159. }
  160. rc := make(chan asyncResult, 1)
  161. c.awaiting[id] = rc
  162. c.awaitingMut.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.awaitingMut.Lock()
  187. c.awaiting[id] = rc
  188. c.awaitingMut.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 c.state < stateCCRcvd {
  217. return fmt.Errorf("protocol error: index message in state %d", c.state)
  218. }
  219. if err := c.handleIndex(); err != nil {
  220. return err
  221. }
  222. c.state = stateIdxRcvd
  223. case messageTypeIndexUpdate:
  224. if c.state < stateIdxRcvd {
  225. return fmt.Errorf("protocol error: index update message in state %d", c.state)
  226. }
  227. if err := c.handleIndexUpdate(); err != nil {
  228. return err
  229. }
  230. case messageTypeRequest:
  231. if c.state < stateIdxRcvd {
  232. return fmt.Errorf("protocol error: request message in state %d", c.state)
  233. }
  234. if err := c.handleRequest(hdr); err != nil {
  235. return err
  236. }
  237. case messageTypeResponse:
  238. if c.state < stateIdxRcvd {
  239. return fmt.Errorf("protocol error: response message in state %d", c.state)
  240. }
  241. if err := c.handleResponse(hdr); err != nil {
  242. return err
  243. }
  244. case messageTypePing:
  245. c.send(header{0, hdr.msgID, messageTypePong})
  246. case messageTypePong:
  247. c.handlePong(hdr)
  248. case messageTypeClusterConfig:
  249. if c.state != stateInitial {
  250. return fmt.Errorf("protocol error: cluster config message in state %d", c.state)
  251. }
  252. if err := c.handleClusterConfig(); err != nil {
  253. return err
  254. }
  255. c.state = stateCCRcvd
  256. default:
  257. return fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  258. }
  259. }
  260. }
  261. type incomingIndex struct {
  262. update bool
  263. id NodeID
  264. repo string
  265. files []FileInfo
  266. }
  267. var incomingIndexes = make(chan incomingIndex, 100) // should be enough for anyone, right?
  268. func (c *rawConnection) indexSerializerLoop() {
  269. // We must avoid blocking the reader loop when processing large indexes.
  270. // There is otherwise a potential deadlock where both sides has the model
  271. // locked because it's sending a large index update and can't receive the
  272. // large index update from the other side. But we must also ensure to
  273. // process the indexes in the order they are received, hence the separate
  274. // routine and buffered channel.
  275. for {
  276. select {
  277. case ii := <-incomingIndexes:
  278. if ii.update {
  279. if debug {
  280. l.Debugf("calling IndexUpdate(%v, %v, %d files)", ii.id, ii.repo, len(ii.files))
  281. }
  282. c.receiver.IndexUpdate(ii.id, ii.repo, ii.files)
  283. } else {
  284. if debug {
  285. l.Debugf("calling Index(%v, %v, %d files)", ii.id, ii.repo, len(ii.files))
  286. }
  287. c.receiver.Index(ii.id, ii.repo, ii.files)
  288. }
  289. case <-c.closed:
  290. return
  291. }
  292. }
  293. }
  294. func (c *rawConnection) handleIndex() error {
  295. var im IndexMessage
  296. im.decodeXDR(c.xr)
  297. if err := c.xr.Error(); err != nil {
  298. return err
  299. } else {
  300. // We run this (and the corresponding one for update, below)
  301. // in a separate goroutine to avoid blocking the read loop.
  302. // There is otherwise a potential deadlock where both sides
  303. // has the model locked because it's sending a large index
  304. // update and can't receive the large index update from the
  305. // other side.
  306. if debug {
  307. l.Debugf("queueing Index(%v, %v, %d files)", c.id, im.Repository, len(im.Files))
  308. }
  309. 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. if debug {
  320. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Repository, len(im.Files))
  321. }
  322. incomingIndexes <- incomingIndex{true, c.id, im.Repository, im.Files}
  323. }
  324. return nil
  325. }
  326. func (c *rawConnection) handleRequest(hdr header) error {
  327. var req RequestMessage
  328. req.decodeXDR(c.xr)
  329. if err := c.xr.Error(); err != nil {
  330. return err
  331. }
  332. go c.processRequest(hdr.msgID, req)
  333. return nil
  334. }
  335. func (c *rawConnection) handleResponse(hdr header) error {
  336. data := c.xr.ReadBytesMax(256 * 1024) // Sufficiently larger than max expected block size
  337. if err := c.xr.Error(); err != nil {
  338. return err
  339. }
  340. c.awaitingMut.Lock()
  341. if rc := c.awaiting[hdr.msgID]; rc != nil {
  342. c.awaiting[hdr.msgID] = nil
  343. rc <- asyncResult{data, nil}
  344. close(rc)
  345. }
  346. c.awaitingMut.Unlock()
  347. return nil
  348. }
  349. func (c *rawConnection) handlePong(hdr header) {
  350. c.awaitingMut.Lock()
  351. if rc := c.awaiting[hdr.msgID]; rc != nil {
  352. c.awaiting[hdr.msgID] = nil
  353. rc <- asyncResult{}
  354. close(rc)
  355. }
  356. c.awaitingMut.Unlock()
  357. }
  358. func (c *rawConnection) handleClusterConfig() error {
  359. var cm ClusterConfigMessage
  360. cm.decodeXDR(c.xr)
  361. if err := c.xr.Error(); err != nil {
  362. return err
  363. } else {
  364. go c.receiver.ClusterConfig(c.id, cm)
  365. }
  366. return nil
  367. }
  368. type encodable interface {
  369. encodeXDR(*xdr.Writer) (int, error)
  370. }
  371. type encodableBytes []byte
  372. func (e encodableBytes) encodeXDR(xw *xdr.Writer) (int, error) {
  373. return xw.WriteBytes(e)
  374. }
  375. func (c *rawConnection) send(h header, es ...encodable) bool {
  376. if h.msgID < 0 {
  377. select {
  378. case id := <-c.nextID:
  379. h.msgID = id
  380. case <-c.closed:
  381. return false
  382. }
  383. }
  384. msg := append([]encodable{h}, es...)
  385. select {
  386. case c.outbox <- msg:
  387. return true
  388. case <-c.closed:
  389. return false
  390. }
  391. }
  392. func (c *rawConnection) writerLoop() {
  393. for {
  394. select {
  395. case es := <-c.outbox:
  396. for _, e := range es {
  397. e.encodeXDR(c.xw)
  398. }
  399. if err := c.flush(); err != nil {
  400. c.close(err)
  401. return
  402. }
  403. case <-c.closed:
  404. return
  405. }
  406. }
  407. }
  408. type flusher interface {
  409. Flush() error
  410. }
  411. func (c *rawConnection) flush() error {
  412. if err := c.xw.Error(); err != nil {
  413. return err
  414. }
  415. if err := c.wb.Flush(); err != nil {
  416. return err
  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. }