protocol.go 32 KB

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