protocol.go 30 KB

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