folder_sendrecv.go 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/sha256"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "path/filepath"
  15. "slices"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/syncthing/syncthing/internal/itererr"
  20. "github.com/syncthing/syncthing/lib/build"
  21. "github.com/syncthing/syncthing/lib/config"
  22. "github.com/syncthing/syncthing/lib/events"
  23. "github.com/syncthing/syncthing/lib/fs"
  24. "github.com/syncthing/syncthing/lib/ignore"
  25. "github.com/syncthing/syncthing/lib/osutil"
  26. "github.com/syncthing/syncthing/lib/protocol"
  27. "github.com/syncthing/syncthing/lib/scanner"
  28. "github.com/syncthing/syncthing/lib/semaphore"
  29. "github.com/syncthing/syncthing/lib/sync"
  30. "github.com/syncthing/syncthing/lib/versioner"
  31. )
  32. var (
  33. blockStats = make(map[string]int)
  34. blockStatsMut = sync.NewMutex()
  35. )
  36. func init() {
  37. folderFactories[config.FolderTypeSendReceive] = newSendReceiveFolder
  38. }
  39. // A pullBlockState is passed to the puller routine for each block that needs
  40. // to be fetched.
  41. type pullBlockState struct {
  42. *sharedPullerState
  43. block protocol.BlockInfo
  44. }
  45. // A copyBlocksState is passed to copy routine if the file has blocks to be
  46. // copied.
  47. type copyBlocksState struct {
  48. *sharedPullerState
  49. blocks []protocol.BlockInfo
  50. have int
  51. }
  52. // Which filemode bits to preserve
  53. const retainBits = fs.ModeSetgid | fs.ModeSetuid | fs.ModeSticky
  54. var (
  55. activity = newDeviceActivity()
  56. errNoDevice = errors.New("peers who had this file went away, or the file has changed while syncing. will retry later")
  57. errDirPrefix = "directory has been deleted on a remote device but "
  58. errDirHasToBeScanned = errors.New(errDirPrefix + "contains changed files, scheduling scan")
  59. errDirHasIgnored = errors.New(errDirPrefix + "contains ignored files (see ignore documentation for (?d) prefix)")
  60. errDirNotEmpty = errors.New(errDirPrefix + "is not empty; the contents are probably ignored on that remote device, but not locally")
  61. errNotAvailable = errors.New("no connected device has the required version of this file")
  62. errModified = errors.New("file modified but not rescanned; will try again later")
  63. errUnexpectedDirOnFileDel = errors.New("encountered directory when trying to remove file/symlink")
  64. errIncompatibleSymlink = errors.New("incompatible symlink entry; rescan with newer Syncthing on source")
  65. contextRemovingOldItem = "removing item to be replaced"
  66. )
  67. type dbUpdateType int
  68. func (d dbUpdateType) String() string {
  69. switch d {
  70. case dbUpdateHandleDir:
  71. return "dbUpdateHandleDir"
  72. case dbUpdateDeleteDir:
  73. return "dbUpdateDeleteDir"
  74. case dbUpdateHandleFile:
  75. return "dbUpdateHandleFile"
  76. case dbUpdateDeleteFile:
  77. return "dbUpdateDeleteFile"
  78. case dbUpdateShortcutFile:
  79. return "dbUpdateShortcutFile"
  80. case dbUpdateHandleSymlink:
  81. return "dbUpdateHandleSymlink"
  82. case dbUpdateInvalidate:
  83. return "dbUpdateHandleInvalidate"
  84. }
  85. panic(fmt.Sprintf("unknown dbUpdateType %d", d))
  86. }
  87. const (
  88. dbUpdateHandleDir dbUpdateType = iota
  89. dbUpdateDeleteDir
  90. dbUpdateHandleFile
  91. dbUpdateDeleteFile
  92. dbUpdateShortcutFile
  93. dbUpdateHandleSymlink
  94. dbUpdateInvalidate
  95. )
  96. const (
  97. defaultCopiers = 2
  98. defaultPullerPause = 60 * time.Second
  99. defaultPullerPendingKiB = 2 * protocol.MaxBlockSize / 1024
  100. maxPullerIterations = 3
  101. )
  102. type dbUpdateJob struct {
  103. file protocol.FileInfo
  104. jobType dbUpdateType
  105. }
  106. type sendReceiveFolder struct {
  107. folder
  108. queue *jobQueue
  109. blockPullReorderer blockPullReorderer
  110. writeLimiter *semaphore.Semaphore
  111. tempPullErrors map[string]string // pull errors that might be just transient
  112. }
  113. func newSendReceiveFolder(model *model, ignores *ignore.Matcher, cfg config.FolderConfiguration, ver versioner.Versioner, evLogger events.Logger, ioLimiter *semaphore.Semaphore) service {
  114. f := &sendReceiveFolder{
  115. folder: newFolder(model, ignores, cfg, evLogger, ioLimiter, ver),
  116. queue: newJobQueue(),
  117. blockPullReorderer: newBlockPullReorderer(cfg.BlockPullOrder, model.id, cfg.DeviceIDs()),
  118. writeLimiter: semaphore.New(cfg.MaxConcurrentWrites),
  119. }
  120. f.puller = f
  121. if f.Copiers == 0 {
  122. f.Copiers = defaultCopiers
  123. }
  124. // If the configured max amount of pending data is zero, we use the
  125. // default. If it's configured to something non-zero but less than the
  126. // protocol block size we adjust it upwards accordingly.
  127. if f.PullerMaxPendingKiB == 0 {
  128. f.PullerMaxPendingKiB = defaultPullerPendingKiB
  129. }
  130. if blockSizeKiB := protocol.MaxBlockSize / 1024; f.PullerMaxPendingKiB < blockSizeKiB {
  131. f.PullerMaxPendingKiB = blockSizeKiB
  132. }
  133. return f
  134. }
  135. // pull returns true if it manages to get all needed items from peers, i.e. get
  136. // the device in sync with the global state.
  137. func (f *sendReceiveFolder) pull() (bool, error) {
  138. l.Debugf("%v pulling", f)
  139. scanChan := make(chan string)
  140. go f.pullScannerRoutine(scanChan)
  141. defer func() {
  142. close(scanChan)
  143. f.setState(FolderIdle)
  144. }()
  145. metricFolderPulls.WithLabelValues(f.ID).Inc()
  146. ctx, cancel := context.WithCancel(f.ctx)
  147. defer cancel()
  148. go addTimeUntilCancelled(ctx, metricFolderPullSeconds.WithLabelValues(f.ID))
  149. changed := 0
  150. f.errorsMut.Lock()
  151. f.pullErrors = nil
  152. f.errorsMut.Unlock()
  153. var err error
  154. for tries := range maxPullerIterations {
  155. select {
  156. case <-f.ctx.Done():
  157. return false, f.ctx.Err()
  158. default:
  159. }
  160. // Needs to be set on every loop, as the puller might have set
  161. // it to FolderSyncing during the last iteration.
  162. f.setState(FolderSyncPreparing)
  163. changed, err = f.pullerIteration(scanChan)
  164. if err != nil {
  165. return false, err
  166. }
  167. l.Debugln(f, "changed", changed, "on try", tries+1)
  168. if changed == 0 {
  169. // No files were changed by the puller, so we are in
  170. // sync (except for unrecoverable stuff like invalid
  171. // filenames on windows).
  172. break
  173. }
  174. }
  175. f.errorsMut.Lock()
  176. pullErrNum := len(f.tempPullErrors)
  177. if pullErrNum > 0 {
  178. f.pullErrors = make([]FileError, 0, len(f.tempPullErrors))
  179. for path, err := range f.tempPullErrors {
  180. l.Infof("Puller (folder %s, item %q): %v", f.Description(), path, err)
  181. f.pullErrors = append(f.pullErrors, FileError{
  182. Err: err,
  183. Path: path,
  184. })
  185. }
  186. f.tempPullErrors = nil
  187. }
  188. f.errorsMut.Unlock()
  189. if pullErrNum > 0 {
  190. l.Infof("%v: Failed to sync %v items", f.Description(), pullErrNum)
  191. f.evLogger.Log(events.FolderErrors, map[string]interface{}{
  192. "folder": f.folderID,
  193. "errors": f.Errors(),
  194. })
  195. }
  196. return changed == 0, nil
  197. }
  198. // pullerIteration runs a single puller iteration for the given folder and
  199. // returns the number items that should have been synced (even those that
  200. // might have failed). One puller iteration handles all files currently
  201. // flagged as needed in the folder.
  202. func (f *sendReceiveFolder) pullerIteration(scanChan chan<- string) (int, error) {
  203. f.errorsMut.Lock()
  204. f.tempPullErrors = make(map[string]string)
  205. f.errorsMut.Unlock()
  206. pullChan := make(chan pullBlockState)
  207. copyChan := make(chan copyBlocksState)
  208. finisherChan := make(chan *sharedPullerState)
  209. dbUpdateChan := make(chan dbUpdateJob)
  210. pullWg := sync.NewWaitGroup()
  211. copyWg := sync.NewWaitGroup()
  212. doneWg := sync.NewWaitGroup()
  213. updateWg := sync.NewWaitGroup()
  214. l.Debugln(f, "copiers:", f.Copiers, "pullerPendingKiB:", f.PullerMaxPendingKiB)
  215. updateWg.Add(1)
  216. go func() {
  217. // dbUpdaterRoutine finishes when dbUpdateChan is closed
  218. f.dbUpdaterRoutine(dbUpdateChan)
  219. updateWg.Done()
  220. }()
  221. for range f.Copiers {
  222. copyWg.Add(1)
  223. go func() {
  224. // copierRoutine finishes when copyChan is closed
  225. f.copierRoutine(copyChan, pullChan, finisherChan)
  226. copyWg.Done()
  227. }()
  228. }
  229. pullWg.Add(1)
  230. go func() {
  231. // pullerRoutine finishes when pullChan is closed
  232. f.pullerRoutine(pullChan, finisherChan)
  233. pullWg.Done()
  234. }()
  235. doneWg.Add(1)
  236. // finisherRoutine finishes when finisherChan is closed
  237. go func() {
  238. f.finisherRoutine(finisherChan, dbUpdateChan, scanChan)
  239. doneWg.Done()
  240. }()
  241. changed, fileDeletions, dirDeletions, err := f.processNeeded(dbUpdateChan, copyChan, scanChan)
  242. // Signal copy and puller routines that we are done with the in data for
  243. // this iteration. Wait for them to finish.
  244. close(copyChan)
  245. copyWg.Wait()
  246. close(pullChan)
  247. pullWg.Wait()
  248. // Signal the finisher chan that there will be no more input and wait
  249. // for it to finish.
  250. close(finisherChan)
  251. doneWg.Wait()
  252. if err == nil {
  253. f.processDeletions(fileDeletions, dirDeletions, dbUpdateChan, scanChan)
  254. }
  255. // Wait for db updates and scan scheduling to complete
  256. close(dbUpdateChan)
  257. updateWg.Wait()
  258. f.queue.Reset()
  259. return changed, err
  260. }
  261. func (f *sendReceiveFolder) processNeeded(dbUpdateChan chan<- dbUpdateJob, copyChan chan<- copyBlocksState, scanChan chan<- string) (int, map[string]protocol.FileInfo, []protocol.FileInfo, error) {
  262. changed := 0
  263. var dirDeletions []protocol.FileInfo
  264. fileDeletions := map[string]protocol.FileInfo{}
  265. buckets := map[string][]protocol.FileInfo{}
  266. // Iterate the list of items that we need and sort them into piles.
  267. // Regular files to pull goes into the file queue, everything else
  268. // (directories, symlinks and deletes) goes into the "process directly"
  269. // pile.
  270. loop:
  271. for file, err := range itererr.Zip(f.model.sdb.AllNeededGlobalFiles(f.folderID, protocol.LocalDeviceID, f.Order, 0, 0)) {
  272. if err != nil {
  273. return changed, nil, nil, err
  274. }
  275. select {
  276. case <-f.ctx.Done():
  277. break loop
  278. default:
  279. }
  280. if f.IgnoreDelete && file.IsDeleted() {
  281. l.Debugln(f, "ignore file deletion (config)", file.FileName())
  282. continue
  283. }
  284. changed++
  285. switch {
  286. case f.ignores.Match(file.Name).IsIgnored():
  287. file.SetIgnored()
  288. l.Debugln(f, "Handling ignored file", file)
  289. dbUpdateChan <- dbUpdateJob{file, dbUpdateInvalidate}
  290. case build.IsWindows && fs.WindowsInvalidFilename(file.Name) != nil:
  291. if file.IsDeleted() {
  292. // Just pretend we deleted it, no reason to create an error
  293. // about a deleted file that we can't have anyway.
  294. // Reason we need it in the first place is, that it was
  295. // ignored at some point.
  296. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  297. } else {
  298. // We can't pull an invalid file. Grab the error again since
  299. // we couldn't assign it directly in the case clause.
  300. f.newPullError(file.Name, fs.WindowsInvalidFilename(file.Name))
  301. // No reason to retry for this
  302. changed--
  303. }
  304. case file.IsDeleted():
  305. switch {
  306. case file.IsDirectory():
  307. // Perform directory deletions at the end, as we may have
  308. // files to delete inside them before we get to that point.
  309. dirDeletions = append(dirDeletions, file)
  310. case file.IsSymlink():
  311. f.deleteFile(file, dbUpdateChan, scanChan)
  312. default:
  313. df, ok, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  314. if err != nil {
  315. return changed, nil, nil, err
  316. }
  317. // Local file can be already deleted, but with a lower version
  318. // number, hence the deletion coming in again as part of
  319. // WithNeed, furthermore, the file can simply be of the wrong
  320. // type if we haven't yet managed to pull it.
  321. if ok && !df.IsDeleted() && !df.IsSymlink() && !df.IsDirectory() && !df.IsInvalid() {
  322. fileDeletions[file.Name] = file
  323. // Put files into buckets per first hash
  324. key := string(df.BlocksHash)
  325. buckets[key] = append(buckets[key], df)
  326. } else {
  327. f.deleteFileWithCurrent(file, df, ok, dbUpdateChan, scanChan)
  328. }
  329. }
  330. case file.Type == protocol.FileInfoTypeFile:
  331. curFile, hasCurFile, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  332. if err != nil {
  333. return changed, nil, nil, err
  334. }
  335. if hasCurFile && file.BlocksEqual(curFile) {
  336. // We are supposed to copy the entire file, and then fetch nothing. We
  337. // are only updating metadata, so we don't actually *need* to make the
  338. // copy.
  339. f.shortcutFile(file, dbUpdateChan)
  340. } else {
  341. // Queue files for processing after directories and symlinks.
  342. f.queue.Push(file.Name, file.Size, file.ModTime())
  343. }
  344. case (build.IsWindows || build.IsAndroid) && file.IsSymlink():
  345. if err := f.handleSymlinkCheckExisting(file, scanChan); err != nil {
  346. f.newPullError(file.Name, fmt.Errorf("handling unsupported symlink: %w", err))
  347. break
  348. }
  349. file.SetUnsupported()
  350. l.Debugln(f, "Invalidating symlink (unsupported)", file.Name)
  351. dbUpdateChan <- dbUpdateJob{file, dbUpdateInvalidate}
  352. case file.IsDirectory() && !file.IsSymlink():
  353. l.Debugln(f, "Handling directory", file.Name)
  354. if f.checkParent(file.Name, scanChan) {
  355. f.handleDir(file, dbUpdateChan, scanChan)
  356. }
  357. case file.IsSymlink():
  358. l.Debugln(f, "Handling symlink", file.Name)
  359. if f.checkParent(file.Name, scanChan) {
  360. f.handleSymlink(file, dbUpdateChan, scanChan)
  361. }
  362. default:
  363. l.Warnln(file)
  364. panic("unhandleable item type, can't happen")
  365. }
  366. }
  367. select {
  368. case <-f.ctx.Done():
  369. return changed, nil, nil, f.ctx.Err()
  370. default:
  371. }
  372. // Process the file queue.
  373. nextFile:
  374. for {
  375. select {
  376. case <-f.ctx.Done():
  377. return changed, fileDeletions, dirDeletions, f.ctx.Err()
  378. default:
  379. }
  380. fileName, ok := f.queue.Pop()
  381. if !ok {
  382. break
  383. }
  384. fi, ok, err := f.model.sdb.GetGlobalFile(f.folderID, fileName)
  385. if err != nil {
  386. return changed, nil, nil, err
  387. }
  388. if !ok {
  389. // File is no longer in the index. Mark it as done and drop it.
  390. f.queue.Done(fileName)
  391. continue
  392. }
  393. if fi.IsDeleted() || fi.IsInvalid() || fi.Type != protocol.FileInfoTypeFile {
  394. // The item has changed type or status in the index while we
  395. // were processing directories above.
  396. f.queue.Done(fileName)
  397. continue
  398. }
  399. if !f.checkParent(fi.Name, scanChan) {
  400. f.queue.Done(fileName)
  401. continue
  402. }
  403. // Check our list of files to be removed for a match, in which case
  404. // we can just do a rename instead.
  405. key := string(fi.BlocksHash)
  406. for candidate, ok := popCandidate(buckets, key); ok; candidate, ok = popCandidate(buckets, key) {
  407. // candidate is our current state of the file, where as the
  408. // desired state with the delete bit set is in the deletion
  409. // map.
  410. desired := fileDeletions[candidate.Name]
  411. if err := f.renameFile(candidate, desired, fi, dbUpdateChan, scanChan); err != nil {
  412. l.Debugf("rename shortcut for %s failed: %s", fi.Name, err.Error())
  413. // Failed to rename, try next one.
  414. continue
  415. }
  416. // Remove the pending deletion (as we performed it by renaming)
  417. delete(fileDeletions, candidate.Name)
  418. f.queue.Done(fileName)
  419. continue nextFile
  420. }
  421. devices := f.model.fileAvailability(f.FolderConfiguration, fi)
  422. if len(devices) > 0 {
  423. if err := f.handleFile(fi, copyChan); err != nil {
  424. f.newPullError(fileName, err)
  425. }
  426. continue
  427. }
  428. f.newPullError(fileName, errNotAvailable)
  429. f.queue.Done(fileName)
  430. }
  431. return changed, fileDeletions, dirDeletions, nil
  432. }
  433. func popCandidate(buckets map[string][]protocol.FileInfo, key string) (protocol.FileInfo, bool) {
  434. cands := buckets[key]
  435. if len(cands) == 0 {
  436. return protocol.FileInfo{}, false
  437. }
  438. buckets[key] = cands[1:]
  439. return cands[0], true
  440. }
  441. func (f *sendReceiveFolder) processDeletions(fileDeletions map[string]protocol.FileInfo, dirDeletions []protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  442. for _, file := range fileDeletions {
  443. select {
  444. case <-f.ctx.Done():
  445. return
  446. default:
  447. }
  448. f.deleteFile(file, dbUpdateChan, scanChan)
  449. }
  450. // Process in reverse order to delete depth first
  451. for i := range dirDeletions {
  452. select {
  453. case <-f.ctx.Done():
  454. return
  455. default:
  456. }
  457. dir := dirDeletions[len(dirDeletions)-i-1]
  458. l.Debugln(f, "Deleting dir", dir.Name)
  459. f.deleteDir(dir, dbUpdateChan, scanChan)
  460. }
  461. }
  462. // handleDir creates or updates the given directory
  463. func (f *sendReceiveFolder) handleDir(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  464. // Used in the defer closure below, updated by the function body. Take
  465. // care not declare another err.
  466. var err error
  467. f.evLogger.Log(events.ItemStarted, map[string]string{
  468. "folder": f.folderID,
  469. "item": file.Name,
  470. "type": "dir",
  471. "action": "update",
  472. })
  473. defer func() {
  474. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  475. "folder": f.folderID,
  476. "item": file.Name,
  477. "error": events.Error(err),
  478. "type": "dir",
  479. "action": "update",
  480. })
  481. }()
  482. mode := fs.FileMode(file.Permissions & 0o777)
  483. if f.IgnorePerms || file.NoPermissions {
  484. mode = 0o777
  485. }
  486. if shouldDebug() {
  487. curFile, _, _ := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  488. l.Debugf("need dir\n\t%v\n\t%v", file, curFile)
  489. }
  490. info, err := f.mtimefs.Lstat(file.Name)
  491. switch {
  492. // There is already something under that name, we need to handle that.
  493. // Unless it already is a directory, as we only track permissions,
  494. // that don't result in a conflict.
  495. case err == nil && !info.IsDir():
  496. // Check that it is what we have in the database.
  497. curFile, hasCurFile, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  498. if err != nil {
  499. f.newPullError(file.Name, fmt.Errorf("handling dir: %w", err))
  500. return
  501. }
  502. if err := f.scanIfItemChanged(file.Name, info, curFile, hasCurFile, false, scanChan); err != nil {
  503. f.newPullError(file.Name, fmt.Errorf("handling dir: %w", err))
  504. return
  505. }
  506. // Remove it to replace with the dir.
  507. if !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  508. // The new file has been changed in conflict with the existing one. We
  509. // should file it away as a conflict instead of just removing or
  510. // archiving.
  511. // Symlinks aren't checked for conflicts.
  512. err = f.inWritableDir(func(name string) error {
  513. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  514. }, curFile.Name)
  515. } else {
  516. err = f.deleteItemOnDisk(curFile, scanChan)
  517. }
  518. if err != nil {
  519. f.newPullError(file.Name, err)
  520. return
  521. }
  522. fallthrough
  523. // The directory doesn't exist, so we create it with the right
  524. // mode bits from the start.
  525. case err != nil && fs.IsNotExist(err):
  526. // We declare a function that acts on only the path name, so
  527. // we can pass it to InWritableDir. We use a regular Mkdir and
  528. // not MkdirAll because the parent should already exist.
  529. mkdir := func(path string) error {
  530. err = f.mtimefs.Mkdir(path, mode)
  531. if err != nil {
  532. return err
  533. }
  534. // Set the platform data (ownership, xattrs, etc).
  535. if err := f.setPlatformData(&file, path); err != nil {
  536. return err
  537. }
  538. if f.IgnorePerms || file.NoPermissions {
  539. return nil
  540. }
  541. // Stat the directory so we can check its permissions.
  542. info, err := f.mtimefs.Lstat(path)
  543. if err != nil {
  544. return err
  545. }
  546. // Mask for the bits we want to preserve and add them in to the
  547. // directories permissions.
  548. return f.mtimefs.Chmod(path, mode|(info.Mode()&retainBits))
  549. }
  550. if err = f.inWritableDir(mkdir, file.Name); err == nil {
  551. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  552. } else {
  553. f.newPullError(file.Name, fmt.Errorf("creating directory: %w", err))
  554. }
  555. return
  556. // Weird error when stat()'ing the dir. Probably won't work to do
  557. // anything else with it if we can't even stat() it.
  558. case err != nil:
  559. f.newPullError(file.Name, fmt.Errorf("checking file to be replaced: %w", err))
  560. return
  561. }
  562. // The directory already exists, so we just correct the metadata. (We
  563. // don't handle modification times on directories, because that sucks...)
  564. // It's OK to change mode bits on stuff within non-writable directories.
  565. if !f.IgnorePerms && !file.NoPermissions {
  566. if err := f.mtimefs.Chmod(file.Name, mode|(info.Mode()&retainBits)); err != nil {
  567. f.newPullError(file.Name, fmt.Errorf("handling dir (setting permissions): %w", err))
  568. return
  569. }
  570. if err := f.setPlatformData(&file, file.Name); err != nil {
  571. f.newPullError(file.Name, fmt.Errorf("handling dir (setting metadata): %w", err))
  572. return
  573. }
  574. }
  575. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  576. }
  577. // checkParent verifies that the thing we are handling lives inside a directory,
  578. // and not a symlink or regular file. It also resurrects missing parent dirs.
  579. func (f *sendReceiveFolder) checkParent(file string, scanChan chan<- string) bool {
  580. parent := filepath.Dir(file)
  581. if err := osutil.TraversesSymlink(f.mtimefs, parent); err != nil {
  582. f.newPullError(file, fmt.Errorf("checking parent dirs: %w", err))
  583. return false
  584. }
  585. // issues #114 and #4475: This works around a race condition
  586. // between two devices, when one device removes a directory and the
  587. // other creates a file in it. However that happens, we end up with
  588. // a directory for "foo" with the delete bit, but a file "foo/bar"
  589. // that we want to sync. We never create the directory, and hence
  590. // fail to create the file and end up looping forever on it. This
  591. // breaks that by creating the directory and scheduling a scan,
  592. // where it will be found and the delete bit on it removed. The
  593. // user can then clean up as they like...
  594. // This can also occur if an entire tree structure was deleted, but only
  595. // a leave has been scanned.
  596. //
  597. // And if this is an encrypted folder:
  598. // Encrypted files have made-up filenames with two synthetic parent
  599. // directories which don't have any meaning. Create those if necessary.
  600. if _, err := f.mtimefs.Lstat(parent); !fs.IsNotExist(err) {
  601. l.Debugf("%v parent not missing %v", f, file)
  602. return true
  603. }
  604. l.Debugf("%v creating parent directory of %v", f, file)
  605. if err := f.mtimefs.MkdirAll(parent, 0o755); err != nil {
  606. f.newPullError(file, fmt.Errorf("creating parent dir: %w", err))
  607. return false
  608. }
  609. if f.Type != config.FolderTypeReceiveEncrypted {
  610. scanChan <- parent
  611. }
  612. return true
  613. }
  614. // handleSymlink creates or updates the given symlink
  615. func (f *sendReceiveFolder) handleSymlink(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  616. // Used in the defer closure below, updated by the function body. Take
  617. // care not declare another err.
  618. var err error
  619. f.evLogger.Log(events.ItemStarted, map[string]string{
  620. "folder": f.folderID,
  621. "item": file.Name,
  622. "type": "symlink",
  623. "action": "update",
  624. })
  625. defer func() {
  626. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  627. "folder": f.folderID,
  628. "item": file.Name,
  629. "error": events.Error(err),
  630. "type": "symlink",
  631. "action": "update",
  632. })
  633. }()
  634. if shouldDebug() {
  635. curFile, ok, _ := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  636. l.Debugf("need symlink\n\t%v\n\t%v", file, curFile, ok)
  637. }
  638. if len(file.SymlinkTarget) == 0 {
  639. // Index entry from a Syncthing predating the support for including
  640. // the link target in the index entry. We log this as an error.
  641. f.newPullError(file.Name, errIncompatibleSymlink)
  642. return
  643. }
  644. if err = f.handleSymlinkCheckExisting(file, scanChan); err != nil {
  645. f.newPullError(file.Name, fmt.Errorf("handling symlink: %w", err))
  646. return
  647. }
  648. // We declare a function that acts on only the path name, so
  649. // we can pass it to InWritableDir.
  650. createLink := func(path string) error {
  651. if err := f.mtimefs.CreateSymlink(string(file.SymlinkTarget), path); err != nil {
  652. return err
  653. }
  654. return f.setPlatformData(&file, path)
  655. }
  656. if err = f.inWritableDir(createLink, file.Name); err == nil {
  657. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleSymlink}
  658. } else {
  659. f.newPullError(file.Name, fmt.Errorf("symlink create: %w", err))
  660. }
  661. }
  662. func (f *sendReceiveFolder) handleSymlinkCheckExisting(file protocol.FileInfo, scanChan chan<- string) error {
  663. // If there is already something under that name, we need to handle that.
  664. info, err := f.mtimefs.Lstat(file.Name)
  665. if err != nil {
  666. if fs.IsNotExist(err) {
  667. return nil
  668. }
  669. return err
  670. }
  671. // Check that it is what we have in the database.
  672. curFile, hasCurFile, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  673. if err != nil {
  674. return err
  675. }
  676. if err := f.scanIfItemChanged(file.Name, info, curFile, hasCurFile, false, scanChan); err != nil {
  677. return err
  678. }
  679. // Remove it to replace with the symlink. This also handles the
  680. // "change symlink type" path.
  681. if !curFile.IsDirectory() && !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  682. // The new file has been changed in conflict with the existing one. We
  683. // should file it away as a conflict instead of just removing or
  684. // archiving.
  685. // Directories and symlinks aren't checked for conflicts.
  686. return f.inWritableDir(func(name string) error {
  687. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  688. }, curFile.Name)
  689. } else {
  690. return f.deleteItemOnDisk(curFile, scanChan)
  691. }
  692. }
  693. // deleteDir attempts to remove a directory that was deleted on a remote
  694. func (f *sendReceiveFolder) deleteDir(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  695. // Used in the defer closure below, updated by the function body. Take
  696. // care not declare another err.
  697. var err error
  698. f.evLogger.Log(events.ItemStarted, map[string]string{
  699. "folder": f.folderID,
  700. "item": file.Name,
  701. "type": "dir",
  702. "action": "delete",
  703. })
  704. defer func() {
  705. if err != nil {
  706. f.newPullError(file.Name, fmt.Errorf("delete dir: %w", err))
  707. }
  708. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  709. "folder": f.folderID,
  710. "item": file.Name,
  711. "error": events.Error(err),
  712. "type": "dir",
  713. "action": "delete",
  714. })
  715. }()
  716. cur, hasCur, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  717. if err != nil {
  718. return
  719. }
  720. if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
  721. if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
  722. err = nil
  723. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  724. }
  725. return
  726. }
  727. if err = f.deleteDirOnDisk(file.Name, scanChan); err != nil {
  728. return
  729. }
  730. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  731. }
  732. // deleteFile attempts to delete the given file
  733. func (f *sendReceiveFolder) deleteFile(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  734. cur, hasCur, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  735. if err != nil {
  736. f.newPullError(file.Name, fmt.Errorf("delete file: %w", err))
  737. return
  738. }
  739. f.deleteFileWithCurrent(file, cur, hasCur, dbUpdateChan, scanChan)
  740. }
  741. func (f *sendReceiveFolder) deleteFileWithCurrent(file, cur protocol.FileInfo, hasCur bool, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  742. // Used in the defer closure below, updated by the function body. Take
  743. // care not declare another err.
  744. var err error
  745. l.Debugln(f, "Deleting file", file.Name)
  746. f.evLogger.Log(events.ItemStarted, map[string]string{
  747. "folder": f.folderID,
  748. "item": file.Name,
  749. "type": "file",
  750. "action": "delete",
  751. })
  752. defer func() {
  753. if err != nil {
  754. f.newPullError(file.Name, fmt.Errorf("delete file: %w", err))
  755. }
  756. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  757. "folder": f.folderID,
  758. "item": file.Name,
  759. "error": events.Error(err),
  760. "type": "file",
  761. "action": "delete",
  762. })
  763. }()
  764. if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
  765. if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
  766. err = nil
  767. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  768. }
  769. return
  770. }
  771. // We are asked to delete a file, but what we have on disk and in db
  772. // is a directory. Something is wrong here, should probably not happen.
  773. if cur.IsDirectory() {
  774. err = errUnexpectedDirOnFileDel
  775. return
  776. }
  777. if f.inConflict(cur.Version, file.Version) {
  778. // There is a conflict here, which shouldn't happen as deletions
  779. // always lose. Merge the version vector of the file we have
  780. // locally and commit it to db to resolve the conflict.
  781. cur.Version = cur.Version.Merge(file.Version)
  782. dbUpdateChan <- dbUpdateJob{cur, dbUpdateHandleFile}
  783. return
  784. }
  785. if f.versioner != nil && !cur.IsSymlink() {
  786. err = f.inWritableDir(f.versioner.Archive, file.Name)
  787. } else {
  788. err = f.inWritableDir(f.mtimefs.Remove, file.Name)
  789. }
  790. if err == nil || fs.IsNotExist(err) {
  791. // It was removed or it doesn't exist to start with
  792. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  793. return
  794. }
  795. if _, serr := f.mtimefs.Lstat(file.Name); serr != nil && !fs.IsPermission(serr) {
  796. // We get an error just looking at the file, and it's not a permission
  797. // problem. Lets assume the error is in fact some variant of "file
  798. // does not exist" (possibly expressed as some parent being a file and
  799. // not a directory etc) and that the delete is handled.
  800. err = nil
  801. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  802. }
  803. }
  804. // renameFile attempts to rename an existing file to a destination
  805. // and set the right attributes on it.
  806. func (f *sendReceiveFolder) renameFile(cur, source, target protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  807. // Used in the defer closure below, updated by the function body. Take
  808. // care not declare another err.
  809. var err error
  810. f.evLogger.Log(events.ItemStarted, map[string]string{
  811. "folder": f.folderID,
  812. "item": source.Name,
  813. "type": "file",
  814. "action": "delete",
  815. })
  816. f.evLogger.Log(events.ItemStarted, map[string]string{
  817. "folder": f.folderID,
  818. "item": target.Name,
  819. "type": "file",
  820. "action": "update",
  821. })
  822. defer func() {
  823. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  824. "folder": f.folderID,
  825. "item": source.Name,
  826. "error": events.Error(err),
  827. "type": "file",
  828. "action": "delete",
  829. })
  830. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  831. "folder": f.folderID,
  832. "item": target.Name,
  833. "error": events.Error(err),
  834. "type": "file",
  835. "action": "update",
  836. })
  837. }()
  838. l.Debugln(f, "taking rename shortcut", source.Name, "->", target.Name)
  839. // Check that source is compatible with what we have in the DB
  840. if err = f.checkToBeDeleted(source, cur, true, scanChan); err != nil {
  841. return err
  842. }
  843. // Check that the target corresponds to what we have in the DB
  844. curTarget, ok, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, target.Name)
  845. if err != nil {
  846. return err
  847. }
  848. switch stat, serr := f.mtimefs.Lstat(target.Name); {
  849. case serr != nil:
  850. var caseErr *fs.ErrCaseConflict
  851. switch {
  852. case errors.As(serr, &caseErr):
  853. if caseErr.Real != source.Name {
  854. err = serr
  855. break
  856. }
  857. fallthrough // This is a case only rename
  858. case fs.IsNotExist(serr):
  859. if !ok || curTarget.IsDeleted() {
  860. break
  861. }
  862. scanChan <- target.Name
  863. err = errModified
  864. default:
  865. // We can't check whether the file changed as compared to the db,
  866. // do not delete.
  867. err = serr
  868. }
  869. case !ok:
  870. // Target appeared from nowhere
  871. scanChan <- target.Name
  872. err = errModified
  873. default:
  874. var fi protocol.FileInfo
  875. if fi, err = scanner.CreateFileInfo(stat, target.Name, f.mtimefs, f.SyncOwnership, f.SyncXattrs, f.XattrFilter); err == nil {
  876. if !fi.IsEquivalentOptional(curTarget, protocol.FileInfoComparison{
  877. ModTimeWindow: f.modTimeWindow,
  878. IgnorePerms: f.IgnorePerms,
  879. IgnoreBlocks: true,
  880. IgnoreFlags: protocol.LocalAllFlags,
  881. IgnoreOwnership: !f.SyncOwnership,
  882. IgnoreXattrs: !f.SyncXattrs,
  883. }) {
  884. // Target changed
  885. scanChan <- target.Name
  886. err = errModified
  887. }
  888. }
  889. }
  890. if err != nil {
  891. return err
  892. }
  893. tempName := fs.TempName(target.Name)
  894. if f.versioner != nil {
  895. err = f.CheckAvailableSpace(uint64(source.Size)) //nolint:gosec
  896. if err == nil {
  897. err = osutil.Copy(f.CopyRangeMethod.ToFS(), f.mtimefs, f.mtimefs, source.Name, tempName)
  898. if err == nil {
  899. err = f.inWritableDir(f.versioner.Archive, source.Name)
  900. }
  901. }
  902. } else {
  903. err = osutil.RenameOrCopy(f.CopyRangeMethod.ToFS(), f.mtimefs, f.mtimefs, source.Name, tempName)
  904. }
  905. if err != nil {
  906. return err
  907. }
  908. blockStatsMut.Lock()
  909. minBlocksPerBlock := target.BlockSize() / protocol.MinBlockSize
  910. blockStats["total"] += len(target.Blocks) * minBlocksPerBlock
  911. blockStats["renamed"] += len(target.Blocks) * minBlocksPerBlock
  912. blockStatsMut.Unlock()
  913. // The file was renamed, so we have handled both the necessary delete
  914. // of the source and the creation of the target temp file. Fix-up the metadata,
  915. // update the local index of the target file and rename from temp to real name.
  916. if err = f.performFinish(target, curTarget, true, tempName, dbUpdateChan, scanChan); err != nil {
  917. return err
  918. }
  919. dbUpdateChan <- dbUpdateJob{source, dbUpdateDeleteFile}
  920. return nil
  921. }
  922. // This is the flow of data and events here, I think...
  923. //
  924. // +-----------------------+
  925. // | | - - - - > ItemStarted
  926. // | handleFile | - - - - > ItemFinished (on shortcuts)
  927. // | |
  928. // +-----------------------+
  929. // |
  930. // | copyChan (copyBlocksState; unless shortcut taken)
  931. // |
  932. // | +-----------------------+
  933. // | | +-----------------------+
  934. // +--->| | |
  935. // | | copierRoutine |
  936. // +-| |
  937. // +-----------------------+
  938. // |
  939. // | pullChan (sharedPullerState)
  940. // |
  941. // | +-----------------------+
  942. // | | +-----------------------+
  943. // +-->| | |
  944. // | | pullerRoutine |
  945. // +-| |
  946. // +-----------------------+
  947. // |
  948. // | finisherChan (sharedPullerState)
  949. // |
  950. // | +-----------------------+
  951. // | | |
  952. // +-->| finisherRoutine | - - - - > ItemFinished
  953. // | |
  954. // +-----------------------+
  955. // handleFile queues the copies and pulls as necessary for a single new or
  956. // changed file.
  957. func (f *sendReceiveFolder) handleFile(file protocol.FileInfo, copyChan chan<- copyBlocksState) error {
  958. curFile, hasCurFile, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, file.Name)
  959. if err != nil {
  960. return err
  961. }
  962. have, _ := blockDiff(curFile.Blocks, file.Blocks)
  963. tempName := fs.TempName(file.Name)
  964. populateOffsets(file.Blocks)
  965. blocks := append([]protocol.BlockInfo{}, file.Blocks...)
  966. reused := make([]int, 0, len(file.Blocks))
  967. if f.Type != config.FolderTypeReceiveEncrypted {
  968. blocks, reused = f.reuseBlocks(blocks, reused, file, tempName)
  969. }
  970. // The sharedpullerstate will know which flags to use when opening the
  971. // temp file depending if we are reusing any blocks or not.
  972. if len(reused) == 0 {
  973. // Otherwise, discard the file ourselves in order for the
  974. // sharedpuller not to panic when it fails to exclusively create a
  975. // file which already exists
  976. f.inWritableDir(f.mtimefs.Remove, tempName)
  977. }
  978. // Reorder blocks
  979. blocks = f.blockPullReorderer.Reorder(blocks)
  980. f.evLogger.Log(events.ItemStarted, map[string]string{
  981. "folder": f.folderID,
  982. "item": file.Name,
  983. "type": "file",
  984. "action": "update",
  985. })
  986. s := newSharedPullerState(file, f.mtimefs, f.folderID, tempName, blocks, reused, f.IgnorePerms || file.NoPermissions, hasCurFile, curFile, !f.DisableSparseFiles, !f.DisableFsync)
  987. l.Debugf("%v need file %s; copy %d, reused %v", f, file.Name, len(blocks), len(reused))
  988. cs := copyBlocksState{
  989. sharedPullerState: s,
  990. blocks: blocks,
  991. have: len(have),
  992. }
  993. copyChan <- cs
  994. return nil
  995. }
  996. func (f *sendReceiveFolder) reuseBlocks(blocks []protocol.BlockInfo, reused []int, file protocol.FileInfo, tempName string) ([]protocol.BlockInfo, []int) {
  997. // Check for an old temporary file which might have some blocks we could
  998. // reuse.
  999. tempBlocks, err := scanner.HashFile(f.ctx, f.ID, f.mtimefs, tempName, file.BlockSize(), nil)
  1000. if err != nil {
  1001. var caseErr *fs.ErrCaseConflict
  1002. if errors.As(err, &caseErr) {
  1003. if rerr := f.mtimefs.Rename(caseErr.Real, tempName); rerr == nil {
  1004. tempBlocks, err = scanner.HashFile(f.ctx, f.ID, f.mtimefs, tempName, file.BlockSize(), nil)
  1005. }
  1006. }
  1007. }
  1008. if err != nil {
  1009. return blocks, reused
  1010. }
  1011. // Check for any reusable blocks in the temp file
  1012. tempCopyBlocks, _ := blockDiff(tempBlocks, file.Blocks)
  1013. // block.String() returns a string unique to the block
  1014. existingBlocks := make(map[string]struct{}, len(tempCopyBlocks))
  1015. for _, block := range tempCopyBlocks {
  1016. existingBlocks[block.String()] = struct{}{}
  1017. }
  1018. // Since the blocks are already there, we don't need to get them.
  1019. blocks = blocks[:0]
  1020. for i, block := range file.Blocks {
  1021. _, ok := existingBlocks[block.String()]
  1022. if !ok {
  1023. blocks = append(blocks, block)
  1024. } else {
  1025. reused = append(reused, i)
  1026. }
  1027. }
  1028. return blocks, reused
  1029. }
  1030. // blockDiff returns lists of common and missing (to transform src into tgt)
  1031. // blocks. Both block lists must have been created with the same block size.
  1032. func blockDiff(src, tgt []protocol.BlockInfo) ([]protocol.BlockInfo, []protocol.BlockInfo) {
  1033. if len(tgt) == 0 {
  1034. return nil, nil
  1035. }
  1036. if len(src) == 0 {
  1037. // Copy the entire file
  1038. return nil, tgt
  1039. }
  1040. have := make([]protocol.BlockInfo, 0, len(src))
  1041. need := make([]protocol.BlockInfo, 0, len(tgt))
  1042. for i := range tgt {
  1043. if i >= len(src) {
  1044. return have, append(need, tgt[i:]...)
  1045. }
  1046. if !bytes.Equal(tgt[i].Hash, src[i].Hash) {
  1047. // Copy differing block
  1048. need = append(need, tgt[i])
  1049. } else {
  1050. have = append(have, tgt[i])
  1051. }
  1052. }
  1053. return have, need
  1054. }
  1055. // populateOffsets sets the Offset field on each block
  1056. func populateOffsets(blocks []protocol.BlockInfo) {
  1057. var offset int64
  1058. for i := range blocks {
  1059. blocks[i].Offset = offset
  1060. offset += int64(blocks[i].Size)
  1061. }
  1062. }
  1063. // shortcutFile sets file metadata, when that's the only thing that has
  1064. // changed.
  1065. func (f *sendReceiveFolder) shortcutFile(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob) {
  1066. l.Debugln(f, "taking shortcut on", file.Name)
  1067. f.evLogger.Log(events.ItemStarted, map[string]string{
  1068. "folder": f.folderID,
  1069. "item": file.Name,
  1070. "type": "file",
  1071. "action": "metadata",
  1072. })
  1073. var err error
  1074. defer f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  1075. "folder": f.folderID,
  1076. "item": file.Name,
  1077. "error": events.Error(err),
  1078. "type": "file",
  1079. "action": "metadata",
  1080. })
  1081. f.queue.Done(file.Name)
  1082. if !f.IgnorePerms && !file.NoPermissions {
  1083. if err = f.mtimefs.Chmod(file.Name, fs.FileMode(file.Permissions&0o777)); err != nil {
  1084. f.newPullError(file.Name, fmt.Errorf("shortcut file (setting permissions): %w", err))
  1085. return
  1086. }
  1087. }
  1088. if err := f.setPlatformData(&file, file.Name); err != nil {
  1089. f.newPullError(file.Name, fmt.Errorf("shortcut file (setting metadata): %w", err))
  1090. return
  1091. }
  1092. // Still need to re-write the trailer with the new encrypted fileinfo.
  1093. if f.Type == config.FolderTypeReceiveEncrypted {
  1094. err = inWritableDir(func(path string) error {
  1095. fd, err := f.mtimefs.OpenFile(path, fs.OptReadWrite, 0o666)
  1096. if err != nil {
  1097. return err
  1098. }
  1099. defer fd.Close()
  1100. trailerSize, err := writeEncryptionTrailer(file, fd)
  1101. if err != nil {
  1102. return err
  1103. }
  1104. file.EncryptionTrailerSize = int(trailerSize)
  1105. file.Size += trailerSize
  1106. return fd.Truncate(file.Size)
  1107. }, f.mtimefs, file.Name, true)
  1108. if err != nil {
  1109. f.newPullError(file.Name, fmt.Errorf("writing encrypted file trailer: %w", err))
  1110. return
  1111. }
  1112. }
  1113. f.mtimefs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  1114. dbUpdateChan <- dbUpdateJob{file, dbUpdateShortcutFile}
  1115. }
  1116. // copierRoutine reads copierStates until the in channel closes and performs
  1117. // the relevant copies when possible, or passes it to the puller routine.
  1118. func (f *sendReceiveFolder) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
  1119. otherFolderFilesystems := make(map[string]fs.Filesystem)
  1120. for folder, cfg := range f.model.cfg.Folders() {
  1121. if folder == f.ID {
  1122. continue
  1123. }
  1124. otherFolderFilesystems[folder] = cfg.Filesystem()
  1125. }
  1126. for state := range in {
  1127. if err := f.CheckAvailableSpace(uint64(state.file.Size)); err != nil { //nolint:gosec
  1128. state.fail(err)
  1129. // Nothing more to do for this failed file, since it would use to much disk space
  1130. out <- state.sharedPullerState
  1131. continue
  1132. }
  1133. if f.Type != config.FolderTypeReceiveEncrypted {
  1134. f.model.progressEmitter.Register(state.sharedPullerState)
  1135. }
  1136. blocks:
  1137. for _, block := range state.blocks {
  1138. select {
  1139. case <-f.ctx.Done():
  1140. state.fail(fmt.Errorf("folder stopped: %w", f.ctx.Err()))
  1141. break blocks
  1142. default:
  1143. }
  1144. if !f.DisableSparseFiles && state.reused == 0 && block.IsEmpty() {
  1145. // The block is a block of all zeroes, and we are not reusing
  1146. // a temp file, so there is no need to do anything with it.
  1147. // If we were reusing a temp file and had this block to copy,
  1148. // it would be because the block in the temp file was *not* a
  1149. // block of all zeroes, so then we should not skip it.
  1150. // Pretend we copied it.
  1151. state.skippedSparseBlock(block.Size)
  1152. state.copyDone(block)
  1153. continue
  1154. }
  1155. if f.copyBlock(block, state, otherFolderFilesystems) {
  1156. state.copyDone(block)
  1157. continue
  1158. }
  1159. if state.failed() != nil {
  1160. break
  1161. }
  1162. state.pullStarted()
  1163. ps := pullBlockState{
  1164. sharedPullerState: state.sharedPullerState,
  1165. block: block,
  1166. }
  1167. pullChan <- ps
  1168. }
  1169. // If there are no blocks to pull/copy, we still need the temporary file in place.
  1170. if len(state.blocks) == 0 {
  1171. _, err := state.tempFile()
  1172. if err != nil {
  1173. state.fail(err)
  1174. }
  1175. }
  1176. out <- state.sharedPullerState
  1177. }
  1178. }
  1179. // Returns true when the block was successfully copied.
  1180. func (f *sendReceiveFolder) copyBlock(block protocol.BlockInfo, state copyBlocksState, otherFolderFilesystems map[string]fs.Filesystem) bool {
  1181. buf := protocol.BufferPool.Get(block.Size)
  1182. defer protocol.BufferPool.Put(buf)
  1183. // Hope that it's usually in the same folder, so start with that
  1184. // one. Also possibly more efficient copy (same filesystem).
  1185. if f.copyBlockFromFolder(f.ID, block, state, f.mtimefs, buf) {
  1186. return true
  1187. }
  1188. if state.failed() != nil {
  1189. return false
  1190. }
  1191. for folderID, ffs := range otherFolderFilesystems {
  1192. if f.copyBlockFromFolder(folderID, block, state, ffs, buf) {
  1193. return true
  1194. }
  1195. if state.failed() != nil {
  1196. return false
  1197. }
  1198. }
  1199. return false
  1200. }
  1201. // Returns true when the block was successfully copied.
  1202. // The passed buffer must be large enough to accommodate the block.
  1203. func (f *sendReceiveFolder) copyBlockFromFolder(folderID string, block protocol.BlockInfo, state copyBlocksState, ffs fs.Filesystem, buf []byte) bool {
  1204. for e, err := range itererr.Zip(f.model.sdb.AllLocalBlocksWithHash(folderID, block.Hash)) {
  1205. if err != nil {
  1206. // We just ignore this and continue pulling instead (though
  1207. // there's a good chance that will fail too, if the DB is
  1208. // unhealthy).
  1209. l.Debugf("Failed to get information from DB about block %v in copier (folderID %v, file %v): %v", block.Hash, f.folderID, state.file.Name)
  1210. return false
  1211. }
  1212. if !f.copyBlockFromFile(e.FileName, e.Offset, state, ffs, block, buf) {
  1213. if state.failed() != nil {
  1214. return false
  1215. }
  1216. continue
  1217. }
  1218. if e.FileName == state.file.Name {
  1219. state.copiedFromOrigin(block.Size)
  1220. } else {
  1221. state.copiedFromElsewhere(block.Size)
  1222. }
  1223. return true
  1224. }
  1225. return false
  1226. }
  1227. // Returns true when the block was successfully copied.
  1228. // The passed buffer must be large enough to accommodate the block.
  1229. func (f *sendReceiveFolder) copyBlockFromFile(srcName string, srcOffset int64, state copyBlocksState, ffs fs.Filesystem, block protocol.BlockInfo, buf []byte) bool {
  1230. fd, err := ffs.Open(srcName)
  1231. if err != nil {
  1232. l.Debugf("Failed to open file %v trying to copy block %v (folderID %v): %v", srcName, block.Hash, f.folderID, err)
  1233. return false
  1234. }
  1235. defer fd.Close()
  1236. _, err = fd.ReadAt(buf, srcOffset)
  1237. if err != nil {
  1238. l.Debugf("Failed to read block from file %v in copier (folderID: %v, hash: %v): %v", srcName, f.folderID, block.Hash, err)
  1239. return false
  1240. }
  1241. // Hash is not SHA256 as it's an encrypted hash token. In that
  1242. // case we can't verify the block integrity so we'll take it on
  1243. // trust. (The other side can and will verify.)
  1244. if f.Type != config.FolderTypeReceiveEncrypted {
  1245. if err := f.verifyBuffer(buf, block); err != nil {
  1246. l.Debugf("Failed to verify buffer in copier (folderID: %v): %v", f.folderID, err)
  1247. return false
  1248. }
  1249. }
  1250. dstFd, err := state.tempFile()
  1251. if err != nil {
  1252. // State is already marked as failed when an error is returned here.
  1253. return false
  1254. }
  1255. if f.CopyRangeMethod != config.CopyRangeMethodStandard {
  1256. err = f.withLimiter(func() error {
  1257. dstFd.mut.Lock()
  1258. defer dstFd.mut.Unlock()
  1259. return fs.CopyRange(f.CopyRangeMethod.ToFS(), fd, dstFd.fd, srcOffset, block.Offset, int64(block.Size))
  1260. })
  1261. } else {
  1262. err = f.limitedWriteAt(dstFd, buf, block.Offset)
  1263. }
  1264. if err != nil {
  1265. state.fail(fmt.Errorf("dst write: %w", err))
  1266. return false
  1267. }
  1268. return true
  1269. }
  1270. func (*sendReceiveFolder) verifyBuffer(buf []byte, block protocol.BlockInfo) error {
  1271. if len(buf) != block.Size {
  1272. return fmt.Errorf("length mismatch %d != %d", len(buf), block.Size)
  1273. }
  1274. hash := sha256.Sum256(buf)
  1275. if !bytes.Equal(hash[:], block.Hash) {
  1276. return fmt.Errorf("hash mismatch %x != %x", hash, block.Hash)
  1277. }
  1278. return nil
  1279. }
  1280. func (f *sendReceiveFolder) pullerRoutine(in <-chan pullBlockState, out chan<- *sharedPullerState) {
  1281. requestLimiter := semaphore.New(f.PullerMaxPendingKiB * 1024)
  1282. wg := sync.NewWaitGroup()
  1283. for state := range in {
  1284. if state.failed() != nil {
  1285. out <- state.sharedPullerState
  1286. continue
  1287. }
  1288. f.setState(FolderSyncing) // Does nothing if already FolderSyncing
  1289. // The requestLimiter limits how many pending block requests we have
  1290. // ongoing at any given time, based on the size of the blocks
  1291. // themselves.
  1292. bytes := state.block.Size
  1293. if err := requestLimiter.TakeWithContext(f.ctx, bytes); err != nil {
  1294. state.fail(err)
  1295. out <- state.sharedPullerState
  1296. continue
  1297. }
  1298. wg.Add(1)
  1299. go func() {
  1300. defer wg.Done()
  1301. defer requestLimiter.Give(bytes)
  1302. f.pullBlock(state, out)
  1303. }()
  1304. }
  1305. wg.Wait()
  1306. }
  1307. func (f *sendReceiveFolder) pullBlock(state pullBlockState, out chan<- *sharedPullerState) {
  1308. // Get an fd to the temporary file. Technically we don't need it until
  1309. // after fetching the block, but if we run into an error here there is
  1310. // no point in issuing the request to the network.
  1311. fd, err := state.tempFile()
  1312. if err != nil {
  1313. out <- state.sharedPullerState
  1314. return
  1315. }
  1316. if !f.DisableSparseFiles && state.reused == 0 && state.block.IsEmpty() {
  1317. // There is no need to request a block of all zeroes. Pretend we
  1318. // requested it and handled it correctly.
  1319. state.pullDone(state.block)
  1320. out <- state.sharedPullerState
  1321. return
  1322. }
  1323. var lastError error
  1324. candidates := f.model.blockAvailability(f.FolderConfiguration, state.file, state.block)
  1325. loop:
  1326. for {
  1327. select {
  1328. case <-f.ctx.Done():
  1329. state.fail(fmt.Errorf("folder stopped: %w", f.ctx.Err()))
  1330. break loop
  1331. default:
  1332. }
  1333. // Select the least busy device to pull the block from. If we found no
  1334. // feasible device at all, fail the block (and in the long run, the
  1335. // file).
  1336. found := activity.leastBusy(candidates)
  1337. if found == -1 {
  1338. if lastError != nil {
  1339. state.fail(fmt.Errorf("pull: %w", lastError))
  1340. } else {
  1341. state.fail(fmt.Errorf("pull: %w", errNoDevice))
  1342. }
  1343. break
  1344. }
  1345. selected := candidates[found]
  1346. candidates[found] = candidates[len(candidates)-1]
  1347. candidates = candidates[:len(candidates)-1]
  1348. // Fetch the block, while marking the selected device as in use so that
  1349. // leastBusy can select another device when someone else asks.
  1350. activity.using(selected)
  1351. var buf []byte
  1352. blockNo := int(state.block.Offset / int64(state.file.BlockSize()))
  1353. buf, lastError = f.model.RequestGlobal(f.ctx, selected.ID, f.folderID, state.file.Name, blockNo, state.block.Offset, state.block.Size, state.block.Hash, selected.FromTemporary)
  1354. activity.done(selected)
  1355. if lastError != nil {
  1356. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, selected.ID.Short(), "returned error:", lastError)
  1357. continue
  1358. }
  1359. // Verify that the received block matches the desired hash, if not
  1360. // try pulling it from another device.
  1361. // For receive-only folders, the hash is not SHA256 as it's an
  1362. // encrypted hash token. In that case we can't verify the block
  1363. // integrity so we'll take it on trust. (The other side can and
  1364. // will verify.)
  1365. if f.Type != config.FolderTypeReceiveEncrypted {
  1366. lastError = f.verifyBuffer(buf, state.block)
  1367. }
  1368. if lastError != nil {
  1369. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, "hash mismatch")
  1370. continue
  1371. }
  1372. // Save the block data we got from the cluster
  1373. err = f.limitedWriteAt(fd, buf, state.block.Offset)
  1374. if err != nil {
  1375. state.fail(fmt.Errorf("save: %w", err))
  1376. } else {
  1377. state.pullDone(state.block)
  1378. }
  1379. break
  1380. }
  1381. out <- state.sharedPullerState
  1382. }
  1383. func (f *sendReceiveFolder) performFinish(file, curFile protocol.FileInfo, hasCurFile bool, tempName string, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  1384. // Set the correct permission bits on the new file
  1385. if !f.IgnorePerms && !file.NoPermissions {
  1386. if err := f.mtimefs.Chmod(tempName, fs.FileMode(file.Permissions&0o777)); err != nil {
  1387. return fmt.Errorf("setting permissions: %w", err)
  1388. }
  1389. }
  1390. // Set file xattrs and ownership.
  1391. if err := f.setPlatformData(&file, tempName); err != nil {
  1392. return fmt.Errorf("setting metadata: %w", err)
  1393. }
  1394. if stat, err := f.mtimefs.Lstat(file.Name); err == nil {
  1395. // There is an old file or directory already in place. We need to
  1396. // handle that.
  1397. if err := f.scanIfItemChanged(file.Name, stat, curFile, hasCurFile, false, scanChan); err != nil {
  1398. return fmt.Errorf("checking existing file: %w", err)
  1399. }
  1400. if !curFile.IsDirectory() && !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  1401. // The new file has been changed in conflict with the existing one. We
  1402. // should file it away as a conflict instead of just removing or
  1403. // archiving.
  1404. // Directories and symlinks aren't checked for conflicts.
  1405. err = f.inWritableDir(func(name string) error {
  1406. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  1407. }, curFile.Name)
  1408. } else {
  1409. err = f.deleteItemOnDisk(curFile, scanChan)
  1410. }
  1411. if err != nil {
  1412. return fmt.Errorf("moving for conflict: %w", err)
  1413. }
  1414. } else if !fs.IsNotExist(err) {
  1415. return fmt.Errorf("checking existing file: %w", err)
  1416. }
  1417. // Replace the original content with the new one. If it didn't work,
  1418. // leave the temp file in place for reuse.
  1419. if err := osutil.RenameOrCopy(f.CopyRangeMethod.ToFS(), f.mtimefs, f.mtimefs, tempName, file.Name); err != nil {
  1420. return fmt.Errorf("replacing file: %w", err)
  1421. }
  1422. // Set the correct timestamp on the new file
  1423. f.mtimefs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  1424. // Record the updated file in the index
  1425. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleFile}
  1426. return nil
  1427. }
  1428. func (f *sendReceiveFolder) finisherRoutine(in <-chan *sharedPullerState, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  1429. for state := range in {
  1430. if closed, err := state.finalClose(); closed {
  1431. l.Debugln(f, "closing", state.file.Name)
  1432. f.queue.Done(state.file.Name)
  1433. if err == nil {
  1434. err = f.performFinish(state.file, state.curFile, state.hasCurFile, state.tempName, dbUpdateChan, scanChan)
  1435. }
  1436. if err != nil {
  1437. f.newPullError(state.file.Name, fmt.Errorf("finishing: %w", err))
  1438. } else {
  1439. minBlocksPerBlock := state.file.BlockSize() / protocol.MinBlockSize
  1440. blockStatsMut.Lock()
  1441. blockStats["total"] += (state.reused + state.copyTotal + state.pullTotal) * minBlocksPerBlock
  1442. blockStats["reused"] += state.reused * minBlocksPerBlock
  1443. blockStats["pulled"] += state.pullTotal * minBlocksPerBlock
  1444. // copyOriginShifted is counted towards copyOrigin due to progress bar reasons
  1445. // for reporting reasons we want to separate these.
  1446. blockStats["copyOrigin"] += (state.copyOrigin - state.copyOriginShifted) * minBlocksPerBlock
  1447. blockStats["copyOriginShifted"] += state.copyOriginShifted * minBlocksPerBlock
  1448. blockStats["copyElsewhere"] += (state.copyTotal - state.copyOrigin) * minBlocksPerBlock
  1449. blockStatsMut.Unlock()
  1450. }
  1451. if f.Type != config.FolderTypeReceiveEncrypted {
  1452. f.model.progressEmitter.Deregister(state)
  1453. }
  1454. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  1455. "folder": f.folderID,
  1456. "item": state.file.Name,
  1457. "error": events.Error(err),
  1458. "type": "file",
  1459. "action": "update",
  1460. })
  1461. }
  1462. }
  1463. }
  1464. // Moves the given filename to the front of the job queue
  1465. func (f *sendReceiveFolder) BringToFront(filename string) {
  1466. f.queue.BringToFront(filename)
  1467. }
  1468. func (f *sendReceiveFolder) Jobs(page, perpage int) ([]string, []string, int) {
  1469. return f.queue.Jobs(page, perpage)
  1470. }
  1471. // dbUpdaterRoutine aggregates db updates and commits them in batches no
  1472. // larger than 1000 items, and no more delayed than 2 seconds.
  1473. func (f *sendReceiveFolder) dbUpdaterRoutine(dbUpdateChan <-chan dbUpdateJob) {
  1474. const maxBatchTime = 2 * time.Second
  1475. changedDirs := make(map[string]struct{})
  1476. found := false
  1477. var lastFile protocol.FileInfo
  1478. tick := time.NewTicker(maxBatchTime)
  1479. defer tick.Stop()
  1480. batch := NewFileInfoBatch(func(files []protocol.FileInfo) error {
  1481. // sync directories
  1482. for dir := range changedDirs {
  1483. delete(changedDirs, dir)
  1484. if !f.DisableFsync {
  1485. fd, err := f.mtimefs.Open(dir)
  1486. if err != nil {
  1487. l.Debugf("fsync %q failed: %v", dir, err)
  1488. continue
  1489. }
  1490. if err := fd.Sync(); err != nil {
  1491. l.Debugf("fsync %q failed: %v", dir, err)
  1492. }
  1493. fd.Close()
  1494. }
  1495. }
  1496. // All updates to file/folder objects that originated remotely
  1497. // (across the network) use this call to updateLocals
  1498. f.updateLocalsFromPulling(files)
  1499. if found {
  1500. f.ReceivedFile(lastFile.Name, lastFile.IsDeleted())
  1501. found = false
  1502. }
  1503. return nil
  1504. })
  1505. loop:
  1506. for {
  1507. select {
  1508. case job, ok := <-dbUpdateChan:
  1509. if !ok {
  1510. break loop
  1511. }
  1512. switch job.jobType {
  1513. case dbUpdateHandleFile, dbUpdateShortcutFile:
  1514. changedDirs[filepath.Dir(job.file.Name)] = struct{}{}
  1515. case dbUpdateHandleDir:
  1516. changedDirs[job.file.Name] = struct{}{}
  1517. case dbUpdateHandleSymlink, dbUpdateInvalidate:
  1518. // fsyncing symlinks is only supported by MacOS
  1519. // and invalidated files are db only changes -> no sync
  1520. }
  1521. // For some reason we seem to care about file deletions and
  1522. // content modification, but not about metadata and dirs/symlinks.
  1523. if !job.file.IsInvalid() && job.jobType&(dbUpdateHandleFile|dbUpdateDeleteFile) != 0 {
  1524. found = true
  1525. lastFile = job.file
  1526. }
  1527. if !job.file.IsDeleted() && !job.file.IsInvalid() {
  1528. // Now that the file is finalized, grab possibly updated
  1529. // inode change time from disk into the local FileInfo. We
  1530. // use this change time to check for changes to xattrs etc
  1531. // on next scan.
  1532. if err := f.updateFileInfoChangeTime(&job.file); err != nil {
  1533. // This means on next scan the likely incorrect change time
  1534. // (resp. whatever caused the error) will cause this file to
  1535. // change. Log at info level to leave a trace if a user
  1536. // notices, but no need to warn
  1537. l.Infof("Error updating metadata for %v at database commit: %v", job.file.Name, err)
  1538. }
  1539. }
  1540. job.file.Sequence = 0
  1541. batch.Append(job.file)
  1542. batch.FlushIfFull()
  1543. case <-tick.C:
  1544. batch.Flush()
  1545. }
  1546. }
  1547. batch.Flush()
  1548. }
  1549. // pullScannerRoutine aggregates paths to be scanned after pulling. The scan is
  1550. // scheduled once when scanChan is closed (scanning can not happen during pulling).
  1551. func (f *sendReceiveFolder) pullScannerRoutine(scanChan <-chan string) {
  1552. toBeScanned := make(map[string]struct{})
  1553. for path := range scanChan {
  1554. toBeScanned[path] = struct{}{}
  1555. }
  1556. if len(toBeScanned) != 0 {
  1557. scanList := make([]string, 0, len(toBeScanned))
  1558. for path := range toBeScanned {
  1559. l.Debugln(f, "scheduling scan after pulling for", path)
  1560. scanList = append(scanList, path)
  1561. }
  1562. f.Scan(scanList)
  1563. }
  1564. }
  1565. func (f *sendReceiveFolder) inConflict(current, replacement protocol.Vector) bool {
  1566. if current.Concurrent(replacement) {
  1567. // Obvious case
  1568. return true
  1569. }
  1570. if replacement.Counter(f.shortID) > current.Counter(f.shortID) {
  1571. // The replacement file contains a higher version for ourselves than
  1572. // what we have. This isn't supposed to be possible, since it's only
  1573. // we who can increment that counter. We take it as a sign that
  1574. // something is wrong (our index may have been corrupted or removed)
  1575. // and flag it as a conflict.
  1576. return true
  1577. }
  1578. return false
  1579. }
  1580. func (f *sendReceiveFolder) moveForConflict(name, lastModBy string, scanChan chan<- string) error {
  1581. if isConflict(name) {
  1582. l.Infoln("Conflict for", name, "which is already a conflict copy; not copying again.")
  1583. if err := f.mtimefs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1584. return fmt.Errorf("%s: %w", contextRemovingOldItem, err)
  1585. }
  1586. return nil
  1587. }
  1588. if f.MaxConflicts == 0 {
  1589. if err := f.mtimefs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1590. return fmt.Errorf("%s: %w", contextRemovingOldItem, err)
  1591. }
  1592. return nil
  1593. }
  1594. metricFolderConflictsTotal.WithLabelValues(f.ID).Inc()
  1595. newName := conflictName(name, lastModBy)
  1596. err := f.mtimefs.Rename(name, newName)
  1597. if fs.IsNotExist(err) {
  1598. // We were supposed to move a file away but it does not exist. Either
  1599. // the user has already moved it away, or the conflict was between a
  1600. // remote modification and a local delete. In either way it does not
  1601. // matter, go ahead as if the move succeeded.
  1602. err = nil
  1603. }
  1604. if f.MaxConflicts > -1 {
  1605. matches := existingConflicts(name, f.mtimefs)
  1606. if len(matches) > f.MaxConflicts {
  1607. slices.SortFunc(matches, func(a, b string) int {
  1608. return strings.Compare(b, a)
  1609. })
  1610. for _, match := range matches[f.MaxConflicts:] {
  1611. if gerr := f.mtimefs.Remove(match); gerr != nil {
  1612. l.Debugln(f, "removing extra conflict", gerr)
  1613. }
  1614. }
  1615. }
  1616. }
  1617. if err == nil {
  1618. scanChan <- newName
  1619. }
  1620. return err
  1621. }
  1622. func (f *sendReceiveFolder) newPullError(path string, err error) {
  1623. if errors.Is(err, f.ctx.Err()) {
  1624. // Error because the folder stopped - no point logging/tracking
  1625. return
  1626. }
  1627. f.errorsMut.Lock()
  1628. defer f.errorsMut.Unlock()
  1629. // We might get more than one error report for a file (i.e. error on
  1630. // Write() followed by Close()); we keep the first error as that is
  1631. // probably closer to the root cause.
  1632. if _, ok := f.tempPullErrors[path]; ok {
  1633. return
  1634. }
  1635. // Establish context to differentiate from errors while scanning.
  1636. // Use "syncing" as opposed to "pulling" as the latter might be used
  1637. // for errors occurring specifically in the puller routine.
  1638. errStr := fmt.Sprintf("syncing: %s", err)
  1639. f.tempPullErrors[path] = errStr
  1640. l.Debugf("%v new error for %v: %v", f, path, err)
  1641. }
  1642. // deleteItemOnDisk deletes the file represented by old that is about to be replaced by new.
  1643. func (f *sendReceiveFolder) deleteItemOnDisk(item protocol.FileInfo, scanChan chan<- string) (err error) {
  1644. defer func() {
  1645. if err != nil {
  1646. err = fmt.Errorf("%s: %w", contextRemovingOldItem, err)
  1647. }
  1648. }()
  1649. switch {
  1650. case item.IsDirectory():
  1651. // Directories aren't archived and need special treatment due
  1652. // to potential children.
  1653. return f.deleteDirOnDisk(item.Name, scanChan)
  1654. case !item.IsSymlink() && f.versioner != nil:
  1655. // If we should use versioning, let the versioner archive the
  1656. // file before we replace it. Archiving a non-existent file is not
  1657. // an error.
  1658. // Symlinks aren't archived.
  1659. return f.inWritableDir(f.versioner.Archive, item.Name)
  1660. }
  1661. return f.inWritableDir(f.mtimefs.Remove, item.Name)
  1662. }
  1663. // deleteDirOnDisk attempts to delete a directory. It checks for files/dirs inside
  1664. // the directory and removes them if possible or returns an error if it fails
  1665. func (f *sendReceiveFolder) deleteDirOnDisk(dir string, scanChan chan<- string) error {
  1666. if err := osutil.TraversesSymlink(f.mtimefs, filepath.Dir(dir)); err != nil {
  1667. return err
  1668. }
  1669. if err := f.deleteDirOnDiskHandleChildren(dir, scanChan); err != nil {
  1670. return err
  1671. }
  1672. err := f.inWritableDir(f.mtimefs.Remove, dir)
  1673. if err == nil || fs.IsNotExist(err) {
  1674. // It was removed or it doesn't exist to start with
  1675. return nil
  1676. }
  1677. if _, serr := f.mtimefs.Lstat(dir); serr != nil && !fs.IsPermission(serr) {
  1678. // We get an error just looking at the directory, and it's not a
  1679. // permission problem. Lets assume the error is in fact some variant
  1680. // of "file does not exist" (possibly expressed as some parent being a
  1681. // file and not a directory etc) and that the delete is handled.
  1682. return nil
  1683. }
  1684. return err
  1685. }
  1686. func (f *sendReceiveFolder) deleteDirOnDiskHandleChildren(dir string, scanChan chan<- string) error {
  1687. var dirsToDelete []string
  1688. var hasIgnored, hasKnown, hasToBeScanned, hasReceiveOnlyChanged bool
  1689. var delErr error
  1690. err := f.mtimefs.Walk(dir, func(path string, info fs.FileInfo, err error) error {
  1691. if path == dir {
  1692. return nil
  1693. }
  1694. if err != nil {
  1695. return err
  1696. }
  1697. switch match := f.ignores.Match(path); {
  1698. case match.IsDeletable():
  1699. if info.IsDir() {
  1700. dirsToDelete = append(dirsToDelete, path)
  1701. return nil
  1702. }
  1703. fallthrough
  1704. case fs.IsTemporary(path):
  1705. if err := f.mtimefs.Remove(path); err != nil && delErr == nil {
  1706. delErr = err
  1707. }
  1708. return nil
  1709. case match.IsIgnored():
  1710. hasIgnored = true
  1711. return nil
  1712. }
  1713. cf, ok, err := f.model.sdb.GetDeviceFile(f.folderID, protocol.LocalDeviceID, path)
  1714. if err != nil {
  1715. return err
  1716. }
  1717. switch {
  1718. case !ok || cf.IsDeleted():
  1719. // Something appeared in the dir that we either are not
  1720. // aware of at all or that we think should be deleted
  1721. // -> schedule scan.
  1722. scanChan <- path
  1723. hasToBeScanned = true
  1724. return nil
  1725. case ok && f.Type == config.FolderTypeReceiveOnly && cf.IsReceiveOnlyChanged():
  1726. hasReceiveOnlyChanged = true
  1727. return nil
  1728. }
  1729. diskFile, err := scanner.CreateFileInfo(info, path, f.mtimefs, f.SyncOwnership, f.SyncXattrs, f.XattrFilter)
  1730. if err != nil {
  1731. // Lets just assume the file has changed.
  1732. scanChan <- path
  1733. hasToBeScanned = true
  1734. return nil //nolint:nilerr
  1735. }
  1736. if !cf.IsEquivalentOptional(diskFile, protocol.FileInfoComparison{
  1737. ModTimeWindow: f.modTimeWindow,
  1738. IgnorePerms: f.IgnorePerms,
  1739. IgnoreBlocks: true,
  1740. IgnoreFlags: protocol.LocalAllFlags,
  1741. IgnoreOwnership: !f.SyncOwnership,
  1742. IgnoreXattrs: !f.SyncXattrs,
  1743. }) {
  1744. // File on disk changed compared to what we have in db
  1745. // -> schedule scan.
  1746. scanChan <- path
  1747. hasToBeScanned = true
  1748. return nil
  1749. }
  1750. // Dir contains file that is valid according to db and
  1751. // not ignored -> something weird is going on
  1752. hasKnown = true
  1753. return nil
  1754. })
  1755. if err != nil {
  1756. return err
  1757. }
  1758. for i := range dirsToDelete {
  1759. if err := f.mtimefs.Remove(dirsToDelete[len(dirsToDelete)-1-i]); err != nil && delErr == nil {
  1760. delErr = err
  1761. }
  1762. }
  1763. // "Error precedence":
  1764. // Something changed on disk, check that and maybe all else gets resolved
  1765. if hasToBeScanned {
  1766. return errDirHasToBeScanned
  1767. }
  1768. // Ignored files will never be touched, i.e. this will keep failing until
  1769. // user acts.
  1770. if hasIgnored {
  1771. return errDirHasIgnored
  1772. }
  1773. if hasReceiveOnlyChanged {
  1774. // Pretend we deleted the directory. It will be resurrected as a
  1775. // receive-only changed item on scan.
  1776. scanChan <- dir
  1777. return nil
  1778. }
  1779. if hasKnown {
  1780. return errDirNotEmpty
  1781. }
  1782. // All good, except maybe failing to remove a (?d) ignored item
  1783. return delErr
  1784. }
  1785. // scanIfItemChanged schedules the given file for scanning and returns errModified
  1786. // if it differs from the information in the database. Returns nil if the file has
  1787. // not changed.
  1788. func (f *sendReceiveFolder) scanIfItemChanged(name string, stat fs.FileInfo, item protocol.FileInfo, hasItem bool, fromDelete bool, scanChan chan<- string) (err error) {
  1789. defer func() {
  1790. if errors.Is(err, errModified) {
  1791. scanChan <- name
  1792. }
  1793. }()
  1794. if !hasItem || item.Deleted {
  1795. // The item appeared from nowhere
  1796. return errModified
  1797. }
  1798. // Check that the item on disk is what we expect it to be according
  1799. // to the database. If there's a mismatch here, there might be local
  1800. // changes that we don't know about yet and we should scan before
  1801. // touching the item.
  1802. statItem, err := scanner.CreateFileInfo(stat, item.Name, f.mtimefs, f.SyncOwnership, f.SyncXattrs, f.XattrFilter)
  1803. if err != nil {
  1804. return fmt.Errorf("comparing item on disk to db: %w", err)
  1805. }
  1806. if !statItem.IsEquivalentOptional(item, protocol.FileInfoComparison{
  1807. ModTimeWindow: f.modTimeWindow,
  1808. IgnorePerms: f.IgnorePerms,
  1809. IgnoreBlocks: true,
  1810. IgnoreFlags: protocol.LocalAllFlags,
  1811. IgnoreOwnership: fromDelete || !f.SyncOwnership,
  1812. IgnoreXattrs: fromDelete || !f.SyncXattrs,
  1813. }) {
  1814. return errModified
  1815. }
  1816. return nil
  1817. }
  1818. // checkToBeDeleted makes sure the file on disk is compatible with what there is
  1819. // in the DB before the caller proceeds with actually deleting it.
  1820. // I.e. non-nil error status means "Do not delete!" or "is already deleted".
  1821. func (f *sendReceiveFolder) checkToBeDeleted(file, cur protocol.FileInfo, hasCur bool, scanChan chan<- string) error {
  1822. if err := osutil.TraversesSymlink(f.mtimefs, filepath.Dir(file.Name)); err != nil {
  1823. l.Debugln(f, "not deleting item behind symlink on disk, but update db", file.Name)
  1824. return fs.ErrNotExist
  1825. }
  1826. stat, err := f.mtimefs.Lstat(file.Name)
  1827. deleted := fs.IsNotExist(err) || fs.IsErrCaseConflict(err)
  1828. if !deleted && err != nil {
  1829. return err
  1830. }
  1831. if deleted {
  1832. if hasCur && !cur.Deleted && !cur.IsUnsupported() {
  1833. scanChan <- file.Name
  1834. return errModified
  1835. }
  1836. l.Debugln(f, "not deleting item we don't have, but update db", file.Name)
  1837. return err
  1838. }
  1839. return f.scanIfItemChanged(file.Name, stat, cur, hasCur, true, scanChan)
  1840. }
  1841. // setPlatformData makes adjustments to the metadata that should happen for
  1842. // all types (files, directories, symlinks). This should be one of the last
  1843. // things we do to a file when syncing changes to it.
  1844. func (f *sendReceiveFolder) setPlatformData(file *protocol.FileInfo, name string) error {
  1845. if f.SyncXattrs {
  1846. // Set extended attributes.
  1847. if err := f.mtimefs.SetXattr(name, file.Platform.Xattrs(), f.XattrFilter); errors.Is(err, fs.ErrXattrsNotSupported) {
  1848. l.Debugf("Cannot set xattrs on %q: %v", file.Name, err)
  1849. } else if err != nil {
  1850. return err
  1851. }
  1852. }
  1853. if f.SyncOwnership {
  1854. // Set ownership based on file metadata.
  1855. if err := f.syncOwnership(file, name); err != nil {
  1856. return err
  1857. }
  1858. } else if f.CopyOwnershipFromParent {
  1859. // Copy the parent owner and group.
  1860. if err := f.copyOwnershipFromParent(name); err != nil {
  1861. return err
  1862. }
  1863. }
  1864. return nil
  1865. }
  1866. func (f *sendReceiveFolder) copyOwnershipFromParent(path string) error {
  1867. if build.IsWindows {
  1868. // Can't do anything.
  1869. return nil
  1870. }
  1871. info, err := f.mtimefs.Lstat(filepath.Dir(path))
  1872. if err != nil {
  1873. return fmt.Errorf("copy owner from parent: %w", err)
  1874. }
  1875. if err := f.mtimefs.Lchown(path, strconv.Itoa(info.Owner()), strconv.Itoa(info.Group())); err != nil {
  1876. return fmt.Errorf("copy owner from parent: %w", err)
  1877. }
  1878. return nil
  1879. }
  1880. func (f *sendReceiveFolder) inWritableDir(fn func(string) error, path string) error {
  1881. return inWritableDir(fn, f.mtimefs, path, f.IgnorePerms)
  1882. }
  1883. func (f *sendReceiveFolder) limitedWriteAt(fd io.WriterAt, data []byte, offset int64) error {
  1884. return f.withLimiter(func() error {
  1885. _, err := fd.WriteAt(data, offset)
  1886. return err
  1887. })
  1888. }
  1889. func (f *sendReceiveFolder) withLimiter(fn func() error) error {
  1890. if err := f.writeLimiter.TakeWithContext(f.ctx, 1); err != nil {
  1891. return err
  1892. }
  1893. defer f.writeLimiter.Give(1)
  1894. return fn()
  1895. }
  1896. // updateFileInfoChangeTime updates the inode change time in the FileInfo,
  1897. // because that depends on the current, new, state of the file on disk.
  1898. func (f *sendReceiveFolder) updateFileInfoChangeTime(file *protocol.FileInfo) error {
  1899. info, err := f.mtimefs.Lstat(file.Name)
  1900. if err != nil {
  1901. return err
  1902. }
  1903. if ct := info.InodeChangeTime(); !ct.IsZero() {
  1904. file.InodeChangeNs = ct.UnixNano()
  1905. } else {
  1906. file.InodeChangeNs = 0
  1907. }
  1908. return nil
  1909. }
  1910. // A []FileError is sent as part of an event and will be JSON serialized.
  1911. type FileError struct {
  1912. Path string `json:"path"`
  1913. Err string `json:"error"`
  1914. }
  1915. func conflictName(name, lastModBy string) string {
  1916. ext := filepath.Ext(name)
  1917. return name[:len(name)-len(ext)] + time.Now().Format(".sync-conflict-20060102-150405-") + lastModBy + ext
  1918. }
  1919. func isConflict(name string) bool {
  1920. return strings.Contains(filepath.Base(name), ".sync-conflict-")
  1921. }
  1922. func existingConflicts(name string, fs fs.Filesystem) []string {
  1923. ext := filepath.Ext(name)
  1924. matches, err := fs.Glob(name[:len(name)-len(ext)] + ".sync-conflict-????????-??????*" + ext)
  1925. if err != nil {
  1926. l.Debugln("globbing for conflicts", err)
  1927. }
  1928. return matches
  1929. }