protocol.go 29 KB

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