casefs.go 12 KB

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