protocol.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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 len(msgBuf) > 1024 {
  351. l.Debugf("message data:\n%s", hex.Dump(msgBuf[:1024]))
  352. } else {
  353. l.Debugf("message data:\n%s", hex.Dump(msgBuf))
  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. l.Debugf("Index(%v, %v, %d file, flags %x, opts: %s)", c.id, im.Folder, len(im.Files), im.Flags, im.Options)
  406. c.receiver.Index(c.id, im.Folder, filterIndexMessageFiles(im.Files), im.Flags, im.Options)
  407. }
  408. func (c *rawConnection) handleIndexUpdate(im IndexMessage) {
  409. l.Debugf("queueing IndexUpdate(%v, %v, %d files, flags %x, opts: %s)", c.id, im.Folder, len(im.Files), im.Flags, im.Options)
  410. c.receiver.IndexUpdate(c.id, im.Folder, filterIndexMessageFiles(im.Files), im.Flags, im.Options)
  411. }
  412. func filterIndexMessageFiles(fs []FileInfo) []FileInfo {
  413. var out []FileInfo
  414. for i, f := range fs {
  415. switch f.Name {
  416. case "", ".", "..", "/": // A few obviously invalid filenames
  417. l.Infof("Dropping invalid filename %q from incoming index", f.Name)
  418. if out == nil {
  419. // Most incoming updates won't contain anything invalid, so we
  420. // delay the allocation and copy to output slice until we
  421. // really need to do it, then copy all the so var valid files
  422. // to it.
  423. out = make([]FileInfo, i, len(fs)-1)
  424. copy(out, fs)
  425. }
  426. default:
  427. if out != nil {
  428. out = append(out, f)
  429. }
  430. }
  431. }
  432. if out != nil {
  433. return out
  434. }
  435. return fs
  436. }
  437. func (c *rawConnection) handleRequest(msgID int, req RequestMessage) {
  438. size := int(req.Size)
  439. usePool := size <= BlockSize
  440. var buf []byte
  441. var done chan struct{}
  442. if usePool {
  443. buf = c.pool.Get().([]byte)[:size]
  444. done = make(chan struct{})
  445. } else {
  446. buf = make([]byte, size)
  447. }
  448. err := c.receiver.Request(c.id, req.Folder, req.Name, int64(req.Offset), req.Hash, req.Flags, req.Options, buf)
  449. if err != nil {
  450. c.send(msgID, messageTypeResponse, ResponseMessage{
  451. Data: nil,
  452. Code: errorToCode(err),
  453. }, done)
  454. } else {
  455. c.send(msgID, messageTypeResponse, ResponseMessage{
  456. Data: buf,
  457. Code: errorToCode(err),
  458. }, done)
  459. }
  460. if usePool {
  461. <-done
  462. c.pool.Put(buf)
  463. }
  464. }
  465. func (c *rawConnection) handleResponse(msgID int, resp ResponseMessage) {
  466. c.awaitingMut.Lock()
  467. if rc := c.awaiting[msgID]; rc != nil {
  468. c.awaiting[msgID] = nil
  469. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  470. close(rc)
  471. }
  472. c.awaitingMut.Unlock()
  473. }
  474. func (c *rawConnection) handlePong(msgID int) {
  475. c.awaitingMut.Lock()
  476. if rc := c.awaiting[msgID]; rc != nil {
  477. c.awaiting[msgID] = nil
  478. rc <- asyncResult{}
  479. close(rc)
  480. }
  481. c.awaitingMut.Unlock()
  482. }
  483. func (c *rawConnection) send(msgID int, msgType int, msg encodable, done chan struct{}) bool {
  484. if msgID < 0 {
  485. select {
  486. case id := <-c.nextID:
  487. msgID = id
  488. case <-c.closed:
  489. return false
  490. }
  491. }
  492. hdr := header{
  493. version: 0,
  494. msgID: msgID,
  495. msgType: msgType,
  496. }
  497. select {
  498. case c.outbox <- hdrMsg{hdr, msg, done}:
  499. return true
  500. case <-c.closed:
  501. return false
  502. }
  503. }
  504. func (c *rawConnection) writerLoop() {
  505. var msgBuf = make([]byte, 8) // buffer for wire format message, kept and reused
  506. var uncBuf []byte // buffer for uncompressed message, kept and reused
  507. for {
  508. var tempBuf []byte
  509. var err error
  510. select {
  511. case hm := <-c.outbox:
  512. if hm.msg != nil {
  513. // Uncompressed message in uncBuf
  514. uncBuf, err = hm.msg.AppendXDR(uncBuf[:0])
  515. if hm.done != nil {
  516. close(hm.done)
  517. }
  518. if err != nil {
  519. c.close(err)
  520. return
  521. }
  522. compress := false
  523. switch c.compression {
  524. case CompressAlways:
  525. compress = true
  526. case CompressMetadata:
  527. compress = hm.hdr.msgType != messageTypeResponse
  528. }
  529. if compress && len(uncBuf) >= compressionThreshold {
  530. // Use compression for large messages
  531. hm.hdr.compression = true
  532. // Make sure we have enough space for the compressed message plus header in msgBug
  533. msgBuf = msgBuf[:cap(msgBuf)]
  534. if maxLen := lz4.CompressBound(len(uncBuf)) + 8; maxLen > len(msgBuf) {
  535. msgBuf = make([]byte, maxLen)
  536. }
  537. // Compressed is written to msgBuf, we keep tb for the length only
  538. tempBuf, err = lz4.Encode(msgBuf[8:], uncBuf)
  539. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(tempBuf)))
  540. msgBuf = msgBuf[0 : len(tempBuf)+8]
  541. l.Debugf("write compressed message; %v (len=%d)", hm.hdr, len(tempBuf))
  542. } else {
  543. // No point in compressing very short messages
  544. hm.hdr.compression = false
  545. msgBuf = msgBuf[:cap(msgBuf)]
  546. if l := len(uncBuf) + 8; l > len(msgBuf) {
  547. msgBuf = make([]byte, l)
  548. }
  549. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(uncBuf)))
  550. msgBuf = msgBuf[0 : len(uncBuf)+8]
  551. copy(msgBuf[8:], uncBuf)
  552. l.Debugf("write uncompressed message; %v (len=%d)", hm.hdr, len(uncBuf))
  553. }
  554. } else {
  555. l.Debugf("write empty message; %v", hm.hdr)
  556. binary.BigEndian.PutUint32(msgBuf[4:8], 0)
  557. msgBuf = msgBuf[:8]
  558. }
  559. binary.BigEndian.PutUint32(msgBuf[0:4], encodeHeader(hm.hdr))
  560. if err == nil {
  561. var n int
  562. n, err = c.cw.Write(msgBuf)
  563. l.Debugf("wrote %d bytes on the wire", n)
  564. }
  565. if err != nil {
  566. c.close(err)
  567. return
  568. }
  569. case <-c.closed:
  570. return
  571. }
  572. }
  573. }
  574. func (c *rawConnection) close(err error) {
  575. c.once.Do(func() {
  576. close(c.closed)
  577. c.awaitingMut.Lock()
  578. for i, ch := range c.awaiting {
  579. if ch != nil {
  580. close(ch)
  581. c.awaiting[i] = nil
  582. }
  583. }
  584. c.awaitingMut.Unlock()
  585. go c.receiver.Close(c.id, err)
  586. })
  587. }
  588. func (c *rawConnection) idGenerator() {
  589. nextID := 0
  590. for {
  591. nextID = (nextID + 1) & 0xfff
  592. select {
  593. case c.nextID <- nextID:
  594. case <-c.closed:
  595. return
  596. }
  597. }
  598. }
  599. // The pingSender makes sure that we've sent a message within the last
  600. // PingSendInterval. If we already have something sent in the last
  601. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  602. // results in an effecting ping interval of somewhere between
  603. // PingSendInterval/2 and PingSendInterval.
  604. func (c *rawConnection) pingSender() {
  605. ticker := time.Tick(PingSendInterval / 2)
  606. for {
  607. select {
  608. case <-ticker:
  609. d := time.Since(c.cw.Last())
  610. if d < PingSendInterval/2 {
  611. l.Debugln(c.id, "ping skipped after wr", d)
  612. continue
  613. }
  614. l.Debugln(c.id, "ping -> after", d)
  615. c.ping()
  616. case <-c.closed:
  617. return
  618. }
  619. }
  620. }
  621. // The pingReciever checks that we've received a message (any message will do,
  622. // but we expect pings in the absence of other messages) within the last
  623. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  624. func (c *rawConnection) pingReceiver() {
  625. ticker := time.Tick(ReceiveTimeout / 2)
  626. for {
  627. select {
  628. case <-ticker:
  629. d := time.Since(c.cr.Last())
  630. if d > ReceiveTimeout {
  631. l.Debugln(c.id, "ping timeout", d)
  632. c.close(ErrTimeout)
  633. }
  634. l.Debugln(c.id, "last read within", d)
  635. case <-c.closed:
  636. return
  637. }
  638. }
  639. }
  640. type Statistics struct {
  641. At time.Time
  642. InBytesTotal int64
  643. OutBytesTotal int64
  644. }
  645. func (c *rawConnection) Statistics() Statistics {
  646. return Statistics{
  647. At: time.Now(),
  648. InBytesTotal: c.cr.Tot(),
  649. OutBytesTotal: c.cw.Tot(),
  650. }
  651. }