casefs.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // Copyright (C) 2020 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 fs
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "path/filepath"
  12. "sync"
  13. "time"
  14. lru "github.com/hashicorp/golang-lru/v2"
  15. "golang.org/x/text/unicode/norm"
  16. )
  17. const (
  18. // How long to consider cached dirnames valid
  19. caseCacheTimeout = time.Second
  20. caseCacheItemLimit = 4 << 10
  21. )
  22. type CaseConflictError struct {
  23. Given, Real string
  24. }
  25. func (e *CaseConflictError) Error() string {
  26. return fmt.Sprintf(`remote "%v" uses different upper or lowercase characters than local "%v"; change the casing on either side to match the other`, e.Given, e.Real)
  27. }
  28. func IsErrCaseConflict(err error) bool {
  29. e := &CaseConflictError{}
  30. return errors.As(err, &e)
  31. }
  32. type realCaser interface {
  33. realCase(name string) (string, error)
  34. dropCache()
  35. }
  36. type fskey struct {
  37. fstype FilesystemType
  38. uri, opts string
  39. }
  40. // caseFilesystemRegistry caches caseFilesystems and runs a routine to drop
  41. // their cache every now and then.
  42. type caseFilesystemRegistry struct {
  43. caseCaches map[fskey]*caseCache
  44. mut sync.RWMutex
  45. startCleaner sync.Once
  46. }
  47. func newFSKey(fs Filesystem) fskey {
  48. k := fskey{
  49. fstype: fs.Type(),
  50. uri: fs.URI(),
  51. }
  52. if opts := fs.Options(); len(opts) > 0 {
  53. k.opts = opts[0].String()
  54. for _, o := range opts[1:] {
  55. k.opts += "&" + o.String()
  56. }
  57. }
  58. return k
  59. }
  60. func (r *caseFilesystemRegistry) get(fs Filesystem) Filesystem {
  61. k := newFSKey(fs)
  62. // Use double locking when getting a caseFs. In the common case it will
  63. // already exist and we take the read lock fast path. If it doesn't, we
  64. // take a write lock and try again.
  65. r.mut.RLock()
  66. cache, ok := r.caseCaches[k]
  67. r.mut.RUnlock()
  68. if !ok {
  69. r.mut.Lock()
  70. cache, ok = r.caseCaches[k]
  71. if !ok {
  72. cache = newCaseCache()
  73. r.caseCaches[k] = cache
  74. r.startCleaner.Do(func() {
  75. go r.cleaner()
  76. })
  77. l.Debugf("Created new case cache for key %v", k)
  78. }
  79. r.mut.Unlock()
  80. }
  81. if ok {
  82. l.Debugf("Reusing case cache for key %v", k)
  83. }
  84. return &caseFilesystem{
  85. Filesystem: fs,
  86. realCaser: &defaultRealCaser{
  87. fs: fs,
  88. cache: cache,
  89. },
  90. }
  91. }
  92. func (r *caseFilesystemRegistry) cleaner() {
  93. for range time.NewTicker(time.Minute).C {
  94. // We need to not hold this lock for a long time, as it blocks
  95. // creating new filesystems in get(), which is needed to do things
  96. // like add new folders. The (*caseFs).dropCache() method can take
  97. // an arbitrarily long time to kick in because it in turn waits for
  98. // locks held by things performing I/O. So we can't call that from
  99. // within the loop.
  100. r.mut.RLock()
  101. toProcess := make([]*caseCache, 0, len(r.caseCaches))
  102. for _, cache := range r.caseCaches {
  103. toProcess = append(toProcess, cache)
  104. }
  105. r.mut.RUnlock()
  106. for _, cache := range toProcess {
  107. cache.Purge()
  108. }
  109. }
  110. }
  111. var globalCaseFilesystemRegistry = caseFilesystemRegistry{caseCaches: make(map[fskey]*caseCache)}
  112. // OptionDetectCaseConflicts ensures that the potentially case-insensitive filesystem
  113. // behaves like a case-sensitive filesystem. Meaning that it takes into account
  114. // the real casing of a path and returns ErrCaseConflict if the given path differs
  115. // from the real path. It is safe to use with any filesystem, i.e. also a
  116. // case-sensitive one. However it will add some overhead and thus shouldn't be
  117. // used if the filesystem is known to already behave case-sensitively.
  118. type OptionDetectCaseConflicts struct{}
  119. func (*OptionDetectCaseConflicts) apply(fs Filesystem) Filesystem {
  120. return globalCaseFilesystemRegistry.get(fs)
  121. }
  122. func (*OptionDetectCaseConflicts) String() string {
  123. return "detectCaseConflicts"
  124. }
  125. // caseFilesystem is a BasicFilesystem with additional checks to make a
  126. // potentially case insensitive underlying FS behave like it's case-sensitive.
  127. type caseFilesystem struct {
  128. Filesystem
  129. realCaser
  130. }
  131. func (f *caseFilesystem) Chmod(name string, mode FileMode) error {
  132. if err := f.checkCase(name); err != nil {
  133. return err
  134. }
  135. return f.Filesystem.Chmod(name, mode)
  136. }
  137. func (f *caseFilesystem) Lchown(name, uid, gid string) error {
  138. if err := f.checkCase(name); err != nil {
  139. return err
  140. }
  141. return f.Filesystem.Lchown(name, uid, gid)
  142. }
  143. func (f *caseFilesystem) Chtimes(name string, atime time.Time, mtime time.Time) error {
  144. if err := f.checkCase(name); err != nil {
  145. return err
  146. }
  147. return f.Filesystem.Chtimes(name, atime, mtime)
  148. }
  149. func (f *caseFilesystem) Mkdir(name string, perm FileMode) error {
  150. if err := f.checkCase(name); err != nil {
  151. return err
  152. }
  153. if err := f.Filesystem.Mkdir(name, perm); err != nil {
  154. return err
  155. }
  156. f.dropCache()
  157. return nil
  158. }
  159. func (f *caseFilesystem) MkdirAll(path string, perm FileMode) error {
  160. if err := f.checkCase(path); err != nil {
  161. return err
  162. }
  163. if err := f.Filesystem.MkdirAll(path, perm); err != nil {
  164. return err
  165. }
  166. f.dropCache()
  167. return nil
  168. }
  169. func (f *caseFilesystem) Lstat(name string) (FileInfo, error) {
  170. var err error
  171. if name, err = Canonicalize(name); err != nil {
  172. return nil, err
  173. }
  174. stat, err := f.Filesystem.Lstat(name)
  175. if err != nil {
  176. return nil, err
  177. }
  178. if err = f.checkCaseExisting(name); err != nil {
  179. return nil, err
  180. }
  181. return stat, nil
  182. }
  183. func (f *caseFilesystem) Remove(name string) error {
  184. if err := f.checkCase(name); err != nil {
  185. return err
  186. }
  187. if err := f.Filesystem.Remove(name); err != nil {
  188. return err
  189. }
  190. f.dropCache()
  191. return nil
  192. }
  193. func (f *caseFilesystem) RemoveAll(name string) error {
  194. if err := f.checkCase(name); err != nil {
  195. return err
  196. }
  197. if err := f.Filesystem.RemoveAll(name); err != nil {
  198. return err
  199. }
  200. f.dropCache()
  201. return nil
  202. }
  203. func (f *caseFilesystem) Rename(oldpath, newpath string) error {
  204. if err := f.checkCase(oldpath); err != nil {
  205. return err
  206. }
  207. if err := f.checkCase(newpath); err != nil {
  208. // Case-only rename is ok
  209. e := &CaseConflictError{}
  210. if !errors.As(err, &e) || e.Real != oldpath {
  211. return err
  212. }
  213. }
  214. if err := f.Filesystem.Rename(oldpath, newpath); err != nil {
  215. return err
  216. }
  217. f.dropCache()
  218. return nil
  219. }
  220. func (f *caseFilesystem) Stat(name string) (FileInfo, error) {
  221. var err error
  222. if name, err = Canonicalize(name); err != nil {
  223. return nil, err
  224. }
  225. stat, err := f.Filesystem.Stat(name)
  226. if err != nil {
  227. return nil, err
  228. }
  229. if err = f.checkCaseExisting(name); err != nil {
  230. return nil, err
  231. }
  232. return stat, nil
  233. }
  234. func (f *caseFilesystem) DirNames(name string) ([]string, error) {
  235. if err := f.checkCase(name); err != nil {
  236. return nil, err
  237. }
  238. return f.Filesystem.DirNames(name)
  239. }
  240. func (f *caseFilesystem) Open(name string) (File, error) {
  241. if err := f.checkCase(name); err != nil {
  242. return nil, err
  243. }
  244. return f.Filesystem.Open(name)
  245. }
  246. func (f *caseFilesystem) OpenFile(name string, flags int, mode FileMode) (File, error) {
  247. if err := f.checkCase(name); err != nil {
  248. return nil, err
  249. }
  250. file, err := f.Filesystem.OpenFile(name, flags, mode)
  251. if err != nil {
  252. return nil, err
  253. }
  254. f.dropCache()
  255. return file, nil
  256. }
  257. func (f *caseFilesystem) ReadSymlink(name string) (string, error) {
  258. if err := f.checkCase(name); err != nil {
  259. return "", err
  260. }
  261. return f.Filesystem.ReadSymlink(name)
  262. }
  263. func (f *caseFilesystem) Create(name string) (File, error) {
  264. if err := f.checkCase(name); err != nil {
  265. return nil, err
  266. }
  267. file, err := f.Filesystem.Create(name)
  268. if err != nil {
  269. return nil, err
  270. }
  271. f.dropCache()
  272. return file, nil
  273. }
  274. func (f *caseFilesystem) CreateSymlink(target, name string) error {
  275. if err := f.checkCase(name); err != nil {
  276. return err
  277. }
  278. if err := f.Filesystem.CreateSymlink(target, name); err != nil {
  279. return err
  280. }
  281. f.dropCache()
  282. return nil
  283. }
  284. func (f *caseFilesystem) Walk(root string, walkFn WalkFunc) error {
  285. // Walking the filesystem is likely (in Syncthing's case certainly) done
  286. // to pick up external changes, for which caching is undesirable.
  287. f.dropCache()
  288. if err := f.checkCase(root); err != nil {
  289. return err
  290. }
  291. return f.Filesystem.Walk(root, walkFn)
  292. }
  293. func (f *caseFilesystem) Watch(path string, ignore Matcher, ctx context.Context, ignorePerms bool) (<-chan Event, <-chan error, error) {
  294. if err := f.checkCase(path); err != nil {
  295. return nil, nil, err
  296. }
  297. return f.Filesystem.Watch(path, ignore, ctx, ignorePerms)
  298. }
  299. func (f *caseFilesystem) Hide(name string) error {
  300. if err := f.checkCase(name); err != nil {
  301. return err
  302. }
  303. return f.Filesystem.Hide(name)
  304. }
  305. func (f *caseFilesystem) Unhide(name string) error {
  306. if err := f.checkCase(name); err != nil {
  307. return err
  308. }
  309. return f.Filesystem.Unhide(name)
  310. }
  311. func (f *caseFilesystem) underlying() (Filesystem, bool) {
  312. return f.Filesystem, true
  313. }
  314. func (f *caseFilesystem) checkCase(name string) error {
  315. var err error
  316. if name, err = Canonicalize(name); err != nil {
  317. return err
  318. }
  319. // Stat is necessary for case sensitive FS, as it's then not a conflict
  320. // if name is e.g. "foo" and on dir there is "Foo".
  321. if _, err := f.Filesystem.Lstat(name); err != nil {
  322. if IsNotExist(err) {
  323. return nil
  324. }
  325. return err
  326. }
  327. return f.checkCaseExisting(name)
  328. }
  329. // checkCaseExisting must only be called after successfully canonicalizing and
  330. // stating the file.
  331. func (f *caseFilesystem) checkCaseExisting(name string) error {
  332. realName, err := f.realCase(name)
  333. if IsNotExist(err) {
  334. // It did exist just before -> cache is outdated, try again
  335. f.dropCache()
  336. realName, err = f.realCase(name)
  337. }
  338. if err != nil {
  339. return err
  340. }
  341. // We normalize the normalization (hah!) of the strings before
  342. // comparing, as we don't want to treat a normalization difference as a
  343. // case conflict.
  344. if norm.NFC.String(realName) != norm.NFC.String(name) {
  345. return &CaseConflictError{name, realName}
  346. }
  347. return nil
  348. }
  349. type defaultRealCaser struct {
  350. cache *caseCache
  351. fs Filesystem
  352. }
  353. type caseCache struct {
  354. *lru.TwoQueueCache[string, *caseNode]
  355. mut sync.Mutex
  356. }
  357. func newCaseCache() *caseCache {
  358. cache, err := lru.New2Q[string, *caseNode](caseCacheItemLimit)
  359. // New2Q only errors if given invalid parameters, which we don't.
  360. if err != nil {
  361. panic(err)
  362. }
  363. return &caseCache{
  364. TwoQueueCache: cache,
  365. }
  366. }
  367. func (r *defaultRealCaser) realCase(name string) (string, error) {
  368. realName := "."
  369. if name == realName {
  370. return realName, nil
  371. }
  372. for _, comp := range PathComponents(name) {
  373. node := r.cache.getExpireAdd(realName, r.fs)
  374. if node.err != nil {
  375. return "", node.err
  376. }
  377. // Try to find a direct or case match
  378. if _, ok := node.children[comp]; !ok {
  379. comp, ok = node.lowerToReal[UnicodeLowercaseNormalized(comp)]
  380. if !ok {
  381. return "", ErrNotExist
  382. }
  383. }
  384. realName = filepath.Join(realName, comp)
  385. }
  386. return realName, nil
  387. }
  388. func (r *defaultRealCaser) dropCache() {
  389. r.cache.Purge()
  390. }
  391. // getExpireAdd gets an entry for the given key. If no entry exists, or it is
  392. // expired a new one is created and added to the cache.
  393. func (c *caseCache) getExpireAdd(key string, fs Filesystem) *caseNode {
  394. c.mut.Lock()
  395. defer c.mut.Unlock()
  396. node, ok := c.Get(key)
  397. if !ok {
  398. node := newCaseNode(key, fs)
  399. c.Add(key, node)
  400. return node
  401. }
  402. if node.expires.Before(time.Now()) {
  403. node = newCaseNode(key, fs)
  404. c.Add(key, node)
  405. }
  406. return node
  407. }
  408. // The keys to children are "real", case resolved names of the path
  409. // component this node represents (i.e. containing no path separator).
  410. // lowerToReal is a map of lowercase path components (as in UnicodeLowercase)
  411. // to their corresponding "real", case resolved names.
  412. // A node is created empty and populated using once. If an error occurs the node
  413. // is removed from cache and the error stored in err, such that anyone that
  414. // already got the node doesn't try to access the nil maps.
  415. type caseNode struct {
  416. expires time.Time
  417. lowerToReal map[string]string
  418. children map[string]struct{}
  419. err error
  420. }
  421. func newCaseNode(name string, filesystem Filesystem) *caseNode {
  422. node := new(caseNode)
  423. dirNames, err := filesystem.DirNames(name)
  424. // Set expiry after calling DirNames in case this is super-slow
  425. // (e.g. dirs with many children on android)
  426. node.expires = time.Now().Add(caseCacheTimeout)
  427. if err != nil {
  428. node.err = err
  429. return node
  430. }
  431. num := len(dirNames)
  432. node.children = make(map[string]struct{}, num)
  433. node.lowerToReal = make(map[string]string, num)
  434. lastLower := ""
  435. for _, n := range dirNames {
  436. node.children[n] = struct{}{}
  437. lower := UnicodeLowercaseNormalized(n)
  438. if lower != lastLower {
  439. node.lowerToReal[lower] = n
  440. lastLower = n
  441. }
  442. }
  443. return node
  444. }