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