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