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