1
0

protocol.go 20 KB

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