rwfolder.go 51 KB

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