-
Notifications
You must be signed in to change notification settings - Fork 137
/
server.go
549 lines (492 loc) · 13.3 KB
/
server.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
package appfs
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"mime"
"net/http"
"os"
"path"
"strconv"
"strings"
"sync"
"time"
"github.com/andybalholm/brotli"
"github.com/cozy/cozy-stack/pkg/consts"
web_utils "github.com/cozy/cozy-stack/pkg/utils"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/labstack/echo/v4"
"github.com/ncw/swift/v2"
"github.com/spf13/afero"
)
// FileServer interface defines a way to access and serve the application's
// data files.
type FileServer interface {
Open(slug, version, shasum, file string) (io.ReadCloser, error)
FilesList(slug, version, shasum string) ([]string, error)
ServeFileContent(w http.ResponseWriter, req *http.Request,
slug, version, shasum, file string) error
ServeCodeTarball(w http.ResponseWriter, req *http.Request,
slug, version, shasum string) error
}
type swiftServer struct {
c *swift.Connection
container string
ctx context.Context
}
type aferoServer struct {
mkPath func(slug, version, shasum, file string) string
fs afero.Fs
}
type brotliReadCloser struct {
br *brotli.Reader
cl io.Closer
}
// brotli.Reader has no Close method. This little wrapper adds a method to
// close the underlying reader.
func newBrotliReadCloser(r io.ReadCloser) (io.ReadCloser, error) {
br := brotli.NewReader(r)
return brotliReadCloser{br: br, cl: r}, nil
}
func (r brotliReadCloser) Read(b []byte) (int, error) {
return r.br.Read(b)
}
func (r brotliReadCloser) Close() error {
return r.cl.Close()
}
type gzipReadCloser struct {
gr *gzip.Reader
cl io.Closer
}
// The Close method of gzip.Reader does not closes the underlying reader. This
// little wrapper does the closing.
func newGzipReadCloser(r io.ReadCloser) (io.ReadCloser, error) {
gr, err := gzip.NewReader(r)
if err != nil {
return nil, err
}
return gzipReadCloser{gr: gr, cl: r}, nil
}
func (g gzipReadCloser) Read(b []byte) (int, error) {
return g.gr.Read(b)
}
func (g gzipReadCloser) Close() error {
err1 := g.gr.Close()
err2 := g.cl.Close()
if err1 != nil {
return err1
}
if err2 != nil {
return err2
}
return nil
}
type cacheEntry struct {
content []byte
headers swift.Headers
}
var cache *lru.Cache[string, cacheEntry]
var initCacheOnce sync.Once
// NewSwiftFileServer returns provides the apps.FileServer implementation
// using the swift backend as file server.
func NewSwiftFileServer(conn *swift.Connection, appsType consts.AppType) FileServer {
initCacheOnce.Do(func() {
c, err := lru.New[string, cacheEntry](128)
if err != nil {
panic(err)
}
cache = c
})
return &swiftServer{
c: conn,
container: containerName(appsType),
ctx: context.Background(),
}
}
func (s *swiftServer) openWithCache(objName string) (io.ReadCloser, swift.Headers, error) {
entry, ok := cache.Get(objName)
if !ok {
f, h, err := s.c.ObjectOpen(s.ctx, s.container, objName, false, nil)
if err != nil {
return f, h, err
}
entry.headers = h
entry.content, err = io.ReadAll(f)
if err != nil {
return nil, h, err
}
cache.Add(objName, entry)
}
f := io.NopCloser(bytes.NewReader(entry.content))
return f, entry.headers, nil
}
func (s *swiftServer) Open(slug, version, shasum, file string) (io.ReadCloser, error) {
objName := s.makeObjectName(slug, version, shasum, file)
f, h, err := s.openWithCache(objName)
if err != nil {
return nil, wrapSwiftErr(err)
}
o := h.ObjectMetadata()
contentEncoding := o["content-encoding"]
if contentEncoding == "br" {
return newBrotliReadCloser(f)
} else if contentEncoding == "gzip" {
return newGzipReadCloser(f)
}
return f, nil
}
func (s *swiftServer) ServeFileContent(w http.ResponseWriter, req *http.Request, slug, version, shasum, file string) error {
objName := s.makeObjectName(slug, version, shasum, file)
f, h, err := s.openWithCache(objName)
if err != nil {
return wrapSwiftErr(err)
}
defer f.Close()
if checkETag := req.Header.Get("Cache-Control") == ""; checkETag {
etag := fmt.Sprintf(`"%s"`, h["Etag"][:10])
if web_utils.CheckPreconditions(w, req, etag) {
return nil
}
w.Header().Set("Etag", etag)
}
var r io.Reader = f
contentLength := h["Content-Length"]
contentType := h["Content-Type"]
o := h.ObjectMetadata()
contentEncoding := o["content-encoding"]
if contentEncoding == "br" {
if acceptBrotliEncoding(req) {
w.Header().Set(echo.HeaderContentEncoding, "br")
} else {
contentLength = o["original-content-length"]
r = brotli.NewReader(f)
}
} else if contentEncoding == "gzip" {
if acceptGzipEncoding(req) {
w.Header().Set(echo.HeaderContentEncoding, "gzip")
} else {
contentLength = o["original-content-length"]
var gr *gzip.Reader
gr, err = gzip.NewReader(f)
if err != nil {
return err
}
defer gr.Close()
r = gr
}
}
ext := path.Ext(file)
if contentType == "" {
contentType = mime.TypeByExtension(ext)
}
if contentType == "text/xml" && ext == ".svg" {
// override for files with text/xml content because of leading <?xml tag
contentType = "image/svg+xml"
}
size, _ := strconv.ParseInt(contentLength, 10, 64)
return serveContent(w, req, contentType, size, r)
}
func (s *swiftServer) ServeCodeTarball(w http.ResponseWriter, req *http.Request, slug, version, shasum string) error {
objName := path.Join(slug, version)
if shasum != "" {
objName += "-" + shasum
}
objName += ".tgz"
f, h, err := s.c.ObjectOpen(s.ctx, s.container, objName, false, nil)
if err == nil {
defer f.Close()
contentLength := h["Content-Length"]
contentType := h["Content-Type"]
size, _ := strconv.ParseInt(contentLength, 10, 64)
return serveContent(w, req, contentType, size, f)
}
buf, err := prepareTarball(s, slug, version, shasum)
if err != nil {
return err
}
contentType := mime.TypeByExtension(".gz")
file, err := s.c.ObjectCreate(s.ctx, s.container, objName, true, "", contentType, nil)
if err == nil {
_, _ = io.Copy(file, buf)
_ = file.Close()
}
return serveContent(w, req, contentType, int64(buf.Len()), buf)
}
func (s *swiftServer) makeObjectName(slug, version, shasum, file string) string {
basepath := path.Join(slug, version)
if shasum != "" {
basepath += "-" + shasum
}
return path.Join(basepath, file)
}
func (s *swiftServer) FilesList(slug, version, shasum string) ([]string, error) {
prefix := s.makeObjectName(slug, version, shasum, "") + "/"
names, err := s.c.ObjectNamesAll(s.ctx, s.container, &swift.ObjectsOpts{
Limit: 10_000,
Prefix: prefix,
})
if err != nil {
return nil, err
}
filtered := names[:0]
for _, n := range names {
n = strings.TrimPrefix(n, prefix)
if n != "" {
filtered = append(filtered, n)
}
}
return filtered, nil
}
// NewAferoFileServer returns a simple wrapper of the afero.Fs interface that
// provides the apps.FileServer interface.
//
// You can provide a makePath method to define how the file name should be
// created from the application's slug, version and file name. If not provided,
// the standard VFS concatenation (starting with vfs.WebappsDirName) is used.
func NewAferoFileServer(fs afero.Fs, makePath func(slug, version, shasum, file string) string) FileServer {
if makePath == nil {
makePath = defaultMakePath
}
return &aferoServer{
mkPath: makePath,
fs: fs,
}
}
const (
uncompressed = iota + 1
gzipped
brotlied
)
// openFile opens the give filepath. By default, it is a file compressed with
// brotli (.br), but it can be a file compressed with gzip (.gz, for apps that
// were installed before brotli compression was enabled), or uncompressed (for
// app development with cozy-stack serve --appdir).
func (s *aferoServer) openFile(filepath string) (afero.File, int, error) {
compression := brotlied
f, err := s.fs.Open(filepath + ".br")
if os.IsNotExist(err) {
compression = gzipped
f, err = s.fs.Open(filepath + ".gz")
}
if os.IsNotExist(err) {
compression = uncompressed
f, err = s.fs.Open(filepath)
}
return f, compression, err
}
func (s *aferoServer) Open(slug, version, shasum, file string) (io.ReadCloser, error) {
filepath := s.mkPath(slug, version, shasum, file)
f, compression, err := s.openFile(filepath)
if err != nil {
return nil, err
}
switch compression {
case uncompressed:
return f, nil
case gzipped:
return newGzipReadCloser(f)
case brotlied:
return newBrotliReadCloser(f)
default:
panic(fmt.Errorf("Unknown compression type: %v", compression))
}
}
func (s *aferoServer) ServeFileContent(w http.ResponseWriter, req *http.Request, slug, version, shasum, file string) error {
filepath := s.mkPath(slug, version, shasum, file)
return s.serveFileContent(w, req, filepath)
}
func (s *aferoServer) serveFileContent(w http.ResponseWriter, req *http.Request, filepath string) error {
f, compression, err := s.openFile(filepath)
if err != nil {
return err
}
defer f.Close()
var content io.Reader
var size int64
if checkEtag := req.Header.Get("Cache-Control") == ""; checkEtag {
var b []byte
h := md5.New()
b, err = io.ReadAll(f)
if err != nil {
return err
}
etag := fmt.Sprintf(`"%s"`, hex.EncodeToString(h.Sum(nil)))
if web_utils.CheckPreconditions(w, req, etag) {
return nil
}
w.Header().Set("Etag", etag)
size = int64(len(b))
content = bytes.NewReader(b)
} else {
size, err = f.Seek(0, io.SeekEnd)
if err != nil {
return err
}
_, err = f.Seek(0, io.SeekStart)
if err != nil {
return err
}
content = f
}
switch compression {
case uncompressed:
// Nothing to do
case gzipped:
if acceptGzipEncoding(req) {
w.Header().Set(echo.HeaderContentEncoding, "gzip")
} else {
var gr *gzip.Reader
var b []byte
gr, err = gzip.NewReader(content)
if err != nil {
return err
}
defer gr.Close()
b, err = io.ReadAll(gr)
if err != nil {
return err
}
size = int64(len(b))
content = bytes.NewReader(b)
}
case brotlied:
if acceptBrotliEncoding(req) {
w.Header().Set(echo.HeaderContentEncoding, "br")
} else {
var b []byte
br := brotli.NewReader(content)
b, err = io.ReadAll(br)
if err != nil {
return err
}
size = int64(len(b))
content = bytes.NewReader(b)
}
default:
panic(fmt.Errorf("Unknown compression type: %v", compression))
}
contentType := mime.TypeByExtension(path.Ext(filepath))
return serveContent(w, req, contentType, size, content)
}
func (s *aferoServer) ServeCodeTarball(w http.ResponseWriter, req *http.Request, slug, version, shasum string) error {
buf, err := prepareTarball(s, slug, version, shasum)
if err != nil {
return err
}
contentType := mime.TypeByExtension(".gz")
return serveContent(w, req, contentType, int64(buf.Len()), buf)
}
func (s *aferoServer) FilesList(slug, version, shasum string) ([]string, error) {
var names []string
rootPath := s.mkPath(slug, version, shasum, "")
err := afero.Walk(s.fs, rootPath, func(path string, infos os.FileInfo, err error) error {
if err != nil {
return err
}
if !infos.IsDir() {
name := strings.TrimPrefix(path, rootPath)
name = strings.TrimSuffix(name, ".gz")
name = strings.TrimSuffix(name, ".br")
names = append(names, name)
}
return nil
})
return names, err
}
func defaultMakePath(slug, version, shasum, file string) string {
basepath := path.Join("/", slug, version)
if shasum != "" {
basepath += "-" + shasum
}
filepath := path.Join("/", file)
return path.Join(basepath, filepath)
}
func acceptBrotliEncoding(req *http.Request) bool {
return strings.Contains(req.Header.Get(echo.HeaderAcceptEncoding), "br")
}
func acceptGzipEncoding(req *http.Request) bool {
return strings.Contains(req.Header.Get(echo.HeaderAcceptEncoding), "gzip")
}
func containerName(appsType consts.AppType) string {
switch appsType {
case consts.WebappType:
return "apps-web"
case consts.KonnectorType:
return "apps-konnectors"
}
panic("Unknown AppType")
}
func wrapSwiftErr(err error) error {
if errors.Is(err, swift.ObjectNotFound) || errors.Is(err, swift.ContainerNotFound) {
return os.ErrNotExist
}
return err
}
func prepareTarball(s FileServer, slug, version, shasum string) (*bytes.Buffer, error) {
filenames, err := s.FilesList(slug, version, shasum)
if err != nil {
return nil, err
}
buf := &bytes.Buffer{}
gw := gzip.NewWriter(buf)
tw := tar.NewWriter(gw)
now := time.Now()
for _, filename := range filenames {
f, err := s.Open(slug, version, shasum, filename)
if err != nil {
return nil, err
}
content, err := io.ReadAll(f)
errc := f.Close()
if err != nil {
return nil, err
}
if errc != nil {
return nil, errc
}
hdr := &tar.Header{
Name: filename,
Mode: 0640,
Size: int64(len(content)),
Typeflag: tar.TypeReg,
ModTime: now,
}
if err := tw.WriteHeader(hdr); err != nil {
return nil, err
}
if _, err := tw.Write(content); err != nil {
return nil, err
}
}
if err := tw.Close(); err != nil {
return nil, err
}
if err := gw.Close(); err != nil {
return nil, err
}
return buf, nil
}
// serveContent replies to the request using the content in the provided
// reader. The Content-Length and Content-Type headers are added with the
// provided values.
func serveContent(w http.ResponseWriter, r *http.Request, contentType string, size int64, content io.Reader) error {
var err error
h := w.Header()
if size > 0 {
h.Set("Content-Length", strconv.FormatInt(size, 10))
}
if contentType != "" {
h.Set("Content-Type", contentType)
}
w.WriteHeader(http.StatusOK)
if r.Method != "HEAD" {
_, err = io.Copy(w, content)
}
return err
}