This repository was archived by the owner on Jun 14, 2024. It is now read-only.
forked from microsoft/cpprestsdk
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhttp_client_winhttp.cpp
More file actions
1564 lines (1375 loc) · 60.5 KB
/
http_client_winhttp.cpp
File metadata and controls
1564 lines (1375 loc) · 60.5 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
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 the implementation for Windows Desktop, based on WinHTTP.
*
* For the latest on this and related APIs, please see: https://github.com/Microsoft/cpprestsdk
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
#include "cpprest/http_headers.h"
#include "http_client_impl.h"
#ifndef CPPREST_TARGET_XP
#include <VersionHelpers.h>
#endif
#undef min
#undef max
namespace web
{
namespace http
{
namespace client
{
namespace details
{
// Helper function to query for the size of header values.
static void query_header_length(HINTERNET request_handle, DWORD header, DWORD &length)
{
WinHttpQueryHeaders(
request_handle,
header,
WINHTTP_HEADER_NAME_BY_INDEX,
WINHTTP_NO_OUTPUT_BUFFER,
&length,
WINHTTP_NO_HEADER_INDEX);
}
// Helper function to get the status code from a WinHTTP response.
static http::status_code parse_status_code(HINTERNET request_handle)
{
DWORD length = 0;
query_header_length(request_handle, WINHTTP_QUERY_STATUS_CODE, length);
utility::string_t buffer;
buffer.resize(length);
WinHttpQueryHeaders(
request_handle,
WINHTTP_QUERY_STATUS_CODE,
WINHTTP_HEADER_NAME_BY_INDEX,
&buffer[0],
&length,
WINHTTP_NO_HEADER_INDEX);
return (unsigned short)_wtoi(buffer.c_str());
}
// Helper function to trim leading and trailing null characters from a string.
static void trim_nulls(utility::string_t &str)
{
size_t index;
for (index = 0; index < str.size() && str[index] == 0; ++index);
str.erase(0, index);
for (index = str.size(); index > 0 && str[index - 1] == 0; --index);
str.erase(index);
}
// Helper function to get the reason phrase from a WinHTTP response.
static utility::string_t parse_reason_phrase(HINTERNET request_handle)
{
utility::string_t phrase;
DWORD length = 0;
query_header_length(request_handle, WINHTTP_QUERY_STATUS_TEXT, length);
phrase.resize(length);
WinHttpQueryHeaders(
request_handle,
WINHTTP_QUERY_STATUS_TEXT,
WINHTTP_HEADER_NAME_BY_INDEX,
&phrase[0],
&length,
WINHTTP_NO_HEADER_INDEX);
// WinHTTP reports back the wrong length, trim any null characters.
trim_nulls(phrase);
return phrase;
}
/// <summary>
/// Parses a string containing HTTP headers.
/// </summary>
static void parse_winhttp_headers(HINTERNET request_handle, _In_z_ utf16char *headersStr, http_response &response)
{
//Clear the header map for each new response; otherwise, the header values will be combined.
response.headers().clear();
// Status code and reason phrase.
response.set_status_code(parse_status_code(request_handle));
response.set_reason_phrase(parse_reason_phrase(request_handle));
web::http::details::parse_headers_string(headersStr, response.headers());
}
// Helper function to build error messages.
static std::string build_error_msg(unsigned long code, const std::string &location)
{
std::string msg(location);
msg.append(": ");
msg.append(std::to_string(code));
msg.append(": ");
msg.append(utility::details::windows_category().message(code));
return msg;
}
// Helper function to build an error message from a WinHTTP async result.
static std::string build_error_msg(_In_ WINHTTP_ASYNC_RESULT *error_result)
{
switch(error_result->dwResult)
{
case API_RECEIVE_RESPONSE:
return build_error_msg(error_result->dwError, "WinHttpReceiveResponse");
case API_QUERY_DATA_AVAILABLE:
return build_error_msg(error_result->dwError, "WinHttpQueryDataAvaliable");
case API_READ_DATA:
return build_error_msg(error_result->dwError, "WinHttpReadData");
case API_WRITE_DATA:
return build_error_msg(error_result->dwError, "WinHttpWriteData");
case API_SEND_REQUEST:
return build_error_msg(error_result->dwError, "WinHttpSendRequest");
default:
return build_error_msg(error_result->dwError, "Unknown WinHTTP Function");
}
}
class memory_holder
{
uint8_t* m_externalData;
std::vector<uint8_t> m_internalData;
public:
memory_holder() : m_externalData(nullptr)
{
}
void allocate_space(size_t length)
{
if (length > m_internalData.size())
{
m_internalData.resize(length);
}
m_externalData = nullptr;
}
inline void reassign_to(_In_opt_ uint8_t *block)
{
assert(block != nullptr);
m_externalData = block;
}
inline bool is_internally_allocated() const
{
return m_externalData == nullptr;
}
inline uint8_t* get()
{
return is_internally_allocated() ? &m_internalData[0] : m_externalData ;
}
};
// Possible ways a message body can be sent/received.
enum msg_body_type
{
no_body,
content_length_chunked,
transfer_encoding_chunked
};
// Additional information necessary to track a WinHTTP request.
class winhttp_request_context : public request_context
{
public:
// Factory function to create requests on the heap.
static std::shared_ptr<request_context> create_request_context(const std::shared_ptr<_http_client_communicator> &client, const http_request &request)
{
std::shared_ptr<winhttp_request_context> ret(new winhttp_request_context(client, request));
ret->m_self_reference = ret;
return std::move(ret);
}
~winhttp_request_context()
{
cleanup();
}
void allocate_request_space(_In_opt_ uint8_t *block, size_t length)
{
if (block == nullptr)
m_body_data.allocate_space(length);
else
m_body_data.reassign_to(block);
}
void allocate_reply_space(_In_opt_ uint8_t *block, size_t length)
{
if (block == nullptr)
m_body_data.allocate_space(length);
else
m_body_data.reassign_to(block);
}
bool is_externally_allocated() const
{
return !m_body_data.is_internally_allocated();
}
HINTERNET m_request_handle;
std::weak_ptr<winhttp_request_context>* m_request_context;
bool m_proxy_authentication_tried;
bool m_server_authentication_tried;
msg_body_type m_bodyType;
utility::size64_t m_remaining_to_write;
std::char_traits<uint8_t>::pos_type m_startingPosition;
// If the user specified that to guarantee data buffering of request data, in case of challenged authentication requests, etc...
// Then if the request stream buffer doesn't support seeking we need to copy the body chunks as it is sent.
concurrency::streams::istream m_readStream;
std::unique_ptr<concurrency::streams::container_buffer<std::vector<uint8_t>>> m_readBufferCopy;
virtual concurrency::streams::streambuf<uint8_t> _get_readbuffer()
{
return m_readStream.streambuf();
}
// This self reference will keep us alive until finish() is called.
std::shared_ptr<winhttp_request_context> m_self_reference;
memory_holder m_body_data;
std::unique_ptr<web::http::details::compression::stream_decompressor> decompressor;
virtual void cleanup()
{
if(m_request_handle != nullptr)
{
auto tmp_handle = m_request_handle;
m_request_handle = nullptr;
WinHttpCloseHandle(tmp_handle);
}
}
protected:
virtual void finish()
{
request_context::finish();
assert(m_self_reference != nullptr);
auto dereference_self = std::move(m_self_reference);
// As the stack frame cleans up, this will be deleted if no other references exist.
}
private:
// Can only create on the heap using factory function.
winhttp_request_context(const std::shared_ptr<_http_client_communicator> &client, const http_request &request)
: request_context(client, request),
m_request_handle(nullptr),
m_request_context(nullptr),
m_bodyType(no_body),
m_startingPosition(std::char_traits<uint8_t>::eof()),
m_body_data(),
m_remaining_to_write(0),
m_proxy_authentication_tried(false),
m_server_authentication_tried(false),
m_readStream(request.body())
{
}
};
static DWORD ChooseAuthScheme( DWORD dwSupportedSchemes )
{
// It is the server's responsibility only to accept
// authentication schemes that provide a sufficient
// level of security to protect the servers resources.
//
// The client is also obligated only to use an authentication
// scheme that adequately protects its username and password.
//
if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_NEGOTIATE )
return WINHTTP_AUTH_SCHEME_NEGOTIATE;
else if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_NTLM )
return WINHTTP_AUTH_SCHEME_NTLM;
else if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_PASSPORT )
return WINHTTP_AUTH_SCHEME_PASSPORT;
else if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_DIGEST )
return WINHTTP_AUTH_SCHEME_DIGEST;
else if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_BASIC )
return WINHTTP_AUTH_SCHEME_BASIC;
else
return 0;
}
// Small RAII helper to ensure that the fields of this struct are always
// properly freed.
struct proxy_info : WINHTTP_PROXY_INFO
{
proxy_info()
{
memset( this, 0, sizeof(WINHTTP_PROXY_INFO) );
}
~proxy_info()
{
if ( lpszProxy )
::GlobalFree(lpszProxy);
if ( lpszProxyBypass )
::GlobalFree(lpszProxyBypass);
}
};
struct ie_proxy_config : WINHTTP_CURRENT_USER_IE_PROXY_CONFIG
{
ie_proxy_config()
{
memset( this, 0, sizeof(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG) );
}
~ie_proxy_config()
{
if ( lpszAutoConfigUrl )
::GlobalFree(lpszAutoConfigUrl);
if ( lpszProxy )
::GlobalFree(lpszProxy);
if ( lpszProxyBypass )
::GlobalFree(lpszProxyBypass);
}
};
// WinHTTP client.
class winhttp_client : public _http_client_communicator
{
public:
winhttp_client(http::uri address, http_client_config client_config)
: _http_client_communicator(std::move(address), std::move(client_config))
, m_secure(m_uri.scheme() == _XPLATSTR("https"))
, m_hSession(nullptr)
, m_hConnection(nullptr) { }
winhttp_client(const winhttp_client&) = delete;
winhttp_client &operator=(const winhttp_client&) = delete;
// Closes session.
~winhttp_client()
{
if(m_hConnection != nullptr)
{
WinHttpCloseHandle(m_hConnection);
}
if(m_hSession != nullptr)
{
// Unregister the callback.
WinHttpSetStatusCallback(
m_hSession,
nullptr,
WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,
NULL);
WinHttpCloseHandle(m_hSession);
}
}
virtual pplx::task<http_response> propagate(http_request request) override
{
auto self = std::static_pointer_cast<_http_client_communicator>(shared_from_this());
auto context = details::winhttp_request_context::create_request_context(self, request);
// Use a task to externally signal the final result and completion of the task.
auto result_task = pplx::create_task(context->m_request_completion);
// Asynchronously send the response with the HTTP client implementation.
this->async_send_request(context);
return result_task;
}
protected:
unsigned long report_failure(const utility::string_t& errorMessage)
{
// Should we log?
CASABLANCA_UNREFERENCED_PARAMETER(errorMessage);
return GetLastError();
}
// Open session and connection with the server.
virtual unsigned long open() override
{
// This object have lifetime greater than proxy_name and proxy_bypass
// which may point to its elements.
ie_proxy_config proxyIE;
DWORD access_type;
LPCWSTR proxy_name;
LPCWSTR proxy_bypass = WINHTTP_NO_PROXY_BYPASS;
utility::string_t proxy_str;
http::uri uri;
const auto& config = client_config();
if(config.proxy().is_disabled())
{
access_type = WINHTTP_ACCESS_TYPE_NO_PROXY;
proxy_name = WINHTTP_NO_PROXY_NAME;
}
else if(config.proxy().is_default() || config.proxy().is_auto_discovery())
{
// Use the default WinHTTP proxy by default.
access_type = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
proxy_name = WINHTTP_NO_PROXY_NAME;
#ifndef CPPREST_TARGET_XP
if (IsWindows8Point1OrGreater())
{
access_type = WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
// However, if it is not configured...
proxy_info proxyDefault;
if(!WinHttpGetDefaultProxyConfiguration(&proxyDefault) ||
proxyDefault.dwAccessType == WINHTTP_ACCESS_TYPE_NO_PROXY)
{
// ... then try to fall back on the default WinINET proxy, as
// recommended for the desktop applications (if we're not
// running under a user account, the function below will just
// fail, so there is no real need to check for this explicitly)
if(WinHttpGetIEProxyConfigForCurrentUser(&proxyIE))
{
if(proxyIE.fAutoDetect)
{
m_proxy_auto_config = true;
}
else if(proxyIE.lpszAutoConfigUrl)
{
m_proxy_auto_config = true;
m_proxy_auto_config_url = proxyIE.lpszAutoConfigUrl;
}
else if(proxyIE.lpszProxy)
{
access_type = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
proxy_name = proxyIE.lpszProxy;
if(proxyIE.lpszProxyBypass)
{
proxy_bypass = proxyIE.lpszProxyBypass;
}
}
}
}
#endif
if (config.proxy().is_auto_discovery())
{
m_proxy_auto_config = true;
}
}
else
{
_ASSERTE(config.proxy().is_specified());
access_type = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
// WinHttpOpen cannot handle trailing slash in the name, so here is some string gymnastics to keep WinHttpOpen happy
// proxy_str is intentionally declared at the function level to avoid pointing to the string in the destructed object
uri = config.proxy().address();
if(uri.is_port_default())
{
proxy_name = uri.host().c_str();
}
else
{
if (uri.port() > 0)
{
utility::ostringstream_t ss;
ss.imbue(std::locale::classic());
ss << uri.host() << _XPLATSTR(":") << uri.port();
proxy_str = ss.str();
}
else
{
proxy_str = uri.host();
}
proxy_name = proxy_str.c_str();
}
}
// Open session.
m_hSession = WinHttpOpen(
NULL,
access_type,
proxy_name,
proxy_bypass,
WINHTTP_FLAG_ASYNC);
if(!m_hSession)
{
return report_failure(_XPLATSTR("Error opening session"));
}
// Set timeouts.
int milliseconds = static_cast<int>(config.timeout<std::chrono::milliseconds>().count());
milliseconds = std::max<decltype(milliseconds)>(milliseconds, 1);
if (!WinHttpSetTimeouts(m_hSession,
milliseconds,
milliseconds,
milliseconds,
milliseconds))
{
return report_failure(_XPLATSTR("Error setting timeouts"));
}
if(config.guarantee_order())
{
// Set max connection to use per server to 1.
DWORD maxConnections = 1;
if(!WinHttpSetOption(m_hSession, WINHTTP_OPTION_MAX_CONNS_PER_SERVER, &maxConnections, sizeof(maxConnections)))
{
return report_failure(_XPLATSTR("Error setting options"));
}
}
//Enable TLS 1.1 and 1.2
#if !defined(CPPREST_TARGET_XP)
BOOL win32_result(FALSE);
DWORD secure_protocols(WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2);
win32_result = ::WinHttpSetOption(m_hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, &secure_protocols, sizeof(secure_protocols));
if(FALSE == win32_result)
{
return report_failure(_XPLATSTR("Error setting session options"));
}
#endif
config._invoke_nativesessionhandle_options(m_hSession);
// Register asynchronous callback.
if(WINHTTP_INVALID_STATUS_CALLBACK == WinHttpSetStatusCallback(
m_hSession,
&winhttp_client::completion_callback,
WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_FLAG_HANDLES | WINHTTP_CALLBACK_FLAG_SECURE_FAILURE,
0))
{
return report_failure(_XPLATSTR("Error registering callback"));
}
// Open connection.
unsigned int port = m_uri.is_port_default() ? (m_secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT) : m_uri.port();
m_hConnection = WinHttpConnect(
m_hSession,
m_uri.host().c_str(),
(INTERNET_PORT)port,
0);
if(m_hConnection == nullptr)
{
return report_failure(_XPLATSTR("Error opening connection"));
}
return S_OK;
}
// Start sending request.
void send_request(_In_ const std::shared_ptr<request_context> &request)
{
http_request &msg = request->m_request;
std::shared_ptr<winhttp_request_context> winhttp_context = std::static_pointer_cast<winhttp_request_context>(request);
std::weak_ptr<winhttp_request_context> weak_winhttp_context = winhttp_context;
proxy_info info;
bool proxy_info_required = false;
if(m_proxy_auto_config)
{
WINHTTP_AUTOPROXY_OPTIONS autoproxy_options;
memset( &autoproxy_options, 0, sizeof(WINHTTP_AUTOPROXY_OPTIONS) );
if(m_proxy_auto_config_url.empty())
{
autoproxy_options.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
autoproxy_options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
}
else
{
autoproxy_options.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
autoproxy_options.lpszAutoConfigUrl = m_proxy_auto_config_url.c_str();
}
autoproxy_options.fAutoLogonIfChallenged = TRUE;
auto result = WinHttpGetProxyForUrl(
m_hSession,
m_uri.to_string().c_str(),
&autoproxy_options,
&info );
if(result)
{
proxy_info_required = true;
}
else
{
// Failure to download the auto-configuration script is not fatal. Fall back to the default proxy.
}
}
// Need to form uri path, query, and fragment for this request.
// Make sure to keep any path that was specified with the uri when the http_client was created.
const utility::string_t encoded_resource = http::uri_builder(m_uri).append(msg.relative_uri()).to_uri().resource().to_string();
// Open the request.
winhttp_context->m_request_handle = WinHttpOpenRequest(
m_hConnection,
msg.method().c_str(),
encoded_resource.c_str(),
nullptr,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_ESCAPE_DISABLE | (m_secure ? WINHTTP_FLAG_SECURE : 0));
if(winhttp_context->m_request_handle == nullptr)
{
auto errorCode = GetLastError();
request->report_error(errorCode, build_error_msg(errorCode, "WinHttpOpenRequest"));
return;
}
// Enable the certificate revocation check
if (m_secure)
{
DWORD dwEnableSSLRevocOpt = WINHTTP_ENABLE_SSL_REVOCATION;
if (!WinHttpSetOption(winhttp_context->m_request_handle, WINHTTP_OPTION_ENABLE_FEATURE, &dwEnableSSLRevocOpt, sizeof(dwEnableSSLRevocOpt)))
{
auto errorCode = GetLastError();
request->report_error(errorCode, build_error_msg(errorCode, "Error enabling SSL revocation check"));
return;
}
}
if(proxy_info_required)
{
auto result = WinHttpSetOption(
winhttp_context->m_request_handle,
WINHTTP_OPTION_PROXY,
&info,
sizeof(WINHTTP_PROXY_INFO) );
if(!result)
{
auto errorCode = GetLastError();
request->report_error(errorCode, build_error_msg(errorCode, "Setting proxy options"));
return;
}
}
// If credentials are specified, use autologon policy: WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH
// => default credentials are not used.
// Else, the default autologon policy WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM will be used.
if (client_config().credentials().is_set())
{
DWORD data = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
auto result = WinHttpSetOption(
winhttp_context->m_request_handle,
WINHTTP_OPTION_AUTOLOGON_POLICY,
&data,
sizeof(data));
if(!result)
{
auto errorCode = GetLastError();
request->report_error(errorCode, build_error_msg(errorCode, "Setting autologon policy to WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH"));
return;
}
}
// Check to turn off server certificate verification.
if(!client_config().validate_certificates())
{
DWORD data = SECURITY_FLAG_IGNORE_UNKNOWN_CA
| SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
| SECURITY_FLAG_IGNORE_CERT_CN_INVALID
| SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE;
auto result = WinHttpSetOption(
winhttp_context->m_request_handle,
WINHTTP_OPTION_SECURITY_FLAGS,
&data,
sizeof(data));
if(!result)
{
auto errorCode = GetLastError();
request->report_error(errorCode, build_error_msg(errorCode, "Setting ignore server certificate verification"));
return;
}
}
const size_t content_length = msg._get_impl()->_get_content_length();
if (content_length > 0)
{
if ( msg.method() == http::methods::GET || msg.method() == http::methods::HEAD )
{
request->report_exception(http_exception(get_with_body_err_msg));
return;
}
// There is a request body that needs to be transferred.
if (content_length == std::numeric_limits<size_t>::max())
{
// The content length is unknown and the application set a stream. This is an
// indication that we will use transfer encoding chunked.
winhttp_context->m_bodyType = transfer_encoding_chunked;
}
else
{
// While we won't be transfer-encoding the data, we will write it in portions.
winhttp_context->m_bodyType = content_length_chunked;
winhttp_context->m_remaining_to_write = content_length;
}
}
if(web::http::details::compression::stream_decompressor::is_supported() && client_config().request_compressed_response())
{
msg.headers().add(web::http::header_names::accept_encoding, U("deflate, gzip"));
}
// Add headers.
if(!msg.headers().empty())
{
const utility::string_t flattened_headers = web::http::details::flatten_http_headers(msg.headers());
if(!WinHttpAddRequestHeaders(
winhttp_context->m_request_handle,
flattened_headers.c_str(),
static_cast<DWORD>(flattened_headers.length()),
WINHTTP_ADDREQ_FLAG_ADD))
{
auto errorCode = GetLastError();
request->report_error(errorCode, build_error_msg(errorCode, "WinHttpAddRequestHeaders"));
return;
}
}
// Register for notification on cancellation to abort this request.
if(msg._cancellation_token() != pplx::cancellation_token::none())
{
// cancellation callback is unregistered when request is completed.
winhttp_context->m_cancellationRegistration = msg._cancellation_token().register_callback([weak_winhttp_context]()
{
// Call the WinHttpSendRequest API after WinHttpCloseHandle will give invalid handle error and we throw this exception.
// Call the cleanup to make the m_request_handle as nullptr, otherwise, Application Verifier will give AV exception on m_request_handle.
auto lock = weak_winhttp_context.lock();
if (!lock) return;
lock->cleanup();
});
}
// Call the callback function of user customized options.
try
{
client_config().invoke_nativehandle_options(winhttp_context->m_request_handle);
}
catch (...)
{
request->report_exception(std::current_exception());
return;
}
// Only need to cache the request body if user specified and the request stream doesn't support seeking.
if (winhttp_context->m_bodyType != no_body && client_config().buffer_request() && !winhttp_context->_get_readbuffer().can_seek())
{
winhttp_context->m_readBufferCopy = ::utility::details::make_unique<::concurrency::streams::container_buffer<std::vector<uint8_t>>>();
}
_start_request_send(winhttp_context, content_length);
return;
}
private:
void _start_request_send(const std::shared_ptr<winhttp_request_context>& winhttp_context, size_t content_length)
{
// WinHttp takes a context object as a void*. We therefore heap allocate a std::weak_ptr to the request context which will be destroyed during the final callback.
std::unique_ptr<std::weak_ptr<winhttp_request_context>> weak_context_holder;
if (winhttp_context->m_request_context == nullptr)
{
weak_context_holder = std::make_unique<std::weak_ptr<winhttp_request_context>>(winhttp_context);
winhttp_context->m_request_context = weak_context_holder.get();
}
if (winhttp_context->m_bodyType == no_body)
{
if(!WinHttpSendRequest(
winhttp_context->m_request_handle,
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
nullptr,
0,
0,
(DWORD_PTR)winhttp_context->m_request_context))
{
if (weak_context_holder)
winhttp_context->m_request_context = nullptr;
auto errorCode = GetLastError();
winhttp_context->report_error(errorCode, build_error_msg(errorCode, "WinHttpSendRequest"));
}
else
{
// Ownership of the weak_context_holder was accepted by the callback, so release the pointer without freeing.
weak_context_holder.release();
}
return;
}
// Capture the current read position of the stream.
auto rbuf = winhttp_context->_get_readbuffer();
// Record starting position in case request is challenged for authorization
// and needs to seek back to where reading is started from.
winhttp_context->m_startingPosition = rbuf.getpos(std::ios_base::in);
// If we find ourselves here, we either don't know how large the message
// body is, or it is larger than our threshold.
if(!WinHttpSendRequest(
winhttp_context->m_request_handle,
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
nullptr,
0,
winhttp_context->m_bodyType == content_length_chunked ? (DWORD)content_length : WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH,
(DWORD_PTR)winhttp_context->m_request_context))
{
if (weak_context_holder)
winhttp_context->m_request_context = nullptr;
auto errorCode = GetLastError();
winhttp_context->report_error(errorCode, build_error_msg(errorCode, "WinHttpSendRequest chunked"));
}
else
{
// Ownership of the weak_context_holder was accepted by the callback, so release the pointer without freeing.
weak_context_holder.release();
}
}
// Helper function to query/read next part of response data from winhttp.
static void read_next_response_chunk(winhttp_request_context *pContext, DWORD bytesRead, bool firstRead=false)
{
const bool defaultChunkSize = pContext->m_http_client->client_config().is_default_chunksize();
// If user specified a chunk size then read in chunks instead of using query data avaliable.
if (defaultChunkSize)
{
if (!WinHttpQueryDataAvailable(pContext->m_request_handle, nullptr))
{
auto errorCode = GetLastError();
pContext->report_error(errorCode, build_error_msg(errorCode, "WinHttpQueryDataAvaliable"));
}
}
else
{
// If bytes read is less than the chunk size this request is done.
const size_t chunkSize = pContext->m_http_client->client_config().chunksize();
if (bytesRead < chunkSize && !firstRead)
{
pContext->complete_request(pContext->m_downloaded);
}
else
{
auto writebuf = pContext->_get_writebuffer();
pContext->allocate_reply_space(writebuf.alloc(chunkSize), chunkSize);
if (!WinHttpReadData(
pContext->m_request_handle,
pContext->m_body_data.get(),
static_cast<DWORD>(chunkSize),
nullptr))
{
auto errorCode = GetLastError();
pContext->report_error(errorCode, build_error_msg(errorCode, "WinHttpReadData"));
}
}
}
}
static void _transfer_encoding_chunked_write_data(_In_ winhttp_request_context * p_request_context)
{
const size_t chunk_size = p_request_context->m_http_client->client_config().chunksize();
p_request_context->allocate_request_space(nullptr, chunk_size+http::details::chunked_encoding::additional_encoding_space);
auto after_read = [p_request_context, chunk_size](pplx::task<size_t> op)
{
size_t bytes_read;
try
{
bytes_read = op.get();
// If the read buffer for copying exists then write to it.
if (p_request_context->m_readBufferCopy)
{
// We have raw memory here writing to a memory stream so it is safe to wait
// since it will always be non-blocking.
p_request_context->m_readBufferCopy->putn_nocopy(&p_request_context->m_body_data.get()[http::details::chunked_encoding::data_offset], bytes_read).wait();
}
}
catch (...)
{
p_request_context->report_exception(std::current_exception());
return;
}
_ASSERTE(bytes_read != static_cast<size_t>(-1));
size_t offset = http::details::chunked_encoding::add_chunked_delimiters(p_request_context->m_body_data.get(), chunk_size + http::details::chunked_encoding::additional_encoding_space, bytes_read);
// Stop writing chunks if we reached the end of the stream.
if (bytes_read == 0)
{
p_request_context->m_bodyType = no_body;
if (p_request_context->m_readBufferCopy)
{
// Move the saved buffer into the read buffer, which now supports seeking.
p_request_context->m_readStream = concurrency::streams::container_stream<std::vector<uint8_t>>::open_istream(std::move(p_request_context->m_readBufferCopy->collection()));
p_request_context->m_readBufferCopy.reset();
}
}
const auto length = bytes_read + (http::details::chunked_encoding::additional_encoding_space - offset);
if (!WinHttpWriteData(
p_request_context->m_request_handle,
&p_request_context->m_body_data.get()[offset],
static_cast<DWORD>(length),
nullptr))
{
auto errorCode = GetLastError();
p_request_context->report_error(errorCode, build_error_msg(errorCode, "WinHttpWriteData"));
}
};
p_request_context->_get_readbuffer().getn(&p_request_context->m_body_data.get()[http::details::chunked_encoding::data_offset], chunk_size).then(after_read);
}
static void _multiple_segment_write_data(_In_ winhttp_request_context * p_request_context)
{
auto rbuf = p_request_context->_get_readbuffer();
msl::safeint3::SafeInt<utility::size64_t> safeCount = p_request_context->m_remaining_to_write;
safeCount = safeCount.Min(p_request_context->m_http_client->client_config().chunksize());
uint8_t* block = nullptr;
size_t length = 0;
if (rbuf.acquire(block, length))
{
if (length == 0)
{
// Unexpected end-of-stream.
if (rbuf.exception() == nullptr)
{
p_request_context->report_error(GetLastError(), _XPLATSTR("Error reading outgoing HTTP body from its stream."));
}
else
{
p_request_context->report_exception(rbuf.exception());
}
return;
}
p_request_context->allocate_request_space(block, length);
const size_t to_write = safeCount.Min(length);
// Stop writing chunks after this one if no more data.
p_request_context->m_remaining_to_write -= to_write;
if ( p_request_context->m_remaining_to_write == 0 )
{
p_request_context->m_bodyType = no_body;
}
if( !WinHttpWriteData(
p_request_context->m_request_handle,
p_request_context->m_body_data.get(),
static_cast<DWORD>(to_write),
nullptr))
{
auto errorCode = GetLastError();
p_request_context->report_error(errorCode, build_error_msg(errorCode, "WinHttpWriteData"));
}