1
0

protocol.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package protocol
  16. import (
  17. "encoding/binary"
  18. "encoding/hex"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "sync"
  23. "time"
  24. lz4 "github.com/bkaradzic/go-lz4"
  25. )
  26. const (
  27. BlockSize = 128 * 1024
  28. )
  29. const (
  30. messageTypeClusterConfig = 0
  31. messageTypeIndex = 1
  32. messageTypeRequest = 2
  33. messageTypeResponse = 3
  34. messageTypePing = 4
  35. messageTypePong = 5
  36. messageTypeIndexUpdate = 6
  37. messageTypeClose = 7
  38. )
  39. const (
  40. stateInitial = iota
  41. stateCCRcvd
  42. stateIdxRcvd
  43. )
  44. const (
  45. FlagDeleted uint32 = 1 << 12
  46. FlagInvalid = 1 << 13
  47. FlagDirectory = 1 << 14
  48. FlagNoPermBits = 1 << 15
  49. )
  50. const (
  51. FlagShareTrusted uint32 = 1 << 0
  52. FlagShareReadOnly = 1 << 1
  53. FlagIntroducer = 1 << 2
  54. FlagShareBits = 0x000000ff
  55. )
  56. var (
  57. ErrClusterHash = fmt.Errorf("configuration error: mismatched cluster hash")
  58. ErrClosed = errors.New("connection closed")
  59. )
  60. type Model interface {
  61. // An index was received from the peer device
  62. Index(deviceID DeviceID, folder string, files []FileInfo)
  63. // An index update was received from the peer device
  64. IndexUpdate(deviceID DeviceID, folder string, files []FileInfo)
  65. // A request was made by the peer device
  66. Request(deviceID DeviceID, folder string, name string, offset int64, size int) ([]byte, error)
  67. // A cluster configuration message was received
  68. ClusterConfig(deviceID DeviceID, config ClusterConfigMessage)
  69. // The peer device closed the connection
  70. Close(deviceID DeviceID, err error)
  71. }
  72. type Connection interface {
  73. ID() DeviceID
  74. Name() string
  75. Index(folder string, files []FileInfo) error
  76. IndexUpdate(folder string, files []FileInfo) error
  77. Request(folder string, name string, offset int64, size int) ([]byte, error)
  78. ClusterConfig(config ClusterConfigMessage)
  79. Statistics() Statistics
  80. }
  81. type rawConnection struct {
  82. id DeviceID
  83. name string
  84. receiver Model
  85. state int
  86. cr *countingReader
  87. cw *countingWriter
  88. awaiting [4096]chan asyncResult
  89. awaitingMut sync.Mutex
  90. idxMut sync.Mutex // ensures serialization of Index calls
  91. nextID chan int
  92. outbox chan hdrMsg
  93. closed chan struct{}
  94. once sync.Once
  95. compressionThreshold int // compress messages larger than this many bytes
  96. rdbuf0 []byte // used & reused by readMessage
  97. rdbuf1 []byte // used & reused by readMessage
  98. }
  99. type asyncResult struct {
  100. val []byte
  101. err error
  102. }
  103. type hdrMsg struct {
  104. hdr header
  105. msg encodable
  106. }
  107. type encodable interface {
  108. AppendXDR([]byte) []byte
  109. }
  110. const (
  111. pingTimeout = 30 * time.Second
  112. pingIdleTime = 60 * time.Second
  113. )
  114. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress bool) Connection {
  115. cr := &countingReader{Reader: reader}
  116. cw := &countingWriter{Writer: writer}
  117. compThres := 1<<31 - 1 // compression disabled
  118. if compress {
  119. compThres = 128 // compress messages that are 128 bytes long or larger
  120. }
  121. c := rawConnection{
  122. id: deviceID,
  123. name: name,
  124. receiver: nativeModel{receiver},
  125. state: stateInitial,
  126. cr: cr,
  127. cw: cw,
  128. outbox: make(chan hdrMsg),
  129. nextID: make(chan int),
  130. closed: make(chan struct{}),
  131. compressionThreshold: compThres,
  132. }
  133. go c.readerLoop()
  134. go c.writerLoop()
  135. go c.pingerLoop()
  136. go c.idGenerator()
  137. return wireFormatConnection{&c}
  138. }
  139. func (c *rawConnection) ID() DeviceID {
  140. return c.id
  141. }
  142. func (c *rawConnection) Name() string {
  143. return c.name
  144. }
  145. // Index writes the list of file information to the connected peer device
  146. func (c *rawConnection) Index(folder string, idx []FileInfo) error {
  147. select {
  148. case <-c.closed:
  149. return ErrClosed
  150. default:
  151. }
  152. c.idxMut.Lock()
  153. c.send(-1, messageTypeIndex, IndexMessage{folder, idx})
  154. c.idxMut.Unlock()
  155. return nil
  156. }
  157. // IndexUpdate writes the list of file information to the connected peer device as an update
  158. func (c *rawConnection) IndexUpdate(folder string, idx []FileInfo) error {
  159. select {
  160. case <-c.closed:
  161. return ErrClosed
  162. default:
  163. }
  164. c.idxMut.Lock()
  165. c.send(-1, messageTypeIndexUpdate, IndexMessage{folder, idx})
  166. c.idxMut.Unlock()
  167. return nil
  168. }
  169. // Request returns the bytes for the specified block after fetching them from the connected peer.
  170. func (c *rawConnection) Request(folder string, name string, offset int64, size int) ([]byte, error) {
  171. var id int
  172. select {
  173. case id = <-c.nextID:
  174. case <-c.closed:
  175. return nil, ErrClosed
  176. }
  177. c.awaitingMut.Lock()
  178. if ch := c.awaiting[id]; ch != nil {
  179. panic("id taken")
  180. }
  181. rc := make(chan asyncResult, 1)
  182. c.awaiting[id] = rc
  183. c.awaitingMut.Unlock()
  184. ok := c.send(id, messageTypeRequest, RequestMessage{folder, name, uint64(offset), uint32(size)})
  185. if !ok {
  186. return nil, ErrClosed
  187. }
  188. res, ok := <-rc
  189. if !ok {
  190. return nil, ErrClosed
  191. }
  192. return res.val, res.err
  193. }
  194. // ClusterConfig send the cluster configuration message to the peer and returns any error
  195. func (c *rawConnection) ClusterConfig(config ClusterConfigMessage) {
  196. c.send(-1, messageTypeClusterConfig, config)
  197. }
  198. func (c *rawConnection) ping() bool {
  199. var id int
  200. select {
  201. case id = <-c.nextID:
  202. case <-c.closed:
  203. return false
  204. }
  205. rc := make(chan asyncResult, 1)
  206. c.awaitingMut.Lock()
  207. c.awaiting[id] = rc
  208. c.awaitingMut.Unlock()
  209. ok := c.send(id, messageTypePing, nil)
  210. if !ok {
  211. return false
  212. }
  213. res, ok := <-rc
  214. return ok && res.err == nil
  215. }
  216. func (c *rawConnection) readerLoop() (err error) {
  217. defer func() {
  218. c.close(err)
  219. }()
  220. for {
  221. select {
  222. case <-c.closed:
  223. return ErrClosed
  224. default:
  225. }
  226. hdr, msg, err := c.readMessage()
  227. if err != nil {
  228. return err
  229. }
  230. switch hdr.msgType {
  231. case messageTypeIndex:
  232. if c.state < stateCCRcvd {
  233. return fmt.Errorf("protocol error: index message in state %d", c.state)
  234. }
  235. c.handleIndex(msg.(IndexMessage))
  236. c.state = stateIdxRcvd
  237. case messageTypeIndexUpdate:
  238. if c.state < stateIdxRcvd {
  239. return fmt.Errorf("protocol error: index update message in state %d", c.state)
  240. }
  241. c.handleIndexUpdate(msg.(IndexMessage))
  242. case messageTypeRequest:
  243. if c.state < stateIdxRcvd {
  244. return fmt.Errorf("protocol error: request message in state %d", c.state)
  245. }
  246. // Requests are handled asynchronously
  247. go c.handleRequest(hdr.msgID, msg.(RequestMessage))
  248. case messageTypeResponse:
  249. if c.state < stateIdxRcvd {
  250. return fmt.Errorf("protocol error: response message in state %d", c.state)
  251. }
  252. c.handleResponse(hdr.msgID, msg.(ResponseMessage))
  253. case messageTypePing:
  254. c.send(hdr.msgID, messageTypePong, EmptyMessage{})
  255. case messageTypePong:
  256. c.handlePong(hdr.msgID)
  257. case messageTypeClusterConfig:
  258. if c.state != stateInitial {
  259. return fmt.Errorf("protocol error: cluster config message in state %d", c.state)
  260. }
  261. go c.receiver.ClusterConfig(c.id, msg.(ClusterConfigMessage))
  262. c.state = stateCCRcvd
  263. case messageTypeClose:
  264. return errors.New(msg.(CloseMessage).Reason)
  265. default:
  266. return fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  267. }
  268. }
  269. }
  270. func (c *rawConnection) readMessage() (hdr header, msg encodable, err error) {
  271. if cap(c.rdbuf0) < 8 {
  272. c.rdbuf0 = make([]byte, 8)
  273. } else {
  274. c.rdbuf0 = c.rdbuf0[:8]
  275. }
  276. _, err = io.ReadFull(c.cr, c.rdbuf0)
  277. if err != nil {
  278. return
  279. }
  280. hdr = decodeHeader(binary.BigEndian.Uint32(c.rdbuf0[0:4]))
  281. msglen := int(binary.BigEndian.Uint32(c.rdbuf0[4:8]))
  282. if debug {
  283. l.Debugf("read header %v (msglen=%d)", hdr, msglen)
  284. }
  285. if cap(c.rdbuf0) < msglen {
  286. c.rdbuf0 = make([]byte, msglen)
  287. } else {
  288. c.rdbuf0 = c.rdbuf0[:msglen]
  289. }
  290. _, err = io.ReadFull(c.cr, c.rdbuf0)
  291. if err != nil {
  292. return
  293. }
  294. if debug {
  295. l.Debugf("read %d bytes", len(c.rdbuf0))
  296. }
  297. msgBuf := c.rdbuf0
  298. if hdr.compression {
  299. c.rdbuf1 = c.rdbuf1[:cap(c.rdbuf1)]
  300. c.rdbuf1, err = lz4.Decode(c.rdbuf1, c.rdbuf0)
  301. if err != nil {
  302. return
  303. }
  304. msgBuf = c.rdbuf1
  305. if debug {
  306. l.Debugf("decompressed to %d bytes", len(msgBuf))
  307. }
  308. }
  309. if debug {
  310. if len(msgBuf) > 1024 {
  311. l.Debugf("message data:\n%s", hex.Dump(msgBuf[:1024]))
  312. } else {
  313. l.Debugf("message data:\n%s", hex.Dump(msgBuf))
  314. }
  315. }
  316. switch hdr.msgType {
  317. case messageTypeIndex, messageTypeIndexUpdate:
  318. var idx IndexMessage
  319. err = idx.UnmarshalXDR(msgBuf)
  320. msg = idx
  321. case messageTypeRequest:
  322. var req RequestMessage
  323. err = req.UnmarshalXDR(msgBuf)
  324. msg = req
  325. case messageTypeResponse:
  326. var resp ResponseMessage
  327. err = resp.UnmarshalXDR(msgBuf)
  328. msg = resp
  329. case messageTypePing, messageTypePong:
  330. msg = EmptyMessage{}
  331. case messageTypeClusterConfig:
  332. var cc ClusterConfigMessage
  333. err = cc.UnmarshalXDR(msgBuf)
  334. msg = cc
  335. case messageTypeClose:
  336. var cm CloseMessage
  337. err = cm.UnmarshalXDR(msgBuf)
  338. msg = cm
  339. default:
  340. err = fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType)
  341. }
  342. return
  343. }
  344. func (c *rawConnection) handleIndex(im IndexMessage) {
  345. if debug {
  346. l.Debugf("Index(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  347. }
  348. c.receiver.Index(c.id, im.Folder, im.Files)
  349. }
  350. func (c *rawConnection) handleIndexUpdate(im IndexMessage) {
  351. if debug {
  352. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  353. }
  354. c.receiver.IndexUpdate(c.id, im.Folder, im.Files)
  355. }
  356. func (c *rawConnection) handleRequest(msgID int, req RequestMessage) {
  357. data, _ := c.receiver.Request(c.id, req.Folder, req.Name, int64(req.Offset), int(req.Size))
  358. c.send(msgID, messageTypeResponse, ResponseMessage{data})
  359. }
  360. func (c *rawConnection) handleResponse(msgID int, resp ResponseMessage) {
  361. c.awaitingMut.Lock()
  362. if rc := c.awaiting[msgID]; rc != nil {
  363. c.awaiting[msgID] = nil
  364. rc <- asyncResult{resp.Data, nil}
  365. close(rc)
  366. }
  367. c.awaitingMut.Unlock()
  368. }
  369. func (c *rawConnection) handlePong(msgID int) {
  370. c.awaitingMut.Lock()
  371. if rc := c.awaiting[msgID]; rc != nil {
  372. c.awaiting[msgID] = nil
  373. rc <- asyncResult{}
  374. close(rc)
  375. }
  376. c.awaitingMut.Unlock()
  377. }
  378. func (c *rawConnection) send(msgID int, msgType int, msg encodable) bool {
  379. if msgID < 0 {
  380. select {
  381. case id := <-c.nextID:
  382. msgID = id
  383. case <-c.closed:
  384. return false
  385. }
  386. }
  387. hdr := header{
  388. version: 0,
  389. msgID: msgID,
  390. msgType: msgType,
  391. }
  392. select {
  393. case c.outbox <- hdrMsg{hdr, msg}:
  394. return true
  395. case <-c.closed:
  396. return false
  397. }
  398. }
  399. func (c *rawConnection) writerLoop() {
  400. var msgBuf = make([]byte, 8) // buffer for wire format message, kept and reused
  401. var uncBuf []byte // buffer for uncompressed message, kept and reused
  402. for {
  403. var tempBuf []byte
  404. var err error
  405. select {
  406. case hm := <-c.outbox:
  407. if hm.msg != nil {
  408. // Uncompressed message in uncBuf
  409. uncBuf = hm.msg.AppendXDR(uncBuf[:0])
  410. if len(uncBuf) >= c.compressionThreshold {
  411. // Use compression for large messages
  412. hm.hdr.compression = true
  413. // Make sure we have enough space for the compressed message plus header in msgBug
  414. msgBuf = msgBuf[:cap(msgBuf)]
  415. if maxLen := lz4.CompressBound(len(uncBuf)) + 8; maxLen > len(msgBuf) {
  416. msgBuf = make([]byte, maxLen)
  417. }
  418. // Compressed is written to msgBuf, we keep tb for the length only
  419. tempBuf, err = lz4.Encode(msgBuf[8:], uncBuf)
  420. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(tempBuf)))
  421. msgBuf = msgBuf[0 : len(tempBuf)+8]
  422. if debug {
  423. l.Debugf("write compressed message; %v (len=%d)", hm.hdr, len(tempBuf))
  424. }
  425. } else {
  426. // No point in compressing very short messages
  427. hm.hdr.compression = false
  428. msgBuf = msgBuf[:cap(msgBuf)]
  429. if l := len(uncBuf) + 8; l > len(msgBuf) {
  430. msgBuf = make([]byte, l)
  431. }
  432. binary.BigEndian.PutUint32(msgBuf[4:8], uint32(len(uncBuf)))
  433. msgBuf = msgBuf[0 : len(uncBuf)+8]
  434. copy(msgBuf[8:], uncBuf)
  435. if debug {
  436. l.Debugf("write uncompressed message; %v (len=%d)", hm.hdr, len(uncBuf))
  437. }
  438. }
  439. } else {
  440. if debug {
  441. l.Debugf("write empty message; %v", hm.hdr)
  442. }
  443. binary.BigEndian.PutUint32(msgBuf[4:8], 0)
  444. msgBuf = msgBuf[:8]
  445. }
  446. binary.BigEndian.PutUint32(msgBuf[0:4], encodeHeader(hm.hdr))
  447. if err == nil {
  448. var n int
  449. n, err = c.cw.Write(msgBuf)
  450. if debug {
  451. l.Debugf("wrote %d bytes on the wire", n)
  452. }
  453. }
  454. if err != nil {
  455. c.close(err)
  456. return
  457. }
  458. case <-c.closed:
  459. return
  460. }
  461. }
  462. }
  463. func (c *rawConnection) close(err error) {
  464. c.once.Do(func() {
  465. close(c.closed)
  466. c.awaitingMut.Lock()
  467. for i, ch := range c.awaiting {
  468. if ch != nil {
  469. close(ch)
  470. c.awaiting[i] = nil
  471. }
  472. }
  473. c.awaitingMut.Unlock()
  474. go c.receiver.Close(c.id, err)
  475. })
  476. }
  477. func (c *rawConnection) idGenerator() {
  478. nextID := 0
  479. for {
  480. nextID = (nextID + 1) & 0xfff
  481. select {
  482. case c.nextID <- nextID:
  483. case <-c.closed:
  484. return
  485. }
  486. }
  487. }
  488. func (c *rawConnection) pingerLoop() {
  489. var rc = make(chan bool, 1)
  490. ticker := time.Tick(pingIdleTime / 2)
  491. for {
  492. select {
  493. case <-ticker:
  494. if d := time.Since(c.cr.Last()); d < pingIdleTime {
  495. if debug {
  496. l.Debugln(c.id, "ping skipped after rd", d)
  497. }
  498. continue
  499. }
  500. if d := time.Since(c.cw.Last()); d < pingIdleTime {
  501. if debug {
  502. l.Debugln(c.id, "ping skipped after wr", d)
  503. }
  504. continue
  505. }
  506. go func() {
  507. if debug {
  508. l.Debugln(c.id, "ping ->")
  509. }
  510. rc <- c.ping()
  511. }()
  512. select {
  513. case ok := <-rc:
  514. if debug {
  515. l.Debugln(c.id, "<- pong")
  516. }
  517. if !ok {
  518. c.close(fmt.Errorf("ping failure"))
  519. }
  520. case <-time.After(pingTimeout):
  521. c.close(fmt.Errorf("ping timeout"))
  522. case <-c.closed:
  523. return
  524. }
  525. case <-c.closed:
  526. return
  527. }
  528. }
  529. }
  530. type Statistics struct {
  531. At time.Time
  532. InBytesTotal uint64
  533. OutBytesTotal uint64
  534. }
  535. func (c *rawConnection) Statistics() Statistics {
  536. return Statistics{
  537. At: time.Now(),
  538. InBytesTotal: c.cr.Tot(),
  539. OutBytesTotal: c.cw.Tot(),
  540. }
  541. }
  542. func IsDeleted(bits uint32) bool {
  543. return bits&FlagDeleted != 0
  544. }
  545. func IsInvalid(bits uint32) bool {
  546. return bits&FlagInvalid != 0
  547. }
  548. func IsDirectory(bits uint32) bool {
  549. return bits&FlagDirectory != 0
  550. }
  551. func HasPermissionBits(bits uint32) bool {
  552. return bits&FlagNoPermBits == 0
  553. }