Merge branch '16850-s3-keycount'
[arvados.git] / services / keep-web / handler.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         "encoding/json"
9         "html"
10         "html/template"
11         "io"
12         "net/http"
13         "net/url"
14         "os"
15         "path/filepath"
16         "sort"
17         "strconv"
18         "strings"
19         "sync"
20
21         "git.arvados.org/arvados.git/sdk/go/arvados"
22         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
23         "git.arvados.org/arvados.git/sdk/go/auth"
24         "git.arvados.org/arvados.git/sdk/go/ctxlog"
25         "git.arvados.org/arvados.git/sdk/go/health"
26         "git.arvados.org/arvados.git/sdk/go/httpserver"
27         "git.arvados.org/arvados.git/sdk/go/keepclient"
28         "github.com/sirupsen/logrus"
29         "golang.org/x/net/webdav"
30 )
31
32 type handler struct {
33         Config        *Config
34         MetricsAPI    http.Handler
35         clientPool    *arvadosclient.ClientPool
36         setupOnce     sync.Once
37         healthHandler http.Handler
38         webdavLS      webdav.LockSystem
39 }
40
41 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
42 // a UUID or URL-encoded PDH; otherwise "".
43 func parseCollectionIDFromDNSName(s string) string {
44         // Strip domain.
45         if i := strings.IndexRune(s, '.'); i >= 0 {
46                 s = s[:i]
47         }
48         // Names like {uuid}--collections.example.com serve the same
49         // purpose as {uuid}.collections.example.com but can reduce
50         // cost/effort of using [additional] wildcard certificates.
51         if i := strings.Index(s, "--"); i >= 0 {
52                 s = s[:i]
53         }
54         if arvadosclient.UUIDMatch(s) {
55                 return s
56         }
57         if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
58                 return pdh
59         }
60         return ""
61 }
62
63 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
64
65 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
66 // PDH (even if it is a PDH with "+" replaced by " " or "-");
67 // otherwise "".
68 func parseCollectionIDFromURL(s string) string {
69         if arvadosclient.UUIDMatch(s) {
70                 return s
71         }
72         if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
73                 return pdh
74         }
75         return ""
76 }
77
78 func (h *handler) setup() {
79         // Errors will be handled at the client pool.
80         arv, _ := arvados.NewClientFromConfig(h.Config.cluster)
81         h.clientPool = arvadosclient.MakeClientPoolWith(arv)
82
83         keepclient.RefreshServiceDiscoveryOnSIGHUP()
84         keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
85
86         h.healthHandler = &health.Handler{
87                 Token:  h.Config.cluster.ManagementToken,
88                 Prefix: "/_health/",
89         }
90
91         // Even though we don't accept LOCK requests, every webdav
92         // handler must have a non-nil LockSystem.
93         h.webdavLS = &noLockSystem{}
94 }
95
96 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
97         json.NewEncoder(w).Encode(struct{ Version string }{version})
98 }
99
100 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
101 // sends an HTTP header indicating success, updateOnSuccess first
102 // calls the provided update func. If the update func fails, a 500
103 // response is sent, and the status code and body sent by the handler
104 // are ignored (all response writes return the update error).
105 type updateOnSuccess struct {
106         httpserver.ResponseWriter
107         logger     logrus.FieldLogger
108         update     func() error
109         sentHeader bool
110         err        error
111 }
112
113 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
114         if !uos.sentHeader {
115                 uos.WriteHeader(http.StatusOK)
116         }
117         if uos.err != nil {
118                 return 0, uos.err
119         }
120         return uos.ResponseWriter.Write(p)
121 }
122
123 func (uos *updateOnSuccess) WriteHeader(code int) {
124         if !uos.sentHeader {
125                 uos.sentHeader = true
126                 if code >= 200 && code < 400 {
127                         if uos.err = uos.update(); uos.err != nil {
128                                 code := http.StatusInternalServerError
129                                 if err, ok := uos.err.(*arvados.TransactionError); ok {
130                                         code = err.StatusCode
131                                 }
132                                 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
133                                 http.Error(uos.ResponseWriter, uos.err.Error(), code)
134                                 return
135                         }
136                 }
137         }
138         uos.ResponseWriter.WriteHeader(code)
139 }
140
141 var (
142         corsAllowHeadersHeader = strings.Join([]string{
143                 "Authorization", "Content-Type", "Range",
144                 // WebDAV request headers:
145                 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
146         }, ", ")
147         writeMethod = map[string]bool{
148                 "COPY":      true,
149                 "DELETE":    true,
150                 "LOCK":      true,
151                 "MKCOL":     true,
152                 "MOVE":      true,
153                 "PROPPATCH": true,
154                 "PUT":       true,
155                 "RMCOL":     true,
156                 "UNLOCK":    true,
157         }
158         webdavMethod = map[string]bool{
159                 "COPY":      true,
160                 "DELETE":    true,
161                 "LOCK":      true,
162                 "MKCOL":     true,
163                 "MOVE":      true,
164                 "OPTIONS":   true,
165                 "PROPFIND":  true,
166                 "PROPPATCH": true,
167                 "PUT":       true,
168                 "RMCOL":     true,
169                 "UNLOCK":    true,
170         }
171         browserMethod = map[string]bool{
172                 "GET":  true,
173                 "HEAD": true,
174                 "POST": true,
175         }
176         // top-level dirs to serve with siteFS
177         siteFSDir = map[string]bool{
178                 "":      true, // root directory
179                 "by_id": true,
180                 "users": true,
181         }
182 )
183
184 // ServeHTTP implements http.Handler.
185 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
186         h.setupOnce.Do(h.setup)
187
188         if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
189                 r.URL.Scheme = xfp
190         }
191
192         w := httpserver.WrapResponseWriter(wOrig)
193
194         if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
195                 h.healthHandler.ServeHTTP(w, r)
196                 return
197         }
198
199         if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
200                 if !browserMethod[method] && !webdavMethod[method] {
201                         w.WriteHeader(http.StatusMethodNotAllowed)
202                         return
203                 }
204                 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
205                 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
206                 w.Header().Set("Access-Control-Allow-Origin", "*")
207                 w.Header().Set("Access-Control-Max-Age", "86400")
208                 return
209         }
210
211         if !browserMethod[r.Method] && !webdavMethod[r.Method] {
212                 w.WriteHeader(http.StatusMethodNotAllowed)
213                 return
214         }
215
216         if r.Header.Get("Origin") != "" {
217                 // Allow simple cross-origin requests without user
218                 // credentials ("user credentials" as defined by CORS,
219                 // i.e., cookies, HTTP authentication, and client-side
220                 // SSL certificates. See
221                 // http://www.w3.org/TR/cors/#user-credentials).
222                 w.Header().Set("Access-Control-Allow-Origin", "*")
223                 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
224         }
225
226         if h.serveS3(w, r) {
227                 return
228         }
229
230         pathParts := strings.Split(r.URL.Path[1:], "/")
231
232         var stripParts int
233         var collectionID string
234         var tokens []string
235         var reqTokens []string
236         var pathToken bool
237         var attachment bool
238         var useSiteFS bool
239         credentialsOK := h.Config.cluster.Collections.TrustAllContent
240
241         if r.Host != "" && r.Host == h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host {
242                 credentialsOK = true
243                 attachment = true
244         } else if r.FormValue("disposition") == "attachment" {
245                 attachment = true
246         }
247
248         if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
249                 // http://ID.collections.example/PATH...
250                 credentialsOK = true
251         } else if r.URL.Path == "/status.json" {
252                 h.serveStatus(w, r)
253                 return
254         } else if strings.HasPrefix(r.URL.Path, "/metrics") {
255                 h.MetricsAPI.ServeHTTP(w, r)
256                 return
257         } else if siteFSDir[pathParts[0]] {
258                 useSiteFS = true
259         } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
260                 // /c=ID[/PATH...]
261                 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
262                 stripParts = 1
263         } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
264                 if len(pathParts) >= 4 && pathParts[1] == "download" {
265                         // /collections/download/ID/TOKEN/PATH...
266                         collectionID = parseCollectionIDFromURL(pathParts[2])
267                         tokens = []string{pathParts[3]}
268                         stripParts = 4
269                         pathToken = true
270                 } else {
271                         // /collections/ID/PATH...
272                         collectionID = parseCollectionIDFromURL(pathParts[1])
273                         stripParts = 2
274                         // This path is only meant to work for public
275                         // data. Tokens provided with the request are
276                         // ignored.
277                         credentialsOK = false
278                 }
279         }
280
281         if collectionID == "" && !useSiteFS {
282                 w.WriteHeader(http.StatusNotFound)
283                 return
284         }
285
286         forceReload := false
287         if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
288                 forceReload = true
289         }
290
291         if credentialsOK {
292                 reqTokens = auth.CredentialsFromRequest(r).Tokens
293         }
294
295         formToken := r.FormValue("api_token")
296         if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
297                 // The client provided an explicit token in the POST
298                 // body. The Origin header indicates this *might* be
299                 // an AJAX request, in which case redirect-with-cookie
300                 // won't work: we should just serve the content in the
301                 // POST response. This is safe because:
302                 //
303                 // * We're supplying an attachment, not inline
304                 //   content, so we don't need to convert the POST to
305                 //   a GET and avoid the "really resubmit form?"
306                 //   problem.
307                 //
308                 // * The token isn't embedded in the URL, so we don't
309                 //   need to worry about bookmarks and copy/paste.
310                 reqTokens = append(reqTokens, formToken)
311         } else if formToken != "" && browserMethod[r.Method] {
312                 // The client provided an explicit token in the query
313                 // string, or a form in POST body. We must put the
314                 // token in an HttpOnly cookie, and redirect to the
315                 // same URL with the query param redacted and method =
316                 // GET.
317                 h.seeOtherWithCookie(w, r, "", credentialsOK)
318                 return
319         }
320
321         if useSiteFS {
322                 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
323                 return
324         }
325
326         targetPath := pathParts[stripParts:]
327         if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
328                 // http://ID.example/t=TOKEN/PATH...
329                 // /c=ID/t=TOKEN/PATH...
330                 //
331                 // This form must only be used to pass scoped tokens
332                 // that give permission for a single collection. See
333                 // FormValue case above.
334                 tokens = []string{targetPath[0][2:]}
335                 pathToken = true
336                 targetPath = targetPath[1:]
337                 stripParts++
338         }
339
340         if tokens == nil {
341                 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
342         }
343
344         if len(targetPath) > 0 && targetPath[0] == "_" {
345                 // If a collection has a directory called "t=foo" or
346                 // "_", it can be served at
347                 // //collections.example/_/t=foo/ or
348                 // //collections.example/_/_/ respectively:
349                 // //collections.example/t=foo/ won't work because
350                 // t=foo will be interpreted as a token "foo".
351                 targetPath = targetPath[1:]
352                 stripParts++
353         }
354
355         arv := h.clientPool.Get()
356         if arv == nil {
357                 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
358                 return
359         }
360         defer h.clientPool.Put(arv)
361
362         var collection *arvados.Collection
363         tokenResult := make(map[string]int)
364         for _, arv.ApiToken = range tokens {
365                 var err error
366                 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
367                 if err == nil {
368                         // Success
369                         break
370                 }
371                 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
372                         switch srvErr.HttpStatusCode {
373                         case 404, 401:
374                                 // Token broken or insufficient to
375                                 // retrieve collection
376                                 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
377                                 continue
378                         }
379                 }
380                 // Something more serious is wrong
381                 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
382                 return
383         }
384         if collection == nil {
385                 if pathToken || !credentialsOK {
386                         // Either the URL is a "secret sharing link"
387                         // that didn't work out (and asking the client
388                         // for additional credentials would just be
389                         // confusing), or we don't even accept
390                         // credentials at this path.
391                         w.WriteHeader(http.StatusNotFound)
392                         return
393                 }
394                 for _, t := range reqTokens {
395                         if tokenResult[t] == 404 {
396                                 // The client provided valid token(s), but the
397                                 // collection was not found.
398                                 w.WriteHeader(http.StatusNotFound)
399                                 return
400                         }
401                 }
402                 // The client's token was invalid (e.g., expired), or
403                 // the client didn't even provide one.  Propagate the
404                 // 401 to encourage the client to use a [different]
405                 // token.
406                 //
407                 // TODO(TC): This response would be confusing to
408                 // someone trying (anonymously) to download public
409                 // data that has been deleted.  Allow a referrer to
410                 // provide this context somehow?
411                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
412                 w.WriteHeader(http.StatusUnauthorized)
413                 return
414         }
415
416         kc, err := keepclient.MakeKeepClient(arv)
417         if err != nil {
418                 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
419                 return
420         }
421         kc.RequestID = r.Header.Get("X-Request-Id")
422
423         var basename string
424         if len(targetPath) > 0 {
425                 basename = targetPath[len(targetPath)-1]
426         }
427         applyContentDispositionHdr(w, r, basename, attachment)
428
429         client := (&arvados.Client{
430                 APIHost:   arv.ApiServer,
431                 AuthToken: arv.ApiToken,
432                 Insecure:  arv.ApiInsecure,
433         }).WithRequestID(r.Header.Get("X-Request-Id"))
434
435         fs, err := collection.FileSystem(client, kc)
436         if err != nil {
437                 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
438                 return
439         }
440
441         writefs, writeOK := fs.(arvados.CollectionFileSystem)
442         targetIsPDH := arvadosclient.PDHMatch(collectionID)
443         if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
444                 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
445                 return
446         }
447
448         if webdavMethod[r.Method] {
449                 if writeMethod[r.Method] {
450                         // Save the collection only if/when all
451                         // webdav->filesystem operations succeed --
452                         // and send a 500 error if the modified
453                         // collection can't be saved.
454                         w = &updateOnSuccess{
455                                 ResponseWriter: w,
456                                 logger:         ctxlog.FromContext(r.Context()),
457                                 update: func() error {
458                                         return h.Config.Cache.Update(client, *collection, writefs)
459                                 }}
460                 }
461                 h := webdav.Handler{
462                         Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
463                         FileSystem: &webdavFS{
464                                 collfs:        fs,
465                                 writing:       writeMethod[r.Method],
466                                 alwaysReadEOF: r.Method == "PROPFIND",
467                         },
468                         LockSystem: h.webdavLS,
469                         Logger: func(_ *http.Request, err error) {
470                                 if err != nil {
471                                         ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
472                                 }
473                         },
474                 }
475                 h.ServeHTTP(w, r)
476                 return
477         }
478
479         openPath := "/" + strings.Join(targetPath, "/")
480         if f, err := fs.Open(openPath); os.IsNotExist(err) {
481                 // Requested non-existent path
482                 w.WriteHeader(http.StatusNotFound)
483         } else if err != nil {
484                 // Some other (unexpected) error
485                 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
486         } else if stat, err := f.Stat(); err != nil {
487                 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
488                 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
489         } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
490                 // If client requests ".../dirname", redirect to
491                 // ".../dirname/". This way, relative links in the
492                 // listing for "dirname" can always be "fnm", never
493                 // "dirname/fnm".
494                 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
495         } else if stat.IsDir() {
496                 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
497         } else {
498                 http.ServeContent(w, r, basename, stat.ModTime(), f)
499                 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && r.Header.Get("Range") == "" {
500                         // If we wrote fewer bytes than expected, it's
501                         // too late to change the real response code
502                         // or send an error message to the client, but
503                         // at least we can try to put some useful
504                         // debugging info in the logs.
505                         n, err := f.Read(make([]byte, 1024))
506                         ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), wrote, n, err)
507
508                 }
509         }
510 }
511
512 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
513         arv = h.clientPool.Get()
514         if arv == nil {
515                 return nil, nil, nil, nil, err
516         }
517         release = func() { h.clientPool.Put(arv) }
518         arv.ApiToken = token
519         kc, err = keepclient.MakeKeepClient(arv)
520         if err != nil {
521                 release()
522                 return
523         }
524         kc.RequestID = reqID
525         client = (&arvados.Client{
526                 APIHost:   arv.ApiServer,
527                 AuthToken: arv.ApiToken,
528                 Insecure:  arv.ApiInsecure,
529         }).WithRequestID(reqID)
530         return
531 }
532
533 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
534         if len(tokens) == 0 {
535                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
536                 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
537                 return
538         }
539         if writeMethod[r.Method] {
540                 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
541                 return
542         }
543         _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), tokens[0])
544         if err != nil {
545                 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
546                 return
547         }
548         defer release()
549
550         fs := client.SiteFileSystem(kc)
551         fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
552         f, err := fs.Open(r.URL.Path)
553         if os.IsNotExist(err) {
554                 http.Error(w, err.Error(), http.StatusNotFound)
555                 return
556         } else if err != nil {
557                 http.Error(w, err.Error(), http.StatusInternalServerError)
558                 return
559         }
560         defer f.Close()
561         if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
562                 if !strings.HasSuffix(r.URL.Path, "/") {
563                         h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
564                 } else {
565                         h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
566                 }
567                 return
568         }
569         if r.Method == "GET" {
570                 _, basename := filepath.Split(r.URL.Path)
571                 applyContentDispositionHdr(w, r, basename, attachment)
572         }
573         wh := webdav.Handler{
574                 Prefix: "/",
575                 FileSystem: &webdavFS{
576                         collfs:        fs,
577                         writing:       writeMethod[r.Method],
578                         alwaysReadEOF: r.Method == "PROPFIND",
579                 },
580                 LockSystem: h.webdavLS,
581                 Logger: func(_ *http.Request, err error) {
582                         if err != nil {
583                                 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
584                         }
585                 },
586         }
587         wh.ServeHTTP(w, r)
588 }
589
590 var dirListingTemplate = `<!DOCTYPE HTML>
591 <HTML><HEAD>
592   <META name="robots" content="NOINDEX">
593   <TITLE>{{ .CollectionName }}</TITLE>
594   <STYLE type="text/css">
595     body {
596       margin: 1.5em;
597     }
598     pre {
599       background-color: #D9EDF7;
600       border-radius: .25em;
601       padding: .75em;
602       overflow: auto;
603     }
604     .footer p {
605       font-size: 82%;
606     }
607     ul {
608       padding: 0;
609     }
610     ul li {
611       font-family: monospace;
612       list-style: none;
613     }
614   </STYLE>
615 </HEAD>
616 <BODY>
617
618 <H1>{{ .CollectionName }}</H1>
619
620 <P>This collection of data files is being shared with you through
621 Arvados.  You can download individual files listed below.  To download
622 the entire directory tree with wget, try:</P>
623
624 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
625
626 <H2>File Listing</H2>
627
628 {{if .Files}}
629 <UL>
630 {{range .Files}}
631 {{if .IsDir }}
632   <LI>{{" " | printf "%15s  " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
633 {{else}}
634   <LI>{{.Size | printf "%15d  " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
635 {{end}}
636 {{end}}
637 </UL>
638 {{else}}
639 <P>(No files; this collection is empty.)</P>
640 {{end}}
641
642 <HR noshade>
643 <DIV class="footer">
644   <P>
645     About Arvados:
646     Arvados is a free and open source software bioinformatics platform.
647     To learn more, visit arvados.org.
648     Arvados is not responsible for the files listed on this page.
649   </P>
650 </DIV>
651
652 </BODY>
653 `
654
655 type fileListEnt struct {
656         Name  string
657         Size  int64
658         IsDir bool
659 }
660
661 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
662         var files []fileListEnt
663         var walk func(string) error
664         if !strings.HasSuffix(base, "/") {
665                 base = base + "/"
666         }
667         walk = func(path string) error {
668                 dirname := base + path
669                 if dirname != "/" {
670                         dirname = strings.TrimSuffix(dirname, "/")
671                 }
672                 d, err := fs.Open(dirname)
673                 if err != nil {
674                         return err
675                 }
676                 ents, err := d.Readdir(-1)
677                 if err != nil {
678                         return err
679                 }
680                 for _, ent := range ents {
681                         if recurse && ent.IsDir() {
682                                 err = walk(path + ent.Name() + "/")
683                                 if err != nil {
684                                         return err
685                                 }
686                         } else {
687                                 files = append(files, fileListEnt{
688                                         Name:  path + ent.Name(),
689                                         Size:  ent.Size(),
690                                         IsDir: ent.IsDir(),
691                                 })
692                         }
693                 }
694                 return nil
695         }
696         if err := walk(""); err != nil {
697                 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
698                 return
699         }
700
701         funcs := template.FuncMap{
702                 "nbsp": func(s string) template.HTML {
703                         return template.HTML(strings.Replace(s, " ", "&nbsp;", -1))
704                 },
705         }
706         tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
707         if err != nil {
708                 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
709                 return
710         }
711         sort.Slice(files, func(i, j int) bool {
712                 return files[i].Name < files[j].Name
713         })
714         w.WriteHeader(http.StatusOK)
715         tmpl.Execute(w, map[string]interface{}{
716                 "CollectionName": collectionName,
717                 "Files":          files,
718                 "Request":        r,
719                 "StripParts":     strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
720         })
721 }
722
723 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
724         disposition := "inline"
725         if isAttachment {
726                 disposition = "attachment"
727         }
728         if strings.ContainsRune(r.RequestURI, '?') {
729                 // Help the UA realize that the filename is just
730                 // "filename.txt", not
731                 // "filename.txt?disposition=attachment".
732                 //
733                 // TODO(TC): Follow advice at RFC 6266 appendix D
734                 disposition += "; filename=" + strconv.QuoteToASCII(filename)
735         }
736         if disposition != "inline" {
737                 w.Header().Set("Content-Disposition", disposition)
738         }
739 }
740
741 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
742         if formToken := r.FormValue("api_token"); formToken != "" {
743                 if !credentialsOK {
744                         // It is not safe to copy the provided token
745                         // into a cookie unless the current vhost
746                         // (origin) serves only a single collection or
747                         // we are in TrustAllContent mode.
748                         http.Error(w, "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)", http.StatusBadRequest)
749                         return
750                 }
751
752                 // The HttpOnly flag is necessary to prevent
753                 // JavaScript code (included in, or loaded by, a page
754                 // in the collection being served) from employing the
755                 // user's token beyond reading other files in the same
756                 // domain, i.e., same collection.
757                 //
758                 // The 303 redirect is necessary in the case of a GET
759                 // request to avoid exposing the token in the Location
760                 // bar, and in the case of a POST request to avoid
761                 // raising warnings when the user refreshes the
762                 // resulting page.
763                 http.SetCookie(w, &http.Cookie{
764                         Name:     "arvados_api_token",
765                         Value:    auth.EncodeTokenCookie([]byte(formToken)),
766                         Path:     "/",
767                         HttpOnly: true,
768                 })
769         }
770
771         // Propagate query parameters (except api_token) from
772         // the original request.
773         redirQuery := r.URL.Query()
774         redirQuery.Del("api_token")
775
776         u := r.URL
777         if location != "" {
778                 newu, err := u.Parse(location)
779                 if err != nil {
780                         http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
781                         return
782                 }
783                 u = newu
784         }
785         redir := (&url.URL{
786                 Scheme:   r.URL.Scheme,
787                 Host:     r.Host,
788                 Path:     u.Path,
789                 RawQuery: redirQuery.Encode(),
790         }).String()
791
792         w.Header().Add("Location", redir)
793         w.WriteHeader(http.StatusSeeOther)
794         io.WriteString(w, `<A href="`)
795         io.WriteString(w, html.EscapeString(redir))
796         io.WriteString(w, `">Continue</A>`)
797 }