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