folder_sendrecv.go 58 KB

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