protocol.go 32 KB

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