16774: text/plain response uses crlf. Tests check error codes.
[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 var notFoundMessage = "404 Not found\r\n\r\nThe requested path was not found, or you do not have permission to access it.\r"
66 var unauthorizedMessage = "401 Unauthorized\r\n\r\nA valid Arvados token must be provided to access this resource.\r"
67
68 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
69 // PDH (even if it is a PDH with "+" replaced by " " or "-");
70 // otherwise "".
71 func parseCollectionIDFromURL(s string) string {
72         if arvadosclient.UUIDMatch(s) {
73                 return s
74         }
75         if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
76                 return pdh
77         }
78         return ""
79 }
80
81 func (h *handler) setup() {
82         // Errors will be handled at the client pool.
83         arv, _ := arvados.NewClientFromConfig(h.Config.cluster)
84         h.clientPool = arvadosclient.MakeClientPoolWith(arv)
85
86         keepclient.RefreshServiceDiscoveryOnSIGHUP()
87         keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
88
89         h.healthHandler = &health.Handler{
90                 Token:  h.Config.cluster.ManagementToken,
91                 Prefix: "/_health/",
92         }
93
94         // Even though we don't accept LOCK requests, every webdav
95         // handler must have a non-nil LockSystem.
96         h.webdavLS = &noLockSystem{}
97 }
98
99 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
100         json.NewEncoder(w).Encode(struct{ Version string }{version})
101 }
102
103 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
104 // sends an HTTP header indicating success, updateOnSuccess first
105 // calls the provided update func. If the update func fails, a 500
106 // response is sent, and the status code and body sent by the handler
107 // are ignored (all response writes return the update error).
108 type updateOnSuccess struct {
109         httpserver.ResponseWriter
110         logger     logrus.FieldLogger
111         update     func() error
112         sentHeader bool
113         err        error
114 }
115
116 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
117         if !uos.sentHeader {
118                 uos.WriteHeader(http.StatusOK)
119         }
120         if uos.err != nil {
121                 return 0, uos.err
122         }
123         return uos.ResponseWriter.Write(p)
124 }
125
126 func (uos *updateOnSuccess) WriteHeader(code int) {
127         if !uos.sentHeader {
128                 uos.sentHeader = true
129                 if code >= 200 && code < 400 {
130                         if uos.err = uos.update(); uos.err != nil {
131                                 code := http.StatusInternalServerError
132                                 if err, ok := uos.err.(*arvados.TransactionError); ok {
133                                         code = err.StatusCode
134                                 }
135                                 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
136                                 http.Error(uos.ResponseWriter, uos.err.Error(), code)
137                                 return
138                         }
139                 }
140         }
141         uos.ResponseWriter.WriteHeader(code)
142 }
143
144 var (
145         corsAllowHeadersHeader = strings.Join([]string{
146                 "Authorization", "Content-Type", "Range",
147                 // WebDAV request headers:
148                 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
149         }, ", ")
150         writeMethod = map[string]bool{
151                 "COPY":      true,
152                 "DELETE":    true,
153                 "LOCK":      true,
154                 "MKCOL":     true,
155                 "MOVE":      true,
156                 "PROPPATCH": true,
157                 "PUT":       true,
158                 "RMCOL":     true,
159                 "UNLOCK":    true,
160         }
161         webdavMethod = map[string]bool{
162                 "COPY":      true,
163                 "DELETE":    true,
164                 "LOCK":      true,
165                 "MKCOL":     true,
166                 "MOVE":      true,
167                 "OPTIONS":   true,
168                 "PROPFIND":  true,
169                 "PROPPATCH": true,
170                 "PUT":       true,
171                 "RMCOL":     true,
172                 "UNLOCK":    true,
173         }
174         browserMethod = map[string]bool{
175                 "GET":  true,
176                 "HEAD": true,
177                 "POST": true,
178         }
179         // top-level dirs to serve with siteFS
180         siteFSDir = map[string]bool{
181                 "":      true, // root directory
182                 "by_id": true,
183                 "users": true,
184         }
185 )
186
187 // ServeHTTP implements http.Handler.
188 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
189         h.setupOnce.Do(h.setup)
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
197         if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
198                 h.healthHandler.ServeHTTP(w, r)
199                 return
200         }
201
202         if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
203                 if !browserMethod[method] && !webdavMethod[method] {
204                         w.WriteHeader(http.StatusMethodNotAllowed)
205                         return
206                 }
207                 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
208                 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
209                 w.Header().Set("Access-Control-Allow-Origin", "*")
210                 w.Header().Set("Access-Control-Max-Age", "86400")
211                 return
212         }
213
214         if !browserMethod[r.Method] && !webdavMethod[r.Method] {
215                 w.WriteHeader(http.StatusMethodNotAllowed)
216                 return
217         }
218
219         if r.Header.Get("Origin") != "" {
220                 // Allow simple cross-origin requests without user
221                 // credentials ("user credentials" as defined by CORS,
222                 // i.e., cookies, HTTP authentication, and client-side
223                 // SSL certificates. See
224                 // http://www.w3.org/TR/cors/#user-credentials).
225                 w.Header().Set("Access-Control-Allow-Origin", "*")
226                 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
227         }
228
229         if h.serveS3(w, r) {
230                 return
231         }
232
233         pathParts := strings.Split(r.URL.Path[1:], "/")
234
235         var stripParts int
236         var collectionID string
237         var tokens []string
238         var reqTokens []string
239         var pathToken bool
240         var attachment bool
241         var useSiteFS bool
242         credentialsOK := h.Config.cluster.Collections.TrustAllContent
243
244         if r.Host != "" && r.Host == h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host {
245                 credentialsOK = true
246                 attachment = true
247         } else if r.FormValue("disposition") == "attachment" {
248                 attachment = true
249         }
250
251         if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
252                 // http://ID.collections.example/PATH...
253                 credentialsOK = true
254         } else if r.URL.Path == "/status.json" {
255                 h.serveStatus(w, r)
256                 return
257         } else if strings.HasPrefix(r.URL.Path, "/metrics") {
258                 h.MetricsAPI.ServeHTTP(w, r)
259                 return
260         } else if siteFSDir[pathParts[0]] {
261                 useSiteFS = true
262         } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
263                 // /c=ID[/PATH...]
264                 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
265                 stripParts = 1
266         } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
267                 if len(pathParts) >= 4 && pathParts[1] == "download" {
268                         // /collections/download/ID/TOKEN/PATH...
269                         collectionID = parseCollectionIDFromURL(pathParts[2])
270                         tokens = []string{pathParts[3]}
271                         stripParts = 4
272                         pathToken = true
273                 } else {
274                         // /collections/ID/PATH...
275                         collectionID = parseCollectionIDFromURL(pathParts[1])
276                         stripParts = 2
277                         // This path is only meant to work for public
278                         // data. Tokens provided with the request are
279                         // ignored.
280                         credentialsOK = false
281                 }
282         }
283
284         if collectionID == "" && !useSiteFS {
285                 http.Error(w, notFoundMessage, http.StatusNotFound)
286                 return
287         }
288
289         forceReload := false
290         if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
291                 forceReload = true
292         }
293
294         if credentialsOK {
295                 reqTokens = auth.CredentialsFromRequest(r).Tokens
296         }
297
298         formToken := r.FormValue("api_token")
299         if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
300                 // The client provided an explicit token in the POST
301                 // body. The Origin header indicates this *might* be
302                 // an AJAX request, in which case redirect-with-cookie
303                 // won't work: we should just serve the content in the
304                 // POST response. This is safe because:
305                 //
306                 // * We're supplying an attachment, not inline
307                 //   content, so we don't need to convert the POST to
308                 //   a GET and avoid the "really resubmit form?"
309                 //   problem.
310                 //
311                 // * The token isn't embedded in the URL, so we don't
312                 //   need to worry about bookmarks and copy/paste.
313                 reqTokens = append(reqTokens, formToken)
314         } else if formToken != "" && browserMethod[r.Method] {
315                 // The client provided an explicit token in the query
316                 // string, or a form in POST body. We must put the
317                 // token in an HttpOnly cookie, and redirect to the
318                 // same URL with the query param redacted and method =
319                 // GET.
320                 h.seeOtherWithCookie(w, r, "", credentialsOK)
321                 return
322         }
323
324         if useSiteFS {
325                 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
326                 return
327         }
328
329         targetPath := pathParts[stripParts:]
330         if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
331                 // http://ID.example/t=TOKEN/PATH...
332                 // /c=ID/t=TOKEN/PATH...
333                 //
334                 // This form must only be used to pass scoped tokens
335                 // that give permission for a single collection. See
336                 // FormValue case above.
337                 tokens = []string{targetPath[0][2:]}
338                 pathToken = true
339                 targetPath = targetPath[1:]
340                 stripParts++
341         }
342
343         if tokens == nil {
344                 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
345         }
346
347         if len(targetPath) > 0 && targetPath[0] == "_" {
348                 // If a collection has a directory called "t=foo" or
349                 // "_", it can be served at
350                 // //collections.example/_/t=foo/ or
351                 // //collections.example/_/_/ respectively:
352                 // //collections.example/t=foo/ won't work because
353                 // t=foo will be interpreted as a token "foo".
354                 targetPath = targetPath[1:]
355                 stripParts++
356         }
357
358         arv := h.clientPool.Get()
359         if arv == nil {
360                 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
361                 return
362         }
363         defer h.clientPool.Put(arv)
364
365         var collection *arvados.Collection
366         tokenResult := make(map[string]int)
367         for _, arv.ApiToken = range tokens {
368                 var err error
369                 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
370                 if err == nil {
371                         // Success
372                         break
373                 }
374                 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
375                         switch srvErr.HttpStatusCode {
376                         case 404, 401:
377                                 // Token broken or insufficient to
378                                 // retrieve collection
379                                 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
380                                 continue
381                         }
382                 }
383                 // Something more serious is wrong
384                 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
385                 return
386         }
387         if collection == nil {
388                 if pathToken || !credentialsOK {
389                         // Either the URL is a "secret sharing link"
390                         // that didn't work out (and asking the client
391                         // for additional credentials would just be
392                         // confusing), or we don't even accept
393                         // credentials at this path.
394                         http.Error(w, notFoundMessage, http.StatusNotFound)
395                         return
396                 }
397                 for _, t := range reqTokens {
398                         if tokenResult[t] == 404 {
399                                 // The client provided valid token(s), but the
400                                 // collection was not found.
401                                 http.Error(w, notFoundMessage, http.StatusNotFound)
402                                 return
403                         }
404                 }
405                 // The client's token was invalid (e.g., expired), or
406                 // the client didn't even provide one.  Propagate the
407                 // 401 to encourage the client to use a [different]
408                 // token.
409                 //
410                 // TODO(TC): This response would be confusing to
411                 // someone trying (anonymously) to download public
412                 // data that has been deleted.  Allow a referrer to
413                 // provide this context somehow?
414                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
415                 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
416                 return
417         }
418
419         kc, err := keepclient.MakeKeepClient(arv)
420         if err != nil {
421                 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
422                 return
423         }
424         kc.RequestID = r.Header.Get("X-Request-Id")
425
426         var basename string
427         if len(targetPath) > 0 {
428                 basename = targetPath[len(targetPath)-1]
429         }
430         applyContentDispositionHdr(w, r, basename, attachment)
431
432         client := (&arvados.Client{
433                 APIHost:   arv.ApiServer,
434                 AuthToken: arv.ApiToken,
435                 Insecure:  arv.ApiInsecure,
436         }).WithRequestID(r.Header.Get("X-Request-Id"))
437
438         fs, err := collection.FileSystem(client, kc)
439         if err != nil {
440                 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
441                 return
442         }
443
444         writefs, writeOK := fs.(arvados.CollectionFileSystem)
445         targetIsPDH := arvadosclient.PDHMatch(collectionID)
446         if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
447                 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
448                 return
449         }
450
451         if webdavMethod[r.Method] {
452                 if writeMethod[r.Method] {
453                         // Save the collection only if/when all
454                         // webdav->filesystem operations succeed --
455                         // and send a 500 error if the modified
456                         // collection can't be saved.
457                         w = &updateOnSuccess{
458                                 ResponseWriter: w,
459                                 logger:         ctxlog.FromContext(r.Context()),
460                                 update: func() error {
461                                         return h.Config.Cache.Update(client, *collection, writefs)
462                                 }}
463                 }
464                 h := webdav.Handler{
465                         Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
466                         FileSystem: &webdavFS{
467                                 collfs:        fs,
468                                 writing:       writeMethod[r.Method],
469                                 alwaysReadEOF: r.Method == "PROPFIND",
470                         },
471                         LockSystem: h.webdavLS,
472                         Logger: func(_ *http.Request, err error) {
473                                 if err != nil {
474                                         ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
475                                 }
476                         },
477                 }
478                 h.ServeHTTP(w, r)
479                 return
480         }
481
482         openPath := "/" + strings.Join(targetPath, "/")
483         if f, err := fs.Open(openPath); os.IsNotExist(err) {
484                 // Requested non-existent path
485                 http.Error(w, notFoundMessage, http.StatusNotFound)
486         } else if err != nil {
487                 // Some other (unexpected) error
488                 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
489         } else if stat, err := f.Stat(); err != nil {
490                 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
491                 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
492         } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
493                 // If client requests ".../dirname", redirect to
494                 // ".../dirname/". This way, relative links in the
495                 // listing for "dirname" can always be "fnm", never
496                 // "dirname/fnm".
497                 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
498         } else if stat.IsDir() {
499                 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
500         } else {
501                 http.ServeContent(w, r, basename, stat.ModTime(), f)
502                 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && r.Header.Get("Range") == "" {
503                         // If we wrote fewer bytes than expected, it's
504                         // too late to change the real response code
505                         // or send an error message to the client, but
506                         // at least we can try to put some useful
507                         // debugging info in the logs.
508                         n, err := f.Read(make([]byte, 1024))
509                         ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), wrote, n, err)
510
511                 }
512         }
513 }
514
515 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
516         arv = h.clientPool.Get()
517         if arv == nil {
518                 return nil, nil, nil, nil, err
519         }
520         release = func() { h.clientPool.Put(arv) }
521         arv.ApiToken = token
522         kc, err = keepclient.MakeKeepClient(arv)
523         if err != nil {
524                 release()
525                 return
526         }
527         kc.RequestID = reqID
528         client = (&arvados.Client{
529                 APIHost:   arv.ApiServer,
530                 AuthToken: arv.ApiToken,
531                 Insecure:  arv.ApiInsecure,
532         }).WithRequestID(reqID)
533         return
534 }
535
536 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
537         if len(tokens) == 0 {
538                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
539                 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
540                 return
541         }
542         if writeMethod[r.Method] {
543                 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
544                 return
545         }
546         _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), tokens[0])
547         if err != nil {
548                 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
549                 return
550         }
551         defer release()
552
553         fs := client.SiteFileSystem(kc)
554         fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
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                                 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
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, "error getting directory listing: "+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, "error parsing template: "+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                         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)
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                         http.Error(w, "error resolving redirect target: "+err.Error(), 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 }