protocol.go 30 KB

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