folder_sendrecv.go 62 KB

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