protocol.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package protocol
  16. import (
  17. "encoding/binary"
  18. "encoding/hex"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "sync"
  23. "time"
  24. lz4 "github.com/bkaradzic/go-lz4"
  25. )
  26. const (
  27. BlockSize = 128 * 1024
  28. )
  29. const (
  30. messageTypeClusterConfig = 0
  31. messageTypeIndex = 1
  32. messageTypeRequest = 2
  33. messageTypeResponse = 3
  34. messageTypePing = 4
  35. messageTypePong = 5
  36. messageTypeIndexUpdate = 6
  37. messageTypeClose = 7
  38. )
  39. const (
  40. stateInitial = iota
  41. stateCCRcvd
  42. stateIdxRcvd
  43. )
  44. const (
  45. FlagDeleted uint32 = 1 << 12
  46. FlagInvalid = 1 << 13
  47. FlagDirectory = 1 << 14
  48. FlagNoPermBits = 1 << 15
  49. FlagSymlink = 1 << 16
  50. FlagSymlinkMissingTarget = 1 << 17
  51. SymlinkTypeMask = FlagDirectory | FlagSymlinkMissingTarget
  52. )
  53. const (
  54. FlagShareTrusted uint32 = 1 << 0
  55. FlagShareReadOnly = 1 << 1
  56. FlagIntroducer = 1 << 2
  57. FlagShareBits = 0x000000ff
  58. )
  59. var (
  60. ErrClusterHash = fmt.Errorf("configuration error: mismatched cluster hash")
  61. ErrClosed = errors.New("connection closed")
  62. )
  63. type Model interface {
  64. // An index was received from the peer device
  65. Index(deviceID DeviceID, folder string, files []FileInfo)
  66. // An index update was received from the peer device
  67. IndexUpdate(deviceID DeviceID, folder string, files []FileInfo)
  68. // A request was made by the peer device
  69. Request(deviceID DeviceID, folder string, name string, offset int64, size int) ([]byte, error)
  70. // A cluster configuration message was received
  71. ClusterConfig(deviceID DeviceID, config ClusterConfigMessage)
  72. // The peer device closed the connection
  73. Close(deviceID DeviceID, err error)
  74. }
  75. type Connection interface {
  76. ID() DeviceID
  77. Name() string
  78. Index(folder string, files []FileInfo) error
  79. IndexUpdate(folder string, files []FileInfo) error
  80. Request(folder string, name string, offset int64, size int) ([]byte, error)
  81. ClusterConfig(config ClusterConfigMessage)
  82. Statistics() Statistics
  83. }
  84. type rawConnection struct {
  85. id DeviceID
  86. name string
  87. receiver Model
  88. state int
  89. cr *countingReader
  90. cw *countingWriter
  91. awaiting [4096]chan asyncResult
  92. awaitingMut sync.Mutex
  93. idxMut sync.Mutex // ensures serialization of Index calls
  94. nextID chan int
  95. outbox chan hdrMsg
  96. closed chan struct{}
  97. once sync.Once
  98. compressionThreshold int // compress messages larger than this many bytes
  99. rdbuf0 []byte // used & reused by readMessage
  100. rdbuf1 []byte // used & reused by readMessage
  101. }
  102. type asyncResult struct {
  103. val []byte
  104. err error
  105. }
  106. type hdrMsg struct {
  107. hdr header
  108. msg encodable
  109. }
  110. type encodable interface {
  111. AppendXDR([]byte) ([]byte, error)
  112. }
  113. const (
  114. pingTimeout = 30 * time.Second
  115. pingIdleTime = 60 * time.Second
  116. )
  117. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress bool) Connection {
  118. cr := &countingReader{Reader: reader}
  119. cw := &countingWriter{Writer: writer}
  120. compThres := 1<<31 - 1 // compression disabled
  121. if compress {
  122. compThres = 128 // compress messages that are 128 bytes long or larger
  123. }
  124. c := rawConnection{
  125. id: deviceID,
  126. name: name,
  127. receiver: nativeModel{receiver},
  128. state: stateInitial,
  129. cr: cr,
  130. cw: cw,
  131. outbox: make(chan hdrMsg),
  132. nextID: make(chan int),
  133. closed: make(chan struct{}),
  134. compressionThreshold: compThres,
  135. }
  136. go c.readerLoop()
  137. go c.writerLoop()
  138. go c.pingerLoop()
  139. go c.idGenerator()
  140. return wireFormatConnection{&c}
  141. }
  142. func (c *rawConnection) ID() DeviceID {
  143. return c.id
  144. }
  145. func (c *rawConnection) Name() string {
  146. return c.name
  147. }
  148. // Index writes the list of file information to the connected peer device
  149. func (c *rawConnection) Index(folder string, idx []FileInfo) error {
  150. select {
  151. case <-c.closed:
  152. return ErrClosed
  153. default:
  154. }
  155. c.idxMut.Lock()
  156. c.send(-1, messageTypeIndex, IndexMessage{folder, idx})
  157. c.idxMut.Unlock()
  158. return nil
  159. }
  160. // IndexUpdate writes the list of file information to the connected peer device as an update
  161. func (c *rawConnection) IndexUpdate(folder string, idx []FileInfo) error {
  162. select {
  163. case <-c.closed:
  164. return ErrClosed
  165. default:
  166. }
  167. c.idxMut.Lock()
  168. c.send(-1, messageTypeIndexUpdate, IndexMessage{folder, idx})
  169. c.idxMut.Unlock()
  170. return nil
  171. }
  172. // Request returns the bytes for the specified block after fetching them from the connected peer.
  173. func (c *rawConnection) Request(folder string, name string, offset int64, size int) ([]byte, error) {
  174. var id int
  175. select {
  176. case id = <-c.nextID:
  177. case <-c.closed:
  178. return nil, ErrClosed
  179. }
  180. c.awaitingMut.Lock()
  181. if ch := c.awaiting[id]; ch != nil {
  182. panic("id taken")
  183. }
  184. rc := make(chan asyncResult, 1)
  185. c.awaiting[id] = rc
  186. c.awaitingMut.Unlock()
  187. ok := c.send(id, messageTypeRequest, RequestMessage{folder, name, uint64(offset), uint32(size)})
  188. if !ok {
  189. return nil, ErrClosed
  190. }
  191. res, ok := <-rc
  192. if !ok {
  193. return nil, ErrClosed
  194. }
  195. return res.val, res.err
  196. }
  197. // ClusterConfig send the cluster configuration message to the peer and returns any error
  198. func (c *rawConnection) ClusterConfig(config ClusterConfigMessage) {
  199. c.send(-1, messageTypeClusterConfig, config)
  200. }
  201. func (c *rawConnection) ping() bool {
  202. var id int
  203. select {
  204. case id = <-c.nextID:
  205. case <-c.closed:
  206. return false
  207. }
  208. rc := make(chan asyncResult, 1)
  209. c.awaitingMut.Lock()
  210. c.awaiting[id] = rc
  211. c.awaitingMut.Unlock()
  212. ok := c.send(id, messageTypePing, nil)
  213. if !ok {
  214. return false
  215. }
  216. res, ok := <-rc
  217. return ok && res.err == nil
  218. }
  219. func (c *rawConnection) readerLoop() (err error) {
  220. defer func() {
  221. c.close(err)
  222. }()
  223. for {
  224. select {
  225. case <-c.closed:
  226. return ErrClosed
  227. default:
  228. }
  229. hdr, msg, err := c.readMessage()
  230. if err != nil {
  231. return err
  232. }
  233. switch hdr.msgType {
  234. case messageTypeIndex:
  235. if c.state < stateCCRcvd {
  236. return fmt.Errorf("protocol error: index message in state %d", c.state)
  237. }
  238. c.handleIndex(msg.(IndexMessage))
  239. c.state = stateIdxRcvd
  240. case messageTypeIndexUpdate:
  241. if c.state < stateIdxRcvd {
  242. return fmt.Errorf("protocol error: index update message in state %d", c.state)
  243. }
  244. c.handleIndexUpdate(msg.(IndexMessage))
  245. case messageTypeRequest:
  246. if c.state < stateIdxRcvd {
  247. return fmt.Errorf("protocol error: request message in state %d", c.state)
  248. }
  249. // Requests are handled asynchronously
  250. go c.handleRequest(hdr.msgID, msg.(RequestMessage))
  251. case messageTypeResponse:
  252. if c.state < stateIdxRcvd {
  253. return fmt.Errorf("protocol error: response message in state %d", c.state)
  254. }
  255. c.handleResponse(hdr.msgID, msg.(ResponseMessage))
  256. case messageTypePing:
  257. c.send(hdr.msgID, messageTypePong, EmptyMessage{})
  258. case messageTypePong:
  259. c.handlePong(hdr.msgID)
  260. case messageTypeClusterConfig:
  261. if c.state != stateInitial {
  262. return fmt.Errorf("protocol error: cluster config message in state %d", c.state)
  263. }
  264. go c.receiver.ClusterConfig(c.id, msg.(ClusterConfigMessage))
  265. c.state = stateCCRcvd
  266. case messageTypeClose:
  267. return errors.New(msg.(CloseMessage).Reason)
  268. default:
  269. return fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  270. }
  271. }
  272. }
  273. func (c *rawConnection) readMessage() (hdr header, msg encodable, err error) {
  274. if cap(c.rdbuf0) < 8 {
  275. c.rdbuf0 = make([]byte, 8)
  276. } else {
  277. c.rdbuf0 = c.rdbuf0[:8]
  278. }
  279. _, err = io.ReadFull(c.cr, c.rdbuf0)
  280. if err != nil {
  281. return
  282. }
  283. hdr = decodeHeader(binary.BigEndian.Uint32(c.rdbuf0[0:4]))
  284. msglen := int(binary.BigEndian.Uint32(c.rdbuf0[4:8]))
  285. if debug {
  286. l.Debugf("read header %v (msglen=%d)", hdr, msglen)
  287. }
  288. if cap(c.rdbuf0) < msglen {
  289. c.rdbuf0 = make([]byte, msglen)
  290. } else {
  291. c.rdbuf0 = c.rdbuf0[:msglen]
  292. }
  293. _, err = io.ReadFull(c.cr, c.rdbuf0)
  294. if err != nil {
  295. return
  296. }
  297. if debug {
  298. l.Debugf("read %d bytes", len(c.rdbuf0))
  299. }
  300. msgBuf := c.rdbuf0
  301. if hdr.compression {
  302. c.rdbuf1 = c.rdbuf1[:cap(c.rdbuf1)]
  303. c.rdbuf1, err = lz4.Decode(c.rdbuf1, c.rdbuf0)
  304. if err != nil {
  305. return
  306. }
  307. msgBuf = c.rdbuf1
  308. if debug {
  309. l.Debugf("decompressed to %d bytes", len(msgBuf))
  310. }
  311. }
  312. if debug {
  313. if len(msgBuf) > 1024 {
  314. l.Debugf("message data:\n%s", hex.Dump(msgBuf[:1024]))
  315. } else {
  316. l.Debugf("message data:\n%s", hex.Dump(msgBuf))
  317. }
  318. }
  319. switch hdr.msgType {
  320. case messageTypeIndex, messageTypeIndexUpdate:
  321. var idx IndexMessage
  322. err = idx.UnmarshalXDR(msgBuf)
  323. msg = idx
  324. case messageTypeRequest:
  325. var req RequestMessage
  326. err = req.UnmarshalXDR(msgBuf)
  327. msg = req
  328. case messageTypeResponse:
  329. var resp ResponseMessage
  330. err = resp.UnmarshalXDR(msgBuf)
  331. msg = resp
  332. case messageTypePing, messageTypePong:
  333. msg = EmptyMessage{}
  334. case messageTypeClusterConfig:
  335. var cc ClusterConfigMessage
  336. err = cc.UnmarshalXDR(msgBuf)
  337. msg = cc
  338. case messageTypeClose:
  339. var cm CloseMessage
  340. err = cm.UnmarshalXDR(msgBuf)
  341. msg = cm
  342. default:
  343. err = fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  344. }
  345. return
  346. }
  347. func (c *rawConnection) handleIndex(im IndexMessage) {
  348. if debug {
  349. l.Debugf("Index(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  350. }
  351. c.receiver.Index(c.id, im.Folder, im.Files)
  352. }
  353. func (c *rawConnection) handleIndexUpdate(im IndexMessage) {
  354. if debug {
  355. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  356. }
  357. c.receiver.IndexUpdate(c.id, im.Folder, im.Files)
  358. }
  359. func (c *rawConnection) handleRequest(msgID int, req RequestMessage) {
  360. data, _ := c.receiver.Request(c.id, req.Folder, req.Name, int64(req.Offset), int(req.Size))
  361. c.send(msgID, messageTypeResponse, ResponseMessage{data})
  362. }
  363. func (c *rawConnection) handleResponse(msgID int, resp ResponseMessage) {
  364. c.awaitingMut.Lock()
  365. if rc := c.awaiting[msgID]; rc != nil {
  366. c.awaiting[msgID] = nil
  367. rc <- asyncResult{resp.Data, nil}
  368. close(rc)
  369. }
  370. c.awaitingMut.Unlock()
  371. }
  372. func (c *rawConnection) handlePong(msgID int) {
  373. c.awaitingMut.Lock()
  374. if rc := c.awaiting[msgID]; rc != nil {
  375. c.awaiting[msgID] = nil
  376. rc <- asyncResult{}
  377. close(rc)
  378. }
  379. c.awaitingMut.Unlock()
  380. }
  381. func (c *rawConnection) send(msgID int, msgType int, msg encodable) bool {
  382. if msgID < 0 {
  383. select {
  384. case id := <-c.nextID:
  385. msgID = id
  386. case <-c.closed:
  387. return false
  388. }
  389. }
  390. hdr := header{
  391. version: 0,
  392. msgID: msgID,
  393. msgType: msgType,
  394. }
  395. select {
  396. case c.outbox <- hdrMsg{hdr, msg}:
  397. return true
  398. case <-c.closed:
  399. return false
  400. }
  401. }
  402. func (c *rawConnection) writerLoop() {
  403. var msgBuf = make([]byte, 8) // buffer for wire format message, kept and reused
  404. var uncBuf []byte // buffer for uncompressed message, kept and reused
  405. for {
  406. var tempBuf []byte
  407. var err error
  408. select {
  409. case hm := <-c.outbox:
  410. if hm.msg != nil {
  411. // Uncompressed message in uncBuf
  412. uncBuf, err = hm.msg.AppendXDR(uncBuf[:0])
  413. if err != nil {
  414. c.close(err)
  415. return
  416. }
  417. if len(uncBuf) >= c.compressionThreshold {
  418. // Use compression for large messages
  419. hm.hdr.compression = true
  420. // Make sure we have enough space for the compressed message plus header in msgBug
  421. msgBuf = msgBuf[:cap(msgBuf)]
  422. if maxLen := lz4.CompressBound(len(uncBuf)) + 8; maxLen > len(msgBuf) {
  423. msgBuf = make([]byte, maxLen)
  424. }
  425. // Compressed is written to msgBuf, we keep tb for the length only
  426. tempBuf, err = lz4.Encode(msgBuf[8:], uncBuf)
  427. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(tempBuf)))
  428. msgBuf = msgBuf[0 : len(tempBuf)+8]
  429. if debug {
  430. l.Debugf("write compressed message; %v (len=%d)", hm.hdr, len(tempBuf))
  431. }
  432. } else {
  433. // No point in compressing very short messages
  434. hm.hdr.compression = false
  435. msgBuf = msgBuf[:cap(msgBuf)]
  436. if l := len(uncBuf) + 8; l > len(msgBuf) {
  437. msgBuf = make([]byte, l)
  438. }
  439. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(uncBuf)))
  440. msgBuf = msgBuf[0 : len(uncBuf)+8]
  441. copy(msgBuf[8:], uncBuf)
  442. if debug {
  443. l.Debugf("write uncompressed message; %v (len=%d)", hm.hdr, len(uncBuf))
  444. }
  445. }
  446. } else {
  447. if debug {
  448. l.Debugf("write empty message; %v", hm.hdr)
  449. }
  450. binary.BigEndian.PutUint32(msgBuf[4:8], 0)
  451. msgBuf = msgBuf[:8]
  452. }
  453. binary.BigEndian.PutUint32(msgBuf[0:4], encodeHeader(hm.hdr))
  454. if err == nil {
  455. var n int
  456. n, err = c.cw.Write(msgBuf)
  457. if debug {
  458. l.Debugf("wrote %d bytes on the wire", n)
  459. }
  460. }
  461. if err != nil {
  462. c.close(err)
  463. return
  464. }
  465. case <-c.closed:
  466. return
  467. }
  468. }
  469. }
  470. func (c *rawConnection) close(err error) {
  471. c.once.Do(func() {
  472. close(c.closed)
  473. c.awaitingMut.Lock()
  474. for i, ch := range c.awaiting {
  475. if ch != nil {
  476. close(ch)
  477. c.awaiting[i] = nil
  478. }
  479. }
  480. c.awaitingMut.Unlock()
  481. go c.receiver.Close(c.id, err)
  482. })
  483. }
  484. func (c *rawConnection) idGenerator() {
  485. nextID := 0
  486. for {
  487. nextID = (nextID + 1) & 0xfff
  488. select {
  489. case c.nextID <- nextID:
  490. case <-c.closed:
  491. return
  492. }
  493. }
  494. }
  495. func (c *rawConnection) pingerLoop() {
  496. var rc = make(chan bool, 1)
  497. ticker := time.Tick(pingIdleTime / 2)
  498. for {
  499. select {
  500. case <-ticker:
  501. if d := time.Since(c.cr.Last()); d < pingIdleTime {
  502. if debug {
  503. l.Debugln(c.id, "ping skipped after rd", d)
  504. }
  505. continue
  506. }
  507. if d := time.Since(c.cw.Last()); d < pingIdleTime {
  508. if debug {
  509. l.Debugln(c.id, "ping skipped after wr", d)
  510. }
  511. continue
  512. }
  513. go func() {
  514. if debug {
  515. l.Debugln(c.id, "ping ->")
  516. }
  517. rc <- c.ping()
  518. }()
  519. select {
  520. case ok := <-rc:
  521. if debug {
  522. l.Debugln(c.id, "<- pong")
  523. }
  524. if !ok {
  525. c.close(fmt.Errorf("ping failure"))
  526. }
  527. case <-time.After(pingTimeout):
  528. c.close(fmt.Errorf("ping timeout"))
  529. case <-c.closed:
  530. return
  531. }
  532. case <-c.closed:
  533. return
  534. }
  535. }
  536. }
  537. type Statistics struct {
  538. At time.Time
  539. InBytesTotal uint64
  540. OutBytesTotal uint64
  541. }
  542. func (c *rawConnection) Statistics() Statistics {
  543. return Statistics{
  544. At: time.Now(),
  545. InBytesTotal: c.cr.Tot(),
  546. OutBytesTotal: c.cw.Tot(),
  547. }
  548. }