protocol.go 29 KB

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