protocol.go 16 KB

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