folder_sendrecv.go 62 KB

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