protocol.go 31 KB

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