protocol.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "crypto/sha256"
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "path"
  10. "strings"
  11. "sync"
  12. "time"
  13. lz4 "github.com/bkaradzic/go-lz4"
  14. )
  15. const (
  16. // Shifts
  17. KiB = 10
  18. MiB = 20
  19. GiB = 30
  20. )
  21. const (
  22. // MaxMessageLen is the largest message size allowed on the wire. (500 MB)
  23. MaxMessageLen = 500 * 1000 * 1000
  24. // MinBlockSize is the minimum block size allowed
  25. MinBlockSize = 128 << KiB
  26. // MaxBlockSize is the maximum block size allowed
  27. MaxBlockSize = 16 << MiB
  28. // DesiredPerFileBlocks is the number of blocks we aim for per file
  29. DesiredPerFileBlocks = 2000
  30. )
  31. // BlockSizes is the list of valid block sizes, from min to max
  32. var BlockSizes []int
  33. // For each block size, the hash of a block of all zeroes
  34. var sha256OfEmptyBlock = make(map[int][sha256.Size]byte)
  35. func init() {
  36. for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
  37. BlockSizes = append(BlockSizes, blockSize)
  38. sha256OfEmptyBlock[blockSize] = sha256.Sum256(make([]byte, blockSize))
  39. }
  40. BufferPool = newBufferPool()
  41. }
  42. // BlockSize returns the block size to use for the given file size
  43. func BlockSize(fileSize int64) int {
  44. var blockSize int
  45. for _, blockSize = range BlockSizes {
  46. if fileSize < DesiredPerFileBlocks*int64(blockSize) {
  47. break
  48. }
  49. }
  50. return blockSize
  51. }
  52. const (
  53. stateInitial = iota
  54. stateReady
  55. )
  56. // Request message flags
  57. const (
  58. FlagFromTemporary uint32 = 1 << iota
  59. )
  60. // ClusterConfigMessage.Folders flags
  61. const (
  62. FlagFolderReadOnly uint32 = 1 << 0
  63. FlagFolderIgnorePerms = 1 << 1
  64. FlagFolderIgnoreDelete = 1 << 2
  65. FlagFolderDisabledTempIndexes = 1 << 3
  66. FlagFolderAll = 1<<4 - 1
  67. )
  68. // ClusterConfigMessage.Folders.Devices flags
  69. const (
  70. FlagShareTrusted uint32 = 1 << 0
  71. FlagShareReadOnly = 1 << 1
  72. FlagIntroducer = 1 << 2
  73. FlagShareBits = 0x000000ff
  74. )
  75. // FileInfo.LocalFlags flags
  76. const (
  77. FlagLocalUnsupported = 1 << 0 // The kind is unsupported, e.g. symlinks on Windows
  78. FlagLocalIgnored = 1 << 1 // Matches local ignore patterns
  79. FlagLocalMustRescan = 1 << 2 // Doesn't match content on disk, must be rechecked fully
  80. FlagLocalReceiveOnly = 1 << 3 // Change detected on receive only folder
  81. // Flags that should result in the Invalid bit on outgoing updates
  82. LocalInvalidFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly
  83. // Flags that should result in a file being in conflict with its
  84. // successor, due to us not having an up to date picture of its state on
  85. // disk.
  86. LocalConflictFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalReceiveOnly
  87. LocalAllFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly
  88. )
  89. var (
  90. ErrClosed = errors.New("connection closed")
  91. ErrTimeout = errors.New("read timeout")
  92. ErrSwitchingConnections = errors.New("switching connections")
  93. errUnknownMessage = errors.New("unknown message")
  94. errInvalidFilename = errors.New("filename is invalid")
  95. errUncleanFilename = errors.New("filename not in canonical format")
  96. errDeletedHasBlocks = errors.New("deleted file with non-empty block list")
  97. errDirectoryHasBlocks = errors.New("directory with non-empty block list")
  98. errFileHasNoBlocks = errors.New("file with empty block list")
  99. )
  100. type Model interface {
  101. // An index was received from the peer device
  102. Index(deviceID DeviceID, folder string, files []FileInfo)
  103. // An index update was received from the peer device
  104. IndexUpdate(deviceID DeviceID, folder string, files []FileInfo)
  105. // A request was made by the peer device
  106. Request(deviceID DeviceID, folder, name string, size int32, offset int64, hash []byte, weakHash uint32, fromTemporary bool) (RequestResponse, error)
  107. // A cluster configuration message was received
  108. ClusterConfig(deviceID DeviceID, config ClusterConfig)
  109. // The peer device closed the connection
  110. Closed(conn Connection, err error)
  111. // The peer device sent progress updates for the files it is currently downloading
  112. DownloadProgress(deviceID DeviceID, folder string, updates []FileDownloadProgressUpdate)
  113. }
  114. type RequestResponse interface {
  115. Data() []byte
  116. Close() // Must always be called once the byte slice is no longer in use
  117. Wait() // Blocks until Close is called
  118. }
  119. type Connection interface {
  120. Start()
  121. ID() DeviceID
  122. Name() string
  123. Index(folder string, files []FileInfo) error
  124. IndexUpdate(folder string, files []FileInfo) error
  125. Request(folder string, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error)
  126. ClusterConfig(config ClusterConfig)
  127. DownloadProgress(folder string, updates []FileDownloadProgressUpdate)
  128. Statistics() Statistics
  129. Closed() bool
  130. }
  131. type rawConnection struct {
  132. id DeviceID
  133. name string
  134. receiver Model
  135. cr *countingReader
  136. cw *countingWriter
  137. awaiting map[int32]chan asyncResult
  138. awaitingMut sync.Mutex
  139. idxMut sync.Mutex // ensures serialization of Index calls
  140. nextID int32
  141. nextIDMut sync.Mutex
  142. outbox chan asyncMessage
  143. closed chan struct{}
  144. once sync.Once
  145. compression Compression
  146. }
  147. type asyncResult struct {
  148. val []byte
  149. err error
  150. }
  151. type message interface {
  152. ProtoSize() int
  153. Marshal() ([]byte, error)
  154. MarshalTo([]byte) (int, error)
  155. Unmarshal([]byte) error
  156. }
  157. type asyncMessage struct {
  158. msg message
  159. done chan struct{} // done closes when we're done sending the message
  160. }
  161. const (
  162. // PingSendInterval is how often we make sure to send a message, by
  163. // triggering pings if necessary.
  164. PingSendInterval = 90 * time.Second
  165. // ReceiveTimeout is the longest we'll wait for a message from the other
  166. // side before closing the connection.
  167. ReceiveTimeout = 300 * time.Second
  168. )
  169. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress Compression) Connection {
  170. cr := &countingReader{Reader: reader}
  171. cw := &countingWriter{Writer: writer}
  172. c := rawConnection{
  173. id: deviceID,
  174. name: name,
  175. receiver: nativeModel{receiver},
  176. cr: cr,
  177. cw: cw,
  178. awaiting: make(map[int32]chan asyncResult),
  179. outbox: make(chan asyncMessage),
  180. closed: make(chan struct{}),
  181. compression: compress,
  182. }
  183. return wireFormatConnection{&c}
  184. }
  185. // Start creates the goroutines for sending and receiving of messages. It must
  186. // be called exactly once after creating a connection.
  187. func (c *rawConnection) Start() {
  188. go c.readerLoop()
  189. go c.writerLoop()
  190. go c.pingSender()
  191. go c.pingReceiver()
  192. }
  193. func (c *rawConnection) ID() DeviceID {
  194. return c.id
  195. }
  196. func (c *rawConnection) Name() string {
  197. return c.name
  198. }
  199. // Index writes the list of file information to the connected peer device
  200. func (c *rawConnection) Index(folder string, idx []FileInfo) error {
  201. select {
  202. case <-c.closed:
  203. return ErrClosed
  204. default:
  205. }
  206. c.idxMut.Lock()
  207. c.send(&Index{
  208. Folder: folder,
  209. Files: idx,
  210. }, nil)
  211. c.idxMut.Unlock()
  212. return nil
  213. }
  214. // IndexUpdate writes the list of file information to the connected peer device as an update
  215. func (c *rawConnection) IndexUpdate(folder string, idx []FileInfo) error {
  216. select {
  217. case <-c.closed:
  218. return ErrClosed
  219. default:
  220. }
  221. c.idxMut.Lock()
  222. c.send(&IndexUpdate{
  223. Folder: folder,
  224. Files: idx,
  225. }, nil)
  226. c.idxMut.Unlock()
  227. return nil
  228. }
  229. // Request returns the bytes for the specified block after fetching them from the connected peer.
  230. func (c *rawConnection) Request(folder string, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  231. c.nextIDMut.Lock()
  232. id := c.nextID
  233. c.nextID++
  234. c.nextIDMut.Unlock()
  235. c.awaitingMut.Lock()
  236. if _, ok := c.awaiting[id]; ok {
  237. panic("id taken")
  238. }
  239. rc := make(chan asyncResult, 1)
  240. c.awaiting[id] = rc
  241. c.awaitingMut.Unlock()
  242. ok := c.send(&Request{
  243. ID: id,
  244. Folder: folder,
  245. Name: name,
  246. Offset: offset,
  247. Size: int32(size),
  248. Hash: hash,
  249. WeakHash: weakHash,
  250. FromTemporary: fromTemporary,
  251. }, nil)
  252. if !ok {
  253. return nil, ErrClosed
  254. }
  255. res, ok := <-rc
  256. if !ok {
  257. return nil, ErrClosed
  258. }
  259. return res.val, res.err
  260. }
  261. // ClusterConfig send the cluster configuration message to the peer and returns any error
  262. func (c *rawConnection) ClusterConfig(config ClusterConfig) {
  263. c.send(&config, nil)
  264. }
  265. func (c *rawConnection) Closed() bool {
  266. select {
  267. case <-c.closed:
  268. return true
  269. default:
  270. return false
  271. }
  272. }
  273. // DownloadProgress sends the progress updates for the files that are currently being downloaded.
  274. func (c *rawConnection) DownloadProgress(folder string, updates []FileDownloadProgressUpdate) {
  275. c.send(&DownloadProgress{
  276. Folder: folder,
  277. Updates: updates,
  278. }, nil)
  279. }
  280. func (c *rawConnection) ping() bool {
  281. return c.send(&Ping{}, nil)
  282. }
  283. func (c *rawConnection) readerLoop() (err error) {
  284. defer func() {
  285. c.close(err)
  286. }()
  287. fourByteBuf := make([]byte, 4)
  288. state := stateInitial
  289. for {
  290. select {
  291. case <-c.closed:
  292. return ErrClosed
  293. default:
  294. }
  295. msg, err := c.readMessage(fourByteBuf)
  296. if err == errUnknownMessage {
  297. // Unknown message types are skipped, for future extensibility.
  298. continue
  299. }
  300. if err != nil {
  301. return err
  302. }
  303. switch msg := msg.(type) {
  304. case *ClusterConfig:
  305. l.Debugln("read ClusterConfig message")
  306. if state != stateInitial {
  307. return fmt.Errorf("protocol error: cluster config message in state %d", state)
  308. }
  309. c.receiver.ClusterConfig(c.id, *msg)
  310. state = stateReady
  311. case *Index:
  312. l.Debugln("read Index message")
  313. if state != stateReady {
  314. return fmt.Errorf("protocol error: index message in state %d", state)
  315. }
  316. if err := checkIndexConsistency(msg.Files); err != nil {
  317. return fmt.Errorf("protocol error: index: %v", err)
  318. }
  319. c.handleIndex(*msg)
  320. state = stateReady
  321. case *IndexUpdate:
  322. l.Debugln("read IndexUpdate message")
  323. if state != stateReady {
  324. return fmt.Errorf("protocol error: index update message in state %d", state)
  325. }
  326. if err := checkIndexConsistency(msg.Files); err != nil {
  327. return fmt.Errorf("protocol error: index update: %v", err)
  328. }
  329. c.handleIndexUpdate(*msg)
  330. state = stateReady
  331. case *Request:
  332. l.Debugln("read Request message")
  333. if state != stateReady {
  334. return fmt.Errorf("protocol error: request message in state %d", state)
  335. }
  336. if err := checkFilename(msg.Name); err != nil {
  337. return fmt.Errorf("protocol error: request: %q: %v", msg.Name, err)
  338. }
  339. go c.handleRequest(*msg)
  340. case *Response:
  341. l.Debugln("read Response message")
  342. if state != stateReady {
  343. return fmt.Errorf("protocol error: response message in state %d", state)
  344. }
  345. c.handleResponse(*msg)
  346. case *DownloadProgress:
  347. l.Debugln("read DownloadProgress message")
  348. if state != stateReady {
  349. return fmt.Errorf("protocol error: response message in state %d", state)
  350. }
  351. c.receiver.DownloadProgress(c.id, msg.Folder, msg.Updates)
  352. case *Ping:
  353. l.Debugln("read Ping message")
  354. if state != stateReady {
  355. return fmt.Errorf("protocol error: ping message in state %d", state)
  356. }
  357. // Nothing
  358. case *Close:
  359. l.Debugln("read Close message")
  360. return errors.New(msg.Reason)
  361. default:
  362. l.Debugf("read unknown message: %+T", msg)
  363. return fmt.Errorf("protocol error: %s: unknown or empty message", c.id)
  364. }
  365. }
  366. }
  367. func (c *rawConnection) readMessage(fourByteBuf []byte) (message, error) {
  368. hdr, err := c.readHeader(fourByteBuf)
  369. if err != nil {
  370. return nil, err
  371. }
  372. return c.readMessageAfterHeader(hdr, fourByteBuf)
  373. }
  374. func (c *rawConnection) readMessageAfterHeader(hdr Header, fourByteBuf []byte) (message, error) {
  375. // First comes a 4 byte message length
  376. if _, err := io.ReadFull(c.cr, fourByteBuf[:4]); err != nil {
  377. return nil, fmt.Errorf("reading message length: %v", err)
  378. }
  379. msgLen := int32(binary.BigEndian.Uint32(fourByteBuf))
  380. if msgLen < 0 {
  381. return nil, fmt.Errorf("negative message length %d", msgLen)
  382. }
  383. // Then comes the message
  384. buf := BufferPool.Get(int(msgLen))
  385. if _, err := io.ReadFull(c.cr, buf); err != nil {
  386. return nil, fmt.Errorf("reading message: %v", err)
  387. }
  388. // ... which might be compressed
  389. switch hdr.Compression {
  390. case MessageCompressionNone:
  391. // Nothing
  392. case MessageCompressionLZ4:
  393. decomp, err := c.lz4Decompress(buf)
  394. BufferPool.Put(buf)
  395. if err != nil {
  396. return nil, fmt.Errorf("decompressing message: %v", err)
  397. }
  398. buf = decomp
  399. default:
  400. return nil, fmt.Errorf("unknown message compression %d", hdr.Compression)
  401. }
  402. // ... and is then unmarshalled
  403. msg, err := c.newMessage(hdr.Type)
  404. if err != nil {
  405. return nil, err
  406. }
  407. if err := msg.Unmarshal(buf); err != nil {
  408. return nil, fmt.Errorf("unmarshalling message: %v", err)
  409. }
  410. BufferPool.Put(buf)
  411. return msg, nil
  412. }
  413. func (c *rawConnection) readHeader(fourByteBuf []byte) (Header, error) {
  414. // First comes a 2 byte header length
  415. if _, err := io.ReadFull(c.cr, fourByteBuf[:2]); err != nil {
  416. return Header{}, fmt.Errorf("reading length: %v", err)
  417. }
  418. hdrLen := int16(binary.BigEndian.Uint16(fourByteBuf))
  419. if hdrLen < 0 {
  420. return Header{}, fmt.Errorf("negative header length %d", hdrLen)
  421. }
  422. // Then comes the header
  423. buf := BufferPool.Get(int(hdrLen))
  424. if _, err := io.ReadFull(c.cr, buf); err != nil {
  425. return Header{}, fmt.Errorf("reading header: %v", err)
  426. }
  427. var hdr Header
  428. if err := hdr.Unmarshal(buf); err != nil {
  429. return Header{}, fmt.Errorf("unmarshalling header: %v", err)
  430. }
  431. BufferPool.Put(buf)
  432. return hdr, nil
  433. }
  434. func (c *rawConnection) handleIndex(im Index) {
  435. l.Debugf("Index(%v, %v, %d file)", c.id, im.Folder, len(im.Files))
  436. c.receiver.Index(c.id, im.Folder, im.Files)
  437. }
  438. func (c *rawConnection) handleIndexUpdate(im IndexUpdate) {
  439. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  440. c.receiver.IndexUpdate(c.id, im.Folder, im.Files)
  441. }
  442. // checkIndexConsistency verifies a number of invariants on FileInfos received in
  443. // index messages.
  444. func checkIndexConsistency(fs []FileInfo) error {
  445. for _, f := range fs {
  446. if err := checkFileInfoConsistency(f); err != nil {
  447. return fmt.Errorf("%q: %v", f.Name, err)
  448. }
  449. }
  450. return nil
  451. }
  452. // checkFileInfoConsistency verifies a number of invariants on the given FileInfo
  453. func checkFileInfoConsistency(f FileInfo) error {
  454. if err := checkFilename(f.Name); err != nil {
  455. return err
  456. }
  457. switch {
  458. case f.Deleted && len(f.Blocks) != 0:
  459. // Deleted files should have no blocks
  460. return errDeletedHasBlocks
  461. case f.Type == FileInfoTypeDirectory && len(f.Blocks) != 0:
  462. // Directories should have no blocks
  463. return errDirectoryHasBlocks
  464. case !f.Deleted && !f.IsInvalid() && f.Type == FileInfoTypeFile && len(f.Blocks) == 0:
  465. // Non-deleted, non-invalid files should have at least one block
  466. return errFileHasNoBlocks
  467. }
  468. return nil
  469. }
  470. // checkFilename verifies that the given filename is valid according to the
  471. // spec on what's allowed over the wire. A filename failing this test is
  472. // grounds for disconnecting the device.
  473. func checkFilename(name string) error {
  474. cleanedName := path.Clean(name)
  475. if cleanedName != name {
  476. // The filename on the wire should be in canonical format. If
  477. // Clean() managed to clean it up, there was something wrong with
  478. // it.
  479. return errUncleanFilename
  480. }
  481. switch name {
  482. case "", ".", "..":
  483. // These names are always invalid.
  484. return errInvalidFilename
  485. }
  486. if strings.HasPrefix(name, "/") {
  487. // Names are folder relative, not absolute.
  488. return errInvalidFilename
  489. }
  490. if strings.HasPrefix(name, "../") {
  491. // Starting with a dotdot is not allowed. Any other dotdots would
  492. // have been handled by the Clean() call at the top.
  493. return errInvalidFilename
  494. }
  495. return nil
  496. }
  497. func (c *rawConnection) handleRequest(req Request) {
  498. res, err := c.receiver.Request(c.id, req.Folder, req.Name, req.Size, req.Offset, req.Hash, req.WeakHash, req.FromTemporary)
  499. if err != nil {
  500. c.send(&Response{
  501. ID: req.ID,
  502. Code: errorToCode(err),
  503. }, nil)
  504. return
  505. }
  506. done := make(chan struct{})
  507. c.send(&Response{
  508. ID: req.ID,
  509. Data: res.Data(),
  510. Code: errorToCode(nil),
  511. }, done)
  512. <-done
  513. res.Close()
  514. }
  515. func (c *rawConnection) handleResponse(resp Response) {
  516. c.awaitingMut.Lock()
  517. if rc := c.awaiting[resp.ID]; rc != nil {
  518. delete(c.awaiting, resp.ID)
  519. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  520. close(rc)
  521. }
  522. c.awaitingMut.Unlock()
  523. }
  524. func (c *rawConnection) send(msg message, done chan struct{}) bool {
  525. select {
  526. case c.outbox <- asyncMessage{msg, done}:
  527. return true
  528. case <-c.closed:
  529. if done != nil {
  530. close(done)
  531. }
  532. return false
  533. }
  534. }
  535. func (c *rawConnection) writerLoop() {
  536. for {
  537. select {
  538. case hm := <-c.outbox:
  539. err := c.writeMessage(hm)
  540. if hm.done != nil {
  541. close(hm.done)
  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) writeMessage(hm asyncMessage) error {
  553. if c.shouldCompressMessage(hm.msg) {
  554. return c.writeCompressedMessage(hm)
  555. }
  556. return c.writeUncompressedMessage(hm)
  557. }
  558. func (c *rawConnection) writeCompressedMessage(hm asyncMessage) error {
  559. size := hm.msg.ProtoSize()
  560. buf := BufferPool.Get(size)
  561. if _, err := hm.msg.MarshalTo(buf); err != nil {
  562. return fmt.Errorf("marshalling message: %v", err)
  563. }
  564. compressed, err := c.lz4Compress(buf)
  565. if err != nil {
  566. return fmt.Errorf("compressing message: %v", err)
  567. }
  568. hdr := Header{
  569. Type: c.typeOf(hm.msg),
  570. Compression: MessageCompressionLZ4,
  571. }
  572. hdrSize := hdr.ProtoSize()
  573. if hdrSize > 1<<16-1 {
  574. panic("impossibly large header")
  575. }
  576. totSize := 2 + hdrSize + 4 + len(compressed)
  577. buf = BufferPool.Upgrade(buf, totSize)
  578. // Header length
  579. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  580. // Header
  581. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  582. return fmt.Errorf("marshalling header: %v", err)
  583. }
  584. // Message length
  585. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(len(compressed)))
  586. // Message
  587. copy(buf[2+hdrSize+4:], compressed)
  588. BufferPool.Put(compressed)
  589. n, err := c.cw.Write(buf)
  590. BufferPool.Put(buf)
  591. l.Debugf("wrote %d bytes on the wire (2 bytes length, %d bytes header, 4 bytes message length, %d bytes message (%d uncompressed)), err=%v", n, hdrSize, len(compressed), size, err)
  592. if err != nil {
  593. return fmt.Errorf("writing message: %v", err)
  594. }
  595. return nil
  596. }
  597. func (c *rawConnection) writeUncompressedMessage(hm asyncMessage) error {
  598. size := hm.msg.ProtoSize()
  599. hdr := Header{
  600. Type: c.typeOf(hm.msg),
  601. }
  602. hdrSize := hdr.ProtoSize()
  603. if hdrSize > 1<<16-1 {
  604. panic("impossibly large header")
  605. }
  606. totSize := 2 + hdrSize + 4 + size
  607. buf := BufferPool.Get(totSize)
  608. // Header length
  609. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  610. // Header
  611. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  612. return fmt.Errorf("marshalling header: %v", err)
  613. }
  614. // Message length
  615. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
  616. // Message
  617. if _, err := hm.msg.MarshalTo(buf[2+hdrSize+4:]); err != nil {
  618. return fmt.Errorf("marshalling message: %v", err)
  619. }
  620. n, err := c.cw.Write(buf[:totSize])
  621. BufferPool.Put(buf)
  622. l.Debugf("wrote %d bytes on the wire (2 bytes length, %d bytes header, 4 bytes message length, %d bytes message), err=%v", n, hdrSize, size, err)
  623. if err != nil {
  624. return fmt.Errorf("writing message: %v", err)
  625. }
  626. return nil
  627. }
  628. func (c *rawConnection) typeOf(msg message) MessageType {
  629. switch msg.(type) {
  630. case *ClusterConfig:
  631. return messageTypeClusterConfig
  632. case *Index:
  633. return messageTypeIndex
  634. case *IndexUpdate:
  635. return messageTypeIndexUpdate
  636. case *Request:
  637. return messageTypeRequest
  638. case *Response:
  639. return messageTypeResponse
  640. case *DownloadProgress:
  641. return messageTypeDownloadProgress
  642. case *Ping:
  643. return messageTypePing
  644. case *Close:
  645. return messageTypeClose
  646. default:
  647. panic("bug: unknown message type")
  648. }
  649. }
  650. func (c *rawConnection) newMessage(t MessageType) (message, error) {
  651. switch t {
  652. case messageTypeClusterConfig:
  653. return new(ClusterConfig), nil
  654. case messageTypeIndex:
  655. return new(Index), nil
  656. case messageTypeIndexUpdate:
  657. return new(IndexUpdate), nil
  658. case messageTypeRequest:
  659. return new(Request), nil
  660. case messageTypeResponse:
  661. return new(Response), nil
  662. case messageTypeDownloadProgress:
  663. return new(DownloadProgress), nil
  664. case messageTypePing:
  665. return new(Ping), nil
  666. case messageTypeClose:
  667. return new(Close), nil
  668. default:
  669. return nil, errUnknownMessage
  670. }
  671. }
  672. func (c *rawConnection) shouldCompressMessage(msg message) bool {
  673. switch c.compression {
  674. case CompressNever:
  675. return false
  676. case CompressAlways:
  677. // Use compression for large enough messages
  678. return msg.ProtoSize() >= compressionThreshold
  679. case CompressMetadata:
  680. _, isResponse := msg.(*Response)
  681. // Compress if it's large enough and not a response message
  682. return !isResponse && msg.ProtoSize() >= compressionThreshold
  683. default:
  684. panic("unknown compression setting")
  685. }
  686. }
  687. func (c *rawConnection) close(err error) {
  688. c.once.Do(func() {
  689. l.Debugln("close due to", err)
  690. close(c.closed)
  691. c.awaitingMut.Lock()
  692. for i, ch := range c.awaiting {
  693. if ch != nil {
  694. close(ch)
  695. delete(c.awaiting, i)
  696. }
  697. }
  698. c.awaitingMut.Unlock()
  699. c.receiver.Closed(c, err)
  700. })
  701. }
  702. // The pingSender makes sure that we've sent a message within the last
  703. // PingSendInterval. If we already have something sent in the last
  704. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  705. // results in an effecting ping interval of somewhere between
  706. // PingSendInterval/2 and PingSendInterval.
  707. func (c *rawConnection) pingSender() {
  708. ticker := time.NewTicker(PingSendInterval / 2)
  709. defer ticker.Stop()
  710. for {
  711. select {
  712. case <-ticker.C:
  713. d := time.Since(c.cw.Last())
  714. if d < PingSendInterval/2 {
  715. l.Debugln(c.id, "ping skipped after wr", d)
  716. continue
  717. }
  718. l.Debugln(c.id, "ping -> after", d)
  719. c.ping()
  720. case <-c.closed:
  721. return
  722. }
  723. }
  724. }
  725. // The pingReceiver checks that we've received a message (any message will do,
  726. // but we expect pings in the absence of other messages) within the last
  727. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  728. func (c *rawConnection) pingReceiver() {
  729. ticker := time.NewTicker(ReceiveTimeout / 2)
  730. defer ticker.Stop()
  731. for {
  732. select {
  733. case <-ticker.C:
  734. d := time.Since(c.cr.Last())
  735. if d > ReceiveTimeout {
  736. l.Debugln(c.id, "ping timeout", d)
  737. c.close(ErrTimeout)
  738. }
  739. l.Debugln(c.id, "last read within", d)
  740. case <-c.closed:
  741. return
  742. }
  743. }
  744. }
  745. type Statistics struct {
  746. At time.Time
  747. InBytesTotal int64
  748. OutBytesTotal int64
  749. }
  750. func (c *rawConnection) Statistics() Statistics {
  751. return Statistics{
  752. At: time.Now(),
  753. InBytesTotal: c.cr.Tot(),
  754. OutBytesTotal: c.cw.Tot(),
  755. }
  756. }
  757. func (c *rawConnection) lz4Compress(src []byte) ([]byte, error) {
  758. var err error
  759. buf := BufferPool.Get(len(src))
  760. buf, err = lz4.Encode(buf, src)
  761. if err != nil {
  762. return nil, err
  763. }
  764. binary.BigEndian.PutUint32(buf, binary.LittleEndian.Uint32(buf))
  765. return buf, nil
  766. }
  767. func (c *rawConnection) lz4Decompress(src []byte) ([]byte, error) {
  768. size := binary.BigEndian.Uint32(src)
  769. binary.LittleEndian.PutUint32(src, size)
  770. var err error
  771. buf := BufferPool.Get(int(size))
  772. buf, err = lz4.Decode(buf, src)
  773. if err != nil {
  774. return nil, err
  775. }
  776. return buf, nil
  777. }