folder_sendrecv.go 66 KB

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