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