folder_sendrecv.go 68 KB

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