protocol.go 29 KB

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