file.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. //
  151. // The frag argument will be empty only if dir is the root node and the walk
  152. // ends at that root node.
  153. func (fs *memFS) walk(op, fullname string, f func(dir *memFSNode, frag string, final bool) error) error {
  154. original := fullname
  155. fullname = slashClean(fullname)
  156. // Strip any leading "/"s to make fullname a relative path, as the walk
  157. // starts at fs.root.
  158. if fullname[0] == '/' {
  159. fullname = fullname[1:]
  160. }
  161. dir := &fs.root
  162. for {
  163. frag, remaining := fullname, ""
  164. i := strings.IndexRune(fullname, '/')
  165. final := i < 0
  166. if !final {
  167. frag, remaining = fullname[:i], fullname[i+1:]
  168. }
  169. if frag == "" && dir != &fs.root {
  170. panic("webdav: empty path fragment for a clean path")
  171. }
  172. if err := f(dir, frag, final); err != nil {
  173. return &os.PathError{
  174. Op: op,
  175. Path: original,
  176. Err: err,
  177. }
  178. }
  179. if final {
  180. break
  181. }
  182. child := dir.children[frag]
  183. if child == nil {
  184. return &os.PathError{
  185. Op: op,
  186. Path: original,
  187. Err: os.ErrNotExist,
  188. }
  189. }
  190. if !child.mode.IsDir() {
  191. return &os.PathError{
  192. Op: op,
  193. Path: original,
  194. Err: os.ErrInvalid,
  195. }
  196. }
  197. dir, fullname = child, remaining
  198. }
  199. return nil
  200. }
  201. // find returns the parent of the named node and the relative name fragment
  202. // from the parent to the child. For example, if finding "/foo/bar/baz" then
  203. // parent will be the node for "/foo/bar" and frag will be "baz".
  204. //
  205. // If the fullname names the root node, then parent, frag and err will be zero.
  206. //
  207. // find returns an error if the parent does not already exist or the parent
  208. // isn't a directory, but it will not return an error per se if the child does
  209. // not already exist. The error returned is either nil or an *os.PathError
  210. // whose Op is op.
  211. func (fs *memFS) find(op, fullname string) (parent *memFSNode, frag string, err error) {
  212. err = fs.walk(op, fullname, func(parent0 *memFSNode, frag0 string, final bool) error {
  213. if !final {
  214. return nil
  215. }
  216. if frag0 != "" {
  217. parent, frag = parent0, frag0
  218. }
  219. return nil
  220. })
  221. return parent, frag, err
  222. }
  223. func (fs *memFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
  224. fs.mu.Lock()
  225. defer fs.mu.Unlock()
  226. dir, frag, err := fs.find("mkdir", name)
  227. if err != nil {
  228. return err
  229. }
  230. if dir == nil {
  231. // We can't create the root.
  232. return os.ErrInvalid
  233. }
  234. if _, ok := dir.children[frag]; ok {
  235. return os.ErrExist
  236. }
  237. dir.children[frag] = &memFSNode{
  238. children: make(map[string]*memFSNode),
  239. mode: perm.Perm() | os.ModeDir,
  240. modTime: time.Now(),
  241. }
  242. return nil
  243. }
  244. func (fs *memFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) {
  245. fs.mu.Lock()
  246. defer fs.mu.Unlock()
  247. dir, frag, err := fs.find("open", name)
  248. if err != nil {
  249. return nil, err
  250. }
  251. var n *memFSNode
  252. if dir == nil {
  253. // We're opening the root.
  254. if runtime.GOOS == "zos" {
  255. if flag&os.O_WRONLY != 0 {
  256. return nil, os.ErrPermission
  257. }
  258. } else {
  259. if flag&(os.O_WRONLY|os.O_RDWR) != 0 {
  260. return nil, os.ErrPermission
  261. }
  262. }
  263. n, frag = &fs.root, "/"
  264. } else {
  265. n = dir.children[frag]
  266. if flag&(os.O_SYNC|os.O_APPEND) != 0 {
  267. // memFile doesn't support these flags yet.
  268. return nil, os.ErrInvalid
  269. }
  270. if flag&os.O_CREATE != 0 {
  271. if flag&os.O_EXCL != 0 && n != nil {
  272. return nil, os.ErrExist
  273. }
  274. if n == nil {
  275. n = &memFSNode{
  276. mode: perm.Perm(),
  277. }
  278. dir.children[frag] = n
  279. }
  280. }
  281. if n == nil {
  282. return nil, os.ErrNotExist
  283. }
  284. if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 {
  285. n.mu.Lock()
  286. n.data = nil
  287. n.mu.Unlock()
  288. }
  289. }
  290. children := make([]os.FileInfo, 0, len(n.children))
  291. for cName, c := range n.children {
  292. children = append(children, c.stat(cName))
  293. }
  294. return &memFile{
  295. n: n,
  296. nameSnapshot: frag,
  297. childrenSnapshot: children,
  298. }, nil
  299. }
  300. func (fs *memFS) RemoveAll(ctx context.Context, name string) error {
  301. fs.mu.Lock()
  302. defer fs.mu.Unlock()
  303. dir, frag, err := fs.find("remove", name)
  304. if err != nil {
  305. return err
  306. }
  307. if dir == nil {
  308. // We can't remove the root.
  309. return os.ErrInvalid
  310. }
  311. delete(dir.children, frag)
  312. return nil
  313. }
  314. func (fs *memFS) Rename(ctx context.Context, oldName, newName string) error {
  315. fs.mu.Lock()
  316. defer fs.mu.Unlock()
  317. oldName = slashClean(oldName)
  318. newName = slashClean(newName)
  319. if oldName == newName {
  320. return nil
  321. }
  322. if strings.HasPrefix(newName, oldName+"/") {
  323. // We can't rename oldName to be a sub-directory of itself.
  324. return os.ErrInvalid
  325. }
  326. oDir, oFrag, err := fs.find("rename", oldName)
  327. if err != nil {
  328. return err
  329. }
  330. if oDir == nil {
  331. // We can't rename from the root.
  332. return os.ErrInvalid
  333. }
  334. nDir, nFrag, err := fs.find("rename", newName)
  335. if err != nil {
  336. return err
  337. }
  338. if nDir == nil {
  339. // We can't rename to the root.
  340. return os.ErrInvalid
  341. }
  342. oNode, ok := oDir.children[oFrag]
  343. if !ok {
  344. return os.ErrNotExist
  345. }
  346. if oNode.children != nil {
  347. if nNode, ok := nDir.children[nFrag]; ok {
  348. if nNode.children == nil {
  349. return errNotADirectory
  350. }
  351. if len(nNode.children) != 0 {
  352. return errDirectoryNotEmpty
  353. }
  354. }
  355. }
  356. delete(oDir.children, oFrag)
  357. nDir.children[nFrag] = oNode
  358. return nil
  359. }
  360. func (fs *memFS) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  361. fs.mu.Lock()
  362. defer fs.mu.Unlock()
  363. dir, frag, err := fs.find("stat", name)
  364. if err != nil {
  365. return nil, err
  366. }
  367. if dir == nil {
  368. // We're stat'ting the root.
  369. return fs.root.stat("/"), nil
  370. }
  371. if n, ok := dir.children[frag]; ok {
  372. return n.stat(path.Base(name)), nil
  373. }
  374. return nil, os.ErrNotExist
  375. }
  376. // A memFSNode represents a single entry in the in-memory filesystem and also
  377. // implements os.FileInfo.
  378. type memFSNode struct {
  379. // children is protected by memFS.mu.
  380. children map[string]*memFSNode
  381. mu sync.Mutex
  382. data []byte
  383. mode os.FileMode
  384. modTime time.Time
  385. deadProps map[xml.Name]Property
  386. }
  387. func (n *memFSNode) stat(name string) *memFileInfo {
  388. n.mu.Lock()
  389. defer n.mu.Unlock()
  390. return &memFileInfo{
  391. name: name,
  392. size: int64(len(n.data)),
  393. mode: n.mode,
  394. modTime: n.modTime,
  395. }
  396. }
  397. func (n *memFSNode) DeadProps() (map[xml.Name]Property, error) {
  398. n.mu.Lock()
  399. defer n.mu.Unlock()
  400. if len(n.deadProps) == 0 {
  401. return nil, nil
  402. }
  403. ret := make(map[xml.Name]Property, len(n.deadProps))
  404. for k, v := range n.deadProps {
  405. ret[k] = v
  406. }
  407. return ret, nil
  408. }
  409. func (n *memFSNode) Patch(patches []Proppatch) ([]Propstat, error) {
  410. n.mu.Lock()
  411. defer n.mu.Unlock()
  412. pstat := Propstat{Status: http.StatusOK}
  413. for _, patch := range patches {
  414. for _, p := range patch.Props {
  415. pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName})
  416. if patch.Remove {
  417. delete(n.deadProps, p.XMLName)
  418. continue
  419. }
  420. if n.deadProps == nil {
  421. n.deadProps = map[xml.Name]Property{}
  422. }
  423. n.deadProps[p.XMLName] = p
  424. }
  425. }
  426. return []Propstat{pstat}, nil
  427. }
  428. type memFileInfo struct {
  429. name string
  430. size int64
  431. mode os.FileMode
  432. modTime time.Time
  433. }
  434. func (f *memFileInfo) Name() string { return f.name }
  435. func (f *memFileInfo) Size() int64 { return f.size }
  436. func (f *memFileInfo) Mode() os.FileMode { return f.mode }
  437. func (f *memFileInfo) ModTime() time.Time { return f.modTime }
  438. func (f *memFileInfo) IsDir() bool { return f.mode.IsDir() }
  439. func (f *memFileInfo) Sys() interface{} { return nil }
  440. // A memFile is a File implementation for a memFSNode. It is a per-file (not
  441. // per-node) read/write position, and a snapshot of the memFS' tree structure
  442. // (a node's name and children) for that node.
  443. type memFile struct {
  444. n *memFSNode
  445. nameSnapshot string
  446. childrenSnapshot []os.FileInfo
  447. // pos is protected by n.mu.
  448. pos int
  449. }
  450. // A *memFile implements the optional DeadPropsHolder interface.
  451. var _ DeadPropsHolder = (*memFile)(nil)
  452. func (f *memFile) DeadProps() (map[xml.Name]Property, error) { return f.n.DeadProps() }
  453. func (f *memFile) Patch(patches []Proppatch) ([]Propstat, error) { return f.n.Patch(patches) }
  454. func (f *memFile) Close() error {
  455. return nil
  456. }
  457. func (f *memFile) Read(p []byte) (int, error) {
  458. f.n.mu.Lock()
  459. defer f.n.mu.Unlock()
  460. if f.n.mode.IsDir() {
  461. return 0, os.ErrInvalid
  462. }
  463. if f.pos >= len(f.n.data) {
  464. return 0, io.EOF
  465. }
  466. n := copy(p, f.n.data[f.pos:])
  467. f.pos += n
  468. return n, nil
  469. }
  470. func (f *memFile) Readdir(count int) ([]os.FileInfo, error) {
  471. f.n.mu.Lock()
  472. defer f.n.mu.Unlock()
  473. if !f.n.mode.IsDir() {
  474. return nil, os.ErrInvalid
  475. }
  476. old := f.pos
  477. if old >= len(f.childrenSnapshot) {
  478. // The os.File Readdir docs say that at the end of a directory,
  479. // the error is io.EOF if count > 0 and nil if count <= 0.
  480. if count > 0 {
  481. return nil, io.EOF
  482. }
  483. return nil, nil
  484. }
  485. if count > 0 {
  486. f.pos += count
  487. if f.pos > len(f.childrenSnapshot) {
  488. f.pos = len(f.childrenSnapshot)
  489. }
  490. } else {
  491. f.pos = len(f.childrenSnapshot)
  492. old = 0
  493. }
  494. return f.childrenSnapshot[old:f.pos], nil
  495. }
  496. func (f *memFile) Seek(offset int64, whence int) (int64, error) {
  497. f.n.mu.Lock()
  498. defer f.n.mu.Unlock()
  499. npos := f.pos
  500. // TODO: How to handle offsets greater than the size of system int?
  501. switch whence {
  502. case io.SeekStart:
  503. npos = int(offset)
  504. case io.SeekCurrent:
  505. npos += int(offset)
  506. case io.SeekEnd:
  507. npos = len(f.n.data) + int(offset)
  508. default:
  509. npos = -1
  510. }
  511. if npos < 0 {
  512. return 0, os.ErrInvalid
  513. }
  514. f.pos = npos
  515. return int64(f.pos), nil
  516. }
  517. func (f *memFile) Stat() (os.FileInfo, error) {
  518. return f.n.stat(f.nameSnapshot), nil
  519. }
  520. func (f *memFile) Write(p []byte) (int, error) {
  521. lenp := len(p)
  522. f.n.mu.Lock()
  523. defer f.n.mu.Unlock()
  524. if f.n.mode.IsDir() {
  525. return 0, os.ErrInvalid
  526. }
  527. if f.pos < len(f.n.data) {
  528. n := copy(f.n.data[f.pos:], p)
  529. f.pos += n
  530. p = p[n:]
  531. } else if f.pos > len(f.n.data) {
  532. // Write permits the creation of holes, if we've seek'ed past the
  533. // existing end of file.
  534. if f.pos <= cap(f.n.data) {
  535. oldLen := len(f.n.data)
  536. f.n.data = f.n.data[:f.pos]
  537. hole := f.n.data[oldLen:]
  538. for i := range hole {
  539. hole[i] = 0
  540. }
  541. } else {
  542. d := make([]byte, f.pos, f.pos+len(p))
  543. copy(d, f.n.data)
  544. f.n.data = d
  545. }
  546. }
  547. if len(p) > 0 {
  548. // We should only get here if f.pos == len(f.n.data).
  549. f.n.data = append(f.n.data, p...)
  550. f.pos = len(f.n.data)
  551. }
  552. f.n.modTime = time.Now()
  553. return lenp, nil
  554. }
  555. // moveFiles moves files and/or directories from src to dst.
  556. //
  557. // See section 9.9.4 for when various HTTP status codes apply.
  558. func moveFiles(ctx context.Context, fs FileSystem, src, dst string, overwrite bool) (status int, err error) {
  559. created := false
  560. if _, err := fs.Stat(ctx, dst); err != nil {
  561. if !os.IsNotExist(err) {
  562. return http.StatusForbidden, err
  563. }
  564. created = true
  565. } else if overwrite {
  566. // Section 9.9.3 says that "If a resource exists at the destination
  567. // and the Overwrite header is "T", then prior to performing the move,
  568. // the server must perform a DELETE with "Depth: infinity" on the
  569. // destination resource.
  570. if err := fs.RemoveAll(ctx, dst); err != nil {
  571. return http.StatusForbidden, err
  572. }
  573. } else {
  574. return http.StatusPreconditionFailed, os.ErrExist
  575. }
  576. if err := fs.Rename(ctx, src, dst); err != nil {
  577. return http.StatusForbidden, err
  578. }
  579. if created {
  580. return http.StatusCreated, nil
  581. }
  582. return http.StatusNoContent, nil
  583. }
  584. func copyProps(dst, src File) error {
  585. d, ok := dst.(DeadPropsHolder)
  586. if !ok {
  587. return nil
  588. }
  589. s, ok := src.(DeadPropsHolder)
  590. if !ok {
  591. return nil
  592. }
  593. m, err := s.DeadProps()
  594. if err != nil {
  595. return err
  596. }
  597. props := make([]Property, 0, len(m))
  598. for _, prop := range m {
  599. props = append(props, prop)
  600. }
  601. _, err = d.Patch([]Proppatch{{Props: props}})
  602. return err
  603. }
  604. // copyFiles copies files and/or directories from src to dst.
  605. //
  606. // See section 9.8.5 for when various HTTP status codes apply.
  607. func copyFiles(ctx context.Context, fs FileSystem, src, dst string, overwrite bool, depth int, recursion int) (status int, err error) {
  608. if recursion == 1000 {
  609. return http.StatusInternalServerError, errRecursionTooDeep
  610. }
  611. recursion++
  612. // TODO: section 9.8.3 says that "Note that an infinite-depth COPY of /A/
  613. // into /A/B/ could lead to infinite recursion if not handled correctly."
  614. srcFile, err := fs.OpenFile(ctx, src, os.O_RDONLY, 0)
  615. if err != nil {
  616. if os.IsNotExist(err) {
  617. return http.StatusNotFound, err
  618. }
  619. return http.StatusInternalServerError, err
  620. }
  621. defer srcFile.Close()
  622. srcStat, err := srcFile.Stat()
  623. if err != nil {
  624. if os.IsNotExist(err) {
  625. return http.StatusNotFound, err
  626. }
  627. return http.StatusInternalServerError, err
  628. }
  629. srcPerm := srcStat.Mode() & os.ModePerm
  630. created := false
  631. if _, err := fs.Stat(ctx, dst); err != nil {
  632. if os.IsNotExist(err) {
  633. created = true
  634. } else {
  635. return http.StatusForbidden, err
  636. }
  637. } else {
  638. if !overwrite {
  639. return http.StatusPreconditionFailed, os.ErrExist
  640. }
  641. if err := fs.RemoveAll(ctx, dst); err != nil && !os.IsNotExist(err) {
  642. return http.StatusForbidden, err
  643. }
  644. }
  645. if srcStat.IsDir() {
  646. if err := fs.Mkdir(ctx, dst, srcPerm); err != nil {
  647. return http.StatusForbidden, err
  648. }
  649. if depth == infiniteDepth {
  650. children, err := srcFile.Readdir(-1)
  651. if err != nil {
  652. return http.StatusForbidden, err
  653. }
  654. for _, c := range children {
  655. name := c.Name()
  656. s := path.Join(src, name)
  657. d := path.Join(dst, name)
  658. cStatus, cErr := copyFiles(ctx, fs, s, d, overwrite, depth, recursion)
  659. if cErr != nil {
  660. // TODO: MultiStatus.
  661. return cStatus, cErr
  662. }
  663. }
  664. }
  665. } else {
  666. dstFile, err := fs.OpenFile(ctx, dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, srcPerm)
  667. if err != nil {
  668. if os.IsNotExist(err) {
  669. return http.StatusConflict, err
  670. }
  671. return http.StatusForbidden, err
  672. }
  673. _, copyErr := io.Copy(dstFile, srcFile)
  674. propsErr := copyProps(dstFile, srcFile)
  675. closeErr := dstFile.Close()
  676. if copyErr != nil {
  677. return http.StatusInternalServerError, copyErr
  678. }
  679. if propsErr != nil {
  680. return http.StatusInternalServerError, propsErr
  681. }
  682. if closeErr != nil {
  683. return http.StatusInternalServerError, closeErr
  684. }
  685. }
  686. if created {
  687. return http.StatusCreated, nil
  688. }
  689. return http.StatusNoContent, nil
  690. }
  691. // walkFS traverses filesystem fs starting at name up to depth levels.
  692. //
  693. // Allowed values for depth are 0, 1 or infiniteDepth. For each visited node,
  694. // walkFS calls walkFn. If a visited file system node is a directory and
  695. // walkFn returns filepath.SkipDir, walkFS will skip traversal of this node.
  696. func walkFS(ctx context.Context, fs FileSystem, depth int, name string, info os.FileInfo, walkFn filepath.WalkFunc) error {
  697. // This implementation is based on Walk's code in the standard path/filepath package.
  698. err := walkFn(name, info, nil)
  699. if err != nil {
  700. if info.IsDir() && err == filepath.SkipDir {
  701. return nil
  702. }
  703. return err
  704. }
  705. if !info.IsDir() || depth == 0 {
  706. return nil
  707. }
  708. if depth == 1 {
  709. depth = 0
  710. }
  711. // Read directory names.
  712. f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0)
  713. if err != nil {
  714. return walkFn(name, info, err)
  715. }
  716. fileInfos, err := f.Readdir(0)
  717. f.Close()
  718. if err != nil {
  719. return walkFn(name, info, err)
  720. }
  721. for _, fileInfo := range fileInfos {
  722. filename := path.Join(name, fileInfo.Name())
  723. fileInfo, err := fs.Stat(ctx, filename)
  724. if err != nil {
  725. if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
  726. return err
  727. }
  728. } else {
  729. err = walkFS(ctx, fs, depth, filename, fileInfo, walkFn)
  730. if err != nil {
  731. if !fileInfo.IsDir() || err != filepath.SkipDir {
  732. return err
  733. }
  734. }
  735. }
  736. }
  737. return nil
  738. }