protocol.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. c.receiver.IndexUpdate(ii.id, ii.repo, ii.files)
  280. } else {
  281. c.receiver.Index(ii.id, ii.repo, ii.files)
  282. }
  283. case <-c.closed:
  284. return
  285. }
  286. }
  287. }
  288. func (c *rawConnection) handleIndex() error {
  289. var im IndexMessage
  290. im.decodeXDR(c.xr)
  291. if err := c.xr.Error(); err != nil {
  292. return err
  293. } else {
  294. // We run this (and the corresponding one for update, below)
  295. // in a separate goroutine to avoid blocking the read loop.
  296. // There is otherwise a potential deadlock where both sides
  297. // has the model locked because it's sending a large index
  298. // update and can't receive the large index update from the
  299. // other side.
  300. incomingIndexes <- incomingIndex{false, c.id, im.Repository, im.Files}
  301. }
  302. return nil
  303. }
  304. func (c *rawConnection) handleIndexUpdate() error {
  305. var im IndexMessage
  306. im.decodeXDR(c.xr)
  307. if err := c.xr.Error(); err != nil {
  308. return err
  309. } else {
  310. incomingIndexes <- incomingIndex{true, c.id, im.Repository, im.Files}
  311. }
  312. return nil
  313. }
  314. func (c *rawConnection) handleRequest(hdr header) error {
  315. var req RequestMessage
  316. req.decodeXDR(c.xr)
  317. if err := c.xr.Error(); err != nil {
  318. return err
  319. }
  320. go c.processRequest(hdr.msgID, req)
  321. return nil
  322. }
  323. func (c *rawConnection) handleResponse(hdr header) error {
  324. data := c.xr.ReadBytesMax(256 * 1024) // Sufficiently larger than max expected block size
  325. if err := c.xr.Error(); err != nil {
  326. return err
  327. }
  328. c.awaitingMut.Lock()
  329. if rc := c.awaiting[hdr.msgID]; rc != nil {
  330. c.awaiting[hdr.msgID] = nil
  331. rc <- asyncResult{data, nil}
  332. close(rc)
  333. }
  334. c.awaitingMut.Unlock()
  335. return nil
  336. }
  337. func (c *rawConnection) handlePong(hdr header) {
  338. c.awaitingMut.Lock()
  339. if rc := c.awaiting[hdr.msgID]; rc != nil {
  340. c.awaiting[hdr.msgID] = nil
  341. rc <- asyncResult{}
  342. close(rc)
  343. }
  344. c.awaitingMut.Unlock()
  345. }
  346. func (c *rawConnection) handleClusterConfig() error {
  347. var cm ClusterConfigMessage
  348. cm.decodeXDR(c.xr)
  349. if err := c.xr.Error(); err != nil {
  350. return err
  351. } else {
  352. go c.receiver.ClusterConfig(c.id, cm)
  353. }
  354. return nil
  355. }
  356. type encodable interface {
  357. encodeXDR(*xdr.Writer) (int, error)
  358. }
  359. type encodableBytes []byte
  360. func (e encodableBytes) encodeXDR(xw *xdr.Writer) (int, error) {
  361. return xw.WriteBytes(e)
  362. }
  363. func (c *rawConnection) send(h header, es ...encodable) bool {
  364. if h.msgID < 0 {
  365. select {
  366. case id := <-c.nextID:
  367. h.msgID = id
  368. case <-c.closed:
  369. return false
  370. }
  371. }
  372. msg := append([]encodable{h}, es...)
  373. select {
  374. case c.outbox <- msg:
  375. return true
  376. case <-c.closed:
  377. return false
  378. }
  379. }
  380. func (c *rawConnection) writerLoop() {
  381. for {
  382. select {
  383. case es := <-c.outbox:
  384. for _, e := range es {
  385. e.encodeXDR(c.xw)
  386. }
  387. if err := c.flush(); err != nil {
  388. c.close(err)
  389. return
  390. }
  391. case <-c.closed:
  392. return
  393. }
  394. }
  395. }
  396. type flusher interface {
  397. Flush() error
  398. }
  399. func (c *rawConnection) flush() error {
  400. if err := c.xw.Error(); err != nil {
  401. return err
  402. }
  403. if err := c.wb.Flush(); err != nil {
  404. return err
  405. }
  406. return nil
  407. }
  408. func (c *rawConnection) close(err error) {
  409. c.once.Do(func() {
  410. close(c.closed)
  411. c.awaitingMut.Lock()
  412. for i, ch := range c.awaiting {
  413. if ch != nil {
  414. close(ch)
  415. c.awaiting[i] = nil
  416. }
  417. }
  418. c.awaitingMut.Unlock()
  419. go c.receiver.Close(c.id, err)
  420. })
  421. }
  422. func (c *rawConnection) idGenerator() {
  423. nextID := 0
  424. for {
  425. nextID = (nextID + 1) & 0xfff
  426. select {
  427. case c.nextID <- nextID:
  428. case <-c.closed:
  429. return
  430. }
  431. }
  432. }
  433. func (c *rawConnection) pingerLoop() {
  434. var rc = make(chan bool, 1)
  435. ticker := time.Tick(pingIdleTime / 2)
  436. for {
  437. select {
  438. case <-ticker:
  439. if d := time.Since(c.xr.LastRead()); d < pingIdleTime {
  440. if debug {
  441. l.Debugln(c.id, "ping skipped after rd", d)
  442. }
  443. continue
  444. }
  445. if d := time.Since(c.xw.LastWrite()); d < pingIdleTime {
  446. if debug {
  447. l.Debugln(c.id, "ping skipped after wr", d)
  448. }
  449. continue
  450. }
  451. go func() {
  452. if debug {
  453. l.Debugln(c.id, "ping ->")
  454. }
  455. rc <- c.ping()
  456. }()
  457. select {
  458. case ok := <-rc:
  459. if debug {
  460. l.Debugln(c.id, "<- pong")
  461. }
  462. if !ok {
  463. c.close(fmt.Errorf("ping failure"))
  464. }
  465. case <-time.After(pingTimeout):
  466. c.close(fmt.Errorf("ping timeout"))
  467. case <-c.closed:
  468. return
  469. }
  470. case <-c.closed:
  471. return
  472. }
  473. }
  474. }
  475. func (c *rawConnection) processRequest(msgID int, req RequestMessage) {
  476. data, _ := c.receiver.Request(c.id, req.Repository, req.Name, int64(req.Offset), int(req.Size))
  477. c.send(header{0, msgID, messageTypeResponse}, encodableBytes(data))
  478. }
  479. type Statistics struct {
  480. At time.Time
  481. InBytesTotal uint64
  482. OutBytesTotal uint64
  483. }
  484. func (c *rawConnection) Statistics() Statistics {
  485. return Statistics{
  486. At: time.Now(),
  487. InBytesTotal: c.cr.Tot(),
  488. OutBytesTotal: c.cw.Tot(),
  489. }
  490. }
  491. func IsDeleted(bits uint32) bool {
  492. return bits&FlagDeleted != 0
  493. }
  494. func IsInvalid(bits uint32) bool {
  495. return bits&FlagInvalid != 0
  496. }
  497. func IsDirectory(bits uint32) bool {
  498. return bits&FlagDirectory != 0
  499. }
  500. func HasPermissionBits(bits uint32) bool {
  501. return bits&FlagNoPermBits == 0
  502. }