Repository navigation
Expand file tree
/
Copy pathCRTHttpClient.cpp
More file actions
934 lines (802 loc) · 41.9 KB
/
Copy pathCRTHttpClient.cpp
File metadata and controls
934 lines (802 loc) · 41.9 KB
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
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/http/crt/CRTHttpClient.h>
#include <aws/core/http/standard/StandardHttpRequest.h>
#include <aws/core/http/standard/StandardHttpResponse.h>
#include <aws/core/utils/crypto/Hash.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/utils/ratelimiter/RateLimiterInterface.h>
#include <aws/core/utils/threading/Semaphore.h>
#include <aws/core/utils/threading/Executor.h>
#include <aws/core/utils/threading/WaitGroup.h>
#include <aws/crt/http/HttpConnectionManager.h>
#include <aws/crt/http/HttpRequestResponse.h>
#include <aws/crt/io/Bootstrap.h>
#include <atomic>
#include <chrono>
#include <mutex>
#include <utility>
static const char *const CRT_HTTP_CLIENT_TAG = "CRTHttpClient";
namespace {
Aws::Client::AWSError<Aws::Client::CoreErrors> MakeCrtClientInitializationError(const Aws::Http::HttpRequest& request) {
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Refusing to send request to " << request.GetUri().GetAuthority()
<< ", the client failed to initialize its TLS context");
return Aws::Client::AWSError<Aws::Client::CoreErrors>{Aws::Client::CoreErrors::INVALID_PARAMETER_COMBINATION,
"InvalidParameterCombination",
"CRTHttpClient failed to initialize its TLS context, check caFile, caPath and the proxy TLS settings",
false};
}
void AddRequestMetadataToCrtRequest(const std::shared_ptr<Aws::Http::HttpRequest>& request,
const std::shared_ptr<Aws::Crt::Http::HttpRequest>& crtRequest) {
const char* methodStr = Aws::Http::HttpMethodMapper::GetNameForHttpMethod(request->GetMethod());
AWS_LOGSTREAM_TRACE(CRT_HTTP_CLIENT_TAG, "Making " << methodStr << " request to " << request->GetURIString());
AWS_LOGSTREAM_TRACE(CRT_HTTP_CLIENT_TAG, "Including headers:");
// Add http headers to the request.
for (const auto& header : request->GetHeaders()) {
Aws::Crt::Http::HttpHeader crtHeader;
AWS_LOGSTREAM_TRACE(CRT_HTTP_CLIENT_TAG, header.first << ": " << header.second);
crtHeader.name = Aws::Crt::ByteCursorFromArray((const uint8_t*)header.first.data(), header.first.length());
crtHeader.value = Aws::Crt::ByteCursorFromArray((const uint8_t*)header.second.data(), header.second.length());
crtRequest->AddHeader(crtHeader);
}
// HTTP method, GET, PUT, DELETE, etc...
auto methodCursor = Aws::Crt::ByteCursorFromCString(methodStr);
crtRequest->SetMethod(methodCursor);
// Path portion of the request
auto pathStrCpy = request->GetUri().GetURLEncodedPathRFC3986();
auto queryStrCpy = request->GetUri().GetQueryString();
Aws::StringStream ss;
// CRT client has you pass the query string as part of the path. concatenate that here.
ss << pathStrCpy << queryStrCpy;
auto fullPathAndQueryCpy = ss.str();
auto pathCursor = Aws::Crt::ByteCursorFromArray((uint8_t*)fullPathAndQueryCpy.c_str(), fullPathAndQueryCpy.length());
crtRequest->SetPath(pathCursor);
}
void OnResponseBodyReceived(Aws::Crt::Http::HttpStream&, const Aws::Crt::ByteCursor& body,
const std::shared_ptr<Aws::Http::HttpResponse>& response,
const std::shared_ptr<Aws::Http::HttpRequest>& request) {
assert(response);
for (const auto& hashIterator : request->GetResponseValidationHashes()) {
if (response->HasHeader(("x-amz-checksum-" + hashIterator.first).c_str())) {
hashIterator.second->Update(reinterpret_cast<unsigned char*>(body.ptr), body.len);
break;
}
}
// When data is received from the content body of the incoming response, just copy it to the output stream.
response->GetResponseBody().write((const char*)body.ptr, static_cast<long>(body.len));
if (response->GetResponseBody().fail()) {
const auto& ref = response->GetResponseBody();
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Failed to write " << body.len << " (eof: " << ref.eof() << ", bad: " << ref.bad() << ")");
}
if ((request->IsEventStreamRequest() || request->HasEventStreamResponse()) && !response->HasHeader(Aws::Http::X_AMZN_ERROR_TYPE)) {
response->GetResponseBody().flush();
}
auto& receivedHandler = request->GetDataReceivedEventHandler();
if (receivedHandler) {
receivedHandler(request.get(), response.get(), static_cast<long long>(body.len));
}
AWS_LOGSTREAM_TRACE(CRT_HTTP_CLIENT_TAG, body.len << " bytes written to response.");
}
// on response headers arriving, write them to the response.
void OnIncomingHeaders(Aws::Crt::Http::HttpStream&, enum aws_http_header_block block, const Aws::Crt::Http::HttpHeader* headersArray,
std::size_t headersCount, const std::shared_ptr<Aws::Http::HttpResponse>& response) {
if (block == AWS_HTTP_HEADER_BLOCK_INFORMATIONAL) return;
AWS_LOGSTREAM_TRACE(CRT_HTTP_CLIENT_TAG, "Received Headers: ");
for (size_t i = 0; i < headersCount; ++i) {
const Aws::Crt::Http::HttpHeader* header = &headersArray[i];
Aws::String headerNameStr((const char*)header->name.ptr, header->name.len);
Aws::String headerValueStr((const char*)header->value.ptr, header->value.len);
AWS_LOGSTREAM_TRACE(CRT_HTTP_CLIENT_TAG, headerNameStr << ": " << headerValueStr);
response->AddHeader(headerNameStr, std::move(headerValueStr));
}
}
void OnIncomingHeadersBlockDone(Aws::Crt::Http::HttpStream& stream, enum aws_http_header_block,
const std::shared_ptr<Aws::Http::HttpResponse>& response) {
AWS_LOGSTREAM_TRACE(CRT_HTTP_CLIENT_TAG, "Received response code: " << stream.GetResponseStatusCode());
response->SetResponseCode((Aws::Http::HttpResponseCode)stream.GetResponseStatusCode());
}
struct AsyncRequestState {
AsyncRequestState(const std::shared_ptr<Aws::Http::HttpRequest>& request,
std::function<void(std::shared_ptr<Aws::Http::HttpResponse>)> onResponseComplete)
: request(request),
response(Aws::MakeShared<Aws::Http::Standard::StandardHttpResponse>(CRT_HTTP_CLIENT_TAG, request)),
crtRequest(Aws::Crt::MakeShared<Aws::Crt::Http::HttpRequest>(Aws::Crt::g_allocator)),
onComplete(std::move(onResponseComplete)) {}
std::shared_ptr<Aws::Http::HttpRequest> request;
std::shared_ptr<Aws::Http::HttpResponse> response;
std::shared_ptr<Aws::Crt::Http::HttpRequest> crtRequest;
std::function<void(std::shared_ptr<Aws::Http::HttpResponse>)> onComplete;
std::atomic<bool> finished{false};
std::shared_ptr<Aws::Utils::Threading::WaitGroup> latch;
std::weak_ptr<Aws::Crt::Http::HttpClientConnection> connection;
std::mutex connectionMutex;
Aws::Crt::Io::ScheduledTask timeoutTask;
void Finish() {
if (finished.exchange(true)) {
return;
}
if (onComplete) {
onComplete(std::move(response));
}
if (latch) {
latch->Done();
}
}
void CompleteWithError(Aws::Client::CoreErrors errorType, const char* errorMessage) {
if (finished.exchange(true)) {
return;
}
response->SetClientErrorType(errorType);
response->SetClientErrorMessage(errorMessage);
if (onComplete) {
onComplete(response);
}
if (latch) {
latch->Done();
}
}
};
void OnStreamCompleteAsync(int errorCode, const std::shared_ptr<AsyncRequestState>& state) {
state->timeoutTask.Cancel();
if (errorCode) {
state->CompleteWithError(Aws::Client::CoreErrors::NETWORK_CONNECTION, aws_error_debug_str(errorCode));
} else {
state->Finish();
}
}
void OnClientConnectionAvailableAsync(const std::shared_ptr<Aws::Crt::Http::HttpClientConnection>& connection, int errorCode,
const std::shared_ptr<AsyncRequestState>& state, const Aws::Http::HttpClient& client) {
bool shouldContinueRequest = client.ContinueRequest(*state->request);
if (!shouldContinueRequest) {
state->timeoutTask.Cancel();
state->CompleteWithError(Aws::Client::CoreErrors::USER_CANCELLED, "Request cancelled by user's continuation handler");
return;
}
int finalErrorCode = errorCode;
if (connection) {
{
std::lock_guard<std::mutex> lock(state->connectionMutex);
state->connection = connection;
}
AWS_LOGSTREAM_DEBUG(CRT_HTTP_CLIENT_TAG, "Obtained connection handle " << (void*)connection.get());
Aws::Crt::Http::HttpRequestOptions requestOptions{};
requestOptions.request = state->crtRequest.get();
requestOptions.onIncomingBody = [&client, state](Aws::Crt::Http::HttpStream& stream, const Aws::Crt::ByteCursor& body) {
if (!client.ContinueRequest(*state->request) || !client.IsRequestProcessingEnabled()) {
AWS_LOGSTREAM_INFO(CRT_HTTP_CLIENT_TAG, "Request canceled. Canceling request by closing the connection.");
stream.GetConnection().Close();
return;
}
OnResponseBodyReceived(stream, body, state->response, state->request);
};
requestOptions.onIncomingHeaders = [state](Aws::Crt::Http::HttpStream& stream, enum aws_http_header_block block,
const Aws::Crt::Http::HttpHeader* headersArray, std::size_t headersCount) {
OnIncomingHeaders(stream, block, headersArray, headersCount, state->response);
// aws-c-http reports the main block done only when the body starts, so stamp as header lines arrive.
// Written on the event-loop thread and read in the completion callback on that same thread.
if (block == AWS_HTTP_HEADER_BLOCK_MAIN) {
state->request->SetResponseHeadersReceivedTime(Aws::Utils::DateTime::Now());
}
};
requestOptions.onIncomingHeadersBlockDone = [state](Aws::Crt::Http::HttpStream& stream, enum aws_http_header_block block) {
OnIncomingHeadersBlockDone(stream, block, state->response);
auto& headersHandler = state->request->GetHeadersReceivedEventHandler();
if (headersHandler) {
headersHandler(state->request.get(), state->response.get());
}
};
requestOptions.onStreamComplete = [state](Aws::Crt::Http::HttpStream&, int streamErrorCode) {
OnStreamCompleteAsync(streamErrorCode, state);
};
auto clientStream = connection->NewClientStream(requestOptions);
if (clientStream && clientStream->Activate()) {
return;
}
finalErrorCode = aws_last_error();
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Initiation of request failed because " << aws_error_debug_str(finalErrorCode));
}
const char* errorMsg = aws_error_debug_str(finalErrorCode);
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Obtaining connection failed because " << errorMsg);
state->timeoutTask.Cancel();
state->CompleteWithError(Aws::Client::CoreErrors::NETWORK_CONNECTION, errorMsg);
}
struct SyncRequestState {
Aws::Utils::Threading::Semaphore signal{0, 1};
std::shared_ptr<Aws::Http::HttpResponse> response;
};
class CRTClientStream : public Aws::Http::ClientStream {
public:
CRTClientStream(std::shared_ptr<Aws::Crt::Http::HttpClientStream> stream, std::shared_ptr<Aws::Http::HttpResponse> response,
std::shared_ptr<Aws::Crt::Http::HttpRequest> crtRequest)
: m_stream(std::move(stream)), m_response(std::move(response)), m_crtRequest(std::move(crtRequest)) {}
~CRTClientStream() override = default;
bool Activate() override {
return m_stream->Activate();
};
int WriteData(std::shared_ptr<Aws::IOStream> stream, const std::function<void(int errorCode)>& onComplete, bool endStream) override {
auto crtStream = std::make_shared<Aws::Crt::Io::StdIOStreamInputStream>(stream, Aws::Crt::ApiAllocator());
if (!crtStream->IsValid()) {
onComplete(AWS_ERROR_HTTP_STREAM_HAS_COMPLETED);
return AWS_ERROR_HTTP_STREAM_HAS_COMPLETED;
}
return m_stream->WriteData(crtStream,
[onComplete](std::shared_ptr<Aws::Crt::Http::HttpStream>&, int errorCode) {
onComplete(errorCode);
},
endStream);
}
std::shared_ptr<Aws::Http::HttpResponse> GetResponse() const override { return m_response; }
private:
std::shared_ptr<Aws::Crt::Http::HttpClientStream> m_stream;
std::shared_ptr<Aws::Http::HttpResponse> m_response;
// extend life of request for duration of client stream. Request must outlive
// the last call to WriteData.
std::shared_ptr<Aws::Crt::Http::HttpRequest> m_crtRequest;
};
class CRTConnection : public Aws::Http::Connection {
public:
explicit CRTConnection(std::shared_ptr<Aws::Crt::Http::HttpClientConnection> connection) : m_connection(std::move(connection)) {}
~CRTConnection() override = default;
void Close() override {
if (m_connection) {
m_connection->Close();
}
}
std::shared_ptr<Aws::Http::ClientStream> NewClientStream(const std::shared_ptr<Aws::Http::HttpRequest>& request,
std::function<void(int errorCode)> onStreamComplete) override {
auto crtRequest = Aws::Crt::MakeShared<Aws::Crt::Http::HttpRequest>(Aws::Crt::g_allocator);
auto response = Aws::MakeShared<Aws::Http::Standard::StandardHttpResponse>(CRT_HTTP_CLIENT_TAG, request);
AddRequestMetadataToCrtRequest(request, crtRequest);
Aws::Crt::Http::HttpRequestOptions requestOptions{};
requestOptions.request = crtRequest.get();
requestOptions.onIncomingHeaders = [request, response](Aws::Crt::Http::HttpStream& stream, enum aws_http_header_block block,
const Aws::Crt::Http::HttpHeader* headersArray, std::size_t headersCount) {
OnIncomingHeaders(stream, block, headersArray, headersCount, response);
// aws-c-http reports the main block done only when the body starts, so stamp as header lines arrive.
// Written on the event-loop thread; the caller reads it only after waiting for stream completion.
if (block == AWS_HTTP_HEADER_BLOCK_MAIN) {
request->SetResponseHeadersReceivedTime(Aws::Utils::DateTime::Now());
}
};
requestOptions.onIncomingHeadersBlockDone = [request, response](Aws::Crt::Http::HttpStream& stream, enum aws_http_header_block block) {
OnIncomingHeadersBlockDone(stream, block, response);
auto& headersHandler = request->GetHeadersReceivedEventHandler();
if (headersHandler) {
headersHandler(request.get(), response.get());
}
};
requestOptions.onIncomingBody = [request, response](Aws::Crt::Http::HttpStream& stream, const Aws::Crt::ByteCursor& body) {
OnResponseBodyReceived(stream, body, response, request);
};
requestOptions.onStreamComplete = [response, onStreamComplete](Aws::Crt::Http::HttpStream &, int errorCode) -> void {
if (errorCode) {
// TODO: get the right error parsed out.
response->SetClientErrorType(Aws::Client::CoreErrors::NETWORK_CONNECTION);
response->SetClientErrorMessage(aws_error_debug_str(errorCode));
}
onStreamComplete(errorCode);
};
requestOptions.UseManualDataWrites = true;
auto crtStream = m_connection->NewClientStream(requestOptions);
if (!crtStream) {
return nullptr;
}
return Aws::MakeShared<CRTClientStream>(CRT_HTTP_CLIENT_TAG, std::move(crtStream), std::move(response), std::move(crtRequest));
}
private:
std::shared_ptr<Aws::Crt::Http::HttpClientConnection> m_connection;
};
} // namespace
// Adapts AWS SDK input streams and rate limiters to the CRT input stream reading model.
class SDKAdaptingInputStream : public Aws::Crt::Io::StdIOStreamInputStream {
public:
SDKAdaptingInputStream(const std::shared_ptr<Aws::Utils::RateLimits::RateLimiterInterface>& rateLimiter,
std::shared_ptr<Aws::Crt::Io::IStream> stream,
const Aws::Http::HttpClient& client,
const Aws::Http::HttpRequest& request,
bool isStreaming,
Aws::Crt::Allocator* allocator = Aws::Crt::ApiAllocator()) noexcept :
Aws::Crt::Io::StdIOStreamInputStream(std::move(stream), allocator),
m_rateLimiter(rateLimiter),
m_client(client),
m_currentRequest(request),
m_isStreaming(isStreaming)
{
}
protected:
bool ReadImpl(Aws::Crt::ByteBuf &buffer) noexcept override
{
if (!m_client.ContinueRequest(m_currentRequest) || !m_client.IsRequestProcessingEnabled())
{
return false;
}
// initial check to see if we should avoid reading for the moment.
if (!m_rateLimiter || (m_rateLimiter && m_rateLimiter->ApplyCost(0) == std::chrono::milliseconds(0))) {
size_t currentPos = buffer.len;
// now do the read. We may over read by an IO buffer size, but it's fine. The throttle will still
// kick-in in plenty of time.
bool retValue = false;
if (!m_isStreaming)
{
retValue = Aws::Crt::Io::StdIOStreamInputStream::ReadImpl(buffer);
}
else
{
if (StdIOStreamInputStream::GetStatusImpl().is_valid && StdIOStreamInputStream::PeekImpl() != std::char_traits<char>::eof())
{
retValue = Aws::Crt::Io::StdIOStreamInputStream::ReadSomeImpl(buffer);
}
}
size_t newPos = buffer.len;
AWS_ASSERT(newPos >= currentPos && "the buffer length should not have decreased in value.");
if (retValue && m_isStreaming)
{
Aws::Crt::Io::StreamStatus streamStatus;
GetStatus(streamStatus);
if (newPos == currentPos && !streamStatus.is_end_of_stream && streamStatus.is_valid)
{
return true;
}
}
size_t amountRead = newPos - currentPos;
auto& sentHandler = m_currentRequest.GetDataSentEventHandler();
if (sentHandler)
{
sentHandler(&m_currentRequest, static_cast<long long>(amountRead));
}
if (m_rateLimiter)
{
// now actually reduce the window.
m_rateLimiter->ApplyCost(static_cast<int64_t>(newPos - currentPos));
return retValue;
}
}
return true;
}
private:
std::shared_ptr<Aws::Utils::RateLimits::RateLimiterInterface> m_rateLimiter;
const Aws::Http::HttpClient& m_client;
const Aws::Http::HttpRequest& m_currentRequest;
bool m_isStreaming;
};
namespace Aws
{
namespace Http
{
CRTHttpClient::CRTHttpClient(const Aws::Client::ClientConfiguration& clientConfig, Crt::Io::ClientBootstrap& bootstrap) :
HttpClient(), m_context(), m_proxyOptions(), m_bootstrap(bootstrap), m_configuration(clientConfig),
m_requestLatch(Aws::MakeShared<Aws::Utils::Threading::WaitGroup>(CRT_HTTP_CLIENT_TAG))
{
//first need to figure TLS out...
Crt::Io::TlsContextOptions tlsContextOptions = Crt::Io::TlsContextOptions::InitDefaultClient();
CheckAndInitializeProxySettings(clientConfig);
// Given current SDK configuration assumptions, if the ca is overridden and a proxy is configured,
// it's intended for the proxy, not this context.
if (!m_proxyOptions.has_value())
{
if (!m_configuration.caPath.empty() || !m_configuration.caFile.empty())
{
const char* caPath = m_configuration.caPath.empty() ? nullptr : m_configuration.caPath.c_str();
const char* caFile = m_configuration.caFile.empty() ? nullptr : m_configuration.caFile.c_str();
if (!tlsContextOptions.OverrideDefaultTrustStore(caPath, caFile))
{
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Failed to load the trust store, caPath: \"" << m_configuration.caPath
<< "\", caFile: \"" << m_configuration.caFile << "\": " << aws_error_debug_str(aws_last_error()));
m_bad = true;
return;
}
}
}
tlsContextOptions.SetVerifyPeer(m_configuration.verifySSL);
if (Crt::Io::TlsContextOptions::IsAlpnSupported())
{
// this may need to be pulled from the client configuration....
if (!tlsContextOptions.SetAlpnList("h2;http/1.1"))
{
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Failed to set the TLS ALPN list: " << aws_error_debug_str(aws_last_error()));
m_bad = true;
return;
}
}
Crt::Io::TlsContext newContext(tlsContextOptions, Crt::Io::TlsMode::CLIENT);
if (!newContext)
{
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Failed to create the TLS context: "
<< aws_error_debug_str(newContext.GetInitializationError()));
m_bad = true;
return;
}
m_context = std::move(newContext);
}
CRTHttpClient::~CRTHttpClient()
{
m_requestLatch->Wait();
Aws::Vector<std::future<void>> shutdownFutures;
for (auto& managerPair : m_connectionPools)
{
shutdownFutures.push_back(managerPair.second->InitiateShutdown());
}
for (auto& shutdownFuture : shutdownFutures)
{
shutdownFuture.get();
}
shutdownFutures.clear();
m_connectionPools.clear();
}
Aws::Crt::Optional<Aws::Client::AWSError<Aws::Client::CoreErrors>> CRTHttpClient::SendOneAttemptAsync(
const std::shared_ptr<HttpRequest>& request,
std::function<void(std::shared_ptr<HttpResponse>)> onResponseComplete) const
{
if (m_bad)
{
return MakeCrtClientInitializationError(*request);
}
auto state = Aws::MakeShared<AsyncRequestState>(CRT_HTTP_CLIENT_TAG, request, std::move(onResponseComplete));
auto requestConnOptions = CreateConnectionOptionsForRequest(request);
auto connectionManager = GetWithCreateConnectionManagerForRequest(request, requestConnOptions);
if (!connectionManager)
{
return Aws::Client::AWSError<Aws::Client::CoreErrors>{
Aws::Client::CoreErrors::INVALID_PARAMETER_COMBINATION,
"InvalidParameterCombination",
aws_error_debug_str(aws_last_error()),
false};
}
AddRequestMetadataToCrtRequest(request, state->crtRequest);
// Set the request body stream on the crt request. Setup the write rate limiter if present
if (request->GetContentBody())
{
bool isStreaming = request->IsEventStreamRequest();
state->crtRequest->SetBody(Aws::MakeShared<SDKAdaptingInputStream>(CRT_HTTP_CLIENT_TAG, m_configuration.writeRateLimiter, request->GetContentBody(), *this, *request, isStreaming));
}
state->latch = m_requestLatch;
m_requestLatch->Add();
auto startSend = [state, this, connectionManager]()
{
if (m_configuration.requestTimeoutMs > 0)
{
std::weak_ptr<AsyncRequestState> weakState = state;
state->timeoutTask = m_bootstrap.GetNextEventLoop().Schedule(
[weakState](Aws::Crt::Io::TaskStatus status)
{
if (status != Aws::Crt::Io::TaskStatus::RunReady)
{
return;
}
auto state = weakState.lock();
if (!state)
{
return;
}
std::shared_ptr<Aws::Crt::Http::HttpClientConnection> connection;
{
std::lock_guard<std::mutex> lock(state->connectionMutex);
connection = state->connection.lock();
}
if (connection)
{
connection->Close();
}
state->CompleteWithError(Aws::Client::CoreErrors::REQUEST_TIMEOUT, "Request Timeout Has Expired");
},
std::chrono::milliseconds(m_configuration.requestTimeoutMs));
}
connectionManager->AcquireConnection(
[state, this](std::shared_ptr<Crt::Http::HttpClientConnection> connection, int errorCode)
{
OnClientConnectionAvailableAsync(connection, errorCode, state, *this);
});
};
startSend();
return {};
}
namespace
{
struct CRTAttemptLoop : std::enable_shared_from_this<CRTAttemptLoop>
{
HttpClient::PrepareAttempt prepare;
HttpClient::EvaluateAttempt evaluate;
HttpClient::OnRetryableRequestComplete complete;
std::function<void(const std::shared_ptr<HttpRequest>&, std::function<void(std::shared_ptr<HttpResponse>)>)> send;
std::function<void(std::function<void(bool)>, std::chrono::milliseconds)> schedule;
std::function<bool()> processingDisabled;
std::shared_ptr<Aws::Utils::Threading::Executor> executor;
void RunAttempt()
{
auto request = prepare();
auto self = shared_from_this();
if (!request)
{
complete();
return;
}
send(request, [self](std::shared_ptr<HttpResponse> response)
{
auto handleResponse = [self, response]()
{
auto outcome = self->evaluate(response);
if (outcome.shouldRetry)
{
self->schedule([self](bool canceled)
{
if (canceled || !self->executor->Submit([self]() { self->RunAttempt(); }))
{
self->complete();
}
}, outcome.backoff);
}
else if (outcome.backoff.count() > 0)
{
self->schedule([self](bool canceled)
{
if (canceled || !self->executor->Submit([self]() { self->complete(); }))
{
self->complete();
}
}, outcome.backoff);
}
else
{
self->complete();
}
};
if (self->processingDisabled() || !self->executor->Submit(handleResponse))
{
handleResponse();
}
});
}
};
}
Aws::Crt::Optional<Aws::Client::AWSError<Aws::Client::CoreErrors>> CRTHttpClient::MakeRequestAsync(
const HttpClient::PrepareAttempt& prepareAttempt,
const HttpClient::EvaluateAttempt& evaluateAttempt,
const HttpClient::OnRetryableRequestComplete& onComplete,
std::shared_ptr<Aws::Utils::Threading::Executor> executor) const
{
if (!executor)
{
return Aws::Client::AWSError<Aws::Client::CoreErrors>{Aws::Client::CoreErrors::INVALID_PARAMETER_VALUE,
"InvalidParameterValue",
"an executor is required to run async requests",
false};
}
auto attemptLoop = Aws::MakeShared<CRTAttemptLoop>(CRT_HTTP_CLIENT_TAG);
attemptLoop->prepare = prepareAttempt;
attemptLoop->evaluate = evaluateAttempt;
attemptLoop->executor = std::move(executor);
auto latch = m_requestLatch;
latch->Add();
attemptLoop->complete = [onComplete, latch]()
{
latch->Done();
onComplete();
};
const CRTHttpClient* self = this;
attemptLoop->send = [self](const std::shared_ptr<HttpRequest>& request,
std::function<void(std::shared_ptr<HttpResponse>)> onResponse)
{
auto error = self->SendOneAttemptAsync(request, onResponse);
if (error.has_value())
{
auto response = Aws::MakeShared<Standard::StandardHttpResponse>(CRT_HTTP_CLIENT_TAG, request);
response->SetResponseCode(Aws::Http::HttpResponseCode::REQUEST_NOT_MADE);
response->SetClientErrorType(error->GetErrorType());
response->SetClientErrorMessage(error->GetMessage());
onResponse(std::move(response));
}
};
attemptLoop->schedule = [self](std::function<void(bool)> task, std::chrono::milliseconds delay)
{
self->m_bootstrap.GetNextEventLoop().Schedule(
[self, task](Aws::Crt::Io::TaskStatus status)
{
task(status != Aws::Crt::Io::TaskStatus::RunReady || !self->IsRequestProcessingEnabled());
},
delay);
};
attemptLoop->processingDisabled = [self]()
{
return !self->IsRequestProcessingEnabled();
};
attemptLoop->RunAttempt();
return {};
}
std::shared_ptr<HttpResponse> CRTHttpClient::MakeRequest(const std::shared_ptr<HttpRequest>& request,
Aws::Utils::RateLimits::RateLimiterInterface* readLimiter,
Aws::Utils::RateLimits::RateLimiterInterface* writeLimiter) const
{
AWS_UNREFERENCED_PARAM(readLimiter);
AWS_UNREFERENCED_PARAM(writeLimiter);
auto sync = Aws::MakeShared<SyncRequestState>(CRT_HTTP_CLIENT_TAG);
auto error = SendOneAttemptAsync(request,
[sync](std::shared_ptr<HttpResponse> response)
{
sync->response = std::move(response);
sync->signal.Release();
});
if (error.has_value())
{
auto response = Aws::MakeShared<Standard::StandardHttpResponse>(CRT_HTTP_CLIENT_TAG, request);
response->SetClientErrorType(error->GetErrorType());
response->SetClientErrorMessage(error->GetMessage());
return response;
}
sync->signal.WaitOne();
// TODO: is VOX support still a thing? If so we need to add the metrics for it.
return std::move(sync->response);
}
Aws::String CRTHttpClient::ResolveConnectionPoolKey(const URI& uri)
{
// create a unique key for this endpoint.
Aws::StringStream ss;
ss << SchemeMapper::ToString(uri.GetScheme()) << "://" << uri.GetAuthority() << ":" << uri.GetPort();
return ss.str();
}
// The main purpose of this is to ensure there's exactly one connection manager per unique endpoint.
// To do so, we simply keep a hash table of the endpoint key (see ResolveConnectionPoolKey()), and
// put a connection manager for that endpoint as the value.
// This runs in multiple threads potentially so there's a lock around it.
std::shared_ptr<Crt::Http::HttpClientConnectionManager> CRTHttpClient::GetWithCreateConnectionManagerForRequest(const std::shared_ptr<HttpRequest>& request, const Crt::Http::HttpClientConnectionOptions& options) const
{
const auto connManagerRequestKey = ResolveConnectionPoolKey(request->GetUri());
std::lock_guard<std::mutex> locker(m_connectionPoolLock);
const auto& foundManager = m_connectionPools.find(connManagerRequestKey);
// We've already got one, return it.
if (foundManager != m_connectionPools.cend()) {
return foundManager->second;
}
// don't have a manager for this endpoint, so create one for it.
Crt::Http::HttpClientConnectionManagerOptions connectionManagerOptions;
connectionManagerOptions.ConnectionOptions = options;
connectionManagerOptions.MaxConnections = m_configuration.maxConnections;
connectionManagerOptions.EnableBlockingShutdown = true;
if (m_configuration.lowSpeedLimit > 0 && m_configuration.requestTimeoutMs > 0)
{
connectionManagerOptions.MinThroughputBytesPerSecond =
static_cast<uint64_t>(m_configuration.lowSpeedLimit);
connectionManagerOptions.AllowableThroughputFailureIntervalSeconds =
static_cast<uint32_t>((m_configuration.requestTimeoutMs + 999) / 1000);
}
auto connectionManager = Crt::Http::HttpClientConnectionManager::NewClientConnectionManager(connectionManagerOptions);
if (!connectionManager)
{
return nullptr;
}
// put it in the hash table and return it.
m_connectionPools.emplace(connManagerRequestKey, connectionManager);
return connectionManager;
}
Crt::Http::HttpClientConnectionOptions CRTHttpClient::CreateConnectionOptionsForRequest(const std::shared_ptr<HttpRequest>& request) const
{
// connection options are unique per request, this is mostly just connection-level configuration mapping.
Crt::Http::HttpClientConnectionOptions connectionOptions;
connectionOptions.HostName = request->GetUri().GetAuthority().c_str();
// TODO: come back and update this when we hook up the rate limiters.
connectionOptions.ManualWindowManagement = false;
connectionOptions.Port = request->GetUri().GetPort();
if (m_context.has_value() && request->GetUri().GetScheme() == Scheme::HTTPS)
{
connectionOptions.TlsOptions = m_context.value().NewConnectionOptions();
auto serverName = request->GetUri().GetAuthority();
auto serverNameCursor = Crt::ByteCursorFromCString(serverName.c_str());
connectionOptions.TlsOptions->SetServerName(serverNameCursor);
}
connectionOptions.Bootstrap = &m_bootstrap;
if (m_proxyOptions.has_value())
{
connectionOptions.ProxyOptions = m_proxyOptions.value();
}
connectionOptions.SocketOptions.SetConnectTimeoutMs(m_configuration.connectTimeoutMs);
connectionOptions.SocketOptions.SetKeepAlive(m_configuration.enableTcpKeepAlive);
if (m_configuration.enableTcpKeepAlive)
{
connectionOptions.SocketOptions.SetKeepAliveIntervalSec(
(uint16_t) (m_configuration.tcpKeepAliveIntervalMs / 1000));
}
connectionOptions.SocketOptions.SetSocketType(Crt::Io::SocketType::Stream);
return connectionOptions;
}
// The proxy config is pretty hefty, so we don't want to create one for each request when we don't have to.
// This converts whatever proxy settings are in clientConfig to CRT specific proxy settings.
// It then sets it on the member variable for re-use elsewhere.
void CRTHttpClient::CheckAndInitializeProxySettings(const Aws::Client::ClientConfiguration& clientConfig)
{
if (!clientConfig.proxyHost.empty())
{
Crt::Http::HttpClientConnectionProxyOptions proxyOptions;
if (!clientConfig.proxyUserName.empty())
{
proxyOptions.AuthType = Crt::Http::AwsHttpProxyAuthenticationType::Basic;
proxyOptions.BasicAuthUsername = clientConfig.proxyUserName.c_str();
proxyOptions.BasicAuthPassword = clientConfig.proxyPassword.c_str();
}
proxyOptions.HostName = m_configuration.proxyHost.c_str();
if (clientConfig.proxyPort != 0)
{
proxyOptions.Port = static_cast<uint16_t>(clientConfig.proxyPort);
}
else
{
proxyOptions.Port = clientConfig.proxyScheme == Scheme::HTTPS ? 443 : 80;
}
if (clientConfig.proxyScheme == Scheme::HTTPS)
{
Crt::Io::TlsContextOptions contextOptions = Crt::Io::TlsContextOptions::InitDefaultClient();
if (clientConfig.proxySSLKeyPassword.empty() && !clientConfig.proxySSLCertPath.empty())
{
const char* certPath = clientConfig.proxySSLCertPath.empty() ? nullptr : clientConfig.proxySSLCertPath.c_str();
const char* certFile = clientConfig.proxySSLKeyPath.empty() ? nullptr : clientConfig.proxySSLKeyPath.c_str();
contextOptions = Crt::Io::TlsContextOptions::InitClientWithMtls(certPath, certFile);
}
else if (!clientConfig.proxySSLKeyPassword.empty())
{
const char* pkcs12CertFile = clientConfig.proxySSLKeyPath.empty() ? nullptr : clientConfig.proxySSLKeyPath.c_str();
const char* pkcs12Pwd = clientConfig.proxySSLKeyPassword.c_str();
contextOptions = Crt::Io::TlsContextOptions::InitClientWithMtlsPkcs12(pkcs12CertFile, pkcs12Pwd);
}
if (!m_configuration.proxyCaFile.empty() || !m_configuration.proxyCaPath.empty())
{
const char* caPath = clientConfig.proxyCaPath.empty() ? nullptr : clientConfig.proxyCaPath.c_str();
const char* caFile = clientConfig.proxyCaFile.empty() ? nullptr : clientConfig.proxyCaFile.c_str();
if (!contextOptions.OverrideDefaultTrustStore(caPath, caFile))
{
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Failed to load the proxy trust store, proxyCaPath: \"" << clientConfig.proxyCaPath
<< "\", proxyCaFile: \"" << clientConfig.proxyCaFile << "\": " << aws_error_debug_str(aws_last_error()));
m_bad = true;
}
}
else if (!m_configuration.caFile.empty() || !m_configuration.caPath.empty())
{
const char* caPath = clientConfig.caPath.empty() ? nullptr : clientConfig.caPath.c_str();
const char* caFile = clientConfig.caFile.empty() ? nullptr : clientConfig.caFile.c_str();
if (!contextOptions.OverrideDefaultTrustStore(caPath, caFile))
{
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Failed to load the proxy trust store, caPath: \"" << clientConfig.caPath
<< "\", caFile: \"" << clientConfig.caFile << "\": " << aws_error_debug_str(aws_last_error()));
m_bad = true;
}
}
contextOptions.SetVerifyPeer(clientConfig.verifySSL);
Crt::Io::TlsContext context = Crt::Io::TlsContext(contextOptions, Crt::Io::TlsMode::CLIENT);
if (!context)
{
AWS_LOGSTREAM_ERROR(CRT_HTTP_CLIENT_TAG, "Failed to create the proxy TLS context: "
<< aws_error_debug_str(context.GetInitializationError()));
m_bad = true;
}
proxyOptions.TlsOptions = context.NewConnectionOptions();
}
m_proxyOptions = std::move(proxyOptions);
}
}
Aws::Crt::Optional<Aws::Client::AWSError<Aws::Client::CoreErrors>> CRTHttpClient::AcquireConnection(
const std::shared_ptr<HttpRequest>& request,
const std::function<void(std::shared_ptr<Aws::Http::Connection>, int)>& onClientConnectionAvailable) {
if (m_bad)
{
return MakeCrtClientInitializationError(*request);
}
auto requestConnOptions = CreateConnectionOptionsForRequest(request);
auto connectionManager = GetWithCreateConnectionManagerForRequest(request, requestConnOptions);
if (!connectionManager)
{
return Aws::Client::AWSError<Aws::Client::CoreErrors>{
Aws::Client::CoreErrors::INVALID_PARAMETER_COMBINATION,
"InvalidParameterCombination",
aws_error_debug_str(aws_last_error()),
false
};
}
connectionManager->AcquireConnection(
[onClientConnectionAvailable](std::shared_ptr<Aws::Crt::Http::HttpClientConnection> acquiredConnection,
int errorCode) -> void {
auto crtConnection = Aws::MakeShared<CRTConnection>(CRT_HTTP_CLIENT_TAG, std::move(acquiredConnection));
onClientConnectionAvailable(std::move(crtConnection), errorCode);
});
return {};
}
}
}