1
0

protocol.go 20 KB

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