protocol.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. cr *countingReader
  129. cw *countingWriter
  130. awaiting map[int32]chan asyncResult
  131. awaitingMut sync.Mutex
  132. idxMut sync.Mutex // ensures serialization of Index calls
  133. nextID int32
  134. nextIDMut sync.Mutex
  135. inbox chan message
  136. outbox chan asyncMessage
  137. closeBox chan asyncMessage
  138. clusterConfigBox chan *ClusterConfig
  139. dispatcherLoopStopped chan struct{}
  140. closed chan struct{}
  141. closeOnce sync.Once
  142. sendCloseOnce sync.Once
  143. compression Compression
  144. }
  145. type asyncResult struct {
  146. val []byte
  147. err error
  148. }
  149. type message interface {
  150. ProtoSize() int
  151. Marshal() ([]byte, error)
  152. MarshalTo([]byte) (int, error)
  153. Unmarshal([]byte) error
  154. }
  155. type asyncMessage struct {
  156. msg message
  157. done chan struct{} // done closes when we're done sending the message
  158. }
  159. const (
  160. // PingSendInterval is how often we make sure to send a message, by
  161. // triggering pings if necessary.
  162. PingSendInterval = 90 * time.Second
  163. // ReceiveTimeout is the longest we'll wait for a message from the other
  164. // side before closing the connection.
  165. ReceiveTimeout = 300 * time.Second
  166. )
  167. // CloseTimeout is the longest we'll wait when trying to send the close
  168. // message before just closing the connection.
  169. // Should not be modified in production code, just for testing.
  170. var CloseTimeout = 10 * time.Second
  171. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress Compression) Connection {
  172. cr := &countingReader{Reader: reader}
  173. cw := &countingWriter{Writer: writer}
  174. c := rawConnection{
  175. id: deviceID,
  176. name: name,
  177. receiver: nativeModel{receiver},
  178. cr: cr,
  179. cw: cw,
  180. awaiting: make(map[int32]chan asyncResult),
  181. inbox: make(chan message),
  182. outbox: make(chan asyncMessage),
  183. closeBox: make(chan asyncMessage),
  184. clusterConfigBox: make(chan *ClusterConfig),
  185. dispatcherLoopStopped: make(chan struct{}),
  186. closed: make(chan struct{}),
  187. compression: compress,
  188. }
  189. return wireFormatConnection{&c}
  190. }
  191. // Start creates the goroutines for sending and receiving of messages. It must
  192. // be called exactly once after creating a connection.
  193. func (c *rawConnection) Start() {
  194. go c.readerLoop()
  195. go func() {
  196. err := c.dispatcherLoop()
  197. c.internalClose(err)
  198. }()
  199. go c.writerLoop()
  200. go c.pingSender()
  201. go c.pingReceiver()
  202. }
  203. func (c *rawConnection) ID() DeviceID {
  204. return c.id
  205. }
  206. func (c *rawConnection) Name() string {
  207. return c.name
  208. }
  209. // Index writes the list of file information to the connected peer device
  210. func (c *rawConnection) Index(ctx context.Context, folder string, idx []FileInfo) error {
  211. select {
  212. case <-c.closed:
  213. return ErrClosed
  214. default:
  215. }
  216. c.idxMut.Lock()
  217. c.send(ctx, &Index{
  218. Folder: folder,
  219. Files: idx,
  220. }, nil)
  221. c.idxMut.Unlock()
  222. return nil
  223. }
  224. // IndexUpdate writes the list of file information to the connected peer device as an update
  225. func (c *rawConnection) IndexUpdate(ctx context.Context, folder string, idx []FileInfo) error {
  226. select {
  227. case <-c.closed:
  228. return ErrClosed
  229. default:
  230. }
  231. c.idxMut.Lock()
  232. c.send(ctx, &IndexUpdate{
  233. Folder: folder,
  234. Files: idx,
  235. }, nil)
  236. c.idxMut.Unlock()
  237. return nil
  238. }
  239. // Request returns the bytes for the specified block after fetching them from the connected peer.
  240. func (c *rawConnection) Request(ctx context.Context, folder string, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  241. c.nextIDMut.Lock()
  242. id := c.nextID
  243. c.nextID++
  244. c.nextIDMut.Unlock()
  245. c.awaitingMut.Lock()
  246. if _, ok := c.awaiting[id]; ok {
  247. panic("id taken")
  248. }
  249. rc := make(chan asyncResult, 1)
  250. c.awaiting[id] = rc
  251. c.awaitingMut.Unlock()
  252. ok := c.send(ctx, &Request{
  253. ID: id,
  254. Folder: folder,
  255. Name: name,
  256. Offset: offset,
  257. Size: int32(size),
  258. Hash: hash,
  259. WeakHash: weakHash,
  260. FromTemporary: fromTemporary,
  261. }, nil)
  262. if !ok {
  263. return nil, ErrClosed
  264. }
  265. select {
  266. case res, ok := <-rc:
  267. if !ok {
  268. return nil, ErrClosed
  269. }
  270. return res.val, res.err
  271. case <-ctx.Done():
  272. return nil, ctx.Err()
  273. }
  274. }
  275. // ClusterConfig sends the cluster configuration message to the peer.
  276. // It must be called just once (as per BEP), otherwise it will panic.
  277. func (c *rawConnection) ClusterConfig(config ClusterConfig) {
  278. select {
  279. case c.clusterConfigBox <- &config:
  280. close(c.clusterConfigBox)
  281. case <-c.closed:
  282. }
  283. }
  284. func (c *rawConnection) Closed() bool {
  285. select {
  286. case <-c.closed:
  287. return true
  288. default:
  289. return false
  290. }
  291. }
  292. // DownloadProgress sends the progress updates for the files that are currently being downloaded.
  293. func (c *rawConnection) DownloadProgress(ctx context.Context, folder string, updates []FileDownloadProgressUpdate) {
  294. c.send(ctx, &DownloadProgress{
  295. Folder: folder,
  296. Updates: updates,
  297. }, nil)
  298. }
  299. func (c *rawConnection) ping() bool {
  300. return c.send(context.Background(), &Ping{}, nil)
  301. }
  302. func (c *rawConnection) readerLoop() {
  303. fourByteBuf := make([]byte, 4)
  304. for {
  305. msg, err := c.readMessage(fourByteBuf)
  306. if err != nil {
  307. if err == errUnknownMessage {
  308. // Unknown message types are skipped, for future extensibility.
  309. continue
  310. }
  311. c.internalClose(err)
  312. return
  313. }
  314. select {
  315. case c.inbox <- msg:
  316. case <-c.closed:
  317. return
  318. }
  319. }
  320. }
  321. func (c *rawConnection) dispatcherLoop() (err error) {
  322. defer close(c.dispatcherLoopStopped)
  323. var msg message
  324. state := stateInitial
  325. for {
  326. select {
  327. case msg = <-c.inbox:
  328. case <-c.closed:
  329. return ErrClosed
  330. }
  331. switch msg := msg.(type) {
  332. case *ClusterConfig:
  333. l.Debugln("read ClusterConfig message")
  334. if state != stateInitial {
  335. return fmt.Errorf("protocol error: cluster config message in state %d", state)
  336. }
  337. if err := c.receiver.ClusterConfig(c.id, *msg); err != nil {
  338. return errors.Wrap(err, "receiver error")
  339. }
  340. state = stateReady
  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, 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 hm := <-c.outbox:
  592. err := c.writeMessage(hm.msg)
  593. if hm.done != nil {
  594. close(hm.done)
  595. }
  596. if err != nil {
  597. c.internalClose(err)
  598. return
  599. }
  600. case hm := <-c.closeBox:
  601. _ = c.writeMessage(hm.msg)
  602. close(hm.done)
  603. return
  604. case <-c.closed:
  605. return
  606. }
  607. }
  608. }
  609. func (c *rawConnection) writeMessage(msg message) error {
  610. if c.shouldCompressMessage(msg) {
  611. return c.writeCompressedMessage(msg)
  612. }
  613. return c.writeUncompressedMessage(msg)
  614. }
  615. func (c *rawConnection) writeCompressedMessage(msg message) error {
  616. size := msg.ProtoSize()
  617. buf := BufferPool.Get(size)
  618. if _, err := msg.MarshalTo(buf); err != nil {
  619. return errors.Wrap(err, "marshalling message")
  620. }
  621. compressed, err := c.lz4Compress(buf)
  622. if err != nil {
  623. return errors.Wrap(err, "compressing message")
  624. }
  625. hdr := Header{
  626. Type: c.typeOf(msg),
  627. Compression: MessageCompressionLZ4,
  628. }
  629. hdrSize := hdr.ProtoSize()
  630. if hdrSize > 1<<16-1 {
  631. panic("impossibly large header")
  632. }
  633. totSize := 2 + hdrSize + 4 + len(compressed)
  634. buf = BufferPool.Upgrade(buf, totSize)
  635. // Header length
  636. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  637. // Header
  638. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  639. return errors.Wrap(err, "marshalling header")
  640. }
  641. // Message length
  642. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(len(compressed)))
  643. // Message
  644. copy(buf[2+hdrSize+4:], compressed)
  645. BufferPool.Put(compressed)
  646. n, err := c.cw.Write(buf)
  647. BufferPool.Put(buf)
  648. 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)
  649. if err != nil {
  650. return errors.Wrap(err, "writing message")
  651. }
  652. return nil
  653. }
  654. func (c *rawConnection) writeUncompressedMessage(msg message) error {
  655. size := msg.ProtoSize()
  656. hdr := Header{
  657. Type: c.typeOf(msg),
  658. }
  659. hdrSize := hdr.ProtoSize()
  660. if hdrSize > 1<<16-1 {
  661. panic("impossibly large header")
  662. }
  663. totSize := 2 + hdrSize + 4 + size
  664. buf := BufferPool.Get(totSize)
  665. // Header length
  666. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  667. // Header
  668. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  669. return errors.Wrap(err, "marshalling header")
  670. }
  671. // Message length
  672. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
  673. // Message
  674. if _, err := msg.MarshalTo(buf[2+hdrSize+4:]); err != nil {
  675. return errors.Wrap(err, "marshalling message")
  676. }
  677. n, err := c.cw.Write(buf[:totSize])
  678. BufferPool.Put(buf)
  679. 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)
  680. if err != nil {
  681. return errors.Wrap(err, "writing message")
  682. }
  683. return nil
  684. }
  685. func (c *rawConnection) typeOf(msg message) MessageType {
  686. switch msg.(type) {
  687. case *ClusterConfig:
  688. return messageTypeClusterConfig
  689. case *Index:
  690. return messageTypeIndex
  691. case *IndexUpdate:
  692. return messageTypeIndexUpdate
  693. case *Request:
  694. return messageTypeRequest
  695. case *Response:
  696. return messageTypeResponse
  697. case *DownloadProgress:
  698. return messageTypeDownloadProgress
  699. case *Ping:
  700. return messageTypePing
  701. case *Close:
  702. return messageTypeClose
  703. default:
  704. panic("bug: unknown message type")
  705. }
  706. }
  707. func (c *rawConnection) newMessage(t MessageType) (message, error) {
  708. switch t {
  709. case messageTypeClusterConfig:
  710. return new(ClusterConfig), nil
  711. case messageTypeIndex:
  712. return new(Index), nil
  713. case messageTypeIndexUpdate:
  714. return new(IndexUpdate), nil
  715. case messageTypeRequest:
  716. return new(Request), nil
  717. case messageTypeResponse:
  718. return new(Response), nil
  719. case messageTypeDownloadProgress:
  720. return new(DownloadProgress), nil
  721. case messageTypePing:
  722. return new(Ping), nil
  723. case messageTypeClose:
  724. return new(Close), nil
  725. default:
  726. return nil, errUnknownMessage
  727. }
  728. }
  729. func (c *rawConnection) shouldCompressMessage(msg message) bool {
  730. switch c.compression {
  731. case CompressNever:
  732. return false
  733. case CompressAlways:
  734. // Use compression for large enough messages
  735. return msg.ProtoSize() >= compressionThreshold
  736. case CompressMetadata:
  737. _, isResponse := msg.(*Response)
  738. // Compress if it's large enough and not a response message
  739. return !isResponse && msg.ProtoSize() >= compressionThreshold
  740. default:
  741. panic("unknown compression setting")
  742. }
  743. }
  744. // Close is called when the connection is regularely closed and thus the Close
  745. // BEP message is sent before terminating the actual connection. The error
  746. // argument specifies the reason for closing the connection.
  747. func (c *rawConnection) Close(err error) {
  748. c.sendCloseOnce.Do(func() {
  749. done := make(chan struct{})
  750. timeout := time.NewTimer(CloseTimeout)
  751. select {
  752. case c.closeBox <- asyncMessage{&Close{err.Error()}, done}:
  753. select {
  754. case <-done:
  755. case <-timeout.C:
  756. case <-c.closed:
  757. }
  758. case <-timeout.C:
  759. case <-c.closed:
  760. }
  761. })
  762. // Close might be called from a method that is called from within
  763. // dispatcherLoop, resulting in a deadlock.
  764. // The sending above must happen before spawning the routine, to prevent
  765. // the underlying connection from terminating before sending the close msg.
  766. go c.internalClose(err)
  767. }
  768. // internalClose is called if there is an unexpected error during normal operation.
  769. func (c *rawConnection) internalClose(err error) {
  770. c.closeOnce.Do(func() {
  771. l.Debugln("close due to", err)
  772. close(c.closed)
  773. c.awaitingMut.Lock()
  774. for i, ch := range c.awaiting {
  775. if ch != nil {
  776. close(ch)
  777. delete(c.awaiting, i)
  778. }
  779. }
  780. c.awaitingMut.Unlock()
  781. <-c.dispatcherLoopStopped
  782. c.receiver.Closed(c, err)
  783. })
  784. }
  785. // The pingSender makes sure that we've sent a message within the last
  786. // PingSendInterval. If we already have something sent in the last
  787. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  788. // results in an effecting ping interval of somewhere between
  789. // PingSendInterval/2 and PingSendInterval.
  790. func (c *rawConnection) pingSender() {
  791. ticker := time.NewTicker(PingSendInterval / 2)
  792. defer ticker.Stop()
  793. for {
  794. select {
  795. case <-ticker.C:
  796. d := time.Since(c.cw.Last())
  797. if d < PingSendInterval/2 {
  798. l.Debugln(c.id, "ping skipped after wr", d)
  799. continue
  800. }
  801. l.Debugln(c.id, "ping -> after", d)
  802. c.ping()
  803. case <-c.closed:
  804. return
  805. }
  806. }
  807. }
  808. // The pingReceiver checks that we've received a message (any message will do,
  809. // but we expect pings in the absence of other messages) within the last
  810. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  811. func (c *rawConnection) pingReceiver() {
  812. ticker := time.NewTicker(ReceiveTimeout / 2)
  813. defer ticker.Stop()
  814. for {
  815. select {
  816. case <-ticker.C:
  817. d := time.Since(c.cr.Last())
  818. if d > ReceiveTimeout {
  819. l.Debugln(c.id, "ping timeout", d)
  820. c.internalClose(ErrTimeout)
  821. }
  822. l.Debugln(c.id, "last read within", d)
  823. case <-c.closed:
  824. return
  825. }
  826. }
  827. }
  828. type Statistics struct {
  829. At time.Time
  830. InBytesTotal int64
  831. OutBytesTotal int64
  832. }
  833. func (c *rawConnection) Statistics() Statistics {
  834. return Statistics{
  835. At: time.Now(),
  836. InBytesTotal: c.cr.Tot(),
  837. OutBytesTotal: c.cw.Tot(),
  838. }
  839. }
  840. func (c *rawConnection) lz4Compress(src []byte) ([]byte, error) {
  841. var err error
  842. buf := BufferPool.Get(lz4.CompressBound(len(src)))
  843. compressed, err := lz4.Encode(buf, src)
  844. if err != nil {
  845. return nil, err
  846. }
  847. if &compressed[0] != &buf[0] {
  848. panic("bug: lz4.Compress allocated, which it must not (should use buffer pool)")
  849. }
  850. binary.BigEndian.PutUint32(compressed, binary.LittleEndian.Uint32(compressed))
  851. return compressed, nil
  852. }
  853. func (c *rawConnection) lz4Decompress(src []byte) ([]byte, error) {
  854. size := binary.BigEndian.Uint32(src)
  855. binary.LittleEndian.PutUint32(src, size)
  856. var err error
  857. buf := BufferPool.Get(int(size))
  858. decoded, err := lz4.Decode(buf, src)
  859. if err != nil {
  860. return nil, err
  861. }
  862. if &decoded[0] != &buf[0] {
  863. panic("bug: lz4.Decode allocated, which it must not (should use buffer pool)")
  864. }
  865. return decoded, nil
  866. }