rwfolder.go 54 KB

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