folder_sendrecv.go 60 KB

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