1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
8 #include <boost/tokenizer.hpp>
10 #include "json_spirit/json_spirit.h"
11 #include "common/ceph_json.h"
14 #include "rgw_common.h"
16 #include "rgw_string.h"
17 #include "rgw_rados.h"
18 #include "rgw_http_errors.h"
20 #include "common/ceph_crypto.h"
21 #include "common/armor.h"
22 #include "common/errno.h"
23 #include "common/Clock.h"
24 #include "common/Formatter.h"
25 #include "common/convenience.h"
26 #include "common/strtol.h"
27 #include "include/str_list.h"
28 #include "auth/Crypto.h"
29 #include "rgw_crypt_sanitize.h"
33 #define dout_context g_ceph_context
34 #define dout_subsys ceph_subsys_rgw
37 using rgw::IAM::Effect
;
38 using rgw::IAM::op_to_perm
;
39 using rgw::IAM::Policy
;
41 const uint32_t RGWBucketInfo::NUM_SHARDS_BLIND_BUCKET(UINT32_MAX
);
43 rgw_http_errors
rgw_http_s3_errors({
45 { STATUS_CREATED
, {201, "Created" }},
46 { STATUS_ACCEPTED
, {202, "Accepted" }},
47 { STATUS_NO_CONTENT
, {204, "NoContent" }},
48 { STATUS_PARTIAL_CONTENT
, {206, "" }},
49 { ERR_PERMANENT_REDIRECT
, {301, "PermanentRedirect" }},
50 { ERR_WEBSITE_REDIRECT
, {301, "WebsiteRedirect" }},
51 { STATUS_REDIRECT
, {303, "" }},
52 { ERR_NOT_MODIFIED
, {304, "NotModified" }},
53 { EINVAL
, {400, "InvalidArgument" }},
54 { ERR_INVALID_REQUEST
, {400, "InvalidRequest" }},
55 { ERR_INVALID_DIGEST
, {400, "InvalidDigest" }},
56 { ERR_BAD_DIGEST
, {400, "BadDigest" }},
57 { ERR_INVALID_LOCATION_CONSTRAINT
, {400, "InvalidLocationConstraint" }},
58 { ERR_ZONEGROUP_DEFAULT_PLACEMENT_MISCONFIGURATION
, {400, "ZonegroupDefaultPlacementMisconfiguration" }},
59 { ERR_INVALID_BUCKET_NAME
, {400, "InvalidBucketName" }},
60 { ERR_INVALID_OBJECT_NAME
, {400, "InvalidObjectName" }},
61 { ERR_UNRESOLVABLE_EMAIL
, {400, "UnresolvableGrantByEmailAddress" }},
62 { ERR_INVALID_PART
, {400, "InvalidPart" }},
63 { ERR_INVALID_PART_ORDER
, {400, "InvalidPartOrder" }},
64 { ERR_REQUEST_TIMEOUT
, {400, "RequestTimeout" }},
65 { ERR_TOO_LARGE
, {400, "EntityTooLarge" }},
66 { ERR_TOO_SMALL
, {400, "EntityTooSmall" }},
67 { ERR_TOO_MANY_BUCKETS
, {400, "TooManyBuckets" }},
68 { ERR_MALFORMED_XML
, {400, "MalformedXML" }},
69 { ERR_AMZ_CONTENT_SHA256_MISMATCH
, {400, "XAmzContentSHA256Mismatch" }},
70 { ERR_MALFORMED_DOC
, {400, "MalformedPolicyDocument"}},
71 { ERR_INVALID_TAG
, {400, "InvalidTag"}},
72 { ERR_MALFORMED_ACL_ERROR
, {400, "MalformedACLError" }},
73 { ERR_INVALID_CORS_RULES_ERROR
, {400, "InvalidRequest" }},
74 { ERR_INVALID_WEBSITE_ROUTING_RULES_ERROR
, {400, "InvalidRequest" }},
75 { ERR_INVALID_ENCRYPTION_ALGORITHM
, {400, "InvalidEncryptionAlgorithmError" }},
76 { ERR_LENGTH_REQUIRED
, {411, "MissingContentLength" }},
77 { EACCES
, {403, "AccessDenied" }},
78 { EPERM
, {403, "AccessDenied" }},
79 { ERR_SIGNATURE_NO_MATCH
, {403, "SignatureDoesNotMatch" }},
80 { ERR_INVALID_ACCESS_KEY
, {403, "InvalidAccessKeyId" }},
81 { ERR_USER_SUSPENDED
, {403, "UserSuspended" }},
82 { ERR_REQUEST_TIME_SKEWED
, {403, "RequestTimeTooSkewed" }},
83 { ERR_QUOTA_EXCEEDED
, {403, "QuotaExceeded" }},
84 { ERR_MFA_REQUIRED
, {403, "AccessDenied" }},
85 { ENOENT
, {404, "NoSuchKey" }},
86 { ERR_NO_SUCH_BUCKET
, {404, "NoSuchBucket" }},
87 { ERR_NO_SUCH_WEBSITE_CONFIGURATION
, {404, "NoSuchWebsiteConfiguration" }},
88 { ERR_NO_SUCH_UPLOAD
, {404, "NoSuchUpload" }},
89 { ERR_NOT_FOUND
, {404, "Not Found"}},
90 { ERR_NO_SUCH_LC
, {404, "NoSuchLifecycleConfiguration"}},
91 { ERR_NO_SUCH_BUCKET_POLICY
, {404, "NoSuchBucketPolicy"}},
92 { ERR_NO_SUCH_USER
, {404, "NoSuchUser"}},
93 { ERR_NO_ROLE_FOUND
, {404, "NoSuchEntity"}},
94 { ERR_NO_CORS_FOUND
, {404, "NoSuchCORSConfiguration"}},
95 { ERR_NO_SUCH_SUBUSER
, {404, "NoSuchSubUser"}},
96 { ERR_NO_SUCH_ENTITY
, {404, "NoSuchEntity"}},
97 { ERR_NO_SUCH_CORS_CONFIGURATION
, {404, "NoSuchCORSConfiguration"}},
98 { ERR_METHOD_NOT_ALLOWED
, {405, "MethodNotAllowed" }},
99 { ETIMEDOUT
, {408, "RequestTimeout" }},
100 { EEXIST
, {409, "BucketAlreadyExists" }},
101 { ERR_USER_EXIST
, {409, "UserAlreadyExists" }},
102 { ERR_EMAIL_EXIST
, {409, "EmailExists" }},
103 { ERR_KEY_EXIST
, {409, "KeyExists"}},
104 { ERR_TAG_CONFLICT
, {409, "OperationAborted"}},
105 { ERR_ROLE_EXISTS
, {409, "EntityAlreadyExists"}},
106 { ERR_DELETE_CONFLICT
, {409, "DeleteConflict"}},
107 { ERR_POSITION_NOT_EQUAL_TO_LENGTH
, {409, "PositionNotEqualToLength"}},
108 { ERR_OBJECT_NOT_APPENDABLE
, {409, "ObjectNotAppendable"}},
109 { ERR_INVALID_BUCKET_STATE
, {409, "InvalidBucketState"}},
110 { ERR_INVALID_SECRET_KEY
, {400, "InvalidSecretKey"}},
111 { ERR_INVALID_KEY_TYPE
, {400, "InvalidKeyType"}},
112 { ERR_INVALID_CAP
, {400, "InvalidCapability"}},
113 { ERR_INVALID_TENANT_NAME
, {400, "InvalidTenantName" }},
114 { ENOTEMPTY
, {409, "BucketNotEmpty" }},
115 { ERR_PRECONDITION_FAILED
, {412, "PreconditionFailed" }},
116 { ERANGE
, {416, "InvalidRange" }},
117 { ERR_UNPROCESSABLE_ENTITY
, {422, "UnprocessableEntity" }},
118 { ERR_LOCKED
, {423, "Locked" }},
119 { ERR_INTERNAL_ERROR
, {500, "InternalError" }},
120 { ERR_NOT_IMPLEMENTED
, {501, "NotImplemented" }},
121 { ERR_SERVICE_UNAVAILABLE
, {503, "ServiceUnavailable"}},
122 { ERR_RATE_LIMITED
, {503, "SlowDown"}},
123 { ERR_ZERO_IN_URL
, {400, "InvalidRequest" }},
126 rgw_http_errors
rgw_http_swift_errors({
127 { EACCES
, {403, "AccessDenied" }},
128 { EPERM
, {401, "AccessDenied" }},
129 { ENAMETOOLONG
, {400, "Metadata name too long" }},
130 { ERR_USER_SUSPENDED
, {401, "UserSuspended" }},
131 { ERR_INVALID_UTF8
, {412, "Invalid UTF8" }},
132 { ERR_BAD_URL
, {412, "Bad URL" }},
133 { ERR_NOT_SLO_MANIFEST
, {400, "Not an SLO manifest" }},
134 { ERR_QUOTA_EXCEEDED
, {413, "QuotaExceeded" }},
135 { ENOTEMPTY
, {409, "There was a conflict when trying "
136 "to complete your request." }},
137 /* FIXME(rzarzynski): we need to find a way to apply Swift's error handling
138 * procedures also for ERR_ZERO_IN_URL. This make a problem as the validation
139 * is performed very early, even before setting the req_state::proto_flags. */
140 { ERR_ZERO_IN_URL
, {412, "Invalid UTF8 or contains NULL"}},
141 { ERR_RATE_LIMITED
, {498, "Rate Limited"}},
144 rgw_http_errors
rgw_http_sts_errors({
145 { ERR_PACKED_POLICY_TOO_LARGE
, {400, "PackedPolicyTooLarge" }},
146 { ERR_INVALID_IDENTITY_TOKEN
, {400, "InvalidIdentityToken" }},
149 using namespace ceph::crypto
;
168 return (http_ret
== 200);
174 return !(http_ret
>= 200 && http_ret
<= 399);
177 // The requestURI transferred from the frontend can be abs_path or absoluteURI
178 // If it is absoluteURI, we should adjust it to abs_path for the following
179 // S3 authorization and some other processes depending on the requestURI
180 // The absoluteURI can start with "http://", "https://", "ws://" or "wss://"
181 static string
get_abs_path(const string
& request_uri
) {
182 const static string ABS_PREFIXS
[] = {"http://", "https://", "ws://", "wss://"};
184 for (int i
= 0; i
< 4; ++i
) {
185 if (boost::algorithm::starts_with(request_uri
, ABS_PREFIXS
[i
])) {
190 if (!isAbs
) { // it is not a valid absolute uri
193 size_t beg_pos
= request_uri
.find("://") + 3;
194 size_t len
= request_uri
.size();
195 beg_pos
= request_uri
.find('/', beg_pos
);
196 if (beg_pos
== string::npos
) return request_uri
;
197 return request_uri
.substr(beg_pos
, len
- beg_pos
);
200 req_info::req_info(CephContext
*cct
, const class RGWEnv
*env
) : env(env
) {
201 method
= env
->get("REQUEST_METHOD", "");
202 script_uri
= env
->get("SCRIPT_URI", cct
->_conf
->rgw_script_uri
.c_str());
203 request_uri
= env
->get("REQUEST_URI", cct
->_conf
->rgw_request_uri
.c_str());
204 if (request_uri
[0] != '/') {
205 request_uri
= get_abs_path(request_uri
);
207 auto pos
= request_uri
.find('?');
208 if (pos
!= string::npos
) {
209 request_params
= request_uri
.substr(pos
+ 1);
210 request_uri
= request_uri
.substr(0, pos
);
212 request_params
= env
->get("QUERY_STRING", "");
214 host
= env
->get("HTTP_HOST", "");
216 // strip off any trailing :port from host (added by CrossFTP and maybe others)
217 size_t colon_offset
= host
.find_last_of(':');
218 if (colon_offset
!= string::npos
) {
219 bool all_digits
= true;
220 for (unsigned i
= colon_offset
+ 1; i
< host
.size(); ++i
) {
221 if (!isdigit(host
[i
])) {
227 host
.resize(colon_offset
);
232 void req_info::rebuild_from(req_info
& src
)
235 script_uri
= src
.script_uri
;
237 if (src
.effective_uri
.empty()) {
238 request_uri
= src
.request_uri
;
240 request_uri
= src
.effective_uri
;
242 effective_uri
.clear();
245 x_meta_map
= src
.x_meta_map
;
246 x_meta_map
.erase("x-amz-date");
250 req_state::req_state(CephContext
* _cct
, RGWEnv
* e
, RGWUserInfo
* u
, uint64_t id
)
251 : cct(_cct
), user(u
),
252 info(_cct
, e
), id(id
)
254 enable_ops_log
= e
->get_enable_ops_log();
255 enable_usage_log
= e
->get_enable_usage_log();
256 defer_to_bucket_acls
= e
->get_defer_to_bucket_acls();
261 req_state::~req_state() {
265 std::ostream
& req_state::gen_prefix(std::ostream
& out
) const
267 auto p
= out
.precision();
268 return out
<< "req " << id
<< ' '
269 << std::setprecision(3) << std::fixed
<< time_elapsed() // '0.123s'
270 << std::setprecision(p
) << std::defaultfloat
<< ' ';
273 bool search_err(rgw_http_errors
& errs
, int err_no
, int& http_ret
, string
& code
)
275 auto r
= errs
.find(err_no
);
276 if (r
!= errs
.end()) {
277 http_ret
= r
->second
.first
;
278 code
= r
->second
.second
;
284 void set_req_state_err(struct rgw_err
& err
, /* out */
286 const int prot_flags
) /* in */
293 if (prot_flags
& RGW_REST_SWIFT
) {
294 if (search_err(rgw_http_swift_errors
, err_no
, err
.http_ret
, err
.err_code
))
298 if (prot_flags
& RGW_REST_STS
) {
299 if (search_err(rgw_http_sts_errors
, err_no
, err
.http_ret
, err
.err_code
))
303 //Default to searching in s3 errors
304 if (search_err(rgw_http_s3_errors
, err_no
, err
.http_ret
, err
.err_code
))
306 dout(0) << "WARNING: set_req_state_err err_no=" << err_no
307 << " resorting to 500" << dendl
;
310 err
.err_code
= "UnknownError";
313 void set_req_state_err(struct req_state
* s
, int err_no
, const string
& err_msg
)
316 set_req_state_err(s
, err_no
);
317 if (s
->prot_flags
& RGW_REST_SWIFT
&& !err_msg
.empty()) {
318 /* TODO(rzarzynski): there never ever should be a check like this one.
319 * It's here only for the sake of the patch's backportability. Further
320 * commits will move the logic to a per-RGWHandler replacement of
321 * the end_header() function. Alternativaly, we might consider making
322 * that just for the dump(). Please take a look on @cbodley's comments
323 * in PR #10690 (https://github.com/ceph/ceph/pull/10690). */
324 s
->err
.err_code
= err_msg
;
326 s
->err
.message
= err_msg
;
331 void set_req_state_err(struct req_state
* s
, int err_no
)
334 set_req_state_err(s
->err
, err_no
, s
->prot_flags
);
338 void dump(struct req_state
* s
)
340 if (s
->format
!= RGW_FORMAT_HTML
)
341 s
->formatter
->open_object_section("Error");
342 if (!s
->err
.err_code
.empty())
343 s
->formatter
->dump_string("Code", s
->err
.err_code
);
344 if (!s
->err
.message
.empty())
345 s
->formatter
->dump_string("Message", s
->err
.message
);
346 if (!s
->bucket_name
.empty()) // TODO: connect to expose_bucket
347 s
->formatter
->dump_string("BucketName", s
->bucket_name
);
348 if (!s
->trans_id
.empty()) // TODO: connect to expose_bucket or another toggle
349 s
->formatter
->dump_string("RequestId", s
->trans_id
);
350 s
->formatter
->dump_string("HostId", s
->host_id
);
351 if (s
->format
!= RGW_FORMAT_HTML
)
352 s
->formatter
->close_section();
360 #define STR_LEN_ENTRY(s) { s, sizeof(s) - 1 }
362 struct str_len meta_prefixes
[] = { STR_LEN_ENTRY("HTTP_X_AMZ"),
363 STR_LEN_ENTRY("HTTP_X_GOOG"),
364 STR_LEN_ENTRY("HTTP_X_DHO"),
365 STR_LEN_ENTRY("HTTP_X_RGW"),
366 STR_LEN_ENTRY("HTTP_X_OBJECT"),
367 STR_LEN_ENTRY("HTTP_X_CONTAINER"),
368 STR_LEN_ENTRY("HTTP_X_ACCOUNT"),
371 void req_info::init_meta_info(bool *found_bad_meta
)
375 for (const auto& kv
: env
->get_map()) {
377 const string
& header_name
= kv
.first
;
378 const string
& val
= kv
.second
;
379 for (int prefix_num
= 0; (prefix
= meta_prefixes
[prefix_num
].str
) != NULL
; prefix_num
++) {
380 int len
= meta_prefixes
[prefix_num
].len
;
381 const char *p
= header_name
.c_str();
382 if (strncmp(p
, prefix
, len
) == 0) {
383 dout(10) << "meta>> " << p
<< dendl
;
384 const char *name
= p
+len
; /* skip the prefix */
385 int name_len
= header_name
.size() - len
;
387 if (found_bad_meta
&& strncmp(name
, "_META_", name_len
) == 0)
388 *found_bad_meta
= true;
390 char name_low
[meta_prefixes
[0].len
+ name_len
+ 1];
391 snprintf(name_low
, meta_prefixes
[0].len
- 5 + name_len
+ 1, "%s%s", meta_prefixes
[0].str
+ 5 /* skip HTTP_ */, name
); // normalize meta prefix
393 for (j
= 0; name_low
[j
]; j
++) {
394 if (name_low
[j
] != '_')
395 name_low
[j
] = tolower(name_low
[j
]);
401 auto it
= x_meta_map
.find(name_low
);
402 if (it
!= x_meta_map
.end()) {
403 string old
= it
->second
;
404 boost::algorithm::trim_right(old
);
407 x_meta_map
[name_low
] = old
;
409 x_meta_map
[name_low
] = val
;
414 for (const auto& kv
: x_meta_map
) {
415 dout(10) << "x>> " << kv
.first
<< ":" << rgw::crypt_sanitize::x_meta_map
{kv
.first
, kv
.second
} << dendl
;
419 std::ostream
& operator<<(std::ostream
& oss
, const rgw_err
&err
)
421 oss
<< "rgw_err(http_ret=" << err
.http_ret
<< ", err_code='" << err
.err_code
<< "') ";
425 string
rgw_string_unquote(const string
& s
)
427 if (s
[0] != '"' || s
.size() < 2)
431 for (len
= s
.size(); len
> 2; --len
) {
432 if (s
[len
- 1] != ' ')
439 return s
.substr(1, len
- 2);
442 static bool check_str_end(const char *s
)
455 static bool check_gmt_end(const char *s
)
460 while (isspace(*s
)) {
464 /* check for correct timezone */
465 if ((strncmp(s
, "GMT", 3) != 0) &&
466 (strncmp(s
, "UTC", 3) != 0)) {
473 static bool parse_rfc850(const char *s
, struct tm
*t
)
475 memset(t
, 0, sizeof(*t
));
476 return check_gmt_end(strptime(s
, "%A, %d-%b-%y %H:%M:%S ", t
));
479 static bool parse_asctime(const char *s
, struct tm
*t
)
481 memset(t
, 0, sizeof(*t
));
482 return check_str_end(strptime(s
, "%a %b %d %H:%M:%S %Y", t
));
485 static bool parse_rfc1123(const char *s
, struct tm
*t
)
487 memset(t
, 0, sizeof(*t
));
488 return check_gmt_end(strptime(s
, "%a, %d %b %Y %H:%M:%S ", t
));
491 static bool parse_rfc1123_alt(const char *s
, struct tm
*t
)
493 memset(t
, 0, sizeof(*t
));
494 return check_str_end(strptime(s
, "%a, %d %b %Y %H:%M:%S %z", t
));
497 bool parse_rfc2616(const char *s
, struct tm
*t
)
499 return parse_rfc850(s
, t
) || parse_asctime(s
, t
) || parse_rfc1123(s
, t
) || parse_rfc1123_alt(s
,t
);
502 bool parse_iso8601(const char *s
, struct tm
*t
, uint32_t *pns
, bool extended_format
)
504 memset(t
, 0, sizeof(*t
));
510 if (extended_format
) {
511 p
= strptime(s
, "%Y-%m-%dT%T", t
);
513 p
= strptime(s
, "%Y-%m-%d %T", t
);
516 p
= strptime(s
, "%Y%m%dT%H%M%S", t
);
519 dout(0) << "parse_iso8601 failed" << dendl
;
522 const boost::string_view str
= rgw_trim_whitespace(boost::string_view(p
));
523 int len
= str
.size();
525 if (len
== 0 || (len
== 1 && str
[0] == 'Z'))
533 boost::string_view nsstr
= str
.substr(1, len
- 2);
534 int r
= stringtoul(nsstr
.to_string(), &ms
);
542 if (nsstr
.size() > 9) {
543 nsstr
= nsstr
.substr(0, 9);
546 uint64_t mul_table
[] = { 0,
558 *pns
= ms
* mul_table
[nsstr
.size()];
563 int parse_key_value(string
& in_str
, const char *delim
, string
& key
, string
& val
)
568 auto pos
= in_str
.find(delim
);
569 if (pos
== string::npos
)
572 key
= rgw_trim_whitespace(in_str
.substr(0, pos
));
573 val
= rgw_trim_whitespace(in_str
.substr(pos
+ 1));
578 int parse_key_value(string
& in_str
, string
& key
, string
& val
)
580 return parse_key_value(in_str
, "=", key
,val
);
583 boost::optional
<std::pair
<boost::string_view
, boost::string_view
>>
584 parse_key_value(const boost::string_view
& in_str
,
585 const boost::string_view
& delim
)
587 const size_t pos
= in_str
.find(delim
);
588 if (pos
== boost::string_view::npos
) {
592 const auto key
= rgw_trim_whitespace(in_str
.substr(0, pos
));
593 const auto val
= rgw_trim_whitespace(in_str
.substr(pos
+ 1));
595 return std::make_pair(key
, val
);
598 boost::optional
<std::pair
<boost::string_view
, boost::string_view
>>
599 parse_key_value(const boost::string_view
& in_str
)
601 return parse_key_value(in_str
, "=");
604 int parse_time(const char *time_str
, real_time
*time
)
609 if (!parse_rfc2616(time_str
, &tm
) && !parse_iso8601(time_str
, &tm
, &ns
)) {
613 time_t sec
= internal_timegm(&tm
);
614 *time
= utime_t(sec
, ns
).to_real_time();
619 #define TIME_BUF_SIZE 128
621 void rgw_to_iso8601(const real_time
& t
, char *dest
, int buf_size
)
625 char buf
[TIME_BUF_SIZE
];
627 time_t epoch
= ut
.sec();
628 struct tm
*tmp
= gmtime_r(&epoch
, &result
);
632 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%T", tmp
) == 0)
635 snprintf(dest
, buf_size
, "%s.%03dZ", buf
, (int)(ut
.usec() / 1000));
638 void rgw_to_iso8601(const real_time
& t
, string
*dest
)
640 char buf
[TIME_BUF_SIZE
];
641 rgw_to_iso8601(t
, buf
, sizeof(buf
));
646 string
rgw_to_asctime(const utime_t
& t
)
654 * calculate the sha1 value of a given msg and key
656 void calc_hmac_sha1(const char *key
, int key_len
,
657 const char *msg
, int msg_len
, char *dest
)
658 /* destination should be CEPH_CRYPTO_HMACSHA1_DIGESTSIZE bytes long */
660 HMACSHA1
hmac((const unsigned char *)key
, key_len
);
661 hmac
.Update((const unsigned char *)msg
, msg_len
);
662 hmac
.Final((unsigned char *)dest
);
666 * calculate the sha256 value of a given msg and key
668 void calc_hmac_sha256(const char *key
, int key_len
,
669 const char *msg
, int msg_len
, char *dest
)
671 char hash_sha256
[CEPH_CRYPTO_HMACSHA256_DIGESTSIZE
];
673 HMACSHA256
hmac((const unsigned char *)key
, key_len
);
674 hmac
.Update((const unsigned char *)msg
, msg_len
);
675 hmac
.Final((unsigned char *)hash_sha256
);
677 memcpy(dest
, hash_sha256
, CEPH_CRYPTO_HMACSHA256_DIGESTSIZE
);
680 using ceph::crypto::SHA256
;
683 * calculate the sha256 hash value of a given msg
685 sha256_digest_t
calc_hash_sha256(const boost::string_view
& msg
)
687 sha256_digest_t hash
;
690 hasher
.Update(reinterpret_cast<const unsigned char*>(msg
.data()), msg
.size());
691 hasher
.Final(hash
.v
);
696 SHA256
* calc_hash_sha256_open_stream()
701 void calc_hash_sha256_update_stream(SHA256
*hash
, const char *msg
, int len
)
703 hash
->Update((const unsigned char *)msg
, len
);
706 string
calc_hash_sha256_close_stream(SHA256
**phash
)
708 SHA256
*hash
= *phash
;
710 hash
= calc_hash_sha256_open_stream();
712 char hash_sha256
[CEPH_CRYPTO_HMACSHA256_DIGESTSIZE
];
714 hash
->Final((unsigned char *)hash_sha256
);
716 char hex_str
[(CEPH_CRYPTO_SHA256_DIGESTSIZE
* 2) + 1];
717 buf_to_hex((unsigned char *)hash_sha256
, CEPH_CRYPTO_SHA256_DIGESTSIZE
, hex_str
);
722 return std::string(hex_str
);
725 std::string
calc_hash_sha256_restart_stream(SHA256
**phash
)
727 const auto hash
= calc_hash_sha256_close_stream(phash
);
728 *phash
= calc_hash_sha256_open_stream();
733 int gen_rand_base64(CephContext
*cct
, char *dest
, int size
) /* size should be the required string size + 1 */
736 char tmp_dest
[size
+ 4]; /* so that there's space for the extra '=' characters, and some */
739 cct
->random()->get_bytes(buf
, sizeof(buf
));
741 ret
= ceph_armor(tmp_dest
, &tmp_dest
[sizeof(tmp_dest
)],
742 (const char *)buf
, ((const char *)buf
) + ((size
- 1) * 3 + 4 - 1) / 4);
744 lderr(cct
) << "ceph_armor failed" << dendl
;
747 tmp_dest
[ret
] = '\0';
748 memcpy(dest
, tmp_dest
, size
);
754 static const char alphanum_upper_table
[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
756 void gen_rand_alphanumeric_upper(CephContext
*cct
, char *dest
, int size
) /* size should be the required string size + 1 */
758 cct
->random()->get_bytes(dest
, size
);
761 for (i
=0; i
<size
- 1; i
++) {
762 int pos
= (unsigned)dest
[i
];
763 dest
[i
] = alphanum_upper_table
[pos
% (sizeof(alphanum_upper_table
) - 1)];
768 static const char alphanum_lower_table
[]="0123456789abcdefghijklmnopqrstuvwxyz";
770 void gen_rand_alphanumeric_lower(CephContext
*cct
, char *dest
, int size
) /* size should be the required string size + 1 */
772 cct
->random()->get_bytes(dest
, size
);
775 for (i
=0; i
<size
- 1; i
++) {
776 int pos
= (unsigned)dest
[i
];
777 dest
[i
] = alphanum_lower_table
[pos
% (sizeof(alphanum_lower_table
) - 1)];
782 void gen_rand_alphanumeric_lower(CephContext
*cct
, string
*str
, int length
)
784 char buf
[length
+ 1];
785 gen_rand_alphanumeric_lower(cct
, buf
, sizeof(buf
));
789 // this is basically a modified base64 charset, url friendly
790 static const char alphanum_table
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
792 void gen_rand_alphanumeric(CephContext
*cct
, char *dest
, int size
) /* size should be the required string size + 1 */
794 cct
->random()->get_bytes(dest
, size
);
797 for (i
=0; i
<size
- 1; i
++) {
798 int pos
= (unsigned)dest
[i
];
799 dest
[i
] = alphanum_table
[pos
& 63];
804 static const char alphanum_no_underscore_table
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
806 void gen_rand_alphanumeric_no_underscore(CephContext
*cct
, char *dest
, int size
) /* size should be the required string size + 1 */
808 cct
->random()->get_bytes(dest
, size
);
811 for (i
=0; i
<size
- 1; i
++) {
812 int pos
= (unsigned)dest
[i
];
813 dest
[i
] = alphanum_no_underscore_table
[pos
& 63];
818 static const char alphanum_plain_table
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
820 void gen_rand_alphanumeric_plain(CephContext
*cct
, char *dest
, int size
) /* size should be the required string size + 1 */
822 cct
->random()->get_bytes(dest
, size
);
825 for (i
=0; i
<size
- 1; i
++) {
826 int pos
= (unsigned)dest
[i
];
827 dest
[i
] = alphanum_plain_table
[pos
% (sizeof(alphanum_plain_table
) - 1)];
834 auto delim_pos
= str
.find('=');
837 if (delim_pos
== string::npos
) {
842 name
= str
.substr(0, delim_pos
);
843 val
= str
.substr(delim_pos
+ 1);
849 int RGWHTTPArgs::parse()
861 int fpos
= str
.find('&', pos
);
866 std::string nameval
= url_decode(str
.substr(pos
, fpos
- pos
), true);
867 NameVal
nv(std::move(nameval
));
868 int ret
= nv
.parse();
870 string
& name
= nv
.get_name();
871 string
& val
= nv
.get_val();
882 void RGWHTTPArgs::append(const string
& name
, const string
& val
)
884 if (name
.compare(0, sizeof(RGW_SYS_PARAM_PREFIX
) - 1, RGW_SYS_PARAM_PREFIX
) == 0) {
885 sys_val_map
[name
] = val
;
890 if ((name
.compare("acl") == 0) ||
891 (name
.compare("cors") == 0) ||
892 (name
.compare("notification") == 0) ||
893 (name
.compare("location") == 0) ||
894 (name
.compare("logging") == 0) ||
895 (name
.compare("usage") == 0) ||
896 (name
.compare("lifecycle") == 0) ||
897 (name
.compare("delete") == 0) ||
898 (name
.compare("uploads") == 0) ||
899 (name
.compare("partNumber") == 0) ||
900 (name
.compare("uploadId") == 0) ||
901 (name
.compare("versionId") == 0) ||
902 (name
.compare("start-date") == 0) ||
903 (name
.compare("end-date") == 0) ||
904 (name
.compare("versions") == 0) ||
905 (name
.compare("versioning") == 0) ||
906 (name
.compare("website") == 0) ||
907 (name
.compare("requestPayment") == 0) ||
908 (name
.compare("torrent") == 0) ||
909 (name
.compare("tagging") == 0) ||
910 (name
.compare("append") == 0) ||
911 (name
.compare("position") == 0)) {
912 sub_resources
[name
] = val
;
913 } else if (name
[0] == 'r') { // root of all evil
914 if ((name
.compare("response-content-type") == 0) ||
915 (name
.compare("response-content-language") == 0) ||
916 (name
.compare("response-expires") == 0) ||
917 (name
.compare("response-cache-control") == 0) ||
918 (name
.compare("response-content-disposition") == 0) ||
919 (name
.compare("response-content-encoding") == 0)) {
920 sub_resources
[name
] = val
;
921 has_resp_modifier
= true;
923 } else if ((name
.compare("subuser") == 0) ||
924 (name
.compare("key") == 0) ||
925 (name
.compare("caps") == 0) ||
926 (name
.compare("index") == 0) ||
927 (name
.compare("policy") == 0) ||
928 (name
.compare("quota") == 0) ||
929 (name
.compare("list") == 0) ||
930 (name
.compare("object") == 0)) {
932 if (!admin_subresource_added
) {
933 sub_resources
[name
] = "";
934 admin_subresource_added
= true;
939 const string
& RGWHTTPArgs::get(const string
& name
, bool *exists
) const
941 auto iter
= val_map
.find(name
);
942 bool e
= (iter
!= std::end(val_map
));
950 boost::optional
<const std::string
&>
951 RGWHTTPArgs::get_optional(const std::string
& name
) const
954 const std::string
& value
= get(name
, &exists
);
962 int RGWHTTPArgs::get_bool(const string
& name
, bool *val
, bool *exists
)
964 map
<string
, string
>::iterator iter
;
965 iter
= val_map
.find(name
);
966 bool e
= (iter
!= val_map
.end());
971 const char *s
= iter
->second
.c_str();
973 if (strcasecmp(s
, "false") == 0) {
975 } else if (strcasecmp(s
, "true") == 0) {
985 int RGWHTTPArgs::get_bool(const char *name
, bool *val
, bool *exists
)
988 return get_bool(s
, val
, exists
);
991 void RGWHTTPArgs::get_bool(const char *name
, bool *val
, bool def_val
)
994 if ((get_bool(name
, val
, &exists
) < 0) ||
1000 int RGWHTTPArgs::get_int(const char *name
, int *val
, int def_val
)
1002 bool exists
= false;
1004 val_str
= get(name
, &exists
);
1012 *val
= (int)strict_strtol(val_str
.c_str(), 10, &err
);
1020 string
RGWHTTPArgs::sys_get(const string
& name
, bool * const exists
) const
1022 const auto iter
= sys_val_map
.find(name
);
1023 const bool e
= (iter
!= sys_val_map
.end());
1029 return e
? iter
->second
: string();
1032 bool rgw_transport_is_secure(CephContext
*cct
, const RGWEnv
& env
)
1034 const auto& m
= env
.get_map();
1035 // frontend connected with ssl
1036 if (m
.count("SERVER_PORT_SECURE")) {
1039 // ignore proxy headers unless explicitly enabled
1040 if (!cct
->_conf
->rgw_trust_forwarded_https
) {
1043 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
1044 // Forwarded: by=<identifier>; for=<identifier>; host=<host>; proto=<http|https>
1045 auto i
= m
.find("HTTP_FORWARDED");
1046 if (i
!= m
.end() && i
->second
.find("proto=https") != std::string::npos
) {
1049 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
1050 i
= m
.find("HTTP_X_FORWARDED_PROTO");
1051 if (i
!= m
.end() && i
->second
== "https") {
1058 Effect
eval_or_pass(const boost::optional
<Policy
>& policy
,
1059 const rgw::IAM::Environment
& env
,
1060 boost::optional
<const rgw::auth::Identity
&> id
,
1064 return Effect::Pass
;
1066 return policy
->eval(env
, id
, op
, arn
);
1071 Effect
eval_user_policies(const vector
<Policy
>& user_policies
,
1072 const rgw::IAM::Environment
& env
,
1073 boost::optional
<const rgw::auth::Identity
&> id
,
1076 auto usr_policy_res
= Effect::Pass
, prev_res
= Effect::Pass
;
1077 for (auto& user_policy
: user_policies
) {
1078 if (usr_policy_res
= eval_or_pass(user_policy
, env
, id
, op
, arn
); usr_policy_res
== Effect::Deny
)
1079 return usr_policy_res
;
1080 else if (usr_policy_res
== Effect::Allow
)
1081 prev_res
= Effect::Allow
;
1082 else if (usr_policy_res
== Effect::Pass
&& prev_res
== Effect::Allow
)
1083 usr_policy_res
= Effect::Allow
;
1085 return usr_policy_res
;
1088 bool verify_user_permission(const DoutPrefixProvider
* dpp
,
1089 struct req_state
* const s
,
1090 RGWAccessControlPolicy
* const user_acl
,
1091 const vector
<rgw::IAM::Policy
>& user_policies
,
1092 const rgw::IAM::ARN
& res
,
1095 auto usr_policy_res
= eval_user_policies(user_policies
, s
->env
, boost::none
, op
, res
);
1096 if (usr_policy_res
== Effect::Deny
) {
1100 if (usr_policy_res
== Effect::Allow
) {
1104 if (op
== rgw::IAM::s3CreateBucket
|| op
== rgw::IAM::s3ListAllMyBuckets
) {
1105 auto perm
= op_to_perm(op
);
1107 return verify_user_permission_no_policy(dpp
, s
, user_acl
, perm
);
1113 bool verify_user_permission_no_policy(const DoutPrefixProvider
* dpp
, struct req_state
* const s
,
1114 RGWAccessControlPolicy
* const user_acl
,
1117 if (s
->auth
.identity
->get_identity_type() == TYPE_ROLE
)
1120 /* S3 doesn't support account ACLs. */
1124 if ((perm
& (int)s
->perm_mask
) != perm
)
1127 return user_acl
->verify_permission(dpp
, *s
->auth
.identity
, perm
, perm
);
1130 bool verify_user_permission(const DoutPrefixProvider
* dpp
,
1131 struct req_state
* const s
,
1132 const rgw::IAM::ARN
& res
,
1135 return verify_user_permission(dpp
, s
, s
->user_acl
.get(), s
->iam_user_policies
, res
, op
);
1138 bool verify_user_permission_no_policy(const DoutPrefixProvider
* dpp
,
1139 struct req_state
* const s
,
1142 return verify_user_permission_no_policy(dpp
, s
, s
->user_acl
.get(), perm
);
1145 bool verify_requester_payer_permission(struct req_state
*s
)
1147 if (!s
->bucket_info
.requester_pays
)
1150 if (s
->auth
.identity
->is_owner_of(s
->bucket_info
.owner
))
1153 if (s
->auth
.identity
->is_anonymous()) {
1157 const char *request_payer
= s
->info
.env
->get("HTTP_X_AMZ_REQUEST_PAYER");
1158 if (!request_payer
) {
1160 request_payer
= s
->info
.args
.get("x-amz-request-payer", &exists
).c_str();
1166 if (strcasecmp(request_payer
, "requester") == 0) {
1173 bool verify_bucket_permission(const DoutPrefixProvider
* dpp
,
1174 struct req_state
* const s
,
1175 const rgw_bucket
& bucket
,
1176 RGWAccessControlPolicy
* const user_acl
,
1177 RGWAccessControlPolicy
* const bucket_acl
,
1178 const boost::optional
<Policy
>& bucket_policy
,
1179 const vector
<Policy
>& user_policies
,
1182 if (!verify_requester_payer_permission(s
))
1185 auto usr_policy_res
= eval_user_policies(user_policies
, s
->env
, boost::none
, op
, ARN(bucket
));
1186 if (usr_policy_res
== Effect::Deny
)
1189 auto r
= eval_or_pass(bucket_policy
, s
->env
, *s
->auth
.identity
,
1191 if (r
== Effect::Allow
)
1192 // It looks like S3 ACLs only GRANT permissions rather than
1193 // denying them, so this should be safe.
1195 else if (r
== Effect::Deny
)
1197 else if (usr_policy_res
== Effect::Allow
) // r is Effect::Pass at this point
1200 const auto perm
= op_to_perm(op
);
1202 return verify_bucket_permission_no_policy(dpp
, s
, user_acl
, bucket_acl
, perm
);
1205 bool verify_bucket_permission_no_policy(const DoutPrefixProvider
* dpp
, struct req_state
* const s
,
1206 RGWAccessControlPolicy
* const user_acl
,
1207 RGWAccessControlPolicy
* const bucket_acl
,
1213 if ((perm
& (int)s
->perm_mask
) != perm
)
1216 if (bucket_acl
->verify_permission(dpp
, *s
->auth
.identity
, perm
, perm
,
1217 s
->info
.env
->get("HTTP_REFERER")))
1223 return user_acl
->verify_permission(dpp
, *s
->auth
.identity
, perm
, perm
);
1226 bool verify_bucket_permission_no_policy(const DoutPrefixProvider
* dpp
, struct req_state
* const s
, const int perm
)
1228 if (!verify_requester_payer_permission(s
))
1231 return verify_bucket_permission_no_policy(dpp
,
1234 s
->bucket_acl
.get(),
1238 bool verify_bucket_permission(const DoutPrefixProvider
* dpp
, struct req_state
* const s
, const uint64_t op
)
1240 return verify_bucket_permission(dpp
,
1244 s
->bucket_acl
.get(),
1246 s
->iam_user_policies
,
1250 // Authorize anyone permitted by the policy and the bucket owner
1251 // unless explicitly denied by the policy.
1253 int verify_bucket_owner_or_policy(struct req_state
* const s
,
1256 auto e
= eval_or_pass(s
->iam_policy
,
1257 s
->env
, *s
->auth
.identity
,
1258 op
, ARN(s
->bucket
));
1259 if (e
== Effect::Allow
||
1260 (e
== Effect::Pass
&&
1261 s
->auth
.identity
->is_owner_of(s
->bucket_owner
.get_id()))) {
1269 static inline bool check_deferred_bucket_perms(const DoutPrefixProvider
* dpp
,
1270 struct req_state
* const s
,
1271 const rgw_bucket
& bucket
,
1272 RGWAccessControlPolicy
* const user_acl
,
1273 RGWAccessControlPolicy
* const bucket_acl
,
1274 const boost::optional
<Policy
>& bucket_policy
,
1275 const vector
<Policy
>& user_policies
,
1276 const uint8_t deferred_check
,
1279 return (s
->defer_to_bucket_acls
== deferred_check \
1280 && verify_bucket_permission(dpp
, s
, bucket
, user_acl
, bucket_acl
, bucket_policy
, user_policies
,op
));
1283 static inline bool check_deferred_bucket_only_acl(const DoutPrefixProvider
* dpp
,
1284 struct req_state
* const s
,
1285 RGWAccessControlPolicy
* const user_acl
,
1286 RGWAccessControlPolicy
* const bucket_acl
,
1287 const uint8_t deferred_check
,
1290 return (s
->defer_to_bucket_acls
== deferred_check \
1291 && verify_bucket_permission_no_policy(dpp
, s
, user_acl
, bucket_acl
, perm
));
1294 bool verify_object_permission(const DoutPrefixProvider
* dpp
, struct req_state
* const s
,
1296 RGWAccessControlPolicy
* const user_acl
,
1297 RGWAccessControlPolicy
* const bucket_acl
,
1298 RGWAccessControlPolicy
* const object_acl
,
1299 const boost::optional
<Policy
>& bucket_policy
,
1300 const vector
<Policy
>& user_policies
,
1303 if (!verify_requester_payer_permission(s
))
1306 auto usr_policy_res
= eval_user_policies(user_policies
, s
->env
, boost::none
, op
, ARN(obj
));
1307 if (usr_policy_res
== Effect::Deny
)
1310 auto r
= eval_or_pass(bucket_policy
, s
->env
, *s
->auth
.identity
, op
, ARN(obj
));
1311 if (r
== Effect::Allow
)
1312 // It looks like S3 ACLs only GRANT permissions rather than
1313 // denying them, so this should be safe.
1315 else if (r
== Effect::Deny
)
1317 else if (usr_policy_res
== Effect::Allow
)
1320 const auto perm
= op_to_perm(op
);
1322 if (check_deferred_bucket_perms(dpp
, s
, obj
.bucket
, user_acl
, bucket_acl
, bucket_policy
,
1323 user_policies
, RGW_DEFER_TO_BUCKET_ACLS_RECURSE
, op
) ||
1324 check_deferred_bucket_perms(dpp
, s
, obj
.bucket
, user_acl
, bucket_acl
, bucket_policy
,
1325 user_policies
, RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL
, rgw::IAM::s3All
)) {
1333 bool ret
= object_acl
->verify_permission(dpp
, *s
->auth
.identity
, s
->perm_mask
, perm
);
1338 if (!s
->cct
->_conf
->rgw_enforce_swift_acls
)
1341 if ((perm
& (int)s
->perm_mask
) != perm
)
1345 if (perm
& (RGW_PERM_READ
| RGW_PERM_READ_ACP
))
1346 swift_perm
|= RGW_PERM_READ_OBJS
;
1347 if (perm
& RGW_PERM_WRITE
)
1348 swift_perm
|= RGW_PERM_WRITE_OBJS
;
1353 /* we already verified the user mask above, so we pass swift_perm as the mask here,
1354 otherwise the mask might not cover the swift permissions bits */
1355 if (bucket_acl
->verify_permission(dpp
, *s
->auth
.identity
, swift_perm
, swift_perm
,
1356 s
->info
.env
->get("HTTP_REFERER")))
1362 return user_acl
->verify_permission(dpp
, *s
->auth
.identity
, swift_perm
, swift_perm
);
1365 bool verify_object_permission_no_policy(const DoutPrefixProvider
* dpp
,
1366 struct req_state
* const s
,
1367 RGWAccessControlPolicy
* const user_acl
,
1368 RGWAccessControlPolicy
* const bucket_acl
,
1369 RGWAccessControlPolicy
* const object_acl
,
1372 if (check_deferred_bucket_only_acl(dpp
, s
, user_acl
, bucket_acl
, RGW_DEFER_TO_BUCKET_ACLS_RECURSE
, perm
) ||
1373 check_deferred_bucket_only_acl(dpp
, s
, user_acl
, bucket_acl
, RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL
, RGW_PERM_FULL_CONTROL
)) {
1381 bool ret
= object_acl
->verify_permission(dpp
, *s
->auth
.identity
, s
->perm_mask
, perm
);
1386 if (!s
->cct
->_conf
->rgw_enforce_swift_acls
)
1389 if ((perm
& (int)s
->perm_mask
) != perm
)
1393 if (perm
& (RGW_PERM_READ
| RGW_PERM_READ_ACP
))
1394 swift_perm
|= RGW_PERM_READ_OBJS
;
1395 if (perm
& RGW_PERM_WRITE
)
1396 swift_perm
|= RGW_PERM_WRITE_OBJS
;
1401 /* we already verified the user mask above, so we pass swift_perm as the mask here,
1402 otherwise the mask might not cover the swift permissions bits */
1403 if (bucket_acl
->verify_permission(dpp
, *s
->auth
.identity
, swift_perm
, swift_perm
,
1404 s
->info
.env
->get("HTTP_REFERER")))
1410 return user_acl
->verify_permission(dpp
, *s
->auth
.identity
, swift_perm
, swift_perm
);
1413 bool verify_object_permission_no_policy(const DoutPrefixProvider
* dpp
, struct req_state
*s
, int perm
)
1415 if (!verify_requester_payer_permission(s
))
1418 return verify_object_permission_no_policy(dpp
,
1421 s
->bucket_acl
.get(),
1422 s
->object_acl
.get(),
1426 bool verify_object_permission(const DoutPrefixProvider
* dpp
, struct req_state
*s
, uint64_t op
)
1428 return verify_object_permission(dpp
,
1430 rgw_obj(s
->bucket
, s
->object
),
1432 s
->bucket_acl
.get(),
1433 s
->object_acl
.get(),
1435 s
->iam_user_policies
,
1445 memset(table
, -1, sizeof(table
));
1447 for (i
= '0'; i
<='9'; i
++)
1449 for (i
= 'A'; i
<='F'; i
++)
1450 table
[i
] = i
- 'A' + 0xa;
1451 for (i
= 'a'; i
<='f'; i
++)
1452 table
[i
] = i
- 'a' + 0xa;
1455 char to_num(char c
) {
1456 return table
[(int)c
];
1460 static char hex_to_num(char c
)
1462 static HexTable hex_table
;
1463 return hex_table
.to_num(c
);
1466 std::string
url_decode(const boost::string_view
& src_str
, bool in_query
)
1468 std::string dest_str
;
1469 dest_str
.reserve(src_str
.length() + 1);
1471 for (auto src
= std::begin(src_str
); src
!= std::end(src_str
); ++src
) {
1473 if (!in_query
|| *src
!= '+') {
1477 dest_str
.push_back(*src
);
1479 dest_str
.push_back(' ');
1482 /* 3 == strlen("%%XX") */
1483 if (std::distance(src
, std::end(src_str
)) < 3) {
1488 const char c1
= hex_to_num(*src
++);
1489 const char c2
= hex_to_num(*src
);
1490 if (c1
< 0 || c2
< 0) {
1491 return std::string();
1493 dest_str
.push_back(c1
<< 4 | c2
);
1501 void rgw_uri_escape_char(char c
, string
& dst
)
1504 snprintf(buf
, sizeof(buf
), "%%%.2X", (int)(unsigned char)c
);
1508 static bool char_needs_url_encoding(char c
)
1510 if (c
<= 0x20 || c
>= 0x7f)
1540 void url_encode(const string
& src
, string
& dst
, bool encode_slash
)
1542 const char *p
= src
.c_str();
1543 for (unsigned i
= 0; i
< src
.size(); i
++, p
++) {
1544 if ((!encode_slash
&& *p
== 0x2F) || !char_needs_url_encoding(*p
)) {
1547 rgw_uri_escape_char(*p
, dst
);
1552 std::string
url_encode(const std::string
& src
, bool encode_slash
)
1555 url_encode(src
, dst
, encode_slash
);
1560 string
rgw_trim_whitespace(const string
& src
)
1567 for (; start
!= (int)src
.size(); start
++) {
1568 if (!isspace(src
[start
]))
1572 int end
= src
.size() - 1;
1577 for (; end
> start
; end
--) {
1578 if (!isspace(src
[end
]))
1582 return src
.substr(start
, end
- start
+ 1);
1585 boost::string_view
rgw_trim_whitespace(const boost::string_view
& src
)
1587 boost::string_view res
= src
;
1589 while (res
.size() > 0 && std::isspace(res
.front())) {
1590 res
.remove_prefix(1);
1592 while (res
.size() > 0 && std::isspace(res
.back())) {
1593 res
.remove_suffix(1);
1598 string
rgw_trim_quotes(const string
& val
)
1600 string s
= rgw_trim_whitespace(val
);
1605 int end
= s
.size() - 1;
1606 int quotes_count
= 0;
1608 if (s
[start
] == '"') {
1612 if (s
[end
] == '"') {
1616 if (quotes_count
== 2) {
1617 return s
.substr(start
, end
- start
+ 1);
1622 struct rgw_name_to_flag
{
1623 const char *type_name
;
1627 static int parse_list_of_flags(struct rgw_name_to_flag
*mapping
,
1628 const string
& str
, uint32_t *perm
)
1631 get_str_list(str
, strs
);
1632 list
<string
>::iterator iter
;
1634 for (iter
= strs
.begin(); iter
!= strs
.end(); ++iter
) {
1636 for (int i
= 0; mapping
[i
].type_name
; i
++) {
1637 if (s
.compare(mapping
[i
].type_name
) == 0)
1638 v
|= mapping
[i
].flag
;
1646 static struct rgw_name_to_flag cap_names
[] = { {"*", RGW_CAP_ALL
},
1647 {"read", RGW_CAP_READ
},
1648 {"write", RGW_CAP_WRITE
},
1651 int RGWUserCaps::parse_cap_perm(const string
& str
, uint32_t *perm
)
1653 return parse_list_of_flags(cap_names
, str
, perm
);
1656 int RGWUserCaps::get_cap(const string
& cap
, string
& type
, uint32_t *pperm
)
1658 int pos
= cap
.find('=');
1660 type
= rgw_trim_whitespace(cap
.substr(0, pos
));
1663 if (!is_valid_cap_type(type
))
1664 return -ERR_INVALID_CAP
;
1668 if (pos
< (int)cap
.size() - 1) {
1669 cap_perm
= cap
.substr(pos
+ 1);
1670 int r
= RGWUserCaps::parse_cap_perm(cap_perm
, &perm
);
1680 int RGWUserCaps::add_cap(const string
& cap
)
1685 int r
= get_cap(cap
, type
, &perm
);
1694 int RGWUserCaps::remove_cap(const string
& cap
)
1699 int r
= get_cap(cap
, type
, &perm
);
1703 map
<string
, uint32_t>::iterator iter
= caps
.find(type
);
1704 if (iter
== caps
.end())
1707 uint32_t& old_perm
= iter
->second
;
1715 int RGWUserCaps::add_from_string(const string
& str
)
1719 auto end
= str
.find(';', start
);
1720 if (end
== string::npos
)
1723 int r
= add_cap(str
.substr(start
, end
- start
));
1728 } while (start
< (int)str
.size());
1733 int RGWUserCaps::remove_from_string(const string
& str
)
1737 auto end
= str
.find(';', start
);
1738 if (end
== string::npos
)
1741 int r
= remove_cap(str
.substr(start
, end
- start
));
1746 } while (start
< (int)str
.size());
1751 void RGWUserCaps::dump(Formatter
*f
) const
1756 void RGWUserCaps::dump(Formatter
*f
, const char *name
) const
1758 f
->open_array_section(name
);
1759 map
<string
, uint32_t>::const_iterator iter
;
1760 for (iter
= caps
.begin(); iter
!= caps
.end(); ++iter
)
1762 f
->open_object_section("cap");
1763 f
->dump_string("type", iter
->first
);
1764 uint32_t perm
= iter
->second
;
1766 for (int i
=0; cap_names
[i
].type_name
; i
++) {
1767 if ((perm
& cap_names
[i
].flag
) == cap_names
[i
].flag
) {
1768 if (perm_str
.size())
1769 perm_str
.append(", ");
1771 perm_str
.append(cap_names
[i
].type_name
);
1772 perm
&= ~cap_names
[i
].flag
;
1775 if (perm_str
.empty())
1776 perm_str
= "<none>";
1778 f
->dump_string("perm", perm_str
);
1789 void decode_json(JSONObj
*obj
) {
1790 JSONDecoder::decode_json("type", type
, obj
);
1792 JSONDecoder::decode_json("perm", perm_str
, obj
);
1793 if (RGWUserCaps::parse_cap_perm(perm_str
, &perm
) < 0) {
1794 throw JSONDecoder::err("failed to parse permissions");
1799 void RGWUserCaps::decode_json(JSONObj
*obj
)
1801 list
<RGWUserCap
> caps_list
;
1802 decode_json_obj(caps_list
, obj
);
1804 list
<RGWUserCap
>::iterator iter
;
1805 for (iter
= caps_list
.begin(); iter
!= caps_list
.end(); ++iter
) {
1806 RGWUserCap
& cap
= *iter
;
1807 caps
[cap
.type
] = cap
.perm
;
1811 int RGWUserCaps::check_cap(const string
& cap
, uint32_t perm
)
1813 map
<string
, uint32_t>::iterator iter
= caps
.find(cap
);
1815 if ((iter
== caps
.end()) ||
1816 (iter
->second
& perm
) != perm
) {
1823 bool RGWUserCaps::is_valid_cap_type(const string
& tp
)
1825 static const char *cap_type
[] = { "user",
1837 for (unsigned int i
= 0; i
< sizeof(cap_type
) / sizeof(char *); ++i
) {
1838 if (tp
.compare(cap_type
[i
]) == 0) {
1846 void rgw_pool::from_str(const string
& s
)
1848 size_t pos
= rgw_unescape_str(s
, 0, '\\', ':', &name
);
1849 if (pos
!= string::npos
) {
1850 pos
= rgw_unescape_str(s
, pos
, '\\', ':', &ns
);
1851 /* ignore return; if pos != string::npos it means that we had a colon
1852 * in the middle of ns that wasn't escaped, we're going to stop there
1857 string
rgw_pool::to_str() const
1860 rgw_escape_str(name
, '\\', ':', &esc_name
);
1865 rgw_escape_str(ns
, '\\', ':', &esc_ns
);
1866 return esc_name
+ ":" + esc_ns
;
1869 void rgw_raw_obj::decode_from_rgw_obj(bufferlist::const_iterator
& bl
)
1873 decode(old_obj
, bl
);
1875 get_obj_bucket_and_oid_loc(old_obj
, oid
, loc
);
1876 pool
= old_obj
.get_explicit_data_pool();
1879 std::string
rgw_bucket::get_key(char tenant_delim
, char id_delim
, size_t reserve
) const
1881 const size_t max_len
= tenant
.size() + sizeof(tenant_delim
) +
1882 name
.size() + sizeof(id_delim
) + bucket_id
.size() + reserve
;
1885 key
.reserve(max_len
);
1886 if (!tenant
.empty() && tenant_delim
) {
1888 key
.append(1, tenant_delim
);
1891 if (!bucket_id
.empty() && id_delim
) {
1892 key
.append(1, id_delim
);
1893 key
.append(bucket_id
);
1898 std::string
rgw_bucket_shard::get_key(char tenant_delim
, char id_delim
,
1899 char shard_delim
) const
1901 static constexpr size_t shard_len
{12}; // ":4294967295\0"
1902 auto key
= bucket
.get_key(tenant_delim
, id_delim
, shard_len
);
1903 if (shard_id
>= 0 && shard_delim
) {
1904 key
.append(1, shard_delim
);
1905 key
.append(std::to_string(shard_id
));
1910 static struct rgw_name_to_flag op_type_mapping
[] = { {"*", RGW_OP_TYPE_ALL
},
1911 {"read", RGW_OP_TYPE_READ
},
1912 {"write", RGW_OP_TYPE_WRITE
},
1913 {"delete", RGW_OP_TYPE_DELETE
},
1917 int rgw_parse_op_type_list(const string
& str
, uint32_t *perm
)
1919 return parse_list_of_flags(op_type_mapping
, str
, perm
);
1922 bool match_policy(boost::string_view pattern
, boost::string_view input
,
1925 const uint32_t flag2
= flag
& (MATCH_POLICY_ACTION
|MATCH_POLICY_ARN
) ?
1926 MATCH_CASE_INSENSITIVE
: 0;
1927 const bool colonblocks
= !(flag
& (MATCH_POLICY_RESOURCE
|
1928 MATCH_POLICY_STRING
));
1930 const auto npos
= boost::string_view::npos
;
1931 boost::string_view::size_type last_pos_input
= 0, last_pos_pattern
= 0;
1933 auto cur_pos_input
= colonblocks
? input
.find(":", last_pos_input
) : npos
;
1934 auto cur_pos_pattern
=
1935 colonblocks
? pattern
.find(":", last_pos_pattern
) : npos
;
1937 auto substr_input
= input
.substr(last_pos_input
, cur_pos_input
);
1938 auto substr_pattern
= pattern
.substr(last_pos_pattern
, cur_pos_pattern
);
1940 if (!match_wildcards(substr_pattern
, substr_input
, flag2
))
1943 if (cur_pos_pattern
== npos
)
1944 return cur_pos_input
== npos
;
1945 if (cur_pos_input
== npos
)
1948 last_pos_pattern
= cur_pos_pattern
+ 1;
1949 last_pos_input
= cur_pos_input
+ 1;
1954 * make attrs look-like-this
1955 * converts underscores to dashes
1957 string
lowercase_dash_http_attr(const string
& orig
)
1959 const char *s
= orig
.c_str();
1960 char buf
[orig
.size() + 1];
1961 buf
[orig
.size()] = '\0';
1963 for (size_t i
= 0; i
< orig
.size(); ++i
, ++s
) {
1969 buf
[i
] = tolower(*s
);
1976 * make attrs Look-Like-This
1977 * converts underscores to dashes
1979 string
camelcase_dash_http_attr(const string
& orig
)
1981 const char *s
= orig
.c_str();
1982 char buf
[orig
.size() + 1];
1983 buf
[orig
.size()] = '\0';
1985 bool last_sep
= true;
1987 for (size_t i
= 0; i
< orig
.size(); ++i
, ++s
) {
1996 buf
[i
] = toupper(*s
);
1998 buf
[i
] = tolower(*s
);