protocol.go 31 KB

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