12216: Merge branch 'master' into 12216-webdav-list
[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         prand "math/rand"
12         "net/http"
13         "os"
14         "sync"
15         "sync/atomic"
16         "time"
17
18         "git.curoverse.com/arvados.git/sdk/go/arvados"
19
20         "golang.org/x/net/context"
21         "golang.org/x/net/webdav"
22 )
23
24 var (
25         lockPrefix     string = uuid()
26         nextLockSuffix int64  = prand.Int63()
27         errReadOnly           = errors.New("read-only filesystem")
28 )
29
30 // webdavFS implements a read-only webdav.FileSystem by wrapping an
31 // arvados.CollectionFilesystem.
32 type webdavFS struct {
33         collfs arvados.CollectionFileSystem
34 }
35
36 var _ webdav.FileSystem = &webdavFS{}
37
38 func (fs *webdavFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
39         return errReadOnly
40 }
41
42 func (fs *webdavFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) {
43         fi, err := fs.collfs.Stat(name)
44         if err != nil {
45                 return nil, err
46         }
47         return &webdavFile{collfs: fs.collfs, fileInfo: fi, name: name}, nil
48 }
49
50 func (fs *webdavFS) RemoveAll(ctx context.Context, name string) error {
51         return errReadOnly
52 }
53
54 func (fs *webdavFS) Rename(ctx context.Context, oldName, newName string) error {
55         return errReadOnly
56 }
57
58 func (fs *webdavFS) Stat(ctx context.Context, name string) (os.FileInfo, error) {
59         return fs.collfs.Stat(name)
60 }
61
62 // webdavFile implements a read-only webdav.File by wrapping
63 // http.File.
64 //
65 // The http.File is opened from an arvados.CollectionFileSystem, but
66 // not until Seek, Read, or Readdir is called. This deferred-open
67 // strategy makes webdav's OpenFile-Stat-Close cycle fast even though
68 // the collfs's Open method is slow. This is relevant because webdav
69 // does OpenFile-Stat-Close on each file when preparing directory
70 // listings.
71 //
72 // Writes to a webdavFile always fail.
73 type webdavFile struct {
74         // fields populated by (*webdavFS).OpenFile()
75         collfs   http.FileSystem
76         fileInfo os.FileInfo
77         name     string
78
79         // internal fields
80         file     http.File
81         loadOnce sync.Once
82         err      error
83 }
84
85 func (f *webdavFile) load() {
86         f.file, f.err = f.collfs.Open(f.name)
87 }
88
89 func (f *webdavFile) Write([]byte) (int, error) {
90         return 0, errReadOnly
91 }
92
93 func (f *webdavFile) Seek(offset int64, whence int) (int64, error) {
94         f.loadOnce.Do(f.load)
95         if f.err != nil {
96                 return 0, f.err
97         }
98         return f.file.Seek(offset, whence)
99 }
100
101 func (f *webdavFile) Read(buf []byte) (int, error) {
102         f.loadOnce.Do(f.load)
103         if f.err != nil {
104                 return 0, f.err
105         }
106         return f.file.Read(buf)
107 }
108
109 func (f *webdavFile) Close() error {
110         if f.file == nil {
111                 // We never called load(), or load() failed
112                 return f.err
113         }
114         return f.file.Close()
115 }
116
117 func (f *webdavFile) Readdir(n int) ([]os.FileInfo, error) {
118         f.loadOnce.Do(f.load)
119         if f.err != nil {
120                 return nil, f.err
121         }
122         return f.file.Readdir(n)
123 }
124
125 func (f *webdavFile) Stat() (os.FileInfo, error) {
126         return f.fileInfo, nil
127 }
128
129 // noLockSystem implements webdav.LockSystem by returning success for
130 // every possible locking operation, even though it has no side
131 // effects such as actually locking anything. This works for a
132 // read-only webdav filesystem because webdav locks only apply to
133 // writes.
134 //
135 // This is more suitable than webdav.NewMemLS() for two reasons:
136 // First, it allows keep-web to use one locker for all collections
137 // even though coll1.vhost/foo and coll2.vhost/foo have the same path
138 // but represent different resources. Additionally, it returns valid
139 // tokens (rfc2518 specifies that tokens are represented as URIs and
140 // are unique across all resources for all time), which might improve
141 // client compatibility.
142 //
143 // However, it does also permit impossible operations, like acquiring
144 // conflicting locks and releasing non-existent locks.  This might
145 // confuse some clients if they try to probe for correctness.
146 //
147 // Currently this is a moot point: the LOCK and UNLOCK methods are not
148 // accepted by keep-web, so it suffices to implement the
149 // webdav.LockSystem interface.
150 type noLockSystem struct{}
151
152 func (*noLockSystem) Confirm(time.Time, string, string, ...webdav.Condition) (func(), error) {
153         return noop, nil
154 }
155
156 func (*noLockSystem) Create(now time.Time, details webdav.LockDetails) (token string, err error) {
157         return fmt.Sprintf("opaquelocktoken:%s-%x", lockPrefix, atomic.AddInt64(&nextLockSuffix, 1)), nil
158 }
159
160 func (*noLockSystem) Refresh(now time.Time, token string, duration time.Duration) (webdav.LockDetails, error) {
161         return webdav.LockDetails{}, nil
162 }
163
164 func (*noLockSystem) Unlock(now time.Time, token string) error {
165         return nil
166 }
167
168 func noop() {}
169
170 // Return a version 1 variant 4 UUID, meaning all bits are random
171 // except the ones indicating the version and variant.
172 func uuid() string {
173         var data [16]byte
174         if _, err := rand.Read(data[:]); err != nil {
175                 panic(err)
176         }
177         // variant 1: N=10xx
178         data[8] = data[8]&0x3f | 0x80
179         // version 4: M=0100
180         data[6] = data[6]&0x0f | 0x40
181         return fmt.Sprintf("%x-%x-%x-%x-%x", data[0:4], data[4:6], data[6:8], data[8:10], data[10:])
182 }