protocol.go 32 KB

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