folder_sendrecv.go 62 KB

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