folder_sendrecv.go 60 KB

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