rwfolder.go 51 KB

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