protocol.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "encoding/binary"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "sync"
  10. "time"
  11. lz4 "github.com/bkaradzic/go-lz4"
  12. )
  13. const (
  14. // BlockSize is the standard ata block size (128 KiB)
  15. BlockSize = 128 << 10
  16. // MaxMessageLen is the largest message size allowed on the wire. (64 MiB)
  17. MaxMessageLen = 64 << 20
  18. )
  19. const (
  20. messageTypeClusterConfig = 0
  21. messageTypeIndex = 1
  22. messageTypeRequest = 2
  23. messageTypeResponse = 3
  24. messageTypePing = 4
  25. messageTypeIndexUpdate = 6
  26. messageTypeClose = 7
  27. )
  28. const (
  29. stateInitial = iota
  30. stateReady
  31. )
  32. // FileInfo flags
  33. const (
  34. FlagDeleted uint32 = 1 << 12
  35. FlagInvalid = 1 << 13
  36. FlagDirectory = 1 << 14
  37. FlagNoPermBits = 1 << 15
  38. FlagSymlink = 1 << 16
  39. FlagSymlinkMissingTarget = 1 << 17
  40. FlagsAll = (1 << 18) - 1
  41. SymlinkTypeMask = FlagDirectory | FlagSymlinkMissingTarget
  42. )
  43. // IndexMessage message flags (for IndexUpdate)
  44. const (
  45. FlagIndexTemporary uint32 = 1 << iota
  46. )
  47. // Request message flags
  48. const (
  49. FlagRequestTemporary uint32 = 1 << iota
  50. )
  51. // ClusterConfigMessage.Folders.Devices flags
  52. const (
  53. FlagShareTrusted uint32 = 1 << 0
  54. FlagShareReadOnly = 1 << 1
  55. FlagIntroducer = 1 << 2
  56. FlagShareBits = 0x000000ff
  57. )
  58. var (
  59. ErrClosed = errors.New("connection closed")
  60. ErrTimeout = errors.New("read timeout")
  61. )
  62. // Specific variants of empty messages...
  63. type pingMessage struct{ EmptyMessage }
  64. type Model interface {
  65. // An index was received from the peer device
  66. Index(deviceID DeviceID, folder string, files []FileInfo, flags uint32, options []Option)
  67. // An index update was received from the peer device
  68. IndexUpdate(deviceID DeviceID, folder string, files []FileInfo, flags uint32, options []Option)
  69. // A request was made by the peer device
  70. Request(deviceID DeviceID, folder string, name string, offset int64, hash []byte, flags uint32, options []Option, buf []byte) error
  71. // A cluster configuration message was received
  72. ClusterConfig(deviceID DeviceID, config ClusterConfigMessage)
  73. // The peer device closed the connection
  74. Close(deviceID DeviceID, err error)
  75. }
  76. type Connection interface {
  77. Start()
  78. ID() DeviceID
  79. Name() string
  80. Index(folder string, files []FileInfo, flags uint32, options []Option) error
  81. IndexUpdate(folder string, files []FileInfo, flags uint32, options []Option) error
  82. Request(folder string, name string, offset int64, size int, hash []byte, flags uint32, options []Option) ([]byte, error)
  83. ClusterConfig(config ClusterConfigMessage)
  84. Statistics() Statistics
  85. }
  86. type rawConnection struct {
  87. id DeviceID
  88. name string
  89. receiver Model
  90. cr *countingReader
  91. cw *countingWriter
  92. awaiting [4096]chan asyncResult
  93. awaitingMut sync.Mutex
  94. idxMut sync.Mutex // ensures serialization of Index calls
  95. nextID chan int
  96. outbox chan hdrMsg
  97. closed chan struct{}
  98. once sync.Once
  99. pool sync.Pool
  100. compression Compression
  101. rdbuf0 []byte // used & reused by readMessage
  102. rdbuf1 []byte // used & reused by readMessage
  103. }
  104. type asyncResult struct {
  105. val []byte
  106. err error
  107. }
  108. type hdrMsg struct {
  109. hdr header
  110. msg encodable
  111. done chan struct{}
  112. }
  113. type encodable interface {
  114. AppendXDR([]byte) ([]byte, error)
  115. }
  116. type isEofer interface {
  117. IsEOF() bool
  118. }
  119. const (
  120. // PingSendInterval is how often we make sure to send a message, by
  121. // triggering pings if necessary.
  122. PingSendInterval = 90 * time.Second
  123. // ReceiveTimeout is the longest we'll wait for a message from the other
  124. // side before closing the connection.
  125. ReceiveTimeout = 300 * time.Second
  126. )
  127. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress Compression) Connection {
  128. cr := &countingReader{Reader: reader}
  129. cw := &countingWriter{Writer: writer}
  130. c := rawConnection{
  131. id: deviceID,
  132. name: name,
  133. receiver: nativeModel{receiver},
  134. cr: cr,
  135. cw: cw,
  136. outbox: make(chan hdrMsg),
  137. nextID: make(chan int),
  138. closed: make(chan struct{}),
  139. pool: sync.Pool{
  140. New: func() interface{} {
  141. return make([]byte, BlockSize)
  142. },
  143. },
  144. compression: compress,
  145. }
  146. return wireFormatConnection{&c}
  147. }
  148. // Start creates the goroutines for sending and receiving of messages. It must
  149. // be called exactly once after creating a connection.
  150. func (c *rawConnection) Start() {
  151. go c.readerLoop()
  152. go c.writerLoop()
  153. go c.pingSender()
  154. go c.pingReceiver()
  155. go c.idGenerator()
  156. }
  157. func (c *rawConnection) ID() DeviceID {
  158. return c.id
  159. }
  160. func (c *rawConnection) Name() string {
  161. return c.name
  162. }
  163. // Index writes the list of file information to the connected peer device
  164. func (c *rawConnection) Index(folder string, idx []FileInfo, flags uint32, options []Option) error {
  165. select {
  166. case <-c.closed:
  167. return ErrClosed
  168. default:
  169. }
  170. c.idxMut.Lock()
  171. c.send(-1, messageTypeIndex, IndexMessage{
  172. Folder: folder,
  173. Files: idx,
  174. Flags: flags,
  175. Options: options,
  176. }, nil)
  177. c.idxMut.Unlock()
  178. return nil
  179. }
  180. // IndexUpdate writes the list of file information to the connected peer device as an update
  181. func (c *rawConnection) IndexUpdate(folder string, idx []FileInfo, flags uint32, options []Option) error {
  182. select {
  183. case <-c.closed:
  184. return ErrClosed
  185. default:
  186. }
  187. c.idxMut.Lock()
  188. c.send(-1, messageTypeIndexUpdate, IndexMessage{
  189. Folder: folder,
  190. Files: idx,
  191. Flags: flags,
  192. Options: options,
  193. }, nil)
  194. c.idxMut.Unlock()
  195. return nil
  196. }
  197. // Request returns the bytes for the specified block after fetching them from the connected peer.
  198. func (c *rawConnection) Request(folder string, name string, offset int64, size int, hash []byte, flags uint32, options []Option) ([]byte, error) {
  199. var id int
  200. select {
  201. case id = <-c.nextID:
  202. case <-c.closed:
  203. return nil, ErrClosed
  204. }
  205. c.awaitingMut.Lock()
  206. if ch := c.awaiting[id]; ch != nil {
  207. panic("id taken")
  208. }
  209. rc := make(chan asyncResult, 1)
  210. c.awaiting[id] = rc
  211. c.awaitingMut.Unlock()
  212. ok := c.send(id, messageTypeRequest, RequestMessage{
  213. Folder: folder,
  214. Name: name,
  215. Offset: offset,
  216. Size: int32(size),
  217. Hash: hash,
  218. Flags: flags,
  219. Options: options,
  220. }, nil)
  221. if !ok {
  222. return nil, ErrClosed
  223. }
  224. res, ok := <-rc
  225. if !ok {
  226. return nil, ErrClosed
  227. }
  228. return res.val, res.err
  229. }
  230. // ClusterConfig send the cluster configuration message to the peer and returns any error
  231. func (c *rawConnection) ClusterConfig(config ClusterConfigMessage) {
  232. c.send(-1, messageTypeClusterConfig, config, nil)
  233. }
  234. func (c *rawConnection) ping() bool {
  235. var id int
  236. select {
  237. case id = <-c.nextID:
  238. case <-c.closed:
  239. return false
  240. }
  241. return c.send(id, messageTypePing, nil, nil)
  242. }
  243. func (c *rawConnection) readerLoop() (err error) {
  244. defer func() {
  245. c.close(err)
  246. }()
  247. state := stateInitial
  248. for {
  249. select {
  250. case <-c.closed:
  251. return ErrClosed
  252. default:
  253. }
  254. hdr, msg, err := c.readMessage()
  255. if err != nil {
  256. return err
  257. }
  258. switch msg := msg.(type) {
  259. case ClusterConfigMessage:
  260. if state != stateInitial {
  261. return fmt.Errorf("protocol error: cluster config message in state %d", state)
  262. }
  263. go c.receiver.ClusterConfig(c.id, msg)
  264. state = stateReady
  265. case IndexMessage:
  266. switch hdr.msgType {
  267. case messageTypeIndex:
  268. if state != stateReady {
  269. return fmt.Errorf("protocol error: index message in state %d", state)
  270. }
  271. c.handleIndex(msg)
  272. state = stateReady
  273. case messageTypeIndexUpdate:
  274. if state != stateReady {
  275. return fmt.Errorf("protocol error: index update message in state %d", state)
  276. }
  277. c.handleIndexUpdate(msg)
  278. state = stateReady
  279. }
  280. case RequestMessage:
  281. if state != stateReady {
  282. return fmt.Errorf("protocol error: request message in state %d", state)
  283. }
  284. // Requests are handled asynchronously
  285. go c.handleRequest(hdr.msgID, msg)
  286. case ResponseMessage:
  287. if state != stateReady {
  288. return fmt.Errorf("protocol error: response message in state %d", state)
  289. }
  290. c.handleResponse(hdr.msgID, msg)
  291. case pingMessage:
  292. if state != stateReady {
  293. return fmt.Errorf("protocol error: ping message in state %d", state)
  294. }
  295. // Nothing
  296. case CloseMessage:
  297. return errors.New(msg.Reason)
  298. default:
  299. return fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  300. }
  301. }
  302. }
  303. func (c *rawConnection) readMessage() (hdr header, msg encodable, err error) {
  304. if cap(c.rdbuf0) < 8 {
  305. c.rdbuf0 = make([]byte, 8)
  306. } else {
  307. c.rdbuf0 = c.rdbuf0[:8]
  308. }
  309. _, err = io.ReadFull(c.cr, c.rdbuf0)
  310. if err != nil {
  311. return
  312. }
  313. hdr = decodeHeader(binary.BigEndian.Uint32(c.rdbuf0[0:4]))
  314. msglen := int(binary.BigEndian.Uint32(c.rdbuf0[4:8]))
  315. l.Debugf("read header %v (msglen=%d)", hdr, msglen)
  316. if msglen > MaxMessageLen {
  317. err = fmt.Errorf("message length %d exceeds maximum %d", msglen, MaxMessageLen)
  318. return
  319. }
  320. if hdr.version != 0 {
  321. err = fmt.Errorf("unknown protocol version 0x%x", hdr.version)
  322. return
  323. }
  324. if cap(c.rdbuf0) < msglen {
  325. c.rdbuf0 = make([]byte, msglen)
  326. } else {
  327. c.rdbuf0 = c.rdbuf0[:msglen]
  328. }
  329. _, err = io.ReadFull(c.cr, c.rdbuf0)
  330. if err != nil {
  331. return
  332. }
  333. l.Debugf("read %d bytes", len(c.rdbuf0))
  334. msgBuf := c.rdbuf0
  335. if hdr.compression && msglen > 0 {
  336. c.rdbuf1 = c.rdbuf1[:cap(c.rdbuf1)]
  337. c.rdbuf1, err = lz4.Decode(c.rdbuf1, c.rdbuf0)
  338. if err != nil {
  339. return
  340. }
  341. msgBuf = c.rdbuf1
  342. l.Debugf("decompressed to %d bytes", len(msgBuf))
  343. }
  344. if len(msgBuf) > 1024 {
  345. l.Debugf("message data:\n%s", hex.Dump(msgBuf[:1024]))
  346. } else {
  347. l.Debugf("message data:\n%s", hex.Dump(msgBuf))
  348. }
  349. // We check each returned error for the XDRError.IsEOF() method.
  350. // IsEOF()==true here means that the message contained fewer fields than
  351. // expected. It does not signify an EOF on the socket, because we've
  352. // successfully read a size value and that many bytes already. New fields
  353. // we expected but the other peer didn't send should be interpreted as
  354. // zero/nil, and if that's not valid we'll verify it somewhere else.
  355. switch hdr.msgType {
  356. case messageTypeIndex, messageTypeIndexUpdate:
  357. var idx IndexMessage
  358. err = idx.UnmarshalXDR(msgBuf)
  359. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  360. err = nil
  361. }
  362. msg = idx
  363. case messageTypeRequest:
  364. var req RequestMessage
  365. err = req.UnmarshalXDR(msgBuf)
  366. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  367. err = nil
  368. }
  369. msg = req
  370. case messageTypeResponse:
  371. var resp ResponseMessage
  372. err = resp.UnmarshalXDR(msgBuf)
  373. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  374. err = nil
  375. }
  376. msg = resp
  377. case messageTypePing:
  378. msg = pingMessage{}
  379. case messageTypeClusterConfig:
  380. var cc ClusterConfigMessage
  381. err = cc.UnmarshalXDR(msgBuf)
  382. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  383. err = nil
  384. }
  385. msg = cc
  386. case messageTypeClose:
  387. var cm CloseMessage
  388. err = cm.UnmarshalXDR(msgBuf)
  389. if xdrErr, ok := err.(isEofer); ok && xdrErr.IsEOF() {
  390. err = nil
  391. }
  392. msg = cm
  393. default:
  394. err = fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  395. }
  396. return
  397. }
  398. func (c *rawConnection) handleIndex(im IndexMessage) {
  399. l.Debugf("Index(%v, %v, %d file, flags %x, opts: %s)", c.id, im.Folder, len(im.Files), im.Flags, im.Options)
  400. c.receiver.Index(c.id, im.Folder, filterIndexMessageFiles(im.Files), im.Flags, im.Options)
  401. }
  402. func (c *rawConnection) handleIndexUpdate(im IndexMessage) {
  403. l.Debugf("queueing IndexUpdate(%v, %v, %d files, flags %x, opts: %s)", c.id, im.Folder, len(im.Files), im.Flags, im.Options)
  404. c.receiver.IndexUpdate(c.id, im.Folder, filterIndexMessageFiles(im.Files), im.Flags, im.Options)
  405. }
  406. func filterIndexMessageFiles(fs []FileInfo) []FileInfo {
  407. var out []FileInfo
  408. for i, f := range fs {
  409. switch f.Name {
  410. case "", ".", "..", "/": // A few obviously invalid filenames
  411. l.Infof("Dropping invalid filename %q from incoming index", f.Name)
  412. if out == nil {
  413. // Most incoming updates won't contain anything invalid, so we
  414. // delay the allocation and copy to output slice until we
  415. // really need to do it, then copy all the so var valid files
  416. // to it.
  417. out = make([]FileInfo, i, len(fs)-1)
  418. copy(out, fs)
  419. }
  420. default:
  421. if out != nil {
  422. out = append(out, f)
  423. }
  424. }
  425. }
  426. if out != nil {
  427. return out
  428. }
  429. return fs
  430. }
  431. func (c *rawConnection) handleRequest(msgID int, req RequestMessage) {
  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().([]byte)[: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, int64(req.Offset), req.Hash, req.Flags, req.Options, buf)
  443. if err != nil {
  444. c.send(msgID, messageTypeResponse, ResponseMessage{
  445. Data: nil,
  446. Code: errorToCode(err),
  447. }, done)
  448. } else {
  449. c.send(msgID, messageTypeResponse, ResponseMessage{
  450. Data: buf,
  451. Code: errorToCode(err),
  452. }, done)
  453. }
  454. if usePool {
  455. <-done
  456. c.pool.Put(buf)
  457. }
  458. }
  459. func (c *rawConnection) handleResponse(msgID int, resp ResponseMessage) {
  460. c.awaitingMut.Lock()
  461. if rc := c.awaiting[msgID]; rc != nil {
  462. c.awaiting[msgID] = nil
  463. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  464. close(rc)
  465. }
  466. c.awaitingMut.Unlock()
  467. }
  468. func (c *rawConnection) handlePong(msgID int) {
  469. c.awaitingMut.Lock()
  470. if rc := c.awaiting[msgID]; rc != nil {
  471. c.awaiting[msgID] = nil
  472. rc <- asyncResult{}
  473. close(rc)
  474. }
  475. c.awaitingMut.Unlock()
  476. }
  477. func (c *rawConnection) send(msgID int, msgType int, msg encodable, done chan struct{}) bool {
  478. if msgID < 0 {
  479. select {
  480. case id := <-c.nextID:
  481. msgID = id
  482. case <-c.closed:
  483. return false
  484. }
  485. }
  486. hdr := header{
  487. version: 0,
  488. msgID: msgID,
  489. msgType: msgType,
  490. }
  491. select {
  492. case c.outbox <- hdrMsg{hdr, msg, done}:
  493. return true
  494. case <-c.closed:
  495. return false
  496. }
  497. }
  498. func (c *rawConnection) writerLoop() {
  499. var msgBuf = make([]byte, 8) // buffer for wire format message, kept and reused
  500. var uncBuf []byte // buffer for uncompressed message, kept and reused
  501. for {
  502. var tempBuf []byte
  503. var err error
  504. select {
  505. case hm := <-c.outbox:
  506. if hm.msg != nil {
  507. // Uncompressed message in uncBuf
  508. uncBuf, err = hm.msg.AppendXDR(uncBuf[:0])
  509. if hm.done != nil {
  510. close(hm.done)
  511. }
  512. if err != nil {
  513. c.close(err)
  514. return
  515. }
  516. compress := false
  517. switch c.compression {
  518. case CompressAlways:
  519. compress = true
  520. case CompressMetadata:
  521. compress = hm.hdr.msgType != messageTypeResponse
  522. }
  523. if compress && len(uncBuf) >= compressionThreshold {
  524. // Use compression for large messages
  525. hm.hdr.compression = true
  526. // Make sure we have enough space for the compressed message plus header in msgBug
  527. msgBuf = msgBuf[:cap(msgBuf)]
  528. if maxLen := lz4.CompressBound(len(uncBuf)) + 8; maxLen > len(msgBuf) {
  529. msgBuf = make([]byte, maxLen)
  530. }
  531. // Compressed is written to msgBuf, we keep tb for the length only
  532. tempBuf, err = lz4.Encode(msgBuf[8:], uncBuf)
  533. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(tempBuf)))
  534. msgBuf = msgBuf[0 : len(tempBuf)+8]
  535. l.Debugf("write compressed message; %v (len=%d)", hm.hdr, len(tempBuf))
  536. } else {
  537. // No point in compressing very short messages
  538. hm.hdr.compression = false
  539. msgBuf = msgBuf[:cap(msgBuf)]
  540. if l := len(uncBuf) + 8; l > len(msgBuf) {
  541. msgBuf = make([]byte, l)
  542. }
  543. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(uncBuf)))
  544. msgBuf = msgBuf[0 : len(uncBuf)+8]
  545. copy(msgBuf[8:], uncBuf)
  546. l.Debugf("write uncompressed message; %v (len=%d)", hm.hdr, len(uncBuf))
  547. }
  548. } else {
  549. l.Debugf("write empty message; %v", hm.hdr)
  550. binary.BigEndian.PutUint32(msgBuf[4:8], 0)
  551. msgBuf = msgBuf[:8]
  552. }
  553. binary.BigEndian.PutUint32(msgBuf[0:4], encodeHeader(hm.hdr))
  554. if err == nil {
  555. var n int
  556. n, err = c.cw.Write(msgBuf)
  557. l.Debugf("wrote %d bytes on the wire", n)
  558. }
  559. if err != nil {
  560. c.close(err)
  561. return
  562. }
  563. case <-c.closed:
  564. return
  565. }
  566. }
  567. }
  568. func (c *rawConnection) close(err error) {
  569. c.once.Do(func() {
  570. close(c.closed)
  571. c.awaitingMut.Lock()
  572. for i, ch := range c.awaiting {
  573. if ch != nil {
  574. close(ch)
  575. c.awaiting[i] = nil
  576. }
  577. }
  578. c.awaitingMut.Unlock()
  579. go c.receiver.Close(c.id, err)
  580. })
  581. }
  582. func (c *rawConnection) idGenerator() {
  583. nextID := 0
  584. for {
  585. nextID = (nextID + 1) & 0xfff
  586. select {
  587. case c.nextID <- nextID:
  588. case <-c.closed:
  589. return
  590. }
  591. }
  592. }
  593. // The pingSender makes sure that we've sent a message within the last
  594. // PingSendInterval. If we already have something sent in the last
  595. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  596. // results in an effecting ping interval of somewhere between
  597. // PingSendInterval/2 and PingSendInterval.
  598. func (c *rawConnection) pingSender() {
  599. ticker := time.Tick(PingSendInterval / 2)
  600. for {
  601. select {
  602. case <-ticker:
  603. d := time.Since(c.cw.Last())
  604. if d < PingSendInterval/2 {
  605. l.Debugln(c.id, "ping skipped after wr", d)
  606. continue
  607. }
  608. l.Debugln(c.id, "ping -> after", d)
  609. c.ping()
  610. case <-c.closed:
  611. return
  612. }
  613. }
  614. }
  615. // The pingReciever checks that we've received a message (any message will do,
  616. // but we expect pings in the absence of other messages) within the last
  617. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  618. func (c *rawConnection) pingReceiver() {
  619. ticker := time.Tick(ReceiveTimeout / 2)
  620. for {
  621. select {
  622. case <-ticker:
  623. d := time.Since(c.cr.Last())
  624. if d > ReceiveTimeout {
  625. l.Debugln(c.id, "ping timeout", d)
  626. c.close(ErrTimeout)
  627. }
  628. l.Debugln(c.id, "last read within", d)
  629. case <-c.closed:
  630. return
  631. }
  632. }
  633. }
  634. type Statistics struct {
  635. At time.Time
  636. InBytesTotal int64
  637. OutBytesTotal int64
  638. }
  639. func (c *rawConnection) Statistics() Statistics {
  640. return Statistics{
  641. At: time.Now(),
  642. InBytesTotal: c.cr.Tot(),
  643. OutBytesTotal: c.cw.Tot(),
  644. }
  645. }