folder_sendrecv.go 58 KB

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