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