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. "errors"
  14. "fmt"
  15. "io"
  16. "net"
  17. "path"
  18. "strings"
  19. "sync"
  20. "time"
  21. lz4 "github.com/pierrec/lz4/v4"
  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. IsLocal() bool
  139. RemoteAddr() net.Addr
  140. Priority() int
  141. String() string
  142. Crypto() string
  143. EstablishedAt() time.Time
  144. }
  145. type rawConnection struct {
  146. ConnectionInfo
  147. id DeviceID
  148. receiver Model
  149. startTime time.Time
  150. cr *countingReader
  151. cw *countingWriter
  152. closer io.Closer // Closing the underlying connection and thus cr and cw
  153. awaitingMut sync.Mutex // Protects awaiting and nextID.
  154. awaiting map[int]chan asyncResult
  155. nextID int
  156. idxMut sync.Mutex // ensures serialization of Index calls
  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. rc := make(chan asyncResult, 1)
  290. c.awaitingMut.Lock()
  291. id := c.nextID
  292. c.nextID++
  293. if _, ok := c.awaiting[id]; ok {
  294. c.awaitingMut.Unlock()
  295. panic("id taken")
  296. }
  297. c.awaiting[id] = rc
  298. c.awaitingMut.Unlock()
  299. ok := c.send(ctx, &Request{
  300. ID: id,
  301. Folder: folder,
  302. Name: name,
  303. Offset: offset,
  304. Size: size,
  305. BlockNo: blockNo,
  306. Hash: hash,
  307. WeakHash: weakHash,
  308. FromTemporary: fromTemporary,
  309. }, nil)
  310. if !ok {
  311. return nil, ErrClosed
  312. }
  313. select {
  314. case res, ok := <-rc:
  315. if !ok {
  316. return nil, ErrClosed
  317. }
  318. return res.val, res.err
  319. case <-ctx.Done():
  320. return nil, ctx.Err()
  321. }
  322. }
  323. // ClusterConfig sends the cluster configuration message to the peer.
  324. func (c *rawConnection) ClusterConfig(config ClusterConfig) {
  325. select {
  326. case c.clusterConfigBox <- &config:
  327. case <-c.closed:
  328. }
  329. }
  330. func (c *rawConnection) Closed() <-chan struct{} {
  331. return c.closed
  332. }
  333. // DownloadProgress sends the progress updates for the files that are currently being downloaded.
  334. func (c *rawConnection) DownloadProgress(ctx context.Context, folder string, updates []FileDownloadProgressUpdate) {
  335. c.send(ctx, &DownloadProgress{
  336. Folder: folder,
  337. Updates: updates,
  338. }, nil)
  339. }
  340. func (c *rawConnection) ping() bool {
  341. return c.send(context.Background(), &Ping{}, nil)
  342. }
  343. func (c *rawConnection) readerLoop() {
  344. fourByteBuf := make([]byte, 4)
  345. for {
  346. msg, err := c.readMessage(fourByteBuf)
  347. if err != nil {
  348. if err == errUnknownMessage {
  349. // Unknown message types are skipped, for future extensibility.
  350. continue
  351. }
  352. c.internalClose(err)
  353. return
  354. }
  355. select {
  356. case c.inbox <- msg:
  357. case <-c.closed:
  358. return
  359. }
  360. }
  361. }
  362. func (c *rawConnection) dispatcherLoop() (err error) {
  363. defer close(c.dispatcherLoopStopped)
  364. var msg message
  365. state := stateInitial
  366. for {
  367. select {
  368. case msg = <-c.inbox:
  369. case <-c.closed:
  370. return ErrClosed
  371. }
  372. msgContext, err := messageContext(msg)
  373. if err != nil {
  374. return fmt.Errorf("protocol error: %w", err)
  375. }
  376. l.Debugf("handle %v message", msgContext)
  377. switch msg := msg.(type) {
  378. case *ClusterConfig:
  379. if state == stateInitial {
  380. state = stateReady
  381. }
  382. case *Close:
  383. return fmt.Errorf("closed by remote: %v", msg.Reason)
  384. default:
  385. if state != stateReady {
  386. return newProtocolError(fmt.Errorf("invalid state %d", state), msgContext)
  387. }
  388. }
  389. switch msg := msg.(type) {
  390. case *Index:
  391. err = checkIndexConsistency(msg.Files)
  392. case *IndexUpdate:
  393. err = checkIndexConsistency(msg.Files)
  394. case *Request:
  395. err = checkFilename(msg.Name)
  396. }
  397. if err != nil {
  398. return newProtocolError(err, msgContext)
  399. }
  400. switch msg := msg.(type) {
  401. case *ClusterConfig:
  402. err = c.receiver.ClusterConfig(c.id, *msg)
  403. case *Index:
  404. err = c.handleIndex(*msg)
  405. case *IndexUpdate:
  406. err = c.handleIndexUpdate(*msg)
  407. case *Request:
  408. go c.handleRequest(*msg)
  409. case *Response:
  410. c.handleResponse(*msg)
  411. case *DownloadProgress:
  412. err = c.receiver.DownloadProgress(c.id, msg.Folder, msg.Updates)
  413. }
  414. if err != nil {
  415. return newHandleError(err, msgContext)
  416. }
  417. }
  418. }
  419. func (c *rawConnection) readMessage(fourByteBuf []byte) (message, error) {
  420. hdr, err := c.readHeader(fourByteBuf)
  421. if err != nil {
  422. return nil, err
  423. }
  424. return c.readMessageAfterHeader(hdr, fourByteBuf)
  425. }
  426. func (c *rawConnection) readMessageAfterHeader(hdr Header, fourByteBuf []byte) (message, error) {
  427. // First comes a 4 byte message length
  428. if _, err := io.ReadFull(c.cr, fourByteBuf[:4]); err != nil {
  429. return nil, fmt.Errorf("reading message length: %w", err)
  430. }
  431. msgLen := int32(binary.BigEndian.Uint32(fourByteBuf))
  432. if msgLen < 0 {
  433. return nil, fmt.Errorf("negative message length %d", msgLen)
  434. } else if msgLen > MaxMessageLen {
  435. return nil, fmt.Errorf("message length %d exceeds maximum %d", msgLen, MaxMessageLen)
  436. }
  437. // Then comes the message
  438. buf := BufferPool.Get(int(msgLen))
  439. if _, err := io.ReadFull(c.cr, buf); err != nil {
  440. BufferPool.Put(buf)
  441. return nil, fmt.Errorf("reading message: %w", err)
  442. }
  443. // ... which might be compressed
  444. switch hdr.Compression {
  445. case MessageCompressionNone:
  446. // Nothing
  447. case MessageCompressionLZ4:
  448. decomp, err := lz4Decompress(buf)
  449. BufferPool.Put(buf)
  450. if err != nil {
  451. return nil, fmt.Errorf("decompressing message: %w", err)
  452. }
  453. buf = decomp
  454. default:
  455. return nil, fmt.Errorf("unknown message compression %d", hdr.Compression)
  456. }
  457. // ... and is then unmarshalled
  458. msg, err := newMessage(hdr.Type)
  459. if err != nil {
  460. BufferPool.Put(buf)
  461. return nil, err
  462. }
  463. if err := msg.Unmarshal(buf); err != nil {
  464. BufferPool.Put(buf)
  465. return nil, fmt.Errorf("unmarshalling message: %w", err)
  466. }
  467. BufferPool.Put(buf)
  468. return msg, nil
  469. }
  470. func (c *rawConnection) readHeader(fourByteBuf []byte) (Header, error) {
  471. // First comes a 2 byte header length
  472. if _, err := io.ReadFull(c.cr, fourByteBuf[:2]); err != nil {
  473. return Header{}, fmt.Errorf("reading length: %w", err)
  474. }
  475. hdrLen := int16(binary.BigEndian.Uint16(fourByteBuf))
  476. if hdrLen < 0 {
  477. return Header{}, fmt.Errorf("negative header length %d", hdrLen)
  478. }
  479. // Then comes the header
  480. buf := BufferPool.Get(int(hdrLen))
  481. if _, err := io.ReadFull(c.cr, buf); err != nil {
  482. BufferPool.Put(buf)
  483. return Header{}, fmt.Errorf("reading header: %w", err)
  484. }
  485. var hdr Header
  486. err := hdr.Unmarshal(buf)
  487. BufferPool.Put(buf)
  488. if err != nil {
  489. return Header{}, fmt.Errorf("unmarshalling header: %w", err)
  490. }
  491. return hdr, nil
  492. }
  493. func (c *rawConnection) handleIndex(im Index) error {
  494. l.Debugf("Index(%v, %v, %d file)", c.id, im.Folder, len(im.Files))
  495. return c.receiver.Index(c.id, im.Folder, im.Files)
  496. }
  497. func (c *rawConnection) handleIndexUpdate(im IndexUpdate) error {
  498. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  499. return c.receiver.IndexUpdate(c.id, im.Folder, im.Files)
  500. }
  501. // checkIndexConsistency verifies a number of invariants on FileInfos received in
  502. // index messages.
  503. func checkIndexConsistency(fs []FileInfo) error {
  504. for _, f := range fs {
  505. if err := checkFileInfoConsistency(f); err != nil {
  506. return fmt.Errorf("%q: %w", f.Name, err)
  507. }
  508. }
  509. return nil
  510. }
  511. // checkFileInfoConsistency verifies a number of invariants on the given FileInfo
  512. func checkFileInfoConsistency(f FileInfo) error {
  513. if err := checkFilename(f.Name); err != nil {
  514. return err
  515. }
  516. switch {
  517. case f.Deleted && len(f.Blocks) != 0:
  518. // Deleted files should have no blocks
  519. return errDeletedHasBlocks
  520. case f.Type == FileInfoTypeDirectory && len(f.Blocks) != 0:
  521. // Directories should have no blocks
  522. return errDirectoryHasBlocks
  523. case !f.Deleted && !f.IsInvalid() && f.Type == FileInfoTypeFile && len(f.Blocks) == 0:
  524. // Non-deleted, non-invalid files should have at least one block
  525. return errFileHasNoBlocks
  526. }
  527. return nil
  528. }
  529. // checkFilename verifies that the given filename is valid according to the
  530. // spec on what's allowed over the wire. A filename failing this test is
  531. // grounds for disconnecting the device.
  532. func checkFilename(name string) error {
  533. cleanedName := path.Clean(name)
  534. if cleanedName != name {
  535. // The filename on the wire should be in canonical format. If
  536. // Clean() managed to clean it up, there was something wrong with
  537. // it.
  538. return errUncleanFilename
  539. }
  540. switch name {
  541. case "", ".", "..":
  542. // These names are always invalid.
  543. return errInvalidFilename
  544. }
  545. if strings.HasPrefix(name, "/") {
  546. // Names are folder relative, not absolute.
  547. return errInvalidFilename
  548. }
  549. if strings.HasPrefix(name, "../") {
  550. // Starting with a dotdot is not allowed. Any other dotdots would
  551. // have been handled by the Clean() call at the top.
  552. return errInvalidFilename
  553. }
  554. return nil
  555. }
  556. func (c *rawConnection) handleRequest(req Request) {
  557. 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)
  558. if err != nil {
  559. c.send(context.Background(), &Response{
  560. ID: req.ID,
  561. Code: errorToCode(err),
  562. }, nil)
  563. return
  564. }
  565. done := make(chan struct{})
  566. c.send(context.Background(), &Response{
  567. ID: req.ID,
  568. Data: res.Data(),
  569. Code: errorToCode(nil),
  570. }, done)
  571. <-done
  572. res.Close()
  573. }
  574. func (c *rawConnection) handleResponse(resp Response) {
  575. c.awaitingMut.Lock()
  576. if rc := c.awaiting[resp.ID]; rc != nil {
  577. delete(c.awaiting, resp.ID)
  578. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  579. close(rc)
  580. }
  581. c.awaitingMut.Unlock()
  582. }
  583. func (c *rawConnection) send(ctx context.Context, msg message, done chan struct{}) bool {
  584. select {
  585. case c.outbox <- asyncMessage{msg, done}:
  586. return true
  587. case <-c.closed:
  588. case <-ctx.Done():
  589. }
  590. if done != nil {
  591. close(done)
  592. }
  593. return false
  594. }
  595. func (c *rawConnection) writerLoop() {
  596. select {
  597. case cc := <-c.clusterConfigBox:
  598. err := c.writeMessage(cc)
  599. if err != nil {
  600. c.internalClose(err)
  601. return
  602. }
  603. case hm := <-c.closeBox:
  604. _ = c.writeMessage(hm.msg)
  605. close(hm.done)
  606. return
  607. case <-c.closed:
  608. return
  609. }
  610. for {
  611. select {
  612. case cc := <-c.clusterConfigBox:
  613. err := c.writeMessage(cc)
  614. if err != nil {
  615. c.internalClose(err)
  616. return
  617. }
  618. case hm := <-c.outbox:
  619. err := c.writeMessage(hm.msg)
  620. if hm.done != nil {
  621. close(hm.done)
  622. }
  623. if err != nil {
  624. c.internalClose(err)
  625. return
  626. }
  627. case hm := <-c.closeBox:
  628. _ = c.writeMessage(hm.msg)
  629. close(hm.done)
  630. return
  631. case <-c.closed:
  632. return
  633. }
  634. }
  635. }
  636. func (c *rawConnection) writeMessage(msg message) error {
  637. msgContext, _ := messageContext(msg)
  638. l.Debugf("Writing %v", msgContext)
  639. size := msg.ProtoSize()
  640. hdr := Header{
  641. Type: typeOf(msg),
  642. }
  643. hdrSize := hdr.ProtoSize()
  644. if hdrSize > 1<<16-1 {
  645. panic("impossibly large header")
  646. }
  647. overhead := 2 + hdrSize + 4
  648. totSize := overhead + size
  649. buf := BufferPool.Get(totSize)
  650. defer BufferPool.Put(buf)
  651. // Message
  652. if _, err := msg.MarshalTo(buf[2+hdrSize+4:]); err != nil {
  653. return fmt.Errorf("marshalling message: %w", err)
  654. }
  655. if c.shouldCompressMessage(msg) {
  656. ok, err := c.writeCompressedMessage(msg, buf[overhead:])
  657. if ok {
  658. return err
  659. }
  660. }
  661. // Header length
  662. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  663. // Header
  664. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  665. return fmt.Errorf("marshalling header: %w", err)
  666. }
  667. // Message length
  668. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
  669. n, err := c.cw.Write(buf)
  670. 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)
  671. if err != nil {
  672. return fmt.Errorf("writing message: %w", err)
  673. }
  674. return nil
  675. }
  676. // Write msg out compressed, given its uncompressed marshaled payload.
  677. //
  678. // The first return value indicates whether compression succeeded.
  679. // If not, the caller should retry without compression.
  680. func (c *rawConnection) writeCompressedMessage(msg message, marshaled []byte) (ok bool, err error) {
  681. hdr := Header{
  682. Type: typeOf(msg),
  683. Compression: MessageCompressionLZ4,
  684. }
  685. hdrSize := hdr.ProtoSize()
  686. if hdrSize > 1<<16-1 {
  687. panic("impossibly large header")
  688. }
  689. cOverhead := 2 + hdrSize + 4
  690. // The compressed size may be at most n-n/32 = .96875*n bytes,
  691. // I.e., if we can't save at least 3.125% bandwidth, we forgo compression.
  692. // This number is arbitrary but cheap to compute.
  693. maxCompressed := cOverhead + len(marshaled) - len(marshaled)/32
  694. buf := BufferPool.Get(maxCompressed)
  695. defer BufferPool.Put(buf)
  696. compressedSize, err := lz4Compress(marshaled, buf[cOverhead:])
  697. totSize := compressedSize + cOverhead
  698. if err != nil {
  699. return false, nil
  700. }
  701. // Header length
  702. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  703. // Header
  704. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  705. return true, fmt.Errorf("marshalling header: %w", err)
  706. }
  707. // Message length
  708. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(compressedSize))
  709. n, err := c.cw.Write(buf[:totSize])
  710. 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)
  711. if err != nil {
  712. return true, fmt.Errorf("writing message: %w", err)
  713. }
  714. return true, nil
  715. }
  716. func typeOf(msg message) MessageType {
  717. switch msg.(type) {
  718. case *ClusterConfig:
  719. return MessageTypeClusterConfig
  720. case *Index:
  721. return MessageTypeIndex
  722. case *IndexUpdate:
  723. return MessageTypeIndexUpdate
  724. case *Request:
  725. return MessageTypeRequest
  726. case *Response:
  727. return MessageTypeResponse
  728. case *DownloadProgress:
  729. return MessageTypeDownloadProgress
  730. case *Ping:
  731. return MessageTypePing
  732. case *Close:
  733. return MessageTypeClose
  734. default:
  735. panic("bug: unknown message type")
  736. }
  737. }
  738. func newMessage(t MessageType) (message, error) {
  739. switch t {
  740. case MessageTypeClusterConfig:
  741. return new(ClusterConfig), nil
  742. case MessageTypeIndex:
  743. return new(Index), nil
  744. case MessageTypeIndexUpdate:
  745. return new(IndexUpdate), nil
  746. case MessageTypeRequest:
  747. return new(Request), nil
  748. case MessageTypeResponse:
  749. return new(Response), nil
  750. case MessageTypeDownloadProgress:
  751. return new(DownloadProgress), nil
  752. case MessageTypePing:
  753. return new(Ping), nil
  754. case MessageTypeClose:
  755. return new(Close), nil
  756. default:
  757. return nil, errUnknownMessage
  758. }
  759. }
  760. func (c *rawConnection) shouldCompressMessage(msg message) bool {
  761. switch c.compression {
  762. case CompressionNever:
  763. return false
  764. case CompressionAlways:
  765. // Use compression for large enough messages
  766. return msg.ProtoSize() >= compressionThreshold
  767. case CompressionMetadata:
  768. _, isResponse := msg.(*Response)
  769. // Compress if it's large enough and not a response message
  770. return !isResponse && msg.ProtoSize() >= compressionThreshold
  771. default:
  772. panic("unknown compression setting")
  773. }
  774. }
  775. // Close is called when the connection is regularely closed and thus the Close
  776. // BEP message is sent before terminating the actual connection. The error
  777. // argument specifies the reason for closing the connection.
  778. func (c *rawConnection) Close(err error) {
  779. c.sendCloseOnce.Do(func() {
  780. done := make(chan struct{})
  781. timeout := time.NewTimer(CloseTimeout)
  782. select {
  783. case c.closeBox <- asyncMessage{&Close{err.Error()}, done}:
  784. select {
  785. case <-done:
  786. case <-timeout.C:
  787. case <-c.closed:
  788. }
  789. case <-timeout.C:
  790. case <-c.closed:
  791. }
  792. })
  793. // Close might be called from a method that is called from within
  794. // dispatcherLoop, resulting in a deadlock.
  795. // The sending above must happen before spawning the routine, to prevent
  796. // the underlying connection from terminating before sending the close msg.
  797. go c.internalClose(err)
  798. }
  799. // internalClose is called if there is an unexpected error during normal operation.
  800. func (c *rawConnection) internalClose(err error) {
  801. c.closeOnce.Do(func() {
  802. l.Debugln("close due to", err)
  803. if cerr := c.closer.Close(); cerr != nil {
  804. l.Debugln(c.id, "failed to close underlying conn:", cerr)
  805. }
  806. close(c.closed)
  807. c.awaitingMut.Lock()
  808. for i, ch := range c.awaiting {
  809. if ch != nil {
  810. close(ch)
  811. delete(c.awaiting, i)
  812. }
  813. }
  814. c.awaitingMut.Unlock()
  815. <-c.dispatcherLoopStopped
  816. c.receiver.Closed(c.ID(), err)
  817. })
  818. }
  819. // The pingSender makes sure that we've sent a message within the last
  820. // PingSendInterval. If we already have something sent in the last
  821. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  822. // results in an effecting ping interval of somewhere between
  823. // PingSendInterval/2 and PingSendInterval.
  824. func (c *rawConnection) pingSender() {
  825. ticker := time.NewTicker(PingSendInterval / 2)
  826. defer ticker.Stop()
  827. for {
  828. select {
  829. case <-ticker.C:
  830. d := time.Since(c.cw.Last())
  831. if d < PingSendInterval/2 {
  832. l.Debugln(c.id, "ping skipped after wr", d)
  833. continue
  834. }
  835. l.Debugln(c.id, "ping -> after", d)
  836. c.ping()
  837. case <-c.closed:
  838. return
  839. }
  840. }
  841. }
  842. // The pingReceiver checks that we've received a message (any message will do,
  843. // but we expect pings in the absence of other messages) within the last
  844. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  845. func (c *rawConnection) pingReceiver() {
  846. ticker := time.NewTicker(ReceiveTimeout / 2)
  847. defer ticker.Stop()
  848. for {
  849. select {
  850. case <-ticker.C:
  851. d := time.Since(c.cr.Last())
  852. if d > ReceiveTimeout {
  853. l.Debugln(c.id, "ping timeout", d)
  854. c.internalClose(ErrTimeout)
  855. }
  856. l.Debugln(c.id, "last read within", d)
  857. case <-c.closed:
  858. return
  859. }
  860. }
  861. }
  862. type Statistics struct {
  863. At time.Time `json:"at"`
  864. InBytesTotal int64 `json:"inBytesTotal"`
  865. OutBytesTotal int64 `json:"outBytesTotal"`
  866. StartedAt time.Time `json:"startedAt"`
  867. }
  868. func (c *rawConnection) Statistics() Statistics {
  869. return Statistics{
  870. At: time.Now().Truncate(time.Second),
  871. InBytesTotal: c.cr.Tot(),
  872. OutBytesTotal: c.cw.Tot(),
  873. StartedAt: c.startTime,
  874. }
  875. }
  876. func lz4Compress(src, buf []byte) (int, error) {
  877. n, err := lz4.CompressBlock(src, buf[4:], nil)
  878. if err != nil {
  879. return -1, err
  880. } else if n == 0 {
  881. return -1, errNotCompressible
  882. }
  883. // The compressed block is prefixed by the size of the uncompressed data.
  884. binary.BigEndian.PutUint32(buf, uint32(len(src)))
  885. return n + 4, nil
  886. }
  887. func lz4Decompress(src []byte) ([]byte, error) {
  888. size := binary.BigEndian.Uint32(src)
  889. buf := BufferPool.Get(int(size))
  890. n, err := lz4.UncompressBlock(src[4:], buf)
  891. if err != nil {
  892. BufferPool.Put(buf)
  893. return nil, err
  894. }
  895. return buf[:n], nil
  896. }
  897. func newProtocolError(err error, msgContext string) error {
  898. return fmt.Errorf("protocol error on %v: %w", msgContext, err)
  899. }
  900. func newHandleError(err error, msgContext string) error {
  901. return fmt.Errorf("handling %v: %w", msgContext, err)
  902. }
  903. func messageContext(msg message) (string, error) {
  904. switch msg := msg.(type) {
  905. case *ClusterConfig:
  906. return "cluster-config", nil
  907. case *Index:
  908. return fmt.Sprintf("index for %v", msg.Folder), nil
  909. case *IndexUpdate:
  910. return fmt.Sprintf("index-update for %v", msg.Folder), nil
  911. case *Request:
  912. return fmt.Sprintf(`request for "%v" in %v`, msg.Name, msg.Folder), nil
  913. case *Response:
  914. return "response", nil
  915. case *DownloadProgress:
  916. return fmt.Sprintf("download-progress for %v", msg.Folder), nil
  917. case *Ping:
  918. return "ping", nil
  919. case *Close:
  920. return "close", nil
  921. default:
  922. return "", errors.New("unknown or empty message")
  923. }
  924. }