]> git.proxmox.com Git - ceph.git/blame - ceph/src/rgw/rgw_rest_swift.cc
bump version to 15.2.11-pve1
[ceph.git] / ceph / src / rgw / rgw_rest_swift.cc
CommitLineData
7c673cae 1// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
9f95a23c 2// vim: ts=8 sw=2 smarttab ft=cpp
7c673cae
FG
3
4#include <boost/algorithm/string/predicate.hpp>
3efd9988 5#include <boost/format.hpp>
7c673cae
FG
6#include <boost/optional.hpp>
7#include <boost/utility/in_place_factory.hpp>
8
11fdf7f2 9#include "include/ceph_assert.h"
7c673cae
FG
10#include "ceph_ver.h"
11
12#include "common/Formatter.h"
13#include "common/utf8.h"
14#include "common/ceph_json.h"
15
16#include "rgw_rest_swift.h"
17#include "rgw_acl_swift.h"
18#include "rgw_cors_swift.h"
19#include "rgw_formats.h"
20#include "rgw_client_io.h"
9f95a23c 21#include "rgw_compression.h"
7c673cae
FG
22
23#include "rgw_auth.h"
24#include "rgw_swift_auth.h"
25
26#include "rgw_request.h"
27#include "rgw_process.h"
28
11fdf7f2
TL
29#include "rgw_zone.h"
30
31#include "services/svc_zone.h"
32
7c673cae
FG
33#include <array>
34#include <sstream>
35#include <memory>
36
37#include <boost/utility/string_ref.hpp>
38
39#define dout_context g_ceph_context
40#define dout_subsys ceph_subsys_rgw
41
42int RGWListBuckets_ObjStore_SWIFT::get_params()
43{
44 prefix = s->info.args.get("prefix");
45 marker = s->info.args.get("marker");
46 end_marker = s->info.args.get("end_marker");
3efd9988 47 wants_reversed = s->info.args.exists("reverse");
7c673cae 48
3efd9988
FG
49 if (wants_reversed) {
50 std::swap(marker, end_marker);
51 }
52
53 std::string limit_str = s->info.args.get("limit");
7c673cae 54 if (!limit_str.empty()) {
3efd9988 55 std::string err;
7c673cae
FG
56 long l = strict_strtol(limit_str.c_str(), 10, &err);
57 if (!err.empty()) {
58 return -EINVAL;
59 }
60
61 if (l > (long)limit_max || l < 0) {
62 return -ERR_PRECONDITION_FAILED;
63 }
64
65 limit = (uint64_t)l;
66 }
67
224ce89b 68 if (s->cct->_conf->rgw_swift_need_stats) {
7c673cae
FG
69 bool stats, exists;
70 int r = s->info.args.get_bool("stats", &stats, &exists);
71
72 if (r < 0) {
73 return r;
74 }
75
76 if (exists) {
77 need_stats = stats;
78 }
224ce89b
WB
79 } else {
80 need_stats = false;
7c673cae
FG
81 }
82
83 return 0;
84}
85
86static void dump_account_metadata(struct req_state * const s,
3efd9988 87 const RGWUsageStats& global_stats,
11fdf7f2 88 const std::map<std::string, RGWUsageStats> &policies_stats,
7c673cae
FG
89 /* const */map<string, bufferlist>& attrs,
90 const RGWQuotaInfo& quota,
91 const RGWAccessControlPolicy_SWIFTAcct &policy)
92{
93 /* Adding X-Timestamp to keep align with Swift API */
94 dump_header(s, "X-Timestamp", ceph_clock_now());
95
3efd9988
FG
96 dump_header(s, "X-Account-Container-Count", global_stats.buckets_count);
97 dump_header(s, "X-Account-Object-Count", global_stats.objects_count);
98 dump_header(s, "X-Account-Bytes-Used", global_stats.bytes_used);
99 dump_header(s, "X-Account-Bytes-Used-Actual", global_stats.bytes_used_rounded);
100
101 for (const auto& kv : policies_stats) {
102 const auto& policy_name = camelcase_dash_http_attr(kv.first);
103 const auto& policy_stats = kv.second;
104
105 dump_header_infixed(s, "X-Account-Storage-Policy-", policy_name,
106 "-Container-Count", policy_stats.buckets_count);
107 dump_header_infixed(s, "X-Account-Storage-Policy-", policy_name,
108 "-Object-Count", policy_stats.objects_count);
109 dump_header_infixed(s, "X-Account-Storage-Policy-", policy_name,
110 "-Bytes-Used", policy_stats.bytes_used);
111 dump_header_infixed(s, "X-Account-Storage-Policy-", policy_name,
112 "-Bytes-Used-Actual", policy_stats.bytes_used_rounded);
113 }
7c673cae
FG
114
115 /* Dump TempURL-related stuff */
116 if (s->perm_mask == RGW_PERM_FULL_CONTROL) {
9f95a23c
TL
117 auto iter = s->user->get_info().temp_url_keys.find(0);
118 if (iter != std::end(s->user->get_info().temp_url_keys) && ! iter->second.empty()) {
7c673cae
FG
119 dump_header(s, "X-Account-Meta-Temp-Url-Key", iter->second);
120 }
121
9f95a23c
TL
122 iter = s->user->get_info().temp_url_keys.find(1);
123 if (iter != std::end(s->user->get_info().temp_url_keys) && ! iter->second.empty()) {
7c673cae
FG
124 dump_header(s, "X-Account-Meta-Temp-Url-Key-2", iter->second);
125 }
126 }
127
128 /* Dump quota headers. */
129 if (quota.enabled) {
130 if (quota.max_size >= 0) {
131 dump_header(s, "X-Account-Meta-Quota-Bytes", quota.max_size);
132 }
133
134 /* Limit on the number of objects in a given account is a RadosGW's
135 * extension. Swift's account quota WSGI filter doesn't support it. */
136 if (quota.max_objects >= 0) {
137 dump_header(s, "X-Account-Meta-Quota-Count", quota.max_objects);
138 }
139 }
140
141 /* Dump user-defined metadata items and generic attrs. */
142 const size_t PREFIX_LEN = sizeof(RGW_ATTR_META_PREFIX) - 1;
143 map<string, bufferlist>::iterator iter;
144 for (iter = attrs.lower_bound(RGW_ATTR_PREFIX); iter != attrs.end(); ++iter) {
145 const char *name = iter->first.c_str();
146 map<string, string>::const_iterator geniter = rgw_to_http_attrs.find(name);
147
148 if (geniter != rgw_to_http_attrs.end()) {
149 dump_header(s, geniter->second, iter->second);
150 } else if (strncmp(name, RGW_ATTR_META_PREFIX, PREFIX_LEN) == 0) {
151 dump_header_prefixed(s, "X-Account-Meta-",
152 camelcase_dash_http_attr(name + PREFIX_LEN),
153 iter->second);
154 }
155 }
156
157 /* Dump account ACLs */
224ce89b
WB
158 auto account_acls = policy.to_str();
159 if (account_acls) {
160 dump_header(s, "X-Account-Access-Control", std::move(*account_acls));
7c673cae
FG
161 }
162}
163
164void RGWListBuckets_ObjStore_SWIFT::send_response_begin(bool has_buckets)
165{
166 if (op_ret) {
167 set_req_state_err(s, op_ret);
168 } else if (!has_buckets && s->format == RGW_FORMAT_PLAIN) {
169 op_ret = STATUS_NO_CONTENT;
170 set_req_state_err(s, op_ret);
171 }
172
173 if (! s->cct->_conf->rgw_swift_enforce_content_length) {
174 /* Adding account stats in the header to keep align with Swift API */
175 dump_account_metadata(s,
3efd9988
FG
176 global_stats,
177 policies_stats,
7c673cae
FG
178 attrs,
179 user_quota,
180 static_cast<RGWAccessControlPolicy_SWIFTAcct&>(*s->user_acl));
181 dump_errno(s);
11fdf7f2 182 dump_header(s, "Accept-Ranges", "bytes");
7c673cae
FG
183 end_header(s, NULL, NULL, NO_CONTENT_LENGTH, true);
184 }
185
186 if (! op_ret) {
187 dump_start(s);
188 s->formatter->open_array_section_with_attrs("account",
9f95a23c 189 FormatterAttrs("name", s->user->get_display_name().c_str(), NULL));
7c673cae
FG
190
191 sent_data = true;
192 }
193}
194
9f95a23c 195void RGWListBuckets_ObjStore_SWIFT::handle_listing_chunk(rgw::sal::RGWBucketList&& buckets)
3efd9988
FG
196{
197 if (wants_reversed) {
198 /* Just store in the reversal buffer. Its content will be handled later,
199 * in send_response_end(). */
200 reverse_buffer.emplace(std::begin(reverse_buffer), std::move(buckets));
201 } else {
202 return send_response_data(buckets);
203 }
204}
205
9f95a23c 206void RGWListBuckets_ObjStore_SWIFT::send_response_data(rgw::sal::RGWBucketList& buckets)
7c673cae
FG
207{
208 if (! sent_data) {
209 return;
210 }
211
212 /* Take care of the prefix parameter of Swift API. There is no business
213 * in applying the filter earlier as we really need to go through all
214 * entries regardless of it (the headers like X-Account-Container-Count
215 * aren't affected by specifying prefix). */
9f95a23c 216 const std::map<std::string, rgw::sal::RGWBucket*>& m = buckets.get_buckets();
7c673cae
FG
217 for (auto iter = m.lower_bound(prefix);
218 iter != m.end() && boost::algorithm::starts_with(iter->first, prefix);
219 ++iter) {
9f95a23c 220 dump_bucket_entry(*iter->second);
3efd9988
FG
221 }
222}
7c673cae 223
9f95a23c 224void RGWListBuckets_ObjStore_SWIFT::dump_bucket_entry(const rgw::sal::RGWBucket& obj)
3efd9988
FG
225{
226 s->formatter->open_object_section("container");
9f95a23c 227 s->formatter->dump_string("name", obj.get_name());
3efd9988
FG
228
229 if (need_stats) {
9f95a23c
TL
230 s->formatter->dump_int("count", obj.get_count());
231 s->formatter->dump_int("bytes", obj.get_size());
3efd9988
FG
232 }
233
234 s->formatter->close_section();
235
236 if (! s->cct->_conf->rgw_swift_enforce_content_length) {
237 rgw_flush_formatter(s, s->formatter);
238 }
239}
240
9f95a23c 241void RGWListBuckets_ObjStore_SWIFT::send_response_data_reversed(rgw::sal::RGWBucketList& buckets)
3efd9988
FG
242{
243 if (! sent_data) {
244 return;
245 }
246
247 /* Take care of the prefix parameter of Swift API. There is no business
248 * in applying the filter earlier as we really need to go through all
249 * entries regardless of it (the headers like X-Account-Container-Count
250 * aren't affected by specifying prefix). */
9f95a23c 251 std::map<std::string, rgw::sal::RGWBucket*>& m = buckets.get_buckets();
3efd9988
FG
252
253 auto iter = m.rbegin();
254 for (/* initialized above */;
255 iter != m.rend() && !boost::algorithm::starts_with(iter->first, prefix);
256 ++iter) {
257 /* NOP */;
258 }
259
260 for (/* iter carried */;
261 iter != m.rend() && boost::algorithm::starts_with(iter->first, prefix);
262 ++iter) {
9f95a23c 263 dump_bucket_entry(*iter->second);
7c673cae
FG
264 }
265}
266
267void RGWListBuckets_ObjStore_SWIFT::send_response_end()
268{
3efd9988
FG
269 if (wants_reversed) {
270 for (auto& buckets : reverse_buffer) {
271 send_response_data_reversed(buckets);
272 }
273 }
274
7c673cae
FG
275 if (sent_data) {
276 s->formatter->close_section();
277 }
278
279 if (s->cct->_conf->rgw_swift_enforce_content_length) {
280 /* Adding account stats in the header to keep align with Swift API */
281 dump_account_metadata(s,
3efd9988
FG
282 global_stats,
283 policies_stats,
7c673cae
FG
284 attrs,
285 user_quota,
286 static_cast<RGWAccessControlPolicy_SWIFTAcct&>(*s->user_acl));
287 dump_errno(s);
3efd9988 288 end_header(s, nullptr, nullptr, s->formatter->get_len(), true);
7c673cae
FG
289 }
290
291 if (sent_data || s->cct->_conf->rgw_swift_enforce_content_length) {
292 rgw_flush_formatter_and_reset(s, s->formatter);
293 }
294}
295
296int RGWListBucket_ObjStore_SWIFT::get_params()
297{
298 prefix = s->info.args.get("prefix");
299 marker = s->info.args.get("marker");
300 end_marker = s->info.args.get("end_marker");
301 max_keys = s->info.args.get("limit");
1adf2230
AA
302
303 // non-standard
304 s->info.args.get_bool("allow_unordered", &allow_unordered, false);
305
306 delimiter = s->info.args.get("delimiter");
307
7c673cae
FG
308 op_ret = parse_max_keys();
309 if (op_ret < 0) {
310 return op_ret;
311 }
f64942e4
AA
312 // S3 behavior is to silently cap the max-keys.
313 // Swift behavior is to abort.
7c673cae
FG
314 if (max > default_max)
315 return -ERR_PRECONDITION_FAILED;
316
7c673cae
FG
317 string path_args;
318 if (s->info.args.exists("path")) { // should handle empty path
319 path_args = s->info.args.get("path");
320 if (!delimiter.empty() || !prefix.empty()) {
321 return -EINVAL;
322 }
323 prefix = path_args;
324 delimiter="/";
325
326 path = prefix;
327 if (path.size() && path[path.size() - 1] != '/')
328 path.append("/");
329
330 int len = prefix.size();
331 int delim_size = delimiter.size();
332
333 if (len >= delim_size) {
334 if (prefix.substr(len - delim_size).compare(delimiter) != 0)
335 prefix.append(delimiter);
336 }
337 }
338
339 return 0;
340}
341
342static void dump_container_metadata(struct req_state *,
9f95a23c 343 const rgw::sal::RGWBucket*,
7c673cae
FG
344 const RGWQuotaInfo&,
345 const RGWBucketWebsiteConf&);
346
347void RGWListBucket_ObjStore_SWIFT::send_response()
348{
349 vector<rgw_bucket_dir_entry>::iterator iter = objs.begin();
350 map<string, bool>::iterator pref_iter = common_prefixes.begin();
351
352 dump_start(s);
353 dump_container_metadata(s, bucket, bucket_quota,
354 s->bucket_info.website_conf);
355
1adf2230
AA
356 s->formatter->open_array_section_with_attrs("container",
357 FormatterAttrs("name",
358 s->bucket.name.c_str(),
359 NULL));
7c673cae
FG
360
361 while (iter != objs.end() || pref_iter != common_prefixes.end()) {
362 bool do_pref = false;
363 bool do_objs = false;
364 rgw_obj_key key;
365 if (iter != objs.end()) {
366 key = iter->key;
367 }
368 if (pref_iter == common_prefixes.end())
369 do_objs = true;
370 else if (iter == objs.end())
371 do_pref = true;
372 else if (!key.empty() && key.name.compare(pref_iter->first) == 0) {
373 do_objs = true;
374 ++pref_iter;
375 } else if (!key.empty() && key.name.compare(pref_iter->first) <= 0)
376 do_objs = true;
377 else
378 do_pref = true;
379
1adf2230 380 if (do_objs && (allow_unordered || marker.empty() || marker < key)) {
7c673cae
FG
381 if (key.name.compare(path) == 0)
382 goto next;
383
384 s->formatter->open_object_section("object");
385 s->formatter->dump_string("name", key.name);
386 s->formatter->dump_string("hash", iter->meta.etag);
387 s->formatter->dump_int("bytes", iter->meta.accounted_size);
388 if (!iter->meta.user_data.empty())
389 s->formatter->dump_string("user_custom_data", iter->meta.user_data);
390 string single_content_type = iter->meta.content_type;
391 if (iter->meta.content_type.size()) {
392 // content type might hold multiple values, just dump the last one
393 ssize_t pos = iter->meta.content_type.rfind(',');
394 if (pos > 0) {
395 ++pos;
396 while (single_content_type[pos] == ' ')
397 ++pos;
398 single_content_type = single_content_type.substr(pos);
399 }
400 s->formatter->dump_string("content_type", single_content_type);
401 }
402 dump_time(s, "last_modified", &iter->meta.mtime);
403 s->formatter->close_section();
404 }
405
406 if (do_pref && (marker.empty() || pref_iter->first.compare(marker.name) > 0)) {
407 const string& name = pref_iter->first;
408 if (name.compare(delimiter) == 0)
409 goto next;
410
411 s->formatter->open_object_section_with_attrs("subdir", FormatterAttrs("name", name.c_str(), NULL));
412
413 /* swift is a bit inconsistent here */
414 switch (s->format) {
415 case RGW_FORMAT_XML:
416 s->formatter->dump_string("name", name);
417 break;
418 default:
419 s->formatter->dump_string("subdir", name);
420 }
421 s->formatter->close_section();
422 }
423next:
424 if (do_objs)
425 ++iter;
426 else
427 ++pref_iter;
428 }
429
430 s->formatter->close_section();
431
432 int64_t content_len = 0;
433 if (! op_ret) {
434 content_len = s->formatter->get_len();
435 if (content_len == 0) {
436 op_ret = STATUS_NO_CONTENT;
437 }
438 } else if (op_ret > 0) {
439 op_ret = 0;
440 }
441
442 set_req_state_err(s, op_ret);
443 dump_errno(s);
444 end_header(s, this, NULL, content_len);
445 if (op_ret < 0) {
446 return;
447 }
448
449 rgw_flush_formatter_and_reset(s, s->formatter);
1adf2230 450} // RGWListBucket_ObjStore_SWIFT::send_response
7c673cae
FG
451
452static void dump_container_metadata(struct req_state *s,
9f95a23c 453 const rgw::sal::RGWBucket* bucket,
7c673cae
FG
454 const RGWQuotaInfo& quota,
455 const RGWBucketWebsiteConf& ws_conf)
456{
457 /* Adding X-Timestamp to keep align with Swift API */
458 dump_header(s, "X-Timestamp", utime_t(s->bucket_info.creation_time));
459
9f95a23c
TL
460 dump_header(s, "X-Container-Object-Count", bucket->get_count());
461 dump_header(s, "X-Container-Bytes-Used", bucket->get_size());
462 dump_header(s, "X-Container-Bytes-Used-Actual", bucket->get_size_rounded());
7c673cae
FG
463
464 if (s->object.empty()) {
c07f9fc5
FG
465 auto swift_policy = \
466 static_cast<RGWAccessControlPolicy_SWIFT*>(s->bucket_acl.get());
7c673cae
FG
467 std::string read_acl, write_acl;
468 swift_policy->to_str(read_acl, write_acl);
469
470 if (read_acl.size()) {
471 dump_header(s, "X-Container-Read", read_acl);
472 }
473 if (write_acl.size()) {
474 dump_header(s, "X-Container-Write", write_acl);
475 }
11fdf7f2
TL
476 if (!s->bucket_info.placement_rule.name.empty()) {
477 dump_header(s, "X-Storage-Policy", s->bucket_info.placement_rule.name);
7c673cae 478 }
11fdf7f2 479 dump_header(s, "X-Storage-Class", s->bucket_info.placement_rule.get_storage_class());
7c673cae
FG
480
481 /* Dump user-defined metadata items and generic attrs. */
482 const size_t PREFIX_LEN = sizeof(RGW_ATTR_META_PREFIX) - 1;
483 map<string, bufferlist>::iterator iter;
484 for (iter = s->bucket_attrs.lower_bound(RGW_ATTR_PREFIX);
485 iter != s->bucket_attrs.end();
486 ++iter) {
487 const char *name = iter->first.c_str();
488 map<string, string>::const_iterator geniter = rgw_to_http_attrs.find(name);
489
490 if (geniter != rgw_to_http_attrs.end()) {
491 dump_header(s, geniter->second, iter->second);
492 } else if (strncmp(name, RGW_ATTR_META_PREFIX, PREFIX_LEN) == 0) {
493 dump_header_prefixed(s, "X-Container-Meta-",
494 camelcase_dash_http_attr(name + PREFIX_LEN),
495 iter->second);
496 }
497 }
498 }
499
500 /* Dump container versioning info. */
501 if (! s->bucket_info.swift_ver_location.empty()) {
502 dump_header(s, "X-Versions-Location",
503 url_encode(s->bucket_info.swift_ver_location));
504 }
505
506 /* Dump quota headers. */
507 if (quota.enabled) {
508 if (quota.max_size >= 0) {
509 dump_header(s, "X-Container-Meta-Quota-Bytes", quota.max_size);
510 }
511
512 if (quota.max_objects >= 0) {
513 dump_header(s, "X-Container-Meta-Quota-Count", quota.max_objects);
514 }
515 }
516
517 /* Dump Static Website headers. */
518 if (! ws_conf.index_doc_suffix.empty()) {
519 dump_header(s, "X-Container-Meta-Web-Index", ws_conf.index_doc_suffix);
520 }
521
522 if (! ws_conf.error_doc.empty()) {
523 dump_header(s, "X-Container-Meta-Web-Error", ws_conf.error_doc);
524 }
525
526 if (! ws_conf.subdir_marker.empty()) {
527 dump_header(s, "X-Container-Meta-Web-Directory-Type",
528 ws_conf.subdir_marker);
529 }
530
531 if (! ws_conf.listing_css_doc.empty()) {
532 dump_header(s, "X-Container-Meta-Web-Listings-CSS",
533 ws_conf.listing_css_doc);
534 }
535
536 if (ws_conf.listing_enabled) {
537 dump_header(s, "X-Container-Meta-Web-Listings", "true");
538 }
11fdf7f2
TL
539
540 /* Dump bucket's modification time. Compliance with the Swift API really
541 * needs that. */
542 dump_last_modified(s, s->bucket_mtime);
7c673cae
FG
543}
544
545void RGWStatAccount_ObjStore_SWIFT::execute()
546{
547 RGWStatAccount_ObjStore::execute();
9f95a23c 548 op_ret = store->ctl()->user->get_attrs_by_uid(s->user->get_id(), &attrs, s->yield);
7c673cae
FG
549}
550
551void RGWStatAccount_ObjStore_SWIFT::send_response()
552{
553 if (op_ret >= 0) {
554 op_ret = STATUS_NO_CONTENT;
555 dump_account_metadata(s,
3efd9988
FG
556 global_stats,
557 policies_stats,
7c673cae
FG
558 attrs,
559 user_quota,
560 static_cast<RGWAccessControlPolicy_SWIFTAcct&>(*s->user_acl));
561 }
562
563 set_req_state_err(s, op_ret);
564 dump_errno(s);
565
566 end_header(s, NULL, NULL, 0, true);
567
568 dump_start(s);
569}
570
571void RGWStatBucket_ObjStore_SWIFT::send_response()
572{
573 if (op_ret >= 0) {
574 op_ret = STATUS_NO_CONTENT;
575 dump_container_metadata(s, bucket, bucket_quota,
576 s->bucket_info.website_conf);
577 }
578
579 set_req_state_err(s, op_ret);
580 dump_errno(s);
581
582 end_header(s, this, NULL, 0, true);
583 dump_start(s);
584}
585
586static int get_swift_container_settings(req_state * const s,
9f95a23c 587 rgw::sal::RGWRadosStore * const store,
7c673cae
FG
588 RGWAccessControlPolicy * const policy,
589 bool * const has_policy,
590 uint32_t * rw_mask,
591 RGWCORSConfiguration * const cors_config,
592 bool * const has_cors)
593{
28e407b8
AA
594 const char * const read_list = s->info.env->get("HTTP_X_CONTAINER_READ");
595 const char * const write_list = s->info.env->get("HTTP_X_CONTAINER_WRITE");
7c673cae
FG
596
597 *has_policy = false;
598
28e407b8 599 if (read_list || write_list) {
7c673cae 600 RGWAccessControlPolicy_SWIFT swift_policy(s->cct);
9f95a23c
TL
601 const auto r = swift_policy.create(store->ctl()->user,
602 s->user->get_id(),
603 s->user->get_display_name(),
7c673cae
FG
604 read_list,
605 write_list,
606 *rw_mask);
607 if (r < 0) {
608 return r;
609 }
610
611 *policy = swift_policy;
612 *has_policy = true;
613 }
614
615 *has_cors = false;
616
617 /*Check and update CORS configuration*/
618 const char *allow_origins = s->info.env->get("HTTP_X_CONTAINER_META_ACCESS_CONTROL_ALLOW_ORIGIN");
619 const char *allow_headers = s->info.env->get("HTTP_X_CONTAINER_META_ACCESS_CONTROL_ALLOW_HEADERS");
620 const char *expose_headers = s->info.env->get("HTTP_X_CONTAINER_META_ACCESS_CONTROL_EXPOSE_HEADERS");
621 const char *max_age = s->info.env->get("HTTP_X_CONTAINER_META_ACCESS_CONTROL_MAX_AGE");
622 if (allow_origins) {
623 RGWCORSConfiguration_SWIFT *swift_cors = new RGWCORSConfiguration_SWIFT;
624 int r = swift_cors->create_update(allow_origins, allow_headers, expose_headers, max_age);
625 if (r < 0) {
626 dout(0) << "Error creating/updating the cors configuration" << dendl;
627 delete swift_cors;
628 return r;
629 }
630 *has_cors = true;
631 *cors_config = *swift_cors;
632 cors_config->dump();
633 delete swift_cors;
634 }
635
636 return 0;
637}
638
639#define ACCT_REMOVE_ATTR_PREFIX "HTTP_X_REMOVE_ACCOUNT_META_"
640#define ACCT_PUT_ATTR_PREFIX "HTTP_X_ACCOUNT_META_"
641#define CONT_REMOVE_ATTR_PREFIX "HTTP_X_REMOVE_CONTAINER_META_"
642#define CONT_PUT_ATTR_PREFIX "HTTP_X_CONTAINER_META_"
643
644static void get_rmattrs_from_headers(const req_state * const s,
645 const char * const put_prefix,
646 const char * const del_prefix,
647 set<string>& rmattr_names)
648{
7c673cae
FG
649 const size_t put_prefix_len = strlen(put_prefix);
650 const size_t del_prefix_len = strlen(del_prefix);
651
31f18b77 652 for (const auto& kv : s->info.env->get_map()) {
7c673cae 653 size_t prefix_len = 0;
31f18b77 654 const char * const p = kv.first.c_str();
7c673cae
FG
655
656 if (strncasecmp(p, del_prefix, del_prefix_len) == 0) {
657 /* Explicitly requested removal. */
658 prefix_len = del_prefix_len;
659 } else if ((strncasecmp(p, put_prefix, put_prefix_len) == 0)
31f18b77 660 && kv.second.empty()) {
7c673cae
FG
661 /* Removal requested by putting an empty value. */
662 prefix_len = put_prefix_len;
663 }
664
665 if (prefix_len > 0) {
666 string name(RGW_ATTR_META_PREFIX);
667 name.append(lowercase_dash_http_attr(p + prefix_len));
668 rmattr_names.insert(name);
669 }
670 }
671}
672
673static int get_swift_versioning_settings(
674 req_state * const s,
675 boost::optional<std::string>& swift_ver_location)
676{
677 /* Removing the Swift's versions location has lower priority than setting
678 * a new one. That's the reason why we're handling it first. */
679 const std::string vlocdel =
680 s->info.env->get("HTTP_X_REMOVE_VERSIONS_LOCATION", "");
681 if (vlocdel.size()) {
682 swift_ver_location = boost::in_place(std::string());
683 }
684
685 if (s->info.env->exists("HTTP_X_VERSIONS_LOCATION")) {
686 /* If the Swift's versioning is globally disabled but someone wants to
687 * enable it for a given container, new version of Swift will generate
688 * the precondition failed error. */
689 if (! s->cct->_conf->rgw_swift_versioning_enabled) {
690 return -ERR_PRECONDITION_FAILED;
691 }
692
693 swift_ver_location = s->info.env->get("HTTP_X_VERSIONS_LOCATION", "");
694 }
695
696 return 0;
697}
698
699int RGWCreateBucket_ObjStore_SWIFT::get_params()
700{
701 bool has_policy;
702 uint32_t policy_rw_mask = 0;
703
704 int r = get_swift_container_settings(s, store, &policy, &has_policy,
705 &policy_rw_mask, &cors_config, &has_cors);
706 if (r < 0) {
707 return r;
708 }
709
710 if (!has_policy) {
9f95a23c 711 policy.create_default(s->user->get_id(), s->user->get_display_name());
7c673cae
FG
712 }
713
9f95a23c 714 location_constraint = store->svc()->zone->get_zonegroup().api_name;
7c673cae
FG
715 get_rmattrs_from_headers(s, CONT_PUT_ATTR_PREFIX,
716 CONT_REMOVE_ATTR_PREFIX, rmattr_names);
11fdf7f2 717 placement_rule.init(s->info.env->get("HTTP_X_STORAGE_POLICY", ""), s->info.storage_class);
7c673cae
FG
718
719 return get_swift_versioning_settings(s, swift_ver_location);
720}
721
3efd9988
FG
722static inline int handle_metadata_errors(req_state* const s, const int op_ret)
723{
724 if (op_ret == -EFBIG) {
725 /* Handle the custom error message of exceeding maximum custom attribute
726 * (stored as xattr) size. */
727 const auto error_message = boost::str(
728 boost::format("Metadata value longer than %lld")
11fdf7f2 729 % s->cct->_conf.get_val<Option::size_t>("rgw_max_attr_size"));
3efd9988
FG
730 set_req_state_err(s, EINVAL, error_message);
731 return -EINVAL;
732 } else if (op_ret == -E2BIG) {
733 const auto error_message = boost::str(
734 boost::format("Too many metadata items; max %lld")
11fdf7f2 735 % s->cct->_conf.get_val<uint64_t>("rgw_max_attrs_num_in_req"));
3efd9988
FG
736 set_req_state_err(s, EINVAL, error_message);
737 return -EINVAL;
738 }
739
740 return op_ret;
741}
742
7c673cae
FG
743void RGWCreateBucket_ObjStore_SWIFT::send_response()
744{
3efd9988
FG
745 const auto meta_ret = handle_metadata_errors(s, op_ret);
746 if (meta_ret != op_ret) {
747 op_ret = meta_ret;
748 } else {
749 if (!op_ret) {
750 op_ret = STATUS_CREATED;
751 } else if (op_ret == -ERR_BUCKET_EXISTS) {
752 op_ret = STATUS_ACCEPTED;
753 }
754 set_req_state_err(s, op_ret);
755 }
756
7c673cae
FG
757 dump_errno(s);
758 /* Propose ending HTTP header with 0 Content-Length header. */
759 end_header(s, NULL, NULL, 0);
760 rgw_flush_formatter_and_reset(s, s->formatter);
761}
762
763void RGWDeleteBucket_ObjStore_SWIFT::send_response()
764{
765 int r = op_ret;
766 if (!r)
767 r = STATUS_NO_CONTENT;
768
769 set_req_state_err(s, r);
770 dump_errno(s);
771 end_header(s, this, NULL, 0);
772 rgw_flush_formatter_and_reset(s, s->formatter);
773}
774
775static int get_delete_at_param(req_state *s, boost::optional<real_time> &delete_at)
776{
777 /* Handle Swift object expiration. */
778 real_time delat_proposal;
779 string x_delete = s->info.env->get("HTTP_X_DELETE_AFTER", "");
780
781 if (x_delete.empty()) {
782 x_delete = s->info.env->get("HTTP_X_DELETE_AT", "");
783 } else {
784 /* X-Delete-After HTTP is present. It means we need add its value
785 * to the current time. */
786 delat_proposal = real_clock::now();
787 }
788
789 if (x_delete.empty()) {
790 delete_at = boost::none;
791 if (s->info.env->exists("HTTP_X_REMOVE_DELETE_AT")) {
792 delete_at = boost::in_place(real_time());
793 }
794 return 0;
795 }
796 string err;
797 long ts = strict_strtoll(x_delete.c_str(), 10, &err);
798
799 if (!err.empty()) {
800 return -EINVAL;
801 }
802
803 delat_proposal += make_timespan(ts);
804 if (delat_proposal < real_clock::now()) {
805 return -EINVAL;
806 }
807
808 delete_at = delat_proposal;
809
810 return 0;
811}
812
813int RGWPutObj_ObjStore_SWIFT::verify_permission()
814{
815 op_ret = RGWPutObj_ObjStore::verify_permission();
816
817 /* We have to differentiate error codes depending on whether user is
818 * anonymous (401 Unauthorized) or he doesn't have necessary permissions
819 * (403 Forbidden). */
820 if (s->auth.identity->is_anonymous() && op_ret == -EACCES) {
821 return -EPERM;
822 } else {
823 return op_ret;
824 }
825}
826
11fdf7f2
TL
827int RGWPutObj_ObjStore_SWIFT::update_slo_segment_size(rgw_slo_entry& entry) {
828
829 int r = 0;
830 const string& path = entry.path;
831
832 /* If the path starts with slashes, strip them all. */
833 const size_t pos_init = path.find_first_not_of('/');
834
835 if (pos_init == string::npos) {
836 return -EINVAL;
837 }
838
839 const size_t pos_sep = path.find('/', pos_init);
840 if (pos_sep == string::npos) {
841 return -EINVAL;
842 }
843
844 string bucket_name = path.substr(pos_init, pos_sep - pos_init);
845 string obj_name = path.substr(pos_sep + 1);
846
847 rgw_bucket bucket;
848
849 if (bucket_name.compare(s->bucket.name) != 0) {
850 RGWBucketInfo bucket_info;
851 map<string, bufferlist> bucket_attrs;
9f95a23c 852 r = store->getRados()->get_bucket_info(store->svc(), s->user->get_id().tenant,
11fdf7f2 853 bucket_name, bucket_info, nullptr,
9f95a23c 854 s->yield, &bucket_attrs);
11fdf7f2
TL
855 if (r < 0) {
856 ldpp_dout(this, 0) << "could not get bucket info for bucket="
857 << bucket_name << dendl;
858 return r;
859 }
860 bucket = bucket_info.bucket;
861 } else {
862 bucket = s->bucket;
863 }
864
865 /* fetch the stored size of the seg (or error if not valid) */
866 rgw_obj_key slo_key(obj_name);
867 rgw_obj slo_seg(bucket, slo_key);
868
869 /* no prefetch */
870 RGWObjectCtx obj_ctx(store);
871 obj_ctx.set_atomic(slo_seg);
872
9f95a23c 873 RGWRados::Object op_target(store->getRados(), s->bucket_info, obj_ctx, slo_seg);
11fdf7f2
TL
874 RGWRados::Object::Read read_op(&op_target);
875
876 bool compressed;
877 RGWCompressionInfo cs_info;
878 map<std::string, buffer::list> attrs;
879 uint64_t size_bytes{0};
880
881 read_op.params.attrs = &attrs;
882 read_op.params.obj_size = &size_bytes;
883
9f95a23c 884 r = read_op.prepare(s->yield);
11fdf7f2
TL
885 if (r < 0) {
886 return r;
887 }
888
889 r = rgw_compression_info_from_attrset(attrs, compressed, cs_info);
890 if (r < 0) {
891 return -EIO;
892 }
893
894 if (compressed) {
895 size_bytes = cs_info.orig_size;
896 }
897
898 /* "When the PUT operation sees the multipart-manifest=put query
899 * parameter, it reads the request body and verifies that each
900 * segment object exists and that the sizes and ETags match. If
901 * there is a mismatch, the PUT operation fails."
902 */
903 if (entry.size_bytes &&
904 (entry.size_bytes != size_bytes)) {
905 return -EINVAL;
906 }
907
908 entry.size_bytes = size_bytes;
909
910 return 0;
911} /* RGWPutObj_ObjStore_SWIFT::update_slo_segment_sizes */
912
7c673cae
FG
913int RGWPutObj_ObjStore_SWIFT::get_params()
914{
915 if (s->has_bad_meta) {
916 return -EINVAL;
917 }
918
919 if (!s->length) {
920 const char *encoding = s->info.env->get("HTTP_TRANSFER_ENCODING");
921 if (!encoding || strcmp(encoding, "chunked") != 0) {
9f95a23c 922 ldpp_dout(this, 20) << "neither length nor chunked encoding" << dendl;
7c673cae
FG
923 return -ERR_LENGTH_REQUIRED;
924 }
925
926 chunked_upload = true;
927 }
928
929 supplied_etag = s->info.env->get("HTTP_ETAG");
930
931 if (!s->generic_attrs.count(RGW_ATTR_CONTENT_TYPE)) {
9f95a23c 932 ldpp_dout(this, 5) << "content type wasn't provided, trying to guess" << dendl;
7c673cae
FG
933 const char *suffix = strrchr(s->object.name.c_str(), '.');
934 if (suffix) {
935 suffix++;
936 if (*suffix) {
937 string suffix_str(suffix);
938 const char *mime = rgw_find_mime_by_ext(suffix_str);
939 if (mime) {
940 s->generic_attrs[RGW_ATTR_CONTENT_TYPE] = mime;
941 }
942 }
943 }
944 }
945
9f95a23c 946 policy.create_default(s->user->get_id(), s->user->get_display_name());
7c673cae
FG
947
948 int r = get_delete_at_param(s, delete_at);
949 if (r < 0) {
9f95a23c 950 ldpp_dout(this, 5) << "ERROR: failed to get Delete-At param" << dendl;
7c673cae
FG
951 return r;
952 }
953
954 if (!s->cct->_conf->rgw_swift_custom_header.empty()) {
955 string custom_header = s->cct->_conf->rgw_swift_custom_header;
956 if (s->info.env->exists(custom_header.c_str())) {
957 user_data = s->info.env->get(custom_header.c_str());
958 }
959 }
960
961 dlo_manifest = s->info.env->get("HTTP_X_OBJECT_MANIFEST");
962 bool exists;
963 string multipart_manifest = s->info.args.get("multipart-manifest", &exists);
964 if (exists) {
965 if (multipart_manifest != "put") {
9f95a23c 966 ldpp_dout(this, 5) << "invalid multipart-manifest http param: " << multipart_manifest << dendl;
7c673cae
FG
967 return -EINVAL;
968 }
969
970#define MAX_SLO_ENTRY_SIZE (1024 + 128) // 1024 - max obj name, 128 - enough extra for other info
971 uint64_t max_len = s->cct->_conf->rgw_max_slo_entries * MAX_SLO_ENTRY_SIZE;
972
973 slo_info = new RGWSLOInfo;
974
11fdf7f2
TL
975 int r = 0;
976 std::tie(r, slo_info->raw_data) = rgw_rest_get_json_input_keep_data(s->cct, s, slo_info->entries, max_len);
7c673cae 977 if (r < 0) {
9f95a23c 978 ldpp_dout(this, 5) << "failed to read input for slo r=" << r << dendl;
7c673cae
FG
979 return r;
980 }
981
982 if ((int64_t)slo_info->entries.size() > s->cct->_conf->rgw_max_slo_entries) {
9f95a23c 983 ldpp_dout(this, 5) << "too many entries in slo request: " << slo_info->entries.size() << dendl;
7c673cae
FG
984 return -EINVAL;
985 }
986
987 MD5 etag_sum;
988 uint64_t total_size = 0;
11fdf7f2
TL
989 for (auto& entry : slo_info->entries) {
990 etag_sum.Update((const unsigned char *)entry.etag.c_str(),
7c673cae 991 entry.etag.length());
11fdf7f2
TL
992
993 /* if size_bytes == 0, it should be replaced with the
994 * real segment size (which could be 0); this follows from the
995 * fact that Swift requires all segments to exist, but permits
996 * the size_bytes element to be omitted from the SLO manifest, see
997 * https://docs.openstack.org/swift/latest/api/large_objects.html
998 */
999 r = update_slo_segment_size(entry);
1000 if (r < 0) {
1001 return r;
1002 }
1003
7c673cae
FG
1004 total_size += entry.size_bytes;
1005
9f95a23c 1006 ldpp_dout(this, 20) << "slo_part: " << entry.path
7c673cae
FG
1007 << " size=" << entry.size_bytes
1008 << " etag=" << entry.etag
1009 << dendl;
1010 }
1011 complete_etag(etag_sum, &lo_etag);
1012 slo_info->total_size = total_size;
1013
11fdf7f2 1014 ofs = slo_info->raw_data.length();
7c673cae
FG
1015 }
1016
1017 return RGWPutObj_ObjStore::get_params();
1018}
1019
1020void RGWPutObj_ObjStore_SWIFT::send_response()
1021{
3efd9988
FG
1022 const auto meta_ret = handle_metadata_errors(s, op_ret);
1023 if (meta_ret) {
1024 op_ret = meta_ret;
1025 } else {
1026 if (!op_ret) {
1027 op_ret = STATUS_CREATED;
1028 }
1029 set_req_state_err(s, op_ret);
7c673cae
FG
1030 }
1031
1032 if (! lo_etag.empty()) {
1033 /* Static Large Object of Swift API has two etags represented by
1034 * following members:
1035 * - etag - for the manifest itself (it will be stored in xattrs),
1036 * - lo_etag - for the content composited from SLO's segments.
1037 * The value is calculated basing on segments' etags.
1038 * In response for PUT request we have to expose the second one.
1039 * The first one may be obtained by GET with "multipart-manifest=get"
1040 * in query string on a given SLO. */
1041 dump_etag(s, lo_etag, true /* quoted */);
1042 } else {
1043 dump_etag(s, etag);
1044 }
1045
1046 dump_last_modified(s, mtime);
1047 set_req_state_err(s, op_ret);
1048 dump_errno(s);
1049 end_header(s, this);
1050 rgw_flush_formatter_and_reset(s, s->formatter);
1051}
1052
1053static int get_swift_account_settings(req_state * const s,
9f95a23c 1054 rgw::sal::RGWRadosStore * const store,
7c673cae
FG
1055 RGWAccessControlPolicy_SWIFTAcct * const policy,
1056 bool * const has_policy)
1057{
1058 *has_policy = false;
1059
1060 const char * const acl_attr = s->info.env->get("HTTP_X_ACCOUNT_ACCESS_CONTROL");
1061 if (acl_attr) {
1062 RGWAccessControlPolicy_SWIFTAcct swift_acct_policy(s->cct);
9f95a23c
TL
1063 const bool r = swift_acct_policy.create(store->ctl()->user,
1064 s->user->get_id(),
1065 s->user->get_display_name(),
7c673cae
FG
1066 string(acl_attr));
1067 if (r != true) {
1068 return -EINVAL;
1069 }
1070
1071 *policy = swift_acct_policy;
1072 *has_policy = true;
1073 }
1074
1075 return 0;
1076}
1077
1078int RGWPutMetadataAccount_ObjStore_SWIFT::get_params()
1079{
1080 if (s->has_bad_meta) {
1081 return -EINVAL;
1082 }
1083
1084 int ret = get_swift_account_settings(s,
1085 store,
1086 // FIXME: we need to carry unique_ptr in generic class
1087 // and allocate appropriate ACL class in the ctor
1088 static_cast<RGWAccessControlPolicy_SWIFTAcct *>(&policy),
1089 &has_policy);
1090 if (ret < 0) {
1091 return ret;
1092 }
1093
1094 get_rmattrs_from_headers(s, ACCT_PUT_ATTR_PREFIX, ACCT_REMOVE_ATTR_PREFIX,
1095 rmattr_names);
1096 return 0;
1097}
1098
1099void RGWPutMetadataAccount_ObjStore_SWIFT::send_response()
1100{
3efd9988
FG
1101 const auto meta_ret = handle_metadata_errors(s, op_ret);
1102 if (meta_ret != op_ret) {
1103 op_ret = meta_ret;
1104 } else {
1105 if (!op_ret) {
1106 op_ret = STATUS_NO_CONTENT;
1107 }
1108 set_req_state_err(s, op_ret);
7c673cae 1109 }
3efd9988 1110
7c673cae
FG
1111 dump_errno(s);
1112 end_header(s, this);
1113 rgw_flush_formatter_and_reset(s, s->formatter);
1114}
1115
1116int RGWPutMetadataBucket_ObjStore_SWIFT::get_params()
1117{
1118 if (s->has_bad_meta) {
1119 return -EINVAL;
1120 }
1121
1122 int r = get_swift_container_settings(s, store, &policy, &has_policy,
1123 &policy_rw_mask, &cors_config, &has_cors);
1124 if (r < 0) {
1125 return r;
1126 }
1127
1128 get_rmattrs_from_headers(s, CONT_PUT_ATTR_PREFIX, CONT_REMOVE_ATTR_PREFIX,
1129 rmattr_names);
11fdf7f2 1130 placement_rule.init(s->info.env->get("HTTP_X_STORAGE_POLICY", ""), s->info.storage_class);
7c673cae
FG
1131
1132 return get_swift_versioning_settings(s, swift_ver_location);
1133}
1134
1135void RGWPutMetadataBucket_ObjStore_SWIFT::send_response()
1136{
3efd9988
FG
1137 const auto meta_ret = handle_metadata_errors(s, op_ret);
1138 if (meta_ret != op_ret) {
1139 op_ret = meta_ret;
1140 } else {
1141 if (!op_ret && (op_ret != -EINVAL)) {
1142 op_ret = STATUS_NO_CONTENT;
1143 }
1144 set_req_state_err(s, op_ret);
7c673cae 1145 }
3efd9988 1146
7c673cae
FG
1147 dump_errno(s);
1148 end_header(s, this);
1149 rgw_flush_formatter_and_reset(s, s->formatter);
1150}
1151
1152int RGWPutMetadataObject_ObjStore_SWIFT::get_params()
1153{
1154 if (s->has_bad_meta) {
1155 return -EINVAL;
1156 }
1157
1158 /* Handle Swift object expiration. */
1159 int r = get_delete_at_param(s, delete_at);
1160 if (r < 0) {
9f95a23c 1161 ldpp_dout(this, 5) << "ERROR: failed to get Delete-At param" << dendl;
7c673cae
FG
1162 return r;
1163 }
1164
7c673cae
FG
1165 dlo_manifest = s->info.env->get("HTTP_X_OBJECT_MANIFEST");
1166
1167 return 0;
1168}
1169
1170void RGWPutMetadataObject_ObjStore_SWIFT::send_response()
1171{
3efd9988
FG
1172 const auto meta_ret = handle_metadata_errors(s, op_ret);
1173 if (meta_ret != op_ret) {
1174 op_ret = meta_ret;
1175 } else {
1176 if (!op_ret) {
1177 op_ret = STATUS_ACCEPTED;
1178 }
1179 set_req_state_err(s, op_ret);
7c673cae 1180 }
3efd9988 1181
31f18b77 1182 if (!s->is_err()) {
7c673cae
FG
1183 dump_content_length(s, 0);
1184 }
3efd9988 1185
7c673cae
FG
1186 dump_errno(s);
1187 end_header(s, this);
1188 rgw_flush_formatter_and_reset(s, s->formatter);
1189}
1190
1191static void bulkdelete_respond(const unsigned num_deleted,
1192 const unsigned int num_unfound,
1193 const std::list<RGWBulkDelete::fail_desc_t>& failures,
1194 const int prot_flags, /* in */
1195 ceph::Formatter& formatter) /* out */
1196{
1197 formatter.open_object_section("delete");
1198
1199 string resp_status;
1200 string resp_body;
1201
1202 if (!failures.empty()) {
1203 int reason = ERR_INVALID_REQUEST;
1204 for (const auto fail_desc : failures) {
1205 if (-ENOENT != fail_desc.err && -EACCES != fail_desc.err) {
1206 reason = fail_desc.err;
1207 }
1208 }
7c673cae
FG
1209 rgw_err err;
1210 set_req_state_err(err, reason, prot_flags);
1211 dump_errno(err, resp_status);
1212 } else if (0 == num_deleted && 0 == num_unfound) {
1213 /* 400 Bad Request */
1214 dump_errno(400, resp_status);
1215 resp_body = "Invalid bulk delete.";
1216 } else {
1217 /* 200 OK */
1218 dump_errno(200, resp_status);
1219 }
1220
1221 encode_json("Number Deleted", num_deleted, &formatter);
1222 encode_json("Number Not Found", num_unfound, &formatter);
1223 encode_json("Response Body", resp_body, &formatter);
1224 encode_json("Response Status", resp_status, &formatter);
1225
1226 formatter.open_array_section("Errors");
1227 for (const auto fail_desc : failures) {
1228 formatter.open_array_section("object");
1229
1230 stringstream ss_name;
1231 ss_name << fail_desc.path;
1232 encode_json("Name", ss_name.str(), &formatter);
1233
1234 rgw_err err;
1235 set_req_state_err(err, fail_desc.err, prot_flags);
1236 string status;
1237 dump_errno(err, status);
1238 encode_json("Status", status, &formatter);
1239 formatter.close_section();
1240 }
1241 formatter.close_section();
1242
1243 formatter.close_section();
1244}
1245
1246int RGWDeleteObj_ObjStore_SWIFT::verify_permission()
1247{
1248 op_ret = RGWDeleteObj_ObjStore::verify_permission();
1249
1250 /* We have to differentiate error codes depending on whether user is
1251 * anonymous (401 Unauthorized) or he doesn't have necessary permissions
1252 * (403 Forbidden). */
1253 if (s->auth.identity->is_anonymous() && op_ret == -EACCES) {
1254 return -EPERM;
1255 } else {
1256 return op_ret;
1257 }
1258}
1259
1260int RGWDeleteObj_ObjStore_SWIFT::get_params()
1261{
1262 const string& mm = s->info.args.get("multipart-manifest");
1263 multipart_delete = (mm.compare("delete") == 0);
1264
1265 return RGWDeleteObj_ObjStore::get_params();
1266}
1267
1268void RGWDeleteObj_ObjStore_SWIFT::send_response()
1269{
1270 int r = op_ret;
1271
1272 if (multipart_delete) {
1273 r = 0;
1274 } else if(!r) {
1275 r = STATUS_NO_CONTENT;
1276 }
1277
1278 set_req_state_err(s, r);
1279 dump_errno(s);
1280
1281 if (multipart_delete) {
1282 end_header(s, this /* RGWOp */, nullptr /* contype */,
1283 CHUNKED_TRANSFER_ENCODING);
1284
1285 if (deleter) {
1286 bulkdelete_respond(deleter->get_num_deleted(),
1287 deleter->get_num_unfound(),
1288 deleter->get_failures(),
1289 s->prot_flags,
1290 *s->formatter);
1291 } else if (-ENOENT == op_ret) {
1292 bulkdelete_respond(0, 1, {}, s->prot_flags, *s->formatter);
1293 } else {
1294 RGWBulkDelete::acct_path_t path;
1295 path.bucket_name = s->bucket_name;
1296 path.obj_key = s->object;
1297
1298 RGWBulkDelete::fail_desc_t fail_desc;
1299 fail_desc.err = op_ret;
1300 fail_desc.path = path;
1301
1302 bulkdelete_respond(0, 0, { fail_desc }, s->prot_flags, *s->formatter);
1303 }
1304 } else {
1305 end_header(s, this);
1306 }
1307
1308 rgw_flush_formatter_and_reset(s, s->formatter);
1309
1310}
1311
1312static void get_contype_from_attrs(map<string, bufferlist>& attrs,
1313 string& content_type)
1314{
1315 map<string, bufferlist>::iterator iter = attrs.find(RGW_ATTR_CONTENT_TYPE);
1316 if (iter != attrs.end()) {
11fdf7f2 1317 content_type = rgw_bl_str(iter->second);
7c673cae
FG
1318 }
1319}
1320
9f95a23c 1321static void dump_object_metadata(const DoutPrefixProvider* dpp, struct req_state * const s,
11fdf7f2 1322 const map<string, bufferlist>& attrs)
7c673cae
FG
1323{
1324 map<string, string> response_attrs;
1325
1326 for (auto kv : attrs) {
1327 const char * name = kv.first.c_str();
1328 const auto aiter = rgw_to_http_attrs.find(name);
1329
1330 if (aiter != std::end(rgw_to_http_attrs)) {
11fdf7f2 1331 response_attrs[aiter->second] = rgw_bl_str(kv.second);
31f18b77 1332 } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {
11fdf7f2 1333 // this attr has an extra length prefix from encode() in prior versions
31f18b77 1334 dump_header(s, "X-Object-Meta-Static-Large-Object", "True");
7c673cae
FG
1335 } else if (strncmp(name, RGW_ATTR_META_PREFIX,
1336 sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {
1337 name += sizeof(RGW_ATTR_META_PREFIX) - 1;
1338 dump_header_prefixed(s, "X-Object-Meta-",
1339 camelcase_dash_http_attr(name), kv.second);
1340 }
1341 }
1342
1343 /* Handle override and fallback for Content-Disposition HTTP header.
1344 * At the moment this will be used only by TempURL of the Swift API. */
1345 const auto cditer = rgw_to_http_attrs.find(RGW_ATTR_CONTENT_DISP);
1346 if (cditer != std::end(rgw_to_http_attrs)) {
1347 const auto& name = cditer->second;
1348
1349 if (!s->content_disp.override.empty()) {
1350 response_attrs[name] = s->content_disp.override;
1351 } else if (!s->content_disp.fallback.empty()
1352 && response_attrs.find(name) == std::end(response_attrs)) {
1353 response_attrs[name] = s->content_disp.fallback;
1354 }
1355 }
1356
1357 for (const auto kv : response_attrs) {
1358 dump_header(s, kv.first, kv.second);
1359 }
1360
1361 const auto iter = attrs.find(RGW_ATTR_DELETE_AT);
1362 if (iter != std::end(attrs)) {
1363 utime_t delete_at;
1364 try {
11fdf7f2 1365 decode(delete_at, iter->second);
7c673cae
FG
1366 if (!delete_at.is_zero()) {
1367 dump_header(s, "X-Delete-At", delete_at.sec());
1368 }
1369 } catch (buffer::error& err) {
9f95a23c 1370 ldpp_dout(dpp, 0) << "ERROR: cannot decode object's " RGW_ATTR_DELETE_AT
7c673cae
FG
1371 " attr, ignoring"
1372 << dendl;
1373 }
1374 }
1375}
1376
1377int RGWCopyObj_ObjStore_SWIFT::init_dest_policy()
1378{
9f95a23c 1379 dest_policy.create_default(s->user->get_id(), s->user->get_display_name());
7c673cae
FG
1380
1381 return 0;
1382}
1383
1384int RGWCopyObj_ObjStore_SWIFT::get_params()
1385{
1386 if_mod = s->info.env->get("HTTP_IF_MODIFIED_SINCE");
1387 if_unmod = s->info.env->get("HTTP_IF_UNMODIFIED_SINCE");
1388 if_match = s->info.env->get("HTTP_COPY_IF_MATCH");
1389 if_nomatch = s->info.env->get("HTTP_COPY_IF_NONE_MATCH");
1390
1391 src_tenant_name = s->src_tenant_name;
1392 src_bucket_name = s->src_bucket_name;
1393 src_object = s->src_object;
1394 dest_tenant_name = s->bucket_tenant;
1395 dest_bucket_name = s->bucket_name;
1396 dest_object = s->object.name;
1397
1398 const char * const fresh_meta = s->info.env->get("HTTP_X_FRESH_METADATA");
1399 if (fresh_meta && strcasecmp(fresh_meta, "TRUE") == 0) {
1400 attrs_mod = RGWRados::ATTRSMOD_REPLACE;
1401 } else {
1402 attrs_mod = RGWRados::ATTRSMOD_MERGE;
1403 }
1404
1405 int r = get_delete_at_param(s, delete_at);
1406 if (r < 0) {
9f95a23c 1407 ldpp_dout(this, 5) << "ERROR: failed to get Delete-At param" << dendl;
7c673cae
FG
1408 return r;
1409 }
1410
1411 return 0;
1412}
1413
1414void RGWCopyObj_ObjStore_SWIFT::send_partial_response(off_t ofs)
1415{
1416 if (! sent_header) {
1417 if (! op_ret)
1418 op_ret = STATUS_CREATED;
1419 set_req_state_err(s, op_ret);
1420 dump_errno(s);
1421 end_header(s, this);
1422
1423 /* Send progress information. Note that this diverge from the original swift
1424 * spec. We do this in order to keep connection alive.
1425 */
1426 if (op_ret == 0) {
1427 s->formatter->open_array_section("progress");
1428 }
1429 sent_header = true;
1430 } else {
1431 s->formatter->dump_int("ofs", (uint64_t)ofs);
1432 }
1433 rgw_flush_formatter(s, s->formatter);
1434}
1435
1436void RGWCopyObj_ObjStore_SWIFT::dump_copy_info()
1437{
1438 /* Dump X-Copied-From. */
1439 dump_header(s, "X-Copied-From", url_encode(src_bucket.name) +
1440 "/" + url_encode(src_object.name));
1441
1442 /* Dump X-Copied-From-Account. */
1443 /* XXX tenant */
9f95a23c 1444 dump_header(s, "X-Copied-From-Account", url_encode(s->user->get_id().id));
7c673cae
FG
1445
1446 /* Dump X-Copied-From-Last-Modified. */
1447 dump_time_header(s, "X-Copied-From-Last-Modified", src_mtime);
1448}
1449
1450void RGWCopyObj_ObjStore_SWIFT::send_response()
1451{
1452 if (! sent_header) {
1453 string content_type;
1454 if (! op_ret)
1455 op_ret = STATUS_CREATED;
1456 set_req_state_err(s, op_ret);
1457 dump_errno(s);
1458 dump_etag(s, etag);
1459 dump_last_modified(s, mtime);
1460 dump_copy_info();
1461 get_contype_from_attrs(attrs, content_type);
9f95a23c 1462 dump_object_metadata(this, s, attrs);
7c673cae
FG
1463 end_header(s, this, !content_type.empty() ? content_type.c_str()
1464 : "binary/octet-stream");
1465 } else {
1466 s->formatter->close_section();
1467 rgw_flush_formatter(s, s->formatter);
1468 }
1469}
1470
1471int RGWGetObj_ObjStore_SWIFT::verify_permission()
1472{
1473 op_ret = RGWGetObj_ObjStore::verify_permission();
1474
1475 /* We have to differentiate error codes depending on whether user is
1476 * anonymous (401 Unauthorized) or he doesn't have necessary permissions
1477 * (403 Forbidden). */
1478 if (s->auth.identity->is_anonymous() && op_ret == -EACCES) {
1479 return -EPERM;
1480 } else {
1481 return op_ret;
1482 }
1483}
1484
1485int RGWGetObj_ObjStore_SWIFT::get_params()
1486{
1487 const string& mm = s->info.args.get("multipart-manifest");
1488 skip_manifest = (mm.compare("get") == 0);
1489
1490 return RGWGetObj_ObjStore::get_params();
1491}
1492
1493int RGWGetObj_ObjStore_SWIFT::send_response_data_error()
1494{
1495 std::string error_content;
1496 op_ret = error_handler(op_ret, &error_content);
1497 if (! op_ret) {
1498 /* The error handler has taken care of the error. */
1499 return 0;
1500 }
1501
1502 bufferlist error_bl;
1503 error_bl.append(error_content);
1504 return send_response_data(error_bl, 0, error_bl.length());
1505}
1506
1507int RGWGetObj_ObjStore_SWIFT::send_response_data(bufferlist& bl,
1508 const off_t bl_ofs,
1509 const off_t bl_len)
1510{
1511 string content_type;
1512
1513 if (sent_header) {
1514 goto send_data;
1515 }
1516
1517 if (custom_http_ret) {
1518 set_req_state_err(s, 0);
1519 dump_errno(s, custom_http_ret);
1520 } else {
1521 set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT
1522 : op_ret);
1523 dump_errno(s);
1524
31f18b77 1525 if (s->is_err()) {
7c673cae
FG
1526 end_header(s, NULL);
1527 return 0;
1528 }
1529 }
1530
1531 if (range_str) {
1532 dump_range(s, ofs, end, s->obj_size);
1533 }
1534
31f18b77 1535 if (s->is_err()) {
7c673cae
FG
1536 end_header(s, NULL);
1537 return 0;
1538 }
1539
1540 dump_content_length(s, total_len);
1541 dump_last_modified(s, lastmod);
1542 dump_header(s, "X-Timestamp", utime_t(lastmod));
1543 if (is_slo) {
1544 dump_header(s, "X-Static-Large-Object", "True");
1545 }
1546
1547 if (! op_ret) {
1548 if (! lo_etag.empty()) {
1549 dump_etag(s, lo_etag, true /* quoted */);
1550 } else {
1551 auto iter = attrs.find(RGW_ATTR_ETAG);
1552 if (iter != attrs.end()) {
11fdf7f2 1553 dump_etag(s, iter->second.to_str());
7c673cae
FG
1554 }
1555 }
1556
1557 get_contype_from_attrs(attrs, content_type);
9f95a23c 1558 dump_object_metadata(this, s, attrs);
7c673cae
FG
1559 }
1560
1561 end_header(s, this, !content_type.empty() ? content_type.c_str()
1562 : "binary/octet-stream");
1563
1564 sent_header = true;
1565
1566send_data:
1567 if (get_data && !op_ret) {
1568 const auto r = dump_body(s, bl.c_str() + bl_ofs, bl_len);
1569 if (r < 0) {
1570 return r;
1571 }
1572 }
1573 rgw_flush_formatter_and_reset(s, s->formatter);
1574
1575 return 0;
1576}
1577
1578void RGWOptionsCORS_ObjStore_SWIFT::send_response()
1579{
1580 string hdrs, exp_hdrs;
1581 uint32_t max_age = CORS_MAX_AGE_INVALID;
1582 /*EACCES means, there is no CORS registered yet for the bucket
1583 *ENOENT means, there is no match of the Origin in the list of CORSRule
1584 */
1585 if (op_ret == -ENOENT)
1586 op_ret = -EACCES;
1587 if (op_ret < 0) {
1588 set_req_state_err(s, op_ret);
1589 dump_errno(s);
1590 end_header(s, NULL);
1591 return;
1592 }
1593 get_response_params(hdrs, exp_hdrs, &max_age);
1594 dump_errno(s);
1595 dump_access_control(s, origin, req_meth, hdrs.c_str(), exp_hdrs.c_str(),
1596 max_age);
1597 end_header(s, NULL);
1598}
1599
1600int RGWBulkDelete_ObjStore_SWIFT::get_data(
1601 list<RGWBulkDelete::acct_path_t>& items, bool * const is_truncated)
1602{
1603 constexpr size_t MAX_LINE_SIZE = 2048;
1604
1605 RGWClientIOStreamBuf ciosb(static_cast<RGWRestfulIO&>(*(s->cio)),
1606 size_t(s->cct->_conf->rgw_max_chunk_size));
1607 istream cioin(&ciosb);
1608
1609 char buf[MAX_LINE_SIZE];
1610 while (cioin.getline(buf, sizeof(buf))) {
1611 string path_str(buf);
1612
9f95a23c 1613 ldpp_dout(this, 20) << "extracted Bulk Delete entry: " << path_str << dendl;
7c673cae
FG
1614
1615 RGWBulkDelete::acct_path_t path;
1616
1617 /* We need to skip all slashes at the beginning in order to preserve
1618 * compliance with Swift. */
1619 const size_t start_pos = path_str.find_first_not_of('/');
1620
1621 if (string::npos != start_pos) {
1622 /* Seperator is the first slash after the leading ones. */
1623 const size_t sep_pos = path_str.find('/', start_pos);
1624
1625 if (string::npos != sep_pos) {
31f18b77
FG
1626 path.bucket_name = url_decode(path_str.substr(start_pos,
1627 sep_pos - start_pos));
1628 path.obj_key = url_decode(path_str.substr(sep_pos + 1));
7c673cae
FG
1629 } else {
1630 /* It's guaranteed here that bucket name is at least one character
1631 * long and is different than slash. */
31f18b77 1632 path.bucket_name = url_decode(path_str.substr(start_pos));
7c673cae
FG
1633 }
1634
1635 items.push_back(path);
1636 }
1637
1638 if (items.size() == MAX_CHUNK_ENTRIES) {
1639 *is_truncated = true;
1640 return 0;
1641 }
1642 }
1643
1644 *is_truncated = false;
1645 return 0;
1646}
1647
1648void RGWBulkDelete_ObjStore_SWIFT::send_response()
1649{
1650 set_req_state_err(s, op_ret);
1651 dump_errno(s);
1652 end_header(s, this /* RGWOp */, nullptr /* contype */,
1653 CHUNKED_TRANSFER_ENCODING);
1654
1655 bulkdelete_respond(deleter->get_num_deleted(),
1656 deleter->get_num_unfound(),
1657 deleter->get_failures(),
1658 s->prot_flags,
1659 *s->formatter);
1660 rgw_flush_formatter_and_reset(s, s->formatter);
1661}
1662
1663
1664std::unique_ptr<RGWBulkUploadOp::StreamGetter>
1665RGWBulkUploadOp_ObjStore_SWIFT::create_stream()
1666{
1667 class SwiftStreamGetter : public StreamGetter {
9f95a23c 1668 const DoutPrefixProvider* dpp;
7c673cae
FG
1669 const size_t conlen;
1670 size_t curpos;
1671 req_state* const s;
1672
1673 public:
9f95a23c
TL
1674 SwiftStreamGetter(const DoutPrefixProvider* dpp, req_state* const s, const size_t conlen)
1675 : dpp(dpp),
1676 conlen(conlen),
7c673cae
FG
1677 curpos(0),
1678 s(s) {
1679 }
1680
1681 ssize_t get_at_most(size_t want, ceph::bufferlist& dst) override {
1682 /* maximum requested by a caller */
1683 /* data provided by client */
1684 /* RadosGW's limit. */
1685 const size_t max_chunk_size = \
1686 static_cast<size_t>(s->cct->_conf->rgw_max_chunk_size);
1687 const size_t max_to_read = std::min({ want, conlen - curpos, max_chunk_size });
1688
9f95a23c 1689 ldpp_dout(dpp, 20) << "bulk_upload: get_at_most max_to_read="
7c673cae
FG
1690 << max_to_read
1691 << ", dst.c_str()=" << reinterpret_cast<intptr_t>(dst.c_str()) << dendl;
1692
1693 bufferptr bp(max_to_read);
1694 const auto read_len = recv_body(s, bp.c_str(), max_to_read);
1695 dst.append(bp, 0, read_len);
1696 //const auto read_len = recv_body(s, dst.c_str(), max_to_read);
1697 if (read_len < 0) {
1698 return read_len;
1699 }
1700
1701 curpos += read_len;
1702 return curpos > s->cct->_conf->rgw_max_put_size ? -ERR_TOO_LARGE
1703 : read_len;
1704 }
1705
1706 ssize_t get_exactly(size_t want, ceph::bufferlist& dst) override {
9f95a23c 1707 ldpp_dout(dpp, 20) << "bulk_upload: get_exactly want=" << want << dendl;
7c673cae
FG
1708
1709 /* FIXME: do this in a loop. */
1710 const auto ret = get_at_most(want, dst);
9f95a23c 1711 ldpp_dout(dpp, 20) << "bulk_upload: get_exactly ret=" << ret << dendl;
7c673cae
FG
1712 if (ret < 0) {
1713 return ret;
1714 } else if (static_cast<size_t>(ret) != want) {
1715 return -EINVAL;
1716 } else {
1717 return want;
1718 }
1719 }
1720 };
1721
1722 if (! s->length) {
1723 op_ret = -EINVAL;
1724 return nullptr;
1725 } else {
9f95a23c 1726 ldpp_dout(this, 20) << "bulk upload: create_stream for length="
7c673cae
FG
1727 << s->length << dendl;
1728
1729 const size_t conlen = atoll(s->length);
9f95a23c 1730 return std::unique_ptr<SwiftStreamGetter>(new SwiftStreamGetter(this, s, conlen));
7c673cae
FG
1731 }
1732}
1733
1734void RGWBulkUploadOp_ObjStore_SWIFT::send_response()
1735{
1736 set_req_state_err(s, op_ret);
1737 dump_errno(s);
1738 end_header(s, this /* RGWOp */, nullptr /* contype */,
1739 CHUNKED_TRANSFER_ENCODING);
1740 rgw_flush_formatter_and_reset(s, s->formatter);
1741
1742 s->formatter->open_object_section("delete");
1743
1744 std::string resp_status;
1745 std::string resp_body;
1746
1747 if (! failures.empty()) {
1748 rgw_err err;
1749
1750 const auto last_err = { failures.back().err };
1751 if (boost::algorithm::contains(last_err, terminal_errors)) {
1752 /* The terminal errors are affecting the status of the whole upload. */
1753 set_req_state_err(err, failures.back().err, s->prot_flags);
1754 } else {
1755 set_req_state_err(err, ERR_INVALID_REQUEST, s->prot_flags);
1756 }
1757
1758 dump_errno(err, resp_status);
1759 } else if (0 == num_created && failures.empty()) {
1760 /* Nothing created, nothing failed. This means the archive contained no
1761 * entity we could understand (regular file or directory). We need to
1762 * send 400 Bad Request to an HTTP client in the internal status field. */
1763 dump_errno(400, resp_status);
1764 resp_body = "Invalid Tar File: No Valid Files";
1765 } else {
1766 /* 200 OK */
1767 dump_errno(201, resp_status);
1768 }
1769
1770 encode_json("Number Files Created", num_created, s->formatter);
1771 encode_json("Response Body", resp_body, s->formatter);
1772 encode_json("Response Status", resp_status, s->formatter);
1773
1774 s->formatter->open_array_section("Errors");
1775 for (const auto& fail_desc : failures) {
1776 s->formatter->open_array_section("object");
1777
1778 encode_json("Name", fail_desc.path, s->formatter);
1779
1780 rgw_err err;
1781 set_req_state_err(err, fail_desc.err, s->prot_flags);
1782 std::string status;
1783 dump_errno(err, status);
1784 encode_json("Status", status, s->formatter);
1785
1786 s->formatter->close_section();
1787 }
1788 s->formatter->close_section();
1789
1790 s->formatter->close_section();
1791 rgw_flush_formatter_and_reset(s, s->formatter);
1792}
1793
1794
1795void RGWGetCrossDomainPolicy_ObjStore_SWIFT::send_response()
1796{
1797 set_req_state_err(s, op_ret);
1798 dump_errno(s);
1799 end_header(s, this, "application/xml");
1800
1801 std::stringstream ss;
1802
1803 ss << R"(<?xml version="1.0"?>)" << "\n"
1804 << R"(<!DOCTYPE cross-domain-policy SYSTEM )"
1805 << R"("http://www.adobe.com/xml/dtds/cross-domain-policy.dtd" >)" << "\n"
1806 << R"(<cross-domain-policy>)" << "\n"
11fdf7f2 1807 << g_conf()->rgw_cross_domain_policy << "\n"
7c673cae
FG
1808 << R"(</cross-domain-policy>)";
1809
1810 dump_body(s, ss.str());
1811}
1812
1813void RGWGetHealthCheck_ObjStore_SWIFT::send_response()
1814{
1815 set_req_state_err(s, op_ret);
1816 dump_errno(s);
1817 end_header(s, this, "application/xml");
1818
1819 if (op_ret) {
1820 static constexpr char DISABLED[] = "DISABLED BY FILE";
1821 dump_body(s, DISABLED, strlen(DISABLED));
1822 }
1823}
1824
1825const vector<pair<string, RGWInfo_ObjStore_SWIFT::info>> RGWInfo_ObjStore_SWIFT::swift_info =
1826{
1827 {"bulk_delete", {false, nullptr}},
1828 {"container_quotas", {false, nullptr}},
1829 {"swift", {false, RGWInfo_ObjStore_SWIFT::list_swift_data}},
1830 {"tempurl", { false, RGWInfo_ObjStore_SWIFT::list_tempurl_data}},
1831 {"slo", {false, RGWInfo_ObjStore_SWIFT::list_slo_data}},
1832 {"account_quotas", {false, nullptr}},
1833 {"staticweb", {false, nullptr}},
224ce89b 1834 {"tempauth", {false, RGWInfo_ObjStore_SWIFT::list_tempauth_data}},
7c673cae
FG
1835};
1836
1837void RGWInfo_ObjStore_SWIFT::execute()
1838{
1839 bool is_admin_info_enabled = false;
1840
1841 const string& swiftinfo_sig = s->info.args.get("swiftinfo_sig");
1842 const string& swiftinfo_expires = s->info.args.get("swiftinfo_expires");
1843
1844 if (!swiftinfo_sig.empty() &&
1845 !swiftinfo_expires.empty() &&
9f95a23c 1846 !is_expired(swiftinfo_expires, this)) {
7c673cae
FG
1847 is_admin_info_enabled = true;
1848 }
1849
1850 s->formatter->open_object_section("info");
1851
1852 for (const auto& pair : swift_info) {
1853 if(!is_admin_info_enabled && pair.second.is_admin_info)
1854 continue;
1855
1856 if (!pair.second.list_data) {
1857 s->formatter->open_object_section((pair.first).c_str());
1858 s->formatter->close_section();
1859 }
1860 else {
9f95a23c 1861 pair.second.list_data(*(s->formatter), s->cct->_conf, *store->getRados());
7c673cae
FG
1862 }
1863 }
1864
1865 s->formatter->close_section();
1866}
1867
1868void RGWInfo_ObjStore_SWIFT::send_response()
1869{
1870 if (op_ret < 0) {
1871 op_ret = STATUS_NO_CONTENT;
1872 }
1873 set_req_state_err(s, op_ret);
1874 dump_errno(s);
1875 end_header(s, this);
1876 rgw_flush_formatter_and_reset(s, s->formatter);
1877}
1878
1879void RGWInfo_ObjStore_SWIFT::list_swift_data(Formatter& formatter,
11fdf7f2 1880 const ConfigProxy& config,
7c673cae
FG
1881 RGWRados& store)
1882{
1883 formatter.open_object_section("swift");
11fdf7f2 1884 formatter.dump_int("max_file_size", config->rgw_max_put_size);
7c673cae
FG
1885 formatter.dump_int("container_listing_limit", RGW_LIST_BUCKETS_LIMIT_MAX);
1886
1887 string ceph_version(CEPH_GIT_NICE_VER);
1888 formatter.dump_string("version", ceph_version);
3efd9988
FG
1889
1890 const size_t max_attr_name_len = \
11fdf7f2 1891 g_conf().get_val<Option::size_t>("rgw_max_attr_name_len");
3efd9988
FG
1892 if (max_attr_name_len) {
1893 const size_t meta_name_limit = \
1894 max_attr_name_len - strlen(RGW_ATTR_PREFIX RGW_AMZ_META_PREFIX);
1895 formatter.dump_int("max_meta_name_length", meta_name_limit);
1896 }
1897
11fdf7f2 1898 const size_t meta_value_limit = g_conf().get_val<Option::size_t>("rgw_max_attr_size");
3efd9988
FG
1899 if (meta_value_limit) {
1900 formatter.dump_int("max_meta_value_length", meta_value_limit);
1901 }
1902
1903 const size_t meta_num_limit = \
11fdf7f2 1904 g_conf().get_val<uint64_t>("rgw_max_attrs_num_in_req");
3efd9988
FG
1905 if (meta_num_limit) {
1906 formatter.dump_int("max_meta_count", meta_num_limit);
1907 }
7c673cae
FG
1908
1909 formatter.open_array_section("policies");
11fdf7f2 1910 const RGWZoneGroup& zonegroup = store.svc.zone->get_zonegroup();
7c673cae
FG
1911
1912 for (const auto& placement_targets : zonegroup.placement_targets) {
1913 formatter.open_object_section("policy");
11fdf7f2 1914 if (placement_targets.second.name.compare(zonegroup.default_placement.name) == 0)
7c673cae
FG
1915 formatter.dump_bool("default", true);
1916 formatter.dump_string("name", placement_targets.second.name.c_str());
1917 formatter.close_section();
1918 }
1919 formatter.close_section();
1920
1921 formatter.dump_int("max_object_name_size", RGWHandler_REST::MAX_OBJ_NAME_LEN);
1922 formatter.dump_bool("strict_cors_mode", true);
1923 formatter.dump_int("max_container_name_length", RGWHandler_REST::MAX_BUCKET_NAME_LEN);
1924 formatter.close_section();
1925}
1926
224ce89b 1927void RGWInfo_ObjStore_SWIFT::list_tempauth_data(Formatter& formatter,
11fdf7f2 1928 const ConfigProxy& config,
224ce89b
WB
1929 RGWRados& store)
1930{
1931 formatter.open_object_section("tempauth");
1932 formatter.dump_bool("account_acls", true);
1933 formatter.close_section();
1934}
7c673cae 1935void RGWInfo_ObjStore_SWIFT::list_tempurl_data(Formatter& formatter,
11fdf7f2 1936 const ConfigProxy& config,
7c673cae
FG
1937 RGWRados& store)
1938{
1939 formatter.open_object_section("tempurl");
1940 formatter.open_array_section("methods");
1941 formatter.dump_string("methodname", "GET");
1942 formatter.dump_string("methodname", "HEAD");
1943 formatter.dump_string("methodname", "PUT");
1944 formatter.dump_string("methodname", "POST");
1945 formatter.dump_string("methodname", "DELETE");
1946 formatter.close_section();
1947 formatter.close_section();
1948}
1949
1950void RGWInfo_ObjStore_SWIFT::list_slo_data(Formatter& formatter,
11fdf7f2 1951 const ConfigProxy& config,
7c673cae
FG
1952 RGWRados& store)
1953{
1954 formatter.open_object_section("slo");
11fdf7f2 1955 formatter.dump_int("max_manifest_segments", config->rgw_max_slo_entries);
7c673cae
FG
1956 formatter.close_section();
1957}
1958
9f95a23c 1959bool RGWInfo_ObjStore_SWIFT::is_expired(const std::string& expires, const DoutPrefixProvider *dpp)
7c673cae
FG
1960{
1961 string err;
1962 const utime_t now = ceph_clock_now();
1963 const uint64_t expiration = (uint64_t)strict_strtoll(expires.c_str(),
1964 10, &err);
1965 if (!err.empty()) {
9f95a23c 1966 ldpp_dout(dpp, 5) << "failed to parse siginfo_expires: " << err << dendl;
7c673cae
FG
1967 return true;
1968 }
1969
1970 if (expiration <= (uint64_t)now.sec()) {
9f95a23c 1971 ldpp_dout(dpp, 5) << "siginfo expired: " << expiration << " <= " << now.sec() << dendl;
7c673cae
FG
1972 return true;
1973 }
1974
1975 return false;
1976}
1977
1978
9f95a23c 1979void RGWFormPost::init(rgw::sal::RGWRadosStore* const store,
7c673cae
FG
1980 req_state* const s,
1981 RGWHandler* const dialect_handler)
1982{
1983 prefix = std::move(s->object.name);
1984 s->object = rgw_obj_key();
1985
1986 return RGWPostObj_ObjStore::init(store, s, dialect_handler);
1987}
1988
1989std::size_t RGWFormPost::get_max_file_size() /*const*/
1990{
1991 std::string max_str = get_part_str(ctrl_parts, "max_file_size", "0");
1992
1993 std::string err;
1994 const std::size_t max_file_size =
1995 static_cast<uint64_t>(strict_strtoll(max_str.c_str(), 10, &err));
1996
1997 if (! err.empty()) {
9f95a23c 1998 ldpp_dout(this, 5) << "failed to parse FormPost's max_file_size: " << err
7c673cae
FG
1999 << dendl;
2000 return 0;
2001 }
2002
2003 return max_file_size;
2004}
2005
2006bool RGWFormPost::is_non_expired()
2007{
2008 std::string expires = get_part_str(ctrl_parts, "expires", "0");
2009
2010 std::string err;
2011 const uint64_t expires_timestamp =
2012 static_cast<uint64_t>(strict_strtoll(expires.c_str(), 10, &err));
2013
2014 if (! err.empty()) {
9f95a23c 2015 ldpp_dout(this, 5) << "failed to parse FormPost's expires: " << err << dendl;
7c673cae
FG
2016 return false;
2017 }
2018
2019 const utime_t now = ceph_clock_now();
2020 if (expires_timestamp <= static_cast<uint64_t>(now.sec())) {
9f95a23c 2021 ldpp_dout(this, 5) << "FormPost form expired: "
7c673cae
FG
2022 << expires_timestamp << " <= " << now.sec() << dendl;
2023 return false;
2024 }
2025
2026 return true;
2027}
2028
2029bool RGWFormPost::is_integral()
2030{
2031 const std::string form_signature = get_part_str(ctrl_parts, "signature");
2032
31f18b77 2033 try {
9f95a23c 2034 get_owner_info(s, s->user->get_info());
31f18b77
FG
2035 s->auth.identity = rgw::auth::transform_old_authinfo(s);
2036 } catch (...) {
9f95a23c 2037 ldpp_dout(this, 5) << "cannot get user_info of account's owner" << dendl;
31f18b77
FG
2038 return false;
2039 }
2040
9f95a23c 2041 for (const auto& kv : s->user->get_info().temp_url_keys) {
7c673cae
FG
2042 const int temp_url_key_num = kv.first;
2043 const string& temp_url_key = kv.second;
2044
2045 if (temp_url_key.empty()) {
2046 continue;
2047 }
2048
2049 SignatureHelper sig_helper;
2050 sig_helper.calc(temp_url_key,
2051 s->info.request_uri,
2052 get_part_str(ctrl_parts, "redirect"),
2053 get_part_str(ctrl_parts, "max_file_size", "0"),
2054 get_part_str(ctrl_parts, "max_file_count", "0"),
2055 get_part_str(ctrl_parts, "expires", "0"));
2056
2057 const auto local_sig = sig_helper.get_signature();
2058
9f95a23c 2059 ldpp_dout(this, 20) << "FormPost signature [" << temp_url_key_num << "]"
7c673cae
FG
2060 << " (calculated): " << local_sig << dendl;
2061
2062 if (sig_helper.is_equal_to(form_signature)) {
2063 return true;
2064 } else {
9f95a23c 2065 ldpp_dout(this, 5) << "FormPost's signature mismatch: "
7c673cae
FG
2066 << local_sig << " != " << form_signature << dendl;
2067 }
2068 }
2069
2070 return false;
2071}
2072
31f18b77
FG
2073void RGWFormPost::get_owner_info(const req_state* const s,
2074 RGWUserInfo& owner_info) const
2075{
2076 /* We cannot use req_state::bucket_name because it isn't available
2077 * now. It will be initialized in RGWHandler_REST_SWIFT::postauth_init(). */
2078 const string& bucket_name = s->init_state.url_bucket;
2079
9f95a23c
TL
2080 auto user_ctl = store->ctl()->user;
2081
31f18b77
FG
2082 /* TempURL in Formpost only requires that bucket name is specified. */
2083 if (bucket_name.empty()) {
2084 throw -EPERM;
2085 }
2086
2087 string bucket_tenant;
2088 if (!s->account_name.empty()) {
2089 RGWUserInfo uinfo;
2090 bool found = false;
2091
2092 const rgw_user uid(s->account_name);
2093 if (uid.tenant.empty()) {
2094 const rgw_user tenanted_uid(uid.id, uid.id);
2095
9f95a23c 2096 if (user_ctl->get_info_by_uid(tenanted_uid, &uinfo, s->yield) >= 0) {
31f18b77
FG
2097 /* Succeeded. */
2098 bucket_tenant = uinfo.user_id.tenant;
2099 found = true;
2100 }
2101 }
2102
9f95a23c 2103 if (!found && user_ctl->get_info_by_uid(uid, &uinfo, s->yield) < 0) {
31f18b77
FG
2104 throw -EPERM;
2105 } else {
2106 bucket_tenant = uinfo.user_id.tenant;
2107 }
2108 }
2109
2110 /* Need to get user info of bucket owner. */
2111 RGWBucketInfo bucket_info;
9f95a23c 2112 int ret = store->getRados()->get_bucket_info(store->svc(),
31f18b77 2113 bucket_tenant, bucket_name,
9f95a23c 2114 bucket_info, nullptr, s->yield);
31f18b77
FG
2115 if (ret < 0) {
2116 throw ret;
2117 }
2118
9f95a23c 2119 ldpp_dout(this, 20) << "temp url user (bucket owner): " << bucket_info.owner
31f18b77
FG
2120 << dendl;
2121
9f95a23c 2122 if (user_ctl->get_info_by_uid(bucket_info.owner, &owner_info, s->yield) < 0) {
31f18b77
FG
2123 throw -EPERM;
2124 }
2125}
2126
7c673cae
FG
2127int RGWFormPost::get_params()
2128{
2129 /* The parentt class extracts boundary info from the Content-Type. */
2130 int ret = RGWPostObj_ObjStore::get_params();
2131 if (ret < 0) {
2132 return ret;
2133 }
2134
9f95a23c 2135 policy.create_default(s->user->get_id(), s->user->get_display_name());
7c673cae
FG
2136
2137 /* Let's start parsing the HTTP body by parsing each form part step-
2138 * by-step till encountering the first part with file data. */
2139 do {
2140 struct post_form_part part;
2141 ret = read_form_part_header(&part, stream_done);
2142 if (ret < 0) {
2143 return ret;
2144 }
2145
11fdf7f2 2146 if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
9f95a23c 2147 ldpp_dout(this, 20) << "read part header -- part.name="
7c673cae
FG
2148 << part.name << dendl;
2149
2150 for (const auto& pair : part.fields) {
9f95a23c
TL
2151 ldpp_dout(this, 20) << "field.name=" << pair.first << dendl;
2152 ldpp_dout(this, 20) << "field.val=" << pair.second.val << dendl;
2153 ldpp_dout(this, 20) << "field.params:" << dendl;
7c673cae
FG
2154
2155 for (const auto& param_pair : pair.second.params) {
9f95a23c 2156 ldpp_dout(this, 20) << " " << param_pair.first
7c673cae
FG
2157 << " -> " << param_pair.second << dendl;
2158 }
2159 }
2160 }
2161
2162 if (stream_done) {
2163 /* Unexpected here. */
2164 err_msg = "Malformed request";
2165 return -EINVAL;
2166 }
2167
2168 const auto field_iter = part.fields.find("Content-Disposition");
2169 if (std::end(part.fields) != field_iter &&
2170 std::end(field_iter->second.params) != field_iter->second.params.find("filename")) {
2171 /* First data part ahead. */
2172 current_data_part = std::move(part);
2173
2174 /* Stop the iteration. We can assume that all control parts have been
2175 * already parsed. The rest of HTTP body should contain data parts
2176 * only. They will be picked up by ::get_data(). */
2177 break;
2178 } else {
2179 /* Control part ahead. Receive, parse and store for later usage. */
2180 bool boundary;
2181 ret = read_data(part.data, s->cct->_conf->rgw_max_chunk_size,
2182 boundary, stream_done);
2183 if (ret < 0) {
2184 return ret;
2185 } else if (! boundary) {
2186 err_msg = "Couldn't find boundary";
2187 return -EINVAL;
2188 }
2189
2190 ctrl_parts[part.name] = std::move(part);
2191 }
2192 } while (! stream_done);
2193
2194 min_len = 0;
2195 max_len = get_max_file_size();
2196
2197 if (! current_data_part) {
2198 err_msg = "FormPost: no files to process";
2199 return -EINVAL;
2200 }
2201
2202 if (! is_non_expired()) {
2203 err_msg = "FormPost: Form Expired";
2204 return -EPERM;
2205 }
2206
2207 if (! is_integral()) {
2208 err_msg = "FormPost: Invalid Signature";
2209 return -EPERM;
2210 }
2211
2212 return 0;
2213}
2214
2215std::string RGWFormPost::get_current_filename() const
2216{
2217 try {
2218 const auto& field = current_data_part->fields.at("Content-Disposition");
2219 const auto iter = field.params.find("filename");
2220
2221 if (std::end(field.params) != iter) {
2222 return prefix + iter->second;
2223 }
2224 } catch (std::out_of_range&) {
2225 /* NOP */;
2226 }
2227
2228 return prefix;
2229}
2230
2231std::string RGWFormPost::get_current_content_type() const
2232{
2233 try {
2234 const auto& field = current_data_part->fields.at("Content-Type");
2235 return field.val;
2236 } catch (std::out_of_range&) {
2237 /* NOP */;
2238 }
2239
2240 return std::string();
2241}
2242
2243bool RGWFormPost::is_next_file_to_upload()
2244{
2245 if (! stream_done) {
2246 /* We have at least one additional part in the body. */
2247 struct post_form_part part;
2248 int r = read_form_part_header(&part, stream_done);
2249 if (r < 0) {
2250 return false;
2251 }
2252
2253 const auto field_iter = part.fields.find("Content-Disposition");
2254 if (std::end(part.fields) != field_iter) {
2255 const auto& params = field_iter->second.params;
31f18b77 2256 const auto& filename_iter = params.find("filename");
7c673cae 2257
31f18b77 2258 if (std::end(params) != filename_iter && ! filename_iter->second.empty()) {
7c673cae
FG
2259 current_data_part = std::move(part);
2260 return true;
2261 }
2262 }
2263 }
2264
2265 return false;
2266}
2267
2268int RGWFormPost::get_data(ceph::bufferlist& bl, bool& again)
2269{
2270 bool boundary;
2271
2272 int r = read_data(bl, s->cct->_conf->rgw_max_chunk_size,
2273 boundary, stream_done);
2274 if (r < 0) {
2275 return r;
2276 }
2277
2278 /* Tell RGWPostObj::execute() that it has some data to put. */
2279 again = !boundary;
2280
2281 return bl.length();
2282}
2283
2284void RGWFormPost::send_response()
2285{
2286 std::string redirect = get_part_str(ctrl_parts, "redirect");
2287 if (! redirect.empty()) {
2288 op_ret = STATUS_REDIRECT;
2289 }
2290
2291 set_req_state_err(s, op_ret);
31f18b77 2292 s->err.err_code = err_msg;
7c673cae
FG
2293 dump_errno(s);
2294 if (! redirect.empty()) {
2295 dump_redirect(s, redirect);
2296 }
2297 end_header(s, this);
2298}
2299
2300bool RGWFormPost::is_formpost_req(req_state* const s)
2301{
2302 std::string content_type;
2303 std::map<std::string, std::string> params;
2304
2305 parse_boundary_params(s->info.env->get("CONTENT_TYPE", ""),
2306 content_type, params);
2307
2308 return boost::algorithm::iequals(content_type, "multipart/form-data") &&
2309 params.count("boundary") > 0;
2310}
2311
2312
2313RGWOp *RGWHandler_REST_Service_SWIFT::op_get()
2314{
2315 return new RGWListBuckets_ObjStore_SWIFT;
2316}
2317
2318RGWOp *RGWHandler_REST_Service_SWIFT::op_head()
2319{
2320 return new RGWStatAccount_ObjStore_SWIFT;
2321}
2322
2323RGWOp *RGWHandler_REST_Service_SWIFT::op_put()
2324{
2325 if (s->info.args.exists("extract-archive")) {
2326 return new RGWBulkUploadOp_ObjStore_SWIFT;
2327 }
2328 return nullptr;
2329}
2330
2331RGWOp *RGWHandler_REST_Service_SWIFT::op_post()
2332{
2333 if (s->info.args.exists("bulk-delete")) {
2334 return new RGWBulkDelete_ObjStore_SWIFT;
2335 }
2336 return new RGWPutMetadataAccount_ObjStore_SWIFT;
2337}
2338
2339RGWOp *RGWHandler_REST_Service_SWIFT::op_delete()
2340{
2341 if (s->info.args.exists("bulk-delete")) {
2342 return new RGWBulkDelete_ObjStore_SWIFT;
2343 }
2344 return NULL;
2345}
2346
2347int RGWSwiftWebsiteHandler::serve_errordoc(const int http_ret,
2348 const std::string error_doc)
2349{
2350 /* Try to throw it all away. */
2351 s->formatter->reset();
2352
2353 class RGWGetErrorPage : public RGWGetObj_ObjStore_SWIFT {
2354 public:
9f95a23c 2355 RGWGetErrorPage(rgw::sal::RGWRadosStore* const store,
7c673cae
FG
2356 RGWHandler_REST* const handler,
2357 req_state* const s,
2358 const int http_ret) {
2359 /* Calling a virtual from the base class is safe as the subobject should
2360 * be properly initialized and we haven't overridden the init method. */
2361 init(store, s, handler);
2362 set_get_data(true);
2363 set_custom_http_response(http_ret);
2364 }
2365
2366 int error_handler(const int err_no,
2367 std::string* const error_content) override {
2368 /* Enforce that any error generated while getting the error page will
2369 * not be send to a client. This allows us to recover from the double
2370 * fault situation by sending the original message. */
2371 return 0;
2372 }
2373 } get_errpage_op(store, handler, s, http_ret);
2374
2375 s->object = std::to_string(http_ret) + error_doc;
2376
2377 RGWOp* newop = &get_errpage_op;
2378 RGWRequest req(0);
2379 return rgw_process_authenticated(handler, newop, &req, s, true);
2380}
2381
2382int RGWSwiftWebsiteHandler::error_handler(const int err_no,
2383 std::string* const error_content)
2384{
2385 const auto& ws_conf = s->bucket_info.website_conf;
2386
2387 if (can_be_website_req() && ! ws_conf.error_doc.empty()) {
31f18b77
FG
2388 set_req_state_err(s, err_no);
2389 return serve_errordoc(s->err.http_ret, ws_conf.error_doc);
7c673cae
FG
2390 }
2391
2392 /* Let's go to the default, no-op handler. */
2393 return err_no;
2394}
2395
2396bool RGWSwiftWebsiteHandler::is_web_mode() const
2397{
2398 const boost::string_ref webmode = s->info.env->get("HTTP_X_WEB_MODE", "");
2399 return boost::algorithm::iequals(webmode, "true");
2400}
2401
2402bool RGWSwiftWebsiteHandler::can_be_website_req() const
2403{
2404 /* Static website works only with the GET or HEAD method. Nothing more. */
2405 static const std::set<boost::string_ref> ws_methods = { "GET", "HEAD" };
2406 if (ws_methods.count(s->info.method) == 0) {
2407 return false;
2408 }
2409
2410 /* We also need to handle early failures from the auth system. In such cases
2411 * req_state::auth.identity may be empty. Let's treat that the same way as
2412 * the anonymous access. */
2413 if (! s->auth.identity) {
2414 return true;
2415 }
2416
2417 /* Swift serves websites only for anonymous requests unless client explicitly
2418 * requested this behaviour by supplying X-Web-Mode HTTP header set to true. */
2419 if (s->auth.identity->is_anonymous() || is_web_mode()) {
2420 return true;
2421 }
2422
2423 return false;
2424}
2425
2426RGWOp* RGWSwiftWebsiteHandler::get_ws_redirect_op()
2427{
2428 class RGWMovedPermanently: public RGWOp {
2429 const std::string location;
2430 public:
11fdf7f2 2431 explicit RGWMovedPermanently(const std::string& location)
7c673cae
FG
2432 : location(location) {
2433 }
2434
2435 int verify_permission() override {
2436 return 0;
2437 }
2438
2439 void execute() override {
2440 op_ret = -ERR_PERMANENT_REDIRECT;
2441 return;
2442 }
2443
2444 void send_response() override {
2445 set_req_state_err(s, op_ret);
2446 dump_errno(s);
2447 dump_content_length(s, 0);
2448 dump_redirect(s, location);
2449 end_header(s, this);
2450 }
2451
11fdf7f2 2452 const char* name() const override {
7c673cae
FG
2453 return "RGWMovedPermanently";
2454 }
2455 };
2456
2457 return new RGWMovedPermanently(s->info.request_uri + '/');
2458}
2459
2460RGWOp* RGWSwiftWebsiteHandler::get_ws_index_op()
2461{
2462 /* Retarget to get obj on requested index file. */
2463 if (! s->object.empty()) {
2464 s->object = s->object.name +
2465 s->bucket_info.website_conf.get_index_doc();
2466 } else {
2467 s->object = s->bucket_info.website_conf.get_index_doc();
2468 }
2469
2470 auto getop = new RGWGetObj_ObjStore_SWIFT;
2471 getop->set_get_data(boost::algorithm::equals("GET", s->info.method));
2472
2473 return getop;
2474}
2475
2476RGWOp* RGWSwiftWebsiteHandler::get_ws_listing_op()
2477{
2478 class RGWWebsiteListing : public RGWListBucket_ObjStore_SWIFT {
2479 const std::string prefix_override;
2480
2481 int get_params() override {
2482 prefix = prefix_override;
2483 max = default_max;
2484 delimiter = "/";
2485 return 0;
2486 }
2487
2488 void send_response() override {
2489 /* Generate the header now. */
2490 set_req_state_err(s, op_ret);
2491 dump_errno(s);
2492 dump_container_metadata(s, bucket, bucket_quota,
2493 s->bucket_info.website_conf);
2494 end_header(s, this, "text/html");
2495 if (op_ret < 0) {
2496 return;
2497 }
2498
2499 /* Now it's the time to start generating HTML bucket listing.
2500 * All the crazy stuff with crafting tags will be delegated to
2501 * RGWSwiftWebsiteListingFormatter. */
2502 std::stringstream ss;
2503 RGWSwiftWebsiteListingFormatter htmler(ss, prefix);
2504
2505 const auto& ws_conf = s->bucket_info.website_conf;
2506 htmler.generate_header(s->decoded_uri,
2507 ws_conf.listing_css_doc);
2508
2509 for (const auto& pair : common_prefixes) {
2510 std::string subdir_name = pair.first;
2511 if (! subdir_name.empty()) {
2512 /* To be compliant with Swift we need to remove the trailing
2513 * slash. */
2514 subdir_name.pop_back();
2515 }
2516
2517 htmler.dump_subdir(subdir_name);
2518 }
2519
2520 for (const rgw_bucket_dir_entry& obj : objs) {
2521 if (! common_prefixes.count(obj.key.name + '/')) {
2522 htmler.dump_object(obj);
2523 }
2524 }
2525
2526 htmler.generate_footer();
2527 dump_body(s, ss.str());
2528 }
2529 public:
2530 /* Taking prefix_override by value to leverage std::string r-value ref
2531 * ctor and thus avoid extra memory copying/increasing ref counter. */
11fdf7f2 2532 explicit RGWWebsiteListing(std::string prefix_override)
7c673cae
FG
2533 : prefix_override(std::move(prefix_override)) {
2534 }
2535 };
2536
2537 std::string prefix = std::move(s->object.name);
2538 s->object = rgw_obj_key();
2539
2540 return new RGWWebsiteListing(std::move(prefix));
2541}
2542
2543bool RGWSwiftWebsiteHandler::is_web_dir() const
2544{
31f18b77 2545 std::string subdir_name = url_decode(s->object.name);
7c673cae
FG
2546
2547 /* Remove character from the subdir name if it is "/". */
2548 if (subdir_name.empty()) {
2549 return false;
2550 } else if (subdir_name.back() == '/') {
2551 subdir_name.pop_back();
2552 }
2553
31f18b77 2554 rgw_obj obj(s->bucket, std::move(subdir_name));
7c673cae
FG
2555
2556 /* First, get attrset of the object we'll try to retrieve. */
2557 RGWObjectCtx& obj_ctx = *static_cast<RGWObjectCtx *>(s->obj_ctx);
11fdf7f2
TL
2558 obj_ctx.set_atomic(obj);
2559 obj_ctx.set_prefetch_data(obj);
7c673cae
FG
2560
2561 RGWObjState* state = nullptr;
9f95a23c 2562 if (store->getRados()->get_obj_state(&obj_ctx, s->bucket_info, obj, &state, false, s->yield) < 0) {
7c673cae
FG
2563 return false;
2564 }
2565
2566 /* A nonexistent object cannot be a considered as a marker representing
2567 * the emulation of catalog in FS hierarchy. */
2568 if (! state->exists) {
2569 return false;
2570 }
2571
2572 /* Decode the content type. */
2573 std::string content_type;
2574 get_contype_from_attrs(state->attrset, content_type);
2575
2576 const auto& ws_conf = s->bucket_info.website_conf;
2577 const std::string subdir_marker = ws_conf.subdir_marker.empty()
2578 ? "application/directory"
2579 : ws_conf.subdir_marker;
2580 return subdir_marker == content_type && state->size <= 1;
2581}
2582
9f95a23c 2583bool RGWSwiftWebsiteHandler::is_index_present(const std::string& index) const
7c673cae
FG
2584{
2585 rgw_obj obj(s->bucket, index);
2586
2587 RGWObjectCtx& obj_ctx = *static_cast<RGWObjectCtx *>(s->obj_ctx);
11fdf7f2
TL
2588 obj_ctx.set_atomic(obj);
2589 obj_ctx.set_prefetch_data(obj);
7c673cae
FG
2590
2591 RGWObjState* state = nullptr;
9f95a23c 2592 if (store->getRados()->get_obj_state(&obj_ctx, s->bucket_info, obj, &state, false, s->yield) < 0) {
7c673cae
FG
2593 return false;
2594 }
2595
2596 /* A nonexistent object cannot be a considered as a viable index. We will
2597 * try to list the bucket or - if this is impossible - return an error. */
2598 return state->exists;
2599}
2600
2601int RGWSwiftWebsiteHandler::retarget_bucket(RGWOp* op, RGWOp** new_op)
2602{
9f95a23c 2603 ldpp_dout(s, 10) << "Starting retarget" << dendl;
7c673cae
FG
2604 RGWOp* op_override = nullptr;
2605
2606 /* In Swift static web content is served if the request is anonymous or
2607 * has X-Web-Mode HTTP header specified to true. */
2608 if (can_be_website_req()) {
2609 const auto& ws_conf = s->bucket_info.website_conf;
2610 const auto& index = s->bucket_info.website_conf.get_index_doc();
2611
2612 if (s->decoded_uri.back() != '/') {
2613 op_override = get_ws_redirect_op();
2614 } else if (! index.empty() && is_index_present(index)) {
2615 op_override = get_ws_index_op();
2616 } else if (ws_conf.listing_enabled) {
2617 op_override = get_ws_listing_op();
2618 }
2619 }
2620
2621 if (op_override) {
2622 handler->put_op(op);
2623 op_override->init(store, s, handler);
2624
2625 *new_op = op_override;
2626 } else {
2627 *new_op = op;
2628 }
2629
2630 /* Return 404 Not Found is the request has web mode enforced but we static web
2631 * wasn't able to serve it accordingly. */
2632 return ! op_override && is_web_mode() ? -ENOENT : 0;
2633}
2634
2635int RGWSwiftWebsiteHandler::retarget_object(RGWOp* op, RGWOp** new_op)
2636{
9f95a23c 2637 ldpp_dout(s, 10) << "Starting object retarget" << dendl;
7c673cae
FG
2638 RGWOp* op_override = nullptr;
2639
2640 /* In Swift static web content is served if the request is anonymous or
2641 * has X-Web-Mode HTTP header specified to true. */
2642 if (can_be_website_req() && is_web_dir()) {
2643 const auto& ws_conf = s->bucket_info.website_conf;
2644 const auto& index = s->bucket_info.website_conf.get_index_doc();
2645
2646 if (s->decoded_uri.back() != '/') {
2647 op_override = get_ws_redirect_op();
2648 } else if (! index.empty() && is_index_present(index)) {
2649 op_override = get_ws_index_op();
2650 } else if (ws_conf.listing_enabled) {
2651 op_override = get_ws_listing_op();
2652 }
2653 } else {
2654 /* A regular request or the specified object isn't a subdirectory marker.
2655 * We don't need any re-targeting. Error handling (like sending a custom
2656 * error page) will be performed by error_handler of the actual RGWOp. */
2657 return 0;
2658 }
2659
2660 if (op_override) {
2661 handler->put_op(op);
2662 op_override->init(store, s, handler);
2663
2664 *new_op = op_override;
2665 } else {
2666 *new_op = op;
2667 }
2668
2669 /* Return 404 Not Found if we aren't able to re-target for subdir marker. */
2670 return ! op_override ? -ENOENT : 0;
2671}
2672
2673
2674RGWOp *RGWHandler_REST_Bucket_SWIFT::get_obj_op(bool get_data)
2675{
2676 if (is_acl_op()) {
2677 return new RGWGetACLs_ObjStore_SWIFT;
2678 }
2679
2680 if (get_data)
2681 return new RGWListBucket_ObjStore_SWIFT;
2682 else
2683 return new RGWStatBucket_ObjStore_SWIFT;
2684}
2685
2686RGWOp *RGWHandler_REST_Bucket_SWIFT::op_get()
2687{
2688 return get_obj_op(true);
2689}
2690
2691RGWOp *RGWHandler_REST_Bucket_SWIFT::op_head()
2692{
2693 return get_obj_op(false);
2694}
2695
2696RGWOp *RGWHandler_REST_Bucket_SWIFT::op_put()
2697{
2698 if (is_acl_op()) {
2699 return new RGWPutACLs_ObjStore_SWIFT;
2700 }
2701 if(s->info.args.exists("extract-archive")) {
2702 return new RGWBulkUploadOp_ObjStore_SWIFT;
2703 }
2704 return new RGWCreateBucket_ObjStore_SWIFT;
2705}
2706
2707RGWOp *RGWHandler_REST_Bucket_SWIFT::op_delete()
2708{
2709 return new RGWDeleteBucket_ObjStore_SWIFT;
2710}
2711
2712RGWOp *RGWHandler_REST_Bucket_SWIFT::op_post()
2713{
2714 if (RGWFormPost::is_formpost_req(s)) {
2715 return new RGWFormPost;
2716 } else {
2717 return new RGWPutMetadataBucket_ObjStore_SWIFT;
2718 }
2719}
2720
2721RGWOp *RGWHandler_REST_Bucket_SWIFT::op_options()
2722{
2723 return new RGWOptionsCORS_ObjStore_SWIFT;
2724}
2725
2726
2727RGWOp *RGWHandler_REST_Obj_SWIFT::get_obj_op(bool get_data)
2728{
2729 if (is_acl_op()) {
2730 return new RGWGetACLs_ObjStore_SWIFT;
2731 }
2732
2733 RGWGetObj_ObjStore_SWIFT *get_obj_op = new RGWGetObj_ObjStore_SWIFT;
2734 get_obj_op->set_get_data(get_data);
2735 return get_obj_op;
2736}
2737
2738RGWOp *RGWHandler_REST_Obj_SWIFT::op_get()
2739{
2740 return get_obj_op(true);
2741}
2742
2743RGWOp *RGWHandler_REST_Obj_SWIFT::op_head()
2744{
2745 return get_obj_op(false);
2746}
2747
2748RGWOp *RGWHandler_REST_Obj_SWIFT::op_put()
2749{
2750 if (is_acl_op()) {
2751 return new RGWPutACLs_ObjStore_SWIFT;
2752 }
2753 if(s->info.args.exists("extract-archive")) {
2754 return new RGWBulkUploadOp_ObjStore_SWIFT;
2755 }
2756 if (s->init_state.src_bucket.empty())
2757 return new RGWPutObj_ObjStore_SWIFT;
2758 else
2759 return new RGWCopyObj_ObjStore_SWIFT;
2760}
2761
2762RGWOp *RGWHandler_REST_Obj_SWIFT::op_delete()
2763{
2764 return new RGWDeleteObj_ObjStore_SWIFT;
2765}
2766
2767RGWOp *RGWHandler_REST_Obj_SWIFT::op_post()
2768{
2769 if (RGWFormPost::is_formpost_req(s)) {
2770 return new RGWFormPost;
2771 } else {
2772 return new RGWPutMetadataObject_ObjStore_SWIFT;
2773 }
2774}
2775
2776RGWOp *RGWHandler_REST_Obj_SWIFT::op_copy()
2777{
2778 return new RGWCopyObj_ObjStore_SWIFT;
2779}
2780
2781RGWOp *RGWHandler_REST_Obj_SWIFT::op_options()
2782{
2783 return new RGWOptionsCORS_ObjStore_SWIFT;
2784}
2785
2786
11fdf7f2 2787int RGWHandler_REST_SWIFT::authorize(const DoutPrefixProvider *dpp)
7c673cae 2788{
11fdf7f2 2789 return rgw::auth::Strategy::apply(dpp, auth_strategy, s);
7c673cae
FG
2790}
2791
2792int RGWHandler_REST_SWIFT::postauth_init()
2793{
2794 struct req_init_state* t = &s->init_state;
2795
2796 /* XXX Stub this until Swift Auth sets account into URL. */
9f95a23c 2797 s->bucket_tenant = s->user->get_tenant();
7c673cae
FG
2798 s->bucket_name = t->url_bucket;
2799
2800 dout(10) << "s->object=" <<
2801 (!s->object.empty() ? s->object : rgw_obj_key("<NULL>"))
2802 << " s->bucket="
2803 << rgw_make_bucket_entry_name(s->bucket_tenant, s->bucket_name)
2804 << dendl;
2805
2806 int ret;
d2e6a577 2807 ret = rgw_validate_tenant_name(s->bucket_tenant);
7c673cae
FG
2808 if (ret)
2809 return ret;
2810 ret = validate_bucket_name(s->bucket_name);
2811 if (ret)
2812 return ret;
2813 ret = validate_object_name(s->object.name);
2814 if (ret)
2815 return ret;
2816
2817 if (!t->src_bucket.empty()) {
2818 /*
2819 * We don't allow cross-tenant copy at present. It requires account
2820 * names in the URL for Swift.
2821 */
9f95a23c 2822 s->src_tenant_name = s->user->get_tenant();
7c673cae
FG
2823 s->src_bucket_name = t->src_bucket;
2824
2825 ret = validate_bucket_name(s->src_bucket_name);
2826 if (ret < 0) {
2827 return ret;
2828 }
2829 ret = validate_object_name(s->src_object.name);
2830 if (ret < 0) {
2831 return ret;
2832 }
2833 }
2834
2835 return 0;
2836}
2837
2838int RGWHandler_REST_SWIFT::validate_bucket_name(const string& bucket)
2839{
3efd9988 2840 const size_t len = bucket.size();
7c673cae 2841
3efd9988
FG
2842 if (len > MAX_BUCKET_NAME_LEN) {
2843 /* Bucket Name too long. Generate custom error message and bind it
2844 * to an R-value reference. */
2845 const auto msg = boost::str(
2846 boost::format("Container name length of %lld longer than %lld")
2847 % len % int(MAX_BUCKET_NAME_LEN));
2848 set_req_state_err(s, ERR_INVALID_BUCKET_NAME, msg);
2849 return -ERR_INVALID_BUCKET_NAME;
2850 }
2851
2852 const auto ret = RGWHandler_REST::validate_bucket_name(bucket);
2853 if (ret < 0) {
2854 return ret;
2855 }
7c673cae
FG
2856
2857 if (len == 0)
2858 return 0;
2859
2860 if (bucket[0] == '.')
2861 return -ERR_INVALID_BUCKET_NAME;
2862
2863 if (check_utf8(bucket.c_str(), len))
2864 return -ERR_INVALID_UTF8;
2865
2866 const char *s = bucket.c_str();
2867
3efd9988 2868 for (size_t i = 0; i < len; ++i, ++s) {
7c673cae
FG
2869 if (*(unsigned char *)s == 0xff)
2870 return -ERR_INVALID_BUCKET_NAME;
11fdf7f2
TL
2871 if (*(unsigned char *)s == '/')
2872 return -ERR_INVALID_BUCKET_NAME;
7c673cae
FG
2873 }
2874
2875 return 0;
2876}
2877
2878static void next_tok(string& str, string& tok, char delim)
2879{
2880 if (str.size() == 0) {
2881 tok = "";
2882 return;
2883 }
2884 tok = str;
2885 int pos = str.find(delim);
2886 if (pos > 0) {
2887 tok = str.substr(0, pos);
2888 str = str.substr(pos + 1);
2889 } else {
2890 str = "";
2891 }
2892}
2893
2894int RGWHandler_REST_SWIFT::init_from_header(struct req_state* const s,
2895 const std::string& frontend_prefix)
2896{
2897 string req;
2898 string first;
2899
2900 s->prot_flags |= RGW_REST_SWIFT;
2901
2902 char reqbuf[frontend_prefix.length() + s->decoded_uri.length() + 1];
2903 sprintf(reqbuf, "%s%s", frontend_prefix.c_str(), s->decoded_uri.c_str());
2904 const char *req_name = reqbuf;
2905
2906 const char *p;
2907
2908 if (*req_name == '?') {
2909 p = req_name;
2910 } else {
2911 p = s->info.request_params.c_str();
2912 }
2913
2914 s->info.args.set(p);
2915 s->info.args.parse();
2916
2917 /* Skip the leading slash of URL hierarchy. */
2918 if (req_name[0] != '/') {
2919 return 0;
2920 } else {
2921 req_name++;
2922 }
2923
2924 if ('\0' == req_name[0]) {
11fdf7f2 2925 return g_conf()->rgw_swift_url_prefix == "/" ? -ERR_BAD_URL : 0;
7c673cae
FG
2926 }
2927
2928 req = req_name;
2929
2930 size_t pos = req.find('/');
11fdf7f2
TL
2931 if (std::string::npos != pos && g_conf()->rgw_swift_url_prefix != "/") {
2932 bool cut_url = g_conf()->rgw_swift_url_prefix.length();
7c673cae
FG
2933 first = req.substr(0, pos);
2934
11fdf7f2 2935 if (first.compare(g_conf()->rgw_swift_url_prefix) == 0) {
7c673cae
FG
2936 if (cut_url) {
2937 /* Rewind to the "v1/..." part. */
2938 next_tok(req, first, '/');
2939 }
2940 }
11fdf7f2 2941 } else if (req.compare(g_conf()->rgw_swift_url_prefix) == 0) {
7c673cae
FG
2942 s->formatter = new RGWFormatter_Plain;
2943 return -ERR_BAD_URL;
2944 } else {
2945 first = req;
2946 }
2947
2948 std::string tenant_path;
11fdf7f2 2949 if (! g_conf()->rgw_swift_tenant_name.empty()) {
7c673cae 2950 tenant_path = "/AUTH_";
11fdf7f2 2951 tenant_path.append(g_conf()->rgw_swift_tenant_name);
7c673cae
FG
2952 }
2953
2954 /* verify that the request_uri conforms with what's expected */
11fdf7f2 2955 char buf[g_conf()->rgw_swift_url_prefix.length() + 16 + tenant_path.length()];
7c673cae 2956 int blen;
11fdf7f2 2957 if (g_conf()->rgw_swift_url_prefix == "/") {
7c673cae
FG
2958 blen = sprintf(buf, "/v1%s", tenant_path.c_str());
2959 } else {
2960 blen = sprintf(buf, "/%s/v1%s",
11fdf7f2 2961 g_conf()->rgw_swift_url_prefix.c_str(), tenant_path.c_str());
7c673cae
FG
2962 }
2963
2964 if (strncmp(reqbuf, buf, blen) != 0) {
2965 return -ENOENT;
2966 }
2967
2968 int ret = allocate_formatter(s, RGW_FORMAT_PLAIN, true);
2969 if (ret < 0)
2970 return ret;
2971
2972 string ver;
2973
2974 next_tok(req, ver, '/');
2975
11fdf7f2 2976 if (!tenant_path.empty() || g_conf()->rgw_swift_account_in_url) {
7c673cae
FG
2977 string account_name;
2978 next_tok(req, account_name, '/');
2979
2980 /* Erase all pre-defined prefixes like "AUTH_" or "KEY_". */
2981 const vector<string> skipped_prefixes = { "AUTH_", "KEY_" };
2982
2983 for (const auto pfx : skipped_prefixes) {
2984 const size_t comp_len = min(account_name.length(), pfx.length());
2985 if (account_name.compare(0, comp_len, pfx) == 0) {
2986 /* Prefix is present. Drop it. */
2987 account_name = account_name.substr(comp_len);
2988 break;
2989 }
2990 }
2991
2992 if (account_name.empty()) {
2993 return -ERR_PRECONDITION_FAILED;
2994 } else {
2995 s->account_name = account_name;
2996 }
2997 }
2998
2999 next_tok(req, first, '/');
3000
3001 dout(10) << "ver=" << ver << " first=" << first << " req=" << req << dendl;
3002 if (first.size() == 0)
3003 return 0;
3004
3005 s->info.effective_uri = "/" + first;
3006
3007 // Save bucket to tide us over until token is parsed.
3008 s->init_state.url_bucket = first;
3009
3010 if (req.size()) {
3011 s->object =
3012 rgw_obj_key(req, s->info.env->get("HTTP_X_OBJECT_VERSION_ID", "")); /* rgw swift extension */
3013 s->info.effective_uri.append("/" + s->object.name);
3014 }
3015
3016 return 0;
3017}
3018
9f95a23c 3019int RGWHandler_REST_SWIFT::init(rgw::sal::RGWRadosStore* store, struct req_state* s,
7c673cae
FG
3020 rgw::io::BasicClient *cio)
3021{
3022 struct req_init_state *t = &s->init_state;
3023
3024 s->dialect = "swift";
3025
494da23a 3026 std::string copy_source = s->info.env->get("HTTP_X_COPY_FROM", "");
3a9019d9 3027 if (! copy_source.empty()) {
7c673cae
FG
3028 bool result = RGWCopyObj::parse_copy_location(copy_source, t->src_bucket,
3029 s->src_object);
3030 if (!result)
3031 return -ERR_BAD_URL;
3032 }
3033
3034 if (s->op == OP_COPY) {
494da23a 3035 std::string req_dest = s->info.env->get("HTTP_DESTINATION", "");
3a9019d9 3036 if (req_dest.empty())
7c673cae
FG
3037 return -ERR_BAD_URL;
3038
3a9019d9 3039 std::string dest_bucket_name;
7c673cae
FG
3040 rgw_obj_key dest_obj_key;
3041 bool result =
3042 RGWCopyObj::parse_copy_location(req_dest, dest_bucket_name,
3043 dest_obj_key);
3044 if (!result)
3045 return -ERR_BAD_URL;
3046
3a9019d9 3047 std::string dest_object = dest_obj_key.name;
7c673cae
FG
3048
3049 /* convert COPY operation into PUT */
3050 t->src_bucket = t->url_bucket;
3051 s->src_object = s->object;
3052 t->url_bucket = dest_bucket_name;
3053 s->object = rgw_obj_key(dest_object);
3054 s->op = OP_PUT;
3055 }
3056
11fdf7f2
TL
3057 s->info.storage_class = s->info.env->get("HTTP_X_OBJECT_STORAGE_CLASS", "");
3058
7c673cae
FG
3059 return RGWHandler_REST::init(store, s, cio);
3060}
3061
3062RGWHandler_REST*
3063RGWRESTMgr_SWIFT::get_handler(struct req_state* const s,
3064 const rgw::auth::StrategyRegistry& auth_registry,
3065 const std::string& frontend_prefix)
3066{
3067 int ret = RGWHandler_REST_SWIFT::init_from_header(s, frontend_prefix);
3068 if (ret < 0) {
9f95a23c 3069 ldpp_dout(s, 10) << "init_from_header returned err=" << ret << dendl;
7c673cae
FG
3070 return nullptr;
3071 }
3072
3073 const auto& auth_strategy = auth_registry.get_swift();
3074
3075 if (s->init_state.url_bucket.empty()) {
3076 return new RGWHandler_REST_Service_SWIFT(auth_strategy);
3077 }
3078
3079 if (s->object.empty()) {
3080 return new RGWHandler_REST_Bucket_SWIFT(auth_strategy);
3081 }
3082
3083 return new RGWHandler_REST_Obj_SWIFT(auth_strategy);
3084}
3085
3086RGWHandler_REST* RGWRESTMgr_SWIFT_Info::get_handler(
3087 struct req_state* const s,
3088 const rgw::auth::StrategyRegistry& auth_registry,
3089 const std::string& frontend_prefix)
3090{
3091 s->prot_flags |= RGW_REST_SWIFT;
3092 const auto& auth_strategy = auth_registry.get_swift();
3093 return new RGWHandler_REST_SWIFT_Info(auth_strategy);
3094}