protocol.go 24 KB

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