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