protocol.go 29 KB

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