rwfolder.go 52 KB

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