rwfolder.go 56 KB

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