protocol.go 18 KB

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