protocol.go 23 KB

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