folder_sendrecv.go 60 KB

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