protocol.go 31 KB

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