protocol.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. }