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