blob: 4a0c7ffbac9f9d8a1c5e849857aa3c6ab152c6a3 [file] [log] [blame]
Nigel Taobaf9fd42014-11-11 17:46:57 +11001// 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
5package webdav
6
7import (
8 "io"
9 "net/http"
10 "os"
Nigel Tao240cea52014-11-14 11:47:41 +110011 "path"
12 "path/filepath"
13 "strings"
Nick Cooper3eb064e2015-01-05 15:04:58 +110014 "sync"
15 "time"
Nigel Taobaf9fd42014-11-11 17:46:57 +110016)
17
Nigel Tao240cea52014-11-14 11:47:41 +110018// A FileSystem implements access to a collection of named files. The elements
19// in a file path are separated by slash ('/', U+002F) characters, regardless
20// of host operating system convention.
21//
22// Each method has the same semantics as the os package's function of the same
23// name.
Nigel Taobaf9fd42014-11-11 17:46:57 +110024type FileSystem interface {
Nigel Tao240cea52014-11-14 11:47:41 +110025 Mkdir(name string, perm os.FileMode) error
26 OpenFile(name string, flag int, perm os.FileMode) (File, error)
27 RemoveAll(name string) error
28 Stat(name string) (os.FileInfo, error)
Nigel Taobaf9fd42014-11-11 17:46:57 +110029}
30
Nigel Tao240cea52014-11-14 11:47:41 +110031// A File is returned by a FileSystem's OpenFile method and can be served by a
32// Handler.
Nigel Taobaf9fd42014-11-11 17:46:57 +110033type File interface {
34 http.File
35 io.Writer
36}
37
Nigel Tao240cea52014-11-14 11:47:41 +110038// A Dir implements FileSystem using the native file system restricted to a
39// specific directory tree.
40//
41// While the FileSystem.OpenFile method takes '/'-separated paths, a Dir's
42// string value is a filename on the native file system, not a URL, so it is
43// separated by filepath.Separator, which isn't necessarily '/'.
44//
45// An empty Dir is treated as ".".
46type Dir string
47
48func (d Dir) resolve(name string) string {
49 // This implementation is based on Dir.Open's code in the standard net/http package.
50 if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
51 strings.Contains(name, "\x00") {
52 return ""
53 }
54 dir := string(d)
55 if dir == "" {
56 dir = "."
57 }
58 return filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
59}
60
61func (d Dir) Mkdir(name string, perm os.FileMode) error {
62 if name = d.resolve(name); name == "" {
63 return os.ErrNotExist
64 }
65 return os.Mkdir(name, perm)
66}
67
68func (d Dir) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
69 if name = d.resolve(name); name == "" {
70 return nil, os.ErrNotExist
71 }
72 return os.OpenFile(name, flag, perm)
73}
74
75func (d Dir) RemoveAll(name string) error {
76 if name = d.resolve(name); name == "" {
77 return os.ErrNotExist
78 }
79 if name == filepath.Clean(string(d)) {
80 // Prohibit removing the virtual root directory.
81 return os.ErrInvalid
82 }
83 return os.RemoveAll(name)
84}
85
86func (d Dir) Stat(name string) (os.FileInfo, error) {
87 if name = d.resolve(name); name == "" {
88 return nil, os.ErrNotExist
89 }
90 return os.Stat(name)
91}
92
Nick Cooper3eb064e2015-01-05 15:04:58 +110093// NewMemFS returns a new in-memory FileSystem implementation.
94func NewMemFS() FileSystem {
95 return &memFS{
96 root: memFSNode{
97 children: make(map[string]*memFSNode),
98 mode: 0660 | os.ModeDir,
99 modTime: time.Now(),
100 },
101 }
102}
103
104// A memFS implements FileSystem, storing all metadata and actual file data
105// in-memory. No limits on filesystem size are used, so it is not recommended
106// this be used where the clients are untrusted.
107//
108// Concurrent access is permitted. The tree structure is protected by a mutex,
109// and each node's contents and metadata are protected by a per-node mutex.
110//
111// TODO: Enforce file permissions.
112type memFS struct {
113 mu sync.Mutex
114 root memFSNode
115}
116
117// walk walks the directory tree for the fullname, calling f at each step. If f
118// returns an error, the walk will be aborted and return that same error.
119//
120// Each walk is atomic: fs's mutex is held for the entire operation, including
121// all calls to f.
122//
123// dir is the directory at that step, frag is the name fragment, and final is
124// whether it is the final step. For example, walking "/foo/bar/x" will result
125// in 3 calls to f:
126// - "/", "foo", false
127// - "/foo/", "bar", false
128// - "/foo/bar/", "x", true
129func (fs *memFS) walk(op, fullname string, f func(dir *memFSNode, frag string, final bool) error) error {
130 fs.mu.Lock()
131 defer fs.mu.Unlock()
132
133 original := fullname
134 fullname = path.Clean("/" + fullname)
135
136 // Strip any leading "/"s to make fullname a relative path, as the walk
137 // starts at fs.root.
138 if fullname[0] == '/' {
139 fullname = fullname[1:]
140 }
141 dir := &fs.root
142
143 for {
144 frag, remaining := fullname, ""
145 i := strings.IndexRune(fullname, '/')
146 final := i < 0
147 if !final {
148 frag, remaining = fullname[:i], fullname[i+1:]
149 }
150 if err := f(dir, frag, final); err != nil {
151 return &os.PathError{
152 Op: op,
153 Path: original,
154 Err: err,
155 }
156 }
157 if final {
158 break
159 }
160 child := dir.children[frag]
161 if child == nil {
162 return &os.PathError{
163 Op: op,
164 Path: original,
165 Err: os.ErrNotExist,
166 }
167 }
168 if !child.IsDir() {
169 return &os.PathError{
170 Op: op,
171 Path: original,
172 Err: os.ErrInvalid,
173 }
174 }
175 dir, fullname = child, remaining
176 }
177 return nil
178}
179
180func (fs *memFS) Mkdir(name string, perm os.FileMode) error {
181 return fs.walk("mkdir", name, func(dir *memFSNode, frag string, final bool) error {
182 if !final {
183 return nil
184 }
185 if frag == "" {
186 return os.ErrInvalid
187 }
188 if _, ok := dir.children[frag]; ok {
189 return os.ErrExist
190 }
191 dir.children[frag] = &memFSNode{
192 name: frag,
193 children: make(map[string]*memFSNode),
194 mode: perm.Perm() | os.ModeDir,
195 modTime: time.Now(),
196 }
197 return nil
198 })
199}
200
201func (fs *memFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
202 var ret *memFile
203 err := fs.walk("open", name, func(dir *memFSNode, frag string, final bool) error {
204 if !final {
205 return nil
206 }
207 if frag == "" {
208 return os.ErrInvalid
209 }
210 if flag&(os.O_SYNC|os.O_APPEND) != 0 {
211 return os.ErrInvalid
212 }
213 n := dir.children[frag]
214 if flag&os.O_CREATE != 0 {
215 if flag&os.O_EXCL != 0 && n != nil {
216 return os.ErrExist
217 }
218 if n == nil {
219 n = &memFSNode{
220 name: frag,
221 mode: perm.Perm(),
222 }
223 dir.children[frag] = n
224 }
225 }
226 if n == nil {
227 return os.ErrNotExist
228 }
229 if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 {
230 n.mu.Lock()
231 n.data = nil
232 n.mu.Unlock()
233 }
234
235 children := make([]os.FileInfo, 0, len(n.children))
236 for _, c := range n.children {
237 children = append(children, c)
238 }
239 ret = &memFile{
240 n: n,
241 children: children,
242 }
243 return nil
244 })
245 if err != nil {
246 return nil, err
247 }
248 return ret, nil
249}
250
251func (fs *memFS) RemoveAll(name string) error {
252 return fs.walk("remove", name, func(dir *memFSNode, frag string, final bool) error {
253 if !final {
254 return nil
255 }
256 if frag == "" {
257 return os.ErrInvalid
258 }
259 if _, ok := dir.children[frag]; !ok {
260 return os.ErrNotExist
261 }
262 delete(dir.children, frag)
263 return nil
264 })
265}
266
267func (fs *memFS) Stat(name string) (os.FileInfo, error) {
268 var n *memFSNode
269 err := fs.walk("stat", name, func(dir *memFSNode, frag string, final bool) error {
270 if !final {
271 return nil
272 }
273 if frag == "" {
274 return os.ErrInvalid
275 }
276 n = dir.children[frag]
277 if n == nil {
278 return os.ErrNotExist
279 }
280 return nil
281 })
282 if err != nil {
283 return nil, err
284 }
285 return n, nil
286}
287
288// A memFSNode represents a single entry in the in-memory filesystem and also
289// implements os.FileInfo.
290type memFSNode struct {
291 name string
292
293 mu sync.Mutex
294 modTime time.Time
295 mode os.FileMode
296 children map[string]*memFSNode
297 data []byte
298}
299
300func (n *memFSNode) Name() string {
301 return n.name
302}
303
304func (n *memFSNode) Size() int64 {
305 n.mu.Lock()
306 defer n.mu.Unlock()
307 return int64(len(n.data))
308}
309
310func (n *memFSNode) Mode() os.FileMode {
311 n.mu.Lock()
312 defer n.mu.Unlock()
313 return n.mode
314}
315
316func (n *memFSNode) ModTime() time.Time {
317 n.mu.Lock()
318 defer n.mu.Unlock()
319 return n.modTime
320}
321
322func (n *memFSNode) IsDir() bool {
323 return n.Mode().IsDir()
324}
325
326func (n *memFSNode) Sys() interface{} {
327 return nil
328}
329
330// A memFile is a File implementation for a memFSNode. It is a per-file (not
331// per-node) read/write position, and if the node is a directory, a snapshot of
332// that node's children.
333type memFile struct {
334 n *memFSNode
335 children []os.FileInfo
336 // Changes to pos are guarded by n.mu.
337 pos int
338}
339
340func (f *memFile) Close() error {
341 return nil
342}
343
344func (f *memFile) Read(p []byte) (int, error) {
345 if f.n.IsDir() {
346 return 0, os.ErrInvalid
347 }
348 f.n.mu.Lock()
349 defer f.n.mu.Unlock()
350 if f.pos >= len(f.n.data) {
351 return 0, io.EOF
352 }
353 n := copy(p, f.n.data[f.pos:])
354 f.pos += n
355 return n, nil
356}
357
358func (f *memFile) Readdir(count int) ([]os.FileInfo, error) {
359 if !f.n.IsDir() {
360 return nil, os.ErrInvalid
361 }
362 f.n.mu.Lock()
363 defer f.n.mu.Unlock()
364 old := f.pos
365 if old >= len(f.children) {
366 return nil, io.EOF
367 }
368 if count > 0 {
369 f.pos += count
370 if f.pos > len(f.children) {
371 f.pos = len(f.children)
372 }
373 } else {
374 f.pos = len(f.children)
375 old = 0
376 }
377 return f.children[old:f.pos], nil
378}
379
380func (f *memFile) Seek(offset int64, whence int) (int64, error) {
381 f.n.mu.Lock()
382 defer f.n.mu.Unlock()
383 npos := f.pos
384 // TODO: How to handle offsets greater than the size of system int?
385 switch whence {
386 case os.SEEK_SET:
387 npos = int(offset)
388 case os.SEEK_CUR:
389 npos += int(offset)
390 case os.SEEK_END:
391 npos = len(f.n.data) + int(offset)
392 default:
393 npos = -1
394 }
395 if npos < 0 {
396 return 0, os.ErrInvalid
397 }
398 f.pos = npos
399 return int64(f.pos), nil
400}
401
402func (f *memFile) Stat() (os.FileInfo, error) {
403 return f.n, nil
404}
405
406func (f *memFile) Write(p []byte) (int, error) {
Nigel Tao0000f672015-01-07 13:32:21 +1100407 lenp := len(p)
Nick Cooper3eb064e2015-01-05 15:04:58 +1100408 f.n.mu.Lock()
409 defer f.n.mu.Unlock()
Nigel Tao0000f672015-01-07 13:32:21 +1100410
411 if f.pos < len(f.n.data) {
412 n := copy(f.n.data[f.pos:], p)
413 f.pos += n
414 p = p[n:]
415 } else if f.pos > len(f.n.data) {
416 // Write permits the creation of holes, if we've seek'ed past the
417 // existing end of file.
418 if f.pos <= cap(f.n.data) {
419 oldLen := len(f.n.data)
420 f.n.data = f.n.data[:f.pos]
421 hole := f.n.data[oldLen:]
422 for i := range hole {
423 hole[i] = 0
424 }
425 } else {
426 d := make([]byte, f.pos, f.pos+len(p))
427 copy(d, f.n.data)
428 f.n.data = d
429 }
Nick Cooper3eb064e2015-01-05 15:04:58 +1100430 }
Nigel Tao0000f672015-01-07 13:32:21 +1100431
432 if len(p) > 0 {
433 // We should only get here if f.pos == len(f.n.data).
434 f.n.data = append(f.n.data, p...)
435 f.pos = len(f.n.data)
436 }
Nick Cooper3eb064e2015-01-05 15:04:58 +1100437 f.n.modTime = time.Now()
Nigel Tao0000f672015-01-07 13:32:21 +1100438 return lenp, nil
Nick Cooper3eb064e2015-01-05 15:04:58 +1100439}