protocol.go 29 KB

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