protocol.go 27 KB

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