aboutsummaryrefslogtreecommitdiff
path: root/webdav/file.go
blob: 34c8df8c603eaad9d182c763b3b722e52eaeaef1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package webdav

import (
	"io"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

// A FileSystem implements access to a collection of named files. The elements
// in a file path are separated by slash ('/', U+002F) characters, regardless
// of host operating system convention.
//
// Each method has the same semantics as the os package's function of the same
// name.
type FileSystem interface {
	Mkdir(name string, perm os.FileMode) error
	OpenFile(name string, flag int, perm os.FileMode) (File, error)
	RemoveAll(name string) error
	Stat(name string) (os.FileInfo, error)
}

// A File is returned by a FileSystem's OpenFile method and can be served by a
// Handler.
type File interface {
	http.File
	io.Writer
}

// A Dir implements FileSystem using the native file system restricted to a
// specific directory tree.
//
// While the FileSystem.OpenFile method takes '/'-separated paths, a Dir's
// string value is a filename on the native file system, not a URL, so it is
// separated by filepath.Separator, which isn't necessarily '/'.
//
// An empty Dir is treated as ".".
type Dir string

func (d Dir) resolve(name string) string {
	// This implementation is based on Dir.Open's code in the standard net/http package.
	if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
		strings.Contains(name, "\x00") {
		return ""
	}
	dir := string(d)
	if dir == "" {
		dir = "."
	}
	return filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
}

func (d Dir) Mkdir(name string, perm os.FileMode) error {
	if name = d.resolve(name); name == "" {
		return os.ErrNotExist
	}
	return os.Mkdir(name, perm)
}

func (d Dir) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
	if name = d.resolve(name); name == "" {
		return nil, os.ErrNotExist
	}
	return os.OpenFile(name, flag, perm)
}

func (d Dir) RemoveAll(name string) error {
	if name = d.resolve(name); name == "" {
		return os.ErrNotExist
	}
	if name == filepath.Clean(string(d)) {
		// Prohibit removing the virtual root directory.
		return os.ErrInvalid
	}
	return os.RemoveAll(name)
}

func (d Dir) Stat(name string) (os.FileInfo, error) {
	if name = d.resolve(name); name == "" {
		return nil, os.ErrNotExist
	}
	return os.Stat(name)
}

// NewMemFS returns a new in-memory FileSystem implementation.
func NewMemFS() FileSystem {
	return &memFS{
		root: memFSNode{
			children: make(map[string]*memFSNode),
			mode:     0660 | os.ModeDir,
			modTime:  time.Now(),
		},
	}
}

// A memFS implements FileSystem, storing all metadata and actual file data
// in-memory. No limits on filesystem size are used, so it is not recommended
// this be used where the clients are untrusted.
//
// Concurrent access is permitted. The tree structure is protected by a mutex,
// and each node's contents and metadata are protected by a per-node mutex.
//
// TODO: Enforce file permissions.
type memFS struct {
	mu   sync.Mutex
	root memFSNode
}

// walk walks the directory tree for the fullname, calling f at each step. If f
// returns an error, the walk will be aborted and return that same error.
//
// Each walk is atomic: fs's mutex is held for the entire operation, including
// all calls to f.
//
// dir is the directory at that step, frag is the name fragment, and final is
// whether it is the final step. For example, walking "/foo/bar/x" will result
// in 3 calls to f:
//   - "/", "foo", false
//   - "/foo/", "bar", false
//   - "/foo/bar/", "x", true
func (fs *memFS) walk(op, fullname string, f func(dir *memFSNode, frag string, final bool) error) error {
	fs.mu.Lock()
	defer fs.mu.Unlock()

	original := fullname
	fullname = path.Clean("/" + fullname)

	// Strip any leading "/"s to make fullname a relative path, as the walk
	// starts at fs.root.
	if fullname[0] == '/' {
		fullname = fullname[1:]
	}
	dir := &fs.root

	for {
		frag, remaining := fullname, ""
		i := strings.IndexRune(fullname, '/')
		final := i < 0
		if !final {
			frag, remaining = fullname[:i], fullname[i+1:]
		}
		if err := f(dir, frag, final); err != nil {
			return &os.PathError{
				Op:   op,
				Path: original,
				Err:  err,
			}
		}
		if final {
			break
		}
		child := dir.children[frag]
		if child == nil {
			return &os.PathError{
				Op:   op,
				Path: original,
				Err:  os.ErrNotExist,
			}
		}
		if !child.IsDir() {
			return &os.PathError{
				Op:   op,
				Path: original,
				Err:  os.ErrInvalid,
			}
		}
		dir, fullname = child, remaining
	}
	return nil
}

func (fs *memFS) Mkdir(name string, perm os.FileMode) error {
	return fs.walk("mkdir", name, func(dir *memFSNode, frag string, final bool) error {
		if !final {
			return nil
		}
		if frag == "" {
			return os.ErrInvalid
		}
		if _, ok := dir.children[frag]; ok {
			return os.ErrExist
		}
		dir.children[frag] = &memFSNode{
			name:     frag,
			children: make(map[string]*memFSNode),
			mode:     perm.Perm() | os.ModeDir,
			modTime:  time.Now(),
		}
		return nil
	})
}

