folder_sendrecv.go 60 KB

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