rwfolder.go 55 KB

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