folder_sendrecv.go 66 KB

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