names.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package smbserver
  2. import (
  3. "errors"
  4. "hash/fnv"
  5. "os"
  6. "path"
  7. "strings"
  8. "sync"
  9. "time"
  10. "unicode"
  11. "imuslab.com/arozos/mod/storage/smbserver/wire"
  12. )
  13. /*
  14. names.go
  15. Everything between a Windows path and a share path: splitting off stream
  16. names, refusing traversal, case insensitive lookup, and the private use
  17. characters that let Windows see Linux names it would otherwise forbid.
  18. */
  19. const (
  20. maxPathLength = 32767
  21. maxNameComponent = 255
  22. //Folders ArozOS keeps its own data in
  23. protectedFolder = ".metadata"
  24. )
  25. // The private use characters SMB clients agree on for names Windows forbids.
  26. var forbiddenToPrivate = map[rune]rune{
  27. '"': 0xF020,
  28. '*': 0xF021,
  29. ':': 0xF022,
  30. '<': 0xF023,
  31. '>': 0xF024,
  32. '?': 0xF025,
  33. '\\': 0xF026,
  34. '|': 0xF027,
  35. }
  36. const (
  37. privateSpace = 0xF028
  38. privatePeriod = 0xF029
  39. )
  40. var privateToForbidden = func() map[rune]rune {
  41. m := map[rune]rune{privateSpace: ' ', privatePeriod: '.'}
  42. for k, v := range forbiddenToPrivate {
  43. m[v] = k
  44. }
  45. return m
  46. }()
  47. // toWireName turns a name on disk into one Windows accepts.
  48. func toWireName(name string) string {
  49. runes := []rune(name)
  50. for i, r := range runes {
  51. if p, ok := forbiddenToPrivate[r]; ok {
  52. runes[i] = p
  53. }
  54. }
  55. //Windows drops a trailing space or dot, which would make the file
  56. //unreachable, so they are kept through the private range too
  57. if n := len(runes); n > 0 {
  58. switch runes[n-1] {
  59. case ' ':
  60. runes[n-1] = privateSpace
  61. case '.':
  62. if name != "." && name != ".." {
  63. runes[n-1] = privatePeriod
  64. }
  65. }
  66. }
  67. return string(runes)
  68. }
  69. // fromWireName is the inverse of toWireName.
  70. func fromWireName(name string) string {
  71. if !strings.ContainsFunc(name, func(r rune) bool { return r >= 0xF020 && r <= 0xF029 }) {
  72. return name
  73. }
  74. runes := []rune(name)
  75. for i, r := range runes {
  76. if p, ok := privateToForbidden[r]; ok {
  77. runes[i] = p
  78. }
  79. }
  80. return string(runes)
  81. }
  82. // parsePath validates a path from the client and returns it share relative.
  83. // Stream syntax is resolved here, so nothing past this point sees a colon that
  84. // Windows meant as a separator. A named stream is refused here; CREATE uses
  85. // parsePathStream, which allows them.
  86. func parsePath(name string) (string, uint32) {
  87. rel, stream, status := parsePathStream(name)
  88. if status == wire.StatusOK && stream != "" {
  89. return "", wire.StatusObjectNameInvalid
  90. }
  91. return rel, status
  92. }
  93. // parsePathStream also returns the named stream of the last component, "" for
  94. // the file itself (":" and "::$DATA" name the file too).
  95. func parsePathStream(name string) (string, string, uint32) {
  96. if len(name) > maxPathLength {
  97. return "", "", wire.StatusObjectNameInvalid
  98. }
  99. if strings.IndexByte(name, 0) >= 0 {
  100. return "", "", wire.StatusObjectNameInvalid
  101. }
  102. name = strings.TrimPrefix(name, `\`)
  103. if name == "" {
  104. return "", "", wire.StatusOK
  105. }
  106. stream := ""
  107. parts := strings.Split(name, `\`)
  108. out := make([]string, 0, len(parts))
  109. for i, part := range parts {
  110. if part == "" {
  111. //A trailing separator names the same folder, others are malformed
  112. if i == len(parts)-1 {
  113. continue
  114. }
  115. return "", "", wire.StatusObjectNameInvalid
  116. }
  117. //name:stream:type, where the type can only be the data type
  118. if colon := strings.IndexByte(part, ':'); colon >= 0 {
  119. if i != len(parts)-1 {
  120. return "", "", wire.StatusObjectNameInvalid
  121. }
  122. spec := part[colon+1:]
  123. part = part[:colon]
  124. streamName, kind := spec, ""
  125. if j := strings.IndexByte(spec, ':'); j >= 0 {
  126. streamName, kind = spec[:j], strings.ToUpper(spec[j+1:])
  127. }
  128. if kind != "" && kind != "$DATA" {
  129. return "", "", wire.StatusObjectNameInvalid
  130. }
  131. if streamName != "" {
  132. if strings.ContainsAny(streamName, `/\`) || len([]rune(streamName)) > maxNameComponent {
  133. return "", "", wire.StatusObjectNameInvalid
  134. }
  135. for _, r := range streamName {
  136. if unicode.IsControl(r) {
  137. return "", "", wire.StatusObjectNameInvalid
  138. }
  139. }
  140. //macOS sends the colons of extended attribute names in
  141. //the private range, so they arrive as colons here
  142. stream = fromWireName(streamName)
  143. }
  144. if part == "" {
  145. continue
  146. }
  147. }
  148. if part == "." || part == ".." {
  149. return "", "", wire.StatusObjectPathSyntaxBad
  150. }
  151. if strings.ContainsAny(part, `<>"|?*/`) {
  152. return "", "", wire.StatusObjectNameInvalid
  153. }
  154. for _, r := range part {
  155. if unicode.IsControl(r) {
  156. return "", "", wire.StatusObjectNameInvalid
  157. }
  158. }
  159. if len([]rune(part)) > maxNameComponent {
  160. return "", "", wire.StatusObjectNameInvalid
  161. }
  162. out = append(out, fromWireName(part))
  163. }
  164. return strings.Join(out, "/"), stream, wire.StatusOK
  165. }
  166. func joinPath(dir, name string) string {
  167. if dir == "" {
  168. return name
  169. }
  170. return dir + "/" + name
  171. }
  172. // isInternal reports the folder ArozOS keeps its own data in. It is left out
  173. // of listings: clients that saw it would try to delete it with the folder it
  174. // is in, and be refused. Paths into it still work, for versions and streams.
  175. func isInternal(name string) bool { return name == protectedFolder }
  176. // isProtected reports a path inside a folder ArozOS keeps for itself.
  177. func isProtected(p string) bool {
  178. for _, part := range strings.Split(p, "/") {
  179. if part == protectedFolder {
  180. return true
  181. }
  182. }
  183. return false
  184. }
  185. // resolved is the outcome of a path lookup.
  186. type resolved struct {
  187. path string
  188. info FileInfo
  189. exists bool
  190. parentExists bool
  191. }
  192. // nameCache remembers folder listings for a moment, so that the lookups Windows
  193. // repeats for files that do not exist, such as desktop.ini, do not read a large
  194. // folder every time. A hit only gives the spelling: the file is then checked on
  195. // disk, so a stale entry can never return wrong data, and writes through this
  196. // server invalidate the folder at once.
  197. type nameCache struct {
  198. mu sync.Mutex
  199. folders map[string]*cachedFolder
  200. }
  201. type cachedFolder struct {
  202. loaded time.Time
  203. names map[string]string //Folded name to real name
  204. }
  205. const (
  206. nameCacheTTL = 2 * time.Second
  207. nameCacheFolders = 1024
  208. )
  209. func newNameCache() *nameCache {
  210. return &nameCache{folders: map[string]*cachedFolder{}}
  211. }
  212. // find returns the real spelling of name in dir.
  213. func (n *nameCache) find(s Share, dir, name string) (string, bool, error) {
  214. key := fileKey(s, dir)
  215. folded := strings.ToLower(name)
  216. n.mu.Lock()
  217. folder := n.folders[key]
  218. if folder != nil && time.Since(folder.loaded) < nameCacheTTL {
  219. real, ok := folder.names[folded]
  220. n.mu.Unlock()
  221. return real, ok, nil
  222. }
  223. n.mu.Unlock()
  224. entries, err := s.ReadDir(dir)
  225. if err != nil {
  226. return "", false, err
  227. }
  228. folder = &cachedFolder{loaded: time.Now(), names: make(map[string]string, len(entries))}
  229. for _, e := range entries {
  230. folder.names[strings.ToLower(e.Name)] = e.Name
  231. }
  232. n.mu.Lock()
  233. if len(n.folders) >= nameCacheFolders {
  234. n.folders = map[string]*cachedFolder{}
  235. }
  236. n.folders[key] = folder
  237. n.mu.Unlock()
  238. real, ok := folder.names[folded]
  239. return real, ok, nil
  240. }
  241. // forget drops a folder after something in it changed.
  242. func (n *nameCache) forget(s Share, dir string) {
  243. n.mu.Lock()
  244. defer n.mu.Unlock()
  245. delete(n.folders, fileKey(s, dir))
  246. }
  247. // resolve looks a path up the way NTFS does, ignoring case. The exact name is
  248. // tried first, so only a miss goes to the name cache.
  249. func resolve(s Share, names *nameCache, rel string) (resolved, error) {
  250. info, err := s.Stat(rel)
  251. if err == nil {
  252. return resolved{path: rel, info: info, exists: true, parentExists: true}, nil
  253. }
  254. if !isMissing(err) {
  255. return resolved{}, err
  256. }
  257. if rel == "" {
  258. return resolved{}, err
  259. }
  260. parts := strings.Split(rel, "/")
  261. current := ""
  262. for i, part := range parts {
  263. last := i == len(parts)-1
  264. next := joinPath(current, part)
  265. info, err := s.Stat(next)
  266. if err != nil {
  267. if !isMissing(err) {
  268. return resolved{}, err
  269. }
  270. real, found, err := names.find(s, current, part)
  271. if err != nil {
  272. if isMissing(err) {
  273. return resolved{path: rel}, nil
  274. }
  275. return resolved{}, err
  276. }
  277. if found {
  278. next = joinPath(current, real)
  279. info, err = s.Stat(next)
  280. if err != nil && !isMissing(err) {
  281. return resolved{}, err
  282. }
  283. found = err == nil
  284. }
  285. if !found {
  286. if last {
  287. return resolved{path: joinPath(current, part), parentExists: true}, nil
  288. }
  289. return resolved{path: rel}, nil
  290. }
  291. }
  292. if !last && !info.IsDir {
  293. return resolved{path: rel}, nil
  294. }
  295. current = next
  296. if last {
  297. return resolved{path: current, info: info, exists: true, parentExists: true}, nil
  298. }
  299. }
  300. return resolved{path: rel}, nil
  301. }
  302. // fileKey identifies a file in the shared table. It folds case, so one file
  303. // reached by two spellings on a case insensitive drive stays one entry. On a
  304. // case sensitive drive two names differing only in case then share a row,
  305. // which can only make share modes stricter than needed.
  306. func fileKey(s Share, p string) string {
  307. return s.Key() + "\x00" + strings.ToLower(p)
  308. }
  309. // fileNumber returns a stable 64 bit id for a file.
  310. func fileNumber(s Share, p string, info FileInfo) uint64 {
  311. if info.ID != 0 {
  312. return info.ID
  313. }
  314. h := fnv.New64a()
  315. h.Write([]byte(s.Key()))
  316. h.Write([]byte{0})
  317. h.Write([]byte(strings.ToLower(p)))
  318. return h.Sum64()
  319. }
  320. func baseName(p string) string {
  321. if p == "" {
  322. return ""
  323. }
  324. return path.Base(p)
  325. }
  326. func dirName(p string) string {
  327. i := strings.LastIndexByte(p, '/')
  328. if i < 0 {
  329. return ""
  330. }
  331. return p[:i]
  332. }
  333. // isMissing reports a not found error of any flavour.
  334. func isMissing(err error) bool {
  335. return errors.Is(err, os.ErrNotExist) || isNotDirectory(err)
  336. }
  337. // statusOf maps a backend error to a status.
  338. func statusOf(err error) uint32 {
  339. switch {
  340. case err == nil:
  341. return wire.StatusOK
  342. case errors.Is(err, ErrFileTooLarge):
  343. return wire.StatusFileTooLarge
  344. case errors.Is(err, os.ErrNotExist):
  345. return wire.StatusObjectNameNotFound
  346. case isNotDirectory(err):
  347. return wire.StatusObjectPathNotFound
  348. case errors.Is(err, os.ErrPermission):
  349. return wire.StatusAccessDenied
  350. case errors.Is(err, os.ErrExist):
  351. return wire.StatusObjectNameCollision
  352. case isDiskFull(err):
  353. return wire.StatusDiskFull
  354. case isNotEmpty(err):
  355. return wire.StatusDirectoryNotEmpty
  356. }
  357. return wire.StatusUnsuccessful
  358. }
  359. // matchPattern is the wildcard matching of FsRtlIsNameInExpression. Beyond
  360. // * and ?, Windows rewrites patterns into the DOS forms: < is DOS_STAR, > is
  361. // DOS_QM and " is DOS_DOT.
  362. func matchPattern(pattern, name string) bool {
  363. if pattern == "" || pattern == "*" || pattern == "*.*" {
  364. return true
  365. }
  366. return matchRunes([]rune(strings.ToUpper(pattern)), []rune(strings.ToUpper(name)))
  367. }
  368. func matchRunes(p, n []rune) bool {
  369. for len(p) > 0 {
  370. switch p[0] {
  371. case '*':
  372. for i := 0; i <= len(n); i++ {
  373. if matchRunes(p[1:], n[i:]) {
  374. return true
  375. }
  376. }
  377. return false
  378. case '<':
  379. //Matches up to and including the last dot, or everything
  380. for i := 0; i <= len(n); i++ {
  381. if matchRunes(p[1:], n[i:]) {
  382. return true
  383. }
  384. if i < len(n) && n[i] == '.' && !containsDot(n[i+1:]) {
  385. return matchRunes(p[1:], n[i+1:]) || matchRunes(p[1:], n[i:])
  386. }
  387. }
  388. return false
  389. case '?':
  390. if len(n) == 0 {
  391. return false
  392. }
  393. n = n[1:]
  394. case '>':
  395. //One character, or nothing at a dot or the end
  396. if len(n) > 0 && n[0] != '.' {
  397. n = n[1:]
  398. }
  399. case '"':
  400. if len(n) > 0 {
  401. if n[0] != '.' {
  402. return false
  403. }
  404. n = n[1:]
  405. }
  406. default:
  407. if len(n) == 0 || n[0] != p[0] {
  408. return false
  409. }
  410. n = n[1:]
  411. }
  412. p = p[1:]
  413. }
  414. return len(n) == 0
  415. }
  416. func containsDot(n []rune) bool {
  417. for _, r := range n {
  418. if r == '.' {
  419. return true
  420. }
  421. }
  422. return false
  423. }
  424. func hasWildcard(pattern string) bool {
  425. return strings.ContainsAny(pattern, `*?<>"`)
  426. }