1
0

traversessymlink.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (C) 2016 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 osutil
  7. import (
  8. "fmt"
  9. "path/filepath"
  10. "github.com/syncthing/syncthing/lib/fs"
  11. )
  12. // TraversesSymlinkError is an error indicating symlink traversal
  13. type TraversesSymlinkError struct {
  14. path string
  15. }
  16. func (e *TraversesSymlinkError) Error() string {
  17. return fmt.Sprintf("traverses symlink: %s", e.path)
  18. }
  19. // NotADirectoryError is an error indicating an expected path is not a directory
  20. type NotADirectoryError struct {
  21. path string
  22. }
  23. func (e *NotADirectoryError) Error() string {
  24. return fmt.Sprintf("not a directory: %s", e.path)
  25. }
  26. // TraversesSymlink returns an error if any path component of name (including name
  27. // itself) traverses a symlink.
  28. func TraversesSymlink(filesystem fs.Filesystem, name string) error {
  29. var err error
  30. name, err = fs.Canonicalize(name)
  31. if err != nil {
  32. return err
  33. }
  34. if name == "." {
  35. // The result of calling TraversesSymlink(filesystem, filepath.Dir("foo"))
  36. return nil
  37. }
  38. var path string
  39. for _, part := range fs.PathComponents(name) {
  40. path = filepath.Join(path, part)
  41. info, err := filesystem.Lstat(path)
  42. if err != nil {
  43. if fs.IsNotExist(err) {
  44. return nil
  45. }
  46. return err
  47. }
  48. if info.IsSymlink() {
  49. return &TraversesSymlinkError{
  50. path: path,
  51. }
  52. }
  53. if !info.IsDir() {
  54. return &NotADirectoryError{
  55. path: path,
  56. }
  57. }
  58. }
  59. return nil
  60. }