folder_sendrecv.go 67 KB

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