protocol.go 29 KB

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