-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathhttp_client_winhttp.cpp
More file actions
2659 lines (2400 loc) · 117 KB
/
http_client_winhttp.cpp
File metadata and controls
2659 lines (2400 loc) · 117 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 "../common/x509_cert_utilities.h"
#include "../common/internal_http_helpers.h"
#include "cpprest/http_headers.h"
#include "http_client_impl.h"
#ifdef WIN32
#include <Wincrypt.h>
#endif
#if defined(CPPREST_FORCE_HTTP_CLIENT_WINHTTPPAL)
#include "winhttppal.h"
#endif
#include <atomic>
#if _WIN32_WINNT && (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
#include <VersionHelpers.h>
#endif
namespace
{
struct security_failure_message
{
std::uint32_t flag;
const char* text;
};
CPPREST_CONSTEXPR security_failure_message g_security_failure_messages[] = {
{WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED,
"WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED failed to check revocation status."},
{WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT,
"WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT SSL certificate is invalid."},
{WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED,
"WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED SSL certificate was revoked."},
{WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA, "WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA SSL invalid CA."},
{WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID,
"WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID SSL common name does not match."},
{WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID,
"WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID SLL certificate is expired."},
{WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR,
"WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR internal error."},
};
std::string generate_security_failure_message(std::uint32_t flags)
{
std::string result("SSL Error:");
for (const auto& message : g_security_failure_messages)
{
if (flags & message.flag)
{
result.push_back(' ');
result.append(message.text);
}
}
return result;
}
} // unnamed namespace
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)stoi(buffer);
}
// 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.
::web::http::details::trim_nulls(phrase);
return phrase;
}
/// <summary>
/// Parses a string containing HTTP headers.
/// </summary>
static void parse_winhttp_headers(HINTERNET request_handle, _In_z_ utility::char_t* 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::platform_category().message(static_cast<int>(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;
size_t m_size;
public:
memory_holder() : m_externalData(nullptr), m_size(0) {}
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, size_t length)
{
assert(block != nullptr);
m_externalData = block;
m_size = length;
}
inline bool is_internally_allocated() const { return m_externalData == nullptr; }
inline uint8_t* get() { return is_internally_allocated() ? &m_internalData[0] : m_externalData; }
inline size_t size() const { return is_internally_allocated() ? m_internalData.size() : m_size; }
};
// Possible ways a message body can be sent/received.
enum msg_body_type
{
no_body,
content_length_chunked,
transfer_encoding_chunked
};
static DWORD WinHttpDefaultProxyConstant() CPPREST_NOEXCEPT
{
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
#if _WIN32_WINNT < _WIN32_WINNT_WINBLUE
if (!IsWindows8Point1OrGreater())
{
// Not Windows 8.1 or later, use the default proxy setting
return WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
#endif // _WIN32_WINNT < _WIN32_WINNT_WINBLUE
// Windows 8.1 or later, use the automatic proxy setting
return WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
#else // ^^^ _WIN32_WINNT >= _WIN32_WINNT_VISTA ^^^ // vvv _WIN32_WINNT < _WIN32_WINNT_VISTA vvv
return WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
#endif // _WIN32_WINNT >= _WIN32_WINNT_VISTA
}
// Additional information necessary to track a WinHTTP request.
class winhttp_request_context final : 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, length);
}
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, length);
}
bool is_externally_allocated() const { return !m_body_data.is_internally_allocated(); }
HINTERNET m_request_handle;
std::weak_ptr<winhttp_request_context>*
m_request_handle_context; // owned by m_request_handle to be deleted by WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING
bool m_proxy_authentication_tried;
bool m_server_authentication_tried;
size_t m_remaining_redirects;
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;
// Compress/decompress-related processing state lives here
class compression_state
{
public:
compression_state()
: m_acquired(nullptr)
, m_bytes_read(0)
, m_bytes_processed(0)
, m_needs_flush(false)
, m_started(false)
, m_done(false)
, m_chunked(false)
{
}
#if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(CPPREST_FORCE_HTTP_CLIENT_WINHTTPPAL)
compression_state(const compression_state&) = delete;
compression_state(compression_state&& other)
: m_buffer(std::move(other.m_buffer))
, m_acquired(other.m_acquired)
, m_bytes_read(other.m_bytes_read)
, m_bytes_processed(other.m_bytes_processed)
, m_needs_flush(other.m_needs_flush)
, m_started(other.m_started)
, m_done(other.m_done)
, m_chunked(other.m_chunked)
, m_chunk_bytes(other.m_chunk_bytes)
, m_chunk(std::move(other.m_chunk))
{
}
compression_state& operator=(const compression_state&) = delete;
compression_state& operator=(compression_state&& other)
{
m_buffer = std::move(other.m_buffer);
m_acquired = other.m_acquired;
m_bytes_read = other.m_bytes_read;
m_bytes_processed = other.m_bytes_processed;
m_needs_flush = other.m_needs_flush;
m_started = other.m_started;
m_done = other.m_done;
m_chunked = other.m_chunked;
m_chunk_bytes = other.m_chunk_bytes;
m_chunk = std::move(other.m_chunk);
return *this;
}
#endif // defined(_MSC_VER) && _MSC_VER < 1900
// Minimal state for on-the-fly decoding of "chunked" encoded data
class _chunk_helper
{
public:
_chunk_helper()
: m_bytes_remaining(0)
, m_chunk_size(true)
, m_chunk_delim(false)
, m_expect_linefeed(false)
, m_ignore(false)
, m_trailer(false)
{
}
// Returns true if the end of chunked data has been reached, specifically whether the 0-length
// chunk and its trailing delimiter has been processed. Otherwise, offset and length bound the
// portion of buffer that represents a contiguous (and possibly partial) chunk of consumable
// data; offset+length is the total number of bytes processed from the buffer on this pass.
bool process_buffer(uint8_t* buffer, size_t buffer_size, size_t& offset, size_t& length)
{
bool done = false;
size_t n = 0;
size_t l = 0;
while (n < buffer_size)
{
if (m_ignore)
{
if (m_expect_linefeed)
{
_ASSERTE(m_chunk_delim && m_trailer);
if (buffer[n] != '\n')
{
// The data stream does not conform to "chunked" encoding
throw http_exception(status_codes::BadRequest, "Transfer-Encoding malformed trailer");
}
// Look for further trailer fields or the end of the stream
m_expect_linefeed = false;
m_trailer = false;
}
else if (buffer[n] == '\r')
{
if (!m_trailer)
{
// We're at the end of the data we need to ignore
_ASSERTE(m_chunk_size || m_chunk_delim);
m_ignore = false;
m_chunk_delim = false; // this is only set if we're at the end of the message
} // else we're at the end of a trailer field
m_expect_linefeed = true;
}
else if (m_chunk_delim)
{
// We're processing (and ignoring) a trailer field
m_trailer = true;
}
}
else if (m_expect_linefeed)
{
// We've already seen a carriage return; confirm the linefeed
if (buffer[n] != '\n')
{
// The data stream does not conform to "chunked" encoding
throw http_exception(status_codes::BadRequest, "Transfer-Encoding malformed delimiter");
}
if (m_chunk_size)
{
if (!m_bytes_remaining)
{
// We're processing the terminating "empty" chunk; there's
// no data, we just need to confirm the final chunk delimiter,
// possibly ignoring a trailer part along the way
m_ignore = true;
m_chunk_delim = true;
} // else we move on to the chunk data itself
m_chunk_size = false;
}
else
{
// Now we move on to the next chunk size
_ASSERTE(!m_bytes_remaining);
if (m_chunk_delim)
{
// We expect a chunk size next
m_chunk_size = true;
}
else
{
// We just processed the end-of-input delimiter
done = true;
}
m_chunk_delim = false;
}
m_expect_linefeed = false;
}
else if (m_chunk_delim)
{
// We're processing a post-chunk delimiter
if (buffer[n] != '\r')
{
// The data stream does not conform to "chunked" encoding
throw http_exception(status_codes::BadRequest,
"Transfer-Encoding malformed chunk delimiter");
}
// We found the carriage return; look for the linefeed
m_expect_linefeed = true;
}
else if (m_chunk_size)
{
// We're processing an ASCII hexadecimal chunk size
if (buffer[n] >= 'a' && buffer[n] <= 'f')
{
m_bytes_remaining *= 16;
m_bytes_remaining += 10 + buffer[n] - 'a';
}
else if (buffer[n] >= 'A' && buffer[n] <= 'F')
{
m_bytes_remaining *= 16;
m_bytes_remaining += 10 + buffer[n] - 'A';
}
else if (buffer[n] >= '0' && buffer[n] <= '9')
{
m_bytes_remaining *= 16;
m_bytes_remaining += buffer[n] - '0';
}
else if (buffer[n] == '\r')
{
// We've reached the end of the size, and there's no chunk extension
m_expect_linefeed = true;
}
else if (buffer[n] == ';')
{
// We've reached the end of the size, and there's a chunk extension;
// we don't support extensions, so we ignore them per RFC
m_ignore = true;
}
else
{
// The data stream does not conform to "chunked" encoding
throw http_exception(status_codes::BadRequest,
"Transfer-Encoding malformed chunk size or extension");
}
}
else
{
if (m_bytes_remaining)
{
// We're at the offset of a chunk of consumable data; let the caller process it
l = (std::min)(m_bytes_remaining, buffer_size - n);
m_bytes_remaining -= l;
if (!m_bytes_remaining)
{
// We're moving on to the post-chunk delimiter
m_chunk_delim = true;
}
}
else
{
// We've previously processed the terminating empty chunk and its
// trailing delimiter; skip the entire buffer, and inform the caller
n = buffer_size;
done = true;
}
// Let the caller process the result
break;
}
// Move on to the next byte
n++;
}
offset = n;
length = l;
return buffer_size ? done : (!m_bytes_remaining && !m_chunk_size && !m_chunk_delim);
}
private:
size_t m_bytes_remaining; // the number of bytes remaining in the chunk we're currently processing
bool m_chunk_size; // if true, we're processing a chunk size or its trailing delimiter
bool m_chunk_delim; // if true, we're processing a delimiter between a chunk and the next chunk's size
bool m_expect_linefeed; // if true, we're processing a delimiter, and we've already seen its carriage return
bool m_ignore; // if true, we're processing a chunk extension or trailer, which we don't support
bool m_trailer; // if true, we're processing (and ignoring) a trailer field; m_ignore is also true
};
std::vector<uint8_t> m_buffer; // we read data from the stream into this before compressing
uint8_t* m_acquired; // we use this in place of m_buffer if the stream has directly-accessible data available
size_t m_bytes_read; // we most recently read this many bytes, which may be less than m_buffer.size()
size_t m_bytes_processed; // we've compressed this many bytes of m_bytes_read so far
bool m_needs_flush; // we've read and compressed all bytes, but the compressor still has compressed bytes to
// give us
bool m_started; // we've sent at least some number of bytes to m_decompressor
bool m_done; // we've read, compressed, and consumed all bytes
bool m_chunked; // if true, we need to decode and decompress a transfer-encoded message
size_t m_chunk_bytes; // un-decompressed bytes remaining in the most-recently-obtained data from m_chunk
std::unique_ptr<_chunk_helper> m_chunk;
} m_compression_state;
void cleanup()
{
if (m_compression_state.m_acquired != nullptr)
{
// We may still hold a piece of the buffer if we encountered an exception; release it here
if (m_decompressor)
{
_get_writebuffer().commit(0);
}
else
{
_get_readbuffer().release(m_compression_state.m_acquired, m_compression_state.m_bytes_processed);
}
m_compression_state.m_acquired = nullptr;
}
if (m_request_handle != nullptr)
{
WinHttpCloseHandle(m_request_handle);
}
}
void install_custom_cn_check(const utility::string_t& customHost)
{
m_customCnCheck = customHost;
utility::details::inplace_tolower(m_customCnCheck);
}
void on_send_request_validate_cn()
{
#if defined(CPPREST_FORCE_HTTP_CLIENT_WINHTTPPAL)
// we do the validation inside curl
return;
#else
if (m_customCnCheck.empty())
{
// no custom validation selected; either we've delegated that to winhttp or
// certificate checking is completely disabled
return;
}
winhttp_cert_context certContext;
DWORD bufferSize = sizeof(certContext.raw);
if (!WinHttpQueryOption(m_request_handle, WINHTTP_OPTION_SERVER_CERT_CONTEXT, &certContext.raw, &bufferSize))
{
auto errorCode = GetLastError();
if (errorCode == HRESULT_CODE(WININET_E_INCORRECT_HANDLE_STATE))
{
// typically happens when given a custom host with an initially HTTP connection
return;
}
report_error(errorCode,
build_error_msg(errorCode, "WinHttpQueryOption WINHTTP_OPTION_SERVER_CERT_CONTEXT"));
cleanup();
return;
}
const auto encodedFirst = certContext.raw->pbCertEncoded;
const auto encodedLast = encodedFirst + certContext.raw->cbCertEncoded;
if (certContext.raw->cbCertEncoded == m_cachedEncodedCert.size() &&
std::equal(encodedFirst, encodedLast, m_cachedEncodedCert.begin()))
{
// already validated OK
return;
}
char oidPkixKpServerAuth[] = szOID_PKIX_KP_SERVER_AUTH;
char oidServerGatedCrypto[] = szOID_SERVER_GATED_CRYPTO;
char oidSgcNetscape[] = szOID_SGC_NETSCAPE;
char* chainUses[] = {
oidPkixKpServerAuth,
oidServerGatedCrypto,
oidSgcNetscape,
};
winhttp_cert_chain_context chainContext;
CERT_CHAIN_PARA chainPara = {sizeof(chainPara)};
chainPara.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
chainPara.RequestedUsage.Usage.cUsageIdentifier = sizeof(chainUses) / sizeof(char*);
chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = chainUses;
// note that the following chain only checks the end certificate; we
// assume WinHTTP already validated everything but the common name.
if (!CertGetCertificateChain(NULL,
certContext.raw,
nullptr,
certContext.raw->hCertStore,
&chainPara,
CERT_CHAIN_CACHE_END_CERT,
NULL,
&chainContext.raw))
{
auto errorCode = GetLastError();
report_error(errorCode, build_error_msg(errorCode, "CertGetCertificateChain"));
cleanup();
return;
}
HTTPSPolicyCallbackData policyData = {
{sizeof(policyData)},
AUTHTYPE_SERVER,
// we assume WinHTTP already checked these:
0x00000080 /* SECURITY_FLAG_IGNORE_REVOCATION */
| 0x00000100 /* SECURITY_FLAG_IGNORE_UNKNOWN_CA */
| 0x00000200 /* SECURITY_FLAG_IGNORE_WRONG_USAGE */
| 0x00002000 /* SECURITY_FLAG_IGNORE_CERT_DATE_INVALID */,
&m_customCnCheck[0],
};
CERT_CHAIN_POLICY_PARA policyPara = {sizeof(policyPara)};
policyPara.pvExtraPolicyPara = &policyData;
CERT_CHAIN_POLICY_STATUS policyStatus = {sizeof(policyStatus)};
if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chainContext.raw, &policyPara, &policyStatus))
{
auto errorCode = GetLastError();
report_error(errorCode, build_error_msg(errorCode, "CertVerifyCertificateChainPolicy"));
cleanup();
return;
}
if (policyStatus.dwError)
{
report_error(policyStatus.dwError, build_error_msg(policyStatus.dwError, "Incorrect common name"));
cleanup();
return;
}
m_cachedEncodedCert.assign(encodedFirst, encodedLast);
#endif
}
protected:
virtual void finish() override
{
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:
utility::string_t m_customCnCheck;
std::vector<unsigned char> m_cachedEncodedCert;
// 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_proxy_authentication_tried(false)
, m_server_authentication_tried(false)
, m_remaining_redirects(0)
, m_bodyType(no_body)
, m_remaining_to_write(0)
, m_startingPosition(std::char_traits<uint8_t>::eof())
, m_readStream(request.body())
, m_body_data()
{
}
};
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 final : 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_opened(false)
, m_hSession(nullptr)
, m_hConnection(nullptr)
, m_secure(m_uri.scheme() == _XPLATSTR("https"))
{
}
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, 0);
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:
// Open session and connection with the server.
unsigned long open()
{
if (m_opened)
{
return 0;
}
pplx::extensibility::scoped_critical_section_t l(m_client_lock);
if (m_opened)
{
return 0;
}
// This object have lifetime greater than proxy_name and proxy_bypass
// which may point to its elements.
ie_proxy_config proxyIE;
DWORD access_type;
LPCTSTR proxy_name = WINHTTP_NO_PROXY_NAME;
LPCTSTR proxy_bypass = WINHTTP_NO_PROXY_BYPASS;
m_proxy_auto_config = false;
utility::string_t proxy_str;
http::uri uri;
const auto& config = client_config();
const auto& proxy = config.proxy();
if (proxy.is_default())
{
access_type = WinHttpDefaultProxyConstant();
}
else if (proxy.is_disabled())
{
access_type = WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (proxy.is_auto_discovery())
{
access_type = WinHttpDefaultProxyConstant();
if (access_type != WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY)
{
// Windows 8 or earlier, do proxy autodetection ourselves
m_proxy_auto_config = true;
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;
}
}
}
}
}
}
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
{
proxy_str = uri.host();
if (uri.port() > 0)
{
proxy_str.push_back(_XPLATSTR(':'));
proxy_str.append(::utility::conversions::details::to_string_t(uri.port()));
}
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 GetLastError();
}
{
// Set timeouts.
const int milliseconds =
(std::max)(static_cast<int>(config.timeout<std::chrono::milliseconds>().count()), 1);
if (!WinHttpSetTimeouts(m_hSession, milliseconds, milliseconds, milliseconds, milliseconds))
{
return GetLastError();
}
}
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 GetLastError();
}
}
{
// Enable TLS 1.1 and 1.2
#if (_WIN32_WINNT >= _WIN32_WINNT_VISTA) || defined(CPPREST_FORCE_HTTP_CLIENT_WINHTTPPAL)
DWORD secure_protocols(WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 |
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2);
if (!WinHttpSetOption(
m_hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, &secure_protocols, sizeof(secure_protocols)))
{
return GetLastError();
}
#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 | WINHTTP_CALLBACK_FLAG_SEND_REQUEST |
WINHTTP_CALLBACK_STATUS_REDIRECT,
0))
{
return GetLastError();
}
// 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 GetLastError();
}
m_opened = true;
return S_OK;
}
// Start sending request.
void send_request(_In_ const std::shared_ptr<request_context>& request)
{
// First see if we need to be opened.
unsigned long error = open();
if (error != 0)
{
// DO NOT TOUCH the this pointer after completing the request
// This object could be freed along with the request as it could
// be the last reference to this object
request->report_error(error, _XPLATSTR("Open failed"));
return;
}
http_request& msg = request->m_request;
http_headers& headers = msg.headers();
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;
const auto& method = msg.method();
// stop injection of headers via method
// resource should be ok, since it's been encoded
// and host won't resolve
if (!::web::http::details::validate_method(method))
{
request->report_exception(http_exception("The method string is invalid."));
return;
}
auto config = client_config();
auto proxy = config.proxy();
if (m_proxy_auto_config)
{
WINHTTP_AUTOPROXY_OPTIONS autoproxy_options {};
if (m_proxy_auto_config_url.empty())