protocol.go 28 KB

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