protocol.go 16 KB

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