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