protocol.go 17 KB

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