-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathhttp.cc
704 lines (634 loc) · 26.9 KB
/
http.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
#include "http.h"
#include <boost/algorithm/string.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/beast.hpp>
#include <boost/beast/ssl.hpp>
#include <sstream>
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "boost/asio/ssl/verify_mode.hpp"
#include "boost/beast/core/tcp_stream.hpp"
#include "spdlog/spdlog.h"
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
namespace authservice {
namespace common {
namespace http {
namespace {
const char forward_alphabet[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
};
const uint8_t reverse_alphabet[] = {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
};
typedef bool (*SafeCharacterFunc)(const char);
bool IsUrlSafeCharacter(const char character) {
return ((character >= 'A' && character <= 'Z') ||
(character >= 'a' && character <= 'z') ||
(character >= '0' && character <= '9') || (character == '-') ||
(character == '_') || (character == '.') || (character == '~'));
}
bool IsFormDataSafeCharacter(const char character) {
return IsUrlSafeCharacter(character) || (character == '+');
}
// We found that at least accounts.google.com[1] could contain `/` in the
// authorization code, as part of OAuth callback URl query param.
// such as `..../?code=4/Abc38.
// RFC 6749[2] specifies "code" could be `VSCHAR`, containing all printable
// ascii chars. RFC 3986[3] about URI specifies that:
// If a reserved character is found in a URI component and
// no delimiting role is known for that character, then it must be
// interpreted as representing the data octet corresponding to that
// character's encoding in US-ASCII.
// [1]
// https://developers.google.com/identity/protocols/oauth2/openid-connect#sendauthrequest
// [2] https://datatracker.ietf.org/doc/html/rfc6749#appendix-A.11.
// [3] https://www.rfc-editor.org/rfc/rfc3986#page-12
// TODO(incfly): move to a separate library specific for OIDC instead of putting
// in http lib.
bool IsOIDCCodeSafeCharacter(const char character) {
return IsUrlSafeCharacter(character) || (character == '/');
}
std::string SafeEncode(absl::string_view in, SafeCharacterFunc IsSafe) {
std::stringstream builder;
for (auto character : in) {
// unreserved characters: see https://www.ietf.org/rfc/rfc3986.txt
if (IsSafe(character)) {
builder << character;
} else {
// percent encode
builder << '%' << forward_alphabet[(character & 0xf0u) >> 4u]
<< forward_alphabet[character & 0x0fu];
}
}
return builder.str();
}
absl::optional<std::string> SafeDecode(absl::string_view in,
SafeCharacterFunc IsSafe) {
std::stringstream builder;
auto iter = in.cbegin();
while (iter != in.cend()) {
// unreserved characters: see https://www.ietf.org/rfc/rfc3986.txt
char character = *iter;
if (IsSafe(character)) {
builder << character;
} else {
// Must be percent encoding.
if (character != '%') {
return absl::optional<std::string>();
}
auto first = ++iter;
// Fail if either there's no more data or the value is out of range
// (non-ascii).
if (first == in.cend() || (*first & 0x80)) {
return absl::nullopt;
}
auto second = ++iter;
// Fail if either there's no more data or the value is out of range
// (non-ascii).
if (second == in.cend() || (*second & 0x80)) {
return absl::optional<std::string>();
}
auto top_nibble = reverse_alphabet[uint8_t(*first) & 0x7fu];
auto bottom_nibble = reverse_alphabet[uint8_t(*second) & 0x7fu];
// The character is invalid if it is set to the value 255 in the reverse
// alphabet.
if ((top_nibble == 255) || (bottom_nibble == 255)) {
return absl::nullopt;
}
// percent encode
builder << char(((top_nibble << 4u) | bottom_nibble));
}
iter++;
}
return builder.str();
}
} // namespace
std::string Http::UrlSafeEncode(absl::string_view url) {
return SafeEncode(url, IsUrlSafeCharacter);
}
absl::optional<std::string> Http::UrlSafeDecode(absl::string_view url) {
return SafeDecode(url, IsUrlSafeCharacter);
}
std::string Http::EncodeQueryData(
const std::multimap<absl::string_view, absl::string_view> &data) {
std::stringstream builder;
auto pair = data.cbegin();
while (pair != data.cend()) {
std::string key(pair->first.data());
std::replace(key.begin(), key.end(), ' ', '+');
std::string value(pair->second.data());
std::replace(value.begin(), value.end(), ' ', '+');
builder << SafeEncode(pair->first.data(), IsUrlSafeCharacter) << '='
<< SafeEncode(pair->second.data(), IsUrlSafeCharacter);
if (++pair != data.cend()) {
builder << "&";
}
}
return builder.str();
}
absl::optional<std::multimap<std::string, std::string>> Http::DecodeQueryData(
absl::string_view query) {
std::multimap<std::string, std::string> result;
std::vector<std::string> parts;
boost::split(parts, query, boost::is_any_of("&"));
spdlog::trace("{} decode query: {}", __func__, query);
for (auto part : parts) {
std::vector<std::string> pair;
boost::split(pair, part, boost::is_any_of("="));
if (pair.size() != 2) {
return absl::nullopt;
}
SafeCharacterFunc checker = IsUrlSafeCharacter;
auto escaped_key = SafeDecode(pair[0], checker);
if (!escaped_key.has_value()) {
spdlog::error("{} decode query fail at the query pair {}, key part.",
__func__, part);
return absl::nullopt;
}
// If the key is the "code", then we use a different checker function.
if (pair[0] == "code") {
checker = IsOIDCCodeSafeCharacter;
}
auto escaped_value = SafeDecode(pair[1], checker);
if (!escaped_value.has_value()) {
spdlog::error("{} decode query fail at the query pair {}, value part.",
__func__, part);
return absl::nullopt;
}
result.insert(std::make_pair(*escaped_key, *escaped_value));
}
return result;
}
std::string Http::EncodeFormData(
const std::multimap<absl::string_view, absl::string_view> &data) {
std::stringstream builder;
auto pair = data.cbegin();
while (pair != data.cend()) {
std::string key(pair->first.data());
std::replace(key.begin(), key.end(), ' ', '+');
std::string value(pair->second.data());
std::replace(value.begin(), value.end(), ' ', '+');
builder << SafeEncode(key, IsFormDataSafeCharacter) << '='
<< SafeEncode(value, IsFormDataSafeCharacter);
if (++pair != data.end()) {
builder << "&";
}
}
return builder.str();
}
absl::optional<std::multimap<std::string, std::string>> Http::DecodeFormData(
absl::string_view form) {
std::multimap<std::string, std::string> result;
std::vector<std::string> parts;
boost::split(parts, form, boost::is_any_of("&"));
for (auto part : parts) {
std::vector<std::string> pair;
boost::split(pair, part, boost::is_any_of("="));
if (pair.size() != 2) {
return absl::nullopt;
}
auto escaped_key = SafeDecode(pair[0], IsFormDataSafeCharacter);
if (!escaped_key.has_value()) {
return absl::nullopt;
}
std::replace(escaped_key->begin(), escaped_key->end(), '+', ' ');
auto escaped_value = SafeDecode(pair[1], IsFormDataSafeCharacter);
if (!escaped_value.has_value()) {
return absl::nullopt;
}
std::replace(escaped_value->begin(), escaped_value->end(), '+', ' ');
result.insert(std::make_pair(*escaped_key, *escaped_value));
}
return result;
}
std::string Http::EncodeBasicAuth(absl::string_view username,
absl::string_view password) {
return absl::StrCat(
"Basic", " ", absl::Base64Escape(absl::StrCat(username, ":", password)));
}
std::string Http::EncodeSetCookie(
absl::string_view name, absl::string_view value,
const std::set<absl::string_view> &directives) {
std::stringstream builder;
builder << name.data() << '=' << value.data();
for (auto directive : directives) {
builder << "; " << directive.data();
}
return builder.str();
}
absl::optional<std::map<std::string, std::string>> Http::DecodeCookies(
absl::string_view cookies) {
// https://tools.ietf.org/html/rfc6265#section-5.4
std::map<std::string, std::string> result;
std::vector<absl::string_view> cookie_list = absl::StrSplit(cookies, "; ");
for (auto cookie : cookie_list) {
std::vector<absl::string_view> cookie_parts =
absl::StrSplit(cookie, absl::MaxSplits('=', 1));
if (cookie_parts.size() != 2) {
// Invalid cookie encoding. Must Name=Value
return absl::nullopt;
}
result.emplace(std::string(cookie_parts[0].data(), cookie_parts[0].size()),
std::string(cookie_parts[1].data(), cookie_parts[1].size()));
}
return result;
}
Uri::Uri(absl::string_view uri) : pathQueryFragment_("/") {
std::string scheme_prefix;
if (uri.find(https_prefix_) == 0) {
scheme_ = "https";
scheme_prefix = https_prefix_;
} else if (uri.find(http_prefix_) == 0) {
scheme_ = "http";
scheme_prefix = http_prefix_;
} else {
throw std::runtime_error(
absl::StrCat("uri must be http or https scheme: ", uri));
}
if (uri.length() == scheme_prefix.length()) {
throw std::runtime_error(absl::StrCat("no host in uri: ", uri));
}
auto uri_without_scheme = uri.substr(scheme_prefix.length());
std::string host_and_port;
auto positions = {uri_without_scheme.find('/'), uri_without_scheme.find('?'),
uri_without_scheme.find('#')};
absl::string_view::size_type end_of_host_and_port_index =
uri_without_scheme.length();
for (auto ptr = positions.begin(); ptr < positions.end(); ptr++) {
if (*ptr == absl::string_view::npos) {
continue;
}
end_of_host_and_port_index = std::min(end_of_host_and_port_index, *ptr);
}
host_and_port = std::string(
uri_without_scheme.substr(0, end_of_host_and_port_index).data(),
end_of_host_and_port_index);
pathQueryFragmentString_ =
std::string(uri_without_scheme.substr(end_of_host_and_port_index).data());
if (!absl::StartsWith(pathQueryFragmentString_, "/")) {
pathQueryFragmentString_ = "/" + pathQueryFragmentString_;
}
pathQueryFragment_ = http::PathQueryFragment(pathQueryFragmentString_);
auto colon_position = host_and_port.find(':');
if (colon_position == 0) {
throw std::runtime_error(absl::StrCat("no host in uri: ", uri));
}
if (colon_position != absl::string_view::npos) {
auto port = host_and_port.substr(colon_position + 1);
try {
port_ = std::stoi(port);
} catch (const std::exception &e) {
throw std::runtime_error(absl::StrCat("port not valid in uri: ", uri));
}
if (port_ > 65535 || port_ < 0) {
throw std::runtime_error(
absl::StrCat("port value must be between 0 and 65535: ", uri));
}
host_ = std::string(host_and_port.substr(0, colon_position).data(),
colon_position);
} else {
host_ = host_and_port;
if (scheme_ == "http") {
port_ = 80;
} else if (scheme_ == "https") {
port_ = 443;
}
}
}
const std::string Uri::https_prefix_ = "https://";
const std::string Uri::http_prefix_ = "http://";
Uri &Uri::operator=(Uri &&uri) noexcept {
host_ = uri.host_;
port_ = uri.port_;
scheme_ = uri.scheme_;
pathQueryFragmentString_ = uri.pathQueryFragmentString_;
pathQueryFragment_ = uri.pathQueryFragment_;
return *this;
}
Uri::Uri(const Uri &uri)
: host_(uri.host_),
scheme_(uri.scheme_),
port_(uri.port_),
pathQueryFragmentString_(uri.pathQueryFragmentString_),
pathQueryFragment_(uri.pathQueryFragment_) {}
std::string Uri::GetPath() { return pathQueryFragment_.Path(); }
std::string Uri::GetFragment() { return pathQueryFragment_.Fragment(); }
std::string Uri::GetQuery() { return pathQueryFragment_.Query(); }
PathQueryFragment::PathQueryFragment(absl::string_view path_query_fragment) {
// See https://tools.ietf.org/html/rfc3986#section-3.4 and
// https://tools.ietf.org/html/rfc3986#section-3.5
auto question_mark_position = path_query_fragment.find('?');
auto hashtag_position = path_query_fragment.find("#");
if (question_mark_position == absl::string_view::npos &&
hashtag_position == absl::string_view::npos) {
path_ = std::string(path_query_fragment.data());
} else if (question_mark_position == absl::string_view::npos) {
path_ = std::string(path_query_fragment.substr(0, hashtag_position).data(),
hashtag_position);
fragment_ =
std::string(path_query_fragment.substr(hashtag_position + 1).data());
} else if (hashtag_position == absl::string_view::npos) {
path_ = std::string(
path_query_fragment.substr(0, question_mark_position).data(),
question_mark_position);
query_ = std::string(
path_query_fragment.substr(question_mark_position + 1).data());
} else {
if (question_mark_position < hashtag_position) {
auto query_length = hashtag_position - question_mark_position - 1;
path_ = std::string(
path_query_fragment.substr(0, question_mark_position).data(),
question_mark_position);
query_ = std::string(
path_query_fragment.substr(question_mark_position + 1, query_length)
.data(),
query_length);
fragment_ =
std::string(path_query_fragment.substr(hashtag_position + 1).data());
} else {
path_ =
std::string(path_query_fragment.substr(0, hashtag_position).data(),
hashtag_position);
fragment_ =
std::string(path_query_fragment.substr(hashtag_position + 1).data());
}
}
}
response_t HttpImpl::Post(
absl::string_view uri,
const std::map<absl::string_view, absl::string_view> &headers,
absl::string_view body, const TransportSocketOptions &options,
absl::string_view proxy_uri, boost::asio::io_context &ioc,
boost::asio::yield_context yield) const {
spdlog::trace("{}", __func__);
try {
int version = 11;
ssl::context ctx(ssl::context::tlsv12_client);
ctx.set_verify_mode(options.verify_peer_ ? ssl::verify_peer
: ssl::verify_none);
ctx.set_default_verify_paths();
if (!options.ca_cert_.empty()) {
spdlog::info("{}: Trusting the provided certificate authority", __func__);
beast::error_code ca_ec;
ctx.add_certificate_authority(
boost::asio::buffer(options.ca_cert_.data(), options.ca_cert_.size()),
ca_ec);
if (ca_ec) {
// X509_R_CERT_ALREADY_IN_HASH_TABLE can be ignored.
// Reference:
// https://github.com/facebook/folly/blob/d3354e2282303402e70d829d19bfecce051a5850/folly/ssl/OpenSSLCertUtils.cpp#L367-L368.
if (ca_ec.category() != boost::asio::error::get_ssl_category() ||
ERR_GET_REASON(ca_ec.value()) !=
X509_R_CERT_ALREADY_IN_HASH_TABLE) {
throw boost::system::system_error{ca_ec};
}
}
}
auto parsed_uri = http::Uri(uri);
tcp::resolver resolver(ioc);
beast::ssl_stream<beast::tcp_stream> stream(ioc, ctx);
if (!SSL_set_tlsext_host_name(stream.native_handle(),
parsed_uri.GetHost().c_str())) {
throw boost::system::error_code{static_cast<int>(::ERR_get_error()),
boost::asio::error::get_ssl_category()};
}
if (!proxy_uri.empty()) {
auto parsed_proxy_uri = http::Uri(proxy_uri);
const auto results = resolver.async_resolve(
parsed_proxy_uri.GetHost(),
std::to_string(parsed_proxy_uri.GetPort()), yield);
spdlog::info(
"{}: opening connection to proxy {} for request to destination {}:{}",
__func__, proxy_uri.data(), parsed_uri.GetHost(),
parsed_uri.GetPort());
beast::get_lowest_layer(stream).async_connect(results, yield);
std::string target = absl::StrCat(parsed_uri.GetHost(), ":",
std::to_string(parsed_uri.GetPort()));
beast::http::request<beast::http::string_body> http_connect_req{
beast::http::verb::connect, target, version};
http_connect_req.set(beast::http::field::host, target);
// Send the HTTP connect request to the remote host
beast::http::async_write(stream.next_layer(), http_connect_req, yield);
// Read the response from the server
boost::beast::flat_buffer http_connect_buffer;
beast::http::response<beast::http::empty_body> http_connect_res;
beast::http::parser<false, beast::http::empty_body> p(http_connect_res);
p.skip(true); // skip reading the body of the response because there
// won't be a body
beast::http::async_read(stream.next_layer(), http_connect_buffer, p,
yield);
if (http_connect_res.result() != beast::http::status::ok) {
throw std::runtime_error(
absl::StrCat("http connect failed with status: ",
http_connect_res.result_int()));
}
} else {
spdlog::info("{}: opening connection to {}:{}", __func__,
parsed_uri.GetHost(), parsed_uri.GetPort());
const auto results = resolver.async_resolve(
parsed_uri.GetHost(), std::to_string(parsed_uri.GetPort()), yield);
beast::get_lowest_layer(stream).async_connect(results, yield);
}
stream.async_handshake(ssl::stream_base::client, yield);
// Set up an HTTP POST request message
beast::http::request<beast::http::string_body> req{
beast::http::verb::post, parsed_uri.GetPathQueryFragment(), version};
req.set(beast::http::field::host, parsed_uri.GetHost());
for (auto header : headers) {
req.set(boost::beast::string_view(header.first.data()),
boost::beast::string_view(header.second.data()));
}
auto &req_body = req.body();
req_body.reserve(body.size());
req_body.append(body.begin(), body.end());
req.prepare_payload();
// Send the HTTP request to the remote host
beast::http::async_write(stream, req, yield);
// Read response
beast::flat_buffer buffer;
response_t res(new beast::http::response<beast::http::string_body>);
beast::http::async_read(stream, buffer, *res, yield);
spdlog::trace("{}: closing connection, response payload size {}", __func__,
res->payload_size().value());
// Close the socket. We already got the response we need so close the socket
// directly. We choose not to use `ssl_stream::async_shutdown` since in some
// case, the HTTPS server does not participate with closing
// stream/connection. That would make the async_shutdown waiting forever.
// TODO(https://github.com/istio-ecosystem/authservice/issues/214): address
// this properly with a timer on `async_shutdown`.
beast::get_lowest_layer(stream).close();
return res;
// If we get here then the connection is closed gracefully
} catch (std::exception const &e) {
spdlog::error("{}: unexpected exception: {}", __func__, e.what());
return response_t();
}
}
response_t HttpImpl::Get(
absl::string_view uri,
const std::map<absl::string_view, absl::string_view> &headers,
absl::string_view body, const TransportSocketOptions &options,
absl::string_view proxy_uri, boost::asio::io_context &ioc,
boost::asio::yield_context yield) const {
spdlog::trace("{}", __func__);
try {
int version = 11;
ssl::context ctx(ssl::context::tlsv12_client);
ctx.set_verify_mode(options.verify_peer_ ? ssl::verify_peer
: ssl::verify_none);
ctx.set_default_verify_paths();
if (!options.ca_cert_.empty()) {
spdlog::info("{}: Trusting the provided certificate authority", __func__);
beast::error_code ca_ec;
ctx.add_certificate_authority(
boost::asio::buffer(options.ca_cert_.data(), options.ca_cert_.size()),
ca_ec);
if (ca_ec) {
// X509_R_CERT_ALREADY_IN_HASH_TABLE can be ignored.
// Reference:
// https://github.com/facebook/folly/blob/d3354e2282303402e70d829d19bfecce051a5850/folly/ssl/OpenSSLCertUtils.cpp#L367-L368.
if (ca_ec.category() != boost::asio::error::get_ssl_category() ||
ERR_GET_REASON(ca_ec.value()) !=
X509_R_CERT_ALREADY_IN_HASH_TABLE) {
throw boost::system::system_error{ca_ec};
}
}
}
auto parsed_uri = http::Uri(uri);
tcp::resolver resolver(ioc);
beast::ssl_stream<beast::tcp_stream> stream(ioc, ctx);
if (!SSL_set_tlsext_host_name(stream.native_handle(),
parsed_uri.GetHost().c_str())) {
throw boost::system::error_code{static_cast<int>(::ERR_get_error()),
boost::asio::error::get_ssl_category()};
}
if (!proxy_uri.empty()) {
auto parsed_proxy_uri = http::Uri(proxy_uri);
const auto results = resolver.async_resolve(
parsed_proxy_uri.GetHost(),
std::to_string(parsed_proxy_uri.GetPort()), yield);
spdlog::info(
"{}: opening connection to proxy {} for request to destination {}:{}",
__func__, proxy_uri.data(), parsed_uri.GetHost(),
parsed_uri.GetPort());
beast::get_lowest_layer(stream).async_connect(results, yield);
std::string target = absl::StrCat(parsed_uri.GetHost(), ":",
std::to_string(parsed_uri.GetPort()));
beast::http::request<beast::http::string_body> http_connect_req{
beast::http::verb::connect, target, version};
http_connect_req.set(beast::http::field::host, target);
// Send the HTTP connect request to the remote host
beast::http::async_write(stream.next_layer(), http_connect_req, yield);
// Read the response from the server
boost::beast::flat_buffer http_connect_buffer;
beast::http::response<beast::http::empty_body> http_connect_res;
beast::http::parser<false, beast::http::empty_body> p(http_connect_res);
p.skip(true); // skip reading the body of the response because there
// won't be a body
beast::http::async_read(stream.next_layer(), http_connect_buffer, p,
yield);
if (http_connect_res.result() != beast::http::status::ok) {
throw std::runtime_error(
absl::StrCat("http connect failed with status: ",
http_connect_res.result_int()));
}
} else {
spdlog::info("{}: opening connection to {}:{}", __func__,
parsed_uri.GetHost(), parsed_uri.GetPort());
const auto results = resolver.async_resolve(
parsed_uri.GetHost(), std::to_string(parsed_uri.GetPort()), yield);
beast::get_lowest_layer(stream).async_connect(results, yield);
}
stream.async_handshake(ssl::stream_base::client, yield);
// Set up an HTTP POST request message
beast::http::request<beast::http::string_body> req{
beast::http::verb::get, parsed_uri.GetPathQueryFragment(), version};
req.set(beast::http::field::host, parsed_uri.GetHost());
for (auto header : headers) {
req.set(boost::beast::string_view(header.first.data()),
boost::beast::string_view(header.second.data()));
}
auto &req_body = req.body();
req_body.reserve(body.size());
req_body.append(body.begin(), body.end());
req.prepare_payload();
// Send the HTTP request to the remote host
beast::http::async_write(stream, req, yield);
// Read response
beast::flat_buffer buffer;
response_t res(new beast::http::response<beast::http::string_body>);
beast::http::async_read(stream, buffer, *res, yield);
spdlog::trace("{}: closing connection, response payload size {}", __func__,
res->payload_size().value());
// Close the socket. We already got the response we need so close the socket
// directly. We choose not to use `ssl_stream::async_shutdown` since in some
// case, the HTTPS server does not participate with closing
// stream/connection. That would make the async_shutdown waiting forever.
beast::get_lowest_layer(stream).close();
return res;
// If we get here then the connection is closed gracefully
} catch (std::exception const &e) {
spdlog::error("{}: unexpected exception: {}", __func__, e.what());
return response_t();
}
}
response_t HttpImpl::SimpleGet(
absl::string_view uri,
const std::map<absl::string_view, absl::string_view> &headers,
absl::string_view body, boost::asio::io_context &ioc,
boost::asio::yield_context yield) const {
spdlog::trace("{}", __func__);
try {
int version = 11;
auto parsed_uri = http::Uri(uri);
tcp::resolver resolver(ioc);
beast::tcp_stream stream(ioc);
spdlog::info("{}: opening connection to {}:{}", __func__,
parsed_uri.GetHost(), parsed_uri.GetPort());
const auto results = resolver.async_resolve(
parsed_uri.GetHost(), std::to_string(parsed_uri.GetPort()), yield);
beast::get_lowest_layer(stream).async_connect(results, yield);
// Set up an HTTP simple get request message
beast::http::request<beast::http::string_body> req{
beast::http::verb::get, parsed_uri.GetPathQueryFragment(), version};
req.set(beast::http::field::host, parsed_uri.GetHost());
for (auto header : headers) {
req.set(boost::beast::string_view(header.first.data()),
boost::beast::string_view(header.second.data()));
}
auto &req_body = req.body();
req_body.reserve(body.size());
req_body.append(body.begin(), body.end());
req.prepare_payload();
// Send the HTTP request to the remote host
beast::http::async_write(stream, req, yield);
// Read response
beast::flat_buffer buffer;
response_t res(new beast::http::response<beast::http::string_body>);
beast::http::async_read(stream, buffer, *res, yield);
return res;
// If we get here then the connection is closed gracefully
} catch (std::exception const &e) {
spdlog::error("{}: unexpected exception: {}", __func__, e.what());
return response_t();
}
}
} // namespace http
} // namespace common
} // namespace authservice