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