folder_sendrecv.go 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234
  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. "errors"
  10. "fmt"
  11. "io"
  12. "path/filepath"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  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 copying 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. f.newPullError(file.Name, fmt.Errorf("handling dir: %w", err))
  505. return
  506. }
  507. // Remove it to replace with the dir.
  508. if !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  509. // The new file has been changed in conflict with the existing one. We
  510. // should file it away as a conflict instead of just removing or
  511. // archiving.
  512. // Symlinks aren't checked for conflicts.
  513. err = f.inWritableDir(func(name string) error {
  514. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  515. }, curFile.Name)
  516. } else {
  517. err = f.deleteItemOnDisk(curFile, snap, scanChan)
  518. }
  519. if err != nil {
  520. f.newPullError(file.Name, err)
  521. return
  522. }
  523. fallthrough
  524. // The directory doesn't exist, so we create it with the right
  525. // mode bits from the start.
  526. case err != nil && fs.IsNotExist(err):
  527. // We declare a function that acts on only the path name, so
  528. // we can pass it to InWritableDir. We use a regular Mkdir and
  529. // not MkdirAll because the parent should already exist.
  530. mkdir := func(path string) error {
  531. err = f.mtimefs.Mkdir(path, mode)
  532. if err != nil || f.IgnorePerms || file.NoPermissions {
  533. return err
  534. }
  535. // Adjust the ownership, if we are supposed to do that.
  536. if err := f.maybeAdjustOwnership(&file, path); err != nil {
  537. return err
  538. }
  539. // Stat the directory so we can check its permissions.
  540. info, err := f.mtimefs.Lstat(path)
  541. if err != nil {
  542. return err
  543. }
  544. // Mask for the bits we want to preserve and add them in to the
  545. // directories permissions.
  546. return f.mtimefs.Chmod(path, mode|(info.Mode()&retainBits))
  547. }
  548. if err = f.inWritableDir(mkdir, file.Name); err == nil {
  549. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  550. } else {
  551. f.newPullError(file.Name, fmt.Errorf("creating directory: %w", err))
  552. }
  553. return
  554. // Weird error when stat()'ing the dir. Probably won't work to do
  555. // anything else with it if we can't even stat() it.
  556. case err != nil:
  557. f.newPullError(file.Name, fmt.Errorf("checking file to be replaced: %w", err))
  558. return
  559. }
  560. // The directory already exists, so we just correct the mode bits. (We
  561. // don't handle modification times on directories, because that sucks...)
  562. // It's OK to change mode bits on stuff within non-writable directories.
  563. if !f.IgnorePerms && !file.NoPermissions {
  564. if err := f.mtimefs.Chmod(file.Name, mode|(info.Mode()&retainBits)); err != nil {
  565. f.newPullError(file.Name, fmt.Errorf("handling dir (setting permissions): %w", err))
  566. return
  567. }
  568. }
  569. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  570. }
  571. // checkParent verifies that the thing we are handling lives inside a directory,
  572. // and not a symlink or regular file. It also resurrects missing parent dirs.
  573. func (f *sendReceiveFolder) checkParent(file string, scanChan chan<- string) bool {
  574. parent := filepath.Dir(file)
  575. if err := osutil.TraversesSymlink(f.mtimefs, parent); err != nil {
  576. f.newPullError(file, fmt.Errorf("checking parent dirs: %w", err))
  577. return false
  578. }
  579. // issues #114 and #4475: This works around a race condition
  580. // between two devices, when one device removes a directory and the
  581. // other creates a file in it. However that happens, we end up with
  582. // a directory for "foo" with the delete bit, but a file "foo/bar"
  583. // that we want to sync. We never create the directory, and hence
  584. // fail to create the file and end up looping forever on it. This
  585. // breaks that by creating the directory and scheduling a scan,
  586. // where it will be found and the delete bit on it removed. The
  587. // user can then clean up as they like...
  588. // This can also occur if an entire tree structure was deleted, but only
  589. // a leave has been scanned.
  590. //
  591. // And if this is an encrypted folder:
  592. // Encrypted files have made-up filenames with two synthetic parent
  593. // directories which don't have any meaning. Create those if necessary.
  594. if _, err := f.mtimefs.Lstat(parent); !fs.IsNotExist(err) {
  595. l.Debugf("%v parent not missing %v", f, file)
  596. return true
  597. }
  598. l.Debugf("%v creating parent directory of %v", f, file)
  599. if err := f.mtimefs.MkdirAll(parent, 0755); err != nil {
  600. f.newPullError(file, fmt.Errorf("creating parent dir: %w", err))
  601. return false
  602. }
  603. if f.Type != config.FolderTypeReceiveEncrypted {
  604. scanChan <- parent
  605. }
  606. return true
  607. }
  608. // handleSymlink creates or updates the given symlink
  609. func (f *sendReceiveFolder) handleSymlink(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  610. // Used in the defer closure below, updated by the function body. Take
  611. // care not declare another err.
  612. var err error
  613. f.evLogger.Log(events.ItemStarted, map[string]string{
  614. "folder": f.folderID,
  615. "item": file.Name,
  616. "type": "symlink",
  617. "action": "update",
  618. })
  619. defer func() {
  620. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  621. "folder": f.folderID,
  622. "item": file.Name,
  623. "error": events.Error(err),
  624. "type": "symlink",
  625. "action": "update",
  626. })
  627. }()
  628. if shouldDebug() {
  629. curFile, _ := snap.Get(protocol.LocalDeviceID, file.Name)
  630. l.Debugf("need symlink\n\t%v\n\t%v", file, curFile)
  631. }
  632. if file.SymlinkTarget == "" {
  633. // Index entry from a Syncthing predating the support for including
  634. // the link target in the index entry. We log this as an error.
  635. f.newPullError(file.Name, errIncompatibleSymlink)
  636. return
  637. }
  638. if err = f.handleSymlinkCheckExisting(file, snap, scanChan); err != nil {
  639. f.newPullError(file.Name, fmt.Errorf("handling symlink: %w", err))
  640. return
  641. }
  642. // We declare a function that acts on only the path name, so
  643. // we can pass it to InWritableDir.
  644. createLink := func(path string) error {
  645. if err := f.mtimefs.CreateSymlink(file.SymlinkTarget, path); err != nil {
  646. return err
  647. }
  648. return f.maybeAdjustOwnership(&file, path)
  649. }
  650. if err = f.inWritableDir(createLink, file.Name); err == nil {
  651. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleSymlink}
  652. } else {
  653. f.newPullError(file.Name, fmt.Errorf("symlink create: %w", err))
  654. }
  655. }
  656. func (f *sendReceiveFolder) handleSymlinkCheckExisting(file protocol.FileInfo, snap *db.Snapshot, scanChan chan<- string) error {
  657. // If there is already something under that name, we need to handle that.
  658. info, err := f.mtimefs.Lstat(file.Name)
  659. if err != nil {
  660. if fs.IsNotExist(err) {
  661. return nil
  662. }
  663. return err
  664. }
  665. // Check that it is what we have in the database.
  666. curFile, hasCurFile := snap.Get(protocol.LocalDeviceID, file.Name)
  667. if err := f.scanIfItemChanged(file.Name, info, curFile, hasCurFile, scanChan); err != nil {
  668. return err
  669. }
  670. // Remove it to replace with the symlink. This also handles the
  671. // "change symlink type" path.
  672. if !curFile.IsDirectory() && !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  673. // The new file has been changed in conflict with the existing one. We
  674. // should file it away as a conflict instead of just removing or
  675. // archiving.
  676. // Directories and symlinks aren't checked for conflicts.
  677. return f.inWritableDir(func(name string) error {
  678. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  679. }, curFile.Name)
  680. } else {
  681. return f.deleteItemOnDisk(curFile, snap, scanChan)
  682. }
  683. }
  684. // deleteDir attempts to remove a directory that was deleted on a remote
  685. func (f *sendReceiveFolder) deleteDir(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  686. // Used in the defer closure below, updated by the function body. Take
  687. // care not declare another err.
  688. var err error
  689. f.evLogger.Log(events.ItemStarted, map[string]string{
  690. "folder": f.folderID,
  691. "item": file.Name,
  692. "type": "dir",
  693. "action": "delete",
  694. })
  695. defer func() {
  696. if err != nil {
  697. f.newPullError(file.Name, fmt.Errorf("delete dir: %w", err))
  698. }
  699. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  700. "folder": f.folderID,
  701. "item": file.Name,
  702. "error": events.Error(err),
  703. "type": "dir",
  704. "action": "delete",
  705. })
  706. }()
  707. cur, hasCur := snap.Get(protocol.LocalDeviceID, file.Name)
  708. if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
  709. if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
  710. err = nil
  711. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  712. }
  713. return
  714. }
  715. if err = f.deleteDirOnDisk(file.Name, snap, scanChan); err != nil {
  716. return
  717. }
  718. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  719. }
  720. // deleteFile attempts to delete the given file
  721. func (f *sendReceiveFolder) deleteFile(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  722. cur, hasCur := snap.Get(protocol.LocalDeviceID, file.Name)
  723. f.deleteFileWithCurrent(file, cur, hasCur, dbUpdateChan, scanChan)
  724. }
  725. func (f *sendReceiveFolder) deleteFileWithCurrent(file, cur protocol.FileInfo, hasCur bool, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  726. // Used in the defer closure below, updated by the function body. Take
  727. // care not declare another err.
  728. var err error
  729. l.Debugln(f, "Deleting file", file.Name)
  730. f.evLogger.Log(events.ItemStarted, map[string]string{
  731. "folder": f.folderID,
  732. "item": file.Name,
  733. "type": "file",
  734. "action": "delete",
  735. })
  736. defer func() {
  737. if err != nil {
  738. f.newPullError(file.Name, fmt.Errorf("delete file: %w", err))
  739. }
  740. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  741. "folder": f.folderID,
  742. "item": file.Name,
  743. "error": events.Error(err),
  744. "type": "file",
  745. "action": "delete",
  746. })
  747. }()
  748. if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
  749. if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
  750. err = nil
  751. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  752. }
  753. return
  754. }
  755. // We are asked to delete a file, but what we have on disk and in db
  756. // is a directory. Something is wrong here, should probably not happen.
  757. if cur.IsDirectory() {
  758. err = errUnexpectedDirOnFileDel
  759. return
  760. }
  761. if f.inConflict(cur.Version, file.Version) {
  762. // There is a conflict here, which shouldn't happen as deletions
  763. // always lose. Merge the version vector of the file we have
  764. // locally and commit it to db to resolve the conflict.
  765. cur.Version = cur.Version.Merge(file.Version)
  766. dbUpdateChan <- dbUpdateJob{cur, dbUpdateHandleFile}
  767. return
  768. }
  769. if f.versioner != nil && !cur.IsSymlink() {
  770. err = f.inWritableDir(f.versioner.Archive, file.Name)
  771. } else {
  772. err = f.inWritableDir(f.mtimefs.Remove, file.Name)
  773. }
  774. if err == nil || fs.IsNotExist(err) {
  775. // It was removed or it doesn't exist to start with
  776. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  777. return
  778. }
  779. if _, serr := f.mtimefs.Lstat(file.Name); serr != nil && !fs.IsPermission(serr) {
  780. // We get an error just looking at the file, and it's not a permission
  781. // problem. Lets assume the error is in fact some variant of "file
  782. // does not exist" (possibly expressed as some parent being a file and
  783. // not a directory etc) and that the delete is handled.
  784. err = nil
  785. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  786. }
  787. }
  788. // renameFile attempts to rename an existing file to a destination
  789. // and set the right attributes on it.
  790. func (f *sendReceiveFolder) renameFile(cur, source, target protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  791. // Used in the defer closure below, updated by the function body. Take
  792. // care not declare another err.
  793. var err error
  794. f.evLogger.Log(events.ItemStarted, map[string]string{
  795. "folder": f.folderID,
  796. "item": source.Name,
  797. "type": "file",
  798. "action": "delete",
  799. })
  800. f.evLogger.Log(events.ItemStarted, map[string]string{
  801. "folder": f.folderID,
  802. "item": target.Name,
  803. "type": "file",
  804. "action": "update",
  805. })
  806. defer func() {
  807. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  808. "folder": f.folderID,
  809. "item": source.Name,
  810. "error": events.Error(err),
  811. "type": "file",
  812. "action": "delete",
  813. })
  814. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  815. "folder": f.folderID,
  816. "item": target.Name,
  817. "error": events.Error(err),
  818. "type": "file",
  819. "action": "update",
  820. })
  821. }()
  822. l.Debugln(f, "taking rename shortcut", source.Name, "->", target.Name)
  823. // Check that source is compatible with what we have in the DB
  824. if err = f.checkToBeDeleted(source, cur, true, scanChan); err != nil {
  825. return err
  826. }
  827. // Check that the target corresponds to what we have in the DB
  828. curTarget, ok := snap.Get(protocol.LocalDeviceID, target.Name)
  829. switch stat, serr := f.mtimefs.Lstat(target.Name); {
  830. case serr != nil:
  831. var caseErr *fs.ErrCaseConflict
  832. switch {
  833. case errors.As(serr, &caseErr):
  834. if caseErr.Real != source.Name {
  835. err = serr
  836. break
  837. }
  838. fallthrough // This is a case only rename
  839. case fs.IsNotExist(serr):
  840. if !ok || curTarget.IsDeleted() {
  841. break
  842. }
  843. scanChan <- target.Name
  844. err = errModified
  845. default:
  846. // We can't check whether the file changed as compared to the db,
  847. // do not delete.
  848. err = serr
  849. }
  850. case !ok:
  851. // Target appeared from nowhere
  852. scanChan <- target.Name
  853. err = errModified
  854. default:
  855. var fi protocol.FileInfo
  856. if fi, err = scanner.CreateFileInfo(stat, target.Name, f.mtimefs, f.SyncOwnership, f.SyncXattrs, f.XattrFilter); err == nil {
  857. if !fi.IsEquivalentOptional(curTarget, protocol.FileInfoComparison{
  858. ModTimeWindow: f.modTimeWindow,
  859. IgnorePerms: f.IgnorePerms,
  860. IgnoreBlocks: true,
  861. IgnoreFlags: protocol.LocalAllFlags,
  862. IgnoreOwnership: !f.SyncOwnership,
  863. IgnoreXattrs: !f.SyncXattrs,
  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 metadata, when that's the only thing that has
  1041. // 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, fmt.Errorf("shortcut file (setting permissions): %w", err))
  1062. return
  1063. }
  1064. }
  1065. if f.SyncXattrs {
  1066. if err = f.mtimefs.SetXattr(file.Name, file.Platform.Xattrs(), f.XattrFilter); errors.Is(err, fs.ErrXattrsNotSupported) {
  1067. l.Debugf("Cannot set xattrs on %q: %v", file.Name, err)
  1068. } else if err != nil {
  1069. f.newPullError(file.Name, fmt.Errorf("shortcut file (setting xattrs): %w", err))
  1070. return
  1071. }
  1072. }
  1073. if err := f.maybeAdjustOwnership(&file, file.Name); err != nil {
  1074. f.newPullError(file.Name, fmt.Errorf("shortcut file (setting ownership): %w", err))
  1075. return
  1076. }
  1077. // Still need to re-write the trailer with the new encrypted fileinfo.
  1078. if f.Type == config.FolderTypeReceiveEncrypted {
  1079. err = inWritableDir(func(path string) error {
  1080. fd, err := f.mtimefs.OpenFile(path, fs.OptReadWrite, 0666)
  1081. if err != nil {
  1082. return err
  1083. }
  1084. defer fd.Close()
  1085. trailerSize, err := writeEncryptionTrailer(file, fd)
  1086. if err != nil {
  1087. return err
  1088. }
  1089. return fd.Truncate(file.Size + trailerSize)
  1090. }, f.mtimefs, file.Name, true)
  1091. if err != nil {
  1092. f.newPullError(file.Name, fmt.Errorf("writing encrypted file trailer: %w", err))
  1093. return
  1094. }
  1095. }
  1096. f.mtimefs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  1097. dbUpdateChan <- dbUpdateJob{file, dbUpdateShortcutFile}
  1098. }
  1099. // copierRoutine reads copierStates until the in channel closes and performs
  1100. // the relevant copies when possible, or passes it to the puller routine.
  1101. func (f *sendReceiveFolder) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
  1102. buf := protocol.BufferPool.Get(protocol.MinBlockSize)
  1103. defer func() {
  1104. protocol.BufferPool.Put(buf)
  1105. }()
  1106. folderFilesystems := make(map[string]fs.Filesystem)
  1107. // Hope that it's usually in the same folder, so start with that one.
  1108. folders := []string{f.folderID}
  1109. for folder, cfg := range f.model.cfg.Folders() {
  1110. folderFilesystems[folder] = cfg.Filesystem(nil)
  1111. if folder != f.folderID {
  1112. folders = append(folders, folder)
  1113. }
  1114. }
  1115. for state := range in {
  1116. if err := f.CheckAvailableSpace(uint64(state.file.Size)); err != nil {
  1117. state.fail(err)
  1118. // Nothing more to do for this failed file, since it would use to much disk space
  1119. out <- state.sharedPullerState
  1120. continue
  1121. }
  1122. dstFd, err := state.tempFile()
  1123. if err != nil {
  1124. // Nothing more to do for this failed file, since we couldn't create a temporary for it.
  1125. out <- state.sharedPullerState
  1126. continue
  1127. }
  1128. if f.Type != config.FolderTypeReceiveEncrypted {
  1129. f.model.progressEmitter.Register(state.sharedPullerState)
  1130. }
  1131. weakHashFinder, file := f.initWeakHashFinder(state)
  1132. blocks:
  1133. for _, block := range state.blocks {
  1134. select {
  1135. case <-f.ctx.Done():
  1136. state.fail(fmt.Errorf("folder stopped: %w", f.ctx.Err()))
  1137. break blocks
  1138. default:
  1139. }
  1140. if !f.DisableSparseFiles && state.reused == 0 && block.IsEmpty() {
  1141. // The block is a block of all zeroes, and we are not reusing
  1142. // a temp file, so there is no need to do anything with it.
  1143. // If we were reusing a temp file and had this block to copy,
  1144. // it would be because the block in the temp file was *not* a
  1145. // block of all zeroes, so then we should not skip it.
  1146. // Pretend we copied it.
  1147. state.copiedFromOrigin()
  1148. state.copyDone(block)
  1149. continue
  1150. }
  1151. buf = protocol.BufferPool.Upgrade(buf, int(block.Size))
  1152. var found bool
  1153. if f.Type != config.FolderTypeReceiveEncrypted {
  1154. found, err = weakHashFinder.Iterate(block.WeakHash, buf, func(offset int64) bool {
  1155. if f.verifyBuffer(buf, block) != nil {
  1156. return true
  1157. }
  1158. err = f.limitedWriteAt(dstFd, buf, block.Offset)
  1159. if err != nil {
  1160. state.fail(fmt.Errorf("dst write: %w", err))
  1161. }
  1162. if offset == block.Offset {
  1163. state.copiedFromOrigin()
  1164. } else {
  1165. state.copiedFromOriginShifted()
  1166. }
  1167. return false
  1168. })
  1169. if err != nil {
  1170. l.Debugln("weak hasher iter", err)
  1171. }
  1172. }
  1173. if !found {
  1174. found = f.model.finder.Iterate(folders, block.Hash, func(folder, path string, index int32) bool {
  1175. ffs := folderFilesystems[folder]
  1176. fd, err := ffs.Open(path)
  1177. if err != nil {
  1178. return false
  1179. }
  1180. defer fd.Close()
  1181. srcOffset := int64(state.file.BlockSize()) * int64(index)
  1182. _, err = fd.ReadAt(buf, srcOffset)
  1183. if err != nil {
  1184. return false
  1185. }
  1186. // Hash is not SHA256 as it's an encrypted hash token. In that
  1187. // case we can't verify the block integrity so we'll take it on
  1188. // trust. (The other side can and will verify.)
  1189. if f.Type != config.FolderTypeReceiveEncrypted {
  1190. if err := f.verifyBuffer(buf, block); err != nil {
  1191. l.Debugln("Finder failed to verify buffer", err)
  1192. return false
  1193. }
  1194. }
  1195. if f.CopyRangeMethod != fs.CopyRangeMethodStandard {
  1196. err = f.withLimiter(func() error {
  1197. dstFd.mut.Lock()
  1198. defer dstFd.mut.Unlock()
  1199. return fs.CopyRange(f.CopyRangeMethod, fd, dstFd.fd, srcOffset, block.Offset, int64(block.Size))
  1200. })
  1201. } else {
  1202. err = f.limitedWriteAt(dstFd, buf, block.Offset)
  1203. }
  1204. if err != nil {
  1205. state.fail(fmt.Errorf("dst write: %w", err))
  1206. }
  1207. if path == state.file.Name {
  1208. state.copiedFromOrigin()
  1209. }
  1210. return true
  1211. })
  1212. }
  1213. if state.failed() != nil {
  1214. break
  1215. }
  1216. if !found {
  1217. state.pullStarted()
  1218. ps := pullBlockState{
  1219. sharedPullerState: state.sharedPullerState,
  1220. block: block,
  1221. }
  1222. pullChan <- ps
  1223. } else {
  1224. state.copyDone(block)
  1225. }
  1226. }
  1227. if file != nil {
  1228. // os.File used to return invalid argument if nil.
  1229. // fs.File panics as it's an interface.
  1230. file.Close()
  1231. }
  1232. out <- state.sharedPullerState
  1233. }
  1234. }
  1235. func (f *sendReceiveFolder) initWeakHashFinder(state copyBlocksState) (*weakhash.Finder, fs.File) {
  1236. if f.Type == config.FolderTypeReceiveEncrypted {
  1237. l.Debugln("not weak hashing due to folder type", f.Type)
  1238. return nil, nil
  1239. }
  1240. blocksPercentChanged := 0
  1241. if tot := len(state.file.Blocks); tot > 0 {
  1242. blocksPercentChanged = (tot - state.have) * 100 / tot
  1243. }
  1244. if blocksPercentChanged < f.WeakHashThresholdPct {
  1245. l.Debugf("not weak hashing %s. not enough changed %.02f < %d", state.file.Name, blocksPercentChanged, f.WeakHashThresholdPct)
  1246. return nil, nil
  1247. }
  1248. hashesToFind := make([]uint32, 0, len(state.blocks))
  1249. for _, block := range state.blocks {
  1250. if block.WeakHash != 0 {
  1251. hashesToFind = append(hashesToFind, block.WeakHash)
  1252. }
  1253. }
  1254. if len(hashesToFind) == 0 {
  1255. l.Debugf("not weak hashing %s. file did not contain any weak hashes", state.file.Name)
  1256. return nil, nil
  1257. }
  1258. file, err := f.mtimefs.Open(state.file.Name)
  1259. if err != nil {
  1260. l.Debugln("weak hasher", err)
  1261. return nil, nil
  1262. }
  1263. weakHashFinder, err := weakhash.NewFinder(f.ctx, file, state.file.BlockSize(), hashesToFind)
  1264. if err != nil {
  1265. l.Debugln("weak hasher", err)
  1266. return nil, file
  1267. }
  1268. return weakHashFinder, file
  1269. }
  1270. func (*sendReceiveFolder) verifyBuffer(buf []byte, block protocol.BlockInfo) error {
  1271. if len(buf) != int(block.Size) {
  1272. return fmt.Errorf("length mismatch %d != %d", len(buf), block.Size)
  1273. }
  1274. hash := sha256.Sum256(buf)
  1275. if !bytes.Equal(hash[:], block.Hash) {
  1276. return fmt.Errorf("hash mismatch %x != %x", hash, block.Hash)
  1277. }
  1278. return nil
  1279. }
  1280. func (f *sendReceiveFolder) pullerRoutine(snap *db.Snapshot, in <-chan pullBlockState, out chan<- *sharedPullerState) {
  1281. requestLimiter := util.NewSemaphore(f.PullerMaxPendingKiB * 1024)
  1282. wg := sync.NewWaitGroup()
  1283. for state := range in {
  1284. if state.failed() != nil {
  1285. out <- state.sharedPullerState
  1286. continue
  1287. }
  1288. f.setState(FolderSyncing) // Does nothing if already FolderSyncing
  1289. // The requestLimiter limits how many pending block requests we have
  1290. // ongoing at any given time, based on the size of the blocks
  1291. // themselves.
  1292. state := state
  1293. bytes := int(state.block.Size)
  1294. if err := requestLimiter.TakeWithContext(f.ctx, bytes); err != nil {
  1295. state.fail(err)
  1296. out <- state.sharedPullerState
  1297. continue
  1298. }
  1299. wg.Add(1)
  1300. go func() {
  1301. defer wg.Done()
  1302. defer requestLimiter.Give(bytes)
  1303. f.pullBlock(state, snap, out)
  1304. }()
  1305. }
  1306. wg.Wait()
  1307. }
  1308. func (f *sendReceiveFolder) pullBlock(state pullBlockState, snap *db.Snapshot, out chan<- *sharedPullerState) {
  1309. // Get an fd to the temporary file. Technically we don't need it until
  1310. // after fetching the block, but if we run into an error here there is
  1311. // no point in issuing the request to the network.
  1312. fd, err := state.tempFile()
  1313. if err != nil {
  1314. out <- state.sharedPullerState
  1315. return
  1316. }
  1317. if !f.DisableSparseFiles && state.reused == 0 && state.block.IsEmpty() {
  1318. // There is no need to request a block of all zeroes. Pretend we
  1319. // requested it and handled it correctly.
  1320. state.pullDone(state.block)
  1321. out <- state.sharedPullerState
  1322. return
  1323. }
  1324. var lastError error
  1325. candidates := f.model.availabilityInSnapshot(f.FolderConfiguration, snap, state.file, state.block)
  1326. loop:
  1327. for {
  1328. select {
  1329. case <-f.ctx.Done():
  1330. state.fail(fmt.Errorf("folder stopped: %w", f.ctx.Err()))
  1331. break loop
  1332. default:
  1333. }
  1334. // Select the least busy device to pull the block from. If we found no
  1335. // feasible device at all, fail the block (and in the long run, the
  1336. // file).
  1337. found := activity.leastBusy(candidates)
  1338. if found == -1 {
  1339. if lastError != nil {
  1340. state.fail(fmt.Errorf("pull: %w", lastError))
  1341. } else {
  1342. state.fail(fmt.Errorf("pull: %w", errNoDevice))
  1343. }
  1344. break
  1345. }
  1346. selected := candidates[found]
  1347. candidates[found] = candidates[len(candidates)-1]
  1348. candidates = candidates[:len(candidates)-1]
  1349. // Fetch the block, while marking the selected device as in use so that
  1350. // leastBusy can select another device when someone else asks.
  1351. activity.using(selected)
  1352. var buf []byte
  1353. blockNo := int(state.block.Offset / int64(state.file.BlockSize()))
  1354. 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)
  1355. activity.done(selected)
  1356. if lastError != nil {
  1357. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, selected.ID.Short(), "returned error:", lastError)
  1358. continue
  1359. }
  1360. // Verify that the received block matches the desired hash, if not
  1361. // try pulling it from another device.
  1362. // For receive-only folders, the hash is not SHA256 as it's an
  1363. // encrypted hash token. In that case we can't verify the block
  1364. // integrity so we'll take it on trust. (The other side can and
  1365. // will verify.)
  1366. if f.Type != config.FolderTypeReceiveEncrypted {
  1367. lastError = f.verifyBuffer(buf, state.block)
  1368. }
  1369. if lastError != nil {
  1370. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, "hash mismatch")
  1371. continue
  1372. }
  1373. // Save the block data we got from the cluster
  1374. err = f.limitedWriteAt(fd, buf, state.block.Offset)
  1375. if err != nil {
  1376. state.fail(fmt.Errorf("save: %w", err))
  1377. } else {
  1378. state.pullDone(state.block)
  1379. }
  1380. break
  1381. }
  1382. out <- state.sharedPullerState
  1383. }
  1384. func (f *sendReceiveFolder) performFinish(file, curFile protocol.FileInfo, hasCurFile bool, tempName string, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  1385. // Set the correct permission bits on the new file
  1386. if !f.IgnorePerms && !file.NoPermissions {
  1387. if err := f.mtimefs.Chmod(tempName, fs.FileMode(file.Permissions&0777)); err != nil {
  1388. return fmt.Errorf("setting permissions: %w", err)
  1389. }
  1390. }
  1391. // Set extended attributes
  1392. if f.SyncXattrs {
  1393. if err := f.mtimefs.SetXattr(tempName, file.Platform.Xattrs(), f.XattrFilter); errors.Is(err, fs.ErrXattrsNotSupported) {
  1394. l.Debugf("Cannot set xattrs on %q: %v", file.Name, err)
  1395. } else if err != nil {
  1396. return fmt.Errorf("setting xattrs: %w", err)
  1397. }
  1398. }
  1399. // Set ownership based on file metadata or parent, maybe.
  1400. if err := f.maybeAdjustOwnership(&file, tempName); err != nil {
  1401. return fmt.Errorf("setting ownership: %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, 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. recvEnc := f.Type == config.FolderTypeReceiveEncrypted
  1515. loop:
  1516. for {
  1517. select {
  1518. case job, ok := <-dbUpdateChan:
  1519. if !ok {
  1520. break loop
  1521. }
  1522. switch job.jobType {
  1523. case dbUpdateHandleFile, dbUpdateShortcutFile:
  1524. changedDirs[filepath.Dir(job.file.Name)] = struct{}{}
  1525. if recvEnc {
  1526. job.file.Size += encryptionTrailerSize(job.file)
  1527. }
  1528. case dbUpdateHandleDir:
  1529. changedDirs[job.file.Name] = struct{}{}
  1530. case dbUpdateHandleSymlink, dbUpdateInvalidate:
  1531. // fsyncing symlinks is only supported by MacOS
  1532. // and invalidated files are db only changes -> no sync
  1533. }
  1534. // For some reason we seem to care about file deletions and
  1535. // content modification, but not about metadata and dirs/symlinks.
  1536. if !job.file.IsInvalid() && job.jobType&(dbUpdateHandleFile|dbUpdateDeleteFile) != 0 {
  1537. found = true
  1538. lastFile = job.file
  1539. }
  1540. if !job.file.IsDeleted() && !job.file.IsInvalid() {
  1541. // Now that the file is finalized, grab possibly updated
  1542. // inode change time from disk into the local FileInfo. We
  1543. // use this change time to check for changes to xattrs etc
  1544. // on next scan.
  1545. if err := f.updateFileInfoChangeTime(&job.file); err != nil {
  1546. l.Warnln("Error updating metadata for %q 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, 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: !f.SyncOwnership,
  1815. IgnoreXattrs: !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, scanChan)
  1843. }
  1844. func (f *sendReceiveFolder) maybeAdjustOwnership(file *protocol.FileInfo, name string) error {
  1845. if f.SyncOwnership {
  1846. // Set ownership based on file metadata.
  1847. if err := f.syncOwnership(file, name); err != nil {
  1848. return err
  1849. }
  1850. } else if f.CopyOwnershipFromParent {
  1851. // Copy the parent owner and group.
  1852. if err := f.copyOwnershipFromParent(name); err != nil {
  1853. return err
  1854. }
  1855. }
  1856. // Nothing to do
  1857. return nil
  1858. }
  1859. func (f *sendReceiveFolder) copyOwnershipFromParent(path string) error {
  1860. if build.IsWindows {
  1861. // Can't do anything.
  1862. return nil
  1863. }
  1864. info, err := f.mtimefs.Lstat(filepath.Dir(path))
  1865. if err != nil {
  1866. return fmt.Errorf("copy owner from parent: %w", err)
  1867. }
  1868. if err := f.mtimefs.Lchown(path, strconv.Itoa(info.Owner()), strconv.Itoa(info.Group())); err != nil {
  1869. return fmt.Errorf("copy owner from parent: %w", err)
  1870. }
  1871. return nil
  1872. }
  1873. func (f *sendReceiveFolder) inWritableDir(fn func(string) error, path string) error {
  1874. return inWritableDir(fn, f.mtimefs, path, f.IgnorePerms)
  1875. }
  1876. func (f *sendReceiveFolder) limitedWriteAt(fd io.WriterAt, data []byte, offset int64) error {
  1877. return f.withLimiter(func() error {
  1878. _, err := fd.WriteAt(data, offset)
  1879. return err
  1880. })
  1881. }
  1882. func (f *sendReceiveFolder) withLimiter(fn func() error) error {
  1883. if err := f.writeLimiter.TakeWithContext(f.ctx, 1); err != nil {
  1884. return err
  1885. }
  1886. defer f.writeLimiter.Give(1)
  1887. return fn()
  1888. }
  1889. // updateFileInfoChangeTime updates the inode change time in the FileInfo,
  1890. // because that depends on the current, new, state of the file on disk.
  1891. func (f *sendReceiveFolder) updateFileInfoChangeTime(file *protocol.FileInfo) error {
  1892. info, err := f.mtimefs.Lstat(file.Name)
  1893. if err != nil {
  1894. return err
  1895. }
  1896. if ct := info.InodeChangeTime(); !ct.IsZero() {
  1897. file.InodeChangeNs = ct.UnixNano()
  1898. } else {
  1899. file.InodeChangeNs = 0
  1900. }
  1901. return nil
  1902. }
  1903. // A []FileError is sent as part of an event and will be JSON serialized.
  1904. type FileError struct {
  1905. Path string `json:"path"`
  1906. Err string `json:"error"`
  1907. }
  1908. type fileErrorList []FileError
  1909. func (l fileErrorList) Len() int {
  1910. return len(l)
  1911. }
  1912. func (l fileErrorList) Less(a, b int) bool {
  1913. return l[a].Path < l[b].Path
  1914. }
  1915. func (l fileErrorList) Swap(a, b int) {
  1916. l[a], l[b] = l[b], l[a]
  1917. }
  1918. func conflictName(name, lastModBy string) string {
  1919. ext := filepath.Ext(name)
  1920. return name[:len(name)-len(ext)] + time.Now().Format(".sync-conflict-20060102-150405-") + lastModBy + ext
  1921. }
  1922. func isConflict(name string) bool {
  1923. return strings.Contains(filepath.Base(name), ".sync-conflict-")
  1924. }
  1925. func existingConflicts(name string, fs fs.Filesystem) []string {
  1926. ext := filepath.Ext(name)
  1927. matches, err := fs.Glob(name[:len(name)-len(ext)] + ".sync-conflict-????????-??????*" + ext)
  1928. if err != nil {
  1929. l.Debugln("globbing for conflicts", err)
  1930. }
  1931. return matches
  1932. }