-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathhttp_client_asio.cpp
2162 lines (1915 loc) · 81.5 KB
/
http_client_asio.cpp
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* HTTP Library: Client-side APIs.
*
* This file contains a cross platform implementation based on Boost.ASIO.
*
* For the latest on this and related APIs, please see: https://github.com/Microsoft/cpprestsdk
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
#include "../common/connection_pool_helpers.h"
#include "../common/internal_http_helpers.h"
#include "cpprest/asyncrt_utils.h"
#include <sstream>
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-local-typedef"
#pragma clang diagnostic ignored "-Winfinite-recursion"
#endif
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/bind.hpp>
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#if defined(BOOST_NO_CXX11_SMART_PTR)
#error "Cpp rest SDK requires c++11 smart pointer support from boost"
#endif
#include "../common/x509_cert_utilities.h"
#include "cpprest/base_uri.h"
#include "cpprest/details/http_helpers.h"
#include "http_client_impl.h"
#include "pplx/threadpool.h"
#include <memory>
#include <unordered_set>
#if defined(__GNUC__) && !defined(__clang__)
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
#define AND_CAPTURE_MEMBER_FUNCTION_POINTERS
#else
// GCC Bug 56222 - Pointer to member in lambda should not require this to be captured
// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56222
// GCC Bug 51494 - Legal program rejection - capturing "this" when using static method inside lambda
// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51494
#define AND_CAPTURE_MEMBER_FUNCTION_POINTERS , this
#endif
#elif defined(_MSC_VER)
#if _MSC_VER >= 1900
#define AND_CAPTURE_MEMBER_FUNCTION_POINTERS
#else
// This bug also afflicts VS2013 which incorrectly reports "warning C4573: the usage of 'symbol' requires the compiler
// to capture 'this' but the current default capture mode does not allow it"
#define AND_CAPTURE_MEMBER_FUNCTION_POINTERS , this
#endif
#else
#define AND_CAPTURE_MEMBER_FUNCTION_POINTERS
#endif
using boost::asio::ip::tcp;
#ifdef __ANDROID__
using utility::conversions::details::to_string;
#else
using std::to_string;
#endif
namespace
{
const std::string CRLF("\r\n");
std::string calc_cn_host(const web::http::uri& baseUri, const web::http::http_headers& requestHeaders)
{
std::string result;
if (baseUri.scheme() == U("https"))
{
const utility::string_t* encResult;
const auto hostHeader = requestHeaders.find(_XPLATSTR("Host"));
if (hostHeader == requestHeaders.end())
{
encResult = &baseUri.host();
}
else
{
encResult = &hostHeader->second;
}
result = utility::conversions::to_utf8string(*encResult);
utility::details::inplace_tolower(result);
}
return result;
}
} // namespace
namespace web
{
namespace http
{
namespace client
{
namespace details
{
enum class httpclient_errorcode_context
{
none = 0,
connect,
handshake,
writeheader,
writebody,
readheader,
readbody,
close
};
static std::string generate_base64_userpass(const ::web::credentials& creds)
{
auto userpass = creds.username() + U(":") + *creds._internal_decrypt();
auto&& u8_userpass = utility::conversions::to_utf8string(userpass);
std::vector<unsigned char> credentials_buffer(u8_userpass.begin(), u8_userpass.end());
return utility::conversions::to_utf8string(utility::conversions::to_base64(credentials_buffer));
}
class asio_connection_pool;
class asio_connection
{
friend class asio_client;
public:
asio_connection(boost::asio::io_service& io_service)
: m_socket_lock()
, m_socket(io_service)
, m_ssl_stream()
, m_cn_hostname()
, m_is_reused(false)
, m_keep_alive(true)
, m_closed(false)
{
}
~asio_connection() { close(); }
// This simply instantiates the internal state to support ssl. It does not perform the handshake.
void upgrade_to_ssl(std::string&& cn_hostname,
const std::function<void(boost::asio::ssl::context&)>& ssl_context_callback)
{
std::lock_guard<std::mutex> lock(m_socket_lock);
assert(!is_ssl());
boost::asio::ssl::context ssl_context(boost::asio::ssl::context::sslv23);
ssl_context.set_default_verify_paths();
ssl_context.set_options(boost::asio::ssl::context::default_workarounds);
if (ssl_context_callback)
{
ssl_context_callback(ssl_context);
}
m_ssl_stream = utility::details::make_unique<boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>>(
m_socket, ssl_context);
m_cn_hostname = std::move(cn_hostname);
}
void close()
{
std::lock_guard<std::mutex> lock(m_socket_lock);
// Ensures closed connections owned by request_context will not be put to pool when they are released.
m_keep_alive = false;
m_closed = true;
boost::system::error_code error;
m_socket.shutdown(tcp::socket::shutdown_both, error);
m_socket.close(error);
}
boost::system::error_code cancel()
{
std::lock_guard<std::mutex> lock(m_socket_lock);
boost::system::error_code error;
m_socket.cancel(error);
return error;
}
bool is_reused() const { return m_is_reused; }
void set_keep_alive(bool keep_alive) { m_keep_alive = keep_alive; }
bool keep_alive() const { return m_keep_alive; }
bool is_ssl() const { return m_ssl_stream ? true : false; }
const std::string& cn_hostname() const { return m_cn_hostname; }
// Check if the error code indicates that the connection was closed by the
// server: this is used to detect if a connection in the pool was closed during
// its period of inactivity and we should reopen it.
bool was_reused_and_closed_by_server(const boost::system::error_code& ec) const
{
if (!is_reused())
{
// Don't bother reopening the connection if it's a new one: in this
// case, even if the connection was really lost, it's still a real
// error and we shouldn't try to reopen it.
return false;
}
// These errors tell if connection was closed.
if ((boost::asio::error::eof == ec) || (boost::asio::error::connection_reset == ec) ||
(boost::asio::error::connection_aborted == ec))
{
return true;
}
if (is_ssl())
{
// For SSL connections, we can also get a different error due to
// incorrect secure connection shutdown if it was closed by the
// server due to inactivity. Unfortunately, the exact error we get
// in this case depends on the Boost.Asio version used.
#if BOOST_ASIO_VERSION >= 101008
if (boost::asio::ssl::error::stream_truncated == ec) return true;
#else // Asio < 1.10.8 didn't have ssl::error::stream_truncated
if (boost::system::error_code(ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SHORT_READ),
boost::asio::error::get_ssl_category()) == ec)
return true;
#endif
}
return false;
}
template<typename Iterator, typename Handler>
void async_connect(const Iterator& begin, const Handler& handler)
{
{
std::lock_guard<std::mutex> lock(m_socket_lock);
if (!m_closed)
{
m_socket.async_connect(begin, handler);
return;
}
} // unlock
handler(boost::asio::error::operation_aborted);
}
template<typename HandshakeHandler, typename CertificateHandler>
void async_handshake(boost::asio::ssl::stream_base::handshake_type type,
const http_client_config& config,
const HandshakeHandler& handshake_handler,
const CertificateHandler& cert_handler)
{
std::lock_guard<std::mutex> lock(m_socket_lock);
assert(is_ssl());
// Check to turn on/off server certificate verification.
if (config.validate_certificates())
{
m_ssl_stream->set_verify_mode(boost::asio::ssl::context::verify_peer);
m_ssl_stream->set_verify_callback(cert_handler);
}
else
{
m_ssl_stream->set_verify_mode(boost::asio::ssl::context::verify_none);
}
// Check to set host name for Server Name Indication (SNI)
if (config.is_tlsext_sni_enabled())
{
SSL_set_tlsext_host_name(m_ssl_stream->native_handle(), &m_cn_hostname[0]);
}
m_ssl_stream->async_handshake(type, handshake_handler);
}
template<typename ConstBufferSequence, typename Handler>
void async_write(ConstBufferSequence& buffer, const Handler& writeHandler)
{
std::lock_guard<std::mutex> lock(m_socket_lock);
if (m_ssl_stream)
{
boost::asio::async_write(*m_ssl_stream, buffer, writeHandler);
}
else
{
boost::asio::async_write(m_socket, buffer, writeHandler);
}
}
template<typename MutableBufferSequence, typename CompletionCondition, typename Handler>
void async_read(MutableBufferSequence& buffer, const CompletionCondition& condition, const Handler& readHandler)
{
std::lock_guard<std::mutex> lock(m_socket_lock);
if (m_ssl_stream)
{
boost::asio::async_read(*m_ssl_stream, buffer, condition, readHandler);
}
else
{
boost::asio::async_read(m_socket, buffer, condition, readHandler);
}
}
template<typename Handler>
void async_read_until(boost::asio::streambuf& buffer, const std::string& delim, const Handler& readHandler)
{
std::lock_guard<std::mutex> lock(m_socket_lock);
if (m_ssl_stream)
{
boost::asio::async_read_until(*m_ssl_stream, buffer, delim, readHandler);
}
else
{
boost::asio::async_read_until(m_socket, buffer, delim, readHandler);
}
}
void start_reuse() { m_is_reused = true; }
void enable_no_delay()
{
boost::asio::ip::tcp::no_delay option(true);
boost::system::error_code error_ignored;
m_socket.set_option(option, error_ignored);
}
private:
// Guards concurrent access to socket/ssl::stream. This is necessary
// because timeouts and cancellation can touch the socket at the same time
// as normal message processing.
std::mutex m_socket_lock;
tcp::socket m_socket;
std::unique_ptr<boost::asio::ssl::stream<tcp::socket&>> m_ssl_stream;
std::string m_cn_hostname;
bool m_is_reused;
bool m_keep_alive;
bool m_closed;
};
/// <summary>Implements a connection pool with adaptive connection removal</summary>
/// <remarks>
/// Every 30 seconds, the lambda in `start_epoch_interval` fires, triggering the
/// cleanup of any connections that have resided in the pool since the last
/// cleanup phase.
///
/// During the cleanup phase, connections are removed starting with the oldest. This
/// ensures that if a high intensity workload is followed by a low intensity workload,
/// the connection pool will correctly adapt to the low intensity workload.
///
/// Specifically, the following code will eventually result in a maximum of one pooled
/// connection regardless of the initial number of pooled connections:
/// <code>
/// while(1)
/// {
/// auto conn = pool.try_acquire();
/// if (!conn) conn = new_conn();
/// pool.release(std::move(conn));
/// }
/// </code>
/// </remarks>
class asio_connection_pool final : public std::enable_shared_from_this<asio_connection_pool>
{
public:
asio_connection_pool()
: m_lock()
, m_connections()
, m_is_timer_running(false)
, m_pool_epoch_timer(crossplat::threadpool::shared_instance().service())
{
}
asio_connection_pool(const asio_connection_pool&) = delete;
asio_connection_pool& operator=(const asio_connection_pool&) = delete;
std::shared_ptr<asio_connection> try_acquire(const std::string& cn_hostname)
{
std::lock_guard<std::mutex> lock(m_lock);
if (m_connections.empty())
{
return nullptr;
}
auto conn = m_connections[cn_hostname].try_acquire();
if (conn)
{
conn->start_reuse();
}
return conn;
}
void release(std::shared_ptr<asio_connection>&& connection)
{
connection->cancel();
if (!connection->keep_alive())
{
connection.reset();
return;
}
std::lock_guard<std::mutex> lock(m_lock);
if (!m_is_timer_running)
{
start_epoch_interval(shared_from_this());
m_is_timer_running = true;
}
m_connections[connection->cn_hostname()].release(std::move(connection));
}
private:
// Note: must be called under m_lock
static void start_epoch_interval(const std::shared_ptr<asio_connection_pool>& pool)
{
auto& self = *pool;
std::weak_ptr<asio_connection_pool> weak_pool = pool;
self.m_pool_epoch_timer.expires_from_now(boost::posix_time::seconds(30));
self.m_pool_epoch_timer.async_wait([weak_pool](const boost::system::error_code& ec) {
if (ec)
{
return;
}
auto pool = weak_pool.lock();
if (!pool)
{
return;
}
auto& self = *pool;
std::lock_guard<std::mutex> lock(self.m_lock);
bool restartTimer = false;
for (auto& entry : self.m_connections)
{
if (entry.second.free_stale_connections())
{
restartTimer = true;
}
}
if (restartTimer)
{
start_epoch_interval(pool);
}
else
{
self.m_is_timer_running = false;
}
});
}
std::mutex m_lock;
std::map<std::string, connection_pool_stack<asio_connection>> m_connections;
bool m_is_timer_running;
boost::asio::deadline_timer m_pool_epoch_timer;
};
class asio_client final : public _http_client_communicator
{
public:
asio_client(http::uri&& address, http_client_config&& client_config)
: _http_client_communicator(std::move(address), std::move(client_config))
, m_pool(std::make_shared<asio_connection_pool>())
{
}
virtual void send_request(const std::shared_ptr<request_context>& request_ctx) override;
void release_connection(std::shared_ptr<asio_connection>&& conn) { m_pool->release(std::move(conn)); }
std::shared_ptr<asio_connection> obtain_connection(const http_request& req)
{
std::string cn_host = calc_cn_host(base_uri(), req.headers());
std::shared_ptr<asio_connection> conn = m_pool->try_acquire(cn_host);
if (conn == nullptr)
{
// Pool was empty. Create a new connection
conn = std::make_shared<asio_connection>(crossplat::threadpool::shared_instance().service());
if (base_uri().scheme() == U("https") && !this->client_config().proxy().is_specified())
{
conn->upgrade_to_ssl(std::move(cn_host), this->client_config().get_ssl_context_callback());
}
}
return conn;
}
virtual pplx::task<http_response> propagate(http_request request) override;
private:
const std::shared_ptr<asio_connection_pool> m_pool;
};
class asio_context final : public request_context, public std::enable_shared_from_this<asio_context>
{
friend class asio_client;
public:
asio_context(const std::shared_ptr<_http_client_communicator>& client,
http_request& request,
const std::shared_ptr<asio_connection>& connection)
: request_context(client, request)
, m_content_length(0)
, m_needChunked(false)
, m_timer(client->client_config().timeout<std::chrono::microseconds>())
, m_resolver(crossplat::threadpool::shared_instance().service())
, m_connection(connection)
#ifdef CPPREST_PLATFORM_ASIO_CERT_VERIFICATION_AVAILABLE
, m_openssl_failed(false)
#endif // CPPREST_PLATFORM_ASIO_CERT_VERIFICATION_AVAILABLE
{
}
virtual ~asio_context()
{
m_timer.stop();
// Release connection back to the pool. If connection was not closed, it will be put to the pool for reuse.
std::static_pointer_cast<asio_client>(m_http_client)->release_connection(std::move(m_connection));
}
static std::shared_ptr<request_context> create_request_context(std::shared_ptr<_http_client_communicator>& client,
http_request& request)
{
auto client_cast(std::static_pointer_cast<asio_client>(client));
auto connection(client_cast->obtain_connection(request));
auto ctx = std::make_shared<asio_context>(client, request, connection);
ctx->m_timer.set_ctx(std::weak_ptr<asio_context>(ctx));
return ctx;
}
class ssl_proxy_tunnel final : public std::enable_shared_from_this<ssl_proxy_tunnel>
{
public:
ssl_proxy_tunnel(std::shared_ptr<asio_context> context,
std::function<void(std::shared_ptr<asio_context>)> ssl_tunnel_established)
: m_ssl_tunnel_established(ssl_tunnel_established), m_context(context)
{
}
void start_proxy_connect()
{
auto proxy = m_context->m_http_client->client_config().proxy();
auto proxy_uri = proxy.address();
utility::string_t proxy_host = proxy_uri.host();
int proxy_port = proxy_uri.port() == -1 ? 8080 : proxy_uri.port();
const auto& base_uri = m_context->m_http_client->base_uri();
const auto& host = utility::conversions::to_utf8string(base_uri.host());
const int portRaw = base_uri.port();
const int port = (portRaw != 0) ? portRaw : 443;
std::ostream request_stream(&m_request);
request_stream.imbue(std::locale::classic());
request_stream << "CONNECT " << host << ":" << port << " HTTP/1.1\r\n";
request_stream << "Host: " << host << ":" << port << CRLF;
request_stream << "Proxy-Connection: Keep-Alive\r\n";
if (m_context->m_http_client->client_config().proxy().credentials().is_set())
{
request_stream << m_context->generate_basic_proxy_auth_header();
}
request_stream << CRLF;
m_context->m_timer.start();
tcp::resolver::query query(utility::conversions::to_utf8string(proxy_host), to_string(proxy_port));
auto client = std::static_pointer_cast<asio_client>(m_context->m_http_client);
m_context->m_resolver.async_resolve(query,
boost::bind(&ssl_proxy_tunnel::handle_resolve,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
private:
void handle_resolve(const boost::system::error_code& ec, tcp::resolver::iterator endpoints)
{
if (ec)
{
m_context->report_error("Error resolving proxy address", ec, httpclient_errorcode_context::connect);
}
else
{
m_context->m_timer.reset();
auto endpoint = *endpoints;
m_context->m_connection->async_connect(endpoint,
boost::bind(&ssl_proxy_tunnel::handle_tcp_connect,
shared_from_this(),
boost::asio::placeholders::error,
++endpoints));
}
}
void handle_tcp_connect(const boost::system::error_code& ec, tcp::resolver::iterator endpoints)
{
if (!ec)
{
m_context->m_timer.reset();
m_context->m_connection->enable_no_delay();
m_context->m_connection->async_write(m_request,
boost::bind(&ssl_proxy_tunnel::handle_write_request,
shared_from_this(),
boost::asio::placeholders::error));
}
else if (endpoints == tcp::resolver::iterator())
{
m_context->report_error(
"Failed to connect to any resolved proxy endpoint", ec, httpclient_errorcode_context::connect);
}
else
{
m_context->m_timer.reset();
//// Replace the connection. This causes old connection object to go out of scope.
auto client = std::static_pointer_cast<asio_client>(m_context->m_http_client);
try
{
m_context->m_connection = client->obtain_connection(m_context->m_request);
}
catch (...)
{
m_context->report_exception(std::current_exception());
return;
}
auto endpoint = *endpoints;
m_context->m_connection->async_connect(endpoint,
boost::bind(&ssl_proxy_tunnel::handle_tcp_connect,
shared_from_this(),
boost::asio::placeholders::error,
++endpoints));
}
}
void handle_write_request(const boost::system::error_code& err)
{
if (!err)
{
m_context->m_timer.reset();
m_context->m_connection->async_read_until(m_response,
CRLF + CRLF,
boost::bind(&ssl_proxy_tunnel::handle_status_line,
shared_from_this(),
boost::asio::placeholders::error));
}
else
{
m_context->report_error(
"Failed to send connect request to proxy.", err, httpclient_errorcode_context::writebody);
}
}
void handle_status_line(const boost::system::error_code& ec)
{
if (!ec)
{
m_context->m_timer.reset();
std::istream response_stream(&m_response);
response_stream.imbue(std::locale::classic());
std::string http_version;
response_stream >> http_version;
status_code status_code;
response_stream >> status_code;
if (!response_stream || http_version.substr(0, 5) != "HTTP/")
{
m_context->report_error("Invalid HTTP status line during proxy connection",
ec,
httpclient_errorcode_context::readheader);
return;
}
if (status_code != 200)
{
m_context->report_error("Expected a 200 response from proxy, received: " + to_string(status_code),
ec,
httpclient_errorcode_context::readheader);
return;
}
try
{
m_context->upgrade_to_ssl();
}
catch (...)
{
m_context->report_exception(std::current_exception());
return;
}
m_ssl_tunnel_established(m_context);
}
else
{
m_context->handle_failed_read_status_line(ec, "Failed to read HTTP status line from proxy");
}
}
std::function<void(std::shared_ptr<asio_context>)> m_ssl_tunnel_established;
std::shared_ptr<asio_context> m_context;
boost::asio::streambuf m_request;
boost::asio::streambuf m_response;
};
enum class http_proxy_type
{
none,
http,
ssl_tunnel
};
void start_request()
{
if (m_request._cancellation_token().is_canceled())
{
request_context::report_error(make_error_code(std::errc::operation_canceled).value(),
"Request canceled by user.");
return;
}
http_proxy_type proxy_type = http_proxy_type::none;
std::string proxy_host;
int proxy_port = -1;
// There is no support for auto-detection of proxies on non-windows platforms, it must be specified explicitly
// from the client code.
if (m_http_client->client_config().proxy().is_specified())
{
proxy_type =
m_http_client->base_uri().scheme() == U("https") ? http_proxy_type::ssl_tunnel : http_proxy_type::http;
auto proxy = m_http_client->client_config().proxy();
auto proxy_uri = proxy.address();
proxy_port = proxy_uri.port() == -1 ? 8080 : proxy_uri.port();
proxy_host = utility::conversions::to_utf8string(proxy_uri.host());
}
auto start_http_request_flow = [proxy_type, proxy_host, proxy_port AND_CAPTURE_MEMBER_FUNCTION_POINTERS](
std::shared_ptr<asio_context> ctx) {
if (ctx->m_request._cancellation_token().is_canceled())
{
ctx->request_context::report_error(make_error_code(std::errc::operation_canceled).value(),
"Request canceled by user.");
return;
}
const auto& base_uri = ctx->m_http_client->base_uri();
const auto full_uri = uri_builder(base_uri).append(ctx->m_request.relative_uri()).to_uri();
// For a normal http proxy, we need to specify the full request uri, otherwise just specify the resource
auto encoded_resource =
proxy_type == http_proxy_type::http ? full_uri.to_string() : full_uri.resource().to_string();
if (encoded_resource.empty())
{
encoded_resource = U("/");
}
const auto& method = ctx->m_request.method();
// stop injection of headers via method
// resource should be ok, since it's been encoded
// and host won't resolve
if (!::web::http::details::validate_method(method))
{
ctx->report_exception(http_exception("The method string is invalid."));
return;
}
std::ostream request_stream(&ctx->m_body_buf);
request_stream.imbue(std::locale::classic());
const auto& host = utility::conversions::to_utf8string(base_uri.host());
request_stream << utility::conversions::to_utf8string(method) << " "
<< utility::conversions::to_utf8string(encoded_resource) << " "
<< "HTTP/1.1\r\n";
int port = base_uri.port();
if (base_uri.is_port_default())
{
port = (ctx->m_connection->is_ssl() ? 443 : 80);
}
// Add the Host header if user has not specified it explicitly
if (!ctx->m_request.headers().has(header_names::host))
{
request_stream << "Host: " << host;
if (!base_uri.is_port_default())
{
request_stream << ":" << port;
}
request_stream << CRLF;
}
// Extra request headers are constructed here.
std::string extra_headers;
// Add header for basic proxy authentication
if (proxy_type == http_proxy_type::http &&
ctx->m_http_client->client_config().proxy().credentials().is_set())
{
extra_headers.append(ctx->generate_basic_proxy_auth_header());
}
if (ctx->m_http_client->client_config().credentials().is_set())
{
extra_headers.append(ctx->generate_basic_auth_header());
}
extra_headers += utility::conversions::to_utf8string(ctx->get_compression_header());
// Check user specified transfer-encoding.
std::string transferencoding;
if (ctx->m_request.headers().match(header_names::transfer_encoding, transferencoding) &&
boost::icontains(transferencoding, U("chunked")))
{
ctx->m_needChunked = true;
}
else if (!ctx->m_request.headers().match(header_names::content_length, ctx->m_content_length))
{
// Stream without content length is the signal of requiring transfer encoding chunked.
if (ctx->m_request.body())
{
ctx->m_needChunked = true;
extra_headers.append("Transfer-Encoding:chunked\r\n");
}
else if (ctx->m_request.method() == methods::POST || ctx->m_request.method() == methods::PUT)
{
// Some servers do not accept POST/PUT requests with a content length of 0, such as
// lighttpd - http://serverfault.com/questions/315849/curl-post-411-length-required
// old apache versions - https://issues.apache.org/jira/browse/TS-2902
extra_headers.append("Content-Length: 0\r\n");
}
}
if (proxy_type == http_proxy_type::http)
{
extra_headers.append("Cache-Control: no-store, no-cache\r\n"
"Pragma: no-cache\r\n");
}
request_stream << utility::conversions::to_utf8string(
::web::http::details::flatten_http_headers(ctx->m_request.headers()));
request_stream << extra_headers;
// Enforce HTTP connection keep alive (even for the old HTTP/1.0 protocol).
request_stream << "Connection: Keep-Alive\r\n\r\n";
// Start connection timeout timer.
if (!ctx->m_timer.has_started())
{
ctx->m_timer.start();
}
if (ctx->m_connection->is_reused() || proxy_type == http_proxy_type::ssl_tunnel)
{
// If socket is a reused connection or we're connected via an ssl-tunneling proxy, try to write the
// request directly. In both cases we have already established a tcp connection.
ctx->write_request();
}
else
{
// If the connection is new (unresolved and unconnected socket), then start async
// call to resolve first, leading eventually to request write.
// For normal http proxies, we want to connect directly to the proxy server. It will relay our request.
auto tcp_host = proxy_type == http_proxy_type::http ? proxy_host : host;
auto tcp_port = proxy_type == http_proxy_type::http ? proxy_port : port;
tcp::resolver::query query(tcp_host, to_string(tcp_port));
ctx->m_resolver.async_resolve(query,
boost::bind(&asio_context::handle_resolve,
ctx,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
// Register for notification on cancellation to abort this request.
if (ctx->m_request._cancellation_token() != pplx::cancellation_token::none())
{
// weak_ptr prevents lambda from taking shared ownership of the context.
// Otherwise context replacement in the handle_status_line() would leak the objects.
std::weak_ptr<asio_context> ctx_weak(ctx);
ctx->m_cancellationRegistration = ctx->m_request._cancellation_token().register_callback([ctx_weak]() {
if (auto ctx_lock = ctx_weak.lock())
{
// Shut down transmissions, close the socket and prevent connection from being pooled.
ctx_lock->m_connection->close();
}
});
}
};
// Note that we must not try to CONNECT using an already established connection via proxy -- this would send
// CONNECT to the end server which is definitely not what we want.
if (proxy_type == http_proxy_type::ssl_tunnel && !m_connection->is_reused())
{
// The ssl_tunnel_proxy keeps the context alive and then calls back once the ssl tunnel is established via
// 'start_http_request_flow'
std::shared_ptr<ssl_proxy_tunnel> ssl_tunnel =
std::make_shared<ssl_proxy_tunnel>(shared_from_this(), start_http_request_flow);
ssl_tunnel->start_proxy_connect();
}
else
{
start_http_request_flow(shared_from_this());
}
}
template<typename _ExceptionType>
void report_exception(const _ExceptionType& e)
{
report_exception(std::make_exception_ptr(e));
}
void report_exception(std::exception_ptr exceptionPtr) override
{
// Don't recycle connections that had an error into the connection pool.
m_connection->close();
request_context::report_exception(exceptionPtr);
}
private:
void upgrade_to_ssl()
{
auto& client = static_cast<asio_client&>(*m_http_client);
m_connection->upgrade_to_ssl(calc_cn_host(client.base_uri(), m_request.headers()),
client.client_config().get_ssl_context_callback());
}
std::string generate_basic_auth_header()
{
std::string header;
header.append("Authorization: Basic ");
header.append(generate_base64_userpass(m_http_client->client_config().credentials()));
header.append(CRLF);
return header;
}
std::string generate_basic_proxy_auth_header()
{
std::string header;
header.append("Proxy-Authorization: Basic ");
header.append(generate_base64_userpass(m_http_client->client_config().proxy().credentials()));
header.append(CRLF);
return header;
}
void report_error(const std::string& message,
const boost::system::error_code& ec,
httpclient_errorcode_context context = httpclient_errorcode_context::none)
{
// By default, errorcodeValue don't need to converted
long errorcodeValue = ec.value();
// map timer cancellation to time_out
if (m_timer.has_timedout())
{
errorcodeValue = make_error_code(std::errc::timed_out).value();
}
else
{
// We need to correct inaccurate ASIO error code base on context information
switch (context)
{
case httpclient_errorcode_context::writeheader:
if (ec == boost::system::errc::broken_pipe)
{
errorcodeValue = make_error_code(std::errc::host_unreachable).value();
}
break;
case httpclient_errorcode_context::connect:
if (ec == boost::system::errc::connection_refused)
{
errorcodeValue = make_error_code(std::errc::host_unreachable).value();
}
break;
case httpclient_errorcode_context::readheader:
if (ec.default_error_condition().value() ==
boost::system::errc::no_such_file_or_directory) // bug in boost error_code mapping
{
errorcodeValue = make_error_code(std::errc::connection_aborted).value();