rwfolder.go 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  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. changed := false
  1186. switch {
  1187. case !state.hasCurFile:
  1188. // The file appeared from nowhere
  1189. l.Debugln("file exists but not scanned; not finishing:", state.file.Name)
  1190. changed = true
  1191. case stat.IsDir() != state.curFile.IsDirectory() || stat.IsSymlink() != state.curFile.IsSymlink():
  1192. // The file changed type. IsRegular is implicitly tested in the condition above
  1193. l.Debugln("file type changed but not rescanned; not finishing:", state.curFile.Name)
  1194. changed = true
  1195. case stat.IsRegular():
  1196. if !stat.ModTime().Equal(state.curFile.ModTime()) || stat.Size() != state.curFile.Size {
  1197. l.Debugln("file modified but not rescanned; not finishing:", state.curFile.Name)
  1198. changed = true
  1199. break
  1200. }
  1201. // check permissions
  1202. fallthrough
  1203. case stat.IsDir():
  1204. // Dirs only have perm, no modetime/size
  1205. if !f.ignorePermissions(state.curFile) && state.curFile.HasPermissionBits() && !scanner.PermsEqual(state.curFile.Permissions, curMode) {
  1206. l.Debugln("file permission modified but not rescanned; not finishing:", state.curFile.Name)
  1207. changed = true
  1208. }
  1209. }
  1210. if changed {
  1211. // Scan() is synchronous (i.e. blocks until the scan is
  1212. // completed and returns an error), but a scan can't happen
  1213. // while we're in the puller routine. Request the scan in the
  1214. // background and it'll be handled when the current pulling
  1215. // sweep is complete. As we do retries, we'll queue the scan
  1216. // for this file up to ten times, but the last nine of those
  1217. // scans will be cheap...
  1218. go f.Scan([]string{state.curFile.Name})
  1219. return fmt.Errorf("file modified but not rescanned; will try again later")
  1220. }
  1221. switch {
  1222. case stat.IsDir() || stat.IsSymlink():
  1223. // It's a directory or a symlink. These are not versioned or
  1224. // archived for conflicts, only removed (which of course fails for
  1225. // non-empty directories).
  1226. // TODO: This is the place where we want to remove temporary files
  1227. // and future hard ignores before attempting a directory delete.
  1228. // Should share code with f.deletDir().
  1229. if err = osutil.InWritableDir(f.fs.Remove, f.fs, state.file.Name); err != nil {
  1230. return err
  1231. }
  1232. case f.inConflict(state.curFile.Version, state.file.Version):
  1233. // The new file has been changed in conflict with the existing one. We
  1234. // should file it away as a conflict instead of just removing or
  1235. // archiving. Also merge with the version vector we had, to indicate
  1236. // we have resolved the conflict.
  1237. state.file.Version = state.file.Version.Merge(state.curFile.Version)
  1238. err = osutil.InWritableDir(func(name string) error {
  1239. return f.moveForConflict(name, state.file.ModifiedBy.String())
  1240. }, f.fs, state.file.Name)
  1241. if err != nil {
  1242. return err
  1243. }
  1244. case f.versioner != nil && !state.file.IsSymlink():
  1245. // If we should use versioning, let the versioner archive the old
  1246. // file before we replace it. Archiving a non-existent file is not
  1247. // an error.
  1248. if err = f.versioner.Archive(state.file.Name); err != nil {
  1249. return err
  1250. }
  1251. }
  1252. }
  1253. // Replace the original content with the new one. If it didn't work,
  1254. // leave the temp file in place for reuse.
  1255. if err := osutil.TryRename(f.fs, state.tempName, state.file.Name); err != nil {
  1256. return err
  1257. }
  1258. // Set the correct timestamp on the new file
  1259. f.fs.Chtimes(state.file.Name, state.file.ModTime(), state.file.ModTime()) // never fails
  1260. // Record the updated file in the index
  1261. f.dbUpdates <- dbUpdateJob{state.file, dbUpdateHandleFile}
  1262. return nil
  1263. }
  1264. func (f *sendReceiveFolder) finisherRoutine(in <-chan *sharedPullerState) {
  1265. for state := range in {
  1266. if closed, err := state.finalClose(); closed {
  1267. l.Debugln(f, "closing", state.file.Name)
  1268. f.queue.Done(state.file.Name)
  1269. if err == nil {
  1270. err = f.performFinish(state)
  1271. }
  1272. if err != nil {
  1273. f.newError("finisher", state.file.Name, err)
  1274. } else {
  1275. blockStatsMut.Lock()
  1276. blockStats["total"] += state.reused + state.copyTotal + state.pullTotal
  1277. blockStats["reused"] += state.reused
  1278. blockStats["pulled"] += state.pullTotal
  1279. // copyOriginShifted is counted towards copyOrigin due to progress bar reasons
  1280. // for reporting reasons we want to separate these.
  1281. blockStats["copyOrigin"] += state.copyOrigin - state.copyOriginShifted
  1282. blockStats["copyOriginShifted"] += state.copyOriginShifted
  1283. blockStats["copyElsewhere"] += state.copyTotal - state.copyOrigin
  1284. blockStatsMut.Unlock()
  1285. }
  1286. events.Default.Log(events.ItemFinished, map[string]interface{}{
  1287. "folder": f.folderID,
  1288. "item": state.file.Name,
  1289. "error": events.Error(err),
  1290. "type": "file",
  1291. "action": "update",
  1292. })
  1293. if f.model.progressEmitter != nil {
  1294. f.model.progressEmitter.Deregister(state)
  1295. }
  1296. }
  1297. }
  1298. }
  1299. // Moves the given filename to the front of the job queue
  1300. func (f *sendReceiveFolder) BringToFront(filename string) {
  1301. f.queue.BringToFront(filename)
  1302. }
  1303. func (f *sendReceiveFolder) Jobs() ([]string, []string) {
  1304. return f.queue.Jobs()
  1305. }
  1306. // dbUpdaterRoutine aggregates db updates and commits them in batches no
  1307. // larger than 1000 items, and no more delayed than 2 seconds.
  1308. func (f *sendReceiveFolder) dbUpdaterRoutine() {
  1309. const maxBatchTime = 2 * time.Second
  1310. batch := make([]dbUpdateJob, 0, maxBatchSizeFiles)
  1311. files := make([]protocol.FileInfo, 0, maxBatchSizeFiles)
  1312. tick := time.NewTicker(maxBatchTime)
  1313. defer tick.Stop()
  1314. changedDirs := make(map[string]struct{})
  1315. handleBatch := func() {
  1316. found := false
  1317. var lastFile protocol.FileInfo
  1318. for _, job := range batch {
  1319. files = append(files, job.file)
  1320. switch job.jobType {
  1321. case dbUpdateHandleFile, dbUpdateShortcutFile:
  1322. changedDirs[filepath.Dir(job.file.Name)] = struct{}{}
  1323. case dbUpdateHandleDir:
  1324. changedDirs[job.file.Name] = struct{}{}
  1325. case dbUpdateHandleSymlink, dbUpdateInvalidate:
  1326. // fsyncing symlinks is only supported by MacOS
  1327. // and invalidated files are db only changes -> no sync
  1328. }
  1329. if job.file.IsInvalid() || (job.file.IsDirectory() && !job.file.IsSymlink()) {
  1330. continue
  1331. }
  1332. if job.jobType&(dbUpdateHandleFile|dbUpdateDeleteFile) == 0 {
  1333. continue
  1334. }
  1335. found = true
  1336. lastFile = job.file
  1337. }
  1338. // sync directories
  1339. for dir := range changedDirs {
  1340. delete(changedDirs, dir)
  1341. fd, err := f.fs.Open(dir)
  1342. if err != nil {
  1343. l.Debugf("fsync %q failed: %v", dir, err)
  1344. continue
  1345. }
  1346. if err := fd.Sync(); err != nil {
  1347. l.Debugf("fsync %q failed: %v", dir, err)
  1348. }
  1349. fd.Close()
  1350. }
  1351. // All updates to file/folder objects that originated remotely
  1352. // (across the network) use this call to updateLocals
  1353. f.model.updateLocalsFromPulling(f.folderID, files)
  1354. if found {
  1355. f.model.receivedFile(f.folderID, lastFile)
  1356. }
  1357. batch = batch[:0]
  1358. files = files[:0]
  1359. }
  1360. batchSizeBytes := 0
  1361. loop:
  1362. for {
  1363. select {
  1364. case job, ok := <-f.dbUpdates:
  1365. if !ok {
  1366. break loop
  1367. }
  1368. job.file.Sequence = 0
  1369. batch = append(batch, job)
  1370. batchSizeBytes += job.file.ProtoSize()
  1371. if len(batch) == maxBatchSizeFiles || batchSizeBytes > maxBatchSizeBytes {
  1372. handleBatch()
  1373. batchSizeBytes = 0
  1374. }
  1375. case <-tick.C:
  1376. if len(batch) > 0 {
  1377. handleBatch()
  1378. batchSizeBytes = 0
  1379. }
  1380. }
  1381. }
  1382. if len(batch) > 0 {
  1383. handleBatch()
  1384. }
  1385. }
  1386. func (f *sendReceiveFolder) inConflict(current, replacement protocol.Vector) bool {
  1387. if current.Concurrent(replacement) {
  1388. // Obvious case
  1389. return true
  1390. }
  1391. if replacement.Counter(f.model.shortID) > current.Counter(f.model.shortID) {
  1392. // The replacement file contains a higher version for ourselves than
  1393. // what we have. This isn't supposed to be possible, since it's only
  1394. // we who can increment that counter. We take it as a sign that
  1395. // something is wrong (our index may have been corrupted or removed)
  1396. // and flag it as a conflict.
  1397. return true
  1398. }
  1399. return false
  1400. }
  1401. func removeAvailability(availabilities []Availability, availability Availability) []Availability {
  1402. for i := range availabilities {
  1403. if availabilities[i] == availability {
  1404. availabilities[i] = availabilities[len(availabilities)-1]
  1405. return availabilities[:len(availabilities)-1]
  1406. }
  1407. }
  1408. return availabilities
  1409. }
  1410. func (f *sendReceiveFolder) moveForConflict(name string, lastModBy string) error {
  1411. if strings.Contains(filepath.Base(name), ".sync-conflict-") {
  1412. l.Infoln("Conflict for", name, "which is already a conflict copy; not copying again.")
  1413. if err := f.fs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1414. return err
  1415. }
  1416. return nil
  1417. }
  1418. if f.MaxConflicts == 0 {
  1419. if err := f.fs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1420. return err
  1421. }
  1422. return nil
  1423. }
  1424. ext := filepath.Ext(name)
  1425. withoutExt := name[:len(name)-len(ext)]
  1426. newName := withoutExt + time.Now().Format(".sync-conflict-20060102-150405-") + lastModBy + ext
  1427. err := f.fs.Rename(name, newName)
  1428. if fs.IsNotExist(err) {
  1429. // We were supposed to move a file away but it does not exist. Either
  1430. // the user has already moved it away, or the conflict was between a
  1431. // remote modification and a local delete. In either way it does not
  1432. // matter, go ahead as if the move succeeded.
  1433. err = nil
  1434. }
  1435. if f.MaxConflicts > -1 {
  1436. matches, gerr := f.fs.Glob(withoutExt + ".sync-conflict-????????-??????*" + ext)
  1437. if gerr == nil && len(matches) > f.MaxConflicts {
  1438. sort.Sort(sort.Reverse(sort.StringSlice(matches)))
  1439. for _, match := range matches[f.MaxConflicts:] {
  1440. gerr = f.fs.Remove(match)
  1441. if gerr != nil {
  1442. l.Debugln(f, "removing extra conflict", gerr)
  1443. }
  1444. }
  1445. } else if gerr != nil {
  1446. l.Debugln(f, "globbing for conflicts", gerr)
  1447. }
  1448. }
  1449. return err
  1450. }
  1451. func (f *sendReceiveFolder) newError(context, path string, err error) {
  1452. f.errorsMut.Lock()
  1453. defer f.errorsMut.Unlock()
  1454. // We might get more than one error report for a file (i.e. error on
  1455. // Write() followed by Close()); we keep the first error as that is
  1456. // probably closer to the root cause.
  1457. if _, ok := f.errors[path]; ok {
  1458. return
  1459. }
  1460. l.Infof("Puller (folder %q, file %q): %s: %v", f.Description(), path, context, err)
  1461. f.errors[path] = fmt.Sprintf("%s: %s", context, err.Error())
  1462. }
  1463. func (f *sendReceiveFolder) clearErrors() {
  1464. f.errorsMut.Lock()
  1465. f.errors = make(map[string]string)
  1466. f.errorsMut.Unlock()
  1467. }
  1468. func (f *sendReceiveFolder) currentErrors() []fileError {
  1469. f.errorsMut.Lock()
  1470. errors := make([]fileError, 0, len(f.errors))
  1471. for path, err := range f.errors {
  1472. errors = append(errors, fileError{path, err})
  1473. }
  1474. sort.Sort(fileErrorList(errors))
  1475. f.errorsMut.Unlock()
  1476. return errors
  1477. }
  1478. func (f *sendReceiveFolder) basePause() time.Duration {
  1479. if f.PullerPauseS == 0 {
  1480. return defaultPullerPause
  1481. }
  1482. return time.Duration(f.PullerPauseS) * time.Second
  1483. }
  1484. func (f *sendReceiveFolder) IgnoresUpdated() {
  1485. f.folder.IgnoresUpdated()
  1486. f.IndexUpdated()
  1487. }
  1488. // A []fileError is sent as part of an event and will be JSON serialized.
  1489. type fileError struct {
  1490. Path string `json:"path"`
  1491. Err string `json:"error"`
  1492. }
  1493. type fileErrorList []fileError
  1494. func (l fileErrorList) Len() int {
  1495. return len(l)
  1496. }
  1497. func (l fileErrorList) Less(a, b int) bool {
  1498. return l[a].Path < l[b].Path
  1499. }
  1500. func (l fileErrorList) Swap(a, b int) {
  1501. l[a], l[b] = l[b], l[a]
  1502. }
  1503. // byComponentCount sorts by the number of path components in Name, that is
  1504. // "x/y" sorts before "foo/bar/baz".
  1505. type byComponentCount []protocol.FileInfo
  1506. func (l byComponentCount) Len() int {
  1507. return len(l)
  1508. }
  1509. func (l byComponentCount) Less(a, b int) bool {
  1510. return componentCount(l[a].Name) < componentCount(l[b].Name)
  1511. }
  1512. func (l byComponentCount) Swap(a, b int) {
  1513. l[a], l[b] = l[b], l[a]
  1514. }
  1515. func componentCount(name string) int {
  1516. count := 0
  1517. for _, codepoint := range name {
  1518. if codepoint == fs.PathSeparator {
  1519. count++
  1520. }
  1521. }
  1522. return count
  1523. }