1
0

folder_sendrecv.go 62 KB

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