casefs.go 12 KB

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