protocol.go 31 KB

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