rwfolder.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  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. if err := f.CheckHealth(); err != nil {
  199. l.Debugln("Skipping pull of", f.Description(), "due to folder error:", err)
  200. return prevIgnoreHash, true
  201. }
  202. f.model.fmut.RLock()
  203. curIgnores := f.model.folderIgnores[f.folderID]
  204. f.model.fmut.RUnlock()
  205. curIgnoreHash = curIgnores.Hash()
  206. ignoresChanged := curIgnoreHash != prevIgnoreHash
  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. if changed == 0 {
  240. return curIgnoreHash, true
  241. }
  242. return prevIgnoreHash, false
  243. }
  244. // pullerIteration runs a single puller iteration for the given folder and
  245. // returns the number items that should have been synced (even those that
  246. // might have failed). One puller iteration handles all files currently
  247. // flagged as needed in the folder.
  248. func (f *sendReceiveFolder) pullerIteration(ignores *ignore.Matcher, ignoresChanged bool) int {
  249. pullChan := make(chan pullBlockState)
  250. copyChan := make(chan copyBlocksState)
  251. finisherChan := make(chan *sharedPullerState)
  252. updateWg := sync.NewWaitGroup()
  253. copyWg := sync.NewWaitGroup()
  254. pullWg := sync.NewWaitGroup()
  255. doneWg := sync.NewWaitGroup()
  256. l.Debugln(f, "c", f.Copiers, "p", f.Pullers)
  257. f.dbUpdates = make(chan dbUpdateJob)
  258. updateWg.Add(1)
  259. go func() {
  260. // dbUpdaterRoutine finishes when f.dbUpdates is closed
  261. f.dbUpdaterRoutine()
  262. updateWg.Done()
  263. }()
  264. for i := 0; i < f.Copiers; i++ {
  265. copyWg.Add(1)
  266. go func() {
  267. // copierRoutine finishes when copyChan is closed
  268. f.copierRoutine(copyChan, pullChan, finisherChan)
  269. copyWg.Done()
  270. }()
  271. }
  272. for i := 0; i < f.Pullers; i++ {
  273. pullWg.Add(1)
  274. go func() {
  275. // pullerRoutine finishes when pullChan is closed
  276. f.pullerRoutine(pullChan, finisherChan)
  277. pullWg.Done()
  278. }()
  279. }
  280. doneWg.Add(1)
  281. // finisherRoutine finishes when finisherChan is closed
  282. go func() {
  283. f.finisherRoutine(finisherChan)
  284. doneWg.Done()
  285. }()
  286. f.model.fmut.RLock()
  287. folderFiles := f.model.folderFiles[f.folderID]
  288. f.model.fmut.RUnlock()
  289. changed := 0
  290. var processDirectly []protocol.FileInfo
  291. // Iterate the list of items that we need and sort them into piles.
  292. // Regular files to pull goes into the file queue, everything else
  293. // (directories, symlinks and deletes) goes into the "process directly"
  294. // pile.
  295. // Don't iterate over invalid/ignored files unless ignores have changed
  296. iterate := folderFiles.WithNeed
  297. if ignoresChanged {
  298. iterate = folderFiles.WithNeedOrInvalid
  299. }
  300. iterate(protocol.LocalDeviceID, func(intf db.FileIntf) bool {
  301. if f.IgnoreDelete && intf.IsDeleted() {
  302. return true
  303. }
  304. // If filename isn't valid, we can terminate early with an appropriate error.
  305. // in case it is deleted, we don't care about the filename, so don't complain.
  306. if !intf.IsDeleted() && runtime.GOOS == "windows" && fs.WindowsInvalidFilename(intf.FileName()) {
  307. f.newError("need", intf.FileName(), fs.ErrInvalidFilename)
  308. changed++
  309. return true
  310. }
  311. file := intf.(protocol.FileInfo)
  312. switch {
  313. case ignores.ShouldIgnore(file.Name):
  314. file.Invalidate(f.model.id.Short())
  315. l.Debugln(f, "Handling ignored file", file)
  316. f.dbUpdates <- dbUpdateJob{file, dbUpdateInvalidate}
  317. case file.IsDeleted():
  318. processDirectly = append(processDirectly, file)
  319. changed++
  320. case file.Type == protocol.FileInfoTypeFile:
  321. // Queue files for processing after directories and symlinks, if
  322. // it has availability.
  323. devices := folderFiles.Availability(file.Name)
  324. for _, dev := range devices {
  325. if _, ok := f.model.Connection(dev); ok {
  326. f.queue.Push(file.Name, file.Size, file.ModTime())
  327. changed++
  328. return true
  329. }
  330. }
  331. l.Debugln(f, "Needed file is unavailable", file)
  332. case runtime.GOOS == "windows" && file.IsSymlink():
  333. file.Invalidate(f.model.id.Short())
  334. l.Debugln(f, "Invalidating symlink (unsupported)", file.Name)
  335. f.dbUpdates <- dbUpdateJob{file, dbUpdateInvalidate}
  336. default:
  337. // Directories, symlinks
  338. processDirectly = append(processDirectly, file)
  339. changed++
  340. }
  341. return true
  342. })
  343. // Sort the "process directly" pile by number of path components. This
  344. // ensures that we handle parents before children.
  345. sort.Sort(byComponentCount(processDirectly))
  346. // Process the list.
  347. fileDeletions := map[string]protocol.FileInfo{}
  348. dirDeletions := []protocol.FileInfo{}
  349. buckets := map[string][]protocol.FileInfo{}
  350. for _, fi := range processDirectly {
  351. // Verify that the thing we are handling lives inside a directory,
  352. // and not a symlink or empty space.
  353. if err := osutil.TraversesSymlink(f.fs, filepath.Dir(fi.Name)); err != nil {
  354. f.newError("traverses d", fi.Name, err)
  355. continue
  356. }
  357. switch {
  358. case fi.IsDeleted():
  359. // A deleted file, directory or symlink
  360. if fi.IsDirectory() {
  361. // Perform directory deletions at the end, as we may have
  362. // files to delete inside them before we get to that point.
  363. dirDeletions = append(dirDeletions, fi)
  364. } else {
  365. fileDeletions[fi.Name] = fi
  366. df, ok := f.model.CurrentFolderFile(f.folderID, fi.Name)
  367. // Local file can be already deleted, but with a lower version
  368. // number, hence the deletion coming in again as part of
  369. // WithNeed, furthermore, the file can simply be of the wrong
  370. // type if we haven't yet managed to pull it.
  371. if ok && !df.IsDeleted() && !df.IsSymlink() && !df.IsDirectory() && !df.IsInvalid() {
  372. // Put files into buckets per first hash
  373. key := string(df.Blocks[0].Hash)
  374. buckets[key] = append(buckets[key], df)
  375. }
  376. }
  377. case fi.IsDirectory() && !fi.IsSymlink():
  378. l.Debugln(f, "Handling directory", fi.Name)
  379. f.handleDir(fi)
  380. case fi.IsSymlink():
  381. l.Debugln(f, "Handling symlink", fi.Name)
  382. f.handleSymlink(fi)
  383. default:
  384. l.Warnln(fi)
  385. panic("unhandleable item type, can't happen")
  386. }
  387. }
  388. // Now do the file queue. Reorder it according to configuration.
  389. switch f.Order {
  390. case config.OrderRandom:
  391. f.queue.Shuffle()
  392. case config.OrderAlphabetic:
  393. // The queue is already in alphabetic order.
  394. case config.OrderSmallestFirst:
  395. f.queue.SortSmallestFirst()
  396. case config.OrderLargestFirst:
  397. f.queue.SortLargestFirst()
  398. case config.OrderOldestFirst:
  399. f.queue.SortOldestFirst()
  400. case config.OrderNewestFirst:
  401. f.queue.SortNewestFirst()
  402. }
  403. // Process the file queue.
  404. nextFile:
  405. for {
  406. select {
  407. case <-f.ctx.Done():
  408. // Stop processing files if the puller has been told to stop.
  409. break nextFile
  410. default:
  411. }
  412. fileName, ok := f.queue.Pop()
  413. if !ok {
  414. break
  415. }
  416. fi, ok := f.model.CurrentGlobalFile(f.folderID, fileName)
  417. if !ok {
  418. // File is no longer in the index. Mark it as done and drop it.
  419. f.queue.Done(fileName)
  420. continue
  421. }
  422. if fi.IsDeleted() || fi.Type != protocol.FileInfoTypeFile {
  423. // The item has changed type or status in the index while we
  424. // were processing directories above.
  425. f.queue.Done(fileName)
  426. continue
  427. }
  428. // Verify that the thing we are handling lives inside a directory,
  429. // and not a symlink or empty space.
  430. if err := osutil.TraversesSymlink(f.fs, filepath.Dir(fi.Name)); err != nil {
  431. f.newError("traverses q", fi.Name, err)
  432. continue
  433. }
  434. // Check our list of files to be removed for a match, in which case
  435. // we can just do a rename instead.
  436. key := string(fi.Blocks[0].Hash)
  437. for i, candidate := range buckets[key] {
  438. if scanner.BlocksEqual(candidate.Blocks, fi.Blocks) {
  439. // Remove the candidate from the bucket
  440. lidx := len(buckets[key]) - 1
  441. buckets[key][i] = buckets[key][lidx]
  442. buckets[key] = buckets[key][:lidx]
  443. // candidate is our current state of the file, where as the
  444. // desired state with the delete bit set is in the deletion
  445. // map.
  446. desired := fileDeletions[candidate.Name]
  447. // Remove the pending deletion (as we perform it by renaming)
  448. delete(fileDeletions, candidate.Name)
  449. f.renameFile(desired, fi)
  450. f.queue.Done(fileName)
  451. continue nextFile
  452. }
  453. }
  454. // Handle the file normally, by coping and pulling, etc.
  455. f.handleFile(fi, copyChan, finisherChan)
  456. }
  457. // Signal copy and puller routines that we are done with the in data for
  458. // this iteration. Wait for them to finish.
  459. close(copyChan)
  460. copyWg.Wait()
  461. close(pullChan)
  462. pullWg.Wait()
  463. // Signal the finisher chan that there will be no more input.
  464. close(finisherChan)
  465. // Wait for the finisherChan to finish.
  466. doneWg.Wait()
  467. for _, file := range fileDeletions {
  468. l.Debugln(f, "Deleting file", file.Name)
  469. f.deleteFile(file)
  470. }
  471. for i := range dirDeletions {
  472. dir := dirDeletions[len(dirDeletions)-i-1]
  473. l.Debugln(f, "Deleting dir", dir.Name)
  474. f.deleteDir(dir, ignores)
  475. }
  476. // Wait for db updates to complete
  477. close(f.dbUpdates)
  478. updateWg.Wait()
  479. return changed
  480. }
  481. // handleDir creates or updates the given directory
  482. func (f *sendReceiveFolder) handleDir(file protocol.FileInfo) {
  483. // Used in the defer closure below, updated by the function body. Take
  484. // care not declare another err.
  485. var err error
  486. events.Default.Log(events.ItemStarted, map[string]string{
  487. "folder": f.folderID,
  488. "item": file.Name,
  489. "type": "dir",
  490. "action": "update",
  491. })
  492. defer func() {
  493. events.Default.Log(events.ItemFinished, map[string]interface{}{
  494. "folder": f.folderID,
  495. "item": file.Name,
  496. "error": events.Error(err),
  497. "type": "dir",
  498. "action": "update",
  499. })
  500. }()
  501. mode := fs.FileMode(file.Permissions & 0777)
  502. if f.ignorePermissions(file) {
  503. mode = 0777
  504. }
  505. if shouldDebug() {
  506. curFile, _ := f.model.CurrentFolderFile(f.folderID, file.Name)
  507. l.Debugf("need dir\n\t%v\n\t%v", file, curFile)
  508. }
  509. info, err := f.fs.Lstat(file.Name)
  510. switch {
  511. // There is already something under that name, but it's a file/link.
  512. // Most likely a file/link is getting replaced with a directory.
  513. // Remove the file/link and fall through to directory creation.
  514. case err == nil && (!info.IsDir() || info.IsSymlink()):
  515. err = osutil.InWritableDir(f.fs.Remove, f.fs, file.Name)
  516. if err != nil {
  517. f.newError("dir replace", file.Name, err)
  518. return
  519. }
  520. fallthrough
  521. // The directory doesn't exist, so we create it with the right
  522. // mode bits from the start.
  523. case err != nil && fs.IsNotExist(err):
  524. // We declare a function that acts on only the path name, so
  525. // we can pass it to InWritableDir. We use a regular Mkdir and
  526. // not MkdirAll because the parent should already exist.
  527. mkdir := func(path string) error {
  528. err = f.fs.Mkdir(path, mode)
  529. if err != nil || f.ignorePermissions(file) {
  530. return err
  531. }
  532. // Stat the directory so we can check its permissions.
  533. info, err := f.fs.Lstat(path)
  534. if err != nil {
  535. return err
  536. }
  537. // Mask for the bits we want to preserve and add them in to the
  538. // directories permissions.
  539. return f.fs.Chmod(path, mode|(info.Mode()&retainBits))
  540. }
  541. if err = osutil.InWritableDir(mkdir, f.fs, file.Name); err == nil {
  542. f.dbUpdates <- dbUpdateJob{file, dbUpdateHandleDir}
  543. } else {
  544. f.newError("dir mkdir", file.Name, err)
  545. }
  546. return
  547. // Weird error when stat()'ing the dir. Probably won't work to do
  548. // anything else with it if we can't even stat() it.
  549. case err != nil:
  550. f.newError("dir stat", file.Name, err)
  551. return
  552. }
  553. // The directory already exists, so we just correct the mode bits. (We
  554. // don't handle modification times on directories, because that sucks...)
  555. // It's OK to change mode bits on stuff within non-writable directories.
  556. if f.ignorePermissions(file) {
  557. f.dbUpdates <- dbUpdateJob{file, dbUpdateHandleDir}
  558. } else if err := f.fs.Chmod(file.Name, mode|(fs.FileMode(info.Mode())&retainBits)); err == nil {
  559. f.dbUpdates <- dbUpdateJob{file, dbUpdateHandleDir}
  560. } else {
  561. f.newError("dir chmod", file.Name, err)
  562. }
  563. }
  564. // handleSymlink creates or updates the given symlink
  565. func (f *sendReceiveFolder) handleSymlink(file protocol.FileInfo) {
  566. // Used in the defer closure below, updated by the function body. Take
  567. // care not declare another err.
  568. var err error
  569. events.Default.Log(events.ItemStarted, map[string]string{
  570. "folder": f.folderID,
  571. "item": file.Name,
  572. "type": "symlink",
  573. "action": "update",
  574. })
  575. defer func() {
  576. events.Default.Log(events.ItemFinished, map[string]interface{}{
  577. "folder": f.folderID,
  578. "item": file.Name,
  579. "error": events.Error(err),
  580. "type": "symlink",
  581. "action": "update",
  582. })
  583. }()
  584. if shouldDebug() {
  585. curFile, _ := f.model.CurrentFolderFile(f.folderID, file.Name)
  586. l.Debugf("need symlink\n\t%v\n\t%v", file, curFile)
  587. }
  588. if len(file.SymlinkTarget) == 0 {
  589. // Index entry from a Syncthing predating the support for including
  590. // the link target in the index entry. We log this as an error.
  591. err = errors.New("incompatible symlink entry; rescan with newer Syncthing on source")
  592. f.newError("symlink", file.Name, err)
  593. return
  594. }
  595. if _, err = f.fs.Lstat(file.Name); err == nil {
  596. // There is already something under that name. Remove it to replace
  597. // with the symlink. This also handles the "change symlink type"
  598. // path.
  599. err = osutil.InWritableDir(f.fs.Remove, f.fs, file.Name)
  600. if err != nil {
  601. f.newError("symlink remove", file.Name, err)
  602. return
  603. }
  604. }
  605. // We declare a function that acts on only the path name, so
  606. // we can pass it to InWritableDir.
  607. createLink := func(path string) error {
  608. return f.fs.CreateSymlink(file.SymlinkTarget, path)
  609. }
  610. if err = osutil.InWritableDir(createLink, f.fs, file.Name); err == nil {
  611. f.dbUpdates <- dbUpdateJob{file, dbUpdateHandleSymlink}
  612. } else {
  613. f.newError("symlink create", file.Name, err)
  614. }
  615. }
  616. // deleteDir attempts to delete the given directory
  617. func (f *sendReceiveFolder) deleteDir(file protocol.FileInfo, matcher *ignore.Matcher) {
  618. // Used in the defer closure below, updated by the function body. Take
  619. // care not declare another err.
  620. var err error
  621. events.Default.Log(events.ItemStarted, map[string]string{
  622. "folder": f.folderID,
  623. "item": file.Name,
  624. "type": "dir",
  625. "action": "delete",
  626. })
  627. defer func() {
  628. events.Default.Log(events.ItemFinished, map[string]interface{}{
  629. "folder": f.folderID,
  630. "item": file.Name,
  631. "error": events.Error(err),
  632. "type": "dir",
  633. "action": "delete",
  634. })
  635. }()
  636. // Delete any temporary files lying around in the directory
  637. files, _ := f.fs.DirNames(file.Name)
  638. for _, dirFile := range files {
  639. fullDirFile := filepath.Join(file.Name, dirFile)
  640. if fs.IsTemporary(dirFile) || (matcher != nil && matcher.Match(fullDirFile).IsDeletable()) {
  641. f.fs.RemoveAll(fullDirFile)
  642. }
  643. }
  644. err = osutil.InWritableDir(f.fs.Remove, f.fs, file.Name)
  645. if err == nil || fs.IsNotExist(err) {
  646. // It was removed or it doesn't exist to start with
  647. f.dbUpdates <- dbUpdateJob{file, dbUpdateDeleteDir}
  648. } else if _, serr := f.fs.Lstat(file.Name); serr != nil && !fs.IsPermission(serr) {
  649. // We get an error just looking at the directory, and it's not a
  650. // permission problem. Lets assume the error is in fact some variant
  651. // of "file does not exist" (possibly expressed as some parent being a
  652. // file and not a directory etc) and that the delete is handled.
  653. f.dbUpdates <- dbUpdateJob{file, dbUpdateDeleteDir}
  654. } else {
  655. f.newError("delete dir", file.Name, err)
  656. }
  657. }
  658. // deleteFile attempts to delete the given file
  659. func (f *sendReceiveFolder) deleteFile(file protocol.FileInfo) {
  660. // Used in the defer closure below, updated by the function body. Take
  661. // care not declare another err.
  662. var err error
  663. events.Default.Log(events.ItemStarted, map[string]string{
  664. "folder": f.folderID,
  665. "item": file.Name,
  666. "type": "file",
  667. "action": "delete",
  668. })
  669. defer func() {
  670. events.Default.Log(events.ItemFinished, map[string]interface{}{
  671. "folder": f.folderID,
  672. "item": file.Name,
  673. "error": events.Error(err),
  674. "type": "file",
  675. "action": "delete",
  676. })
  677. }()
  678. cur, ok := f.model.CurrentFolderFile(f.folderID, file.Name)
  679. if ok && f.inConflict(cur.Version, file.Version) {
  680. // There is a conflict here. Move the file to a conflict copy instead
  681. // of deleting. Also merge with the version vector we had, to indicate
  682. // we have resolved the conflict.
  683. file.Version = file.Version.Merge(cur.Version)
  684. err = osutil.InWritableDir(func(name string) error {
  685. return f.moveForConflict(name, file.ModifiedBy.String())
  686. }, f.fs, file.Name)
  687. } else if f.versioner != nil && !cur.IsSymlink() {
  688. err = osutil.InWritableDir(f.versioner.Archive, f.fs, file.Name)
  689. } else {
  690. err = osutil.InWritableDir(f.fs.Remove, f.fs, file.Name)
  691. }
  692. if err == nil || fs.IsNotExist(err) {
  693. // It was removed or it doesn't exist to start with
  694. f.dbUpdates <- dbUpdateJob{file, dbUpdateDeleteFile}
  695. } else if _, serr := f.fs.Lstat(file.Name); serr != nil && !fs.IsPermission(serr) {
  696. // We get an error just looking at the file, and it's not a permission
  697. // problem. Lets assume the error is in fact some variant of "file
  698. // does not exist" (possibly expressed as some parent being a file and
  699. // not a directory etc) and that the delete is handled.
  700. f.dbUpdates <- dbUpdateJob{file, dbUpdateDeleteFile}
  701. } else {
  702. f.newError("delete file", file.Name, err)
  703. }
  704. }
  705. // renameFile attempts to rename an existing file to a destination
  706. // and set the right attributes on it.
  707. func (f *sendReceiveFolder) renameFile(source, target protocol.FileInfo) {
  708. // Used in the defer closure below, updated by the function body. Take
  709. // care not declare another err.
  710. var err error
  711. events.Default.Log(events.ItemStarted, map[string]string{
  712. "folder": f.folderID,
  713. "item": source.Name,
  714. "type": "file",
  715. "action": "delete",
  716. })
  717. events.Default.Log(events.ItemStarted, map[string]string{
  718. "folder": f.folderID,
  719. "item": target.Name,
  720. "type": "file",
  721. "action": "update",
  722. })
  723. defer func() {
  724. events.Default.Log(events.ItemFinished, map[string]interface{}{
  725. "folder": f.folderID,
  726. "item": source.Name,
  727. "error": events.Error(err),
  728. "type": "file",
  729. "action": "delete",
  730. })
  731. events.Default.Log(events.ItemFinished, map[string]interface{}{
  732. "folder": f.folderID,
  733. "item": target.Name,
  734. "error": events.Error(err),
  735. "type": "file",
  736. "action": "update",
  737. })
  738. }()
  739. l.Debugln(f, "taking rename shortcut", source.Name, "->", target.Name)
  740. if f.versioner != nil {
  741. err = osutil.Copy(f.fs, source.Name, target.Name)
  742. if err == nil {
  743. err = osutil.InWritableDir(f.versioner.Archive, f.fs, source.Name)
  744. }
  745. } else {
  746. err = osutil.TryRename(f.fs, source.Name, target.Name)
  747. }
  748. if err == nil {
  749. blockStatsMut.Lock()
  750. blockStats["total"] += len(target.Blocks)
  751. blockStats["renamed"] += len(target.Blocks)
  752. blockStatsMut.Unlock()
  753. // The file was renamed, so we have handled both the necessary delete
  754. // of the source and the creation of the target. Fix-up the metadata,
  755. // and update the local index of the target file.
  756. f.dbUpdates <- dbUpdateJob{source, dbUpdateDeleteFile}
  757. err = f.shortcutFile(target)
  758. if err != nil {
  759. err = fmt.Errorf("from %s: %s", source.Name, err.Error())
  760. f.newError("rename shortcut", target.Name, err)
  761. return
  762. }
  763. f.dbUpdates <- dbUpdateJob{target, dbUpdateHandleFile}
  764. } else {
  765. // We failed the rename so we have a source file that we still need to
  766. // get rid of. Attempt to delete it instead so that we make *some*
  767. // progress. The target is unhandled.
  768. err = osutil.InWritableDir(f.fs.Remove, f.fs, source.Name)
  769. if err != nil {
  770. err = fmt.Errorf("from %s: %s", source.Name, err.Error())
  771. f.newError("rename delete", target.Name, err)
  772. return
  773. }
  774. f.dbUpdates <- dbUpdateJob{source, dbUpdateDeleteFile}
  775. }
  776. }
  777. // This is the flow of data and events here, I think...
  778. //
  779. // +-----------------------+
  780. // | | - - - - > ItemStarted
  781. // | handleFile | - - - - > ItemFinished (on shortcuts)
  782. // | |
  783. // +-----------------------+
  784. // |
  785. // | copyChan (copyBlocksState; unless shortcut taken)
  786. // |
  787. // | +-----------------------+
  788. // | | +-----------------------+
  789. // +--->| | |
  790. // | | copierRoutine |
  791. // +-| |
  792. // +-----------------------+
  793. // |
  794. // | pullChan (sharedPullerState)
  795. // |
  796. // | +-----------------------+
  797. // | | +-----------------------+
  798. // +-->| | |
  799. // | | pullerRoutine |
  800. // +-| |
  801. // +-----------------------+
  802. // |
  803. // | finisherChan (sharedPullerState)
  804. // |
  805. // | +-----------------------+
  806. // | | |
  807. // +-->| finisherRoutine | - - - - > ItemFinished
  808. // | |
  809. // +-----------------------+
  810. // handleFile queues the copies and pulls as necessary for a single new or
  811. // changed file.
  812. func (f *sendReceiveFolder) handleFile(file protocol.FileInfo, copyChan chan<- copyBlocksState, finisherChan chan<- *sharedPullerState) {
  813. curFile, hasCurFile := f.model.CurrentFolderFile(f.folderID, file.Name)
  814. have, need := scanner.BlockDiff(curFile.Blocks, file.Blocks)
  815. if hasCurFile && len(need) == 0 {
  816. // We are supposed to copy the entire file, and then fetch nothing. We
  817. // are only updating metadata, so we don't actually *need* to make the
  818. // copy.
  819. l.Debugln(f, "taking shortcut on", file.Name)
  820. events.Default.Log(events.ItemStarted, map[string]string{
  821. "folder": f.folderID,
  822. "item": file.Name,
  823. "type": "file",
  824. "action": "metadata",
  825. })
  826. f.queue.Done(file.Name)
  827. err := f.shortcutFile(file)
  828. events.Default.Log(events.ItemFinished, map[string]interface{}{
  829. "folder": f.folderID,
  830. "item": file.Name,
  831. "error": events.Error(err),
  832. "type": "file",
  833. "action": "metadata",
  834. })
  835. if err != nil {
  836. f.newError("shortcut", file.Name, err)
  837. } else {
  838. f.dbUpdates <- dbUpdateJob{file, dbUpdateShortcutFile}
  839. }
  840. return
  841. }
  842. tempName := fs.TempName(file.Name)
  843. scanner.PopulateOffsets(file.Blocks)
  844. var blocks []protocol.BlockInfo
  845. var blocksSize int64
  846. var reused []int32
  847. // Check for an old temporary file which might have some blocks we could
  848. // reuse.
  849. tempBlocks, err := scanner.HashFile(f.ctx, f.fs, tempName, protocol.BlockSize, nil, false)
  850. if err == nil {
  851. // Check for any reusable blocks in the temp file
  852. tempCopyBlocks, _ := scanner.BlockDiff(tempBlocks, file.Blocks)
  853. // block.String() returns a string unique to the block
  854. existingBlocks := make(map[string]struct{}, len(tempCopyBlocks))
  855. for _, block := range tempCopyBlocks {
  856. existingBlocks[block.String()] = struct{}{}
  857. }
  858. // Since the blocks are already there, we don't need to get them.
  859. for i, block := range file.Blocks {
  860. _, ok := existingBlocks[block.String()]
  861. if !ok {
  862. blocks = append(blocks, block)
  863. blocksSize += int64(block.Size)
  864. } else {
  865. reused = append(reused, int32(i))
  866. }
  867. }
  868. // The sharedpullerstate will know which flags to use when opening the
  869. // temp file depending if we are reusing any blocks or not.
  870. if len(reused) == 0 {
  871. // Otherwise, discard the file ourselves in order for the
  872. // sharedpuller not to panic when it fails to exclusively create a
  873. // file which already exists
  874. osutil.InWritableDir(f.fs.Remove, f.fs, tempName)
  875. }
  876. } else {
  877. // Copy the blocks, as we don't want to shuffle them on the FileInfo
  878. blocks = append(blocks, file.Blocks...)
  879. blocksSize = file.Size
  880. }
  881. if f.MinDiskFree.BaseValue() > 0 {
  882. if usage, err := f.fs.Usage("."); err == nil && usage.Free < blocksSize {
  883. 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)
  884. f.newError("disk space", file.Name, errors.New("insufficient space"))
  885. return
  886. }
  887. }
  888. // Shuffle the blocks
  889. for i := range blocks {
  890. j := rand.Intn(i + 1)
  891. blocks[i], blocks[j] = blocks[j], blocks[i]
  892. }
  893. events.Default.Log(events.ItemStarted, map[string]string{
  894. "folder": f.folderID,
  895. "item": file.Name,
  896. "type": "file",
  897. "action": "update",
  898. })
  899. s := sharedPullerState{
  900. file: file,
  901. fs: f.fs,
  902. folder: f.folderID,
  903. tempName: tempName,
  904. realName: file.Name,
  905. copyTotal: len(blocks),
  906. copyNeeded: len(blocks),
  907. reused: len(reused),
  908. updated: time.Now(),
  909. available: reused,
  910. availableUpdated: time.Now(),
  911. ignorePerms: f.ignorePermissions(file),
  912. hasCurFile: hasCurFile,
  913. curFile: curFile,
  914. mut: sync.NewRWMutex(),
  915. sparse: !f.DisableSparseFiles,
  916. created: time.Now(),
  917. }
  918. l.Debugf("%v need file %s; copy %d, reused %v", f, file.Name, len(blocks), len(reused))
  919. cs := copyBlocksState{
  920. sharedPullerState: &s,
  921. blocks: blocks,
  922. have: len(have),
  923. }
  924. copyChan <- cs
  925. }
  926. // shortcutFile sets file mode and modification time, when that's the only
  927. // thing that has changed.
  928. func (f *sendReceiveFolder) shortcutFile(file protocol.FileInfo) error {
  929. if !f.ignorePermissions(file) {
  930. if err := f.fs.Chmod(file.Name, fs.FileMode(file.Permissions&0777)); err != nil {
  931. f.newError("shortcut chmod", file.Name, err)
  932. return err
  933. }
  934. }
  935. f.fs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  936. // This may have been a conflict. We should merge the version vectors so
  937. // that our clock doesn't move backwards.
  938. if cur, ok := f.model.CurrentFolderFile(f.folderID, file.Name); ok {
  939. file.Version = file.Version.Merge(cur.Version)
  940. }
  941. return nil
  942. }
  943. // copierRoutine reads copierStates until the in channel closes and performs
  944. // the relevant copies when possible, or passes it to the puller routine.
  945. func (f *sendReceiveFolder) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
  946. buf := make([]byte, protocol.BlockSize)
  947. for state := range in {
  948. dstFd, err := state.tempFile()
  949. if err != nil {
  950. // Nothing more to do for this failed file, since we couldn't create a temporary for it.
  951. out <- state.sharedPullerState
  952. continue
  953. }
  954. if f.model.progressEmitter != nil {
  955. f.model.progressEmitter.Register(state.sharedPullerState)
  956. }
  957. folderFilesystems := make(map[string]fs.Filesystem)
  958. var folders []string
  959. f.model.fmut.RLock()
  960. for folder, cfg := range f.model.folderCfgs {
  961. folderFilesystems[folder] = cfg.Filesystem()
  962. folders = append(folders, folder)
  963. }
  964. f.model.fmut.RUnlock()
  965. var file fs.File
  966. var weakHashFinder *weakhash.Finder
  967. if weakhash.Enabled {
  968. blocksPercentChanged := 0
  969. if tot := len(state.file.Blocks); tot > 0 {
  970. blocksPercentChanged = (tot - state.have) * 100 / tot
  971. }
  972. if blocksPercentChanged >= f.WeakHashThresholdPct {
  973. hashesToFind := make([]uint32, 0, len(state.blocks))
  974. for _, block := range state.blocks {
  975. if block.WeakHash != 0 {
  976. hashesToFind = append(hashesToFind, block.WeakHash)
  977. }
  978. }
  979. if len(hashesToFind) > 0 {
  980. file, err = f.fs.Open(state.file.Name)
  981. if err == nil {
  982. weakHashFinder, err = weakhash.NewFinder(file, protocol.BlockSize, hashesToFind)
  983. if err != nil {
  984. l.Debugln("weak hasher", err)
  985. }
  986. }
  987. } else {
  988. l.Debugf("not weak hashing %s. file did not contain any weak hashes", state.file.Name)
  989. }
  990. } else {
  991. l.Debugf("not weak hashing %s. not enough changed %.02f < %d", state.file.Name, blocksPercentChanged, f.WeakHashThresholdPct)
  992. }
  993. } else {
  994. l.Debugf("not weak hashing %s. weak hashing disabled", state.file.Name)
  995. }
  996. for _, block := range state.blocks {
  997. if !f.DisableSparseFiles && state.reused == 0 && block.IsEmpty() {
  998. // The block is a block of all zeroes, and we are not reusing
  999. // a temp file, so there is no need to do anything with it.
  1000. // If we were reusing a temp file and had this block to copy,
  1001. // it would be because the block in the temp file was *not* a
  1002. // block of all zeroes, so then we should not skip it.
  1003. // Pretend we copied it.
  1004. state.copiedFromOrigin()
  1005. continue
  1006. }
  1007. buf = buf[:int(block.Size)]
  1008. found, err := weakHashFinder.Iterate(block.WeakHash, buf, func(offset int64) bool {
  1009. if _, err := scanner.VerifyBuffer(buf, block); err != nil {
  1010. return true
  1011. }
  1012. _, err = dstFd.WriteAt(buf, block.Offset)
  1013. if err != nil {
  1014. state.fail("dst write", err)
  1015. }
  1016. if offset == block.Offset {
  1017. state.copiedFromOrigin()
  1018. } else {
  1019. state.copiedFromOriginShifted()
  1020. }
  1021. return false
  1022. })
  1023. if err != nil {
  1024. l.Debugln("weak hasher iter", err)
  1025. }
  1026. if !found {
  1027. found = f.model.finder.Iterate(folders, block.Hash, func(folder, path string, index int32) bool {
  1028. fs := folderFilesystems[folder]
  1029. fd, err := fs.Open(path)
  1030. if err != nil {
  1031. return false
  1032. }
  1033. _, err = fd.ReadAt(buf, protocol.BlockSize*int64(index))
  1034. fd.Close()
  1035. if err != nil {
  1036. return false
  1037. }
  1038. hash, err := scanner.VerifyBuffer(buf, block)
  1039. if err != nil {
  1040. if hash != nil {
  1041. l.Debugf("Finder block mismatch in %s:%s:%d expected %q got %q", folder, path, index, block.Hash, hash)
  1042. err = f.model.finder.Fix(folder, path, index, block.Hash, hash)
  1043. if err != nil {
  1044. l.Warnln("finder fix:", err)
  1045. }
  1046. } else {
  1047. l.Debugln("Finder failed to verify buffer", err)
  1048. }
  1049. return false
  1050. }
  1051. _, err = dstFd.WriteAt(buf, block.Offset)
  1052. if err != nil {
  1053. state.fail("dst write", err)
  1054. }
  1055. if path == state.file.Name {
  1056. state.copiedFromOrigin()
  1057. }
  1058. return true
  1059. })
  1060. }
  1061. if state.failed() != nil {
  1062. break
  1063. }
  1064. if !found {
  1065. state.pullStarted()
  1066. ps := pullBlockState{
  1067. sharedPullerState: state.sharedPullerState,
  1068. block: block,
  1069. }
  1070. pullChan <- ps
  1071. } else {
  1072. state.copyDone(block)
  1073. }
  1074. }
  1075. if file != nil {
  1076. // os.File used to return invalid argument if nil.
  1077. // fs.File panics as it's an interface.
  1078. file.Close()
  1079. }
  1080. out <- state.sharedPullerState
  1081. }
  1082. }
  1083. func (f *sendReceiveFolder) pullerRoutine(in <-chan pullBlockState, out chan<- *sharedPullerState) {
  1084. for state := range in {
  1085. if state.failed() != nil {
  1086. out <- state.sharedPullerState
  1087. continue
  1088. }
  1089. // Get an fd to the temporary file. Technically we don't need it until
  1090. // after fetching the block, but if we run into an error here there is
  1091. // no point in issuing the request to the network.
  1092. fd, err := state.tempFile()
  1093. if err != nil {
  1094. out <- state.sharedPullerState
  1095. continue
  1096. }
  1097. if !f.DisableSparseFiles && state.reused == 0 && state.block.IsEmpty() {
  1098. // There is no need to request a block of all zeroes. Pretend we
  1099. // requested it and handled it correctly.
  1100. state.pullDone(state.block)
  1101. out <- state.sharedPullerState
  1102. continue
  1103. }
  1104. var lastError error
  1105. candidates := f.model.Availability(f.folderID, state.file.Name, state.file.Version, state.block)
  1106. for {
  1107. // Select the least busy device to pull the block from. If we found no
  1108. // feasible device at all, fail the block (and in the long run, the
  1109. // file).
  1110. selected, found := activity.leastBusy(candidates)
  1111. if !found {
  1112. if lastError != nil {
  1113. state.fail("pull", lastError)
  1114. } else {
  1115. state.fail("pull", errNoDevice)
  1116. }
  1117. break
  1118. }
  1119. candidates = removeAvailability(candidates, selected)
  1120. // Fetch the block, while marking the selected device as in use so that
  1121. // leastBusy can select another device when someone else asks.
  1122. activity.using(selected)
  1123. buf, lastError := f.model.requestGlobal(selected.ID, f.folderID, state.file.Name, state.block.Offset, int(state.block.Size), state.block.Hash, selected.FromTemporary)
  1124. activity.done(selected)
  1125. if lastError != nil {
  1126. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, "returned error:", lastError)
  1127. continue
  1128. }
  1129. // Verify that the received block matches the desired hash, if not
  1130. // try pulling it from another device.
  1131. _, lastError = scanner.VerifyBuffer(buf, state.block)
  1132. if lastError != nil {
  1133. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, "hash mismatch")
  1134. continue
  1135. }
  1136. // Save the block data we got from the cluster
  1137. _, err = fd.WriteAt(buf, state.block.Offset)
  1138. if err != nil {
  1139. state.fail("save", err)
  1140. } else {
  1141. state.pullDone(state.block)
  1142. }
  1143. break
  1144. }
  1145. out <- state.sharedPullerState
  1146. }
  1147. }
  1148. func (f *sendReceiveFolder) performFinish(state *sharedPullerState) error {
  1149. // Set the correct permission bits on the new file
  1150. if !f.ignorePermissions(state.file) {
  1151. if err := f.fs.Chmod(state.tempName, fs.FileMode(state.file.Permissions&0777)); err != nil {
  1152. return err
  1153. }
  1154. }
  1155. if stat, err := f.fs.Lstat(state.file.Name); err == nil {
  1156. // There is an old file or directory already in place. We need to
  1157. // handle that.
  1158. curMode := uint32(stat.Mode())
  1159. if runtime.GOOS == "windows" && osutil.IsWindowsExecutable(state.file.Name) {
  1160. curMode |= 0111
  1161. }
  1162. // Check that the file on disk is what we expect it to be according
  1163. // to the database. If there's a mismatch here, there might be local
  1164. // changes that we don't know about yet and we should scan before
  1165. // touching the file. There is also a case where we think the file
  1166. // should be there, but it was removed, which is a conflict, yet
  1167. // creations always wins when competing with a deletion, so no need
  1168. // to handle that specially.
  1169. changed := false
  1170. switch {
  1171. case !state.hasCurFile:
  1172. // The file appeared from nowhere
  1173. l.Debugln("file exists but not scanned; not finishing:", state.file.Name)
  1174. changed = true
  1175. case stat.IsDir() != state.curFile.IsDirectory() || stat.IsSymlink() != state.curFile.IsSymlink():
  1176. // The file changed type. IsRegular is implicitly tested in the condition above
  1177. l.Debugln("file type changed but not rescanned; not finishing:", state.curFile.Name)
  1178. changed = true
  1179. case stat.IsRegular():
  1180. if !stat.ModTime().Equal(state.curFile.ModTime()) || stat.Size() != state.curFile.Size {
  1181. l.Debugln("file modified but not rescanned; not finishing:", state.curFile.Name)
  1182. changed = true
  1183. break
  1184. }
  1185. // check permissions
  1186. fallthrough
  1187. case stat.IsDir():
  1188. // Dirs only have perm, no modetime/size
  1189. if !f.ignorePermissions(state.curFile) && state.curFile.HasPermissionBits() && !scanner.PermsEqual(state.curFile.Permissions, curMode) {
  1190. l.Debugln("file permission modified but not rescanned; not finishing:", state.curFile.Name)
  1191. changed = true
  1192. }
  1193. }
  1194. if changed {
  1195. // Scan() is synchronous (i.e. blocks until the scan is
  1196. // completed and returns an error), but a scan can't happen
  1197. // while we're in the puller routine. Request the scan in the
  1198. // background and it'll be handled when the current pulling
  1199. // sweep is complete. As we do retries, we'll queue the scan
  1200. // for this file up to ten times, but the last nine of those
  1201. // scans will be cheap...
  1202. go f.Scan([]string{state.curFile.Name})
  1203. return fmt.Errorf("file modified but not rescanned; will try again later")
  1204. }
  1205. switch {
  1206. case stat.IsDir() || stat.IsSymlink():
  1207. // It's a directory or a symlink. These are not versioned or
  1208. // archived for conflicts, only removed (which of course fails for
  1209. // non-empty directories).
  1210. // 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.SchedulePull()
  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. }