folder_sendrecv.go 56 KB

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