folder_sendrecv.go 63 KB

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