util.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 fs
  7. import (
  8. "fmt"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "unicode"
  14. )
  15. const pathSeparatorString = string(PathSeparator)
  16. func ExpandTilde(path string) (string, error) {
  17. if path == "~" {
  18. return getHomeDir()
  19. }
  20. path = filepath.FromSlash(path)
  21. if !strings.HasPrefix(path, fmt.Sprintf("~%c", PathSeparator)) {
  22. return path, nil
  23. }
  24. home, err := getHomeDir()
  25. if err != nil {
  26. return "", err
  27. }
  28. return filepath.Join(home, path[2:]), nil
  29. }
  30. func getHomeDir() (string, error) {
  31. if runtime.GOOS == "windows" {
  32. // Legacy -- we prioritize this for historical reasons, whereas
  33. // os.UserHomeDir uses %USERPROFILE% always.
  34. home := filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  35. if home != "" {
  36. return home, nil
  37. }
  38. }
  39. return os.UserHomeDir()
  40. }
  41. var (
  42. windowsDisallowedCharacters = string([]rune{
  43. '<', '>', ':', '"', '|', '?', '*',
  44. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  45. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  46. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  47. 31,
  48. })
  49. windowsDisallowedNames = []string{"CON", "PRN", "AUX", "NUL",
  50. "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
  51. "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
  52. }
  53. )
  54. func WindowsInvalidFilename(name string) error {
  55. // None of the path components should end in space or period, or be a
  56. // reserved name. COM0 and LPT0 are missing from the Microsoft docs,
  57. // but Windows Explorer treats them as invalid too.
  58. // (https://docs.microsoft.com/windows/win32/fileio/naming-a-file)
  59. for _, part := range strings.Split(name, `\`) {
  60. if len(part) == 0 {
  61. continue
  62. }
  63. switch part[len(part)-1] {
  64. case ' ', '.':
  65. // Names ending in space or period are not valid.
  66. return errInvalidFilenameWindowsSpacePeriod
  67. }
  68. if windowsIsReserved(part) {
  69. return errInvalidFilenameWindowsReservedName
  70. }
  71. }
  72. // The path must not contain any disallowed characters
  73. if strings.ContainsAny(name, windowsDisallowedCharacters) {
  74. return errInvalidFilenameWindowsReservedChar
  75. }
  76. return nil
  77. }
  78. // SanitizePath takes a string that might contain all kinds of special
  79. // characters and makes a valid, similar, path name out of it.
  80. //
  81. // Spans of invalid characters, whitespace and/or non-UTF-8 sequences are
  82. // replaced by a single space. The result is always UTF-8 and contains only
  83. // printable characters, as determined by unicode.IsPrint.
  84. //
  85. // Invalid characters are non-printing runes, things not allowed in file names
  86. // in Windows, and common shell metacharacters. Even if asterisks and pipes
  87. // and stuff are allowed on Unixes in general they might not be allowed by
  88. // the filesystem and may surprise the user and cause shell oddness. This
  89. // function is intended for file names we generate on behalf of the user,
  90. // and surprising them with odd shell characters in file names is unkind.
  91. //
  92. // We include whitespace in the invalid characters so that multiple
  93. // whitespace is collapsed to a single space. Additionally, whitespace at
  94. // either end is removed.
  95. //
  96. // If the result is a name disallowed on windows, a hyphen is prepended.
  97. func SanitizePath(path string) string {
  98. var b strings.Builder
  99. disallowed := `<>:"'/\|?*[]{};:!@$%&^#` + windowsDisallowedCharacters
  100. prev := ' '
  101. for _, c := range path {
  102. if !unicode.IsPrint(c) || c == unicode.ReplacementChar ||
  103. strings.ContainsRune(disallowed, c) {
  104. c = ' '
  105. }
  106. if !(c == ' ' && prev == ' ') {
  107. b.WriteRune(c)
  108. }
  109. prev = c
  110. }
  111. path = strings.TrimSpace(b.String())
  112. if windowsIsReserved(path) {
  113. path = "-" + path
  114. }
  115. return path
  116. }
  117. func windowsIsReserved(part string) bool {
  118. upperCased := strings.ToUpper(part)
  119. for _, disallowed := range windowsDisallowedNames {
  120. if upperCased == disallowed {
  121. return true
  122. }
  123. if strings.HasPrefix(upperCased, disallowed+".") {
  124. // nul.txt.jpg is also disallowed
  125. return true
  126. }
  127. }
  128. return false
  129. }
  130. // IsParent compares paths purely lexicographically, meaning it returns false
  131. // if path and parent aren't both absolute or relative.
  132. func IsParent(path, parent string) bool {
  133. if parent == path {
  134. // Twice the same root on windows would not be caught at the end.
  135. return false
  136. }
  137. if filepath.IsAbs(path) != filepath.IsAbs(parent) {
  138. return false
  139. }
  140. if parent == "" || parent == "." {
  141. // The empty string is the parent of everything except the empty
  142. // string and ".". (Avoids panic in the last step.)
  143. return path != "" && path != "."
  144. }
  145. if parent == "/" {
  146. // The root is the parent of everything except itself, which would
  147. // not be caught below.
  148. return path != "/"
  149. }
  150. if parent[len(parent)-1] != PathSeparator {
  151. parent += pathSeparatorString
  152. }
  153. return strings.HasPrefix(path, parent)
  154. }
  155. func CommonPrefix(first, second string) string {
  156. if filepath.IsAbs(first) != filepath.IsAbs(second) {
  157. // Whatever
  158. return ""
  159. }
  160. firstParts := PathComponents(filepath.Clean(first))
  161. secondParts := PathComponents(filepath.Clean(second))
  162. isAbs := filepath.IsAbs(first) && filepath.IsAbs(second)
  163. count := len(firstParts)
  164. if len(secondParts) < len(firstParts) {
  165. count = len(secondParts)
  166. }
  167. common := make([]string, 0, count)
  168. for i := 0; i < count; i++ {
  169. if firstParts[i] != secondParts[i] {
  170. break
  171. }
  172. common = append(common, firstParts[i])
  173. }
  174. if isAbs {
  175. if runtime.GOOS == "windows" && isVolumeNameOnly(common) {
  176. // Because strings.Split strips out path separators, if we're at the volume name, we end up without a separator
  177. // Wedge an empty element to be joined with.
  178. common = append(common, "")
  179. } else if len(common) == 1 {
  180. // If isAbs on non Windows, first element in both first and second is "", hence joining that returns nothing.
  181. return pathSeparatorString
  182. }
  183. }
  184. // This should only be true on Windows when drive letters are different or when paths are relative.
  185. // In case of UNC paths we should end up with more than a single element hence joining is fine
  186. if len(common) == 0 {
  187. return ""
  188. }
  189. // This has to be strings.Join, because filepath.Join([]string{"", "", "?", "C:", "Audrius"}...) returns garbage
  190. result := strings.Join(common, pathSeparatorString)
  191. return filepath.Clean(result)
  192. }
  193. // PathComponents returns a list of names of parent directories and the leaf
  194. // item for the given native (fs.PathSeparator delimited) and clean path.
  195. func PathComponents(path string) []string {
  196. return strings.Split(path, pathSeparatorString)
  197. }
  198. func isVolumeNameOnly(parts []string) bool {
  199. isNormalVolumeName := len(parts) == 1 && strings.HasSuffix(parts[0], ":")
  200. isUNCVolumeName := len(parts) == 4 && strings.HasSuffix(parts[3], ":")
  201. return isNormalVolumeName || isUNCVolumeName
  202. }