protocol.go 20 KB

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