protocol.go 32 KB

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