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