folder_sendrecv.go 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239
  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. }