1
0

protocol.go 29 KB

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