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