casefs.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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"
  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 ErrCaseConflict struct {
  23. Given, Real string
  24. }
  25. func (e *ErrCaseConflict) Error() string {
  26. return fmt.Sprintf(`given name "%v" differs from name in filesystem "%v"`, e.Given, e.Real)
  27. }
  28. func IsErrCaseConflict(err error) bool {
  29. e := &ErrCaseConflict{}
  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. fss map[fskey]*caseFilesystem
  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. caseFs, ok := r.fss[k]
  67. r.mut.RUnlock()
  68. if !ok {
  69. r.mut.Lock()
  70. caseFs, ok = r.fss[k]
  71. if !ok {
  72. caseFs = &caseFilesystem{
  73. Filesystem: fs,
  74. realCaser: newDefaultRealCaser(fs),
  75. }
  76. r.fss[k] = caseFs
  77. r.startCleaner.Do(func() {
  78. go r.cleaner()
  79. })
  80. }
  81. r.mut.Unlock()
  82. }
  83. return caseFs
  84. }
  85. func (r *caseFilesystemRegistry) cleaner() {
  86. for range time.NewTicker(time.Minute).C {
  87. // We need to not hold this lock for a long time, as it blocks
  88. // creating new filesystems in get(), which is needed to do things
  89. // like add new folders. The (*caseFs).dropCache() method can take
  90. // an arbitrarily long time to kick in because it in turn waits for
  91. // locks held by things performing I/O. So we can't call that from
  92. // within the loop.
  93. r.mut.RLock()
  94. toProcess := make([]*caseFilesystem, 0, len(r.fss))
  95. for _, caseFs := range r.fss {
  96. toProcess = append(toProcess, caseFs)
  97. }
  98. r.mut.RUnlock()
  99. for _, caseFs := range toProcess {
  100. caseFs.dropCache()
  101. }
  102. }
  103. }
  104. var globalCaseFilesystemRegistry = caseFilesystemRegistry{fss: make(map[fskey]*caseFilesystem)}
  105. // caseFilesystem is a BasicFilesystem with additional checks to make a
  106. // potentially case insensitive underlying FS behave like it's case-sensitive.
  107. type caseFilesystem struct {
  108. Filesystem
  109. realCaser
  110. }
  111. // NewCaseFilesystem ensures that the given, potentially case-insensitive filesystem
  112. // behaves like a case-sensitive filesystem. Meaning that it takes into account
  113. // the real casing of a path and returns ErrCaseConflict if the given path differs
  114. // from the real path. It is safe to use with any filesystem, i.e. also a
  115. // case-sensitive one. However it will add some overhead and thus shouldn't be
  116. // used if the filesystem is known to already behave case-sensitively.
  117. func NewCaseFilesystem(fs Filesystem) Filesystem {
  118. return wrapFilesystem(fs, globalCaseFilesystemRegistry.get)
  119. }
  120. func (f *caseFilesystem) Chmod(name string, mode FileMode) error {
  121. if err := f.checkCase(name); err != nil {
  122. return err
  123. }
  124. return f.Filesystem.Chmod(name, mode)
  125. }
  126. func (f *caseFilesystem) Lchown(name string, uid, gid int) error {
  127. if err := f.checkCase(name); err != nil {
  128. return err
  129. }
  130. return f.Filesystem.Lchown(name, uid, gid)
  131. }
  132. func (f *caseFilesystem) Chtimes(name string, atime time.Time, mtime time.Time) error {
  133. if err := f.checkCase(name); err != nil {
  134. return err
  135. }
  136. return f.Filesystem.Chtimes(name, atime, mtime)
  137. }
  138. func (f *caseFilesystem) Mkdir(name string, perm FileMode) error {
  139. if err := f.checkCase(name); err != nil {
  140. return err
  141. }
  142. if err := f.Filesystem.Mkdir(name, perm); err != nil {
  143. return err
  144. }
  145. f.dropCache()
  146. return nil
  147. }
  148. func (f *caseFilesystem) MkdirAll(path string, perm FileMode) error {
  149. if err := f.checkCase(path); err != nil {
  150. return err
  151. }
  152. if err := f.Filesystem.MkdirAll(path, perm); err != nil {
  153. return err
  154. }
  155. f.dropCache()
  156. return nil
  157. }
  158. func (f *caseFilesystem) Lstat(name string) (FileInfo, error) {
  159. var err error
  160. if name, err = Canonicalize(name); err != nil {
  161. return nil, err
  162. }
  163. stat, err := f.Filesystem.Lstat(name)
  164. if err != nil {
  165. return nil, err
  166. }
  167. if err = f.checkCaseExisting(name); err != nil {
  168. return nil, err
  169. }
  170. return stat, nil
  171. }
  172. func (f *caseFilesystem) Remove(name string) error {
  173. if err := f.checkCase(name); err != nil {
  174. return err
  175. }
  176. if err := f.Filesystem.Remove(name); err != nil {
  177. return err
  178. }
  179. f.dropCache()
  180. return nil
  181. }
  182. func (f *caseFilesystem) RemoveAll(name string) error {
  183. if err := f.checkCase(name); err != nil {
  184. return err
  185. }
  186. if err := f.Filesystem.RemoveAll(name); err != nil {
  187. return err
  188. }
  189. f.dropCache()
  190. return nil
  191. }
  192. func (f *caseFilesystem) Rename(oldpath, newpath string) error {
  193. if err := f.checkCase(oldpath); err != nil {
  194. return err
  195. }
  196. if err := f.checkCase(newpath); err != nil {
  197. // Case-only rename is ok
  198. e := &ErrCaseConflict{}
  199. if !errors.As(err, &e) || e.Real != oldpath {
  200. return err
  201. }
  202. }
  203. if err := f.Filesystem.Rename(oldpath, newpath); err != nil {
  204. return err
  205. }
  206. f.dropCache()
  207. return nil
  208. }
  209. func (f *caseFilesystem) Stat(name string) (FileInfo, error) {
  210. var err error
  211. if name, err = Canonicalize(name); err != nil {
  212. return nil, err
  213. }
  214. stat, err := f.Filesystem.Stat(name)
  215. if err != nil {
  216. return nil, err
  217. }
  218. if err = f.checkCaseExisting(name); err != nil {
  219. return nil, err
  220. }
  221. return stat, nil
  222. }
  223. func (f *caseFilesystem) DirNames(name string) ([]string, error) {
  224. if err := f.checkCase(name); err != nil {
  225. return nil, err
  226. }
  227. return f.Filesystem.DirNames(name)
  228. }
  229. func (f *caseFilesystem) Open(name string) (File, error) {
  230. if err := f.checkCase(name); err != nil {
  231. return nil, err
  232. }
  233. return f.Filesystem.Open(name)
  234. }
  235. func (f *caseFilesystem) OpenFile(name string, flags int, mode FileMode) (File, error) {
  236. if err := f.checkCase(name); err != nil {
  237. return nil, err
  238. }
  239. file, err := f.Filesystem.OpenFile(name, flags, mode)
  240. if err != nil {
  241. return nil, err
  242. }
  243. f.dropCache()
  244. return file, nil
  245. }
  246. func (f *caseFilesystem) ReadSymlink(name string) (string, error) {
  247. if err := f.checkCase(name); err != nil {
  248. return "", err
  249. }
  250. return f.Filesystem.ReadSymlink(name)
  251. }
  252. func (f *caseFilesystem) Create(name string) (File, error) {
  253. if err := f.checkCase(name); err != nil {
  254. return nil, err
  255. }
  256. file, err := f.Filesystem.Create(name)
  257. if err != nil {
  258. return nil, err
  259. }
  260. f.dropCache()
  261. return file, nil
  262. }
  263. func (f *caseFilesystem) CreateSymlink(target, name string) error {
  264. if err := f.checkCase(name); err != nil {
  265. return err
  266. }
  267. if err := f.Filesystem.CreateSymlink(target, name); err != nil {
  268. return err
  269. }
  270. f.dropCache()
  271. return nil
  272. }
  273. func (f *caseFilesystem) Walk(root string, walkFn WalkFunc) error {
  274. // Walking the filesystem is likely (in Syncthing's case certainly) done
  275. // to pick up external changes, for which caching is undesirable.
  276. f.dropCache()
  277. if err := f.checkCase(root); err != nil {
  278. return err
  279. }
  280. return f.Filesystem.Walk(root, walkFn)
  281. }
  282. func (f *caseFilesystem) Watch(path string, ignore Matcher, ctx context.Context, ignorePerms bool) (<-chan Event, <-chan error, error) {
  283. if err := f.checkCase(path); err != nil {
  284. return nil, nil, err
  285. }
  286. return f.Filesystem.Watch(path, ignore, ctx, ignorePerms)
  287. }
  288. func (f *caseFilesystem) Hide(name string) error {
  289. if err := f.checkCase(name); err != nil {
  290. return err
  291. }
  292. return f.Filesystem.Hide(name)
  293. }
  294. func (f *caseFilesystem) Unhide(name string) error {
  295. if err := f.checkCase(name); err != nil {
  296. return err
  297. }
  298. return f.Filesystem.Unhide(name)
  299. }
  300. func (f *caseFilesystem) underlying() (Filesystem, bool) {
  301. return f.Filesystem, true
  302. }
  303. func (f *caseFilesystem) wrapperType() filesystemWrapperType {
  304. return filesystemWrapperTypeCase
  305. }
  306. func (f *caseFilesystem) checkCase(name string) error {
  307. var err error
  308. if name, err = Canonicalize(name); err != nil {
  309. return err
  310. }
  311. // Stat is necessary for case sensitive FS, as it's then not a conflict
  312. // if name is e.g. "foo" and on dir there is "Foo".
  313. if _, err := f.Filesystem.Lstat(name); err != nil {
  314. if IsNotExist(err) {
  315. return nil
  316. }
  317. return err
  318. }
  319. return f.checkCaseExisting(name)
  320. }
  321. // checkCaseExisting must only be called after successfully canonicalizing and
  322. // stating the file.
  323. func (f *caseFilesystem) checkCaseExisting(name string) error {
  324. realName, err := f.realCase(name)
  325. if IsNotExist(err) {
  326. // It did exist just before -> cache is outdated, try again
  327. f.dropCache()
  328. realName, err = f.realCase(name)
  329. }
  330. if err != nil {
  331. return err
  332. }
  333. // We normalize the normalization (hah!) of the strings before
  334. // comparing, as we don't want to treat a normalization difference as a
  335. // case conflict.
  336. if norm.NFC.String(realName) != norm.NFC.String(name) {
  337. return &ErrCaseConflict{name, realName}
  338. }
  339. return nil
  340. }
  341. type defaultRealCaser struct {
  342. fs Filesystem
  343. cache caseCache
  344. }
  345. func newDefaultRealCaser(fs Filesystem) *defaultRealCaser {
  346. cache, err := lru.New2Q(caseCacheItemLimit)
  347. // New2Q only errors if given invalid parameters, which we don't.
  348. if err != nil {
  349. panic(err)
  350. }
  351. caser := &defaultRealCaser{
  352. fs: fs,
  353. cache: caseCache{
  354. TwoQueueCache: cache,
  355. },
  356. }
  357. return caser
  358. }
  359. func (r *defaultRealCaser) realCase(name string) (string, error) {
  360. realName := "."
  361. if name == realName {
  362. return realName, nil
  363. }
  364. for _, comp := range PathComponents(name) {
  365. node := r.cache.getExpireAdd(realName)
  366. node.once.Do(func() {
  367. dirNames, err := r.fs.DirNames(realName)
  368. if err != nil {
  369. r.cache.Remove(realName)
  370. node.err = err
  371. return
  372. }
  373. num := len(dirNames)
  374. node.children = make(map[string]struct{}, num)
  375. node.lowerToReal = make(map[string]string, num)
  376. lastLower := ""
  377. for _, n := range dirNames {
  378. node.children[n] = struct{}{}
  379. lower := UnicodeLowercaseNormalized(n)
  380. if lower != lastLower {
  381. node.lowerToReal[lower] = n
  382. lastLower = n
  383. }
  384. }
  385. })
  386. if node.err != nil {
  387. return "", node.err
  388. }
  389. // Try to find a direct or case match
  390. if _, ok := node.children[comp]; !ok {
  391. comp, ok = node.lowerToReal[UnicodeLowercaseNormalized(comp)]
  392. if !ok {
  393. return "", ErrNotExist
  394. }
  395. }
  396. realName = filepath.Join(realName, comp)
  397. }
  398. return realName, nil
  399. }
  400. func (r *defaultRealCaser) dropCache() {
  401. r.cache.Purge()
  402. }
  403. func newCaseNode() *caseNode {
  404. return &caseNode{
  405. expires: time.Now().Add(caseCacheTimeout),
  406. }
  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. once sync.Once
  420. err error
  421. }
  422. type caseCache struct {
  423. *lru.TwoQueueCache
  424. mut sync.Mutex
  425. }
  426. // getExpireAdd gets an entry for the given key. If no entry exists, or it is
  427. // expired a new one is created and added to the cache.
  428. func (c *caseCache) getExpireAdd(key string) *caseNode {
  429. c.mut.Lock()
  430. defer c.mut.Unlock()
  431. v, ok := c.Get(key)
  432. if !ok {
  433. node := newCaseNode()
  434. c.Add(key, node)
  435. return node
  436. }
  437. node := v.(*caseNode)
  438. if node.expires.Before(time.Now()) {
  439. node = newCaseNode()
  440. c.Add(key, node)
  441. }
  442. return node
  443. }