rwfolder.go 52 KB

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