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