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