folder_sendrecv.go 59 KB

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