protocol.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //go:generate -command counterfeiter go run github.com/maxbrunsfeld/counterfeiter/v6
  7. // Prevents import loop, for internal testing
  8. //go:generate counterfeiter -o mocked_connection_info_test.go --fake-name mockedConnectionInfo . ConnectionInfo
  9. //go:generate go run ../../script/prune_mocks.go -t mocked_connection_info_test.go
  10. //go:generate counterfeiter -o mocks/connection_info.go --fake-name ConnectionInfo . ConnectionInfo
  11. //go:generate counterfeiter -o mocks/connection.go --fake-name Connection . Connection
  12. package protocol
  13. import (
  14. "context"
  15. "encoding/binary"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "net"
  20. "path"
  21. "strings"
  22. "sync"
  23. "time"
  24. lz4 "github.com/pierrec/lz4/v4"
  25. "google.golang.org/protobuf/proto"
  26. "github.com/syncthing/syncthing/internal/gen/bep"
  27. "github.com/syncthing/syncthing/internal/protoutil"
  28. )
  29. const (
  30. // Shifts
  31. KiB = 10
  32. MiB = 20
  33. GiB = 30
  34. )
  35. const (
  36. // MaxMessageLen is the largest message size allowed on the wire. (500 MB)
  37. MaxMessageLen = 500 * 1000 * 1000
  38. // MinBlockSize is the minimum block size allowed
  39. MinBlockSize = 128 << KiB
  40. // MaxBlockSize is the maximum block size allowed
  41. MaxBlockSize = 16 << MiB
  42. // DesiredPerFileBlocks is the number of blocks we aim for per file
  43. DesiredPerFileBlocks = 2000
  44. SyntheticDirectorySize = 128
  45. // don't bother compressing messages smaller than this many bytes
  46. compressionThreshold = 128
  47. )
  48. var errNotCompressible = errors.New("not compressible")
  49. const (
  50. stateInitial = iota
  51. stateReady
  52. )
  53. var (
  54. ErrClosed = errors.New("connection closed")
  55. ErrTimeout = errors.New("read timeout")
  56. errUnknownMessage = errors.New("unknown message")
  57. errInvalidFilename = errors.New("filename is invalid")
  58. errUncleanFilename = errors.New("filename not in canonical format")
  59. errDeletedHasBlocks = errors.New("deleted file with non-empty block list")
  60. errDirectoryHasBlocks = errors.New("directory with non-empty block list")
  61. errFileHasNoBlocks = errors.New("file with empty block list")
  62. )
  63. type Model interface {
  64. // An index was received from the peer device
  65. Index(conn Connection, idx *Index) error
  66. // An index update was received from the peer device
  67. IndexUpdate(conn Connection, idxUp *IndexUpdate) error
  68. // A request was made by the peer device
  69. Request(conn Connection, req *Request) (RequestResponse, error)
  70. // A cluster configuration message was received
  71. ClusterConfig(conn Connection, config *ClusterConfig) error
  72. // The peer device closed the connection or an error occurred
  73. Closed(conn Connection, err error)
  74. // The peer device sent progress updates for the files it is currently downloading
  75. DownloadProgress(conn Connection, p *DownloadProgress) error
  76. }
  77. // rawModel is the Model interface, but without the initial Connection
  78. // parameter. Internal use only.
  79. type rawModel interface {
  80. Index(*Index) error
  81. IndexUpdate(*IndexUpdate) error
  82. Request(*Request) (RequestResponse, error)
  83. ClusterConfig(*ClusterConfig) error
  84. Closed(err error)
  85. DownloadProgress(*DownloadProgress) error
  86. }
  87. type RequestResponse interface {
  88. Data() []byte
  89. Close() // Must always be called once the byte slice is no longer in use
  90. Wait() // Blocks until Close is called
  91. }
  92. type Connection interface {
  93. // Send an Index message to the peer device. The message in the
  94. // parameter may be altered by the connection and should not be used
  95. // further by the caller.
  96. Index(ctx context.Context, idx *Index) error
  97. // Send an Index Update message to the peer device. The message in the
  98. // parameter may be altered by the connection and should not be used
  99. // further by the caller.
  100. IndexUpdate(ctx context.Context, idxUp *IndexUpdate) error
  101. // Send a Request message to the peer device. The message in the
  102. // parameter may be altered by the connection and should not be used
  103. // further by the caller.
  104. Request(ctx context.Context, req *Request) ([]byte, error)
  105. // Send a Cluster Configuration message to the peer device. The message
  106. // in the parameter may be altered by the connection and should not be
  107. // used further by the caller.
  108. ClusterConfig(config *ClusterConfig)
  109. // Send a Download Progress message to the peer device. The message in
  110. // the parameter may be altered by the connection and should not be used
  111. // further by the caller.
  112. DownloadProgress(ctx context.Context, dp *DownloadProgress)
  113. Start()
  114. SetFolderPasswords(passwords map[string]string)
  115. Close(err error)
  116. DeviceID() DeviceID
  117. Statistics() Statistics
  118. Closed() <-chan struct{}
  119. ConnectionInfo
  120. }
  121. type ConnectionInfo interface {
  122. Type() string
  123. Transport() string
  124. IsLocal() bool
  125. RemoteAddr() net.Addr
  126. Priority() int
  127. String() string
  128. Crypto() string
  129. EstablishedAt() time.Time
  130. ConnectionID() string
  131. }
  132. type rawConnection struct {
  133. ConnectionInfo
  134. deviceID DeviceID
  135. idString string
  136. model rawModel
  137. startTime time.Time
  138. started chan struct{}
  139. cr *countingReader
  140. cw *countingWriter
  141. closer io.Closer // Closing the underlying connection and thus cr and cw
  142. awaitingMut sync.Mutex // Protects awaiting and nextID.
  143. awaiting map[int]chan asyncResult
  144. nextID int
  145. idxMut sync.Mutex // ensures serialization of Index calls
  146. inbox chan proto.Message
  147. outbox chan asyncMessage
  148. closeBox chan asyncMessage
  149. clusterConfigBox chan *ClusterConfig
  150. dispatcherLoopStopped chan struct{}
  151. closed chan struct{}
  152. closeOnce sync.Once
  153. sendCloseOnce sync.Once
  154. compression Compression
  155. startStopMut sync.Mutex // start and stop must be serialized
  156. loopWG sync.WaitGroup // Need to ensure no leftover routines in testing
  157. }
  158. type asyncResult struct {
  159. val []byte
  160. err error
  161. }
  162. type asyncMessage struct {
  163. msg proto.Message
  164. done chan struct{} // done closes when we're done sending the message
  165. }
  166. const (
  167. // PingSendInterval is how often we make sure to send a message, by
  168. // triggering pings if necessary.
  169. PingSendInterval = 90 * time.Second
  170. // ReceiveTimeout is the longest we'll wait for a message from the other
  171. // side before closing the connection.
  172. ReceiveTimeout = 300 * time.Second
  173. )
  174. // CloseTimeout is the longest we'll wait when trying to send the close
  175. // message before just closing the connection.
  176. // Should not be modified in production code, just for testing.
  177. var CloseTimeout = 10 * time.Second
  178. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, closer io.Closer, model Model, connInfo ConnectionInfo, compress Compression, passwords map[string]string, keyGen *KeyGenerator) Connection {
  179. // We create the wrapper for the model first, as it needs to be passed
  180. // in at the lowest level in the stack. At the end of construction,
  181. // before returning, we add the connection to cwm so that it can be used
  182. // by the model.
  183. cwm := &connectionWrappingModel{model: model}
  184. // Encryption / decryption is first (outermost) before conversion to
  185. // native path formats.
  186. nm := makeNative(cwm)
  187. em := newEncryptedModel(nm, newFolderKeyRegistry(keyGen, passwords), keyGen)
  188. // We do the wire format conversion first (outermost) so that the
  189. // metadata is in wire format when it reaches the encryption step.
  190. rc := newRawConnection(deviceID, reader, writer, closer, em, connInfo, compress)
  191. ec := newEncryptedConnection(rc, rc, em.folderKeys, keyGen)
  192. wc := wireFormatConnection{ec}
  193. cwm.conn = wc
  194. return wc
  195. }
  196. func newRawConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, closer io.Closer, receiver rawModel, connInfo ConnectionInfo, compress Compression) *rawConnection {
  197. idString := deviceID.String()
  198. cr := &countingReader{Reader: reader, idString: idString}
  199. cw := &countingWriter{Writer: writer, idString: idString}
  200. registerDeviceMetrics(idString)
  201. return &rawConnection{
  202. ConnectionInfo: connInfo,
  203. deviceID: deviceID,
  204. idString: deviceID.String(),
  205. model: receiver,
  206. started: make(chan struct{}),
  207. cr: cr,
  208. cw: cw,
  209. closer: closer,
  210. awaiting: make(map[int]chan asyncResult),
  211. inbox: make(chan proto.Message),
  212. outbox: make(chan asyncMessage),
  213. closeBox: make(chan asyncMessage),
  214. clusterConfigBox: make(chan *ClusterConfig),
  215. dispatcherLoopStopped: make(chan struct{}),
  216. closed: make(chan struct{}),
  217. compression: compress,
  218. loopWG: sync.WaitGroup{},
  219. }
  220. }
  221. // Start creates the goroutines for sending and receiving of messages. It must
  222. // be called exactly once after creating a connection.
  223. func (c *rawConnection) Start() {
  224. c.startStopMut.Lock()
  225. defer c.startStopMut.Unlock()
  226. c.loopWG.Add(5)
  227. go func() {
  228. c.readerLoop()
  229. c.loopWG.Done()
  230. }()
  231. go func() {
  232. err := c.dispatcherLoop()
  233. c.Close(err)
  234. c.loopWG.Done()
  235. }()
  236. go func() {
  237. c.writerLoop()
  238. c.loopWG.Done()
  239. }()
  240. go func() {
  241. c.pingSender()
  242. c.loopWG.Done()
  243. }()
  244. go func() {
  245. c.pingReceiver()
  246. c.loopWG.Done()
  247. }()
  248. c.startTime = time.Now().Truncate(time.Second)
  249. close(c.started)
  250. }
  251. func (c *rawConnection) DeviceID() DeviceID {
  252. return c.deviceID
  253. }
  254. // Index writes the list of file information to the connected peer device
  255. func (c *rawConnection) Index(ctx context.Context, idx *Index) error {
  256. select {
  257. case <-c.closed:
  258. return ErrClosed
  259. case <-ctx.Done():
  260. return ctx.Err()
  261. default:
  262. }
  263. c.idxMut.Lock()
  264. c.send(ctx, idx.toWire(), nil)
  265. c.idxMut.Unlock()
  266. return nil
  267. }
  268. // IndexUpdate writes the list of file information to the connected peer device as an update
  269. func (c *rawConnection) IndexUpdate(ctx context.Context, idxUp *IndexUpdate) error {
  270. select {
  271. case <-c.closed:
  272. return ErrClosed
  273. case <-ctx.Done():
  274. return ctx.Err()
  275. default:
  276. }
  277. c.idxMut.Lock()
  278. c.send(ctx, idxUp.toWire(), nil)
  279. c.idxMut.Unlock()
  280. return nil
  281. }
  282. // Request returns the bytes for the specified block after fetching them from the connected peer.
  283. func (c *rawConnection) Request(ctx context.Context, req *Request) ([]byte, error) {
  284. select {
  285. case <-c.closed:
  286. return nil, ErrClosed
  287. case <-ctx.Done():
  288. return nil, ctx.Err()
  289. default:
  290. }
  291. rc := make(chan asyncResult, 1)
  292. c.awaitingMut.Lock()
  293. id := c.nextID
  294. c.nextID++
  295. if _, ok := c.awaiting[id]; ok {
  296. c.awaitingMut.Unlock()
  297. panic("id taken")
  298. }
  299. c.awaiting[id] = rc
  300. c.awaitingMut.Unlock()
  301. req.ID = id
  302. ok := c.send(ctx, req.toWire(), nil)
  303. if !ok {
  304. return nil, ErrClosed
  305. }
  306. select {
  307. case res, ok := <-rc:
  308. if !ok {
  309. return nil, ErrClosed
  310. }
  311. return res.val, res.err
  312. case <-ctx.Done():
  313. return nil, ctx.Err()
  314. }
  315. }
  316. // ClusterConfig sends the cluster configuration message to the peer.
  317. func (c *rawConnection) ClusterConfig(config *ClusterConfig) {
  318. select {
  319. case c.clusterConfigBox <- config:
  320. case <-c.closed:
  321. }
  322. }
  323. func (c *rawConnection) Closed() <-chan struct{} {
  324. return c.closed
  325. }
  326. // DownloadProgress sends the progress updates for the files that are currently being downloaded.
  327. func (c *rawConnection) DownloadProgress(ctx context.Context, dp *DownloadProgress) {
  328. c.send(ctx, dp.toWire(), nil)
  329. }
  330. func (c *rawConnection) ping() bool {
  331. return c.send(context.Background(), &bep.Ping{}, nil)
  332. }
  333. func (c *rawConnection) readerLoop() {
  334. fourByteBuf := make([]byte, 4)
  335. for {
  336. msg, err := c.readMessage(fourByteBuf)
  337. if err != nil {
  338. if err == errUnknownMessage {
  339. // Unknown message types are skipped, for future extensibility.
  340. continue
  341. }
  342. c.internalClose(err)
  343. return
  344. }
  345. select {
  346. case c.inbox <- msg:
  347. case <-c.closed:
  348. return
  349. }
  350. }
  351. }
  352. func (c *rawConnection) dispatcherLoop() (err error) {
  353. defer close(c.dispatcherLoopStopped)
  354. var msg proto.Message
  355. state := stateInitial
  356. for {
  357. select {
  358. case <-c.closed:
  359. return ErrClosed
  360. default:
  361. }
  362. select {
  363. case msg = <-c.inbox:
  364. case <-c.closed:
  365. return ErrClosed
  366. }
  367. metricDeviceRecvMessages.WithLabelValues(c.idString).Inc()
  368. msgContext, err := messageContext(msg)
  369. if err != nil {
  370. return fmt.Errorf("protocol error: %w", err)
  371. }
  372. l.Debugf("handle %v message", msgContext)
  373. switch msg := msg.(type) {
  374. case *bep.ClusterConfig:
  375. if state == stateInitial {
  376. state = stateReady
  377. }
  378. case *bep.Close:
  379. return fmt.Errorf("closed by remote: %v", msg.Reason)
  380. default:
  381. if state != stateReady {
  382. return newProtocolError(fmt.Errorf("invalid state %d", state), msgContext)
  383. }
  384. }
  385. switch msg := msg.(type) {
  386. case *bep.Request:
  387. err = checkFilename(msg.Name)
  388. }
  389. if err != nil {
  390. return newProtocolError(err, msgContext)
  391. }
  392. switch msg := msg.(type) {
  393. case *bep.ClusterConfig:
  394. err = c.model.ClusterConfig(clusterConfigFromWire(msg))
  395. case *bep.Index:
  396. idx := indexFromWire(msg)
  397. if err := checkIndexConsistency(idx.Files); err != nil {
  398. return newProtocolError(err, msgContext)
  399. }
  400. err = c.handleIndex(idx)
  401. case *bep.IndexUpdate:
  402. idxUp := indexUpdateFromWire(msg)
  403. if err := checkIndexConsistency(idxUp.Files); err != nil {
  404. return newProtocolError(err, msgContext)
  405. }
  406. err = c.handleIndexUpdate(idxUp)
  407. case *bep.Request:
  408. go c.handleRequest(requestFromWire(msg))
  409. case *bep.Response:
  410. c.handleResponse(responseFromWire(msg))
  411. case *bep.DownloadProgress:
  412. err = c.model.DownloadProgress(downloadProgressFromWire(msg))
  413. }
  414. if err != nil {
  415. return newHandleError(err, msgContext)
  416. }
  417. }
  418. }
  419. func (c *rawConnection) readMessage(fourByteBuf []byte) (proto.Message, error) {
  420. hdr, err := c.readHeader(fourByteBuf)
  421. if err != nil {
  422. return nil, err
  423. }
  424. return c.readMessageAfterHeader(hdr, fourByteBuf)
  425. }
  426. func (c *rawConnection) readMessageAfterHeader(hdr *bep.Header, fourByteBuf []byte) (proto.Message, error) {
  427. // First comes a 4 byte message length
  428. if _, err := io.ReadFull(c.cr, fourByteBuf[:4]); err != nil {
  429. return nil, fmt.Errorf("reading message length: %w", err)
  430. }
  431. msgLen := int32(binary.BigEndian.Uint32(fourByteBuf))
  432. if msgLen < 0 {
  433. return nil, fmt.Errorf("negative message length %d", msgLen)
  434. } else if msgLen > MaxMessageLen {
  435. return nil, fmt.Errorf("message length %d exceeds maximum %d", msgLen, MaxMessageLen)
  436. }
  437. // Then comes the message
  438. buf := BufferPool.Get(int(msgLen))
  439. defer BufferPool.Put(buf)
  440. if _, err := io.ReadFull(c.cr, buf); err != nil {
  441. return nil, fmt.Errorf("reading message: %w", err)
  442. }
  443. // ... which might be compressed
  444. switch hdr.Compression {
  445. case bep.MessageCompression_MESSAGE_COMPRESSION_NONE:
  446. // Nothing
  447. case bep.MessageCompression_MESSAGE_COMPRESSION_LZ4:
  448. decomp, err := lz4Decompress(buf)
  449. if err != nil {
  450. return nil, fmt.Errorf("decompressing message: %w", err)
  451. }
  452. buf = decomp
  453. default:
  454. return nil, fmt.Errorf("unknown message compression %d", hdr.Compression)
  455. }
  456. // ... and is then unmarshalled
  457. metricDeviceRecvDecompressedBytes.WithLabelValues(c.idString).Add(float64(4 + len(buf)))
  458. msg, err := newMessage(hdr.Type)
  459. if err != nil {
  460. return nil, err
  461. }
  462. if err := proto.Unmarshal(buf, msg); err != nil {
  463. return nil, fmt.Errorf("unmarshalling message: %w", err)
  464. }
  465. return msg, nil
  466. }
  467. func (c *rawConnection) readHeader(fourByteBuf []byte) (*bep.Header, error) {
  468. // First comes a 2 byte header length
  469. if _, err := io.ReadFull(c.cr, fourByteBuf[:2]); err != nil {
  470. return nil, fmt.Errorf("reading length: %w", err)
  471. }
  472. hdrLen := int16(binary.BigEndian.Uint16(fourByteBuf))
  473. if hdrLen < 0 {
  474. return nil, fmt.Errorf("negative header length %d", hdrLen)
  475. }
  476. // Then comes the header
  477. buf := BufferPool.Get(int(hdrLen))
  478. defer BufferPool.Put(buf)
  479. if _, err := io.ReadFull(c.cr, buf); err != nil {
  480. return nil, fmt.Errorf("reading header: %w", err)
  481. }
  482. var hdr bep.Header
  483. err := proto.Unmarshal(buf, &hdr)
  484. if err != nil {
  485. return nil, fmt.Errorf("unmarshalling header: %w", err)
  486. }
  487. metricDeviceRecvDecompressedBytes.WithLabelValues(c.idString).Add(float64(2 + len(buf)))
  488. return &hdr, nil
  489. }
  490. func (c *rawConnection) handleIndex(im *Index) error {
  491. l.Debugf("Index(%v, %v, %d file)", c.deviceID, im.Folder, len(im.Files))
  492. return c.model.Index(im)
  493. }
  494. func (c *rawConnection) handleIndexUpdate(im *IndexUpdate) error {
  495. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.deviceID, im.Folder, len(im.Files))
  496. return c.model.IndexUpdate(im)
  497. }
  498. // checkIndexConsistency verifies a number of invariants on FileInfos received in
  499. // index messages.
  500. func checkIndexConsistency(fs []FileInfo) error {
  501. for _, f := range fs {
  502. if err := checkFileInfoConsistency(f); err != nil {
  503. return fmt.Errorf("%q: %w", f.Name, err)
  504. }
  505. }
  506. return nil
  507. }
  508. // checkFileInfoConsistency verifies a number of invariants on the given FileInfo
  509. func checkFileInfoConsistency(f FileInfo) error {
  510. if err := checkFilename(f.Name); err != nil {
  511. return err
  512. }
  513. switch {
  514. case f.Deleted && len(f.Blocks) != 0:
  515. // Deleted files should have no blocks
  516. return errDeletedHasBlocks
  517. case f.Type == FileInfoTypeDirectory && len(f.Blocks) != 0:
  518. // Directories should have no blocks
  519. return errDirectoryHasBlocks
  520. case !f.Deleted && !f.IsInvalid() && f.Type == FileInfoTypeFile && len(f.Blocks) == 0:
  521. // Non-deleted, non-invalid files should have at least one block
  522. return errFileHasNoBlocks
  523. }
  524. return nil
  525. }
  526. // checkFilename verifies that the given filename is valid according to the
  527. // spec on what's allowed over the wire. A filename failing this test is
  528. // grounds for disconnecting the device.
  529. func checkFilename(name string) error {
  530. cleanedName := path.Clean(name)
  531. if cleanedName != name {
  532. // The filename on the wire should be in canonical format. If
  533. // Clean() managed to clean it up, there was something wrong with
  534. // it.
  535. return errUncleanFilename
  536. }
  537. switch name {
  538. case "", ".", "..":
  539. // These names are always invalid.
  540. return errInvalidFilename
  541. }
  542. if strings.HasPrefix(name, "/") {
  543. // Names are folder relative, not absolute.
  544. return errInvalidFilename
  545. }
  546. if strings.HasPrefix(name, "../") {
  547. // Starting with a dotdot is not allowed. Any other dotdots would
  548. // have been handled by the Clean() call at the top.
  549. return errInvalidFilename
  550. }
  551. return nil
  552. }
  553. func (c *rawConnection) handleRequest(req *Request) {
  554. res, err := c.model.Request(req)
  555. if err != nil {
  556. resp := &Response{
  557. ID: req.ID,
  558. Code: errorToCode(err),
  559. }
  560. c.send(context.Background(), resp.toWire(), nil)
  561. return
  562. }
  563. done := make(chan struct{})
  564. resp := &Response{
  565. ID: req.ID,
  566. Data: res.Data(),
  567. Code: errorToCode(nil),
  568. }
  569. c.send(context.Background(), resp.toWire(), done)
  570. <-done
  571. res.Close()
  572. }
  573. func (c *rawConnection) handleResponse(resp *Response) {
  574. c.awaitingMut.Lock()
  575. if rc := c.awaiting[resp.ID]; rc != nil {
  576. delete(c.awaiting, resp.ID)
  577. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  578. close(rc)
  579. }
  580. c.awaitingMut.Unlock()
  581. }
  582. func (c *rawConnection) send(ctx context.Context, msg proto.Message, done chan struct{}) bool {
  583. select {
  584. case c.outbox <- asyncMessage{msg, done}:
  585. return true
  586. case <-c.closed:
  587. case <-ctx.Done():
  588. }
  589. if done != nil {
  590. close(done)
  591. }
  592. return false
  593. }
  594. func (c *rawConnection) writerLoop() {
  595. select {
  596. case cc := <-c.clusterConfigBox:
  597. err := c.writeMessage(cc.toWire())
  598. if err != nil {
  599. c.internalClose(err)
  600. return
  601. }
  602. case hm := <-c.closeBox:
  603. _ = c.writeMessage(hm.msg)
  604. close(hm.done)
  605. return
  606. case <-c.closed:
  607. return
  608. }
  609. for {
  610. // When the connection is closing or closed, that should happen
  611. // immediately, not compete with the (potentially very busy) outbox.
  612. select {
  613. case hm := <-c.closeBox:
  614. _ = c.writeMessage(hm.msg)
  615. close(hm.done)
  616. return
  617. case <-c.closed:
  618. return
  619. default:
  620. }
  621. select {
  622. case cc := <-c.clusterConfigBox:
  623. err := c.writeMessage(cc.toWire())
  624. if err != nil {
  625. c.internalClose(err)
  626. return
  627. }
  628. case hm := <-c.outbox:
  629. err := c.writeMessage(hm.msg)
  630. if hm.done != nil {
  631. close(hm.done)
  632. }
  633. if err != nil {
  634. c.internalClose(err)
  635. return
  636. }
  637. case hm := <-c.closeBox:
  638. _ = c.writeMessage(hm.msg)
  639. close(hm.done)
  640. return
  641. case <-c.closed:
  642. return
  643. }
  644. }
  645. }
  646. func (c *rawConnection) writeMessage(msg proto.Message) error {
  647. msgContext, _ := messageContext(msg)
  648. l.Debugf("Writing %v", msgContext)
  649. defer func() {
  650. metricDeviceSentMessages.WithLabelValues(c.idString).Inc()
  651. }()
  652. size := proto.Size(msg)
  653. hdr := &bep.Header{
  654. Type: typeOf(msg),
  655. }
  656. hdrSize := proto.Size(hdr)
  657. if hdrSize > 1<<16-1 {
  658. panic("impossibly large header")
  659. }
  660. overhead := 2 + hdrSize + 4
  661. totSize := overhead + size
  662. buf := BufferPool.Get(totSize)
  663. defer BufferPool.Put(buf)
  664. // Message
  665. if _, err := protoutil.MarshalTo(buf[overhead:], msg); err != nil {
  666. return fmt.Errorf("marshalling message: %w", err)
  667. }
  668. if c.shouldCompressMessage(msg) {
  669. ok, err := c.writeCompressedMessage(msg, buf[overhead:])
  670. if ok {
  671. return err
  672. }
  673. }
  674. metricDeviceSentUncompressedBytes.WithLabelValues(c.idString).Add(float64(totSize))
  675. // Header length
  676. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  677. // Header
  678. if _, err := protoutil.MarshalTo(buf[2:], hdr); err != nil {
  679. return fmt.Errorf("marshalling header: %w", err)
  680. }
  681. // Message length
  682. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
  683. n, err := c.cw.Write(buf)
  684. l.Debugf("wrote %d bytes on the wire (2 bytes length, %d bytes header, 4 bytes message length, %d bytes message), err=%v", n, hdrSize, size, err)
  685. if err != nil {
  686. return fmt.Errorf("writing message: %w", err)
  687. }
  688. return nil
  689. }
  690. // Write msg out compressed, given its uncompressed marshaled payload.
  691. //
  692. // The first return value indicates whether compression succeeded.
  693. // If not, the caller should retry without compression.
  694. func (c *rawConnection) writeCompressedMessage(msg proto.Message, marshaled []byte) (ok bool, err error) {
  695. hdr := &bep.Header{
  696. Type: typeOf(msg),
  697. Compression: bep.MessageCompression_MESSAGE_COMPRESSION_LZ4,
  698. }
  699. hdrSize := proto.Size(hdr)
  700. if hdrSize > 1<<16-1 {
  701. panic("impossibly large header")
  702. }
  703. cOverhead := 2 + hdrSize + 4
  704. metricDeviceSentUncompressedBytes.WithLabelValues(c.idString).Add(float64(cOverhead + len(marshaled)))
  705. // The compressed size may be at most n-n/32 = .96875*n bytes,
  706. // I.e., if we can't save at least 3.125% bandwidth, we forgo compression.
  707. // This number is arbitrary but cheap to compute.
  708. maxCompressed := cOverhead + len(marshaled) - len(marshaled)/32
  709. buf := BufferPool.Get(maxCompressed)
  710. defer BufferPool.Put(buf)
  711. compressedSize, err := lz4Compress(marshaled, buf[cOverhead:])
  712. totSize := compressedSize + cOverhead
  713. if err != nil {
  714. return false, nil
  715. }
  716. // Header length
  717. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  718. // Header
  719. if _, err := protoutil.MarshalTo(buf[2:], hdr); err != nil {
  720. return true, fmt.Errorf("marshalling header: %w", err)
  721. }
  722. // Message length
  723. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(compressedSize))
  724. n, err := c.cw.Write(buf[:totSize])
  725. l.Debugf("wrote %d bytes on the wire (2 bytes length, %d bytes header, 4 bytes message length, %d bytes message (%d uncompressed)), err=%v", n, hdrSize, compressedSize, len(marshaled), err)
  726. if err != nil {
  727. return true, fmt.Errorf("writing message: %w", err)
  728. }
  729. return true, nil
  730. }
  731. func typeOf(msg proto.Message) bep.MessageType {
  732. switch msg.(type) {
  733. case *bep.ClusterConfig:
  734. return bep.MessageType_MESSAGE_TYPE_CLUSTER_CONFIG
  735. case *bep.Index:
  736. return bep.MessageType_MESSAGE_TYPE_INDEX
  737. case *bep.IndexUpdate:
  738. return bep.MessageType_MESSAGE_TYPE_INDEX_UPDATE
  739. case *bep.Request:
  740. return bep.MessageType_MESSAGE_TYPE_REQUEST
  741. case *bep.Response:
  742. return bep.MessageType_MESSAGE_TYPE_RESPONSE
  743. case *bep.DownloadProgress:
  744. return bep.MessageType_MESSAGE_TYPE_DOWNLOAD_PROGRESS
  745. case *bep.Ping:
  746. return bep.MessageType_MESSAGE_TYPE_PING
  747. case *bep.Close:
  748. return bep.MessageType_MESSAGE_TYPE_CLOSE
  749. default:
  750. panic("bug: unknown message type")
  751. }
  752. }
  753. func newMessage(t bep.MessageType) (proto.Message, error) {
  754. switch t {
  755. case bep.MessageType_MESSAGE_TYPE_CLUSTER_CONFIG:
  756. return new(bep.ClusterConfig), nil
  757. case bep.MessageType_MESSAGE_TYPE_INDEX:
  758. return new(bep.Index), nil
  759. case bep.MessageType_MESSAGE_TYPE_INDEX_UPDATE:
  760. return new(bep.IndexUpdate), nil
  761. case bep.MessageType_MESSAGE_TYPE_REQUEST:
  762. return new(bep.Request), nil
  763. case bep.MessageType_MESSAGE_TYPE_RESPONSE:
  764. return new(bep.Response), nil
  765. case bep.MessageType_MESSAGE_TYPE_DOWNLOAD_PROGRESS:
  766. return new(bep.DownloadProgress), nil
  767. case bep.MessageType_MESSAGE_TYPE_PING:
  768. return new(bep.Ping), nil
  769. case bep.MessageType_MESSAGE_TYPE_CLOSE:
  770. return new(bep.Close), nil
  771. default:
  772. return nil, errUnknownMessage
  773. }
  774. }
  775. func (c *rawConnection) shouldCompressMessage(msg proto.Message) bool {
  776. switch c.compression {
  777. case CompressionNever:
  778. return false
  779. case CompressionAlways:
  780. // Use compression for large enough messages
  781. return proto.Size(msg) >= compressionThreshold
  782. case CompressionMetadata:
  783. _, isResponse := msg.(*bep.Response)
  784. // Compress if it's large enough and not a response message
  785. return !isResponse && proto.Size(msg) >= compressionThreshold
  786. default:
  787. panic("unknown compression setting")
  788. }
  789. }
  790. // Close is called when the connection is regularely closed and thus the Close
  791. // BEP message is sent before terminating the actual connection. The error
  792. // argument specifies the reason for closing the connection.
  793. func (c *rawConnection) Close(err error) {
  794. c.sendCloseOnce.Do(func() {
  795. done := make(chan struct{})
  796. timeout := time.NewTimer(CloseTimeout)
  797. select {
  798. case c.closeBox <- asyncMessage{&bep.Close{Reason: err.Error()}, done}:
  799. select {
  800. case <-done:
  801. case <-timeout.C:
  802. case <-c.closed:
  803. }
  804. case <-timeout.C:
  805. case <-c.closed:
  806. }
  807. })
  808. // Close might be called from a method that is called from within
  809. // dispatcherLoop, resulting in a deadlock.
  810. // The sending above must happen before spawning the routine, to prevent
  811. // the underlying connection from terminating before sending the close msg.
  812. go c.internalClose(err)
  813. }
  814. // internalClose is called if there is an unexpected error during normal operation.
  815. func (c *rawConnection) internalClose(err error) {
  816. c.startStopMut.Lock()
  817. defer c.startStopMut.Unlock()
  818. c.closeOnce.Do(func() {
  819. l.Debugf("close connection to %s at %s due to %v", c.deviceID.Short(), c.ConnectionInfo, err)
  820. if cerr := c.closer.Close(); cerr != nil {
  821. l.Debugf("failed to close underlying conn %s at %s %v:", c.deviceID.Short(), c.ConnectionInfo, cerr)
  822. }
  823. close(c.closed)
  824. c.awaitingMut.Lock()
  825. for i, ch := range c.awaiting {
  826. if ch != nil {
  827. close(ch)
  828. delete(c.awaiting, i)
  829. }
  830. }
  831. c.awaitingMut.Unlock()
  832. if !c.startTime.IsZero() {
  833. // Wait for the dispatcher loop to exit, if it was started to
  834. // begin with.
  835. <-c.dispatcherLoopStopped
  836. }
  837. c.model.Closed(err)
  838. })
  839. }
  840. // The pingSender makes sure that we've sent a message within the last
  841. // PingSendInterval. If we already have something sent in the last
  842. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  843. // results in an effecting ping interval of somewhere between
  844. // PingSendInterval/2 and PingSendInterval.
  845. func (c *rawConnection) pingSender() {
  846. ticker := time.NewTicker(PingSendInterval / 2)
  847. defer ticker.Stop()
  848. for {
  849. select {
  850. case <-ticker.C:
  851. d := time.Since(c.cw.Last())
  852. if d < PingSendInterval/2 {
  853. l.Debugln(c.deviceID, "ping skipped after wr", d)
  854. continue
  855. }
  856. l.Debugln(c.deviceID, "ping -> after", d)
  857. c.ping()
  858. case <-c.closed:
  859. return
  860. }
  861. }
  862. }
  863. // The pingReceiver checks that we've received a message (any message will do,
  864. // but we expect pings in the absence of other messages) within the last
  865. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  866. func (c *rawConnection) pingReceiver() {
  867. ticker := time.NewTicker(ReceiveTimeout / 2)
  868. defer ticker.Stop()
  869. for {
  870. select {
  871. case <-ticker.C:
  872. d := time.Since(c.cr.Last())
  873. if d > ReceiveTimeout {
  874. l.Debugln(c.deviceID, "ping timeout", d)
  875. c.internalClose(ErrTimeout)
  876. }
  877. l.Debugln(c.deviceID, "last read within", d)
  878. case <-c.closed:
  879. return
  880. }
  881. }
  882. }
  883. type Statistics struct {
  884. At time.Time `json:"at"`
  885. InBytesTotal int64 `json:"inBytesTotal"`
  886. OutBytesTotal int64 `json:"outBytesTotal"`
  887. StartedAt time.Time `json:"startedAt"`
  888. }
  889. func (c *rawConnection) Statistics() Statistics {
  890. return Statistics{
  891. At: time.Now().Truncate(time.Second),
  892. InBytesTotal: c.cr.Tot(),
  893. OutBytesTotal: c.cw.Tot(),
  894. StartedAt: c.startTime,
  895. }
  896. }
  897. func lz4Compress(src, buf []byte) (int, error) {
  898. n, err := lz4.CompressBlock(src, buf[4:], nil)
  899. if err != nil {
  900. return -1, err
  901. } else if n == 0 {
  902. return -1, errNotCompressible
  903. }
  904. // The compressed block is prefixed by the size of the uncompressed data.
  905. binary.BigEndian.PutUint32(buf, uint32(len(src)))
  906. return n + 4, nil
  907. }
  908. func lz4Decompress(src []byte) ([]byte, error) {
  909. size := binary.BigEndian.Uint32(src)
  910. buf := BufferPool.Get(int(size))
  911. n, err := lz4.UncompressBlock(src[4:], buf)
  912. if err != nil {
  913. BufferPool.Put(buf)
  914. return nil, err
  915. }
  916. return buf[:n], nil
  917. }
  918. func newProtocolError(err error, msgContext string) error {
  919. return fmt.Errorf("protocol error on %v: %w", msgContext, err)
  920. }
  921. func newHandleError(err error, msgContext string) error {
  922. return fmt.Errorf("handling %v: %w", msgContext, err)
  923. }
  924. func messageContext(msg proto.Message) (string, error) {
  925. switch msg := msg.(type) {
  926. case *bep.ClusterConfig:
  927. return "cluster-config", nil
  928. case *bep.Index:
  929. return fmt.Sprintf("index for %v", msg.Folder), nil
  930. case *bep.IndexUpdate:
  931. return fmt.Sprintf("index-update for %v", msg.Folder), nil
  932. case *bep.Request:
  933. return fmt.Sprintf(`request for "%v" in %v`, msg.Name, msg.Folder), nil
  934. case *bep.Response:
  935. return "response", nil
  936. case *bep.DownloadProgress:
  937. return fmt.Sprintf("download-progress for %v", msg.Folder), nil
  938. case *bep.Ping:
  939. return "ping", nil
  940. case *bep.Close:
  941. return "close", nil
  942. default:
  943. return "", errors.New("unknown or empty message")
  944. }
  945. }
  946. // connectionWrappingModel takes the Model interface from the model package,
  947. // which expects the Connection as the first parameter in all methods, and
  948. // wraps it to conform to the rawModel interface.
  949. type connectionWrappingModel struct {
  950. conn Connection
  951. model Model
  952. }
  953. func (c *connectionWrappingModel) Index(m *Index) error {
  954. return c.model.Index(c.conn, m)
  955. }
  956. func (c *connectionWrappingModel) IndexUpdate(idxUp *IndexUpdate) error {
  957. return c.model.IndexUpdate(c.conn, idxUp)
  958. }
  959. func (c *connectionWrappingModel) Request(req *Request) (RequestResponse, error) {
  960. return c.model.Request(c.conn, req)
  961. }
  962. func (c *connectionWrappingModel) ClusterConfig(config *ClusterConfig) error {
  963. return c.model.ClusterConfig(c.conn, config)
  964. }
  965. func (c *connectionWrappingModel) Closed(err error) {
  966. c.model.Closed(c.conn, err)
  967. }
  968. func (c *connectionWrappingModel) DownloadProgress(p *DownloadProgress) error {
  969. return c.model.DownloadProgress(c.conn, p)
  970. }