folder_sendrecv.go 62 KB

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