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