protocol.go 18 KB

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