1
0

protocol.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. type isEofer interface {
  114. IsEOF() bool
  115. }
  116. const (
  117. pingTimeout = 30 * time.Second
  118. pingIdleTime = 60 * time.Second
  119. )
  120. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress bool) Connection {
  121. cr := &countingReader{Reader: reader}
  122. cw := &countingWriter{Writer: writer}
  123. compThres := 1<<31 - 1 // compression disabled
  124. if compress {
  125. compThres = 128 // compress messages that are 128 bytes long or larger
  126. }
  127. c := rawConnection{
  128. id: deviceID,
  129. name: name,
  130. receiver: nativeModel{receiver},
  131. state: stateInitial,
  132. cr: cr,
  133. cw: cw,
  134. outbox: make(chan hdrMsg),
  135. nextID: make(chan int),
  136. closed: make(chan struct{}),
  137. compressionThreshold: compThres,
  138. }
  139. go c.readerLoop()
  140. go c.writerLoop()
  141. go c.pingerLoop()
  142. go c.idGenerator()
  143. return wireFormatConnection{&c}
  144. }
  145. func (c *rawConnection) ID() DeviceID {
  146. return c.id
  147. }
  148. func (c *rawConnection) Name() string {
  149. return c.name
  150. }
  151. // Index writes the list of file information to the connected peer device
  152. func (c *rawConnection) Index(folder string, idx []FileInfo) error {
  153. select {
  154. case <-c.closed:
  155. return ErrClosed
  156. default:
  157. }
  158. c.idxMut.Lock()
  159. c.send(-1, messageTypeIndex, IndexMessage{folder, idx})
  160. c.idxMut.Unlock()
  161. return nil
  162. }
  163. // IndexUpdate writes the list of file information to the connected peer device as an update
  164. func (c *rawConnection) IndexUpdate(folder string, idx []FileInfo) error {
  165. select {
  166. case <-c.closed:
  167. return ErrClosed
  168. default:
  169. }
  170. c.idxMut.Lock()
  171. c.send(-1, messageTypeIndexUpdate, IndexMessage{folder, idx})
  172. c.idxMut.Unlock()
  173. return nil
  174. }
  175. // Request returns the bytes for the specified block after fetching them from the connected peer.
  176. func (c *rawConnection) Request(folder string, name string, offset int64, size int) ([]byte, error) {
  177. var id int
  178. select {
  179. case id = <-c.nextID:
  180. case <-c.closed:
  181. return nil, ErrClosed
  182. }
  183. c.awaitingMut.Lock()
  184. if ch := c.awaiting[id]; ch != nil {
  185. panic("id taken")
  186. }
  187. rc := make(chan asyncResult, 1)
  188. c.awaiting[id] = rc
  189. c.awaitingMut.Unlock()
  190. ok := c.send(id, messageTypeRequest, RequestMessage{folder, name, uint64(offset), uint32(size)})
  191. if !ok {
  192. return nil, ErrClosed
  193. }
  194. res, ok := <-rc
  195. if !ok {
  196. return nil, ErrClosed
  197. }
  198. return res.val, res.err
  199. }
  200. // ClusterConfig send the cluster configuration message to the peer and returns any error
  201. func (c *rawConnection) ClusterConfig(config ClusterConfigMessage) {
  202. c.send(-1, messageTypeClusterConfig, config)
  203. }
  204. func (c *rawConnection) ping() bool {
  205. var id int
  206. select {
  207. case id = <-c.nextID:
  208. case <-c.closed:
  209. return false
  210. }
  211. rc := make(chan asyncResult, 1)
  212. c.awaitingMut.Lock()
  213. c.awaiting[id] = rc
  214. c.awaitingMut.Unlock()
  215. ok := c.send(id, messageTypePing, nil)
  216. if !ok {
  217. return false
  218. }
  219. res, ok := <-rc
  220. return ok && res.err == nil
  221. }
  222. func (c *rawConnection) readerLoop() (err error) {
  223. defer func() {
  224. c.close(err)
  225. }()
  226. for {
  227. select {
  228. case <-c.closed:
  229. return ErrClosed
  230. default:
  231. }
  232. hdr, msg, err := c.readMessage()
  233. if err != nil {
  234. return err
  235. }
  236. switch hdr.msgType {
  237. case messageTypeIndex:
  238. if c.state < stateCCRcvd {
  239. return fmt.Errorf("protocol error: index message in state %d", c.state)
  240. }
  241. c.handleIndex(msg.(IndexMessage))
  242. c.state = stateIdxRcvd
  243. case messageTypeIndexUpdate:
  244. if c.state < stateIdxRcvd {
  245. return fmt.Errorf("protocol error: index update message in state %d", c.state)
  246. }
  247. c.handleIndexUpdate(msg.(IndexMessage))
  248. case messageTypeRequest:
  249. if c.state < stateIdxRcvd {
  250. return fmt.Errorf("protocol error: request message in state %d", c.state)
  251. }
  252. // Requests are handled asynchronously
  253. go c.handleRequest(hdr.msgID, msg.(RequestMessage))
  254. case messageTypeResponse:
  255. if c.state < stateIdxRcvd {
  256. return fmt.Errorf("protocol error: response message in state %d", c.state)
  257. }
  258. c.handleResponse(hdr.msgID, msg.(ResponseMessage))
  259. case messageTypePing:
  260. c.send(hdr.msgID, messageTypePong, EmptyMessage{})
  261. case messageTypePong:
  262. c.handlePong(hdr.msgID)
  263. case messageTypeClusterConfig:
  264. if c.state != stateInitial {
  265. return fmt.Errorf("protocol error: cluster config message in state %d", c.state)
  266. }
  267. go c.receiver.ClusterConfig(c.id, msg.(ClusterConfigMessage))
  268. c.state = stateCCRcvd
  269. case messageTypeClose:
  270. return errors.New(msg.(CloseMessage).Reason)
  271. default:
  272. return fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  273. }
  274. }
  275. }
  276. func (c *rawConnection) readMessage() (hdr header, msg encodable, err error) {
  277. if cap(c.rdbuf0) < 8 {
  278. c.rdbuf0 = make([]byte, 8)
  279. } else {
  280. c.rdbuf0 = c.rdbuf0[:8]
  281. }
  282. _, err = io.ReadFull(c.cr, c.rdbuf0)
  283. if err != nil {
  284. return
  285. }
  286. hdr = decodeHeader(binary.BigEndian.Uint32(c.rdbuf0[0:4]))
  287. msglen := int(binary.BigEndian.Uint32(c.rdbuf0[4:8]))
  288. if debug {
  289. l.Debugf("read header %v (msglen=%d)", hdr, msglen)
  290. }
  291. if cap(c.rdbuf0) < msglen {
  292. c.rdbuf0 = make([]byte, msglen)
  293. } else {
  294. c.rdbuf0 = c.rdbuf0[:msglen]
  295. }
  296. _, err = io.ReadFull(c.cr, c.rdbuf0)
  297. if err != nil {
  298. return
  299. }
  300. if debug {
  301. l.Debugf("read %d bytes", len(c.rdbuf0))
  302. }
  303. msgBuf := c.rdbuf0
  304. if hdr.compression {
  305. c.rdbuf1 = c.rdbuf1[:cap(c.rdbuf1)]
  306. c.rdbuf1, err = lz4.Decode(c.rdbuf1, c.rdbuf0)
  307. if err != nil {
  308. return
  309. }
  310. msgBuf = c.rdbuf1
  311. if debug {
  312. l.Debugf("decompressed to %d bytes", len(msgBuf))
  313. }
  314. }
  315. if debug {
  316. if len(msgBuf) > 1024 {
  317. l.Debugf("message data:\n%s", hex.Dump(msgBuf[:1024]))
  318. } else {
  319. l.Debugf("message data:\n%s", hex.Dump(msgBuf))
  320. }
  321. }
  322. // We check each returned error for the XDRError.IsEOF() method.
  323. // IsEOF()==true here means that the message contained fewer fields than
  324. // expected. It does not signify an EOF on the socket, because we've
  325. // successfully read a size value and that many bytes already. New fields
  326. // we expected but the other peer didn't send should be interpreted as
  327. // zero/nil, and if that's not valid we'll verify it somewhere else.
  328. switch hdr.msgType {
  329. case messageTypeIndex, messageTypeIndexUpdate:
  330. var idx IndexMessage
  331. err = idx.UnmarshalXDR(msgBuf)
  332. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  333. err = nil
  334. }
  335. msg = idx
  336. case messageTypeRequest:
  337. var req RequestMessage
  338. err = req.UnmarshalXDR(msgBuf)
  339. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  340. err = nil
  341. }
  342. msg = req
  343. case messageTypeResponse:
  344. var resp ResponseMessage
  345. err = resp.UnmarshalXDR(msgBuf)
  346. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  347. err = nil
  348. }
  349. msg = resp
  350. case messageTypePing, messageTypePong:
  351. msg = EmptyMessage{}
  352. case messageTypeClusterConfig:
  353. var cc ClusterConfigMessage
  354. err = cc.UnmarshalXDR(msgBuf)
  355. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  356. err = nil
  357. }
  358. msg = cc
  359. case messageTypeClose:
  360. var cm CloseMessage
  361. err = cm.UnmarshalXDR(msgBuf)
  362. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  363. err = nil
  364. }
  365. msg = cm
  366. default:
  367. err = fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  368. }
  369. return
  370. }
  371. func (c *rawConnection) handleIndex(im IndexMessage) {
  372. if debug {
  373. l.Debugf("Index(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  374. }
  375. c.receiver.Index(c.id, im.Folder, im.Files)
  376. }
  377. func (c *rawConnection) handleIndexUpdate(im IndexMessage) {
  378. if debug {
  379. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  380. }
  381. c.receiver.IndexUpdate(c.id, im.Folder, im.Files)
  382. }
  383. func (c *rawConnection) handleRequest(msgID int, req RequestMessage) {
  384. data, _ := c.receiver.Request(c.id, req.Folder, req.Name, int64(req.Offset), int(req.Size))
  385. c.send(msgID, messageTypeResponse, ResponseMessage{data})
  386. }
  387. func (c *rawConnection) handleResponse(msgID int, resp ResponseMessage) {
  388. c.awaitingMut.Lock()
  389. if rc := c.awaiting[msgID]; rc != nil {
  390. c.awaiting[msgID] = nil
  391. rc <- asyncResult{resp.Data, nil}
  392. close(rc)
  393. }
  394. c.awaitingMut.Unlock()
  395. }
  396. func (c *rawConnection) handlePong(msgID int) {
  397. c.awaitingMut.Lock()
  398. if rc := c.awaiting[msgID]; rc != nil {
  399. c.awaiting[msgID] = nil
  400. rc <- asyncResult{}
  401. close(rc)
  402. }
  403. c.awaitingMut.Unlock()
  404. }
  405. func (c *rawConnection) send(msgID int, msgType int, msg encodable) bool {
  406. if msgID < 0 {
  407. select {
  408. case id := <-c.nextID:
  409. msgID = id
  410. case <-c.closed:
  411. return false
  412. }
  413. }
  414. hdr := header{
  415. version: 0,
  416. msgID: msgID,
  417. msgType: msgType,
  418. }
  419. select {
  420. case c.outbox <- hdrMsg{hdr, msg}:
  421. return true
  422. case <-c.closed:
  423. return false
  424. }
  425. }
  426. func (c *rawConnection) writerLoop() {
  427. var msgBuf = make([]byte, 8) // buffer for wire format message, kept and reused
  428. var uncBuf []byte // buffer for uncompressed message, kept and reused
  429. for {
  430. var tempBuf []byte
  431. var err error
  432. select {
  433. case hm := <-c.outbox:
  434. if hm.msg != nil {
  435. // Uncompressed message in uncBuf
  436. uncBuf, err = hm.msg.AppendXDR(uncBuf[:0])
  437. if err != nil {
  438. c.close(err)
  439. return
  440. }
  441. if len(uncBuf) >= c.compressionThreshold {
  442. // Use compression for large messages
  443. hm.hdr.compression = true
  444. // Make sure we have enough space for the compressed message plus header in msgBug
  445. msgBuf = msgBuf[:cap(msgBuf)]
  446. if maxLen := lz4.CompressBound(len(uncBuf)) + 8; maxLen > len(msgBuf) {
  447. msgBuf = make([]byte, maxLen)
  448. }
  449. // Compressed is written to msgBuf, we keep tb for the length only
  450. tempBuf, err = lz4.Encode(msgBuf[8:], uncBuf)
  451. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(tempBuf)))
  452. msgBuf = msgBuf[0 : len(tempBuf)+8]
  453. if debug {
  454. l.Debugf("write compressed message; %v (len=%d)", hm.hdr, len(tempBuf))
  455. }
  456. } else {
  457. // No point in compressing very short messages
  458. hm.hdr.compression = false
  459. msgBuf = msgBuf[:cap(msgBuf)]
  460. if l := len(uncBuf) + 8; l > len(msgBuf) {
  461. msgBuf = make([]byte, l)
  462. }
  463. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(uncBuf)))
  464. msgBuf = msgBuf[0 : len(uncBuf)+8]
  465. copy(msgBuf[8:], uncBuf)
  466. if debug {
  467. l.Debugf("write uncompressed message; %v (len=%d)", hm.hdr, len(uncBuf))
  468. }
  469. }
  470. } else {
  471. if debug {
  472. l.Debugf("write empty message; %v", hm.hdr)
  473. }
  474. binary.BigEndian.PutUint32(msgBuf[4:8], 0)
  475. msgBuf = msgBuf[:8]
  476. }
  477. binary.BigEndian.PutUint32(msgBuf[0:4], encodeHeader(hm.hdr))
  478. if err == nil {
  479. var n int
  480. n, err = c.cw.Write(msgBuf)
  481. if debug {
  482. l.Debugf("wrote %d bytes on the wire", n)
  483. }
  484. }
  485. if err != nil {
  486. c.close(err)
  487. return
  488. }
  489. case <-c.closed:
  490. return
  491. }
  492. }
  493. }
  494. func (c *rawConnection) close(err error) {
  495. c.once.Do(func() {
  496. close(c.closed)
  497. c.awaitingMut.Lock()
  498. for i, ch := range c.awaiting {
  499. if ch != nil {
  500. close(ch)
  501. c.awaiting[i] = nil
  502. }
  503. }
  504. c.awaitingMut.Unlock()
  505. go c.receiver.Close(c.id, err)
  506. })
  507. }
  508. func (c *rawConnection) idGenerator() {
  509. nextID := 0
  510. for {
  511. nextID = (nextID + 1) & 0xfff
  512. select {
  513. case c.nextID <- nextID:
  514. case <-c.closed:
  515. return
  516. }
  517. }
  518. }
  519. func (c *rawConnection) pingerLoop() {
  520. var rc = make(chan bool, 1)
  521. ticker := time.Tick(pingIdleTime / 2)
  522. for {
  523. select {
  524. case <-ticker:
  525. if d := time.Since(c.cr.Last()); d < pingIdleTime {
  526. if debug {
  527. l.Debugln(c.id, "ping skipped after rd", d)
  528. }
  529. continue
  530. }
  531. if d := time.Since(c.cw.Last()); d < pingIdleTime {
  532. if debug {
  533. l.Debugln(c.id, "ping skipped after wr", d)
  534. }
  535. continue
  536. }
  537. go func() {
  538. if debug {
  539. l.Debugln(c.id, "ping ->")
  540. }
  541. rc <- c.ping()
  542. }()
  543. select {
  544. case ok := <-rc:
  545. if debug {
  546. l.Debugln(c.id, "<- pong")
  547. }
  548. if !ok {
  549. c.close(fmt.Errorf("ping failure"))
  550. }
  551. case <-time.After(pingTimeout):
  552. c.close(fmt.Errorf("ping timeout"))
  553. case <-c.closed:
  554. return
  555. }
  556. case <-c.closed:
  557. return
  558. }
  559. }
  560. }
  561. type Statistics struct {
  562. At time.Time
  563. InBytesTotal uint64
  564. OutBytesTotal uint64
  565. }
  566. func (c *rawConnection) Statistics() Statistics {
  567. return Statistics{
  568. At: time.Now(),
  569. InBytesTotal: c.cr.Tot(),
  570. OutBytesTotal: c.cw.Tot(),
  571. }
  572. }