protocol.go 18 KB

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