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