casefs.go 11 KB

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