folder_sendrecv.go 64 KB

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