protocol.go 20 KB

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