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. "fmt"
  14. "io"
  15. "net"
  16. "path"
  17. "strings"
  18. "sync"
  19. "time"
  20. lz4 "github.com/bkaradzic/go-lz4"
  21. "github.com/pkg/errors"
  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. func init() {
  53. for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
  54. BlockSizes = append(BlockSizes, blockSize)
  55. if _, ok := sha256OfEmptyBlock[blockSize]; !ok {
  56. panic("missing hard coded value for sha256 of empty block")
  57. }
  58. }
  59. BufferPool = newBufferPool()
  60. }
  61. // BlockSize returns the block size to use for the given file size
  62. func BlockSize(fileSize int64) int {
  63. var blockSize int
  64. for _, blockSize = range BlockSizes {
  65. if fileSize < DesiredPerFileBlocks*int64(blockSize) {
  66. break
  67. }
  68. }
  69. return blockSize
  70. }
  71. const (
  72. stateInitial = iota
  73. stateReady
  74. )
  75. // FileInfo.LocalFlags flags
  76. const (
  77. FlagLocalUnsupported = 1 << 0 // The kind is unsupported, e.g. symlinks on Windows
  78. FlagLocalIgnored = 1 << 1 // Matches local ignore patterns
  79. FlagLocalMustRescan = 1 << 2 // Doesn't match content on disk, must be rechecked fully
  80. FlagLocalReceiveOnly = 1 << 3 // Change detected on receive only folder
  81. // Flags that should result in the Invalid bit on outgoing updates
  82. LocalInvalidFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly
  83. // Flags that should result in a file being in conflict with its
  84. // successor, due to us not having an up to date picture of its state on
  85. // disk.
  86. LocalConflictFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalReceiveOnly
  87. LocalAllFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly
  88. )
  89. var (
  90. ErrClosed = errors.New("connection closed")
  91. ErrTimeout = errors.New("read timeout")
  92. errUnknownMessage = errors.New("unknown message")
  93. errInvalidFilename = errors.New("filename is invalid")
  94. errUncleanFilename = errors.New("filename not in canonical format")
  95. errDeletedHasBlocks = errors.New("deleted file with non-empty block list")
  96. errDirectoryHasBlocks = errors.New("directory with non-empty block list")
  97. errFileHasNoBlocks = errors.New("file with empty block list")
  98. )
  99. type Model interface {
  100. // An index was received from the peer device
  101. Index(deviceID DeviceID, folder string, files []FileInfo) error
  102. // An index update was received from the peer device
  103. IndexUpdate(deviceID DeviceID, folder string, files []FileInfo) error
  104. // A request was made by the peer device
  105. Request(deviceID DeviceID, folder, name string, blockNo, size int32, offset int64, hash []byte, weakHash uint32, fromTemporary bool) (RequestResponse, error)
  106. // A cluster configuration message was received
  107. ClusterConfig(deviceID DeviceID, config ClusterConfig) error
  108. // The peer device closed the connection or an error occurred
  109. Closed(device DeviceID, err error)
  110. // The peer device sent progress updates for the files it is currently downloading
  111. DownloadProgress(deviceID DeviceID, folder string, updates []FileDownloadProgressUpdate) error
  112. }
  113. type RequestResponse interface {
  114. Data() []byte
  115. Close() // Must always be called once the byte slice is no longer in use
  116. Wait() // Blocks until Close is called
  117. }
  118. type Connection interface {
  119. Start()
  120. SetFolderPasswords(passwords map[string]string)
  121. Close(err error)
  122. ID() DeviceID
  123. Index(ctx context.Context, folder string, files []FileInfo) error
  124. IndexUpdate(ctx context.Context, folder string, files []FileInfo) error
  125. Request(ctx context.Context, folder string, name string, blockNo int, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error)
  126. ClusterConfig(config ClusterConfig)
  127. DownloadProgress(ctx context.Context, folder string, updates []FileDownloadProgressUpdate)
  128. Statistics() Statistics
  129. Closed() <-chan struct{}
  130. ConnectionInfo
  131. }
  132. type ConnectionInfo interface {
  133. Type() string
  134. Transport() string
  135. RemoteAddr() net.Addr
  136. Priority() int
  137. String() string
  138. Crypto() string
  139. EstablishedAt() time.Time
  140. }
  141. type rawConnection struct {
  142. ConnectionInfo
  143. id DeviceID
  144. receiver Model
  145. startTime time.Time
  146. cr *countingReader
  147. cw *countingWriter
  148. closer io.Closer // Closing the underlying connection and thus cr and cw
  149. awaiting map[int]chan asyncResult
  150. awaitingMut sync.Mutex
  151. idxMut sync.Mutex // ensures serialization of Index calls
  152. nextID int
  153. nextIDMut sync.Mutex
  154. inbox chan message
  155. outbox chan asyncMessage
  156. closeBox chan asyncMessage
  157. clusterConfigBox chan *ClusterConfig
  158. dispatcherLoopStopped chan struct{}
  159. closed chan struct{}
  160. closeOnce sync.Once
  161. sendCloseOnce sync.Once
  162. compression Compression
  163. loopWG sync.WaitGroup // Need to ensure no leftover routines in testing
  164. }
  165. type asyncResult struct {
  166. val []byte
  167. err error
  168. }
  169. type message interface {
  170. ProtoSize() int
  171. Marshal() ([]byte, error)
  172. MarshalTo([]byte) (int, error)
  173. Unmarshal([]byte) error
  174. }
  175. type asyncMessage struct {
  176. msg message
  177. done chan struct{} // done closes when we're done sending the message
  178. }
  179. const (
  180. // PingSendInterval is how often we make sure to send a message, by
  181. // triggering pings if necessary.
  182. PingSendInterval = 90 * time.Second
  183. // ReceiveTimeout is the longest we'll wait for a message from the other
  184. // side before closing the connection.
  185. ReceiveTimeout = 300 * time.Second
  186. )
  187. // CloseTimeout is the longest we'll wait when trying to send the close
  188. // message before just closing the connection.
  189. // Should not be modified in production code, just for testing.
  190. var CloseTimeout = 10 * time.Second
  191. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, closer io.Closer, receiver Model, connInfo ConnectionInfo, compress Compression, passwords map[string]string) Connection {
  192. // Encryption / decryption is first (outermost) before conversion to
  193. // native path formats.
  194. nm := makeNative(receiver)
  195. em := &encryptedModel{model: nm, folderKeys: newFolderKeyRegistry(passwords)}
  196. // We do the wire format conversion first (outermost) so that the
  197. // metadata is in wire format when it reaches the encryption step.
  198. rc := newRawConnection(deviceID, reader, writer, closer, em, connInfo, compress)
  199. ec := encryptedConnection{ConnectionInfo: rc, conn: rc, folderKeys: em.folderKeys}
  200. wc := wireFormatConnection{ec}
  201. return wc
  202. }
  203. func newRawConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, closer io.Closer, receiver Model, connInfo ConnectionInfo, compress Compression) *rawConnection {
  204. cr := &countingReader{Reader: reader}
  205. cw := &countingWriter{Writer: writer}
  206. return &rawConnection{
  207. ConnectionInfo: connInfo,
  208. id: deviceID,
  209. receiver: receiver,
  210. cr: cr,
  211. cw: cw,
  212. closer: closer,
  213. awaiting: make(map[int]chan asyncResult),
  214. inbox: make(chan message),
  215. outbox: make(chan asyncMessage),
  216. closeBox: make(chan asyncMessage),
  217. clusterConfigBox: make(chan *ClusterConfig),
  218. dispatcherLoopStopped: make(chan struct{}),
  219. closed: make(chan struct{}),
  220. compression: compress,
  221. loopWG: sync.WaitGroup{},
  222. }
  223. }
  224. // Start creates the goroutines for sending and receiving of messages. It must
  225. // be called exactly once after creating a connection.
  226. func (c *rawConnection) Start() {
  227. c.loopWG.Add(5)
  228. go func() {
  229. c.readerLoop()
  230. c.loopWG.Done()
  231. }()
  232. go func() {
  233. err := c.dispatcherLoop()
  234. c.Close(err)
  235. c.loopWG.Done()
  236. }()
  237. go func() {
  238. c.writerLoop()
  239. c.loopWG.Done()
  240. }()
  241. go func() {
  242. c.pingSender()
  243. c.loopWG.Done()
  244. }()
  245. go func() {
  246. c.pingReceiver()
  247. c.loopWG.Done()
  248. }()
  249. c.startTime = time.Now().Truncate(time.Second)
  250. }
  251. func (c *rawConnection) ID() DeviceID {
  252. return c.id
  253. }
  254. // Index writes the list of file information to the connected peer device
  255. func (c *rawConnection) Index(ctx context.Context, folder string, idx []FileInfo) error {
  256. select {
  257. case <-c.closed:
  258. return ErrClosed
  259. default:
  260. }
  261. c.idxMut.Lock()
  262. c.send(ctx, &Index{
  263. Folder: folder,
  264. Files: idx,
  265. }, nil)
  266. c.idxMut.Unlock()
  267. return nil
  268. }
  269. // IndexUpdate writes the list of file information to the connected peer device as an update
  270. func (c *rawConnection) IndexUpdate(ctx context.Context, folder string, idx []FileInfo) error {
  271. select {
  272. case <-c.closed:
  273. return ErrClosed
  274. default:
  275. }
  276. c.idxMut.Lock()
  277. c.send(ctx, &IndexUpdate{
  278. Folder: folder,
  279. Files: idx,
  280. }, nil)
  281. c.idxMut.Unlock()
  282. return nil
  283. }
  284. // Request returns the bytes for the specified block after fetching them from the connected peer.
  285. 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) {
  286. c.nextIDMut.Lock()
  287. id := c.nextID
  288. c.nextID++
  289. c.nextIDMut.Unlock()
  290. c.awaitingMut.Lock()
  291. if _, ok := c.awaiting[id]; ok {
  292. c.awaitingMut.Unlock()
  293. panic("id taken")
  294. }
  295. rc := make(chan asyncResult, 1)
  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, errors.Wrap(err, "reading message length")
  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, errors.Wrap(err, "reading message")
  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, errors.Wrap(err, "decompressing message")
  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 := c.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, errors.Wrap(err, "unmarshalling message")
  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{}, errors.Wrap(err, "reading length")
  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{}, errors.Wrap(err, "reading header")
  483. }
  484. var hdr Header
  485. err := hdr.Unmarshal(buf)
  486. BufferPool.Put(buf)
  487. if err != nil {
  488. return Header{}, errors.Wrap(err, "unmarshalling header")
  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 errors.Wrapf(err, "%q", f.Name)
  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: c.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 errors.Wrap(err, "marshalling message")
  653. }
  654. if c.shouldCompressMessage(msg) {
  655. ok, err := c.writeCompressedMessage(msg, buf[overhead:], 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 errors.Wrap(err, "marshalling header")
  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 errors.Wrap(err, "writing message")
  672. }
  673. return nil
  674. }
  675. // Write msg out compressed, given its uncompressed marshaled payload and overhead.
  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, overhead int) (ok bool, err error) {
  680. hdr := Header{
  681. Type: c.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. maxCompressed := cOverhead + lz4.CompressBound(len(marshaled))
  690. buf := BufferPool.Get(maxCompressed)
  691. defer BufferPool.Put(buf)
  692. compressedSize, err := lz4Compress(marshaled, buf[cOverhead:])
  693. totSize := compressedSize + cOverhead
  694. if err != nil || totSize >= len(marshaled)+overhead {
  695. return false, nil
  696. }
  697. // Header length
  698. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  699. // Header
  700. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  701. return true, errors.Wrap(err, "marshalling header")
  702. }
  703. // Message length
  704. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(compressedSize))
  705. n, err := c.cw.Write(buf[:totSize])
  706. 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)
  707. if err != nil {
  708. return true, errors.Wrap(err, "writing message")
  709. }
  710. return true, nil
  711. }
  712. func (c *rawConnection) typeOf(msg message) MessageType {
  713. switch msg.(type) {
  714. case *ClusterConfig:
  715. return MessageTypeClusterConfig
  716. case *Index:
  717. return MessageTypeIndex
  718. case *IndexUpdate:
  719. return MessageTypeIndexUpdate
  720. case *Request:
  721. return MessageTypeRequest
  722. case *Response:
  723. return MessageTypeResponse
  724. case *DownloadProgress:
  725. return MessageTypeDownloadProgress
  726. case *Ping:
  727. return MessageTypePing
  728. case *Close:
  729. return MessageTypeClose
  730. default:
  731. panic("bug: unknown message type")
  732. }
  733. }
  734. func (c *rawConnection) newMessage(t MessageType) (message, error) {
  735. switch t {
  736. case MessageTypeClusterConfig:
  737. return new(ClusterConfig), nil
  738. case MessageTypeIndex:
  739. return new(Index), nil
  740. case MessageTypeIndexUpdate:
  741. return new(IndexUpdate), nil
  742. case MessageTypeRequest:
  743. return new(Request), nil
  744. case MessageTypeResponse:
  745. return new(Response), nil
  746. case MessageTypeDownloadProgress:
  747. return new(DownloadProgress), nil
  748. case MessageTypePing:
  749. return new(Ping), nil
  750. case MessageTypeClose:
  751. return new(Close), nil
  752. default:
  753. return nil, errUnknownMessage
  754. }
  755. }
  756. func (c *rawConnection) shouldCompressMessage(msg message) bool {
  757. switch c.compression {
  758. case CompressionNever:
  759. return false
  760. case CompressionAlways:
  761. // Use compression for large enough messages
  762. return msg.ProtoSize() >= compressionThreshold
  763. case CompressionMetadata:
  764. _, isResponse := msg.(*Response)
  765. // Compress if it's large enough and not a response message
  766. return !isResponse && msg.ProtoSize() >= compressionThreshold
  767. default:
  768. panic("unknown compression setting")
  769. }
  770. }
  771. // Close is called when the connection is regularely closed and thus the Close
  772. // BEP message is sent before terminating the actual connection. The error
  773. // argument specifies the reason for closing the connection.
  774. func (c *rawConnection) Close(err error) {
  775. c.sendCloseOnce.Do(func() {
  776. done := make(chan struct{})
  777. timeout := time.NewTimer(CloseTimeout)
  778. select {
  779. case c.closeBox <- asyncMessage{&Close{err.Error()}, done}:
  780. select {
  781. case <-done:
  782. case <-timeout.C:
  783. case <-c.closed:
  784. }
  785. case <-timeout.C:
  786. case <-c.closed:
  787. }
  788. })
  789. // Close might be called from a method that is called from within
  790. // dispatcherLoop, resulting in a deadlock.
  791. // The sending above must happen before spawning the routine, to prevent
  792. // the underlying connection from terminating before sending the close msg.
  793. go c.internalClose(err)
  794. }
  795. // internalClose is called if there is an unexpected error during normal operation.
  796. func (c *rawConnection) internalClose(err error) {
  797. c.closeOnce.Do(func() {
  798. l.Debugln("close due to", err)
  799. if cerr := c.closer.Close(); cerr != nil {
  800. l.Debugln(c.id, "failed to close underlying conn:", cerr)
  801. }
  802. close(c.closed)
  803. c.awaitingMut.Lock()
  804. for i, ch := range c.awaiting {
  805. if ch != nil {
  806. close(ch)
  807. delete(c.awaiting, i)
  808. }
  809. }
  810. c.awaitingMut.Unlock()
  811. <-c.dispatcherLoopStopped
  812. c.receiver.Closed(c.ID(), err)
  813. })
  814. }
  815. // The pingSender makes sure that we've sent a message within the last
  816. // PingSendInterval. If we already have something sent in the last
  817. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  818. // results in an effecting ping interval of somewhere between
  819. // PingSendInterval/2 and PingSendInterval.
  820. func (c *rawConnection) pingSender() {
  821. ticker := time.NewTicker(PingSendInterval / 2)
  822. defer ticker.Stop()
  823. for {
  824. select {
  825. case <-ticker.C:
  826. d := time.Since(c.cw.Last())
  827. if d < PingSendInterval/2 {
  828. l.Debugln(c.id, "ping skipped after wr", d)
  829. continue
  830. }
  831. l.Debugln(c.id, "ping -> after", d)
  832. c.ping()
  833. case <-c.closed:
  834. return
  835. }
  836. }
  837. }
  838. // The pingReceiver checks that we've received a message (any message will do,
  839. // but we expect pings in the absence of other messages) within the last
  840. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  841. func (c *rawConnection) pingReceiver() {
  842. ticker := time.NewTicker(ReceiveTimeout / 2)
  843. defer ticker.Stop()
  844. for {
  845. select {
  846. case <-ticker.C:
  847. d := time.Since(c.cr.Last())
  848. if d > ReceiveTimeout {
  849. l.Debugln(c.id, "ping timeout", d)
  850. c.internalClose(ErrTimeout)
  851. }
  852. l.Debugln(c.id, "last read within", d)
  853. case <-c.closed:
  854. return
  855. }
  856. }
  857. }
  858. type Statistics struct {
  859. At time.Time `json:"at"`
  860. InBytesTotal int64 `json:"inBytesTotal"`
  861. OutBytesTotal int64 `json:"outBytesTotal"`
  862. StartedAt time.Time `json:"startedAt"`
  863. }
  864. func (c *rawConnection) Statistics() Statistics {
  865. return Statistics{
  866. At: time.Now().Truncate(time.Second),
  867. InBytesTotal: c.cr.Tot(),
  868. OutBytesTotal: c.cw.Tot(),
  869. StartedAt: c.startTime,
  870. }
  871. }
  872. func lz4Compress(src, buf []byte) (int, error) {
  873. compressed, err := lz4.Encode(buf, src)
  874. if err != nil {
  875. return -1, err
  876. }
  877. if &compressed[0] != &buf[0] {
  878. panic("bug: lz4.Compress allocated, which it must not (should use buffer pool)")
  879. }
  880. binary.BigEndian.PutUint32(compressed, binary.LittleEndian.Uint32(compressed))
  881. return len(compressed), nil
  882. }
  883. func lz4Decompress(src []byte) ([]byte, error) {
  884. size := binary.BigEndian.Uint32(src)
  885. binary.LittleEndian.PutUint32(src, size)
  886. var err error
  887. buf := BufferPool.Get(int(size))
  888. decoded, err := lz4.Decode(buf, src)
  889. if err != nil {
  890. BufferPool.Put(buf)
  891. return nil, err
  892. }
  893. if &decoded[0] != &buf[0] {
  894. panic("bug: lz4.Decode allocated, which it must not (should use buffer pool)")
  895. }
  896. return decoded, nil
  897. }
  898. func newProtocolError(err error, msgContext string) error {
  899. return fmt.Errorf("protocol error on %v: %w", msgContext, err)
  900. }
  901. func newHandleError(err error, msgContext string) error {
  902. return fmt.Errorf("handling %v: %w", msgContext, err)
  903. }
  904. func messageContext(msg message) (string, error) {
  905. switch msg := msg.(type) {
  906. case *ClusterConfig:
  907. return "cluster-config", nil
  908. case *Index:
  909. return fmt.Sprintf("index for %v", msg.Folder), nil
  910. case *IndexUpdate:
  911. return fmt.Sprintf("index-update for %v", msg.Folder), nil
  912. case *Request:
  913. return fmt.Sprintf(`request for "%v" in %v`, msg.Name, msg.Folder), nil
  914. case *Response:
  915. return "response", nil
  916. case *DownloadProgress:
  917. return fmt.Sprintf("download-progress for %v", msg.Folder), nil
  918. case *Ping:
  919. return "ping", nil
  920. case *Close:
  921. return "close", nil
  922. default:
  923. return "", errors.New("unknown or empty message")
  924. }
  925. }