folder_sendrecv.go 69 KB

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