protocol.go 18 KB

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