protocol.go 23 KB

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