folder_sendrecv.go 60 KB

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