-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathwinhttp_connection.cpp
1730 lines (1505 loc) · 63.3 KB
/
winhttp_connection.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 Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include <httpClient/httpProvider.h>
#include "HTTP/httpcall.h"
#include "uri.h"
#include "winhttp_connection.h"
#include <schannel.h>
#if HC_PLATFORM == HC_PLATFORM_GDK
#include <XNetworking.h>
#include <XGameRuntimeFeature.h>
#include <winsock2.h>
#include <iphlpapi.h>
#endif
using namespace xbox::httpclient;
#define CRLF L"\r\n"
#define WINHTTP_WEBSOCKET_RECVBUFFER_INITIAL_SIZE (1024 * 4)
#ifndef WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET
#define WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET 114
#endif
#define SUB_PROTOCOL_HEADER "Sec-WebSocket-Protocol"
NAMESPACE_XBOX_HTTP_CLIENT_BEGIN
WinHttpConnection::WinHttpConnection(
HINTERNET hSession,
HCCallHandle call,
proxy_type proxyType,
XPlatSecurityInformation&& securityInformation
) :
m_hSession{ hSession },
m_call{ call },
m_proxyType{ proxyType },
m_securityInformation{ std::move(securityInformation) },
m_winHttpWebSocketExports{ WinHttpProvider::GetWinHttpWebSocketExports() }
{
}
WinHttpConnection::~WinHttpConnection()
{
HC_TRACE_INFORMATION(HTTPCLIENT, __FUNCTION__);
// We should only ever be destroyed in the Initialized state or Closed state
if (m_state != ConnectionState::Initialized && m_state != ConnectionState::Closed)
{
HC_TRACE_VERBOSE(HTTPCLIENT, "WinHttpConnection destroyed in unexpected state (%lu)", m_state);
}
if (m_state == ConnectionState::WebSocketConnected && m_hRequest && m_winHttpWebSocketExports.close)
{
// Use WinHttpWebSocketClose rather than disconnect in this case to close both the send and receive channels
m_winHttpWebSocketExports.close(m_hRequest, static_cast<USHORT>(HCWebSocketCloseStatus::GoingAway), nullptr, 0);
}
if (m_websocketCall)
{
HCHttpCallCloseHandle(m_websocketCall);
}
if (m_hRequest != nullptr)
{
WinHttpCloseHandle(m_hRequest);
}
if (m_hConnection != nullptr)
{
WinHttpCloseHandle(m_hConnection);
}
}
Result<std::shared_ptr<WinHttpConnection>> WinHttpConnection::Initialize(
HINTERNET hSession,
HCCallHandle call,
proxy_type proxyType,
XPlatSecurityInformation&& securityInformation
)
{
RETURN_HR_IF(E_INVALIDARG, !hSession);
RETURN_HR_IF(E_INVALIDARG, !call);
http_stl_allocator<WinHttpConnection> a{};
auto connection = std::shared_ptr<WinHttpConnection>{ new (a.allocate(1)) WinHttpConnection(hSession, call, proxyType, std::move(securityInformation)), http_alloc_deleter<WinHttpConnection>(), a };
RETURN_IF_FAILED(connection->Initialize());
return connection;
}
#if !HC_NOWEBSOCKETS
Result<std::shared_ptr<WinHttpConnection>> WinHttpConnection::Initialize(
HINTERNET hSession,
HCWebsocketHandle webSocket,
const char* uri,
const char* subprotocol,
proxy_type proxyType,
XPlatSecurityInformation&& securityInformation
)
{
RETURN_HR_IF(E_INVALIDARG, !webSocket);
// For WebSocket connections, create a dummy HCHttpCall so that the rest of the logic can be reused more easily
HCCallHandle webSocketCall{};
RETURN_IF_FAILED(HCHttpCallCreate(&webSocketCall));
RETURN_IF_FAILED(HCHttpCallRequestSetUrl(webSocketCall, "GET", uri));
auto initResult = WinHttpConnection::Initialize(hSession, webSocketCall, proxyType, std::move(securityInformation));
if (FAILED(initResult.hr))
{
HCHttpCallCloseHandle(webSocketCall);
return initResult.hr;
}
else
{
auto& connection{ initResult.Payload() };
connection->m_websocketCall = webSocketCall; // WinHttpConnection now owns webSocketCall
connection->m_websocketHandle = webSocket;
if (subprotocol)
{
connection->m_websocketSubprotocol = subprotocol;
}
return initResult;
}
}
#endif
http_internal_wstring flatten_http_headers(_In_ const HttpHeaders& headers)
{
http_internal_wstring flattened_headers;
bool foundUserAgent = false;
for (const auto& header : headers)
{
auto wHeaderName = utf16_from_utf8(header.first);
if (wHeaderName == L"User-Agent")
{
foundUserAgent = true;
}
flattened_headers.append(wHeaderName);
flattened_headers.push_back(L':');
flattened_headers.append(utf16_from_utf8(header.second));
flattened_headers.append(CRLF);
}
if (!foundUserAgent)
{
flattened_headers.append(L"User-Agent:libHttpClient/1.0.0.0\r\n");
}
return flattened_headers;
}
HRESULT WinHttpConnection::Initialize()
{
try
{
const char* url = nullptr;
const char* method = nullptr;
RETURN_IF_FAILED(HCHttpCallRequestGetUrl(m_call, &method, &url));
m_uri = Uri{ url };
unsigned int port = m_uri.IsPortDefault() ? (m_uri.IsSecure() ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT) : m_uri.Port();
http_internal_wstring wUrlHost = utf16_from_utf8(m_uri.Host());
m_hConnection = WinHttpConnect(
m_hSession,
wUrlHost.c_str(),
(INTERNET_PORT)port,
0);
if (m_hConnection == nullptr)
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WinHttpConnect errorcode %d", TO_ULL(HCHttpCallGetId(m_call)), GetCurrentThreadId(), dwError);
return HRESULT_FROM_WIN32(dwError);
}
// Need to form uri path, query, and fragment for this request.
http_internal_wstring wEncodedResource = utf16_from_utf8(m_uri.Resource());
http_internal_wstring wMethod = utf16_from_utf8(method);
// Open the request.
m_hRequest = WinHttpOpenRequest(
m_hConnection,
wMethod.c_str(),
wEncodedResource.c_str(),
nullptr,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_ESCAPE_DISABLE | (m_uri.IsSecure() ? WINHTTP_FLAG_SECURE : 0));
if (m_hRequest == nullptr)
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WinHttpOpenRequest errorcode %d", TO_ULL(HCHttpCallGetId(m_call)), GetCurrentThreadId(), dwError);
return HRESULT_FROM_WIN32(dwError);
}
uint32_t timeoutInSeconds = 0;
RETURN_IF_FAILED(HCHttpCallRequestGetTimeout(m_call, &timeoutInSeconds));
int timeoutInMilliseconds = static_cast<int>(timeoutInSeconds * 1000);
if (!WinHttpSetTimeouts(
m_hSession,
timeoutInMilliseconds,
timeoutInMilliseconds,
timeoutInMilliseconds,
timeoutInMilliseconds))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WinHttpSetTimeouts errorcode %d", TO_ULL(HCHttpCallGetId(m_call)), GetCurrentThreadId(), dwError);
return HRESULT_FROM_WIN32(dwError);
}
#if HC_PLATFORM_IS_MICROSOFT && (HC_PLATFORM != HC_PLATFORM_UWP) && (HC_PLATFORM != HC_PLATFORM_XDK)
if (!m_call->sslValidation)
{
DWORD dwOption = SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
if (!WinHttpSetOption(
m_hRequest,
WINHTTP_OPTION_SECURITY_FLAGS,
&dwOption,
sizeof(dwOption)))
{
DWORD dwError = GetLastError();
HC_TRACE_WARNING(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WinHttpSetOption errorcode %d", HCHttpCallGetId(m_call), GetCurrentThreadId(), dwError);
}
}
#endif
#if HC_PLATFORM != HC_PLATFORM_GDK
if (m_proxyType == proxy_type::autodiscover_proxy)
{
RETURN_IF_FAILED(set_autodiscover_proxy());
}
#endif
HCHttpCallRequestBodyReadFunction requestBodyReadFunction{ nullptr };
void* context{ nullptr };
RETURN_IF_FAILED(HCHttpCallRequestGetRequestBodyReadFunction(m_call, &requestBodyReadFunction, &m_requestBodySize, &context));
if (m_requestBodySize > 0)
{
// While we won't be transfer-encoding the data, we will write it in portions.
m_requestBodyType = msg_body_type::content_length_chunked;
m_requestBodyRemainingToWrite = m_requestBodySize;
}
else
{
m_requestBodyType = msg_body_type::no_body;
m_requestBodyRemainingToWrite = 0;
}
uint32_t numHeaders = 0;
RETURN_IF_FAILED(HCHttpCallRequestGetNumHeaders(m_call, &numHeaders));
if (numHeaders > 0)
{
http_internal_wstring flattenedHeaders = flatten_http_headers(m_call->requestHeaders);
if (!WinHttpAddRequestHeaders(
m_hRequest,
flattenedHeaders.c_str(),
static_cast<DWORD>(flattenedHeaders.length()),
WINHTTP_ADDREQ_FLAG_ADD))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WinHttpAddRequestHeaders errorcode %d", TO_ULL(HCHttpCallGetId(m_call)), GetCurrentThreadId(), dwError);
return HRESULT_FROM_WIN32(dwError);
}
}
if (m_uri.IsSecure())
{
if (!WinHttpSetOption(
m_hRequest,
WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
WINHTTP_NO_CLIENT_CERT_CONTEXT,
0))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WinHttpSetOption errorcode %d", TO_ULL(HCHttpCallGetId(m_call)), GetCurrentThreadId(), dwError);
return HRESULT_FROM_WIN32(dwError);
}
}
}
catch (std::bad_alloc const& e)
{
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [%d] std::bad_alloc: %s", E_OUTOFMEMORY, e.what());
return E_OUTOFMEMORY;
}
catch (...)
{
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [%d] unknown exception", E_FAIL);
return E_FAIL;
}
return S_OK;
}
HRESULT WinHttpConnection::HttpCallPerformAsync(XAsyncBlock* async)
{
RETURN_HR_IF(E_INVALIDARG, !async);
m_asyncBlock = async;
SendRequest();
return S_OK;
}
#if !HC_NOWEBSOCKETS
HRESULT WinHttpConnection::WebSocketConnectAsync(XAsyncBlock* async)
{
RETURN_HR_IF(E_INVALIDARG, !async);
// Set WebSocket specific options and then call send
auto headers{ m_websocketHandle->websocket->Headers() };
// Add subprotocol header manually
if (headers.find(SUB_PROTOCOL_HEADER) == headers.end() && !m_websocketSubprotocol.empty())
{
headers[SUB_PROTOCOL_HEADER] = m_websocketSubprotocol;
}
if (!headers.empty())
{
http_internal_wstring flattenedHeaders = flatten_http_headers(headers);
if (!WinHttpAddRequestHeaders(
m_hRequest,
flattenedHeaders.c_str(),
static_cast<DWORD>(flattenedHeaders.length()),
WINHTTP_ADDREQ_FLAG_ADD))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "winhttp_http_task [ID %llu] [TID %ul] WinHttpAddRequestHeaders errorcode %d", TO_ULL(HCHttpCallGetId(m_call)), GetCurrentThreadId(), dwError);
return HRESULT_FROM_WIN32(dwError);
}
}
// Request protocol upgrade from http to websocket.
#pragma warning(push)
#pragma warning(disable : 6387) // WinHttpSetOption's SAL doesn't understand WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET
bool status = WinHttpSetOption(m_hRequest, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, nullptr, 0);
if (!status)
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "winhttp_http_task [ID %llu] [TID %ul] WinHttpAddRequestHeaders errorcode %d", TO_ULL(HCHttpCallGetId(m_call)), GetCurrentThreadId(), dwError);
return HRESULT_FROM_WIN32(dwError);
}
#pragma warning(pop)
m_asyncBlock = async;
// Unlike HTTP, WebSocket providers need to implement the XAsyncProvider for each operation
RETURN_IF_FAILED(XAsyncBegin(async, this, HCWebSocketConnectAsync, "HCWebSocketConnectAsync", WinHttpConnection::WebSocketConnectProvider));
return S_OK;
}
HRESULT WinHttpConnection::WebSocketSendMessageAsync(XAsyncBlock* async, const char* message)
{
return WebSocketSendMessageAsync(async, (const uint8_t*)message, strlen(message), WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE);
}
HRESULT WinHttpConnection::WebSocketSendMessageAsync(XAsyncBlock* async, const uint8_t* payloadBytes, size_t payloadSize, WINHTTP_WEB_SOCKET_BUFFER_TYPE payloadType)
{
auto sendContext = http_allocate_unique<WebSocketSendContext>();
sendContext->async = async;
sendContext->connection = this;
sendContext->socket = m_websocketHandle; // Store socket handle because 'connection' may be invalid in WebSocketSendProvider GetResult
sendContext->payload = http_internal_vector<uint8_t>(payloadBytes, payloadBytes + payloadSize);
sendContext->payloadType = payloadType;
RETURN_IF_FAILED(XAsyncBegin(async, sendContext.get(), HCWebSocketSendMessageAsync, "HCWebSocketSendMessageAsync", WinHttpConnection::WebSocketSendProvider));
// At this point WebSocketSendProvider is responsible for lifetime of sendContext
sendContext.release();
return S_OK;
}
HRESULT WinHttpConnection::WebSocketDisconnect(_In_ HCWebSocketCloseStatus closeStatus)
{
assert(m_winHttpWebSocketExports.shutdown);
{
win32_cs_autolock autoCriticalSection(&m_lock);
m_state = ConnectionState::WebSocketClosing;
}
// Shutdown closes the send channel after sending a close frame. When we receive a close frame we are fully disconnected
DWORD dwError = m_winHttpWebSocketExports.shutdown(m_hRequest, static_cast<short>(closeStatus), nullptr, 0);
return HRESULT_FROM_WIN32(dwError);
}
#endif
HRESULT WinHttpConnection::Close(ConnectionClosedCallback callback)
{
bool doWinHttpClose = false;
bool closeComplete = false;
{
win32_cs_autolock autoCriticalSection(&m_lock);
if (m_connectionClosedCallback)
{
// WinHttpProvider shouldn't close connection more than once
assert(!m_connectionClosedCallback);
return E_UNEXPECTED;
}
m_connectionClosedCallback = std::move(callback);
switch (m_state)
{
case ConnectionState::WebSocketConnected:
{
doWinHttpClose = true;
HC_TRACE_VERBOSE(HTTPCLIENT, "WinHttpConnection::Close: ConnectionState=WebSocketConnected, Closing WinHttp handle");
break;
}
case ConnectionState::WebSocketClosing:
{
// Nothing to do. WinHttpClose will happen after websocket close completes
return S_OK;
}
case ConnectionState::WinHttpClosing:
{
// Nothing to do
return S_OK;
}
case ConnectionState::Closed:
{
closeComplete = true;
break;
}
default:
{
doWinHttpClose = true;
break;
}
}
}
if (doWinHttpClose)
{
StartWinHttpClose();
}
else if (closeComplete)
{
m_connectionClosedCallback();
}
return S_OK;
}
void WinHttpConnection::complete_task(_In_ HRESULT translatedHR)
{
complete_task(translatedHR, translatedHR);
}
// complete_task is used to complete the XAsync operation associated with either the HttpCallPerformAsync call (for pure HTTP WinHttpConnections)
// or the WebSocketConnectAsync call (for WebSocket WinHttpConnections). In either case, XAsyncComplete should be called
// exactly once. We reset m_asyncBlock after completing it so it doesn't get completed again.
void WinHttpConnection::complete_task(_In_ HRESULT translatedHR, uint32_t platformSpecificError)
{
if (m_asyncBlock != nullptr)
{
// WebSocket Connect XAyncProvider will pull connect result from m_call
HCHttpCallResponseSetNetworkErrorCode(m_call, translatedHR, platformSpecificError);
size_t resultSize{ 0 };
#if !HC_NOWEBSOCKETS
if (m_websocketHandle)
{
resultSize = sizeof(WebSocketCompletionResult);
}
#endif
XAsyncComplete(m_asyncBlock, S_OK, resultSize);
m_asyncBlock = nullptr;
}
else
{
// This case can happen if WinHttp reports multiple errors for the same request. We will just complete the operation with the first
// reported error and ignore subsequent ones
HC_TRACE_VERBOSE(HTTPCLIENT, "WinHttpConnection::complete_task unexpectedly called multiple times. Ignoring subsequent call.");
}
// If this is an HTTP request, we can always start WinHttp cleanup at this point.
// If this is a WebSocket connection, we can start cleanup only if the connect failed. If the connect succeeded,
// WinHttp cleanup won't happen until the WebSocket is disconnected.
if (!m_websocketHandle || FAILED(translatedHR))
{
StartWinHttpClose();
}
}
// Helper function to query/read next part of response data from winhttp.
void WinHttpConnection::read_next_response_chunk(_In_ WinHttpConnection* pRequestContext, DWORD /*bytesRead*/)
{
if (!WinHttpQueryDataAvailable(pRequestContext->m_hRequest, nullptr))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WinHttpQueryDataAvailable errorcode %d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), dwError);
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(dwError));
}
}
void WinHttpConnection::_multiple_segment_write_data(_In_ WinHttpConnection* pRequestContext)
{
const size_t defaultChunkSize = 64 * 1024;
size_t safeSize = std::min(pRequestContext->m_requestBodyRemainingToWrite, defaultChunkSize);
HCHttpCallRequestBodyReadFunction readFunction = nullptr;
size_t bodySize = 0;
void* context = nullptr;
HRESULT hr = HCHttpCallRequestGetRequestBodyReadFunction(pRequestContext->m_call, &readFunction, &bodySize, &context);
if (FAILED(hr))
{
pRequestContext->complete_task(hr);
return;
}
if (readFunction == nullptr) {
pRequestContext->complete_task(E_UNEXPECTED);
return;
}
size_t bytesWritten = 0;
try
{
pRequestContext->m_requestBuffer.resize(safeSize);
hr = readFunction(pRequestContext->m_call, pRequestContext->m_requestBodyOffset, safeSize, context, pRequestContext->m_requestBuffer.data(), &bytesWritten);
if (FAILED(hr))
{
pRequestContext->complete_task(hr);
return;
}
}
catch (...)
{
pRequestContext->complete_task(E_FAIL, static_cast<uint32_t>(E_FAIL));
return;
}
if( !WinHttpWriteData(
pRequestContext->m_hRequest,
pRequestContext->m_requestBuffer.data(),
static_cast<DWORD>(bytesWritten),
nullptr))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WinHttpWriteData errorcode %d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), dwError);
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(dwError));
return;
}
// Stop writing chunks after this one if no more data.
pRequestContext->m_requestBodyRemainingToWrite -= bytesWritten;
if (pRequestContext->m_requestBodyRemainingToWrite == 0)
{
pRequestContext->m_requestBodyType = msg_body_type::no_body;
}
pRequestContext->m_requestBodyOffset += bytesWritten;
}
void WinHttpConnection::callback_status_write_complete(
_In_ HINTERNET hRequestHandle,
_In_ WinHttpConnection* pRequestContext,
_In_ void* statusInfo)
{
{
win32_cs_autolock autoCriticalSection(&pRequestContext->m_lock);
DWORD bytesWritten = *((DWORD *)statusInfo);
HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE bytesWritten=%d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), bytesWritten);
UNREFERENCED_LOCAL(bytesWritten);
if (pRequestContext->m_requestBodyType == content_length_chunked)
{
_multiple_segment_write_data(pRequestContext);
return;
}
}
if (!WinHttpReceiveResponse(hRequestHandle, nullptr))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WinHttpReceiveResponse errorcode %d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), dwError);
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(dwError));
return;
}
}
void WinHttpConnection::callback_websocket_status_write_complete(WinHttpConnection* connection)
{
#if !HC_NOWEBSOCKETS
WebSocketSendContext* nextSendContext{ nullptr };
WebSocketSendContext* completedSendContext{ nullptr };
{
std::lock_guard<std::recursive_mutex> lock{ connection->m_websocketSendMutex };
assert(!connection->m_websocketSendQueue.empty());
completedSendContext = connection->m_websocketSendQueue.front();
connection->m_websocketSendQueue.pop();
if (!connection->m_websocketSendQueue.empty())
{
nextSendContext = connection->m_websocketSendQueue.front();
}
}
assert(completedSendContext);
XAsyncComplete(completedSendContext->async, S_OK, sizeof(WebSocketCompletionResult));
if (nextSendContext)
{
connection->WebSocketSendMessage(*nextSendContext);
}
#else
UNREFERENCED_PARAMETER(connection);
assert(false);
#endif
}
void WinHttpConnection::callback_status_request_error(
_In_ HINTERNET hRequestHandle,
_In_ WinHttpConnection* pRequestContext,
_In_ void* statusInfo)
{
WINHTTP_ASYNC_RESULT *error_result = reinterpret_cast<WINHTTP_ASYNC_RESULT *>(statusInfo);
if (error_result == nullptr)
return;
DWORD errorCode = error_result->dwError;
HC_TRACE_ERROR(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WINHTTP_CALLBACK_STATUS_REQUEST_ERROR dwResult=%llu dwError=%u", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), error_result->dwResult, error_result->dwError);
bool reissueSend{ false };
if (error_result->dwError == ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED)
{
SecPkgContext_IssuerListInfoEx* pIssuerList{ nullptr };
DWORD dwBufferSize{ sizeof(void*) };
if (WinHttpQueryOption(
hRequestHandle,
WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST,
&pIssuerList,
&dwBufferSize
))
{
PCERT_CONTEXT pClientCert{ nullptr };
PCCERT_CHAIN_CONTEXT pClientCertChain{ nullptr };
CERT_CHAIN_FIND_BY_ISSUER_PARA searchCriteria{};
searchCriteria.cbSize = sizeof(CERT_CHAIN_FIND_BY_ISSUER_PARA);
searchCriteria.cIssuer = pIssuerList->cIssuers;
searchCriteria.rgIssuer = pIssuerList->aIssuers;
HCERTSTORE hCertStore = CertOpenSystemStore(0, L"MY");
if (hCertStore)
{
pClientCertChain = CertFindChainInStore(
hCertStore,
X509_ASN_ENCODING,
CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG | CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG,
CERT_CHAIN_FIND_BY_ISSUER,
&searchCriteria,
nullptr
);
if (pClientCertChain)
{
pClientCert = (PCERT_CONTEXT)pClientCertChain->rgpChain[0]->rgpElement[0]->pCertContext;
// "!!" to cast from BOOL to bool
reissueSend = !!WinHttpSetOption(
hRequestHandle,
WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
(LPVOID)pClientCert,
sizeof(CERT_CONTEXT)
);
CertFreeCertificateChain(pClientCertChain);
}
CertCloseStore(hCertStore, 0);
}
GlobalFree(pIssuerList);
}
else
{
auto certError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "WinHttp returned ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED but unable to get cert issuer list, dwError=%d", certError);
}
}
// Reissue the send if we were able to address a Cert error. All other errors are considered fatal.
// Handle appropriately depending on if this is a WebSocket or Http request
if (reissueSend)
{
pRequestContext->SendRequest();
}
else if (pRequestContext->m_websocketHandle)
{
// If the WebSocket was connected (or previously connected) the error is treated as a disconnection.
// If it hasn't yet been invoked, the client's disconnect handler will be invoked with the error. If the WebSocket wasn't yet
// connected, complete the connect operation with the error
bool disconnect{ false };
{
win32_cs_autolock autoCriticalSection(&pRequestContext->m_lock);
if (pRequestContext->m_state == ConnectionState::WebSocketConnected || pRequestContext->m_state == ConnectionState::WebSocketClosing)
{
HC_TRACE_VERBOSE(HTTPCLIENT, "WinHttpConnection::callback_status_request_error after WebSocket was connected, moving to disconnect flow.");
disconnect = true;
}
else if (pRequestContext->m_state == ConnectionState::WinHttpClosing)
{
HC_TRACE_VERBOSE(HTTPCLIENT, "WinHttpConnection::callback_status_request_error during WinHttpCloseHandle was connected, moving to disconnect flow.");
disconnect = true;
}
}
if (disconnect)
{
pRequestContext->on_websocket_disconnected(static_cast<USHORT>(errorCode));
}
else
{
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(errorCode));
}
}
else
{
// For Http requests, complete with error
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(errorCode));
}
}
#if HC_PLATFORM == HC_PLATFORM_GDK
void WinHttpConnection::callback_status_sending_request(
_In_ HINTERNET hRequestHandle,
_In_ WinHttpConnection* pRequestContext,
_In_ void* /*statusInfo*/)
{
if (hRequestHandle != nullptr)
{
HRESULT hr = XNetworkingVerifyServerCertificate(hRequestHandle, pRequestContext->m_securityInformation.securityInformation);
if (FAILED(hr))
{
win32_cs_autolock autoCriticalSection(&pRequestContext->m_lock);
pRequestContext->complete_task(hr, hr);
// Set the failure and complete the web request before calling WinHttpCloseHandle because the
// WinHttpCloseHandle call can cause a synchronous callback indicating the request has been canceled
// which would complete the web request with the wrong error.
(void)WinHttpCloseHandle(hRequestHandle);
pRequestContext->m_hRequest = nullptr;
}
}
}
#endif
void WinHttpConnection::callback_status_sendrequest_complete(
_In_ HINTERNET hRequestHandle,
_In_ WinHttpConnection* pRequestContext,
_In_ void* /*statusInfo*/)
{
{
win32_cs_autolock autoCriticalSection(&pRequestContext->m_lock);
HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId());
if (pRequestContext->m_requestBodyType == content_length_chunked)
{
_multiple_segment_write_data(pRequestContext);
return;
}
}
if (!WinHttpReceiveResponse(hRequestHandle, nullptr))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WinHttpReceiveResponse errorcode %d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), dwError);
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(dwError));
return;
}
}
HRESULT WinHttpConnection::query_header_length(
_In_ HCCallHandle call,
_In_ HINTERNET hRequestHandle,
_In_ DWORD header,
_Out_ DWORD* pLength)
{
*pLength = 0;
if (!WinHttpQueryHeaders(
hRequestHandle,
header,
WINHTTP_HEADER_NAME_BY_INDEX,
WINHTTP_NO_OUTPUT_BUFFER,
pLength,
WINHTTP_NO_HEADER_INDEX))
{
DWORD dwError = GetLastError();
if (dwError != ERROR_INSUFFICIENT_BUFFER)
{
HC_TRACE_ERROR(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WinHttpQueryHeaders errorcode %d", TO_ULL(HCHttpCallGetId(call)), GetCurrentThreadId(), dwError);
return E_FAIL;
}
}
return S_OK;
}
uint32_t WinHttpConnection::parse_status_code(
_In_ HCCallHandle call,
_In_ HINTERNET hRequestHandle,
_In_ WinHttpConnection* pRequestContext
)
{
DWORD length = 0;
HRESULT hr = query_header_length(pRequestContext->m_call, hRequestHandle, WINHTTP_QUERY_STATUS_CODE, &length);
if (FAILED(hr))
{
pRequestContext->complete_task(E_FAIL, hr);
return 0;
}
http_internal_wstring buffer;
buffer.resize(length);
if (!WinHttpQueryHeaders(
hRequestHandle,
WINHTTP_QUERY_STATUS_CODE,
WINHTTP_HEADER_NAME_BY_INDEX,
&buffer[0],
&length,
WINHTTP_NO_HEADER_INDEX))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "HCHttpCallPerform [ID %llu] [TID %ul] WinHttpQueryHeaders errorcode %d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), dwError);
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(dwError));
return 0;
}
uint32_t statusCode = static_cast<uint32_t>(_wtoi(buffer.c_str()));
HCHttpCallResponseSetStatusCode(call, statusCode);
return statusCode;
}
void WinHttpConnection::parse_headers_string(
_In_ HCCallHandle call,
_In_z_ wchar_t* headersStr)
{
wchar_t* context = nullptr;
wchar_t* line = wcstok_s(headersStr, CRLF, &context);
while (line != nullptr)
{
http_internal_wstring header_line(line);
const size_t colonIndex = header_line.find_first_of(L":");
if (colonIndex != http_internal_wstring::npos)
{
http_internal_wstring key = header_line.substr(0, colonIndex);
http_internal_wstring value = header_line.substr(colonIndex + 1, header_line.length() - colonIndex - 1);
trim_whitespace(key);
trim_whitespace(value);
http_internal_string aKey = utf8_from_utf16(key);
http_internal_string aValue = utf8_from_utf16(value);
HCHttpCallResponseSetHeader(call, aKey.c_str(), aValue.c_str());
}
line = wcstok_s(nullptr, CRLF, &context);
}
}
void WinHttpConnection::callback_status_headers_available(
_In_ HINTERNET hRequestHandle,
_In_ WinHttpConnection* pRequestContext,
_In_ void* /*statusInfo*/)
{
HC_TRACE_INFORMATION(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId() );
// First need to query to see what the headers size is.
DWORD headerBufferLength = 0;
HRESULT hr = query_header_length(pRequestContext->m_call, hRequestHandle, WINHTTP_QUERY_RAW_HEADERS_CRLF, &headerBufferLength);
if (FAILED(hr))
{
pRequestContext->complete_task(E_FAIL, hr);
return;
}
// Now allocate buffer for headers and query for them.
http_internal_vector<unsigned char> header_raw_buffer;
header_raw_buffer.resize(headerBufferLength);
wchar_t* headerBuffer = reinterpret_cast<wchar_t*>(&header_raw_buffer[0]);
if (!WinHttpQueryHeaders(
hRequestHandle,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
headerBuffer,
&headerBufferLength,
WINHTTP_NO_HEADER_INDEX))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WinHttpQueryHeaders errorcode %d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), dwError);
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(dwError));
return;
}
parse_status_code(pRequestContext->m_call, hRequestHandle, pRequestContext);
parse_headers_string(pRequestContext->m_call, headerBuffer);
read_next_response_chunk(pRequestContext, 0);
}
void WinHttpConnection::callback_status_data_available(
_In_ HINTERNET hRequestHandle,
_In_ WinHttpConnection* pRequestContext,
_In_ void* statusInfo)
{
pRequestContext->m_lock.lock();
// Status information contains pointer to DWORD containing number of bytes available.
DWORD newBytesAvailable = *(PDWORD)statusInfo;
HC_TRACE_INFORMATION(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE newBytesAvailable=%d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), newBytesAvailable);
// Flush response buffer from previous call to WinHttpReadData
if (pRequestContext->m_responseBuffer.size())
{
HRESULT hr = flush_response_buffer(pRequestContext);
if (FAILED(hr)) {
pRequestContext->m_lock.unlock();
pRequestContext->complete_task(hr);
return;
}
}
// Read new data into buffer
if (newBytesAvailable > 0)
{
pRequestContext->m_responseBuffer.resize(newBytesAvailable);
// Read in body all at once.
if (!WinHttpReadData(
hRequestHandle,
pRequestContext->m_responseBuffer.data(),
newBytesAvailable,
nullptr))
{
DWORD dwError = GetLastError();
HC_TRACE_ERROR(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WinHttpReadData errorcode %d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), GetLastError());
pRequestContext->m_lock.unlock();
pRequestContext->complete_task(E_FAIL, HRESULT_FROM_WIN32(dwError));
return;
}
pRequestContext->m_lock.unlock();
}
else
{
pRequestContext->m_lock.unlock();
// No more data available
pRequestContext->complete_task(S_OK);
}
}
void WinHttpConnection::callback_status_read_complete(
_In_ HINTERNET /*hRequestHandle*/,
_In_ WinHttpConnection* pRequestContext,
_In_ DWORD statusInfoLength)
{
// Status information length contains the number of bytes read.
const DWORD bytesRead = statusInfoLength;
HC_TRACE_INFORMATION(HTTPCLIENT, "WinHttpConnection [ID %llu] [TID %ul] WINHTTP_CALLBACK_STATUS_READ_COMPLETE bytesRead=%d", TO_ULL(HCHttpCallGetId(pRequestContext->m_call)), GetCurrentThreadId(), bytesRead);
// If no bytes have been read, then this is the end of the response.
if (bytesRead == 0)
{
HRESULT hr = S_OK;
{
win32_cs_autolock autoCriticalSection(&pRequestContext->m_lock);
// Flush remaining buffered data
hr = flush_response_buffer(pRequestContext);
}
pRequestContext->complete_task(hr);
}
else
{
read_next_response_chunk(pRequestContext, bytesRead);
}
}
HRESULT WinHttpConnection::flush_response_buffer(