folder_sendrecv.go 59 KB

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