protocol.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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]uint64
  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. indexSent: make(map[string]uint64),
  102. awaiting: make([]chan asyncResult, 0x1000),
  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. maxSent := c.indexSent[repo]
  121. var newMaxSent uint64
  122. if maxSent == 0 {
  123. // This is the first time we send an index.
  124. msgType = messageTypeIndex
  125. for _, f := range idx {
  126. if f.Version > newMaxSent {
  127. newMaxSent = f.Version
  128. }
  129. }
  130. } else {
  131. // We have sent one full index. Only send updates now.
  132. msgType = messageTypeIndexUpdate
  133. var diff []FileInfo
  134. for _, f := range idx {
  135. if f.Version > maxSent {
  136. diff = append(diff, f)
  137. newMaxSent = f.Version
  138. }
  139. }
  140. idx = diff
  141. }
  142. c.indexSent[repo] = newMaxSent
  143. c.imut.Unlock()
  144. c.send(header{0, -1, msgType}, IndexMessage{repo, idx})
  145. }
  146. // Request returns the bytes for the specified block after fetching them from the connected peer.
  147. func (c *rawConnection) Request(repo string, name string, offset int64, size int) ([]byte, error) {
  148. var id int
  149. select {
  150. case id = <-c.nextID:
  151. case <-c.closed:
  152. return nil, ErrClosed
  153. }
  154. c.imut.Lock()
  155. if ch := c.awaiting[id]; ch != nil {
  156. panic("id taken")
  157. }
  158. rc := make(chan asyncResult)
  159. c.awaiting[id] = rc
  160. c.imut.Unlock()
  161. ok := c.send(header{0, id, messageTypeRequest},
  162. RequestMessage{repo, name, uint64(offset), uint32(size)})
  163. if !ok {
  164. return nil, ErrClosed
  165. }
  166. res, ok := <-rc
  167. if !ok {
  168. return nil, ErrClosed
  169. }
  170. return res.val, res.err
  171. }
  172. // ClusterConfig send the cluster configuration message to the peer and returns any error
  173. func (c *rawConnection) ClusterConfig(config ClusterConfigMessage) {
  174. c.send(header{0, -1, messageTypeClusterConfig}, config)
  175. }
  176. func (c *rawConnection) ping() bool {
  177. var id int
  178. select {
  179. case id = <-c.nextID:
  180. case <-c.closed:
  181. return false
  182. }
  183. rc := make(chan asyncResult, 1)
  184. c.imut.Lock()
  185. c.awaiting[id] = rc
  186. c.imut.Unlock()
  187. ok := c.send(header{0, id, messageTypePing})
  188. if !ok {
  189. return false
  190. }
  191. res, ok := <-rc
  192. return ok && res.err == nil
  193. }
  194. func (c *rawConnection) readerLoop() (err error) {
  195. defer func() {
  196. c.close(err)
  197. }()
  198. for {
  199. select {
  200. case <-c.closed:
  201. return ErrClosed
  202. default:
  203. }
  204. var hdr header
  205. hdr.decodeXDR(c.xr)
  206. if err := c.xr.Error(); err != nil {
  207. return err
  208. }
  209. if hdr.version != 0 {
  210. return fmt.Errorf("protocol error: %s: unknown message version %#x", c.id, hdr.version)
  211. }
  212. switch hdr.msgType {
  213. case messageTypeIndex:
  214. if err := c.handleIndex(); err != nil {
  215. return err
  216. }
  217. case messageTypeIndexUpdate:
  218. if err := c.handleIndexUpdate(); err != nil {
  219. return err
  220. }
  221. case messageTypeRequest:
  222. if err := c.handleRequest(hdr); err != nil {
  223. return err
  224. }
  225. case messageTypeResponse:
  226. if err := c.handleResponse(hdr); err != nil {
  227. return err
  228. }
  229. case messageTypePing:
  230. c.send(header{0, hdr.msgID, messageTypePong})
  231. case messageTypePong:
  232. c.handlePong(hdr)
  233. case messageTypeClusterConfig:
  234. if err := c.handleClusterConfig(); err != nil {
  235. return err
  236. }
  237. default:
  238. return fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  239. }
  240. }
  241. }
  242. func (c *rawConnection) handleIndex() error {
  243. var im IndexMessage
  244. im.decodeXDR(c.xr)
  245. if err := c.xr.Error(); err != nil {
  246. return err
  247. } else {
  248. // We run this (and the corresponding one for update, below)
  249. // in a separate goroutine to avoid blocking the read loop.
  250. // There is otherwise a potential deadlock where both sides
  251. // has the model locked because it's sending a large index
  252. // update and can't receive the large index update from the
  253. // other side.
  254. go c.receiver.Index(c.id, im.Repository, im.Files)
  255. }
  256. return nil
  257. }
  258. func (c *rawConnection) handleIndexUpdate() error {
  259. var im IndexMessage
  260. im.decodeXDR(c.xr)
  261. if err := c.xr.Error(); err != nil {
  262. return err
  263. } else {
  264. go c.receiver.IndexUpdate(c.id, im.Repository, im.Files)
  265. }
  266. return nil
  267. }
  268. func (c *rawConnection) handleRequest(hdr header) error {
  269. var req RequestMessage
  270. req.decodeXDR(c.xr)
  271. if err := c.xr.Error(); err != nil {
  272. return err
  273. }
  274. go c.processRequest(hdr.msgID, req)
  275. return nil
  276. }
  277. func (c *rawConnection) handleResponse(hdr header) error {
  278. data := c.xr.ReadBytesMax(256 * 1024) // Sufficiently larger than max expected block size
  279. if err := c.xr.Error(); err != nil {
  280. return err
  281. }
  282. go func(hdr header, err error) {
  283. c.imut.Lock()
  284. rc := c.awaiting[hdr.msgID]
  285. c.awaiting[hdr.msgID] = nil
  286. c.imut.Unlock()
  287. if rc != nil {
  288. rc <- asyncResult{data, err}
  289. close(rc)
  290. }
  291. }(hdr, c.xr.Error())
  292. return nil
  293. }
  294. func (c *rawConnection) handlePong(hdr header) {
  295. c.imut.Lock()
  296. if rc := c.awaiting[hdr.msgID]; rc != nil {
  297. go func() {
  298. rc <- asyncResult{}
  299. close(rc)
  300. }()
  301. c.awaiting[hdr.msgID] = nil
  302. }
  303. c.imut.Unlock()
  304. }
  305. func (c *rawConnection) handleClusterConfig() error {
  306. var cm ClusterConfigMessage
  307. cm.decodeXDR(c.xr)
  308. if err := c.xr.Error(); err != nil {
  309. return err
  310. } else {
  311. go c.receiver.ClusterConfig(c.id, cm)
  312. }
  313. return nil
  314. }
  315. type encodable interface {
  316. encodeXDR(*xdr.Writer) (int, error)
  317. }
  318. type encodableBytes []byte
  319. func (e encodableBytes) encodeXDR(xw *xdr.Writer) (int, error) {
  320. return xw.WriteBytes(e)
  321. }
  322. func (c *rawConnection) send(h header, es ...encodable) bool {
  323. if h.msgID < 0 {
  324. select {
  325. case id := <-c.nextID:
  326. h.msgID = id
  327. case <-c.closed:
  328. return false
  329. }
  330. }
  331. msg := append([]encodable{h}, es...)
  332. select {
  333. case c.outbox <- msg:
  334. return true
  335. case <-c.closed:
  336. return false
  337. }
  338. }
  339. func (c *rawConnection) writerLoop() {
  340. var err error
  341. for es := range c.outbox {
  342. c.wmut.Lock()
  343. for _, e := range es {
  344. e.encodeXDR(c.xw)
  345. }
  346. if err = c.flush(); err != nil {
  347. c.wmut.Unlock()
  348. c.close(err)
  349. return
  350. }
  351. c.wmut.Unlock()
  352. }
  353. }
  354. type flusher interface {
  355. Flush() error
  356. }
  357. func (c *rawConnection) flush() error {
  358. if err := c.xw.Error(); err != nil {
  359. return err
  360. }
  361. if err := c.wb.Flush(); err != nil {
  362. return err
  363. }
  364. if f, ok := c.writer.(flusher); ok {
  365. return f.Flush()
  366. }
  367. return nil
  368. }
  369. func (c *rawConnection) close(err error) {
  370. c.imut.Lock()
  371. c.wmut.Lock()
  372. defer c.imut.Unlock()
  373. defer c.wmut.Unlock()
  374. select {
  375. case <-c.closed:
  376. return
  377. default:
  378. close(c.closed)
  379. for i, ch := range c.awaiting {
  380. if ch != nil {
  381. close(ch)
  382. c.awaiting[i] = nil
  383. }
  384. }
  385. c.writer.Close()
  386. c.reader.Close()
  387. go c.receiver.Close(c.id, err)
  388. }
  389. }
  390. func (c *rawConnection) idGenerator() {
  391. nextID := 0
  392. for {
  393. nextID = (nextID + 1) & 0xfff
  394. select {
  395. case c.nextID <- nextID:
  396. case <-c.closed:
  397. return
  398. }
  399. }
  400. }
  401. func (c *rawConnection) pingerLoop() {
  402. var rc = make(chan bool, 1)
  403. ticker := time.Tick(pingIdleTime / 2)
  404. for {
  405. select {
  406. case <-ticker:
  407. go func() {
  408. rc <- c.ping()
  409. }()
  410. select {
  411. case ok := <-rc:
  412. if !ok {
  413. c.close(fmt.Errorf("ping failure"))
  414. }
  415. case <-time.After(pingTimeout):
  416. c.close(fmt.Errorf("ping timeout"))
  417. case <-c.closed:
  418. return
  419. }
  420. case <-c.closed:
  421. return
  422. }
  423. }
  424. }
  425. func (c *rawConnection) processRequest(msgID int, req RequestMessage) {
  426. data, _ := c.receiver.Request(c.id, req.Repository, req.Name, int64(req.Offset), int(req.Size))
  427. c.send(header{0, msgID, messageTypeResponse},
  428. encodableBytes(data))
  429. }
  430. type Statistics struct {
  431. At time.Time
  432. InBytesTotal int
  433. OutBytesTotal int
  434. }
  435. func (c *rawConnection) Statistics() Statistics {
  436. return Statistics{
  437. At: time.Now(),
  438. InBytesTotal: int(c.cr.Tot()),
  439. OutBytesTotal: int(c.cw.Tot()),
  440. }
  441. }
  442. func IsDeleted(bits uint32) bool {
  443. return bits&FlagDeleted != 0
  444. }
  445. func IsInvalid(bits uint32) bool {
  446. return bits&FlagInvalid != 0
  447. }
  448. func IsDirectory(bits uint32) bool {
  449. return bits&FlagDirectory != 0
  450. }
  451. func HasPermissionBits(bits uint32) bool {
  452. return bits&FlagNoPermBits == 0
  453. }