-
Notifications
You must be signed in to change notification settings - Fork 112
/
handler.go
286 lines (236 loc) · 7.19 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Copyright 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
package archiver
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"regexp"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/cs3org/reva/v2/internal/http/services/archiver/manager"
"github.com/cs3org/reva/v2/pkg/errtypes"
"github.com/cs3org/reva/v2/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/v2/pkg/rhttp"
"github.com/cs3org/reva/v2/pkg/rhttp/global"
"github.com/cs3org/reva/v2/pkg/sharedconf"
"github.com/cs3org/reva/v2/pkg/storage/utils/downloader"
"github.com/cs3org/reva/v2/pkg/storage/utils/walker"
"github.com/cs3org/reva/v2/pkg/storagespace"
"github.com/gdexlab/go-render/render"
ua "github.com/mileusna/useragent"
"github.com/mitchellh/mapstructure"
"github.com/rs/zerolog"
)
type svc struct {
config *Config
gtwClient gateway.GatewayAPIClient
log *zerolog.Logger
walker walker.Walker
downloader downloader.Downloader
allowedFolders []*regexp.Regexp
}
// Config holds the config options that need to be passed down to all ocdav handlers
type Config struct {
Prefix string `mapstructure:"prefix"`
GatewaySvc string `mapstructure:"gatewaysvc"`
Timeout int64 `mapstructure:"timeout"`
Insecure bool `mapstructure:"insecure"`
Name string `mapstructure:"name"`
MaxNumFiles int64 `mapstructure:"max_num_files"`
MaxSize int64 `mapstructure:"max_size"`
AllowedFolders []string `mapstructure:"allowed_folders"`
}
func init() {
global.Register("archiver", New)
}
// New creates a new archiver service
func New(conf map[string]interface{}, log *zerolog.Logger) (global.Service, error) {
c := &Config{}
err := mapstructure.Decode(conf, c)
if err != nil {
return nil, err
}
c.init()
gtw, err := pool.GetGatewayServiceClient(c.GatewaySvc)
if err != nil {
return nil, err
}
// compile all the regex for filtering folders
allowedFolderRegex := make([]*regexp.Regexp, 0, len(c.AllowedFolders))
for _, s := range c.AllowedFolders {
regex, err := regexp.Compile(s)
if err != nil {
return nil, err
}
allowedFolderRegex = append(allowedFolderRegex, regex)
}
return &svc{
config: c,
gtwClient: gtw,
downloader: downloader.NewDownloader(gtw, rhttp.Insecure(c.Insecure), rhttp.Timeout(time.Duration(c.Timeout*int64(time.Second)))),
walker: walker.NewWalker(gtw),
log: log,
allowedFolders: allowedFolderRegex,
}, nil
}
func (c *Config) init() {
if c.Prefix == "" {
c.Prefix = "download_archive"
}
if c.Name == "" {
c.Name = "download"
}
c.GatewaySvc = sharedconf.GetGatewaySVC(c.GatewaySvc)
}
func (s *svc) getResources(ctx context.Context, paths, ids []string) ([]*provider.ResourceId, error) {
if len(paths) == 0 && len(ids) == 0 {
return nil, errtypes.BadRequest("path and id lists are both empty")
}
resources := make([]*provider.ResourceId, 0, len(paths)+len(ids))
for _, id := range ids {
// id is base64 encoded and after decoding has the form <storage_id>:<resource_id>
decodedID, err := storagespace.ParseID(id)
if err != nil {
return nil, errors.New("could not unwrap given file id")
}
resources = append(resources, &decodedID)
}
for _, p := range paths {
// id is base64 encoded and after decoding has the form <storage_id>:<resource_id>
resp, err := s.gtwClient.Stat(ctx, &provider.StatRequest{
Ref: &provider.Reference{
Path: p,
},
})
switch {
case err != nil:
return nil, err
case resp.Status.Code == rpc.Code_CODE_NOT_FOUND:
return nil, errtypes.NotFound(p)
case resp.Status.Code != rpc.Code_CODE_OK:
return nil, errtypes.InternalError(fmt.Sprintf("error stating %s", p))
}
resources = append(resources, resp.Info.Id)
}
// check if all the folders are allowed to be archived
/* FIXME bring back filtering
err := s.allAllowed(resources)
if err != nil {
return nil, err
}
*/
return resources, nil
}
// return true if path match with at least with one allowed folder regex
/*
func (s *svc) isPathAllowed(path string) bool {
for _, reg := range s.allowedFolders {
if reg.MatchString(path) {
return true
}
}
return false
}
// return nil if all the paths in the slide match with at least one allowed folder regex
func (s *svc) allAllowed(paths []string) error {
if len(s.allowedFolders) == 0 {
return nil
}
for _, f := range paths {
if !s.isPathAllowed(f) {
return errtypes.BadRequest(fmt.Sprintf("resource at %s not allowed to be archived", f))
}
}
return nil
}
*/
func (s *svc) writeHTTPError(rw http.ResponseWriter, err error) {
s.log.Error().Msg(err.Error())
switch err.(type) {
case errtypes.NotFound, errtypes.PermissionDenied:
rw.WriteHeader(http.StatusNotFound)
case manager.ErrMaxSize, manager.ErrMaxFileCount:
rw.WriteHeader(http.StatusRequestEntityTooLarge)
case errtypes.BadRequest:
rw.WriteHeader(http.StatusBadRequest)
default:
rw.WriteHeader(http.StatusInternalServerError)
}
_, _ = rw.Write([]byte(err.Error()))
}
func (s *svc) Handler() http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// get the paths and/or the resources id from the query
ctx := r.Context()
v := r.URL.Query()
paths, ok := v["path"]
if !ok {
paths = []string{}
}
ids, ok := v["id"]
if !ok {
ids = []string{}
}
resources, err := s.getResources(ctx, paths, ids)
if err != nil {
s.writeHTTPError(rw, err)
return
}
arch, err := manager.NewArchiver(resources, s.walker, s.downloader, manager.Config{
MaxNumFiles: s.config.MaxNumFiles,
MaxSize: s.config.MaxSize,
})
if err != nil {
s.writeHTTPError(rw, err)
return
}
userAgent := ua.Parse(r.Header.Get("User-Agent"))
archName := s.config.Name
if userAgent.OS == ua.Windows {
archName += ".zip"
} else {
archName += ".tar"
}
s.log.Debug().Msg("Requested the following resoucres to archive: " + render.Render(resources))
rw.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", archName))
rw.Header().Set("Content-Transfer-Encoding", "binary")
// create the archive
if userAgent.OS == ua.Windows {
err = arch.CreateZip(ctx, rw)
} else {
err = arch.CreateTar(ctx, rw)
}
if err != nil {
s.writeHTTPError(rw, err)
return
}
})
}
func (s *svc) Prefix() string {
return s.config.Prefix
}
func (s *svc) Close() error {
return nil
}
func (s *svc) Unprotected() []string {
return nil
}