19889: Stop using old x/net/context library.
[arvados.git] / lib / webdavfs / fs.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 // Package webdavfs adds special behaviors to an arvados.FileSystem so
6 // it's suitable to use with a webdav server.
7 package webdavfs
8
9 import (
10         "context"
11         "crypto/rand"
12         "errors"
13         "fmt"
14         "io"
15         prand "math/rand"
16         "os"
17         "path"
18         "strings"
19         "sync/atomic"
20         "time"
21
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23         "golang.org/x/net/webdav"
24 )
25
26 var (
27         lockPrefix     string = uuid()
28         nextLockSuffix int64  = prand.Int63()
29         ErrReadOnly           = errors.New("read-only filesystem")
30 )
31
32 // FS implements a webdav.FileSystem by wrapping an
33 // arvados.CollectionFilesystem.
34 //
35 // Collections don't preserve empty directories, so Mkdir is
36 // effectively a no-op, and we need to make parent dirs spring into
37 // existence automatically so sequences like "mkcol foo; put foo/bar"
38 // work as expected.
39 type FS struct {
40         FileSystem arvados.FileSystem
41         // Prefix works like fs.Sub: Stat(name) calls
42         // Stat(prefix+name) in the wrapped filesystem.
43         Prefix  string
44         Writing bool
45         // webdav PROPFIND reads the first few bytes of each file
46         // whose filename extension isn't recognized, which is
47         // prohibitively expensive: we end up fetching multiple 64MiB
48         // blocks. Avoid this by returning EOF on all reads when
49         // handling a PROPFIND.
50         AlwaysReadEOF bool
51 }
52
53 func (fs *FS) makeparents(name string) {
54         if !fs.Writing {
55                 return
56         }
57         dir, _ := path.Split(name)
58         if dir == "" || dir == "/" {
59                 return
60         }
61         dir = dir[:len(dir)-1]
62         fs.makeparents(dir)
63         fs.FileSystem.Mkdir(fs.Prefix+dir, 0755)
64 }
65
66 func (fs *FS) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
67         if !fs.Writing {
68                 return ErrReadOnly
69         }
70         name = strings.TrimRight(name, "/")
71         fs.makeparents(name)
72         return fs.FileSystem.Mkdir(fs.Prefix+name, 0755)
73 }
74
75 func (fs *FS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (f webdav.File, err error) {
76         writing := flag&(os.O_WRONLY|os.O_RDWR|os.O_TRUNC) != 0
77         if writing && fs.Writing {
78                 fs.makeparents(name)
79         }
80         f, err = fs.FileSystem.OpenFile(fs.Prefix+name, flag, perm)
81         if !fs.Writing {
82                 // webdav module returns 404 on all OpenFile errors,
83                 // but returns 405 Method Not Allowed if OpenFile()
84                 // succeeds but Write() or Close() fails. We'd rather
85                 // have 405. writeFailer ensures Close() fails if the
86                 // file is opened for writing *or* Write() is called.
87                 var err error
88                 if writing {
89                         err = ErrReadOnly
90                 }
91                 f = writeFailer{File: f, err: err}
92         }
93         if fs.AlwaysReadEOF {
94                 f = readEOF{File: f}
95         }
96         return
97 }
98
99 func (fs *FS) RemoveAll(ctx context.Context, name string) error {
100         return fs.FileSystem.RemoveAll(fs.Prefix + name)
101 }
102
103 func (fs *FS) Rename(ctx context.Context, oldName, newName string) error {
104         if !fs.Writing {
105                 return ErrReadOnly
106         }
107         if strings.HasSuffix(oldName, "/") {
108                 // WebDAV "MOVE foo/ bar/" means rename foo to bar.
109                 oldName = oldName[:len(oldName)-1]
110                 newName = strings.TrimSuffix(newName, "/")
111         }
112         fs.makeparents(newName)
113         return fs.FileSystem.Rename(fs.Prefix+oldName, fs.Prefix+newName)
114 }
115
116 func (fs *FS) Stat(ctx context.Context, name string) (os.FileInfo, error) {
117         if fs.Writing {
118                 fs.makeparents(name)
119         }
120         return fs.FileSystem.Stat(fs.Prefix + name)
121 }
122
123 type writeFailer struct {
124         webdav.File
125         err error
126 }
127
128 func (wf writeFailer) Write([]byte) (int, error) {
129         wf.err = ErrReadOnly
130         return 0, wf.err
131 }
132
133 func (wf writeFailer) Close() error {
134         err := wf.File.Close()
135         if err != nil {
136                 wf.err = err
137         }
138         return wf.err
139 }
140
141 type readEOF struct {
142         webdav.File
143 }
144
145 func (readEOF) Read(p []byte) (int, error) {
146         return 0, io.EOF
147 }
148
149 // NoLockSystem implements webdav.LockSystem by returning success for
150 // every possible locking operation, even though it has no side
151 // effects such as actually locking anything. This works for a
152 // read-only webdav filesystem because webdav locks only apply to
153 // writes.
154 //
155 // This is more suitable than webdav.NewMemLS() for two reasons:
156 // First, it allows keep-web to use one locker for all collections
157 // even though coll1.vhost/foo and coll2.vhost/foo have the same path
158 // but represent different resources. Additionally, it returns valid
159 // tokens (rfc2518 specifies that tokens are represented as URIs and
160 // are unique across all resources for all time), which might improve
161 // client compatibility.
162 //
163 // However, it does also permit impossible operations, like acquiring
164 // conflicting locks and releasing non-existent locks.  This might
165 // confuse some clients if they try to probe for correctness.
166 //
167 // Currently this is a moot point: the LOCK and UNLOCK methods are not
168 // accepted by keep-web, so it suffices to implement the
169 // webdav.LockSystem interface.
170 var NoLockSystem = noLockSystem{}
171
172 type noLockSystem struct{}
173
174 func (noLockSystem) Confirm(time.Time, string, string, ...webdav.Condition) (func(), error) {
175         return noop, nil
176 }
177
178 func (noLockSystem) Create(now time.Time, details webdav.LockDetails) (token string, err error) {
179         return fmt.Sprintf("opaquelocktoken:%s-%x", lockPrefix, atomic.AddInt64(&nextLockSuffix, 1)), nil
180 }
181
182 func (noLockSystem) Refresh(now time.Time, token string, duration time.Duration) (webdav.LockDetails, error) {
183         return webdav.LockDetails{}, nil
184 }
185
186 func (noLockSystem) Unlock(now time.Time, token string) error {
187         return nil
188 }
189
190 func noop() {}
191
192 // Return a version 1 variant 4 UUID, meaning all bits are random
193 // except the ones indicating the version and variant.
194 func uuid() string {
195         var data [16]byte
196         if _, err := rand.Read(data[:]); err != nil {
197                 panic(err)
198         }
199         // variant 1: N=10xx
200         data[8] = data[8]&0x3f | 0x80
201         // version 4: M=0100
202         data[6] = data[6]&0x0f | 0x40
203         return fmt.Sprintf("%x-%x-%x-%x-%x", data[0:4], data[4:6], data[6:8], data[8:10], data[10:])
204 }