folder_sendrecv.go 62 KB

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