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