Merge branch '13201-less-validate' closes #13201
[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.CollectionFileSystem
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         dir, _ := path.Split(name)
51         if dir == "" || dir == "/" {
52                 return
53         }
54         dir = dir[:len(dir)-1]
55         fs.makeparents(dir)
56         fs.collfs.Mkdir(dir, 0755)
57 }
58
59 func (fs *webdavFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
60         if !fs.writing {
61                 return errReadOnly
62         }
63         name = strings.TrimRight(name, "/")
64         fs.makeparents(name)
65         return fs.collfs.Mkdir(name, 0755)
66 }
67
68 func (fs *webdavFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (f webdav.File, err error) {
69         writing := flag&(os.O_WRONLY|os.O_RDWR) != 0
70         if writing {
71                 fs.makeparents(name)
72         }
73         f, err = fs.collfs.OpenFile(name, flag, perm)
74         if !fs.writing {
75                 // webdav module returns 404 on all OpenFile errors,
76                 // but returns 405 Method Not Allowed if OpenFile()
77                 // succeeds but Write() or Close() fails. We'd rather
78                 // have 405.
79                 f = writeFailer{File: f, err: errReadOnly}
80         }
81         if fs.alwaysReadEOF {
82                 f = readEOF{File: f}
83         }
84         return
85 }
86
87 func (fs *webdavFS) RemoveAll(ctx context.Context, name string) error {
88         return fs.collfs.RemoveAll(name)
89 }
90
91 func (fs *webdavFS) Rename(ctx context.Context, oldName, newName string) error {
92         if !fs.writing {
93                 return errReadOnly
94         }
95         fs.makeparents(newName)
96         return fs.collfs.Rename(oldName, newName)
97 }
98
99 func (fs *webdavFS) Stat(ctx context.Context, name string) (os.FileInfo, error) {
100         if fs.writing {
101                 fs.makeparents(name)
102         }
103         return fs.collfs.Stat(name)
104 }
105
106 type writeFailer struct {
107         webdav.File
108         err error
109 }
110
111 func (wf writeFailer) Write([]byte) (int, error) {
112         return 0, wf.err
113 }
114
115 func (wf writeFailer) Close() error {
116         return wf.err
117 }
118
119 type readEOF struct {
120         webdav.File
121 }
122
123 func (readEOF) Read(p []byte) (int, error) {
124         return 0, io.EOF
125 }
126
127 // noLockSystem implements webdav.LockSystem by returning success for
128 // every possible locking operation, even though it has no side
129 // effects such as actually locking anything. This works for a
130 // read-only webdav filesystem because webdav locks only apply to
131 // writes.
132 //
133 // This is more suitable than webdav.NewMemLS() for two reasons:
134 // First, it allows keep-web to use one locker for all collections
135 // even though coll1.vhost/foo and coll2.vhost/foo have the same path
136 // but represent different resources. Additionally, it returns valid
137 // tokens (rfc2518 specifies that tokens are represented as URIs and
138 // are unique across all resources for all time), which might improve
139 // client compatibility.
140 //
141 // However, it does also permit impossible operations, like acquiring
142 // conflicting locks and releasing non-existent locks.  This might
143 // confuse some clients if they try to probe for correctness.
144 //
145 // Currently this is a moot point: the LOCK and UNLOCK methods are not
146 // accepted by keep-web, so it suffices to implement the
147 // webdav.LockSystem interface.
148 type noLockSystem struct{}
149
150 func (*noLockSystem) Confirm(time.Time, string, string, ...webdav.Condition) (func(), error) {
151         return noop, nil
152 }
153
154 func (*noLockSystem) Create(now time.Time, details webdav.LockDetails) (token string, err error) {
155         return fmt.Sprintf("opaquelocktoken:%s-%x", lockPrefix, atomic.AddInt64(&nextLockSuffix, 1)), nil
156 }
157
158 func (*noLockSystem) Refresh(now time.Time, token string, duration time.Duration) (webdav.LockDetails, error) {
159         return webdav.LockDetails{}, nil
160 }
161
162 func (*noLockSystem) Unlock(now time.Time, token string) error {
163         return nil
164 }
165
166 func noop() {}
167
168 // Return a version 1 variant 4 UUID, meaning all bits are random
169 // except the ones indicating the version and variant.
170 func uuid() string {
171         var data [16]byte
172         if _, err := rand.Read(data[:]); err != nil {
173                 panic(err)
174         }
175         // variant 1: N=10xx
176         data[8] = data[8]&0x3f | 0x80
177         // version 4: M=0100
178         data[6] = data[6]&0x0f | 0x40
179         return fmt.Sprintf("%x-%x-%x-%x-%x", data[0:4], data[4:6], data[6:8], data[8:10], data[10:])
180 }