func (fs *memFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
	var ret *memFile
	err := fs.walk("open", name, func(dir *memFSNode, frag string, final bool) error {
		if !final {
			return nil
		}
		if frag == "" {
			return os.ErrInvalid
		}
		if flag&(os.O_SYNC|os.O_APPEND) != 0 {
			return os.ErrInvalid
		}
		n := dir.children[frag]
		if flag&os.O_CREATE != 0 {
			if flag&os.O_EXCL != 0 && n != nil {
				return os.ErrExist
			}
			if n == nil {
				n = &memFSNode{
					name: frag,
					mode: perm.Perm(),
				}
				dir.children[frag] = n
			}
		}
		if n == nil {
			return os.ErrNotExist
		}
		if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 {
			n.mu.Lock()
			n.data = nil
			n.mu.Unlock()
		}

		children := make([]os.FileInfo, 0, len(n.children))
		for _, c := range n.children {
			children = append(children, c)
		}
		ret = &memFile{
			n:        n,
			children: children,
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return ret, nil
}

func (fs *memFS) RemoveAll(name string) error {
	return fs.walk("remove", name, func(dir *memFSNode, frag string, final bool) error {
		if !final {
			return nil
		}
		if frag == "" {
			return os.ErrInvalid
		}
		if _, ok := dir.children[frag]; !ok {
			return os.ErrNotExist
		}
		delete(dir.children, frag)
		return nil
	})
}

func (fs *memFS) Stat(name string) (os.FileInfo, error) {
	var n *memFSNode
	err := fs.walk("stat", name, func(dir *memFSNode, frag string, final bool) error {
		if !final {
			return nil
		}
		if frag == "" {
			return os.ErrInvalid
		}
		n = dir.children[frag]
		if n == nil {
			return os.ErrNotExist
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return n, nil
}

// A memFSNode represents a single entry in the in-memory filesystem and also
// implements os.FileInfo.
type memFSNode struct {
	name string

	mu       sync.Mutex
	modTime  time.Time
	mode     os.FileMode
	children map[string]*memFSNode
	data     []byte
}

func (n *memFSNode) Name() string {
	return n.name
}

func (n *memFSNode) Size() int64 {
	n.mu.Lock()
	defer n.mu.Unlock()
	return int64(len(n.data))
}

func (n *memFSNode) Mode() os.FileMode {
	n.mu.Lock()
	defer n.mu.Unlock()
	return n.mode
}

func (n *memFSNode) ModTime() time.Time {
	n.mu.Lock()
	defer n.mu.Unlock()
	return n.modTime
}

func (n *memFSNode) IsDir() bool {
	return n.Mode().IsDir()
}

func (n *memFSNode) Sys() interface{} {
	return nil
}

// A memFile is a File implementation for a memFSNode. It is a per-file (not
// per-node) read/write position, and if the node is a directory, a snapshot of
// that node's children.
type memFile struct {
	n        *memFSNode
	children []os.FileInfo
	// Changes to pos are guarded by n.mu.
	pos int
}

func (f *memFile) Close() error {
	return nil
}

func (f *memFile) Read(p []byte) (int, error) {
	if f.n.IsDir() {
		return 0, os.ErrInvalid
	}
	f.n.mu.Lock()
	defer f.n.mu.Unlock()
	if f.pos >= len(f.n.data) {
		return 0, io.EOF
	}
	n := copy(p, f.n.data[f.pos:])
	f.pos += n
	return n, nil
}

func (f *memFile) Readdir(count int) ([]os.FileInfo, error) {
	if !f.n.IsDir() {
		return nil, os.ErrInvalid
	}
	f.n.mu.Lock()
	defer f.n.mu.Unlock()
	old := f.pos
	if old >= len(f.children) {
		return nil, io.EOF
	}
	if count > 0 {
		f.pos += count
		if f.pos > len(f.children) {
			f.pos = len(f.children)
		}
	} else {
		f.pos = len(f.children)
		old = 0
	}
	return f.children[old:f.pos], nil
}

func (f *memFile) Seek(offset int64, whence int) (int64, error) {
	f.n.mu.Lock()
	defer f.n.mu.Unlock()
	npos := f.pos
	// TODO: How to handle offsets greater than the size of system int?
	switch whence {
	case os.SEEK_SET:
		npos = int(offset)
	case os.SEEK_CUR:
		npos += int(offset)
	case os.SEEK_END:
		npos = len(f.n.data) + int(offset)
	default:
		npos = -1
	}
	if npos < 0 {
		return 0, os.ErrInvalid
	}
	f.pos = npos
	return int64(f.pos), nil
}

func (f *memFile) Stat() (os.FileInfo, error) {
	return f.n, nil
}

func (f *memFile) Write(p []byte) (int, error) {
	f.n.mu.Lock()
	defer f.n.mu.Unlock()
	epos := len(p) + f.pos
	if epos > len(f.n.data) {
		d := make([]byte, epos)
		copy(d, f.n.data)
		f.n.data = d
	}
	copy(f.n.data[f.pos:], p)
	f.pos = epos
	f.n.modTime = time.Now()
	return len(p), nil
}