folder_sendrecv.go 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  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. "errors"
  11. "fmt"
  12. "io"
  13. "path/filepath"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/syncthing/syncthing/lib/build"
  19. "github.com/syncthing/syncthing/lib/config"
  20. "github.com/syncthing/syncthing/lib/db"
  21. "github.com/syncthing/syncthing/lib/events"
  22. "github.com/syncthing/syncthing/lib/fs"
  23. "github.com/syncthing/syncthing/lib/ignore"
  24. "github.com/syncthing/syncthing/lib/osutil"
  25. "github.com/syncthing/syncthing/lib/protocol"
  26. "github.com/syncthing/syncthing/lib/scanner"
  27. "github.com/syncthing/syncthing/lib/sha256"
  28. "github.com/syncthing/syncthing/lib/sync"
  29. "github.com/syncthing/syncthing/lib/util"
  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 "dbUpdateShourtcutFile"
  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 *util.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 *util.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: util.NewSemaphore(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 close(scanChan)
  143. metricFolderPulls.WithLabelValues(f.ID).Inc()
  144. ctx, cancel := context.WithCancel(f.ctx)
  145. defer cancel()
  146. go addTimeUntilCancelled(ctx, metricFolderPullSeconds.WithLabelValues(f.ID))
  147. changed := 0
  148. f.errorsMut.Lock()
  149. f.pullErrors = nil
  150. f.errorsMut.Unlock()
  151. var err error
  152. for tries := 0; tries < maxPullerIterations; tries++ {
  153. select {
  154. case <-f.ctx.Done():
  155. return false, f.ctx.Err()
  156. default:
  157. }
  158. // Needs to be set on every loop, as the puller might have set
  159. // it to FolderSyncing during the last iteration.
  160. f.setState(FolderSyncPreparing)
  161. changed, err = f.pullerIteration(scanChan)
  162. if err != nil {
  163. return false, err
  164. }
  165. l.Debugln(f, "changed", changed, "on try", tries+1)
  166. if changed == 0 {
  167. // No files were changed by the puller, so we are in
  168. // sync (except for unrecoverable stuff like invalid
  169. // filenames on windows).
  170. break
  171. }
  172. }
  173. f.errorsMut.Lock()
  174. pullErrNum := len(f.tempPullErrors)
  175. if pullErrNum > 0 {
  176. f.pullErrors = make([]FileError, 0, len(f.tempPullErrors))
  177. for path, err := range f.tempPullErrors {
  178. l.Infof("Puller (folder %s, item %q): %v", f.Description(), path, err)
  179. f.pullErrors = append(f.pullErrors, FileError{
  180. Err: err,
  181. Path: path,
  182. })
  183. }
  184. f.tempPullErrors = nil
  185. }
  186. f.errorsMut.Unlock()
  187. if pullErrNum > 0 {
  188. l.Infof("%v: Failed to sync %v items", f.Description(), pullErrNum)
  189. f.evLogger.Log(events.FolderErrors, map[string]interface{}{
  190. "folder": f.folderID,
  191. "errors": f.Errors(),
  192. })
  193. }
  194. return changed == 0, nil
  195. }
  196. // pullerIteration runs a single puller iteration for the given folder and
  197. // returns the number items that should have been synced (even those that
  198. // might have failed). One puller iteration handles all files currently
  199. // flagged as needed in the folder.
  200. func (f *sendReceiveFolder) pullerIteration(scanChan chan<- string) (int, error) {
  201. f.errorsMut.Lock()
  202. f.tempPullErrors = make(map[string]string)
  203. f.errorsMut.Unlock()
  204. snap, err := f.dbSnapshot()
  205. if err != nil {
  206. return 0, err
  207. }
  208. defer snap.Release()
  209. pullChan := make(chan pullBlockState)
  210. copyChan := make(chan copyBlocksState)
  211. finisherChan := make(chan *sharedPullerState)
  212. dbUpdateChan := make(chan dbUpdateJob)
  213. pullWg := sync.NewWaitGroup()
  214. copyWg := sync.NewWaitGroup()
  215. doneWg := sync.NewWaitGroup()
  216. updateWg := sync.NewWaitGroup()
  217. l.Debugln(f, "copiers:", f.Copiers, "pullerPendingKiB:", f.PullerMaxPendingKiB)
  218. updateWg.Add(1)
  219. go func() {
  220. // dbUpdaterRoutine finishes when dbUpdateChan is closed
  221. f.dbUpdaterRoutine(dbUpdateChan)
  222. updateWg.Done()
  223. }()
  224. for i := 0; i < f.Copiers; i++ {
  225. copyWg.Add(1)
  226. go func() {
  227. // copierRoutine finishes when copyChan is closed
  228. f.copierRoutine(copyChan, pullChan, finisherChan)
  229. copyWg.Done()
  230. }()
  231. }
  232. pullWg.Add(1)
  233. go func() {
  234. // pullerRoutine finishes when pullChan is closed
  235. f.pullerRoutine(snap, pullChan, finisherChan)
  236. pullWg.Done()
  237. }()
  238. doneWg.Add(1)
  239. // finisherRoutine finishes when finisherChan is closed
  240. go func() {
  241. f.finisherRoutine(snap, finisherChan, dbUpdateChan, scanChan)
  242. doneWg.Done()
  243. }()
  244. changed, fileDeletions, dirDeletions, err := f.processNeeded(snap, dbUpdateChan, copyChan, scanChan)
  245. // Signal copy and puller routines that we are done with the in data for
  246. // this iteration. Wait for them to finish.
  247. close(copyChan)
  248. copyWg.Wait()
  249. close(pullChan)
  250. pullWg.Wait()
  251. // Signal the finisher chan that there will be no more input and wait
  252. // for it to finish.
  253. close(finisherChan)
  254. doneWg.Wait()
  255. if err == nil {
  256. f.processDeletions(fileDeletions, dirDeletions, snap, dbUpdateChan, scanChan)
  257. }
  258. // Wait for db updates and scan scheduling to complete
  259. close(dbUpdateChan)
  260. updateWg.Wait()
  261. f.queue.Reset()
  262. return changed, err
  263. }
  264. func (f *sendReceiveFolder) processNeeded(snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, copyChan chan<- copyBlocksState, scanChan chan<- string) (int, map[string]protocol.FileInfo, []protocol.FileInfo, error) {
  265. changed := 0
  266. var dirDeletions []protocol.FileInfo
  267. fileDeletions := map[string]protocol.FileInfo{}
  268. buckets := map[string][]protocol.FileInfo{}
  269. // Iterate the list of items that we need and sort them into piles.
  270. // Regular files to pull goes into the file queue, everything else
  271. // (directories, symlinks and deletes) goes into the "process directly"
  272. // pile.
  273. snap.WithNeed(protocol.LocalDeviceID, func(intf protocol.FileIntf) bool {
  274. select {
  275. case <-f.ctx.Done():
  276. return false
  277. default:
  278. }
  279. if f.IgnoreDelete && intf.IsDeleted() {
  280. l.Debugln(f, "ignore file deletion (config)", intf.FileName())
  281. return true
  282. }
  283. changed++
  284. file := intf.(protocol.FileInfo)
  285. switch {
  286. case f.ignores.ShouldIgnore(file.Name):
  287. file.SetIgnored()
  288. l.Debugln(f, "Handling ignored file", file)
  289. dbUpdateChan <- dbUpdateJob{file, dbUpdateInvalidate}
  290. case build.IsWindows && fs.WindowsInvalidFilename(file.Name) != nil:
  291. if file.IsDeleted() {
  292. // Just pretend we deleted it, no reason to create an error
  293. // about a deleted file that we can't have anyway.
  294. // Reason we need it in the first place is, that it was
  295. // ignored at some point.
  296. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  297. } else {
  298. // We can't pull an invalid file. Grab the error again since
  299. // we couldn't assign it directly in the case clause.
  300. f.newPullError(file.Name, fs.WindowsInvalidFilename(file.Name))
  301. // No reason to retry for this
  302. changed--
  303. }
  304. case file.IsDeleted():
  305. if file.IsDirectory() {
  306. // Perform directory deletions at the end, as we may have
  307. // files to delete inside them before we get to that point.
  308. dirDeletions = append(dirDeletions, file)
  309. } else if file.IsSymlink() {
  310. f.deleteFile(file, snap, dbUpdateChan, scanChan)
  311. } else {
  312. df, ok := snap.Get(protocol.LocalDeviceID, file.Name)
  313. // Local file can be already deleted, but with a lower version
  314. // number, hence the deletion coming in again as part of
  315. // WithNeed, furthermore, the file can simply be of the wrong
  316. // type if we haven't yet managed to pull it.
  317. if ok && !df.IsDeleted() && !df.IsSymlink() && !df.IsDirectory() && !df.IsInvalid() {
  318. fileDeletions[file.Name] = file
  319. // Put files into buckets per first hash
  320. key := string(df.BlocksHash)
  321. buckets[key] = append(buckets[key], df)
  322. } else {
  323. f.deleteFileWithCurrent(file, df, ok, dbUpdateChan, scanChan)
  324. }
  325. }
  326. case file.Type == protocol.FileInfoTypeFile:
  327. curFile, hasCurFile := snap.Get(protocol.LocalDeviceID, file.Name)
  328. if hasCurFile && file.BlocksEqual(curFile) {
  329. // We are supposed to copy the entire file, and then fetch nothing. We
  330. // are only updating metadata, so we don't actually *need* to make the
  331. // copy.
  332. f.shortcutFile(file, dbUpdateChan)
  333. } else {
  334. // Queue files for processing after directories and symlinks.
  335. f.queue.Push(file.Name, file.Size, file.ModTime())
  336. }
  337. case build.IsWindows && file.IsSymlink():
  338. if err := f.handleSymlinkCheckExisting(file, snap, scanChan); err != nil {
  339. f.newPullError(file.Name, fmt.Errorf("handling unsupported symlink: %w", err))
  340. break
  341. }
  342. file.SetUnsupported()
  343. l.Debugln(f, "Invalidating symlink (unsupported)", file.Name)
  344. dbUpdateChan <- dbUpdateJob{file, dbUpdateInvalidate}
  345. case file.IsDirectory() && !file.IsSymlink():
  346. l.Debugln(f, "Handling directory", file.Name)
  347. if f.checkParent(file.Name, scanChan) {
  348. f.handleDir(file, snap, dbUpdateChan, scanChan)
  349. }
  350. case file.IsSymlink():
  351. l.Debugln(f, "Handling symlink", file.Name)
  352. if f.checkParent(file.Name, scanChan) {
  353. f.handleSymlink(file, snap, dbUpdateChan, scanChan)
  354. }
  355. default:
  356. l.Warnln(file)
  357. panic("unhandleable item type, can't happen")
  358. }
  359. return true
  360. })
  361. select {
  362. case <-f.ctx.Done():
  363. return changed, nil, nil, f.ctx.Err()
  364. default:
  365. }
  366. // Now do the file queue. Reorder it according to configuration.
  367. switch f.Order {
  368. case config.PullOrderRandom:
  369. f.queue.Shuffle()
  370. case config.PullOrderAlphabetic:
  371. // The queue is already in alphabetic order.
  372. case config.PullOrderSmallestFirst:
  373. f.queue.SortSmallestFirst()
  374. case config.PullOrderLargestFirst:
  375. f.queue.SortLargestFirst()
  376. case config.PullOrderOldestFirst:
  377. f.queue.SortOldestFirst()
  378. case config.PullOrderNewestFirst:
  379. f.queue.SortNewestFirst()
  380. }
  381. // Process the file queue.
  382. nextFile:
  383. for {
  384. select {
  385. case <-f.ctx.Done():
  386. return changed, fileDeletions, dirDeletions, f.ctx.Err()
  387. default:
  388. }
  389. fileName, ok := f.queue.Pop()
  390. if !ok {
  391. break
  392. }
  393. fi, ok := snap.GetGlobal(fileName)
  394. if !ok {
  395. // File is no longer in the index. Mark it as done and drop it.
  396. f.queue.Done(fileName)
  397. continue
  398. }
  399. if fi.IsDeleted() || fi.IsInvalid() || fi.Type != protocol.FileInfoTypeFile {
  400. // The item has changed type or status in the index while we
  401. // were processing directories above.
  402. f.queue.Done(fileName)
  403. continue
  404. }
  405. if !f.checkParent(fi.Name, scanChan) {
  406. f.queue.Done(fileName)
  407. continue
  408. }
  409. // Check our list of files to be removed for a match, in which case
  410. // we can just do a rename instead.
  411. key := string(fi.BlocksHash)
  412. for candidate, ok := popCandidate(buckets, key); ok; candidate, ok = popCandidate(buckets, key) {
  413. // candidate is our current state of the file, where as the
  414. // desired state with the delete bit set is in the deletion
  415. // map.
  416. desired := fileDeletions[candidate.Name]
  417. if err := f.renameFile(candidate, desired, fi, snap, dbUpdateChan, scanChan); err != nil {
  418. l.Debugf("rename shortcut for %s failed: %s", fi.Name, err.Error())
  419. // Failed to rename, try next one.
  420. continue
  421. }
  422. // Remove the pending deletion (as we performed it by renaming)
  423. delete(fileDeletions, candidate.Name)
  424. f.queue.Done(fileName)
  425. continue nextFile
  426. }
  427. devices := snap.Availability(fileName)
  428. for _, dev := range devices {
  429. if _, ok := f.model.Connection(dev); ok {
  430. // Handle the file normally, by copying and pulling, etc.
  431. f.handleFile(fi, snap, copyChan)
  432. continue nextFile
  433. }
  434. }
  435. f.newPullError(fileName, errNotAvailable)
  436. f.queue.Done(fileName)
  437. }
  438. return changed, fileDeletions, dirDeletions, nil
  439. }
  440. func popCandidate(buckets map[string][]protocol.FileInfo, key string) (protocol.FileInfo, bool) {
  441. cands := buckets[key]
  442. if len(cands) == 0 {
  443. return protocol.FileInfo{}, false
  444. }
  445. buckets[key] = cands[1:]
  446. return cands[0], true
  447. }
  448. func (f *sendReceiveFolder) processDeletions(fileDeletions map[string]protocol.FileInfo, dirDeletions []protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  449. for _, file := range fileDeletions {
  450. select {
  451. case <-f.ctx.Done():
  452. return
  453. default:
  454. }
  455. f.deleteFile(file, snap, dbUpdateChan, scanChan)
  456. }
  457. // Process in reverse order to delete depth first
  458. for i := range dirDeletions {
  459. select {
  460. case <-f.ctx.Done():
  461. return
  462. default:
  463. }
  464. dir := dirDeletions[len(dirDeletions)-i-1]
  465. l.Debugln(f, "Deleting dir", dir.Name)
  466. f.deleteDir(dir, snap, dbUpdateChan, scanChan)
  467. }
  468. }
  469. // handleDir creates or updates the given directory
  470. func (f *sendReceiveFolder) handleDir(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  471. // Used in the defer closure below, updated by the function body. Take
  472. // care not declare another err.
  473. var err error
  474. f.evLogger.Log(events.ItemStarted, map[string]string{
  475. "folder": f.folderID,
  476. "item": file.Name,
  477. "type": "dir",
  478. "action": "update",
  479. })
  480. defer func() {
  481. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  482. "folder": f.folderID,
  483. "item": file.Name,
  484. "error": events.Error(err),
  485. "type": "dir",
  486. "action": "update",
  487. })
  488. }()
  489. mode := fs.FileMode(file.Permissions & 0o777)
  490. if f.IgnorePerms || file.NoPermissions {
  491. mode = 0o777
  492. }
  493. if shouldDebug() {
  494. curFile, _ := snap.Get(protocol.LocalDeviceID, file.Name)
  495. l.Debugf("need dir\n\t%v\n\t%v", file, curFile)
  496. }
  497. info, err := f.mtimefs.Lstat(file.Name)
  498. switch {
  499. // There is already something under that name, we need to handle that.
  500. // Unless it already is a directory, as we only track permissions,
  501. // that don't result in a conflict.
  502. case err == nil && !info.IsDir():
  503. // Check that it is what we have in the database.
  504. curFile, hasCurFile := snap.Get(protocol.LocalDeviceID, file.Name)
  505. if err := f.scanIfItemChanged(file.Name, info, curFile, hasCurFile, scanChan); err != nil {
  506. f.newPullError(file.Name, fmt.Errorf("handling dir: %w", err))
  507. return
  508. }
  509. // Remove it to replace with the dir.
  510. if !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  511. // The new file has been changed in conflict with the existing one. We
  512. // should file it away as a conflict instead of just removing or
  513. // archiving.
  514. // Symlinks aren't checked for conflicts.
  515. err = f.inWritableDir(func(name string) error {
  516. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  517. }, curFile.Name)
  518. } else {
  519. err = f.deleteItemOnDisk(curFile, snap, scanChan)
  520. }
  521. if err != nil {
  522. f.newPullError(file.Name, err)
  523. return
  524. }
  525. fallthrough
  526. // The directory doesn't exist, so we create it with the right
  527. // mode bits from the start.
  528. case err != nil && fs.IsNotExist(err):
  529. // We declare a function that acts on only the path name, so
  530. // we can pass it to InWritableDir. We use a regular Mkdir and
  531. // not MkdirAll because the parent should already exist.
  532. mkdir := func(path string) error {
  533. err = f.mtimefs.Mkdir(path, mode)
  534. if err != nil {
  535. return err
  536. }
  537. // Set the platform data (ownership, xattrs, etc).
  538. if err := f.setPlatformData(&file, path); err != nil {
  539. return err
  540. }
  541. if f.IgnorePerms || file.NoPermissions {
  542. return nil
  543. }
  544. // Stat the directory so we can check its permissions.
  545. info, err := f.mtimefs.Lstat(path)
  546. if err != nil {
  547. return err
  548. }
  549. // Mask for the bits we want to preserve and add them in to the
  550. // directories permissions.
  551. return f.mtimefs.Chmod(path, mode|(info.Mode()&retainBits))
  552. }
  553. if err = f.inWritableDir(mkdir, file.Name); err == nil {
  554. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  555. } else {
  556. f.newPullError(file.Name, fmt.Errorf("creating directory: %w", err))
  557. }
  558. return
  559. // Weird error when stat()'ing the dir. Probably won't work to do
  560. // anything else with it if we can't even stat() it.
  561. case err != nil:
  562. f.newPullError(file.Name, fmt.Errorf("checking file to be replaced: %w", err))
  563. return
  564. }
  565. // The directory already exists, so we just correct the metadata. (We
  566. // don't handle modification times on directories, because that sucks...)
  567. // It's OK to change mode bits on stuff within non-writable directories.
  568. if !f.IgnorePerms && !file.NoPermissions {
  569. if err := f.mtimefs.Chmod(file.Name, mode|(info.Mode()&retainBits)); err != nil {
  570. f.newPullError(file.Name, fmt.Errorf("handling dir (setting permissions): %w", err))
  571. return
  572. }
  573. if err := f.setPlatformData(&file, file.Name); err != nil {
  574. f.newPullError(file.Name, fmt.Errorf("handling dir (setting metadata): %w", err))
  575. return
  576. }
  577. }
  578. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  579. }
  580. // checkParent verifies that the thing we are handling lives inside a directory,
  581. // and not a symlink or regular file. It also resurrects missing parent dirs.
  582. func (f *sendReceiveFolder) checkParent(file string, scanChan chan<- string) bool {
  583. parent := filepath.Dir(file)
  584. if err := osutil.TraversesSymlink(f.mtimefs, parent); err != nil {
  585. f.newPullError(file, fmt.Errorf("checking parent dirs: %w", err))
  586. return false
  587. }
  588. // issues #114 and #4475: This works around a race condition
  589. // between two devices, when one device removes a directory and the
  590. // other creates a file in it. However that happens, we end up with
  591. // a directory for "foo" with the delete bit, but a file "foo/bar"
  592. // that we want to sync. We never create the directory, and hence
  593. // fail to create the file and end up looping forever on it. This
  594. // breaks that by creating the directory and scheduling a scan,
  595. // where it will be found and the delete bit on it removed. The
  596. // user can then clean up as they like...
  597. // This can also occur if an entire tree structure was deleted, but only
  598. // a leave has been scanned.
  599. //
  600. // And if this is an encrypted folder:
  601. // Encrypted files have made-up filenames with two synthetic parent
  602. // directories which don't have any meaning. Create those if necessary.
  603. if _, err := f.mtimefs.Lstat(parent); !fs.IsNotExist(err) {
  604. l.Debugf("%v parent not missing %v", f, file)
  605. return true
  606. }
  607. l.Debugf("%v creating parent directory of %v", f, file)
  608. if err := f.mtimefs.MkdirAll(parent, 0o755); err != nil {
  609. f.newPullError(file, fmt.Errorf("creating parent dir: %w", err))
  610. return false
  611. }
  612. if f.Type != config.FolderTypeReceiveEncrypted {
  613. scanChan <- parent
  614. }
  615. return true
  616. }
  617. // handleSymlink creates or updates the given symlink
  618. func (f *sendReceiveFolder) handleSymlink(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  619. // Used in the defer closure below, updated by the function body. Take
  620. // care not declare another err.
  621. var err error
  622. f.evLogger.Log(events.ItemStarted, map[string]string{
  623. "folder": f.folderID,
  624. "item": file.Name,
  625. "type": "symlink",
  626. "action": "update",
  627. })
  628. defer func() {
  629. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  630. "folder": f.folderID,
  631. "item": file.Name,
  632. "error": events.Error(err),
  633. "type": "symlink",
  634. "action": "update",
  635. })
  636. }()
  637. if shouldDebug() {
  638. curFile, _ := snap.Get(protocol.LocalDeviceID, file.Name)
  639. l.Debugf("need symlink\n\t%v\n\t%v", file, curFile)
  640. }
  641. if file.SymlinkTarget == "" {
  642. // Index entry from a Syncthing predating the support for including
  643. // the link target in the index entry. We log this as an error.
  644. f.newPullError(file.Name, errIncompatibleSymlink)
  645. return
  646. }
  647. if err = f.handleSymlinkCheckExisting(file, snap, scanChan); err != nil {
  648. f.newPullError(file.Name, fmt.Errorf("handling symlink: %w", err))
  649. return
  650. }
  651. // We declare a function that acts on only the path name, so
  652. // we can pass it to InWritableDir.
  653. createLink := func(path string) error {
  654. if err := f.mtimefs.CreateSymlink(file.SymlinkTarget, path); err != nil {
  655. return err
  656. }
  657. return f.setPlatformData(&file, path)
  658. }
  659. if err = f.inWritableDir(createLink, file.Name); err == nil {
  660. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleSymlink}
  661. } else {
  662. f.newPullError(file.Name, fmt.Errorf("symlink create: %w", err))
  663. }
  664. }
  665. func (f *sendReceiveFolder) handleSymlinkCheckExisting(file protocol.FileInfo, snap *db.Snapshot, scanChan chan<- string) error {
  666. // If there is already something under that name, we need to handle that.
  667. info, err := f.mtimefs.Lstat(file.Name)
  668. if err != nil {
  669. if fs.IsNotExist(err) {
  670. return nil
  671. }
  672. return err
  673. }
  674. // Check that it is what we have in the database.
  675. curFile, hasCurFile := snap.Get(protocol.LocalDeviceID, file.Name)
  676. if err := f.scanIfItemChanged(file.Name, info, curFile, hasCurFile, scanChan); err != nil {
  677. return err
  678. }
  679. // Remove it to replace with the symlink. This also handles the
  680. // "change symlink type" path.
  681. if !curFile.IsDirectory() && !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  682. // The new file has been changed in conflict with the existing one. We
  683. // should file it away as a conflict instead of just removing or
  684. // archiving.
  685. // Directories and symlinks aren't checked for conflicts.
  686. return f.inWritableDir(func(name string) error {
  687. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  688. }, curFile.Name)
  689. } else {
  690. return f.deleteItemOnDisk(curFile, snap, scanChan)
  691. }
  692. }
  693. // deleteDir attempts to remove a directory that was deleted on a remote
  694. func (f *sendReceiveFolder) deleteDir(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  695. // Used in the defer closure below, updated by the function body. Take
  696. // care not declare another err.
  697. var err error
  698. f.evLogger.Log(events.ItemStarted, map[string]string{
  699. "folder": f.folderID,
  700. "item": file.Name,
  701. "type": "dir",
  702. "action": "delete",
  703. })
  704. defer func() {
  705. if err != nil {
  706. f.newPullError(file.Name, fmt.Errorf("delete dir: %w", err))
  707. }
  708. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  709. "folder": f.folderID,
  710. "item": file.Name,
  711. "error": events.Error(err),
  712. "type": "dir",
  713. "action": "delete",
  714. })
  715. }()
  716. cur, hasCur := snap.Get(protocol.LocalDeviceID, file.Name)
  717. if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
  718. if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
  719. err = nil
  720. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  721. }
  722. return
  723. }
  724. if err = f.deleteDirOnDisk(file.Name, snap, scanChan); err != nil {
  725. return
  726. }
  727. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  728. }
  729. // deleteFile attempts to delete the given file
  730. func (f *sendReceiveFolder) deleteFile(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  731. cur, hasCur := snap.Get(protocol.LocalDeviceID, file.Name)
  732. f.deleteFileWithCurrent(file, cur, hasCur, dbUpdateChan, scanChan)
  733. }
  734. func (f *sendReceiveFolder) deleteFileWithCurrent(file, cur protocol.FileInfo, hasCur bool, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  735. // Used in the defer closure below, updated by the function body. Take
  736. // care not declare another err.
  737. var err error
  738. l.Debugln(f, "Deleting file", file.Name)
  739. f.evLogger.Log(events.ItemStarted, map[string]string{
  740. "folder": f.folderID,
  741. "item": file.Name,
  742. "type": "file",
  743. "action": "delete",
  744. })
  745. defer func() {
  746. if err != nil {
  747. f.newPullError(file.Name, fmt.Errorf("delete file: %w", err))
  748. }
  749. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  750. "folder": f.folderID,
  751. "item": file.Name,
  752. "error": events.Error(err),
  753. "type": "file",
  754. "action": "delete",
  755. })
  756. }()
  757. if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
  758. if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
  759. err = nil
  760. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  761. }
  762. return
  763. }
  764. // We are asked to delete a file, but what we have on disk and in db
  765. // is a directory. Something is wrong here, should probably not happen.
  766. if cur.IsDirectory() {
  767. err = errUnexpectedDirOnFileDel
  768. return
  769. }
  770. if f.inConflict(cur.Version, file.Version) {
  771. // There is a conflict here, which shouldn't happen as deletions
  772. // always lose. Merge the version vector of the file we have
  773. // locally and commit it to db to resolve the conflict.
  774. cur.Version = cur.Version.Merge(file.Version)
  775. dbUpdateChan <- dbUpdateJob{cur, dbUpdateHandleFile}
  776. return
  777. }
  778. if f.versioner != nil && !cur.IsSymlink() {
  779. err = f.inWritableDir(f.versioner.Archive, file.Name)
  780. } else {
  781. err = f.inWritableDir(f.mtimefs.Remove, file.Name)
  782. }
  783. if err == nil || fs.IsNotExist(err) {
  784. // It was removed or it doesn't exist to start with
  785. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  786. return
  787. }
  788. if _, serr := f.mtimefs.Lstat(file.Name); serr != nil && !fs.IsPermission(serr) {
  789. // We get an error just looking at the file, and it's not a permission
  790. // problem. Lets assume the error is in fact some variant of "file
  791. // does not exist" (possibly expressed as some parent being a file and
  792. // not a directory etc) and that the delete is handled.
  793. err = nil
  794. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  795. }
  796. }
  797. // renameFile attempts to rename an existing file to a destination
  798. // and set the right attributes on it.
  799. func (f *sendReceiveFolder) renameFile(cur, source, target protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  800. // Used in the defer closure below, updated by the function body. Take
  801. // care not declare another err.
  802. var err error
  803. f.evLogger.Log(events.ItemStarted, map[string]string{
  804. "folder": f.folderID,
  805. "item": source.Name,
  806. "type": "file",
  807. "action": "delete",
  808. })
  809. f.evLogger.Log(events.ItemStarted, map[string]string{
  810. "folder": f.folderID,
  811. "item": target.Name,
  812. "type": "file",
  813. "action": "update",
  814. })
  815. defer func() {
  816. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  817. "folder": f.folderID,
  818. "item": source.Name,
  819. "error": events.Error(err),
  820. "type": "file",
  821. "action": "delete",
  822. })
  823. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  824. "folder": f.folderID,
  825. "item": target.Name,
  826. "error": events.Error(err),
  827. "type": "file",
  828. "action": "update",
  829. })
  830. }()
  831. l.Debugln(f, "taking rename shortcut", source.Name, "->", target.Name)
  832. // Check that source is compatible with what we have in the DB
  833. if err = f.checkToBeDeleted(source, cur, true, scanChan); err != nil {
  834. return err
  835. }
  836. // Check that the target corresponds to what we have in the DB
  837. curTarget, ok := snap.Get(protocol.LocalDeviceID, target.Name)
  838. switch stat, serr := f.mtimefs.Lstat(target.Name); {
  839. case serr != nil:
  840. var caseErr *fs.ErrCaseConflict
  841. switch {
  842. case errors.As(serr, &caseErr):
  843. if caseErr.Real != source.Name {
  844. err = serr
  845. break
  846. }
  847. fallthrough // This is a case only rename
  848. case fs.IsNotExist(serr):
  849. if !ok || curTarget.IsDeleted() {
  850. break
  851. }
  852. scanChan <- target.Name
  853. err = errModified
  854. default:
  855. // We can't check whether the file changed as compared to the db,
  856. // do not delete.
  857. err = serr
  858. }
  859. case !ok:
  860. // Target appeared from nowhere
  861. scanChan <- target.Name
  862. err = errModified
  863. default:
  864. var fi protocol.FileInfo
  865. if fi, err = scanner.CreateFileInfo(stat, target.Name, f.mtimefs, f.SyncOwnership, f.SyncXattrs, f.XattrFilter); err == nil {
  866. if !fi.IsEquivalentOptional(curTarget, protocol.FileInfoComparison{
  867. ModTimeWindow: f.modTimeWindow,
  868. IgnorePerms: f.IgnorePerms,
  869. IgnoreBlocks: true,
  870. IgnoreFlags: protocol.LocalAllFlags,
  871. IgnoreOwnership: !f.SyncOwnership,
  872. IgnoreXattrs: !f.SyncXattrs,
  873. }) {
  874. // Target changed
  875. scanChan <- target.Name
  876. err = errModified
  877. }
  878. }
  879. }
  880. if err != nil {
  881. return err
  882. }
  883. tempName := fs.TempName(target.Name)
  884. if f.versioner != nil {
  885. err = f.CheckAvailableSpace(uint64(source.Size))
  886. if err == nil {
  887. err = osutil.Copy(f.CopyRangeMethod, f.mtimefs, f.mtimefs, source.Name, tempName)
  888. if err == nil {
  889. err = f.inWritableDir(f.versioner.Archive, source.Name)
  890. }
  891. }
  892. } else {
  893. err = osutil.RenameOrCopy(f.CopyRangeMethod, f.mtimefs, f.mtimefs, source.Name, tempName)
  894. }
  895. if err != nil {
  896. return err
  897. }
  898. blockStatsMut.Lock()
  899. minBlocksPerBlock := target.BlockSize() / protocol.MinBlockSize
  900. blockStats["total"] += len(target.Blocks) * minBlocksPerBlock
  901. blockStats["renamed"] += len(target.Blocks) * minBlocksPerBlock
  902. blockStatsMut.Unlock()
  903. // The file was renamed, so we have handled both the necessary delete
  904. // of the source and the creation of the target temp file. Fix-up the metadata,
  905. // update the local index of the target file and rename from temp to real name.
  906. if err = f.performFinish(target, curTarget, true, tempName, snap, dbUpdateChan, scanChan); err != nil {
  907. return err
  908. }
  909. dbUpdateChan <- dbUpdateJob{source, dbUpdateDeleteFile}
  910. return nil
  911. }
  912. // This is the flow of data and events here, I think...
  913. //
  914. // +-----------------------+
  915. // | | - - - - > ItemStarted
  916. // | handleFile | - - - - > ItemFinished (on shortcuts)
  917. // | |
  918. // +-----------------------+
  919. // |
  920. // | copyChan (copyBlocksState; unless shortcut taken)
  921. // |
  922. // | +-----------------------+
  923. // | | +-----------------------+
  924. // +--->| | |
  925. // | | copierRoutine |
  926. // +-| |
  927. // +-----------------------+
  928. // |
  929. // | pullChan (sharedPullerState)
  930. // |
  931. // | +-----------------------+
  932. // | | +-----------------------+
  933. // +-->| | |
  934. // | | pullerRoutine |
  935. // +-| |
  936. // +-----------------------+
  937. // |
  938. // | finisherChan (sharedPullerState)
  939. // |
  940. // | +-----------------------+
  941. // | | |
  942. // +-->| finisherRoutine | - - - - > ItemFinished
  943. // | |
  944. // +-----------------------+
  945. // handleFile queues the copies and pulls as necessary for a single new or
  946. // changed file.
  947. func (f *sendReceiveFolder) handleFile(file protocol.FileInfo, snap *db.Snapshot, copyChan chan<- copyBlocksState) {
  948. curFile, hasCurFile := snap.Get(protocol.LocalDeviceID, file.Name)
  949. have, _ := blockDiff(curFile.Blocks, file.Blocks)
  950. tempName := fs.TempName(file.Name)
  951. populateOffsets(file.Blocks)
  952. blocks := append([]protocol.BlockInfo{}, file.Blocks...)
  953. reused := make([]int, 0, len(file.Blocks))
  954. if f.Type != config.FolderTypeReceiveEncrypted {
  955. blocks, reused = f.reuseBlocks(blocks, reused, file, tempName)
  956. }
  957. // The sharedpullerstate will know which flags to use when opening the
  958. // temp file depending if we are reusing any blocks or not.
  959. if len(reused) == 0 {
  960. // Otherwise, discard the file ourselves in order for the
  961. // sharedpuller not to panic when it fails to exclusively create a
  962. // file which already exists
  963. f.inWritableDir(f.mtimefs.Remove, tempName)
  964. }
  965. // Reorder blocks
  966. blocks = f.blockPullReorderer.Reorder(blocks)
  967. f.evLogger.Log(events.ItemStarted, map[string]string{
  968. "folder": f.folderID,
  969. "item": file.Name,
  970. "type": "file",
  971. "action": "update",
  972. })
  973. s := newSharedPullerState(file, f.mtimefs, f.folderID, tempName, blocks, reused, f.IgnorePerms || file.NoPermissions, hasCurFile, curFile, !f.DisableSparseFiles, !f.DisableFsync)
  974. l.Debugf("%v need file %s; copy %d, reused %v", f, file.Name, len(blocks), len(reused))
  975. cs := copyBlocksState{
  976. sharedPullerState: s,
  977. blocks: blocks,
  978. have: len(have),
  979. }
  980. copyChan <- cs
  981. }
  982. func (f *sendReceiveFolder) reuseBlocks(blocks []protocol.BlockInfo, reused []int, file protocol.FileInfo, tempName string) ([]protocol.BlockInfo, []int) {
  983. // Check for an old temporary file which might have some blocks we could
  984. // reuse.
  985. tempBlocks, err := scanner.HashFile(f.ctx, f.ID, f.mtimefs, tempName, file.BlockSize(), nil, false)
  986. if err != nil {
  987. var caseErr *fs.ErrCaseConflict
  988. if errors.As(err, &caseErr) {
  989. if rerr := f.mtimefs.Rename(caseErr.Real, tempName); rerr == nil {
  990. tempBlocks, err = scanner.HashFile(f.ctx, f.ID, f.mtimefs, tempName, file.BlockSize(), nil, false)
  991. }
  992. }
  993. }
  994. if err != nil {
  995. return blocks, reused
  996. }
  997. // Check for any reusable blocks in the temp file
  998. tempCopyBlocks, _ := blockDiff(tempBlocks, file.Blocks)
  999. // block.String() returns a string unique to the block
  1000. existingBlocks := make(map[string]struct{}, len(tempCopyBlocks))
  1001. for _, block := range tempCopyBlocks {
  1002. existingBlocks[block.String()] = struct{}{}
  1003. }
  1004. // Since the blocks are already there, we don't need to get them.
  1005. blocks = blocks[:0]
  1006. for i, block := range file.Blocks {
  1007. _, ok := existingBlocks[block.String()]
  1008. if !ok {
  1009. blocks = append(blocks, block)
  1010. } else {
  1011. reused = append(reused, i)
  1012. }
  1013. }
  1014. return blocks, reused
  1015. }
  1016. // blockDiff returns lists of common and missing (to transform src into tgt)
  1017. // blocks. Both block lists must have been created with the same block size.
  1018. func blockDiff(src, tgt []protocol.BlockInfo) ([]protocol.BlockInfo, []protocol.BlockInfo) {
  1019. if len(tgt) == 0 {
  1020. return nil, nil
  1021. }
  1022. if len(src) == 0 {
  1023. // Copy the entire file
  1024. return nil, tgt
  1025. }
  1026. have := make([]protocol.BlockInfo, 0, len(src))
  1027. need := make([]protocol.BlockInfo, 0, len(tgt))
  1028. for i := range tgt {
  1029. if i >= len(src) {
  1030. return have, append(need, tgt[i:]...)
  1031. }
  1032. if !bytes.Equal(tgt[i].Hash, src[i].Hash) {
  1033. // Copy differing block
  1034. need = append(need, tgt[i])
  1035. } else {
  1036. have = append(have, tgt[i])
  1037. }
  1038. }
  1039. return have, need
  1040. }
  1041. // populateOffsets sets the Offset field on each block
  1042. func populateOffsets(blocks []protocol.BlockInfo) {
  1043. var offset int64
  1044. for i := range blocks {
  1045. blocks[i].Offset = offset
  1046. offset += int64(blocks[i].Size)
  1047. }
  1048. }
  1049. // shortcutFile sets file metadata, when that's the only thing that has
  1050. // changed.
  1051. func (f *sendReceiveFolder) shortcutFile(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob) {
  1052. l.Debugln(f, "taking shortcut on", file.Name)
  1053. f.evLogger.Log(events.ItemStarted, map[string]string{
  1054. "folder": f.folderID,
  1055. "item": file.Name,
  1056. "type": "file",
  1057. "action": "metadata",
  1058. })
  1059. var err error
  1060. defer f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  1061. "folder": f.folderID,
  1062. "item": file.Name,
  1063. "error": events.Error(err),
  1064. "type": "file",
  1065. "action": "metadata",
  1066. })
  1067. f.queue.Done(file.Name)
  1068. if !f.IgnorePerms && !file.NoPermissions {
  1069. if err = f.mtimefs.Chmod(file.Name, fs.FileMode(file.Permissions&0o777)); err != nil {
  1070. f.newPullError(file.Name, fmt.Errorf("shortcut file (setting permissions): %w", err))
  1071. return
  1072. }
  1073. }
  1074. if err := f.setPlatformData(&file, file.Name); err != nil {
  1075. f.newPullError(file.Name, fmt.Errorf("shortcut file (setting metadata): %w", err))
  1076. return
  1077. }
  1078. // Still need to re-write the trailer with the new encrypted fileinfo.
  1079. if f.Type == config.FolderTypeReceiveEncrypted {
  1080. err = inWritableDir(func(path string) error {
  1081. fd, err := f.mtimefs.OpenFile(path, fs.OptReadWrite, 0o666)
  1082. if err != nil {
  1083. return err
  1084. }
  1085. defer fd.Close()
  1086. trailerSize, err := writeEncryptionTrailer(file, fd)
  1087. if err != nil {
  1088. return err
  1089. }
  1090. file.EncryptionTrailerSize = int(trailerSize)
  1091. file.Size += trailerSize
  1092. return fd.Truncate(file.Size)
  1093. }, f.mtimefs, file.Name, true)
  1094. if err != nil {
  1095. f.newPullError(file.Name, fmt.Errorf("writing encrypted file trailer: %w", err))
  1096. return
  1097. }
  1098. }
  1099. f.mtimefs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  1100. dbUpdateChan <- dbUpdateJob{file, dbUpdateShortcutFile}
  1101. }
  1102. // copierRoutine reads copierStates until the in channel closes and performs
  1103. // the relevant copies when possible, or passes it to the puller routine.
  1104. func (f *sendReceiveFolder) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
  1105. buf := protocol.BufferPool.Get(protocol.MinBlockSize)
  1106. defer func() {
  1107. protocol.BufferPool.Put(buf)
  1108. }()
  1109. folderFilesystems := make(map[string]fs.Filesystem)
  1110. // Hope that it's usually in the same folder, so start with that one.
  1111. folders := []string{f.folderID}
  1112. for folder, cfg := range f.model.cfg.Folders() {
  1113. folderFilesystems[folder] = cfg.Filesystem(nil)
  1114. if folder != f.folderID {
  1115. folders = append(folders, folder)
  1116. }
  1117. }
  1118. for state := range in {
  1119. if err := f.CheckAvailableSpace(uint64(state.file.Size)); err != nil {
  1120. state.fail(err)
  1121. // Nothing more to do for this failed file, since it would use to much disk space
  1122. out <- state.sharedPullerState
  1123. continue
  1124. }
  1125. dstFd, err := state.tempFile()
  1126. if err != nil {
  1127. // Nothing more to do for this failed file, since we couldn't create a temporary for it.
  1128. out <- state.sharedPullerState
  1129. continue
  1130. }
  1131. if f.Type != config.FolderTypeReceiveEncrypted {
  1132. f.model.progressEmitter.Register(state.sharedPullerState)
  1133. }
  1134. weakHashFinder, file := f.initWeakHashFinder(state)
  1135. blocks:
  1136. for _, block := range state.blocks {
  1137. select {
  1138. case <-f.ctx.Done():
  1139. state.fail(fmt.Errorf("folder stopped: %w", f.ctx.Err()))
  1140. break blocks
  1141. default:
  1142. }
  1143. if !f.DisableSparseFiles && state.reused == 0 && block.IsEmpty() {
  1144. // The block is a block of all zeroes, and we are not reusing
  1145. // a temp file, so there is no need to do anything with it.
  1146. // If we were reusing a temp file and had this block to copy,
  1147. // it would be because the block in the temp file was *not* a
  1148. // block of all zeroes, so then we should not skip it.
  1149. // Pretend we copied it.
  1150. state.skippedSparseBlock(block.Size)
  1151. state.copyDone(block)
  1152. continue
  1153. }
  1154. buf = protocol.BufferPool.Upgrade(buf, int(block.Size))
  1155. var found bool
  1156. if f.Type != config.FolderTypeReceiveEncrypted {
  1157. found, err = weakHashFinder.Iterate(block.WeakHash, buf, func(offset int64) bool {
  1158. if f.verifyBuffer(buf, block) != nil {
  1159. return true
  1160. }
  1161. err = f.limitedWriteAt(dstFd, buf, block.Offset)
  1162. if err != nil {
  1163. state.fail(fmt.Errorf("dst write: %w", err))
  1164. }
  1165. if offset == block.Offset {
  1166. state.copiedFromOrigin(block.Size)
  1167. } else {
  1168. state.copiedFromOriginShifted(block.Size)
  1169. }
  1170. return false
  1171. })
  1172. if err != nil {
  1173. l.Debugln("weak hasher iter", err)
  1174. }
  1175. }
  1176. if !found {
  1177. found = f.model.finder.Iterate(folders, block.Hash, func(folder, path string, index int32) bool {
  1178. ffs := folderFilesystems[folder]
  1179. fd, err := ffs.Open(path)
  1180. if err != nil {
  1181. return false
  1182. }
  1183. defer fd.Close()
  1184. srcOffset := int64(state.file.BlockSize()) * int64(index)
  1185. _, err = fd.ReadAt(buf, srcOffset)
  1186. if err != nil {
  1187. return false
  1188. }
  1189. // Hash is not SHA256 as it's an encrypted hash token. In that
  1190. // case we can't verify the block integrity so we'll take it on
  1191. // trust. (The other side can and will verify.)
  1192. if f.Type != config.FolderTypeReceiveEncrypted {
  1193. if err := f.verifyBuffer(buf, block); err != nil {
  1194. l.Debugln("Finder failed to verify buffer", err)
  1195. return false
  1196. }
  1197. }
  1198. if f.CopyRangeMethod != fs.CopyRangeMethodStandard {
  1199. err = f.withLimiter(func() error {
  1200. dstFd.mut.Lock()
  1201. defer dstFd.mut.Unlock()
  1202. return fs.CopyRange(f.CopyRangeMethod, fd, dstFd.fd, srcOffset, block.Offset, int64(block.Size))
  1203. })
  1204. } else {
  1205. err = f.limitedWriteAt(dstFd, buf, block.Offset)
  1206. }
  1207. if err != nil {
  1208. state.fail(fmt.Errorf("dst write: %w", err))
  1209. }
  1210. if path == state.file.Name {
  1211. state.copiedFromOrigin(block.Size)
  1212. } else {
  1213. state.copiedFromElsewhere(block.Size)
  1214. }
  1215. return true
  1216. })
  1217. }
  1218. if state.failed() != nil {
  1219. break
  1220. }
  1221. if !found {
  1222. state.pullStarted()
  1223. ps := pullBlockState{
  1224. sharedPullerState: state.sharedPullerState,
  1225. block: block,
  1226. }
  1227. pullChan <- ps
  1228. } else {
  1229. state.copyDone(block)
  1230. }
  1231. }
  1232. if file != nil {
  1233. // os.File used to return invalid argument if nil.
  1234. // fs.File panics as it's an interface.
  1235. file.Close()
  1236. }
  1237. out <- state.sharedPullerState
  1238. }
  1239. }
  1240. func (f *sendReceiveFolder) initWeakHashFinder(state copyBlocksState) (*weakhash.Finder, fs.File) {
  1241. if f.Type == config.FolderTypeReceiveEncrypted {
  1242. l.Debugln("not weak hashing due to folder type", f.Type)
  1243. return nil, nil
  1244. }
  1245. blocksPercentChanged := 0
  1246. if tot := len(state.file.Blocks); tot > 0 {
  1247. blocksPercentChanged = (tot - state.have) * 100 / tot
  1248. }
  1249. if blocksPercentChanged < f.WeakHashThresholdPct {
  1250. l.Debugf("not weak hashing %s. not enough changed %.02f < %d", state.file.Name, blocksPercentChanged, f.WeakHashThresholdPct)
  1251. return nil, nil
  1252. }
  1253. hashesToFind := make([]uint32, 0, len(state.blocks))
  1254. for _, block := range state.blocks {
  1255. if block.WeakHash != 0 {
  1256. hashesToFind = append(hashesToFind, block.WeakHash)
  1257. }
  1258. }
  1259. if len(hashesToFind) == 0 {
  1260. l.Debugf("not weak hashing %s. file did not contain any weak hashes", state.file.Name)
  1261. return nil, nil
  1262. }
  1263. file, err := f.mtimefs.Open(state.file.Name)
  1264. if err != nil {
  1265. l.Debugln("weak hasher", err)
  1266. return nil, nil
  1267. }
  1268. weakHashFinder, err := weakhash.NewFinder(f.ctx, file, state.file.BlockSize(), hashesToFind)
  1269. if err != nil {
  1270. l.Debugln("weak hasher", err)
  1271. return nil, file
  1272. }
  1273. return weakHashFinder, file
  1274. }
  1275. func (*sendReceiveFolder) verifyBuffer(buf []byte, block protocol.BlockInfo) error {
  1276. if len(buf) != int(block.Size) {
  1277. return fmt.Errorf("length mismatch %d != %d", len(buf), block.Size)
  1278. }
  1279. hash := sha256.Sum256(buf)
  1280. if !bytes.Equal(hash[:], block.Hash) {
  1281. return fmt.Errorf("hash mismatch %x != %x", hash, block.Hash)
  1282. }
  1283. return nil
  1284. }
  1285. func (f *sendReceiveFolder) pullerRoutine(snap *db.Snapshot, in <-chan pullBlockState, out chan<- *sharedPullerState) {
  1286. requestLimiter := util.NewSemaphore(f.PullerMaxPendingKiB * 1024)
  1287. wg := sync.NewWaitGroup()
  1288. for state := range in {
  1289. if state.failed() != nil {
  1290. out <- state.sharedPullerState
  1291. continue
  1292. }
  1293. f.setState(FolderSyncing) // Does nothing if already FolderSyncing
  1294. // The requestLimiter limits how many pending block requests we have
  1295. // ongoing at any given time, based on the size of the blocks
  1296. // themselves.
  1297. state := state
  1298. bytes := int(state.block.Size)
  1299. if err := requestLimiter.TakeWithContext(f.ctx, bytes); err != nil {
  1300. state.fail(err)
  1301. out <- state.sharedPullerState
  1302. continue
  1303. }
  1304. wg.Add(1)
  1305. go func() {
  1306. defer wg.Done()
  1307. defer requestLimiter.Give(bytes)
  1308. f.pullBlock(state, snap, out)
  1309. }()
  1310. }
  1311. wg.Wait()
  1312. }
  1313. func (f *sendReceiveFolder) pullBlock(state pullBlockState, snap *db.Snapshot, out chan<- *sharedPullerState) {
  1314. // Get an fd to the temporary file. Technically we don't need it until
  1315. // after fetching the block, but if we run into an error here there is
  1316. // no point in issuing the request to the network.
  1317. fd, err := state.tempFile()
  1318. if err != nil {
  1319. out <- state.sharedPullerState
  1320. return
  1321. }
  1322. if !f.DisableSparseFiles && state.reused == 0 && state.block.IsEmpty() {
  1323. // There is no need to request a block of all zeroes. Pretend we
  1324. // requested it and handled it correctly.
  1325. state.pullDone(state.block)
  1326. out <- state.sharedPullerState
  1327. return
  1328. }
  1329. var lastError error
  1330. candidates := f.model.availabilityInSnapshot(f.FolderConfiguration, snap, state.file, state.block)
  1331. loop:
  1332. for {
  1333. select {
  1334. case <-f.ctx.Done():
  1335. state.fail(fmt.Errorf("folder stopped: %w", f.ctx.Err()))
  1336. break loop
  1337. default:
  1338. }
  1339. // Select the least busy device to pull the block from. If we found no
  1340. // feasible device at all, fail the block (and in the long run, the
  1341. // file).
  1342. found := activity.leastBusy(candidates)
  1343. if found == -1 {
  1344. if lastError != nil {
  1345. state.fail(fmt.Errorf("pull: %w", lastError))
  1346. } else {
  1347. state.fail(fmt.Errorf("pull: %w", errNoDevice))
  1348. }
  1349. break
  1350. }
  1351. selected := candidates[found]
  1352. candidates[found] = candidates[len(candidates)-1]
  1353. candidates = candidates[:len(candidates)-1]
  1354. // Fetch the block, while marking the selected device as in use so that
  1355. // leastBusy can select another device when someone else asks.
  1356. activity.using(selected)
  1357. var buf []byte
  1358. blockNo := int(state.block.Offset / int64(state.file.BlockSize()))
  1359. 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)
  1360. activity.done(selected)
  1361. if lastError != nil {
  1362. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, selected.ID.Short(), "returned error:", lastError)
  1363. continue
  1364. }
  1365. // Verify that the received block matches the desired hash, if not
  1366. // try pulling it from another device.
  1367. // For receive-only folders, the hash is not SHA256 as it's an
  1368. // encrypted hash token. In that case we can't verify the block
  1369. // integrity so we'll take it on trust. (The other side can and
  1370. // will verify.)
  1371. if f.Type != config.FolderTypeReceiveEncrypted {
  1372. lastError = f.verifyBuffer(buf, state.block)
  1373. }
  1374. if lastError != nil {
  1375. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, "hash mismatch")
  1376. continue
  1377. }
  1378. // Save the block data we got from the cluster
  1379. err = f.limitedWriteAt(fd, buf, state.block.Offset)
  1380. if err != nil {
  1381. state.fail(fmt.Errorf("save: %w", err))
  1382. } else {
  1383. state.pullDone(state.block)
  1384. }
  1385. break
  1386. }
  1387. out <- state.sharedPullerState
  1388. }
  1389. func (f *sendReceiveFolder) performFinish(file, curFile protocol.FileInfo, hasCurFile bool, tempName string, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  1390. // Set the correct permission bits on the new file
  1391. if !f.IgnorePerms && !file.NoPermissions {
  1392. if err := f.mtimefs.Chmod(tempName, fs.FileMode(file.Permissions&0o777)); err != nil {
  1393. return fmt.Errorf("setting permissions: %w", err)
  1394. }
  1395. }
  1396. // Set file xattrs and ownership.
  1397. if err := f.setPlatformData(&file, tempName); err != nil {
  1398. return fmt.Errorf("setting metadata: %w", err)
  1399. }
  1400. if stat, err := f.mtimefs.Lstat(file.Name); err == nil {
  1401. // There is an old file or directory already in place. We need to
  1402. // handle that.
  1403. if err := f.scanIfItemChanged(file.Name, stat, curFile, hasCurFile, scanChan); err != nil {
  1404. return fmt.Errorf("checking existing file: %w", err)
  1405. }
  1406. if !curFile.IsDirectory() && !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  1407. // The new file has been changed in conflict with the existing one. We
  1408. // should file it away as a conflict instead of just removing or
  1409. // archiving.
  1410. // Directories and symlinks aren't checked for conflicts.
  1411. err = f.inWritableDir(func(name string) error {
  1412. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  1413. }, curFile.Name)
  1414. } else {
  1415. err = f.deleteItemOnDisk(curFile, snap, scanChan)
  1416. }
  1417. if err != nil {
  1418. return fmt.Errorf("moving for conflict: %w", err)
  1419. }
  1420. } else if !fs.IsNotExist(err) {
  1421. return fmt.Errorf("checking existing file: %w", err)
  1422. }
  1423. // Replace the original content with the new one. If it didn't work,
  1424. // leave the temp file in place for reuse.
  1425. if err := osutil.RenameOrCopy(f.CopyRangeMethod, f.mtimefs, f.mtimefs, tempName, file.Name); err != nil {
  1426. return fmt.Errorf("replacing file: %w", err)
  1427. }
  1428. // Set the correct timestamp on the new file
  1429. f.mtimefs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  1430. // Record the updated file in the index
  1431. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleFile}
  1432. return nil
  1433. }
  1434. func (f *sendReceiveFolder) finisherRoutine(snap *db.Snapshot, in <-chan *sharedPullerState, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  1435. for state := range in {
  1436. if closed, err := state.finalClose(); closed {
  1437. l.Debugln(f, "closing", state.file.Name)
  1438. f.queue.Done(state.file.Name)
  1439. if err == nil {
  1440. err = f.performFinish(state.file, state.curFile, state.hasCurFile, state.tempName, snap, dbUpdateChan, scanChan)
  1441. }
  1442. if err != nil {
  1443. f.newPullError(state.file.Name, fmt.Errorf("finishing: %w", err))
  1444. } else {
  1445. minBlocksPerBlock := state.file.BlockSize() / protocol.MinBlockSize
  1446. blockStatsMut.Lock()
  1447. blockStats["total"] += (state.reused + state.copyTotal + state.pullTotal) * minBlocksPerBlock
  1448. blockStats["reused"] += state.reused * minBlocksPerBlock
  1449. blockStats["pulled"] += state.pullTotal * minBlocksPerBlock
  1450. // copyOriginShifted is counted towards copyOrigin due to progress bar reasons
  1451. // for reporting reasons we want to separate these.
  1452. blockStats["copyOrigin"] += (state.copyOrigin - state.copyOriginShifted) * minBlocksPerBlock
  1453. blockStats["copyOriginShifted"] += state.copyOriginShifted * minBlocksPerBlock
  1454. blockStats["copyElsewhere"] += (state.copyTotal - state.copyOrigin) * minBlocksPerBlock
  1455. blockStatsMut.Unlock()
  1456. }
  1457. if f.Type != config.FolderTypeReceiveEncrypted {
  1458. f.model.progressEmitter.Deregister(state)
  1459. }
  1460. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  1461. "folder": f.folderID,
  1462. "item": state.file.Name,
  1463. "error": events.Error(err),
  1464. "type": "file",
  1465. "action": "update",
  1466. })
  1467. }
  1468. }
  1469. }
  1470. // Moves the given filename to the front of the job queue
  1471. func (f *sendReceiveFolder) BringToFront(filename string) {
  1472. f.queue.BringToFront(filename)
  1473. }
  1474. func (f *sendReceiveFolder) Jobs(page, perpage int) ([]string, []string, int) {
  1475. return f.queue.Jobs(page, perpage)
  1476. }
  1477. // dbUpdaterRoutine aggregates db updates and commits them in batches no
  1478. // larger than 1000 items, and no more delayed than 2 seconds.
  1479. func (f *sendReceiveFolder) dbUpdaterRoutine(dbUpdateChan <-chan dbUpdateJob) {
  1480. const maxBatchTime = 2 * time.Second
  1481. changedDirs := make(map[string]struct{})
  1482. found := false
  1483. var lastFile protocol.FileInfo
  1484. tick := time.NewTicker(maxBatchTime)
  1485. defer tick.Stop()
  1486. batch := db.NewFileInfoBatch(func(files []protocol.FileInfo) error {
  1487. // sync directories
  1488. for dir := range changedDirs {
  1489. delete(changedDirs, dir)
  1490. if !f.FolderConfiguration.DisableFsync {
  1491. fd, err := f.mtimefs.Open(dir)
  1492. if err != nil {
  1493. l.Debugf("fsync %q failed: %v", dir, err)
  1494. continue
  1495. }
  1496. if err := fd.Sync(); err != nil {
  1497. l.Debugf("fsync %q failed: %v", dir, err)
  1498. }
  1499. fd.Close()
  1500. }
  1501. }
  1502. // All updates to file/folder objects that originated remotely
  1503. // (across the network) use this call to updateLocals
  1504. f.updateLocalsFromPulling(files)
  1505. if found {
  1506. f.ReceivedFile(lastFile.Name, lastFile.IsDeleted())
  1507. found = false
  1508. }
  1509. return nil
  1510. })
  1511. loop:
  1512. for {
  1513. select {
  1514. case job, ok := <-dbUpdateChan:
  1515. if !ok {
  1516. break loop
  1517. }
  1518. switch job.jobType {
  1519. case dbUpdateHandleFile, dbUpdateShortcutFile:
  1520. changedDirs[filepath.Dir(job.file.Name)] = struct{}{}
  1521. case dbUpdateHandleDir:
  1522. changedDirs[job.file.Name] = struct{}{}
  1523. case dbUpdateHandleSymlink, dbUpdateInvalidate:
  1524. // fsyncing symlinks is only supported by MacOS
  1525. // and invalidated files are db only changes -> no sync
  1526. }
  1527. // For some reason we seem to care about file deletions and
  1528. // content modification, but not about metadata and dirs/symlinks.
  1529. if !job.file.IsInvalid() && job.jobType&(dbUpdateHandleFile|dbUpdateDeleteFile) != 0 {
  1530. found = true
  1531. lastFile = job.file
  1532. }
  1533. if !job.file.IsDeleted() && !job.file.IsInvalid() {
  1534. // Now that the file is finalized, grab possibly updated
  1535. // inode change time from disk into the local FileInfo. We
  1536. // use this change time to check for changes to xattrs etc
  1537. // on next scan.
  1538. if err := f.updateFileInfoChangeTime(&job.file); err != nil {
  1539. // This means on next scan the likely incorrect change time
  1540. // (resp. whatever caused the error) will cause this file to
  1541. // change. Log at info level to leave a trace if a user
  1542. // notices, but no need to warn
  1543. l.Infof("Error updating metadata for %v at database commit: %v", job.file.Name, err)
  1544. }
  1545. }
  1546. job.file.Sequence = 0
  1547. batch.Append(job.file)
  1548. batch.FlushIfFull()
  1549. case <-tick.C:
  1550. batch.Flush()
  1551. }
  1552. }
  1553. batch.Flush()
  1554. }
  1555. // pullScannerRoutine aggregates paths to be scanned after pulling. The scan is
  1556. // scheduled once when scanChan is closed (scanning can not happen during pulling).
  1557. func (f *sendReceiveFolder) pullScannerRoutine(scanChan <-chan string) {
  1558. toBeScanned := make(map[string]struct{})
  1559. for path := range scanChan {
  1560. toBeScanned[path] = struct{}{}
  1561. }
  1562. if len(toBeScanned) != 0 {
  1563. scanList := make([]string, 0, len(toBeScanned))
  1564. for path := range toBeScanned {
  1565. l.Debugln(f, "scheduling scan after pulling for", path)
  1566. scanList = append(scanList, path)
  1567. }
  1568. f.Scan(scanList)
  1569. }
  1570. }
  1571. func (f *sendReceiveFolder) inConflict(current, replacement protocol.Vector) bool {
  1572. if current.Concurrent(replacement) {
  1573. // Obvious case
  1574. return true
  1575. }
  1576. if replacement.Counter(f.shortID) > current.Counter(f.shortID) {
  1577. // The replacement file contains a higher version for ourselves than
  1578. // what we have. This isn't supposed to be possible, since it's only
  1579. // we who can increment that counter. We take it as a sign that
  1580. // something is wrong (our index may have been corrupted or removed)
  1581. // and flag it as a conflict.
  1582. return true
  1583. }
  1584. return false
  1585. }
  1586. func (f *sendReceiveFolder) moveForConflict(name, lastModBy string, scanChan chan<- string) error {
  1587. if isConflict(name) {
  1588. l.Infoln("Conflict for", name, "which is already a conflict copy; not copying again.")
  1589. if err := f.mtimefs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1590. return fmt.Errorf("%s: %w", contextRemovingOldItem, err)
  1591. }
  1592. return nil
  1593. }
  1594. if f.MaxConflicts == 0 {
  1595. if err := f.mtimefs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1596. return fmt.Errorf("%s: %w", contextRemovingOldItem, err)
  1597. }
  1598. return nil
  1599. }
  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, 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: !f.SyncOwnership,
  1812. IgnoreXattrs: !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, 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. }