folder_sendrecv.go 60 KB

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