protocol.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. package protocol
  2. import (
  3. "bufio"
  4. "compress/flate"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "sync"
  9. "time"
  10. "github.com/calmh/syncthing/xdr"
  11. )
  12. const BlockSize = 128 * 1024
  13. const (
  14. messageTypeClusterConfig = 0
  15. messageTypeIndex = 1
  16. messageTypeRequest = 2
  17. messageTypeResponse = 3
  18. messageTypePing = 4
  19. messageTypePong = 5
  20. messageTypeIndexUpdate = 6
  21. )
  22. const (
  23. FlagDeleted uint32 = 1 << 12
  24. FlagInvalid = 1 << 13
  25. FlagDirectory = 1 << 14
  26. FlagNoPermBits = 1 << 15
  27. )
  28. const (
  29. FlagShareTrusted uint32 = 1 << 0
  30. FlagShareReadOnly = 1 << 1
  31. FlagShareBits = 0x000000ff
  32. )
  33. var (
  34. ErrClusterHash = fmt.Errorf("configuration error: mismatched cluster hash")
  35. ErrClosed = errors.New("connection closed")
  36. )
  37. type Model interface {
  38. // An index was received from the peer node
  39. Index(nodeID string, repo string, files []FileInfo)
  40. // An index update was received from the peer node
  41. IndexUpdate(nodeID string, repo string, files []FileInfo)
  42. // A request was made by the peer node
  43. Request(nodeID string, repo string, name string, offset int64, size int) ([]byte, error)
  44. // A cluster configuration message was received
  45. ClusterConfig(nodeID string, config ClusterConfigMessage)
  46. // The peer node closed the connection
  47. Close(nodeID string, err error)
  48. }
  49. type Connection interface {
  50. ID() string
  51. Index(repo string, files []FileInfo)
  52. Request(repo string, name string, offset int64, size int) ([]byte, error)
  53. ClusterConfig(config ClusterConfigMessage)
  54. Statistics() Statistics
  55. }
  56. type rawConnection struct {
  57. id string
  58. receiver Model
  59. reader io.ReadCloser
  60. cr *countingReader
  61. xr *xdr.Reader
  62. writer io.WriteCloser
  63. cw *countingWriter
  64. wb *bufio.Writer
  65. xw *xdr.Writer
  66. wmut sync.Mutex
  67. indexSent map[string]map[string][2]int64
  68. awaiting []chan asyncResult
  69. imut sync.Mutex
  70. nextID chan int
  71. outbox chan []encodable
  72. closed chan struct{}
  73. }
  74. type asyncResult struct {
  75. val []byte
  76. err error
  77. }
  78. const (
  79. pingTimeout = 4 * time.Minute
  80. pingIdleTime = 5 * time.Minute
  81. )
  82. func NewConnection(nodeID string, reader io.Reader, writer io.Writer, receiver Model) Connection {
  83. cr := &countingReader{Reader: reader}
  84. cw := &countingWriter{Writer: writer}
  85. flrd := flate.NewReader(cr)
  86. flwr, err := flate.NewWriter(cw, flate.BestSpeed)
  87. if err != nil {
  88. panic(err)
  89. }
  90. wb := bufio.NewWriter(flwr)
  91. c := rawConnection{
  92. id: nodeID,
  93. receiver: nativeModel{receiver},
  94. reader: flrd,
  95. cr: cr,
  96. xr: xdr.NewReader(flrd),
  97. writer: flwr,
  98. cw: cw,
  99. wb: wb,
  100. xw: xdr.NewWriter(wb),
  101. awaiting: make([]chan asyncResult, 0x1000),
  102. indexSent: make(map[string]map[string][2]int64),
  103. outbox: make(chan []encodable),
  104. nextID: make(chan int),
  105. closed: make(chan struct{}),
  106. }
  107. go c.readerLoop()
  108. go c.writerLoop()
  109. go c.pingerLoop()
  110. go c.idGenerator()
  111. return wireFormatConnection{&c}
  112. }
  113. func (c *rawConnection) ID() string {
  114. return c.id
  115. }
  116. // Index writes the list of file information to the connected peer node
  117. func (c *rawConnection) Index(repo string, idx []FileInfo) {
  118. c.imut.Lock()
  119. var msgType int
  120. if c.indexSent[repo] == nil {
  121. // This is the first time we send an index.
  122. msgType = messageTypeIndex
  123. c.indexSent[repo] = make(map[string][2]int64)
  124. for _, f := range idx {
  125. c.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}
  126. }
  127. } else {
  128. // We have sent one full index. Only send updates now.
  129. msgType = messageTypeIndexUpdate
  130. var diff []FileInfo
  131. for _, f := range idx {
  132. if vs, ok := c.indexSent[repo][f.Name]; !ok || f.Modified != vs[0] || int64(f.Version) != vs[1] {
  133. diff = append(diff, f)
  134. c.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}
  135. }
  136. }
  137. idx = diff
  138. }
  139. c.imut.Unlock()
  140. c.send(header{0, -1, msgType}, IndexMessage{repo, idx})
  141. }
  142. // Request returns the bytes for the specified block after fetching them from the connected peer.
  143. func (c *rawConnection) Request(repo string, name string, offset int64, size int) ([]byte, error) {
  144. var id int
  145. select {
  146. case id = <-c.nextID:
  147. case <-c.closed:
  148. return nil, ErrClosed
  149. }
  150. c.imut.Lock()
  151. if ch := c.awaiting[id]; ch != nil {
  152. panic("id taken")
  153. }
  154. rc := make(chan asyncResult)
  155. c.awaiting[id] = rc
  156. c.imut.Unlock()
  157. ok := c.send(header{0, id, messageTypeRequest},
  158. RequestMessage{repo, name, uint64(offset), uint32(size)})
  159. if !ok {
  160. return nil, ErrClosed
  161. }
  162. res, ok := <-rc
  163. if !ok {
  164. return nil, ErrClosed
  165. }
  166. return res.val, res.err
  167. }
  168. // ClusterConfig send the cluster configuration message to the peer and returns any error
  169. func (c *rawConnection) ClusterConfig(config ClusterConfigMessage) {
  170. c.send(header{0, -1, messageTypeClusterConfig}, config)
  171. }
  172. func (c *rawConnection) ping() bool {
  173. var id int
  174. select {
  175. case id = <-c.nextID:
  176. case <-c.closed:
  177. return false
  178. }
  179. rc := make(chan asyncResult, 1)
  180. c.imut.Lock()
  181. c.awaiting[id] = rc
  182. c.imut.Unlock()
  183. ok := c.send(header{0, id, messageTypePing})
  184. if !ok {
  185. return false
  186. }
  187. res, ok := <-rc
  188. return ok && res.err == nil
  189. }
  190. func (c *rawConnection) readerLoop() (err error) {
  191. defer func() {
  192. c.close(err)
  193. }()
  194. for {
  195. select {
  196. case <-c.closed:
  197. return ErrClosed
  198. default:
  199. }
  200. var hdr header
  201. hdr.decodeXDR(c.xr)
  202. if err := c.xr.Error(); err != nil {
  203. return err
  204. }
  205. if hdr.version != 0 {
  206. return fmt.Errorf("protocol error: %s: unknown message version %#x", c.id, hdr.version)
  207. }
  208. switch hdr.msgType {
  209. case messageTypeIndex:
  210. if err := c.handleIndex(); err != nil {
  211. return err
  212. }
  213. case messageTypeIndexUpdate:
  214. if err := c.handleIndexUpdate(); err != nil {
  215. return err
  216. }
  217. case messageTypeRequest:
  218. if err := c.handleRequest(hdr); err != nil {
  219. return err
  220. }
  221. case messageTypeResponse:
  222. if err := c.handleResponse(hdr); err != nil {
  223. return err
  224. }
  225. case messageTypePing:
  226. c.send(header{0, hdr.msgID, messageTypePong})
  227. case messageTypePong:
  228. c.handlePong(hdr)
  229. case messageTypeClusterConfig:
  230. if err := c.handleClusterConfig(); err != nil {
  231. return err
  232. }
  233. default:
  234. return fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  235. }
  236. }
  237. }
  238. func (c *rawConnection) handleIndex() error {
  239. var im IndexMessage
  240. im.decodeXDR(c.xr)
  241. if err := c.xr.Error(); err != nil {
  242. return err
  243. } else {
  244. // We run this (and the corresponding one for update, below)
  245. // in a separate goroutine to avoid blocking the read loop.
  246. // There is otherwise a potential deadlock where both sides
  247. // has the model locked because it's sending a large index
  248. // update and can't receive the large index update from the
  249. // other side.
  250. go c.receiver.Index(c.id, im.Repository, im.Files)
  251. }
  252. return nil
  253. }
  254. func (c *rawConnection) handleIndexUpdate() error {
  255. var im IndexMessage
  256. im.decodeXDR(c.xr)
  257. if err := c.xr.Error(); err != nil {
  258. return err
  259. } else {
  260. go c.receiver.IndexUpdate(c.id, im.Repository, im.Files)
  261. }
  262. return nil
  263. }
  264. func (c *rawConnection) handleRequest(hdr header) error {
  265. var req RequestMessage
  266. req.decodeXDR(c.xr)
  267. if err := c.xr.Error(); err != nil {
  268. return err
  269. }
  270. go c.processRequest(hdr.msgID, req)
  271. return nil
  272. }
  273. func (c *rawConnection) handleResponse(hdr header) error {
  274. data := c.xr.ReadBytesMax(256 * 1024) // Sufficiently larger than max expected block size
  275. if err := c.xr.Error(); err != nil {
  276. return err
  277. }
  278. go func(hdr header, err error) {
  279. c.imut.Lock()
  280. rc := c.awaiting[hdr.msgID]
  281. c.awaiting[hdr.msgID] = nil
  282. c.imut.Unlock()
  283. if rc != nil {
  284. rc <- asyncResult{data, err}
  285. close(rc)
  286. }
  287. }(hdr, c.xr.Error())
  288. return nil
  289. }
  290. func (c *rawConnection) handlePong(hdr header) {
  291. c.imut.Lock()
  292. if rc := c.awaiting[hdr.msgID]; rc != nil {
  293. go func() {
  294. rc <- asyncResult{}
  295. close(rc)
  296. }()
  297. c.awaiting[hdr.msgID] = nil
  298. }
  299. c.imut.Unlock()
  300. }
  301. func (c *rawConnection) handleClusterConfig() error {
  302. var cm ClusterConfigMessage
  303. cm.decodeXDR(c.xr)
  304. if err := c.xr.Error(); err != nil {
  305. return err
  306. } else {
  307. go c.receiver.ClusterConfig(c.id, cm)
  308. }
  309. return nil
  310. }
  311. type encodable interface {
  312. encodeXDR(*xdr.Writer) (int, error)
  313. }
  314. type encodableBytes []byte
  315. func (e encodableBytes) encodeXDR(xw *xdr.Writer) (int, error) {
  316. return xw.WriteBytes(e)
  317. }
  318. func (c *rawConnection) send(h header, es ...encodable) bool {
  319. if h.msgID < 0 {
  320. select {
  321. case id := <-c.nextID:
  322. h.msgID = id
  323. case <-c.closed:
  324. return false
  325. }
  326. }
  327. msg := append([]encodable{h}, es...)
  328. select {
  329. case c.outbox <- msg:
  330. return true
  331. case <-c.closed:
  332. return false
  333. }
  334. }
  335. func (c *rawConnection) writerLoop() {
  336. var err error
  337. for es := range c.outbox {
  338. c.wmut.Lock()
  339. for _, e := range es {
  340. e.encodeXDR(c.xw)
  341. }
  342. if err = c.flush(); err != nil {
  343. c.wmut.Unlock()
  344. c.close(err)
  345. return
  346. }
  347. c.wmut.Unlock()
  348. }
  349. }
  350. type flusher interface {
  351. Flush() error
  352. }
  353. func (c *rawConnection) flush() error {
  354. if err := c.xw.Error(); err != nil {
  355. return err
  356. }
  357. if err := c.wb.Flush(); err != nil {
  358. return err
  359. }
  360. if f, ok := c.writer.(flusher); ok {
  361. return f.Flush()
  362. }
  363. return nil
  364. }
  365. func (c *rawConnection) close(err error) {
  366. c.imut.Lock()
  367. c.wmut.Lock()
  368. defer c.imut.Unlock()
  369. defer c.wmut.Unlock()
  370. select {
  371. case <-c.closed:
  372. return
  373. default:
  374. close(c.closed)
  375. for i, ch := range c.awaiting {
  376. if ch != nil {
  377. close(ch)
  378. c.awaiting[i] = nil
  379. }
  380. }
  381. c.writer.Close()
  382. c.reader.Close()
  383. go c.receiver.Close(c.id, err)
  384. }
  385. }
  386. func (c *rawConnection) idGenerator() {
  387. nextID := 0
  388. for {
  389. nextID = (nextID + 1) & 0xfff
  390. select {
  391. case c.nextID <- nextID:
  392. case <-c.closed:
  393. return
  394. }
  395. }
  396. }
  397. func (c *rawConnection) pingerLoop() {
  398. var rc = make(chan bool, 1)
  399. ticker := time.Tick(pingIdleTime / 2)
  400. for {
  401. select {
  402. case <-ticker:
  403. go func() {
  404. rc <- c.ping()
  405. }()
  406. select {
  407. case ok := <-rc:
  408. if !ok {
  409. c.close(fmt.Errorf("ping failure"))
  410. }
  411. case <-time.After(pingTimeout):
  412. c.close(fmt.Errorf("ping timeout"))
  413. case <-c.closed:
  414. return
  415. }
  416. case <-c.closed:
  417. return
  418. }
  419. }
  420. }
  421. func (c *rawConnection) processRequest(msgID int, req RequestMessage) {
  422. data, _ := c.receiver.Request(c.id, req.Repository, req.Name, int64(req.Offset), int(req.Size))
  423. c.send(header{0, msgID, messageTypeResponse},
  424. encodableBytes(data))
  425. }
  426. type Statistics struct {
  427. At time.Time
  428. InBytesTotal int
  429. OutBytesTotal int
  430. }
  431. func (c *rawConnection) Statistics() Statistics {
  432. return Statistics{
  433. At: time.Now(),
  434. InBytesTotal: int(c.cr.Tot()),
  435. OutBytesTotal: int(c.cw.Tot()),
  436. }
  437. }
  438. func IsDeleted(bits uint32) bool {
  439. return bits&FlagDeleted != 0
  440. }
  441. func IsInvalid(bits uint32) bool {
  442. return bits&FlagInvalid != 0
  443. }
  444. func IsDirectory(bits uint32) bool {
  445. return bits&FlagDirectory != 0
  446. }
  447. func HasPermissionBits(bits uint32) bool {
  448. return bits&FlagNoPermBits == 0
  449. }