folder_sendrecv.go 59 KB

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