protocol.go 27 KB

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