protocol.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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. The connection will read and marshal the
  131. // parameters asynchronously, so they should not be modified after
  132. // calling Index().
  133. Index(ctx context.Context, folder string, files []FileInfo) error
  134. // Send an index update message. The connection will read and marshal
  135. // the parameters asynchronously, so they should not be modified after
  136. // calling IndexUpdate().
  137. IndexUpdate(ctx context.Context, folder string, files []FileInfo) error
  138. // Send a request message. The connection will read and marshal the
  139. // parameters asynchronously, so they should not be modified after
  140. // calling Request().
  141. Request(ctx context.Context, folder string, name string, blockNo int, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error)
  142. // Send a cluster configuration message. The connection will read and
  143. // marshal the message asynchronously, so it should not be modified
  144. // after calling ClusterConfig().
  145. ClusterConfig(config ClusterConfig)
  146. // Send a download progress message. The connection will read and
  147. // marshal the parameters asynchronously, so they should not be modified
  148. // after calling DownloadProgress().
  149. DownloadProgress(ctx context.Context, folder string, updates []FileDownloadProgressUpdate)
  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, folder string, idx []FileInfo) error {
  299. select {
  300. case <-c.closed:
  301. return ErrClosed
  302. default:
  303. }
  304. c.idxMut.Lock()
  305. c.send(ctx, &Index{
  306. Folder: folder,
  307. Files: idx,
  308. }, nil)
  309. c.idxMut.Unlock()
  310. return nil
  311. }
  312. // IndexUpdate writes the list of file information to the connected peer device as an update
  313. func (c *rawConnection) IndexUpdate(ctx context.Context, folder string, idx []FileInfo) error {
  314. select {
  315. case <-c.closed:
  316. return ErrClosed
  317. default:
  318. }
  319. c.idxMut.Lock()
  320. c.send(ctx, &IndexUpdate{
  321. Folder: folder,
  322. Files: idx,
  323. }, nil)
  324. c.idxMut.Unlock()
  325. return nil
  326. }
  327. // Request returns the bytes for the specified block after fetching them from the connected peer.
  328. func (c *rawConnection) Request(ctx context.Context, folder string, name string, blockNo int, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  329. rc := make(chan asyncResult, 1)
  330. c.awaitingMut.Lock()
  331. id := c.nextID
  332. c.nextID++
  333. if _, ok := c.awaiting[id]; ok {
  334. c.awaitingMut.Unlock()
  335. panic("id taken")
  336. }
  337. c.awaiting[id] = rc
  338. c.awaitingMut.Unlock()
  339. ok := c.send(ctx, &Request{
  340. ID: id,
  341. Folder: folder,
  342. Name: name,
  343. Offset: offset,
  344. Size: size,
  345. BlockNo: blockNo,
  346. Hash: hash,
  347. WeakHash: weakHash,
  348. FromTemporary: fromTemporary,
  349. }, nil)
  350. if !ok {
  351. return nil, ErrClosed
  352. }
  353. select {
  354. case res, ok := <-rc:
  355. if !ok {
  356. return nil, ErrClosed
  357. }
  358. return res.val, res.err
  359. case <-ctx.Done():
  360. return nil, ctx.Err()
  361. }
  362. }
  363. // ClusterConfig sends the cluster configuration message to the peer.
  364. func (c *rawConnection) ClusterConfig(config ClusterConfig) {
  365. select {
  366. case c.clusterConfigBox <- &config:
  367. case <-c.closed:
  368. }
  369. }
  370. func (c *rawConnection) Closed() <-chan struct{} {
  371. return c.closed
  372. }
  373. // DownloadProgress sends the progress updates for the files that are currently being downloaded.
  374. func (c *rawConnection) DownloadProgress(ctx context.Context, folder string, updates []FileDownloadProgressUpdate) {
  375. c.send(ctx, &DownloadProgress{
  376. Folder: folder,
  377. Updates: updates,
  378. }, nil)
  379. }
  380. func (c *rawConnection) ping() bool {
  381. return c.send(context.Background(), &Ping{}, nil)
  382. }
  383. func (c *rawConnection) readerLoop() {
  384. fourByteBuf := make([]byte, 4)
  385. for {
  386. msg, err := c.readMessage(fourByteBuf)
  387. if err != nil {
  388. if err == errUnknownMessage {
  389. // Unknown message types are skipped, for future extensibility.
  390. continue
  391. }
  392. c.internalClose(err)
  393. return
  394. }
  395. select {
  396. case c.inbox <- msg:
  397. case <-c.closed:
  398. return
  399. }
  400. }
  401. }
  402. func (c *rawConnection) dispatcherLoop() (err error) {
  403. defer close(c.dispatcherLoopStopped)
  404. var msg message
  405. state := stateInitial
  406. for {
  407. select {
  408. case msg = <-c.inbox:
  409. case <-c.closed:
  410. return ErrClosed
  411. }
  412. metricDeviceRecvMessages.WithLabelValues(c.idString).Inc()
  413. msgContext, err := messageContext(msg)
  414. if err != nil {
  415. return fmt.Errorf("protocol error: %w", err)
  416. }
  417. l.Debugf("handle %v message", msgContext)
  418. switch msg := msg.(type) {
  419. case *ClusterConfig:
  420. if state == stateInitial {
  421. state = stateReady
  422. }
  423. case *Close:
  424. return fmt.Errorf("closed by remote: %v", msg.Reason)
  425. default:
  426. if state != stateReady {
  427. return newProtocolError(fmt.Errorf("invalid state %d", state), msgContext)
  428. }
  429. }
  430. switch msg := msg.(type) {
  431. case *Index:
  432. err = checkIndexConsistency(msg.Files)
  433. case *IndexUpdate:
  434. err = checkIndexConsistency(msg.Files)
  435. case *Request:
  436. err = checkFilename(msg.Name)
  437. }
  438. if err != nil {
  439. return newProtocolError(err, msgContext)
  440. }
  441. switch msg := msg.(type) {
  442. case *ClusterConfig:
  443. err = c.model.ClusterConfig(msg)
  444. case *Index:
  445. err = c.handleIndex(msg)
  446. case *IndexUpdate:
  447. err = c.handleIndexUpdate(msg)
  448. case *Request:
  449. go c.handleRequest(msg)
  450. case *Response:
  451. c.handleResponse(msg)
  452. case *DownloadProgress:
  453. err = c.model.DownloadProgress(msg)
  454. }
  455. if err != nil {
  456. return newHandleError(err, msgContext)
  457. }
  458. }
  459. }
  460. func (c *rawConnection) readMessage(fourByteBuf []byte) (message, error) {
  461. hdr, err := c.readHeader(fourByteBuf)
  462. if err != nil {
  463. return nil, err
  464. }
  465. return c.readMessageAfterHeader(hdr, fourByteBuf)
  466. }
  467. func (c *rawConnection) readMessageAfterHeader(hdr Header, fourByteBuf []byte) (message, error) {
  468. // First comes a 4 byte message length
  469. if _, err := io.ReadFull(c.cr, fourByteBuf[:4]); err != nil {
  470. return nil, fmt.Errorf("reading message length: %w", err)
  471. }
  472. msgLen := int32(binary.BigEndian.Uint32(fourByteBuf))
  473. if msgLen < 0 {
  474. return nil, fmt.Errorf("negative message length %d", msgLen)
  475. } else if msgLen > MaxMessageLen {
  476. return nil, fmt.Errorf("message length %d exceeds maximum %d", msgLen, MaxMessageLen)
  477. }
  478. // Then comes the message
  479. buf := BufferPool.Get(int(msgLen))
  480. if _, err := io.ReadFull(c.cr, buf); err != nil {
  481. BufferPool.Put(buf)
  482. return nil, fmt.Errorf("reading message: %w", err)
  483. }
  484. // ... which might be compressed
  485. switch hdr.Compression {
  486. case MessageCompressionNone:
  487. // Nothing
  488. case MessageCompressionLZ4:
  489. decomp, err := lz4Decompress(buf)
  490. BufferPool.Put(buf)
  491. if err != nil {
  492. return nil, fmt.Errorf("decompressing message: %w", err)
  493. }
  494. buf = decomp
  495. default:
  496. return nil, fmt.Errorf("unknown message compression %d", hdr.Compression)
  497. }
  498. // ... and is then unmarshalled
  499. metricDeviceRecvDecompressedBytes.WithLabelValues(c.idString).Add(float64(4 + len(buf)))
  500. msg, err := newMessage(hdr.Type)
  501. if err != nil {
  502. BufferPool.Put(buf)
  503. return nil, err
  504. }
  505. if err := msg.Unmarshal(buf); err != nil {
  506. BufferPool.Put(buf)
  507. return nil, fmt.Errorf("unmarshalling message: %w", err)
  508. }
  509. BufferPool.Put(buf)
  510. return msg, nil
  511. }
  512. func (c *rawConnection) readHeader(fourByteBuf []byte) (Header, error) {
  513. // First comes a 2 byte header length
  514. if _, err := io.ReadFull(c.cr, fourByteBuf[:2]); err != nil {
  515. return Header{}, fmt.Errorf("reading length: %w", err)
  516. }
  517. hdrLen := int16(binary.BigEndian.Uint16(fourByteBuf))
  518. if hdrLen < 0 {
  519. return Header{}, fmt.Errorf("negative header length %d", hdrLen)
  520. }
  521. // Then comes the header
  522. buf := BufferPool.Get(int(hdrLen))
  523. if _, err := io.ReadFull(c.cr, buf); err != nil {
  524. BufferPool.Put(buf)
  525. return Header{}, fmt.Errorf("reading header: %w", err)
  526. }
  527. var hdr Header
  528. err := hdr.Unmarshal(buf)
  529. BufferPool.Put(buf)
  530. if err != nil {
  531. return Header{}, fmt.Errorf("unmarshalling header: %w", err)
  532. }
  533. metricDeviceRecvDecompressedBytes.WithLabelValues(c.idString).Add(float64(2 + len(buf)))
  534. return hdr, nil
  535. }
  536. func (c *rawConnection) handleIndex(im *Index) error {
  537. l.Debugf("Index(%v, %v, %d file)", c.deviceID, im.Folder, len(im.Files))
  538. return c.model.Index(im)
  539. }
  540. func (c *rawConnection) handleIndexUpdate(im *IndexUpdate) error {
  541. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.deviceID, im.Folder, len(im.Files))
  542. return c.model.IndexUpdate(im)
  543. }
  544. // checkIndexConsistency verifies a number of invariants on FileInfos received in
  545. // index messages.
  546. func checkIndexConsistency(fs []FileInfo) error {
  547. for _, f := range fs {
  548. if err := checkFileInfoConsistency(f); err != nil {
  549. return fmt.Errorf("%q: %w", f.Name, err)
  550. }
  551. }
  552. return nil
  553. }
  554. // checkFileInfoConsistency verifies a number of invariants on the given FileInfo
  555. func checkFileInfoConsistency(f FileInfo) error {
  556. if err := checkFilename(f.Name); err != nil {
  557. return err
  558. }
  559. switch {
  560. case f.Deleted && len(f.Blocks) != 0:
  561. // Deleted files should have no blocks
  562. return errDeletedHasBlocks
  563. case f.Type == FileInfoTypeDirectory && len(f.Blocks) != 0:
  564. // Directories should have no blocks
  565. return errDirectoryHasBlocks
  566. case !f.Deleted && !f.IsInvalid() && f.Type == FileInfoTypeFile && len(f.Blocks) == 0:
  567. // Non-deleted, non-invalid files should have at least one block
  568. return errFileHasNoBlocks
  569. }
  570. return nil
  571. }
  572. // checkFilename verifies that the given filename is valid according to the
  573. // spec on what's allowed over the wire. A filename failing this test is
  574. // grounds for disconnecting the device.
  575. func checkFilename(name string) error {
  576. cleanedName := path.Clean(name)
  577. if cleanedName != name {
  578. // The filename on the wire should be in canonical format. If
  579. // Clean() managed to clean it up, there was something wrong with
  580. // it.
  581. return errUncleanFilename
  582. }
  583. switch name {
  584. case "", ".", "..":
  585. // These names are always invalid.
  586. return errInvalidFilename
  587. }
  588. if strings.HasPrefix(name, "/") {
  589. // Names are folder relative, not absolute.
  590. return errInvalidFilename
  591. }
  592. if strings.HasPrefix(name, "../") {
  593. // Starting with a dotdot is not allowed. Any other dotdots would
  594. // have been handled by the Clean() call at the top.
  595. return errInvalidFilename
  596. }
  597. return nil
  598. }
  599. func (c *rawConnection) handleRequest(req *Request) {
  600. res, err := c.model.Request(req)
  601. if err != nil {
  602. c.send(context.Background(), &Response{
  603. ID: req.ID,
  604. Code: errorToCode(err),
  605. }, nil)
  606. return
  607. }
  608. done := make(chan struct{})
  609. c.send(context.Background(), &Response{
  610. ID: req.ID,
  611. Data: res.Data(),
  612. Code: errorToCode(nil),
  613. }, done)
  614. <-done
  615. res.Close()
  616. }
  617. func (c *rawConnection) handleResponse(resp *Response) {
  618. c.awaitingMut.Lock()
  619. if rc := c.awaiting[resp.ID]; rc != nil {
  620. delete(c.awaiting, resp.ID)
  621. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  622. close(rc)
  623. }
  624. c.awaitingMut.Unlock()
  625. }
  626. func (c *rawConnection) send(ctx context.Context, msg message, done chan struct{}) bool {
  627. select {
  628. case c.outbox <- asyncMessage{msg, done}:
  629. return true
  630. case <-c.closed:
  631. case <-ctx.Done():
  632. }
  633. if done != nil {
  634. close(done)
  635. }
  636. return false
  637. }
  638. func (c *rawConnection) writerLoop() {
  639. select {
  640. case cc := <-c.clusterConfigBox:
  641. err := c.writeMessage(cc)
  642. if err != nil {
  643. c.internalClose(err)
  644. return
  645. }
  646. case hm := <-c.closeBox:
  647. _ = c.writeMessage(hm.msg)
  648. close(hm.done)
  649. return
  650. case <-c.closed:
  651. return
  652. }
  653. for {
  654. select {
  655. case cc := <-c.clusterConfigBox:
  656. err := c.writeMessage(cc)
  657. if err != nil {
  658. c.internalClose(err)
  659. return
  660. }
  661. case hm := <-c.outbox:
  662. err := c.writeMessage(hm.msg)
  663. if hm.done != nil {
  664. close(hm.done)
  665. }
  666. if err != nil {
  667. c.internalClose(err)
  668. return
  669. }
  670. case hm := <-c.closeBox:
  671. _ = c.writeMessage(hm.msg)
  672. close(hm.done)
  673. return
  674. case <-c.closed:
  675. return
  676. }
  677. }
  678. }
  679. func (c *rawConnection) writeMessage(msg message) error {
  680. msgContext, _ := messageContext(msg)
  681. l.Debugf("Writing %v", msgContext)
  682. defer func() {
  683. metricDeviceSentMessages.WithLabelValues(c.idString).Inc()
  684. }()
  685. size := msg.ProtoSize()
  686. hdr := Header{
  687. Type: typeOf(msg),
  688. }
  689. hdrSize := hdr.ProtoSize()
  690. if hdrSize > 1<<16-1 {
  691. panic("impossibly large header")
  692. }
  693. overhead := 2 + hdrSize + 4
  694. totSize := overhead + size
  695. buf := BufferPool.Get(totSize)
  696. defer BufferPool.Put(buf)
  697. // Message
  698. if _, err := msg.MarshalTo(buf[2+hdrSize+4:]); err != nil {
  699. return fmt.Errorf("marshalling message: %w", err)
  700. }
  701. if c.shouldCompressMessage(msg) {
  702. ok, err := c.writeCompressedMessage(msg, buf[overhead:])
  703. if ok {
  704. return err
  705. }
  706. }
  707. metricDeviceSentUncompressedBytes.WithLabelValues(c.idString).Add(float64(totSize))
  708. // Header length
  709. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  710. // Header
  711. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  712. return fmt.Errorf("marshalling header: %w", err)
  713. }
  714. // Message length
  715. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
  716. n, err := c.cw.Write(buf)
  717. 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)
  718. if err != nil {
  719. return fmt.Errorf("writing message: %w", err)
  720. }
  721. return nil
  722. }
  723. // Write msg out compressed, given its uncompressed marshaled payload.
  724. //
  725. // The first return value indicates whether compression succeeded.
  726. // If not, the caller should retry without compression.
  727. func (c *rawConnection) writeCompressedMessage(msg message, marshaled []byte) (ok bool, err error) {
  728. hdr := Header{
  729. Type: typeOf(msg),
  730. Compression: MessageCompressionLZ4,
  731. }
  732. hdrSize := hdr.ProtoSize()
  733. if hdrSize > 1<<16-1 {
  734. panic("impossibly large header")
  735. }
  736. cOverhead := 2 + hdrSize + 4
  737. metricDeviceSentUncompressedBytes.WithLabelValues(c.idString).Add(float64(cOverhead + len(marshaled)))
  738. // The compressed size may be at most n-n/32 = .96875*n bytes,
  739. // I.e., if we can't save at least 3.125% bandwidth, we forgo compression.
  740. // This number is arbitrary but cheap to compute.
  741. maxCompressed := cOverhead + len(marshaled) - len(marshaled)/32
  742. buf := BufferPool.Get(maxCompressed)
  743. defer BufferPool.Put(buf)
  744. compressedSize, err := lz4Compress(marshaled, buf[cOverhead:])
  745. totSize := compressedSize + cOverhead
  746. if err != nil {
  747. return false, nil
  748. }
  749. // Header length
  750. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  751. // Header
  752. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  753. return true, fmt.Errorf("marshalling header: %w", err)
  754. }
  755. // Message length
  756. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(compressedSize))
  757. n, err := c.cw.Write(buf[:totSize])
  758. 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)
  759. if err != nil {
  760. return true, fmt.Errorf("writing message: %w", err)
  761. }
  762. return true, nil
  763. }
  764. func typeOf(msg message) MessageType {
  765. switch msg.(type) {
  766. case *ClusterConfig:
  767. return MessageTypeClusterConfig
  768. case *Index:
  769. return MessageTypeIndex
  770. case *IndexUpdate:
  771. return MessageTypeIndexUpdate
  772. case *Request:
  773. return MessageTypeRequest
  774. case *Response:
  775. return MessageTypeResponse
  776. case *DownloadProgress:
  777. return MessageTypeDownloadProgress
  778. case *Ping:
  779. return MessageTypePing
  780. case *Close:
  781. return MessageTypeClose
  782. default:
  783. panic("bug: unknown message type")
  784. }
  785. }
  786. func newMessage(t MessageType) (message, error) {
  787. switch t {
  788. case MessageTypeClusterConfig:
  789. return new(ClusterConfig), nil
  790. case MessageTypeIndex:
  791. return new(Index), nil
  792. case MessageTypeIndexUpdate:
  793. return new(IndexUpdate), nil
  794. case MessageTypeRequest:
  795. return new(Request), nil
  796. case MessageTypeResponse:
  797. return new(Response), nil
  798. case MessageTypeDownloadProgress:
  799. return new(DownloadProgress), nil
  800. case MessageTypePing:
  801. return new(Ping), nil
  802. case MessageTypeClose:
  803. return new(Close), nil
  804. default:
  805. return nil, errUnknownMessage
  806. }
  807. }
  808. func (c *rawConnection) shouldCompressMessage(msg message) bool {
  809. switch c.compression {
  810. case CompressionNever:
  811. return false
  812. case CompressionAlways:
  813. // Use compression for large enough messages
  814. return msg.ProtoSize() >= compressionThreshold
  815. case CompressionMetadata:
  816. _, isResponse := msg.(*Response)
  817. // Compress if it's large enough and not a response message
  818. return !isResponse && msg.ProtoSize() >= compressionThreshold
  819. default:
  820. panic("unknown compression setting")
  821. }
  822. }
  823. // Close is called when the connection is regularely closed and thus the Close
  824. // BEP message is sent before terminating the actual connection. The error
  825. // argument specifies the reason for closing the connection.
  826. func (c *rawConnection) Close(err error) {
  827. c.sendCloseOnce.Do(func() {
  828. done := make(chan struct{})
  829. timeout := time.NewTimer(CloseTimeout)
  830. select {
  831. case c.closeBox <- asyncMessage{&Close{err.Error()}, done}:
  832. select {
  833. case <-done:
  834. case <-timeout.C:
  835. case <-c.closed:
  836. }
  837. case <-timeout.C:
  838. case <-c.closed:
  839. }
  840. })
  841. // Close might be called from a method that is called from within
  842. // dispatcherLoop, resulting in a deadlock.
  843. // The sending above must happen before spawning the routine, to prevent
  844. // the underlying connection from terminating before sending the close msg.
  845. go c.internalClose(err)
  846. }
  847. // internalClose is called if there is an unexpected error during normal operation.
  848. func (c *rawConnection) internalClose(err error) {
  849. c.startStopMut.Lock()
  850. defer c.startStopMut.Unlock()
  851. c.closeOnce.Do(func() {
  852. l.Debugf("close connection to %s at %s due to %v", c.deviceID.Short(), c.ConnectionInfo, err)
  853. if cerr := c.closer.Close(); cerr != nil {
  854. l.Debugf("failed to close underlying conn %s at %s %v:", c.deviceID.Short(), c.ConnectionInfo, cerr)
  855. }
  856. close(c.closed)
  857. c.awaitingMut.Lock()
  858. for i, ch := range c.awaiting {
  859. if ch != nil {
  860. close(ch)
  861. delete(c.awaiting, i)
  862. }
  863. }
  864. c.awaitingMut.Unlock()
  865. if !c.startTime.IsZero() {
  866. // Wait for the dispatcher loop to exit, if it was started to
  867. // begin with.
  868. <-c.dispatcherLoopStopped
  869. }
  870. c.model.Closed(err)
  871. })
  872. }
  873. // The pingSender makes sure that we've sent a message within the last
  874. // PingSendInterval. If we already have something sent in the last
  875. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  876. // results in an effecting ping interval of somewhere between
  877. // PingSendInterval/2 and PingSendInterval.
  878. func (c *rawConnection) pingSender() {
  879. ticker := time.NewTicker(PingSendInterval / 2)
  880. defer ticker.Stop()
  881. for {
  882. select {
  883. case <-ticker.C:
  884. d := time.Since(c.cw.Last())
  885. if d < PingSendInterval/2 {
  886. l.Debugln(c.deviceID, "ping skipped after wr", d)
  887. continue
  888. }
  889. l.Debugln(c.deviceID, "ping -> after", d)
  890. c.ping()
  891. case <-c.closed:
  892. return
  893. }
  894. }
  895. }
  896. // The pingReceiver checks that we've received a message (any message will do,
  897. // but we expect pings in the absence of other messages) within the last
  898. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  899. func (c *rawConnection) pingReceiver() {
  900. ticker := time.NewTicker(ReceiveTimeout / 2)
  901. defer ticker.Stop()
  902. for {
  903. select {
  904. case <-ticker.C:
  905. d := time.Since(c.cr.Last())
  906. if d > ReceiveTimeout {
  907. l.Debugln(c.deviceID, "ping timeout", d)
  908. c.internalClose(ErrTimeout)
  909. }
  910. l.Debugln(c.deviceID, "last read within", d)
  911. case <-c.closed:
  912. return
  913. }
  914. }
  915. }
  916. type Statistics struct {
  917. At time.Time `json:"at"`
  918. InBytesTotal int64 `json:"inBytesTotal"`
  919. OutBytesTotal int64 `json:"outBytesTotal"`
  920. StartedAt time.Time `json:"startedAt"`
  921. }
  922. func (c *rawConnection) Statistics() Statistics {
  923. return Statistics{
  924. At: time.Now().Truncate(time.Second),
  925. InBytesTotal: c.cr.Tot(),
  926. OutBytesTotal: c.cw.Tot(),
  927. StartedAt: c.startTime,
  928. }
  929. }
  930. func lz4Compress(src, buf []byte) (int, error) {
  931. n, err := lz4.CompressBlock(src, buf[4:], nil)
  932. if err != nil {
  933. return -1, err
  934. } else if n == 0 {
  935. return -1, errNotCompressible
  936. }
  937. // The compressed block is prefixed by the size of the uncompressed data.
  938. binary.BigEndian.PutUint32(buf, uint32(len(src)))
  939. return n + 4, nil
  940. }
  941. func lz4Decompress(src []byte) ([]byte, error) {
  942. size := binary.BigEndian.Uint32(src)
  943. buf := BufferPool.Get(int(size))
  944. n, err := lz4.UncompressBlock(src[4:], buf)
  945. if err != nil {
  946. BufferPool.Put(buf)
  947. return nil, err
  948. }
  949. return buf[:n], nil
  950. }
  951. func newProtocolError(err error, msgContext string) error {
  952. return fmt.Errorf("protocol error on %v: %w", msgContext, err)
  953. }
  954. func newHandleError(err error, msgContext string) error {
  955. return fmt.Errorf("handling %v: %w", msgContext, err)
  956. }
  957. func messageContext(msg message) (string, error) {
  958. switch msg := msg.(type) {
  959. case *ClusterConfig:
  960. return "cluster-config", nil
  961. case *Index:
  962. return fmt.Sprintf("index for %v", msg.Folder), nil
  963. case *IndexUpdate:
  964. return fmt.Sprintf("index-update for %v", msg.Folder), nil
  965. case *Request:
  966. return fmt.Sprintf(`request for "%v" in %v`, msg.Name, msg.Folder), nil
  967. case *Response:
  968. return "response", nil
  969. case *DownloadProgress:
  970. return fmt.Sprintf("download-progress for %v", msg.Folder), nil
  971. case *Ping:
  972. return "ping", nil
  973. case *Close:
  974. return "close", nil
  975. default:
  976. return "", errors.New("unknown or empty message")
  977. }
  978. }
  979. // connectionWrappingModel takes the Model interface from the model package,
  980. // which expects the Connection as the first parameter in all methods, and
  981. // wraps it to conform to the rawModel interface.
  982. type connectionWrappingModel struct {
  983. conn Connection
  984. model Model
  985. }
  986. func (c *connectionWrappingModel) Index(m *Index) error {
  987. return c.model.Index(c.conn, m)
  988. }
  989. func (c *connectionWrappingModel) IndexUpdate(idxUp *IndexUpdate) error {
  990. return c.model.IndexUpdate(c.conn, idxUp)
  991. }
  992. func (c *connectionWrappingModel) Request(req *Request) (RequestResponse, error) {
  993. return c.model.Request(c.conn, req)
  994. }
  995. func (c *connectionWrappingModel) ClusterConfig(config *ClusterConfig) error {
  996. return c.model.ClusterConfig(c.conn, config)
  997. }
  998. func (c *connectionWrappingModel) Closed(err error) {
  999. c.model.Closed(c.conn, err)
  1000. }
  1001. func (c *connectionWrappingModel) DownloadProgress(p *DownloadProgress) error {
  1002. return c.model.DownloadProgress(c.conn, p)
  1003. }