37std::string urlquote(
const std::string input) {
39 output.reserve(3 * input.size());
40 for (
char val : input) {
41 if ((val >= 48 && val <= 57) ||
42 (val >= 65 && val <= 90) ||
43 (val >= 97 && val <= 122) ||
44 (val == 95 || val == 46 || val == 45 || val == 126 ||
49 output +=
"%" + std::to_string(val);
57 StatHandler(
const std::string &path,
const std::string &s3_url, XrdClHttp::HeaderCallout *header_callout, XrdCl::ResponseHandler *handler, time_t timeout, XrdCl::Log &log) :
60 m_header_callout(header_callout),
66 virtual void HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response)
override;
70 XrdCl::ResponseHandler *m_handler{
nullptr};
71 XrdClHttp::HeaderCallout *m_header_callout{
nullptr};
83 StatHandlerDirectory(XrdCl::ResponseHandler *handler) :
87 virtual void HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response)
override;
90 XrdCl::ResponseHandler *m_handler{
nullptr};
96 DirListResponseHandler(
bool existence_check,
const std::string &url, XrdClHttp::HeaderCallout *header_callout, XrdCl::ResponseHandler *handler, time_t expiry, XrdCl::Log &log) :
97 m_existence_check(existence_check),
99 m_header_callout(header_callout),
101 m_host(Factory::ExtractHostname(url)),
106 virtual void HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response)
override;
112 bool m_existence_check;
115 XrdClHttp::HeaderCallout *m_header_callout{
nullptr};
119 std::unique_ptr<XrdCl::DirectoryList> dirlist{
new XrdCl::DirectoryList()};
121 XrdCl::ResponseHandler *m_handler{
nullptr};
122 XrdCl::Log &m_logger;
128 MkdirHandler(XrdCl::File *file, XrdCl::ResponseHandler *handler, time_t timeout) :
129 m_expiry(time(NULL) + (timeout ? timeout : 30)),
134 virtual void HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response)
override;
138 bool m_started_close{
false};
139 std::unique_ptr<XrdCl::File> m_file;
140 XrdCl::ResponseHandler *m_handler{
nullptr};
145 std::unique_ptr<StatHandler> self(
this);
146 std::unique_ptr<XrdCl::AnyObject> response_holder(response_raw);
147 std::unique_ptr<XrdCl::XRootDStatus> status(status_raw);
150 if (m_handler) {
return m_handler->
HandleResponse(status.release(), response_holder.release());}
155 if (m_handler) {
return m_handler->
HandleResponse(status.release(), response_holder.release());}
161 std::string https_url, err_msg;
168 obj = obj.substr(0, obj.find(
'?'));
169 auto query_loc = https_url.find(
'?');
170 https_url += (query_loc == std::string::npos) ?
"?" :
"&";
171 https_url +=
"list-type=2&delimiter=/&encoding-type=url";
172 https_url +=
"&prefix=" + urlquote(obj) +
"/";
174 auto expiry = time(NULL) + m_timeout;
179 new DirListResponseHandler(
180 true, https_url, m_header_callout,
new StatHandlerDirectory(m_handler), expiry, m_logger
185 if (m_handler)
return m_handler->
HandleResponse(
new XrdCl::XRootDStatus(st), response_holder.release());
191StatHandlerDirectory::HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response) {
192 std::unique_ptr<StatHandlerDirectory> self(
this);
198 if (!status || !status->
IsOK()) {
202 auto obj =
new XrdCl::AnyObject();
209DirListResponseHandler::HandleResponse(XrdCl::XRootDStatus *status_raw, XrdCl::AnyObject *response_raw) {
210 std::unique_ptr<DirListResponseHandler> self(
this);
211 std::unique_ptr<XrdCl::AnyObject> response(response_raw);
212 std::unique_ptr<XrdCl::XRootDStatus> status(status_raw);
216 if (!status || !status->
IsOK()) {
217 return m_handler->
HandleResponse(status.release(), response.release());
221 m_logger.
Error(
kLogXrdClS3,
"Directory listing returned without any response object.");
225 XrdCl::Buffer *buffer =
nullptr;
226 response->
Get(buffer);
228 m_logger.
Error(
kLogXrdClS3,
"Directory listing response object was not a buffer.");
235 doc.Parse(buffer_str.c_str());
237 std::string errMsg =
"Error when parsing S3 endpoint's listing response: " + std::string(doc.ErrorDesc());
242 auto elem = doc.RootElement();
243 if (strcmp(elem->Value(),
"ListBucketResult")) {
245 "S3 ListBucket response is not rooted with ListBucketResult element"),
nullptr);
283 bool isTruncated =
false;
285 bool found_sentinel =
false;
286 for (
auto child = elem->FirstChildElement(); child !=
nullptr;
287 child = child->NextSiblingElement()) {
288 if (!strcmp(child->Value(),
"IsTruncated")) {
289 auto text = child->GetText();
290 if (!strcasecmp(text,
"true")) {
292 }
else if (!strcasecmp(text,
"false")) {
295 }
else if (!strcmp(child->Value(),
"CommonPrefixes")) {
296 auto prefix = child->FirstChildElement(
"Prefix");
297 if (prefix !=
nullptr) {
298 auto prefixChar = prefix->GetText();
299 if (prefixChar !=
nullptr) {
300 auto prefixStr = std::string_view(prefixChar);
302 if (!prefixStr.empty()) {
303 if (prefixStr[prefixStr.size() - 1] ==
'/') prefixStr = prefixStr.substr(0, prefixStr.size() - 1);
308 new XrdCl::DirectoryList::ListEntry(
309 m_host, std::string(prefixStr),
new XrdCl::StatInfo(
310 "nobody", 4096, flags, 0)));
314 }
else if (!strcmp(child->Value(),
"Contents")) {
315 std::string_view keyStr;
317 bool goodSize =
false;
318 auto key = child->FirstChildElement(
"Key");
319 if (key !=
nullptr) {
320 auto keyChar = key->GetText();
321 if (keyChar !=
nullptr) {
325 auto last_slash = keyStr.rfind(
'/');
326 if (last_slash != std::string_view::npos) {
328 found_sentinel =
true;
329 if (m_existence_check)
break;
333 auto sizeElem = child->FirstChildElement(
"Size");
334 if (sizeElem !=
nullptr) {
335 auto sizeChar = sizeElem->GetText();
336 if (sizeChar !=
nullptr && *sizeChar) {
337 auto res = std::from_chars(sizeChar, sizeChar + strlen(sizeChar), size);
338 if (res.ec == std::errc()) {
343 auto lastModifiedElem = child->FirstChildElement(
"LastModified");
344 time_t lastModified = 0;
345 if (lastModifiedElem !=
nullptr) {
346 auto lastModifiedChar = lastModifiedElem->GetText();
347 if (lastModifiedChar !=
nullptr) {
350 if (strptime(lastModifiedChar,
"%Y-%m-%dT%H:%M:%S", &tm) !=
nullptr) {
352 lastModified = mktime(&tm);
356 if (goodSize && !keyStr.empty()) {
359 new XrdCl::DirectoryList::ListEntry(
360 m_host, std::string(keyStr),
new XrdCl::StatInfo(
361 "nobody", size, flags, lastModified)));
363 }
else if (!strcmp(child->Value(),
"NextContinuationToken")) {
364 auto ctChar = child->GetText();
374 if (!isTruncated || (m_existence_check && (dirlist->
GetSize() || found_sentinel))) {
376 if (!found_sentinel && !dirlist->
GetSize()) {
383 auto object =
new XrdCl::AnyObject();
384 object->Set(dirlist.release());
386 new XrdCl::XRootDStatus{},
392 auto url = m_url +
"&continuation-token=" + urlquote(ct);
395 time_t now = time(NULL);
396 if (now >= m_expiry) {
404 auto st =
DownloadUrl(url, m_header_callout,
this, m_expiry - now);
412MkdirHandler::HandleResponse(XrdCl::XRootDStatus *status_raw, XrdCl::AnyObject *response_raw)
414 std::unique_ptr<MkdirHandler> self(
this);
415 std::unique_ptr<XrdCl::XRootDStatus> status(status_raw);
416 std::unique_ptr<XrdCl::AnyObject> response(response_raw);
418 if (!status || !status->
IsOK() || m_started_close) {
419 if (m_handler) m_handler->
HandleResponse(status.release(), response.release());
423 time_t now = time(NULL);
424 if (now >= m_expiry) {
432 m_started_close =
true;
433 auto st = m_file->
Close(
this, m_expiry - now);
435 if (m_handler) m_handler->
HandleResponse(status.release(), response.release());
449 m_url.SetParams(map);
451 m_logger->Debug(
kLogXrdClS3,
"S3 filesystem constructed with URL: %s.",
452 m_url.GetURL().c_str());
463 std::string https_url, err_msg;
469 obj = obj.substr(0, obj.find(
'?'));
470 auto query_loc = https_url.find(
'?');
471 https_url += (query_loc == std::string::npos) ?
"?" :
"&";
472 https_url +=
"list-type=2&delimiter=/&encoding-type=url";
473 https_url +=
"&prefix=" + urlquote(obj) +
"/";
475 auto expiry = time(NULL) + timeout;
480 new DirListResponseHandler(
481 false, https_url, &m_header_callout, handler, expiry, *m_logger
487std::pair<XrdCl::XRootDStatus, XrdCl::FileSystem*>
488Filesystem::GetFSHandle(
const std::string &path) {
490 std::string https_url, err_msg;
494 auto loc = https_url.find(
'/', 8);
495 if (loc == std::string::npos) {
498 auto endpoint = https_url.substr(0, loc);
500 std::shared_lock lock(m_handles_mutex);
501 auto iter = m_handles.find(endpoint);
502 if (iter != m_handles.end()) {
503 return std::make_pair(XrdCl::XRootDStatus{}, iter->second);
510 std::unique_lock lock(m_handles_mutex);
511 auto iter = m_handles.find(endpoint);
512 if (iter != m_handles.end()) {
513 return std::make_pair(XrdCl::XRootDStatus{}, iter->second);
515 auto fs =
new XrdCl::FileSystem(url);
516 std::stringstream ss;
517 ss << std::hex << reinterpret_cast<long long>(&m_header_callout);
518 if (!fs->SetProperty(
"XrdClHttpHeaderCallout", ss.str())) {
522 m_handles[endpoint] = fs;
524 return std::make_pair(XrdCl::XRootDStatus{}, fs);
529 std::string &value)
const
531 std::unique_lock lock(m_properties_mutex);
532 const auto p = m_properties.find(name);
533 if (p == std::end(m_properties)) {
548 auto [st, fs] = GetFSHandle(cleaned_path);
552 return fs->Locate(cleaned_path, flags, handler, timeout);
563 if (sentinel.empty()) {
567 auto loc = input_path.find(
'?');
568 auto path = input_path.substr(0, loc);
569 if (!path.empty() && path[path.size() - 1] !=
'/') path +=
"/";
571 if (loc != std::string::npos) {
572 path += input_path.substr(loc);
576 std::string https_url, err_msg;
584 auto callout_loc =
reinterpret_cast<long long>(&m_header_callout);
585 size_t buf_size = 16;
586 char callout_buf[buf_size];
587 std::to_chars_result result = std::to_chars(callout_buf, callout_buf + buf_size - 1, callout_loc, 16);
588 if (result.ec == std::errc{}) {
589 std::string callout_str(callout_buf, result.ptr - callout_buf);
590 http_file->
SetProperty(
"XrdClHttpHeaderCallout", callout_str);
593 MkdirHandler *mkdirHandler =
new MkdirHandler(http_file, handler, timeout);
608 auto [st, fs] = GetFSHandle(cleaned_path);
614 return fs->Query(queryCode, cleanedArg, handler, timeout);
624 auto [st, fs] = GetFSHandle(cleaned_path);
628 return fs->Rm(cleaned_path, handler, timeout);
637 if (sentinel.empty()) {
641 auto loc = input_path.find(
'?');
642 auto path = input_path.substr(0, loc);
643 if (!path.empty() && path[path.size() - 1] !=
'/') path +=
"/";
645 if (loc != std::string::npos) {
646 path += input_path.substr(loc);
648 return Rm(path, handler, timeout);
654 const std::string &value)
656 std::unique_lock lock(m_properties_mutex);
657 m_properties[name] = value;
667 auto [st, fs] = GetFSHandle(cleaned_path);
671 return fs->Stat(cleaned_path,
new StatHandler(cleaned_path, m_url.GetURL(), &m_header_callout, handler, timeout, *m_logger), timeout);
674std::shared_ptr<XrdClHttp::HeaderCallout::HeaderList>
675Filesystem::S3HeaderCallout::GetHeaders(
const std::string &verb,
676 const std::string &url,
679 std::string auth_token, err_msg;
680 std::shared_ptr<HeaderList> header_list(
new HeaderList(headers));
682 header_list->emplace_back(
"Authorization", auth_token);
684 m_parent.m_logger->
Error(
kLogXrdClS3,
"Failed to generate V4 signature: %s", err_msg.c_str());
static std::string CleanObjectName(const std::string &object)
static bool GenerateHttpUrl(const std::string &s3_url, std::string &https_url, std::string *obj_result, std::string &err_msg)
static bool GenerateV4Signature(const std::string &url, const std::string &verb, std::vector< std::pair< std::string, std::string > > &headers, std::string &auth_token, std::string &err_msg)
static std::string_view TrimView(const std::string_view str)
static const std::string & GetMkdirSentinel()
virtual XrdCl::XRootDStatus MkDir(const std::string &path, XrdCl::MkDirFlags::Flags flags, XrdCl::Access::Mode mode, XrdCl::ResponseHandler *handler, time_t timeout) override
Filesystem(const std::string &, XrdCl::Log *log)
virtual bool SetProperty(const std::string &name, const std::string &value) override
virtual XrdCl::XRootDStatus DirList(const std::string &path, XrdCl::DirListFlags::Flags flags, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual XrdCl::XRootDStatus Rm(const std::string &path, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual XrdCl::XRootDStatus Stat(const std::string &path, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual XrdCl::XRootDStatus Locate(const std::string &path, XrdCl::OpenFlags::Flags flags, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual ~Filesystem() noexcept
virtual XrdCl::XRootDStatus RmDir(const std::string &path, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual bool GetProperty(const std::string &name, std::string &value) const override
virtual XrdCl::XRootDStatus Query(XrdCl::QueryCode::Code queryCode, const XrdCl::Buffer &arg, XrdCl::ResponseHandler *handler, time_t timeout) override
void Get(Type &object)
Retrieve the object being held.
Binary blob representation.
void FromString(const std::string str)
Fill the buffer from a string.
const char * GetBuffer(uint32_t offset=0) const
Get the message buffer.
uint32_t GetSize() const
Get the size of the message.
std::string ToString() const
Convert the buffer to a string.
void Add(ListEntry *entry)
Add an entry to the list - takes ownership.
uint32_t GetSize() const
Get the size of the listing.
XRootDStatus Open(const std::string &url, OpenFlags::Flags flags, Access::Mode mode, ResponseHandler *handler, time_t timeout=0) XRD_WARN_UNUSED_RESULT
XRootDStatus Close(ResponseHandler *handler, time_t timeout=0) XRD_WARN_UNUSED_RESULT
bool SetProperty(const std::string &name, const std::string &value)
void Error(uint64_t topic, const char *format,...)
Report an error.
Handle an async response.
virtual void HandleResponse(XRootDStatus *status, AnyObject *response)
@ IsReadable
Read access is allowed.
@ IsDir
This is a directory.
@ XBitSet
Executable/searchable bit set.
std::map< std::string, std::string > ParamsMap
bool FromString(const std::string &url)
Parse a string and fill the URL fields.
std::string GetURL() const
Get the URL.
static std::string JoinUrl(const std::string &base, const std::string &path)
XrdCl::XRootDStatus DownloadUrl(const std::string &url, XrdClHttp::HeaderCallout *header_callout, XrdCl::ResponseHandler *handler, time_t timeout)
const uint64_t kLogXrdClS3
const uint16_t errInvalidAddr
const uint16_t errErrorResponse
const uint16_t errOperationExpired
const uint16_t errNotImplemented
Operation is not implemented.
const uint16_t stError
An error occurred that could potentially be retried.
const uint16_t errInvalidResponse
Flags
Open flags, may be or'd when appropriate.
@ Write
Open only for writing.
Code
XRootD query request codes.
@ XAttr
Query file extended attributes.
@ Checksum
Query file checksum.
bool IsOK() const
We're fine.