folder_sendrecv.go 59 KB

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