The reconcile package is used for DOM reconcilation in Isomorphic Go web applications.

file.go 20KB

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