protocol.go 18 KB

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