1
0

protocol.go 15 KB

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