1 /*
2   Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
3 
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License, version 2.0,
6   as published by the Free Software Foundation.
7 
8   This program is also distributed with certain software (including
9   but not limited to OpenSSL) that is licensed under separate terms,
10   as designated in a particular file or component or in included license
11   documentation.  The authors of MySQL hereby grant you an additional
12   permission to link the program and your derivative works with the
13   separately licensed software that they have included with MySQL.
14 
15   This program is distributed in the hope that it will be useful,
16   but WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18   GNU General Public License for more details.
19 
20   You should have received a copy of the GNU General Public License
21   along with this program; if not, write to the Free Software
22   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23 */
24 
25 #include "mysqlrouter/rest_client.h"
26 #include "base64.h"
27 
request_sync(HttpMethod::type method,const std::string & uri,const std::string & request_body,const std::string & content_type)28 HttpRequest RestClient::request_sync(
29     HttpMethod::type method, const std::string &uri,
30     const std::string &request_body /* = {} */,
31     const std::string &content_type /* = "application/json" */) {
32   HttpRequest req{HttpRequest::sync_callback, nullptr};
33 
34   // TRACE forbids a request-body
35   if (!request_body.empty()) {
36     if (method == HttpMethod::Trace) {
37       throw std::logic_error("TRACE can't have request-body");
38     }
39     req.get_output_headers().add("Content-Type", content_type.c_str());
40     auto out_buf = req.get_output_buffer();
41     out_buf.add(request_body.data(), request_body.size());
42   }
43 
44   if (!username_.empty()) {
45     std::string crds{username_ + ":" + password_};
46     req.get_output_headers().add(
47         "Authorization", ("Basic " + Base64::encode(std::vector<uint8_t>{
48                                          crds.begin(), crds.end()}))
49                              .c_str());
50   }
51 
52   // ask the server to close the connection after this request
53   req.get_output_headers().add("Connection", "close");
54   req.get_output_headers().add("Host", http_client_->hostname().c_str());
55 
56   // tell the server that we would accept error-messages as problem+json
57   req.get_output_headers().add("Accept", "application/problem+json");
58   http_client_->make_request_sync(&req, method, uri);
59 
60   return req;
61 }
62