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