1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/lib/cmd"
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25 "git.arvados.org/arvados.git/sdk/go/auth"
26 "git.arvados.org/arvados.git/sdk/go/ctxlog"
27 "git.arvados.org/arvados.git/sdk/go/httpserver"
28 "git.arvados.org/arvados.git/sdk/go/keepclient"
29 "github.com/sirupsen/logrus"
30 "golang.org/x/net/webdav"
35 Cluster *arvados.Cluster
37 webdavLS webdav.LockSystem
40 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
42 var notFoundMessage = "Not Found"
43 var unauthorizedMessage = "401 Unauthorized\r\n\r\nA valid Arvados token must be provided to access this resource.\r\n"
45 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
46 // PDH (even if it is a PDH with "+" replaced by " " or "-");
48 func parseCollectionIDFromURL(s string) string {
49 if arvadosclient.UUIDMatch(s) {
52 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
58 func (h *handler) setup() {
59 keepclient.DefaultBlockCache.MaxBlocks = h.Cluster.Collections.WebDAVCache.MaxBlockEntries
61 // Even though we don't accept LOCK requests, every webdav
62 // handler must have a non-nil LockSystem.
63 h.webdavLS = &noLockSystem{}
66 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
67 json.NewEncoder(w).Encode(struct{ Version string }{cmd.Version.String()})
70 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
71 // sends an HTTP header indicating success, updateOnSuccess first
72 // calls the provided update func. If the update func fails, an error
73 // response is sent (using the error's HTTP status or 500 if none),
74 // and the status code and body sent by the handler are ignored (all
75 // response writes return the update error).
76 type updateOnSuccess struct {
77 httpserver.ResponseWriter
78 logger logrus.FieldLogger
84 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
86 uos.WriteHeader(http.StatusOK)
91 return uos.ResponseWriter.Write(p)
94 func (uos *updateOnSuccess) WriteHeader(code int) {
97 if code >= 200 && code < 400 {
98 if uos.err = uos.update(); uos.err != nil {
99 code := http.StatusInternalServerError
100 var he interface{ HTTPStatus() int }
101 if errors.As(uos.err, &he) {
102 code = he.HTTPStatus()
104 uos.logger.WithError(uos.err).Errorf("update() returned %T error, changing response to HTTP %d", uos.err, code)
105 http.Error(uos.ResponseWriter, uos.err.Error(), code)
110 uos.ResponseWriter.WriteHeader(code)
114 corsAllowHeadersHeader = strings.Join([]string{
115 "Authorization", "Content-Type", "Range",
116 // WebDAV request headers:
117 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
119 writeMethod = map[string]bool{
130 webdavMethod = map[string]bool{
143 browserMethod = map[string]bool{
148 // top-level dirs to serve with siteFS
149 siteFSDir = map[string]bool{
150 "": true, // root directory
156 func stripDefaultPort(host string) string {
157 // Will consider port 80 and port 443 to be the same vhost. I think that's fine.
158 u := &url.URL{Host: host}
159 if p := u.Port(); p == "80" || p == "443" {
160 return strings.ToLower(u.Hostname())
162 return strings.ToLower(host)
166 // CheckHealth implements service.Handler.
167 func (h *handler) CheckHealth() error {
171 // Done implements service.Handler.
172 func (h *handler) Done() <-chan struct{} {
176 // ServeHTTP implements http.Handler.
177 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
178 h.setupOnce.Do(h.setup)
180 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
184 w := httpserver.WrapResponseWriter(wOrig)
186 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
187 if !browserMethod[method] && !webdavMethod[method] {
188 w.WriteHeader(http.StatusMethodNotAllowed)
191 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
192 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
193 w.Header().Set("Access-Control-Allow-Origin", "*")
194 w.Header().Set("Access-Control-Max-Age", "86400")
198 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
199 w.WriteHeader(http.StatusMethodNotAllowed)
203 if r.Header.Get("Origin") != "" {
204 // Allow simple cross-origin requests without user
205 // credentials ("user credentials" as defined by CORS,
206 // i.e., cookies, HTTP authentication, and client-side
207 // SSL certificates. See
208 // http://www.w3.org/TR/cors/#user-credentials).
209 w.Header().Set("Access-Control-Allow-Origin", "*")
210 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
217 pathParts := strings.Split(r.URL.Path[1:], "/")
220 var collectionID string
222 var reqTokens []string
226 credentialsOK := h.Cluster.Collections.TrustAllContent
227 reasonNotAcceptingCredentials := ""
229 if r.Host != "" && stripDefaultPort(r.Host) == stripDefaultPort(h.Cluster.Services.WebDAVDownload.ExternalURL.Host) {
232 } else if r.FormValue("disposition") == "attachment" {
237 reasonNotAcceptingCredentials = fmt.Sprintf("vhost %q does not specify a single collection ID or match Services.WebDAVDownload.ExternalURL %q, and Collections.TrustAllContent is false",
238 r.Host, h.Cluster.Services.WebDAVDownload.ExternalURL)
241 if collectionID = arvados.CollectionIDFromDNSName(r.Host); collectionID != "" {
242 // http://ID.collections.example/PATH...
244 } else if r.URL.Path == "/status.json" {
247 } else if siteFSDir[pathParts[0]] {
249 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
251 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
253 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
254 if len(pathParts) >= 4 && pathParts[1] == "download" {
255 // /collections/download/ID/TOKEN/PATH...
256 collectionID = parseCollectionIDFromURL(pathParts[2])
257 tokens = []string{pathParts[3]}
261 // /collections/ID/PATH...
262 collectionID = parseCollectionIDFromURL(pathParts[1])
264 // This path is only meant to work for public
265 // data. Tokens provided with the request are
267 credentialsOK = false
268 reasonNotAcceptingCredentials = "the '/collections/UUID/PATH' form only works for public data"
273 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
278 reqTokens = auth.CredentialsFromRequest(r).Tokens
281 formToken := r.FormValue("api_token")
282 origin := r.Header.Get("Origin")
283 cors := origin != "" && !strings.HasSuffix(origin, "://"+r.Host)
284 safeAjax := cors && (r.Method == http.MethodGet || r.Method == http.MethodHead)
285 safeAttachment := attachment && r.URL.Query().Get("api_token") == ""
287 // No token to use or redact.
288 } else if safeAjax || safeAttachment {
289 // If this is a cross-origin request, the URL won't
290 // appear in the browser's address bar, so
291 // substituting a clipboard-safe URL is pointless.
292 // Redirect-with-cookie wouldn't work anyway, because
293 // it's not safe to allow third-party use of our
296 // If we're supplying an attachment, we don't need to
297 // convert POST to GET to avoid the "really resubmit
298 // form?" problem, so provided the token isn't
299 // embedded in the URL, there's no reason to do
300 // redirect-with-cookie in this case either.
301 reqTokens = append(reqTokens, formToken)
302 } else if browserMethod[r.Method] {
303 // If this is a page view, and the client provided a
304 // token via query string or POST body, we must put
305 // the token in an HttpOnly cookie, and redirect to an
306 // equivalent URL with the query param redacted and
308 h.seeOtherWithCookie(w, r, "", credentialsOK)
312 targetPath := pathParts[stripParts:]
313 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
314 // http://ID.example/t=TOKEN/PATH...
315 // /c=ID/t=TOKEN/PATH...
317 // This form must only be used to pass scoped tokens
318 // that give permission for a single collection. See
319 // FormValue case above.
320 tokens = []string{targetPath[0][2:]}
322 targetPath = targetPath[1:]
328 if writeMethod[r.Method] {
329 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
332 if len(reqTokens) == 0 {
333 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
334 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
338 } else if collectionID == "" {
339 http.Error(w, notFoundMessage, http.StatusNotFound)
342 fsprefix = "by_id/" + collectionID + "/"
347 if h.Cluster.Users.AnonymousUserToken != "" {
348 tokens = append(tokens, h.Cluster.Users.AnonymousUserToken)
354 http.Error(w, fmt.Sprintf("Authorization tokens are not accepted here: %v, and no anonymous user token is configured.", reasonNotAcceptingCredentials), http.StatusUnauthorized)
356 http.Error(w, fmt.Sprintf("No authorization token in request, and no anonymous user token is configured."), http.StatusUnauthorized)
361 if len(targetPath) > 0 && targetPath[0] == "_" {
362 // If a collection has a directory called "t=foo" or
363 // "_", it can be served at
364 // //collections.example/_/t=foo/ or
365 // //collections.example/_/_/ respectively:
366 // //collections.example/t=foo/ won't work because
367 // t=foo will be interpreted as a token "foo".
368 targetPath = targetPath[1:]
372 dirOpenMode := os.O_RDONLY
373 if writeMethod[r.Method] {
374 dirOpenMode = os.O_RDWR
377 validToken := make(map[string]bool)
379 var tokenUser *arvados.User
380 var sessionFS arvados.CustomFileSystem
381 var session *cachedSession
382 var collectionDir arvados.File
383 for _, token = range tokens {
384 var statusErr interface{ HTTPStatus() int }
385 fs, sess, user, err := h.Cache.GetSession(token)
386 if errors.As(err, &statusErr) && statusErr.HTTPStatus() == http.StatusUnauthorized {
389 } else if err != nil {
390 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
393 f, err := fs.OpenFile(fsprefix, dirOpenMode, 0)
394 if errors.As(err, &statusErr) && statusErr.HTTPStatus() == http.StatusForbidden {
395 // collection id is outside token scope
396 validToken[token] = true
399 validToken[token] = true
400 if os.IsNotExist(err) {
401 // collection does not exist or is not
402 // readable using this token
404 } else if err != nil {
405 http.Error(w, err.Error(), http.StatusInternalServerError)
410 collectionDir, sessionFS, session, tokenUser = f, fs, sess, user
414 err := collectionDir.Sync()
416 var statusErr interface{ HTTPStatus() int }
417 if errors.As(err, &statusErr) {
418 http.Error(w, err.Error(), statusErr.HTTPStatus())
420 http.Error(w, err.Error(), http.StatusInternalServerError)
426 if pathToken || !credentialsOK {
427 // Either the URL is a "secret sharing link"
428 // that didn't work out (and asking the client
429 // for additional credentials would just be
430 // confusing), or we don't even accept
431 // credentials at this path.
432 http.Error(w, notFoundMessage, http.StatusNotFound)
435 for _, t := range reqTokens {
437 // The client provided valid token(s),
438 // but the collection was not found.
439 http.Error(w, notFoundMessage, http.StatusNotFound)
443 // The client's token was invalid (e.g., expired), or
444 // the client didn't even provide one. Redirect to
445 // workbench2's login-and-redirect-to-download url if
446 // this is a browser navigation request. (The redirect
447 // flow can't preserve the original method if it's not
448 // GET, and doesn't make sense if the UA is a
449 // command-line tool, is trying to load an inline
450 // image, etc.; in these cases, there's nothing we can
451 // do, so return 401 unauthorized.)
453 // Note Sec-Fetch-Mode is sent by all non-EOL
454 // browsers, except Safari.
455 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Mode
457 // TODO(TC): This response would be confusing to
458 // someone trying (anonymously) to download public
459 // data that has been deleted. Allow a referrer to
460 // provide this context somehow?
461 if r.Method == http.MethodGet && r.Header.Get("Sec-Fetch-Mode") == "navigate" {
462 target := url.URL(h.Cluster.Services.Workbench2.ExternalURL)
463 redirkey := "redirectToPreview"
465 redirkey = "redirectToDownload"
467 callback := "/c=" + collectionID + "/" + strings.Join(targetPath, "/")
468 // target.RawQuery = url.Values{redirkey:
469 // {target}}.Encode() would be the obvious
470 // thing to do here, but wb2 doesn't decode
471 // this as a query param -- it takes
472 // everything after "${redirkey}=" as the
473 // target URL. If we encode "/" as "%2F" etc.,
474 // the redirect won't work.
475 target.RawQuery = redirkey + "=" + callback
476 w.Header().Add("Location", target.String())
477 w.WriteHeader(http.StatusSeeOther)
479 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
480 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
485 if r.Method == http.MethodGet || r.Method == http.MethodHead {
486 targetfnm := fsprefix + strings.Join(pathParts[stripParts:], "/")
487 if fi, err := sessionFS.Stat(targetfnm); err == nil && fi.IsDir() {
488 if !strings.HasSuffix(r.URL.Path, "/") {
489 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
491 h.serveDirectory(w, r, fi.Name(), sessionFS, targetfnm, !useSiteFS)
498 if len(targetPath) > 0 {
499 basename = targetPath[len(targetPath)-1]
501 if arvadosclient.PDHMatch(collectionID) && writeMethod[r.Method] {
502 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
505 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
506 http.Error(w, "Not permitted", http.StatusForbidden)
509 h.logUploadOrDownload(r, session.arvadosclient, sessionFS, fsprefix+strings.Join(targetPath, "/"), nil, tokenUser)
511 if writeMethod[r.Method] {
512 // Save the collection only if/when all
513 // webdav->filesystem operations succeed --
514 // and send a 500 error if the modified
515 // collection can't be saved.
517 // Perform the write in a separate sitefs, so
518 // concurrent read operations on the same
519 // collection see the previous saved
520 // state. After the write succeeds and the
521 // collection record is updated, we reset the
522 // session so the updates are visible in
523 // subsequent read requests.
524 client := session.client.WithRequestID(r.Header.Get("X-Request-Id"))
525 sessionFS = client.SiteFileSystem(session.keepclient)
526 writingDir, err := sessionFS.OpenFile(fsprefix, os.O_RDONLY, 0)
528 http.Error(w, err.Error(), http.StatusInternalServerError)
531 defer writingDir.Close()
532 w = &updateOnSuccess{
534 logger: ctxlog.FromContext(r.Context()),
535 update: func() error {
536 err := writingDir.Sync()
537 var te arvados.TransactionError
538 if errors.As(err, &te) {
544 // Sync the changes to the persistent
545 // sessionfs for this token.
546 snap, err := writingDir.Snapshot()
550 collectionDir.Splice(snap)
554 if r.Method == http.MethodGet {
555 applyContentDispositionHdr(w, r, basename, attachment)
557 wh := webdav.Handler{
558 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
559 FileSystem: &webdavFS{
562 writing: writeMethod[r.Method],
563 alwaysReadEOF: r.Method == "PROPFIND",
565 LockSystem: h.webdavLS,
566 Logger: func(r *http.Request, err error) {
568 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
573 if r.Method == http.MethodGet && w.WroteStatus() == http.StatusOK {
574 wrote := int64(w.WroteBodyBytes())
575 fnm := strings.Join(pathParts[stripParts:], "/")
576 fi, err := wh.FileSystem.Stat(r.Context(), fnm)
577 if err == nil && fi.Size() != wrote {
579 f, err := wh.FileSystem.OpenFile(r.Context(), fnm, os.O_RDONLY, 0)
581 n, err = f.Read(make([]byte, 1024))
584 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %v", fi.Size(), wrote, n, err)
589 var dirListingTemplate = `<!DOCTYPE HTML>
591 <META name="robots" content="NOINDEX">
592 <TITLE>{{ .CollectionName }}</TITLE>
593 <STYLE type="text/css">
598 background-color: #D9EDF7;
599 border-radius: .25em;
610 font-family: monospace;
617 <H1>{{ .CollectionName }}</H1>
619 <P>This collection of data files is being shared with you through
620 Arvados. You can download individual files listed below. To download
621 the entire directory tree with wget, try:</P>
623 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
625 <H2>File Listing</H2>
631 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
633 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
638 <P>(No files; this collection is empty.)</P>
645 Arvados is a free and open source software bioinformatics platform.
646 To learn more, visit arvados.org.
647 Arvados is not responsible for the files listed on this page.
654 type fileListEnt struct {
660 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
661 var files []fileListEnt
662 var walk func(string) error
663 if !strings.HasSuffix(base, "/") {
666 walk = func(path string) error {
667 dirname := base + path
669 dirname = strings.TrimSuffix(dirname, "/")
671 d, err := fs.Open(dirname)
675 ents, err := d.Readdir(-1)
679 for _, ent := range ents {
680 if recurse && ent.IsDir() {
681 err = walk(path + ent.Name() + "/")
686 files = append(files, fileListEnt{
687 Name: path + ent.Name(),
695 if err := walk(""); err != nil {
696 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
700 funcs := template.FuncMap{
701 "nbsp": func(s string) template.HTML {
702 return template.HTML(strings.Replace(s, " ", " ", -1))
705 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
707 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
710 sort.Slice(files, func(i, j int) bool {
711 return files[i].Name < files[j].Name
713 w.WriteHeader(http.StatusOK)
714 tmpl.Execute(w, map[string]interface{}{
715 "CollectionName": collectionName,
718 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
722 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
723 disposition := "inline"
725 disposition = "attachment"
727 if strings.ContainsRune(r.RequestURI, '?') {
728 // Help the UA realize that the filename is just
729 // "filename.txt", not
730 // "filename.txt?disposition=attachment".
732 // TODO(TC): Follow advice at RFC 6266 appendix D
733 disposition += "; filename=" + strconv.QuoteToASCII(filename)
735 if disposition != "inline" {
736 w.Header().Set("Content-Disposition", disposition)
740 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
741 if formToken := r.FormValue("api_token"); formToken != "" {
743 // It is not safe to copy the provided token
744 // into a cookie unless the current vhost
745 // (origin) serves only a single collection or
746 // we are in TrustAllContent mode.
747 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)
751 // The HttpOnly flag is necessary to prevent
752 // JavaScript code (included in, or loaded by, a page
753 // in the collection being served) from employing the
754 // user's token beyond reading other files in the same
755 // domain, i.e., same collection.
757 // The 303 redirect is necessary in the case of a GET
758 // request to avoid exposing the token in the Location
759 // bar, and in the case of a POST request to avoid
760 // raising warnings when the user refreshes the
762 http.SetCookie(w, &http.Cookie{
763 Name: "arvados_api_token",
764 Value: auth.EncodeTokenCookie([]byte(formToken)),
767 SameSite: http.SameSiteLaxMode,
771 // Propagate query parameters (except api_token) from
772 // the original request.
773 redirQuery := r.URL.Query()
774 redirQuery.Del("api_token")
778 newu, err := u.Parse(location)
780 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
786 Scheme: r.URL.Scheme,
789 RawQuery: redirQuery.Encode(),
792 w.Header().Add("Location", redir)
793 w.WriteHeader(http.StatusSeeOther)
794 io.WriteString(w, `<A href="`)
795 io.WriteString(w, html.EscapeString(redir))
796 io.WriteString(w, `">Continue</A>`)
799 func (h *handler) userPermittedToUploadOrDownload(method string, tokenUser *arvados.User) bool {
800 var permitDownload bool
801 var permitUpload bool
802 if tokenUser != nil && tokenUser.IsAdmin {
803 permitUpload = h.Cluster.Collections.WebDAVPermission.Admin.Upload
804 permitDownload = h.Cluster.Collections.WebDAVPermission.Admin.Download
806 permitUpload = h.Cluster.Collections.WebDAVPermission.User.Upload
807 permitDownload = h.Cluster.Collections.WebDAVPermission.User.Download
809 if (method == "PUT" || method == "POST") && !permitUpload {
810 // Disallow operations that upload new files.
811 // Permit webdav operations that move existing files around.
813 } else if method == "GET" && !permitDownload {
814 // Disallow downloading file contents.
815 // Permit webdav operations like PROPFIND that retrieve metadata
816 // but not file contents.
822 func (h *handler) logUploadOrDownload(
824 client *arvadosclient.ArvadosClient,
825 fs arvados.CustomFileSystem,
827 collection *arvados.Collection,
828 user *arvados.User) {
830 log := ctxlog.FromContext(r.Context())
831 props := make(map[string]string)
832 props["reqPath"] = r.URL.Path
835 log = log.WithField("user_uuid", user.UUID).
836 WithField("user_full_name", user.FullName)
839 useruuid = fmt.Sprintf("%s-tpzed-anonymouspublic", h.Cluster.ClusterID)
841 if collection == nil && fs != nil {
842 collection, filepath = h.determineCollection(fs, filepath)
844 if collection != nil {
845 log = log.WithField("collection_file_path", filepath)
846 props["collection_file_path"] = filepath
847 // h.determineCollection populates the collection_uuid
848 // prop with the PDH, if this collection is being
849 // accessed via PDH. For logging, we use a different
850 // field depending on whether it's a UUID or PDH.
851 if len(collection.UUID) > 32 {
852 log = log.WithField("portable_data_hash", collection.UUID)
853 props["portable_data_hash"] = collection.UUID
855 log = log.WithField("collection_uuid", collection.UUID)
856 props["collection_uuid"] = collection.UUID
859 if r.Method == "PUT" || r.Method == "POST" {
860 log.Info("File upload")
861 if h.Cluster.Collections.WebDAVLogEvents {
863 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
864 "object_uuid": useruuid,
865 "event_type": "file_upload",
866 "properties": props}}
867 err := client.Create("logs", lr, nil)
869 log.WithError(err).Error("Failed to create upload log event on API server")
873 } else if r.Method == "GET" {
874 if collection != nil && collection.PortableDataHash != "" {
875 log = log.WithField("portable_data_hash", collection.PortableDataHash)
876 props["portable_data_hash"] = collection.PortableDataHash
878 log.Info("File download")
879 if h.Cluster.Collections.WebDAVLogEvents {
881 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
882 "object_uuid": useruuid,
883 "event_type": "file_download",
884 "properties": props}}
885 err := client.Create("logs", lr, nil)
887 log.WithError(err).Error("Failed to create download log event on API server")
894 func (h *handler) determineCollection(fs arvados.CustomFileSystem, path string) (*arvados.Collection, string) {
895 target := strings.TrimSuffix(path, "/")
896 for cut := len(target); cut >= 0; cut = strings.LastIndexByte(target, '/') {
897 target = target[:cut]
898 fi, err := fs.Stat(target)
899 if os.IsNotExist(err) {
900 // creating a new file/dir, or download
903 } else if err != nil {
906 switch src := fi.Sys().(type) {
907 case *arvados.Collection:
908 return src, strings.TrimPrefix(path[len(target):], "/")
912 if _, ok := src.(error); ok {