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