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