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