protocol.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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 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) {
  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. if _, err := io.ReadFull(c.cr, buf); err != nil {
  450. BufferPool.Put(buf)
  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. BufferPool.Put(buf)
  460. if err != nil {
  461. return nil, fmt.Errorf("decompressing message: %w", err)
  462. }
  463. buf = decomp
  464. default:
  465. return nil, fmt.Errorf("unknown message compression %d", hdr.Compression)
  466. }
  467. // ... and is then unmarshalled
  468. metricDeviceRecvDecompressedBytes.WithLabelValues(c.idString).Add(float64(4 + len(buf)))
  469. msg, err := newMessage(hdr.Type)
  470. if err != nil {
  471. BufferPool.Put(buf)
  472. return nil, err
  473. }
  474. if err := proto.Unmarshal(buf, msg); err != nil {
  475. BufferPool.Put(buf)
  476. return nil, fmt.Errorf("unmarshalling message: %w", err)
  477. }
  478. BufferPool.Put(buf)
  479. return msg, nil
  480. }
  481. func (c *rawConnection) readHeader(fourByteBuf []byte) (*bep.Header, error) {
  482. // First comes a 2 byte header length
  483. if _, err := io.ReadFull(c.cr, fourByteBuf[:2]); err != nil {
  484. return nil, fmt.Errorf("reading length: %w", err)
  485. }
  486. hdrLen := int16(binary.BigEndian.Uint16(fourByteBuf))
  487. if hdrLen < 0 {
  488. return nil, fmt.Errorf("negative header length %d", hdrLen)
  489. }
  490. // Then comes the header
  491. buf := BufferPool.Get(int(hdrLen))
  492. if _, err := io.ReadFull(c.cr, buf); err != nil {
  493. BufferPool.Put(buf)
  494. return nil, fmt.Errorf("reading header: %w", err)
  495. }
  496. var hdr bep.Header
  497. err := proto.Unmarshal(buf, &hdr)
  498. BufferPool.Put(buf)
  499. if err != nil {
  500. return nil, fmt.Errorf("unmarshalling header: %w %x", err, buf)
  501. }
  502. metricDeviceRecvDecompressedBytes.WithLabelValues(c.idString).Add(float64(2 + len(buf)))
  503. return &hdr, nil
  504. }
  505. func (c *rawConnection) handleIndex(im *Index) error {
  506. l.Debugf("Index(%v, %v, %d file)", c.deviceID, im.Folder, len(im.Files))
  507. return c.model.Index(im)
  508. }
  509. func (c *rawConnection) handleIndexUpdate(im *IndexUpdate) error {
  510. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.deviceID, im.Folder, len(im.Files))
  511. return c.model.IndexUpdate(im)
  512. }
  513. // checkIndexConsistency verifies a number of invariants on FileInfos received in
  514. // index messages.
  515. func checkIndexConsistency(fs []FileInfo) error {
  516. for _, f := range fs {
  517. if err := checkFileInfoConsistency(f); err != nil {
  518. return fmt.Errorf("%q: %w", f.Name, err)
  519. }
  520. }
  521. return nil
  522. }
  523. // checkFileInfoConsistency verifies a number of invariants on the given FileInfo
  524. func checkFileInfoConsistency(f FileInfo) error {
  525. if err := checkFilename(f.Name); err != nil {
  526. return err
  527. }
  528. switch {
  529. case f.Deleted && len(f.Blocks) != 0:
  530. // Deleted files should have no blocks
  531. return errDeletedHasBlocks
  532. case f.Type == FileInfoTypeDirectory && len(f.Blocks) != 0:
  533. // Directories should have no blocks
  534. return errDirectoryHasBlocks
  535. case !f.Deleted && !f.IsInvalid() && f.Type == FileInfoTypeFile && len(f.Blocks) == 0:
  536. // Non-deleted, non-invalid files should have at least one block
  537. return errFileHasNoBlocks
  538. }
  539. return nil
  540. }
  541. // checkFilename verifies that the given filename is valid according to the
  542. // spec on what's allowed over the wire. A filename failing this test is
  543. // grounds for disconnecting the device.
  544. func checkFilename(name string) error {
  545. cleanedName := path.Clean(name)
  546. if cleanedName != name {
  547. // The filename on the wire should be in canonical format. If
  548. // Clean() managed to clean it up, there was something wrong with
  549. // it.
  550. return errUncleanFilename
  551. }
  552. switch name {
  553. case "", ".", "..":
  554. // These names are always invalid.
  555. return errInvalidFilename
  556. }
  557. if strings.HasPrefix(name, "/") {
  558. // Names are folder relative, not absolute.
  559. return errInvalidFilename
  560. }
  561. if strings.HasPrefix(name, "../") {
  562. // Starting with a dotdot is not allowed. Any other dotdots would
  563. // have been handled by the Clean() call at the top.
  564. return errInvalidFilename
  565. }
  566. return nil
  567. }
  568. func (c *rawConnection) handleRequest(req *Request) {
  569. res, err := c.model.Request(req)
  570. if err != nil {
  571. resp := &Response{
  572. ID: req.ID,
  573. Code: errorToCode(err),
  574. }
  575. c.send(context.Background(), resp.toWire(), nil)
  576. return
  577. }
  578. done := make(chan struct{})
  579. resp := &Response{
  580. ID: req.ID,
  581. Data: res.Data(),
  582. Code: errorToCode(nil),
  583. }
  584. c.send(context.Background(), resp.toWire(), done)
  585. <-done
  586. res.Close()
  587. }
  588. func (c *rawConnection) handleResponse(resp *Response) {
  589. c.awaitingMut.Lock()
  590. if rc := c.awaiting[resp.ID]; rc != nil {
  591. delete(c.awaiting, resp.ID)
  592. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  593. close(rc)
  594. }
  595. c.awaitingMut.Unlock()
  596. }
  597. func (c *rawConnection) send(ctx context.Context, msg proto.Message, done chan struct{}) bool {
  598. select {
  599. case c.outbox <- asyncMessage{msg, done}:
  600. return true
  601. case <-c.closed:
  602. case <-ctx.Done():
  603. }
  604. if done != nil {
  605. close(done)
  606. }
  607. return false
  608. }
  609. func (c *rawConnection) writerLoop() {
  610. select {
  611. case cc := <-c.clusterConfigBox:
  612. err := c.writeMessage(cc.toWire())
  613. if err != nil {
  614. c.internalClose(err)
  615. return
  616. }
  617. case hm := <-c.closeBox:
  618. _ = c.writeMessage(hm.msg)
  619. close(hm.done)
  620. return
  621. case <-c.closed:
  622. return
  623. }
  624. for {
  625. // When the connection is closing or closed, that should happen
  626. // immediately, not compete with the (potentially very busy) outbox.
  627. select {
  628. case hm := <-c.closeBox:
  629. _ = c.writeMessage(hm.msg)
  630. close(hm.done)
  631. return
  632. case <-c.closed:
  633. return
  634. default:
  635. }
  636. select {
  637. case cc := <-c.clusterConfigBox:
  638. err := c.writeMessage(cc.toWire())
  639. if err != nil {
  640. c.internalClose(err)
  641. return
  642. }
  643. case hm := <-c.outbox:
  644. err := c.writeMessage(hm.msg)
  645. if hm.done != nil {
  646. close(hm.done)
  647. }
  648. if err != nil {
  649. c.internalClose(err)
  650. return
  651. }
  652. case hm := <-c.closeBox:
  653. _ = c.writeMessage(hm.msg)
  654. close(hm.done)
  655. return
  656. case <-c.closed:
  657. return
  658. }
  659. }
  660. }
  661. func (c *rawConnection) writeMessage(msg proto.Message) error {
  662. msgContext, _ := messageContext(msg)
  663. l.Debugf("Writing %v", msgContext)
  664. defer func() {
  665. metricDeviceSentMessages.WithLabelValues(c.idString).Inc()
  666. }()
  667. size := proto.Size(msg)
  668. hdr := &bep.Header{
  669. Type: typeOf(msg),
  670. }
  671. hdrSize := proto.Size(hdr)
  672. if hdrSize > 1<<16-1 {
  673. panic("impossibly large header")
  674. }
  675. overhead := 2 + hdrSize + 4
  676. totSize := overhead + size
  677. buf := BufferPool.Get(totSize)
  678. defer BufferPool.Put(buf)
  679. // Message
  680. if _, err := protoutil.MarshalTo(buf[overhead:], msg); err != nil {
  681. return fmt.Errorf("marshalling message: %w", err)
  682. }
  683. if c.shouldCompressMessage(msg) {
  684. ok, err := c.writeCompressedMessage(msg, buf[overhead:])
  685. if ok {
  686. return err
  687. }
  688. }
  689. metricDeviceSentUncompressedBytes.WithLabelValues(c.idString).Add(float64(totSize))
  690. // Header length
  691. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  692. // Header
  693. if _, err := protoutil.MarshalTo(buf[2:], hdr); err != nil {
  694. return fmt.Errorf("marshalling header: %w", err)
  695. }
  696. // Message length
  697. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
  698. n, err := c.cw.Write(buf)
  699. 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)
  700. if err != nil {
  701. return fmt.Errorf("writing message: %w", err)
  702. }
  703. return nil
  704. }
  705. // Write msg out compressed, given its uncompressed marshaled payload.
  706. //
  707. // The first return value indicates whether compression succeeded.
  708. // If not, the caller should retry without compression.
  709. func (c *rawConnection) writeCompressedMessage(msg proto.Message, marshaled []byte) (ok bool, err error) {
  710. hdr := &bep.Header{
  711. Type: typeOf(msg),
  712. Compression: bep.MessageCompression_MESSAGE_COMPRESSION_LZ4,
  713. }
  714. hdrSize := proto.Size(hdr)
  715. if hdrSize > 1<<16-1 {
  716. panic("impossibly large header")
  717. }
  718. cOverhead := 2 + hdrSize + 4
  719. metricDeviceSentUncompressedBytes.WithLabelValues(c.idString).Add(float64(cOverhead + len(marshaled)))
  720. // The compressed size may be at most n-n/32 = .96875*n bytes,
  721. // I.e., if we can't save at least 3.125% bandwidth, we forgo compression.
  722. // This number is arbitrary but cheap to compute.
  723. maxCompressed := cOverhead + len(marshaled) - len(marshaled)/32
  724. buf := BufferPool.Get(maxCompressed)
  725. defer BufferPool.Put(buf)
  726. compressedSize, err := lz4Compress(marshaled, buf[cOverhead:])
  727. totSize := compressedSize + cOverhead
  728. if err != nil {
  729. return false, nil
  730. }
  731. // Header length
  732. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  733. // Header
  734. if _, err := protoutil.MarshalTo(buf[2:], hdr); err != nil {
  735. return true, fmt.Errorf("marshalling header: %w", err)
  736. }
  737. // Message length
  738. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(compressedSize))
  739. n, err := c.cw.Write(buf[:totSize])
  740. 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)
  741. if err != nil {
  742. return true, fmt.Errorf("writing message: %w", err)
  743. }
  744. return true, nil
  745. }
  746. func typeOf(msg proto.Message) bep.MessageType {
  747. switch msg.(type) {
  748. case *bep.ClusterConfig:
  749. return bep.MessageType_MESSAGE_TYPE_CLUSTER_CONFIG
  750. case *bep.Index:
  751. return bep.MessageType_MESSAGE_TYPE_INDEX
  752. case *bep.IndexUpdate:
  753. return bep.MessageType_MESSAGE_TYPE_INDEX_UPDATE
  754. case *bep.Request:
  755. return bep.MessageType_MESSAGE_TYPE_REQUEST
  756. case *bep.Response:
  757. return bep.MessageType_MESSAGE_TYPE_RESPONSE
  758. case *bep.DownloadProgress:
  759. return bep.MessageType_MESSAGE_TYPE_DOWNLOAD_PROGRESS
  760. case *bep.Ping:
  761. return bep.MessageType_MESSAGE_TYPE_PING
  762. case *bep.Close:
  763. return bep.MessageType_MESSAGE_TYPE_CLOSE
  764. default:
  765. panic("bug: unknown message type")
  766. }
  767. }
  768. func newMessage(t bep.MessageType) (proto.Message, error) {
  769. switch t {
  770. case bep.MessageType_MESSAGE_TYPE_CLUSTER_CONFIG:
  771. return new(bep.ClusterConfig), nil
  772. case bep.MessageType_MESSAGE_TYPE_INDEX:
  773. return new(bep.Index), nil
  774. case bep.MessageType_MESSAGE_TYPE_INDEX_UPDATE:
  775. return new(bep.IndexUpdate), nil
  776. case bep.MessageType_MESSAGE_TYPE_REQUEST:
  777. return new(bep.Request), nil
  778. case bep.MessageType_MESSAGE_TYPE_RESPONSE:
  779. return new(bep.Response), nil
  780. case bep.MessageType_MESSAGE_TYPE_DOWNLOAD_PROGRESS:
  781. return new(bep.DownloadProgress), nil
  782. case bep.MessageType_MESSAGE_TYPE_PING:
  783. return new(bep.Ping), nil
  784. case bep.MessageType_MESSAGE_TYPE_CLOSE:
  785. return new(bep.Close), nil
  786. default:
  787. return nil, errUnknownMessage
  788. }
  789. }
  790. func (c *rawConnection) shouldCompressMessage(msg proto.Message) bool {
  791. switch c.compression {
  792. case CompressionNever:
  793. return false
  794. case CompressionAlways:
  795. // Use compression for large enough messages
  796. return proto.Size(msg) >= compressionThreshold
  797. case CompressionMetadata:
  798. _, isResponse := msg.(*bep.Response)
  799. // Compress if it's large enough and not a response message
  800. return !isResponse && proto.Size(msg) >= compressionThreshold
  801. default:
  802. panic("unknown compression setting")
  803. }
  804. }
  805. // Close is called when the connection is regularely closed and thus the Close
  806. // BEP message is sent before terminating the actual connection. The error
  807. // argument specifies the reason for closing the connection.
  808. func (c *rawConnection) Close(err error) {
  809. c.sendCloseOnce.Do(func() {
  810. done := make(chan struct{})
  811. timeout := time.NewTimer(CloseTimeout)
  812. select {
  813. case c.closeBox <- asyncMessage{&bep.Close{Reason: err.Error()}, done}:
  814. select {
  815. case <-done:
  816. case <-timeout.C:
  817. case <-c.closed:
  818. }
  819. case <-timeout.C:
  820. case <-c.closed:
  821. }
  822. })
  823. // Close might be called from a method that is called from within
  824. // dispatcherLoop, resulting in a deadlock.
  825. // The sending above must happen before spawning the routine, to prevent
  826. // the underlying connection from terminating before sending the close msg.
  827. go c.internalClose(err)
  828. }
  829. // internalClose is called if there is an unexpected error during normal operation.
  830. func (c *rawConnection) internalClose(err error) {
  831. c.closeOnce.Do(func() {
  832. c.startStopMut.Lock()
  833. l.Debugf("close connection to %s at %s due to %v", c.deviceID.Short(), c.ConnectionInfo, err)
  834. if cerr := c.closer.Close(); cerr != nil {
  835. l.Debugf("failed to close underlying conn %s at %s %v:", c.deviceID.Short(), c.ConnectionInfo, cerr)
  836. }
  837. close(c.closed)
  838. c.awaitingMut.Lock()
  839. for i, ch := range c.awaiting {
  840. if ch != nil {
  841. close(ch)
  842. delete(c.awaiting, i)
  843. }
  844. }
  845. c.awaitingMut.Unlock()
  846. if !c.startTime.IsZero() {
  847. // Wait for the dispatcher loop to exit, if it was started to
  848. // begin with.
  849. <-c.dispatcherLoopStopped
  850. }
  851. c.startStopMut.Unlock()
  852. // We don't want to call into the model while holding the
  853. // startStopMut.
  854. c.model.Closed(err)
  855. })
  856. }
  857. // The pingSender makes sure that we've sent a message within the last
  858. // PingSendInterval. If we already have something sent in the last
  859. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  860. // results in an effecting ping interval of somewhere between
  861. // PingSendInterval/2 and PingSendInterval.
  862. func (c *rawConnection) pingSender() {
  863. ticker := time.NewTicker(PingSendInterval / 2)
  864. defer ticker.Stop()
  865. for {
  866. select {
  867. case <-ticker.C:
  868. d := time.Since(c.cw.Last())
  869. if d < PingSendInterval/2 {
  870. l.Debugln(c.deviceID, "ping skipped after wr", d)
  871. continue
  872. }
  873. l.Debugln(c.deviceID, "ping -> after", d)
  874. c.ping()
  875. case <-c.closed:
  876. return
  877. }
  878. }
  879. }
  880. // The pingReceiver checks that we've received a message (any message will do,
  881. // but we expect pings in the absence of other messages) within the last
  882. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  883. func (c *rawConnection) pingReceiver() {
  884. ticker := time.NewTicker(ReceiveTimeout / 2)
  885. defer ticker.Stop()
  886. for {
  887. select {
  888. case <-ticker.C:
  889. d := time.Since(c.cr.Last())
  890. if d > ReceiveTimeout {
  891. l.Debugln(c.deviceID, "ping timeout", d)
  892. c.internalClose(ErrTimeout)
  893. }
  894. l.Debugln(c.deviceID, "last read within", d)
  895. case <-c.closed:
  896. return
  897. }
  898. }
  899. }
  900. type Statistics struct {
  901. At time.Time `json:"at"`
  902. InBytesTotal int64 `json:"inBytesTotal"`
  903. OutBytesTotal int64 `json:"outBytesTotal"`
  904. StartedAt time.Time `json:"startedAt"`
  905. }
  906. func (c *rawConnection) Statistics() Statistics {
  907. return Statistics{
  908. At: time.Now().Truncate(time.Second),
  909. InBytesTotal: c.cr.Tot(),
  910. OutBytesTotal: c.cw.Tot(),
  911. StartedAt: c.startTime,
  912. }
  913. }
  914. func lz4Compress(src, buf []byte) (int, error) {
  915. n, err := lz4.CompressBlock(src, buf[4:], nil)
  916. if err != nil {
  917. return -1, err
  918. } else if n == 0 {
  919. return -1, errNotCompressible
  920. }
  921. // The compressed block is prefixed by the size of the uncompressed data.
  922. binary.BigEndian.PutUint32(buf, uint32(len(src)))
  923. return n + 4, nil
  924. }
  925. func lz4Decompress(src []byte) ([]byte, error) {
  926. size := binary.BigEndian.Uint32(src)
  927. buf := BufferPool.Get(int(size))
  928. n, err := lz4.UncompressBlock(src[4:], buf)
  929. if err != nil {
  930. BufferPool.Put(buf)
  931. return nil, err
  932. }
  933. return buf[:n], nil
  934. }
  935. func newProtocolError(err error, msgContext string) error {
  936. return fmt.Errorf("protocol error on %v: %w", msgContext, err)
  937. }
  938. func newHandleError(err error, msgContext string) error {
  939. return fmt.Errorf("handling %v: %w", msgContext, err)
  940. }
  941. func messageContext(msg proto.Message) (string, error) {
  942. switch msg := msg.(type) {
  943. case *bep.ClusterConfig:
  944. return "cluster-config", nil
  945. case *bep.Index:
  946. return fmt.Sprintf("index for %v", msg.Folder), nil
  947. case *bep.IndexUpdate:
  948. return fmt.Sprintf("index-update for %v", msg.Folder), nil
  949. case *bep.Request:
  950. return fmt.Sprintf(`request for "%v" in %v`, msg.Name, msg.Folder), nil
  951. case *bep.Response:
  952. return "response", nil
  953. case *bep.DownloadProgress:
  954. return fmt.Sprintf("download-progress for %v", msg.Folder), nil
  955. case *bep.Ping:
  956. return "ping", nil
  957. case *bep.Close:
  958. return "close", nil
  959. default:
  960. return "", errors.New("unknown or empty message")
  961. }
  962. }
  963. // connectionWrappingModel takes the Model interface from the model package,
  964. // which expects the Connection as the first parameter in all methods, and
  965. // wraps it to conform to the rawModel interface.
  966. type connectionWrappingModel struct {
  967. conn Connection
  968. model Model
  969. }
  970. func (c *connectionWrappingModel) Index(m *Index) error {
  971. return c.model.Index(c.conn, m)
  972. }
  973. func (c *connectionWrappingModel) IndexUpdate(idxUp *IndexUpdate) error {
  974. return c.model.IndexUpdate(c.conn, idxUp)
  975. }
  976. func (c *connectionWrappingModel) Request(req *Request) (RequestResponse, error) {
  977. return c.model.Request(c.conn, req)
  978. }
  979. func (c *connectionWrappingModel) ClusterConfig(config *ClusterConfig) error {
  980. return c.model.ClusterConfig(c.conn, config)
  981. }
  982. func (c *connectionWrappingModel) Closed(err error) {
  983. c.model.Closed(c.conn, err)
  984. }
  985. func (c *connectionWrappingModel) DownloadProgress(p *DownloadProgress) error {
  986. return c.model.DownloadProgress(c.conn, p)
  987. }