file.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package webdav
  5. import (
  6. "context"
  7. "encoding/xml"
  8. "io"
  9. "net/http"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "runtime"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. // slashClean is equivalent to but slightly more efficient than
  19. // path.Clean("/" + name).
  20. func slashClean(name string) string {
  21. if name == "" || name[0] != '/' {
  22. name = "/" + name
  23. }
  24. return path.Clean(name)
  25. }
  26. // A FileSystem implements access to a collection of named files. The elements
  27. // in a file path are separated by slash ('/', U+002F) characters, regardless
  28. // of host operating system convention.
  29. //
  30. // Each method has the same semantics as the os package's function of the same
  31. // name.
  32. //
  33. // Note that the os.Rename documentation says that "OS-specific restrictions
  34. // might apply". In particular, whether or not renaming a file or directory
  35. // overwriting another existing file or directory is an error is OS-dependent.
  36. type FileSystem interface {
  37. Mkdir(ctx context.Context, name string, perm os.FileMode) error
  38. OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error)
  39. RemoveAll(ctx context.Context, name string) error
  40. Rename(ctx context.Context, oldName, newName string) error
  41. Stat(ctx context.Context, name string) (os.FileInfo, error)
  42. }
  43. // A File is returned by a FileSystem's OpenFile method and can be served by a
  44. // Handler.
  45. //
  46. // A File may optionally implement the DeadPropsHolder interface, if it can
  47. // load and save dead properties.
  48. type File interface {
  49. http.File
  50. io.Writer
  51. }
  52. // A Dir implements FileSystem using the native file system restricted to a
  53. // specific directory tree.
  54. //
  55. // While the FileSystem.OpenFile method takes '/'-separated paths, a Dir's
  56. // string value is a filename on the native file system, not a URL, so it is
  57. // separated by filepath.Separator, which isn't necessarily '/'.
  58. //
  59. // An empty Dir is treated as ".".
  60. type Dir string
  61. func (d Dir) resolve(name string) string {
  62. // This implementation is based on Dir.Open's code in the standard net/http package.
  63. if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
  64. strings.Contains(name, "\x00") {
  65. return ""
  66. }
  67. dir := string(d)
  68. if dir == "" {
  69. dir = "."
  70. }
  71. return filepath.Join(dir, filepath.FromSlash(slashClean(name)))
  72. }
  73. func (d Dir) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
  74. if name = d.resolve(name); name == "" {
  75. return os.ErrNotExist
  76. }
  77. return os.Mkdir(name, perm)
  78. }
  79. func (d Dir) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) {
  80. if name = d.resolve(name); name == "" {
  81. return nil, os.ErrNotExist
  82. }
  83. f, err := os.OpenFile(name, flag, perm)
  84. if err != nil {
  85. return nil, err
  86. }
  87. return f, nil
  88. }
  89. func (d Dir) RemoveAll(ctx context.Context, name string) error {
  90. if name = d.resolve(name); name == "" {
  91. return os.ErrNotExist
  92. }
  93. if name == filepath.Clean(string(d)) {
  94. // Prohibit removing the virtual root directory.
  95. return os.ErrInvalid
  96. }
  97. return os.RemoveAll(name)
  98. }
  99. func (d Dir) Rename(ctx context.Context, oldName, newName string) error {
  100. if oldName = d.resolve(oldName); oldName == "" {
  101. return os.ErrNotExist
  102. }
  103. if newName = d.resolve(newName); newName == "" {
  104. return os.ErrNotExist
  105. }
  106. if root := filepath.Clean(string(d)); root == oldName || root == newName {
  107. // Prohibit renaming from or to the virtual root directory.
  108. return os.ErrInvalid
  109. }
  110. return os.Rename(oldName, newName)
  111. }
  112. func (d Dir) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  113. if name = d.resolve(name); name == "" {
  114. return nil, os.ErrNotExist
  115. }
  116. return os.Stat(name)
  117. }
  118. // NewMemFS returns a new in-memory FileSystem implementation.
  119. func NewMemFS() FileSystem {
  120. return &memFS{
  121. root: memFSNode{
  122. children: make(map[string]*memFSNode),
  123. mode: 0660 | os.ModeDir,
  124. modTime: time.Now(),
  125. },
  126. }
  127. }
  128. // A memFS implements FileSystem, storing all metadata and actual file data
  129. // in-memory. No limits on filesystem size are used, so it is not recommended
  130. // this be used where the clients are untrusted.
  131. //
  132. // Concurrent access is permitted. The tree structure is protected by a mutex,
  133. // and each node's contents and metadata are protected by a per-node mutex.
  134. //
  135. // TODO: Enforce file permissions.
  136. type memFS struct {
  137. mu sync.Mutex
  138. root memFSNode
  139. }
  140. // TODO: clean up and rationalize the walk/find code.
  141. // walk walks the directory tree for the fullname, calling f at each step. If f
  142. // returns an error, the walk will be aborted and return that same error.
  143. //
  144. // dir is the directory at that step, frag is the name fragment, and final is
  145. // whether it is the final step. For example, walking "/foo/bar/x" will result
  146. // in 3 calls to f:
  147. // - "/", "foo", false
  148. // - "/foo/", "bar", false
  149. // - "/foo/bar/", "x", true
  150. // The frag argument will be empty only if dir is the root node and the walk
  151. // ends at that root node.
  152. func (fs *memFS) walk(op, fullname string, f func(dir *memFSNode, frag string, final bool) error) error {
  153. original := fullname
  154. fullname = slashClean(fullname)
  155. // Strip any leading "/"s to make fullname a relative path, as the walk
  156. // starts at fs.root.
  157. if fullname[0] == '/' {
  158. fullname = fullname[1:]
  159. }
  160. dir := &fs.root
  161. for {
  162. frag, remaining := fullname, ""
  163. i := strings.IndexRune(fullname, '/')
  164. final := i < 0
  165. if !final {
  166. frag, remaining = fullname[:i], fullname[i+1:]
  167. }
  168. if frag == "" && dir != &fs.root {
  169. panic("webdav: empty path fragment for a clean path")
  170. }
  171. if err := f(dir, frag, final); err != nil {
  172. return &os.PathError{
  173. Op: op,
  174. Path: original,
  175. Err: err,
  176. }
  177. }
  178. if final {
  179. break
  180. }
  181. child := dir.children[frag]
  182. if child == nil {
  183. return &os.PathError{
  184. Op: op,
  185. Path: original,
  186. Err: os.ErrNotExist,
  187. }
  188. }
  189. if !child.mode.IsDir() {
  190. return &os.PathError{
  191. Op: op,
  192. Path: original,
  193. Err: os.ErrInvalid,
  194. }
  195. }
  196. dir, fullname = child, remaining
  197. }
  198. return nil
  199. }
  200. // find returns the parent of the named node and the relative name fragment
  201. // from the parent to the child. For example, if finding "/foo/bar/baz" then
  202. // parent will be the node for "/foo/bar" and frag will be "baz".
  203. //
  204. // If the fullname names the root node, then parent, frag and err will be zero.
  205. //
  206. // find returns an error if the parent does not already exist or the parent
  207. // isn't a directory, but it will not return an error per se if the child does
  208. // not already exist. The error returned is either nil or an *os.PathError
  209. // whose Op is op.
  210. func (fs *memFS) find(op, fullname string) (parent *memFSNode, frag string, err error) {
  211. err = fs.walk(op, fullname, func(parent0 *memFSNode, frag0 string, final bool) error {
  212. if !final {
  213. return nil
  214. }
  215. if frag0 != "" {
  216. parent, frag = parent0, frag0
  217. }
  218. return nil
  219. })
  220. return parent, frag, err
  221. }
  222. func (fs *memFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
  223. fs.mu.Lock()
  224. defer fs.mu.Unlock()
  225. dir, frag, err := fs.find("mkdir", name)
  226. if err != nil {
  227. return err
  228. }
  229. if dir == nil {
  230. // We can't create the root.
  231. return os.ErrInvalid
  232. }
  233. if _, ok := dir.children[frag]; ok {
  234. return os.ErrExist
  235. }
  236. dir.children[frag] = &memFSNode{
  237. children: make(map[string]*memFSNode),
  238. mode: perm.Perm() | os.ModeDir,
  239. modTime: time.Now(),
  240. }
  241. return nil
  242. }
  243. func (fs *memFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) {
  244. fs.mu.Lock()
  245. defer fs.mu.Unlock()
  246. dir, frag, err := fs.find("open", name)
  247. if err != nil {
  248. return nil, err
  249. }
  250. var n *memFSNode
  251. if dir == nil {
  252. // We're opening the root.
  253. if runtime.GOOS == "zos" {
  254. if flag&os.O_WRONLY != 0 {
  255. return nil, os.ErrPermission
  256. }
  257. } else {
  258. if flag&(os.O_WRONLY|os.O_RDWR) != 0 {
  259. return nil, os.ErrPermission
  260. }
  261. }
  262. n, frag = &fs.root, "/"
  263. } else {
  264. n = dir.children[frag]
  265. if flag&(os.O_SYNC|os.O_APPEND) != 0 {
  266. // memFile doesn't support these flags yet.
  267. return nil, os.ErrInvalid
  268. }
  269. if flag&os.O_CREATE != 0 {
  270. if flag&os.O_EXCL != 0 && n != nil {
  271. return nil, os.ErrExist
  272. }
  273. if n == nil {
  274. n = &memFSNode{
  275. mode: perm.Perm(),
  276. }
  277. dir.children[frag] = n
  278. }
  279. }
  280. if n == nil {
  281. return nil, os.ErrNotExist
  282. }
  283. if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 {
  284. n.mu.Lock()
  285. n.data = nil
  286. n.mu.Unlock()
  287. }
  288. }
  289. children := make([]os.FileInfo, 0, len(n.children))
  290. for cName, c := range n.children {
  291. children = append(children, c.stat(cName))
  292. }
  293. return &memFile{
  294. n: n,
  295. nameSnapshot: frag,
  296. childrenSnapshot: children,
  297. }, nil
  298. }
  299. func (fs *memFS) RemoveAll(ctx context.Context, name string) error {
  300. fs.mu.Lock()
  301. defer fs.mu.Unlock()
  302. dir, frag, err := fs.find("remove", name)
  303. if err != nil {
  304. return err
  305. }
  306. if dir == nil {
  307. // We can't remove the root.
  308. return os.ErrInvalid
  309. }
  310. delete(dir.children, frag)
  311. return nil
  312. }
  313. func (fs *memFS) Rename(ctx context.Context, oldName, newName string) error {
  314. fs.mu.Lock()
  315. defer fs.mu.Unlock()
  316. oldName = slashClean(oldName)
  317. newName = slashClean(newName)
  318. if oldName == newName {
  319. return nil
  320. }
  321. if strings.HasPrefix(newName, oldName+"/") {
  322. // We can't rename oldName to be a sub-directory of itself.
  323. return os.ErrInvalid
  324. }
  325. oDir, oFrag, err := fs.find("rename", oldName)
  326. if err != nil {
  327. return err
  328. }
  329. if oDir == nil {
  330. // We can't rename from the root.
  331. return os.ErrInvalid
  332. }
  333. nDir, nFrag, err := fs.find("rename", newName)
  334. if err != nil {
  335. return err
  336. }
  337. if nDir == nil {
  338. // We can't rename to the root.
  339. return os.ErrInvalid
  340. }
  341. oNode, ok := oDir.children[oFrag]
  342. if !ok {
  343. return os.ErrNotExist
  344. }
  345. if oNode.children != nil {
  346. if nNode, ok := nDir.children[nFrag]; ok {
  347. if nNode.children == nil {
  348. return errNotADirectory
  349. }
  350. if len(nNode.children) != 0 {
  351. return errDirectoryNotEmpty
  352. }
  353. }
  354. }
  355. delete(oDir.children, oFrag)
  356. nDir.children[nFrag] = oNode
  357. return nil
  358. }
  359. func (fs *memFS) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  360. fs.mu.Lock()
  361. defer fs.mu.Unlock()
  362. dir, frag, err := fs.find("stat", name)
  363. if err != nil {
  364. return nil, err
  365. }
  366. if dir == nil {
  367. // We're stat'ting the root.
  368. return fs.root.stat("/"), nil
  369. }
  370. if n, ok := dir.children[frag]; ok {
  371. return n.stat(path.Base(name)), nil
  372. }
  373. return nil, os.ErrNotExist
  374. }
  375. // A memFSNode represents a single entry in the in-memory filesystem and also
  376. // implements os.FileInfo.
  377. type memFSNode struct {
  378. // children is protected by memFS.mu.
  379. children map[string]*memFSNode
  380. mu sync.Mutex
  381. data []byte
  382. mode os.FileMode
  383. modTime time.Time
  384. deadProps map[xml.Name]Property
  385. }
  386. func (n *memFSNode) stat(name string) *memFileInfo {
  387. n.mu.Lock()
  388. defer n.mu.Unlock()
  389. return &memFileInfo{
  390. name: name,
  391. size: int64(len(n.data)),
  392. mode: n.mode,
  393. modTime: n.modTime,
  394. }
  395. }
  396. func (n *memFSNode) DeadProps() (map[xml.Name]Property, error) {
  397. n.mu.Lock()
  398. defer n.mu.Unlock()
  399. if len(n.deadProps) == 0 {
  400. return nil, nil
  401. }
  402. ret := make(map[xml.Name]Property, len(n.deadProps))
  403. for k, v := range n.deadProps {
  404. ret[k] = v
  405. }
  406. return ret, nil
  407. }
  408. func (n *memFSNode) Patch(patches []Proppatch) ([]Propstat, error) {
  409. n.mu.Lock()
  410. defer n.mu.Unlock()
  411. pstat := Propstat{Status: http.StatusOK}
  412. for _, patch := range patches {
  413. for _, p := range patch.Props {
  414. pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName})
  415. if patch.Remove {
  416. delete(n.deadProps, p.XMLName)
  417. continue
  418. }
  419. if n.deadProps == nil {
  420. n.deadProps = map[xml.Name]Property{}
  421. }
  422. n.deadProps[p.XMLName] = p
  423. }
  424. }
  425. return []Propstat{pstat}, nil
  426. }
  427. type memFileInfo struct {
  428. name string
  429. size int64
  430. mode os.FileMode
  431. modTime time.Time
  432. }
  433. func (f *memFileInfo) Name() string { return f.name }
  434. func (f *memFileInfo) Size() int64 { return f.size }
  435. func (f *memFileInfo) Mode() os.FileMode { return f.mode }
  436. func (f *memFileInfo) ModTime() time.Time { return f.modTime }
  437. func (f *memFileInfo) IsDir() bool { return f.mode.IsDir() }
  438. func (f *memFileInfo) Sys() interface{} { return nil }
  439. // A memFile is a File implementation for a memFSNode. It is a per-file (not
  440. // per-node) read/write position, and a snapshot of the memFS' tree structure
  441. // (a node's name and children) for that node.
  442. type memFile struct {
  443. n *memFSNode
  444. nameSnapshot string
  445. childrenSnapshot []os.FileInfo
  446. // pos is protected by n.mu.
  447. pos int
  448. }
  449. // A *memFile implements the optional DeadPropsHolder interface.
  450. var _ DeadPropsHolder = (*memFile)(nil)
  451. func (f *memFile) DeadProps() (map[xml.Name]Property, error) { return f.n.DeadProps() }
  452. func (f *memFile) Patch(patches []Proppatch) ([]Propstat, error) { return f.n.Patch(patches) }
  453. func (f *memFile) Close() error {
  454. return nil
  455. }
  456. func (f *memFile) Read(p []byte) (int, error) {
  457. f.n.mu.Lock()
  458. defer f.n.mu.Unlock()
  459. if f.n.mode.IsDir() {
  460. return 0, os.ErrInvalid
  461. }
  462. if f.pos >= len(f.n.data) {
  463. return 0, io.EOF
  464. }
  465. n := copy(p, f.n.data[f.pos:])
  466. f.pos += n
  467. return n, nil
  468. }
  469. func (f *memFile) Readdir(count int) ([]os.FileInfo, error) {
  470. f.n.mu.Lock()
  471. defer f.n.mu.Unlock()
  472. if !f.n.mode.IsDir() {
  473. return nil, os.ErrInvalid
  474. }
  475. old := f.pos
  476. if old >= len(f.childrenSnapshot) {
  477. // The os.File Readdir docs say that at the end of a directory,
  478. // the error is io.EOF if count > 0 and nil if count <= 0.
  479. if count > 0 {
  480. return nil, io.EOF
  481. }
  482. return nil, nil
  483. }
  484. if count > 0 {
  485. f.pos += count
  486. if f.pos > len(f.childrenSnapshot) {
  487. f.pos = len(f.childrenSnapshot)
  488. }
  489. } else {
  490. f.pos = len(f.childrenSnapshot)
  491. old = 0
  492. }
  493. return f.childrenSnapshot[old:f.pos], nil
  494. }
  495. func (f *memFile) Seek(offset int64, whence int) (int64, error) {
  496. f.n.mu.Lock()
  497. defer f.n.mu.Unlock()
  498. npos := f.pos
  499. // TODO: How to handle offsets greater than the size of system int?
  500. switch whence {
  501. case os.SEEK_SET:
  502. npos = int(offset)
  503. case os.SEEK_CUR:
  504. npos += int(offset)
  505. case os.SEEK_END:
  506. npos = len(f.n.data) + int(offset)
  507. default:
  508. npos = -1
  509. }
  510. if npos < 0 {
  511. return 0, os.ErrInvalid
  512. }
  513. f.pos = npos
  514. return int64(f.pos), nil
  515. }
  516. func (f *memFile) Stat() (os.FileInfo, error) {
  517. return f.n.stat(f.nameSnapshot), nil
  518. }
  519. func (f *memFile) Write(p []byte) (int, error) {
  520. lenp := len(p)
  521. f.n.mu.Lock()
  522. defer f.n.mu.Unlock()
  523. if f.n.mode.IsDir() {
  524. return 0, os.ErrInvalid
  525. }
  526. if f.pos < len(f.n.data) {
  527. n := copy(f.n.data[f.pos:], p)
  528. f.pos += n
  529. p = p[n:]
  530. } else if f.pos > len(f.n.data) {
  531. // Write permits the creation of holes, if we've seek'ed past the
  532. // existing end of file.
  533. if f.pos <= cap(f.n.data) {
  534. oldLen := len(f.n.data)
  535. f.n.data = f.n.data[:f.pos]
  536. hole := f.n.data[oldLen:]
  537. for i := range hole {
  538. hole[i] = 0
  539. }
  540. } else {
  541. d := make([]byte, f.pos, f.pos+len(p))
  542. copy(d, f.n.data)
  543. f.n.data = d
  544. }
  545. }
  546. if len(p) > 0 {
  547. // We should only get here if f.pos == len(f.n.data).
  548. f.n.data = append(f.n.data, p...)
  549. f.pos = len(f.n.data)
  550. }
  551. f.n.modTime = time.Now()
  552. return lenp, nil
  553. }
  554. // moveFiles moves files and/or directories from src to dst.
  555. //
  556. // See section 9.9.4 for when various HTTP status codes apply.
  557. func moveFiles(ctx context.Context, fs FileSystem, src, dst string, overwrite bool) (status int, err error) {
  558. created := false
  559. if _, err := fs.Stat(ctx, dst); err != nil {
  560. if !os.IsNotExist(err) {
  561. return http.StatusForbidden, err
  562. }
  563. created = true
  564. } else if overwrite {
  565. // Section 9.9.3 says that "If a resource exists at the destination
  566. // and the Overwrite header is "T", then prior to performing the move,
  567. // the server must perform a DELETE with "Depth: infinity" on the
  568. // destination resource.
  569. if err := fs.RemoveAll(ctx, dst); err != nil {
  570. return http.StatusForbidden, err
  571. }
  572. } else {
  573. return http.StatusPreconditionFailed, os.ErrExist
  574. }
  575. if err := fs.Rename(ctx, src, dst); err != nil {
  576. return http.StatusForbidden, err
  577. }
  578. if created {
  579. return http.StatusCreated, nil
  580. }
  581. return http.StatusNoContent, nil
  582. }
  583. func copyProps(dst, src File) error {
  584. d, ok := dst.(DeadPropsHolder)
  585. if !ok {
  586. return nil
  587. }
  588. s, ok := src.(DeadPropsHolder)
  589. if !ok {
  590. return nil
  591. }
  592. m, err := s.DeadProps()
  593. if err != nil {
  594. return err
  595. }
  596. props := make([]Property, 0, len(m))
  597. for _, prop := range m {
  598. props = append(props, prop)
  599. }
  600. _, err = d.Patch([]Proppatch{{Props: props}})
  601. return err
  602. }
  603. // copyFiles copies files and/or directories from src to dst.
  604. //
  605. // See section 9.8.5 for when various HTTP status codes apply.
  606. func copyFiles(ctx context.Context, fs FileSystem, src, dst string, overwrite bool, depth int, recursion int) (status int, err error) {
  607. if recursion == 1000 {
  608. return http.StatusInternalServerError, errRecursionTooDeep
  609. }
  610. recursion++
  611. // TODO: section 9.8.3 says that "Note that an infinite-depth COPY of /A/
  612. // into /A/B/ could lead to infinite recursion if not handled correctly."
  613. srcFile, err := fs.OpenFile(ctx, src, os.O_RDONLY, 0)
  614. if err != nil {
  615. if os.IsNotExist(err) {
  616. return http.StatusNotFound, err
  617. }
  618. return http.StatusInternalServerError, err
  619. }
  620. defer srcFile.Close()
  621. srcStat, err := srcFile.Stat()
  622. if err != nil {
  623. if os.IsNotExist(err) {
  624. return http.StatusNotFound, err
  625. }
  626. return http.StatusInternalServerError, err
  627. }
  628. srcPerm := srcStat.Mode() & os.ModePerm
  629. created := false
  630. if _, err := fs.Stat(ctx, dst); err != nil {
  631. if os.IsNotExist(err) {
  632. created = true
  633. } else {
  634. return http.StatusForbidden, err
  635. }
  636. } else {
  637. if !overwrite {
  638. return http.StatusPreconditionFailed, os.ErrExist
  639. }
  640. if err := fs.RemoveAll(ctx, dst); err != nil && !os.IsNotExist(err) {
  641. return http.StatusForbidden, err
  642. }
  643. }
  644. if srcStat.IsDir() {
  645. if err := fs.Mkdir(ctx, dst, srcPerm); err != nil {
  646. return http.StatusForbidden, err
  647. }
  648. if depth == infiniteDepth {
  649. children, err := srcFile.Readdir(-1)
  650. if err != nil {
  651. return http.StatusForbidden, err
  652. }
  653. for _, c := range children {
  654. name := c.Name()
  655. s := path.Join(src, name)
  656. d := path.Join(dst, name)
  657. cStatus, cErr := copyFiles(ctx, fs, s, d, overwrite, depth, recursion)
  658. if cErr != nil {
  659. // TODO: MultiStatus.
  660. return cStatus, cErr
  661. }
  662. }
  663. }
  664. } else {
  665. dstFile, err := fs.OpenFile(ctx, dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, srcPerm)
  666. if err != nil {
  667. if os.IsNotExist(err) {
  668. return http.StatusConflict, err
  669. }
  670. return http.StatusForbidden, err
  671. }
  672. _, copyErr := io.Copy(dstFile, srcFile)
  673. propsErr := copyProps(dstFile, srcFile)
  674. closeErr := dstFile.Close()
  675. if copyErr != nil {
  676. return http.StatusInternalServerError, copyErr
  677. }
  678. if propsErr != nil {
  679. return http.StatusInternalServerError, propsErr
  680. }
  681. if closeErr != nil {
  682. return http.StatusInternalServerError, closeErr
  683. }
  684. }
  685. if created {
  686. return http.StatusCreated, nil
  687. }
  688. return http.StatusNoContent, nil
  689. }
  690. // walkFS traverses filesystem fs starting at name up to depth levels.
  691. //
  692. // Allowed values for depth are 0, 1 or infiniteDepth. For each visited node,
  693. // walkFS calls walkFn. If a visited file system node is a directory and
  694. // walkFn returns filepath.SkipDir, walkFS will skip traversal of this node.
  695. func walkFS(ctx context.Context, fs FileSystem, depth int, name string, info os.FileInfo, walkFn filepath.WalkFunc) error {
  696. // This implementation is based on Walk's code in the standard path/filepath package.
  697. err := walkFn(name, info, nil)
  698. if err != nil {
  699. if info.IsDir() && err == filepath.SkipDir {
  700. return nil
  701. }
  702. return err
  703. }
  704. if !info.IsDir() || depth == 0 {
  705. return nil
  706. }
  707. if depth == 1 {
  708. depth = 0
  709. }
  710. // Read directory names.
  711. f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0)
  712. if err != nil {
  713. return walkFn(name, info, err)
  714. }
  715. fileInfos, err := f.Readdir(0)
  716. f.Close()
  717. if err != nil {
  718. return walkFn(name, info, err)
  719. }
  720. for _, fileInfo := range fileInfos {
  721. filename := path.Join(name, fileInfo.Name())
  722. fileInfo, err := fs.Stat(ctx, filename)
  723. if err != nil {
  724. if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
  725. return err
  726. }
  727. } else {
  728. err = walkFS(ctx, fs, depth, filename, fileInfo, walkFn)
  729. if err != nil {
  730. if !fileInfo.IsDir() || err != filepath.SkipDir {
  731. return err
  732. }
  733. }
  734. }
  735. }
  736. return nil
  737. }