protocol.go 32 KB

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