-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWinHTTPWrappers.h
1638 lines (1383 loc) · 76.3 KB
/
WinHTTPWrappers.h
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
/*
Module : WinHTTPWrappers.h
Purpose: Defines the interface for a set of C++ class which encapsulate WinHTTP. The classes are based on
the MSDN Magazine article by Kenny Kerr at
https://docs.microsoft.com/en-us/archive/msdn-magazine/2008/august/windows-with-c-asynchronous-winhttp
History: PJN / 30-05-2011 1. All tracing in CWinHTTPHandle::OnCallback has been moved into a new TraceCallback
method which client code is free to call. Also all tracing in CWinHTTPHandle::
OnCallbackComplete has been moved into a new TraceCallbackComplete method. Also all
tracing in CDownloadFileWinHttpRequest::OnCallbackComplete has been moved into a new
TraceCallbackComplete method.
2. Moved cleanup of resources from CDownloadFileWinHttpRequest::OnCallbackComplete
to a new public method called ReleaseResources()
PJN / 30-07-2011 1. CDownloadFileWinHttpRequest class is now called CAsyncWinHttpDownloader
2. Major rework of the CAsyncWinHttpDownloader to now support HTTP and Proxy
authentication, pre-authentication, resumed downloads, file uploads, in-memory arrays
and bandwidth throttling.
3. Fixed an issue in TraceCallback where WINHTTP_CALLBACK_STATUS_SECURE_FAILURE would
be reported incorrectly by TRACE statements
4. Addition of a new CSyncWinHttpDownloader class which provides for synchronous
WinHTTP downloads.
5. Updated the sample app to allow all of the new configuration settings of
CAsyncWinHttpDownloader and CSyncWinHttpDownloader classes to be exercised.
6. Fixed a bug in CWinHTTPRequest::WriteData() where buffer parameter was incorrectly
set as a LPVOID instead of a LPCVOID.
PJN / 30-03-2013 1. Updated copyright details.
2. Updated the sample app to correctly release the file handles when the file is
downloaded. Thanks to David Lowndes for reporting this bug.
3. Updated the code to clean compile on VC 2012
4. TimeSinceStartDownload() method has been extended to return a __int64 return value
instead of a DWORD.
5. Changed class names to use C*WinHTTP* prefix instead of C*WinHttp*.
PJN / 01-12-2013 1. Updated the code to clean compile on VC 2013.
PJN / 08-06-2014 1. Updated copyright details.
2. Updated燙AsyncWinHTTPDownloader::Initialize爐o燼llow爐he燿wShareMode爌arameter爋f
the ATL::CAtlFile::Create燾all for the file爄nstances to燽e燿ownload燼nd爑ploaded爐o?
be燾ustomized.燭he燿efault爒alue for爐he爏hare爉ode爄s爊ow?爄nstead爋f燜ILE_SHARE_READ.?
Thanks爐o燬imon燨rde爁or爌roviding爐his爊ice燼ddition.
3. All the class methods have had SAL annotations added
PJN / 08-03-2015 1. Updated copyright details.
2. Reworked the classes to optionally compile without MFC. By default the classes now use
STL classes and idioms but if you define WINHTTPWRAPPERS_MFC_EXTENSTIONS the classes will
revert back to the MFC behaviour.
3. Moved all the classes to a WinHTTPWrappers namespace
4. Renamed CWinHTTPHandle class to CHandle
5. Renamed CWinHTTPSession class to CSession
6. Renamed CWinHTTPConnection class to CConnection
7. Renamed CWinHTTPRequest class to CRequest
8. Renamed CAsyncWinHTTPDownloader class to CAsyncDownloader
9. Renamed CSyncWinHTTPDownloader class to CSyncDownloader
10. DeleteDownloadedFile now checks to see if "m_sFileToDownloadInto" is valid before it
calls DeleteFile. Thanks to Paul Jackson for reporting this issue.
11. Reworked the CAsyncDownloader::SendRequest, On407Response, On401Response &
OnRequestErrorCallback methods to pass a more correct value for the "dwTotalLength"
parameter in the call to WinHttpSendRequest. Thanks to Paul Jackson for reporting this
issue.
PJN / 11-03-2015 1. Optimized allocation of temporary string stack variables in
CAsyncDownloader::Initialize & CAsyncDownloader::DeleteDownloadedFile. Thanks to Paul
Jackson for reporting this issue.
PJN / 14-06-2015 1. Addition of a CAsyncDownloader::GetLastStatusCode method.
2. CAsyncDownloader::OnHeadersAvailableCallback and CSyncDownloader::SendRequestSync now
preserves the HTTP status code when the value received is not 200, 206, 401 or 407 and
the return value ATL::AtlHresultFromWin32(ERROR_WINHTTP_INVALID_HEADER) is about to be returned.
3. CSyncDownloader::SendRequestSync method has been made virtual.
4. Update the sample app to report the last status code if available when a download request
fails.
PJN / 07-11-2015 1. Updated SAL annotations in CHandle::SetOption to be consistent with Windows 10 SDK.
2. Fixed an issue in the use of _When_ SAL annotation in CHandle::SetOption
3. Update the code to compile cleanly on VC 2015
PJN / 06-03-2016 1. Updated copyright details.
2. The CAsyncDownloader destructor now resets the status callback function via
SetStatusCallback(NULL, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS). This prevents spurious
callbacks occuring after the C++ object is destroyed which depending on how you allocated the
C++ object could cause access violations in CHandle::_Callback.
3. Optimized the logic in the sample app when updating the edit box with status information
PJN / 16-04-2017 1. Updated copyright details.
2. Added support for WinHttpCreateProxyResolver, WinHttpResetAutoProxy, WinHttpWriteProxySettings,
WinHttpReadProxySettings & WinHttpGetProxySettingsVersion from the latest Windows 10 SDK
PJN / 18-09-2017 1. Replaced CString::operator LPC*STR() calls throughout the codebase with CString::GetString
calls
PJN / 23-05-2018 1. Replaced NULL with nullptr throughout the code.
3. Fixed a number of C++ core guidelines compiler warnings. These changes mean that the code
will now only compile on VC 2017 or later.
PJN / 02-09-2018 1. Fixed a number of compiler warnings when using VS 2017 15.8.2
PJN / 29-09-2018 1. Removed code which supported WINHTTPWRAPPERS_MFC_EXTENSIONS define
2. Added wrappers for WinHttpWebSocketCompleteUpgrade, WinHttpWebSocketSend, WinHttpWebSocketReceive,
WinHttpWebSocketShutdown, WinHttpWebSocketClose & WinHttpWebSocketQueryCloseStatus APIs.
3. Added wrappers for WinHttpGetProxyForUrlEx, WinHttpGetProxyForUrlEx2, WinHttpGetProxyResult &
WinHttpGetProxyResultEx APIs.
4. Reworked TimeSinceStartDownload to use GetTickCount64 API.
PJN / 24-11-2018 1. Fixed some further compiler warnings when using VS 2017 15.9.2
PJN / 19-04-2019 1. Updated copyright details
2. Updated the code to clean compile on VC 2019
PJN / 23-06-2019 1. Updated the code to clean compile when _ATL_NO_AUTOMATIC_NAMESPACE is defined.
PJN / 14-08-2019 1. Fixed some further compiler warnings when using VC 2019 Preview v16.3.0 Preview 2.0
2. Added support for new WinHttpAddRequestHeadersEx API available in latest Windows 10 SDK
PJN / 16-09-2019 1. Updated code to handle all 2XX response codes.
PJN / 03-11-2019 1. Updated initialization of various structs to use C++ 11 list initialization
PJN / 18-01-2020 1. Updated copyright details
2. Fixed more Clang-Tidy static code analysis warnings in the code.
3. Replaced BOOL with bool in various places
PJN / 01-02-2020 1. Fixed a bug in the sample app when calling the WinHttpCrackUrl. Thanks to Onur Senturk for
reporting this issue.
2. Fixed a bug in CSyncDownloader::SendRequestSync where the resources would not be released if
the download was successful. Again thanks to to Onur Senturk for reporting this issue.
PJN / 12-04-2020 1. Fixed more Clang-Tidy static code analysis warnings in the code.
PJN / 13-11-2020 1. Added support for new WinHttpReadDataEx & WinHttpQueryHeadersEx APIs available in latest
Windows 10 SDK.
PJN / 09-04-2021 1. Updated copyright details
2. Fixed more /analyze static code analysis warnings in the code.
Copyright (c) 2011 - 2021 by PJ Naughter (Web: www.naughter.com, Email: [email protected])
All rights reserved.
Copyright / Usage Details:
You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
when your product is released in binary form. You are allowed to modify the source code in any way you want
except you cannot modify the copyright details at the top of each module. If you want to distribute source
code with your application, then you are only allowed to distribute versions released by the author. This is
to maintain a single distribution point for the source code.
*/
/////////////////////////// Macros / Defines //////////////////////////////////
#ifndef __WINHTTPWRAPPERS_H__
#define __WINHTTPWRAPPERS_H__
#ifndef CWINHTTPWRAPPERS_EXT_CLASS
#define CWINHTTPWRAPPERS_EXT_CLASS
#endif //#ifndef CWINHTTPWRAPPERS_EXT_CLASS
#pragma comment(lib, "Winhttp.lib")
/////////////////////////// Includes //////////////////////////////////////////
#include <Windows.h>
#include <winhttp.h>
#include <atlstr.h>
#include <atlfile.h>
#include <string>
#include <vector>
/////////////////////////// Classes ///////////////////////////////////////////
namespace lxd::WinHTTPWrappers {
//Typedefs
using String = std::wstring;
using ByteArray = std::vector<BYTE>;
//Wrapper for a WinHttp HINTERNET handle
class CWINHTTPWRAPPERS_EXT_CLASS CHandle {
public:
//Constructors / Destructors
CHandle() noexcept : m_h(nullptr) {
}
CHandle(_In_ const CHandle&) = delete;
CHandle(_In_ CHandle&& handle) noexcept {
m_h = handle.m_h;
handle.m_h = nullptr;
}
explicit CHandle(_In_ HINTERNET h) noexcept : m_h(h) {
}
virtual ~CHandle() {
if (m_h != nullptr)
Close();
}
//Methods
CHandle& operator=(_In_ const CHandle&) = delete;
CHandle& operator=(_In_ CHandle&& handle) noexcept {
if (m_h != nullptr)
Close();
m_h = handle.m_h;
handle.m_h = nullptr;
return *this;
}
operator HINTERNET() const noexcept {
return m_h;
}
void Attach(_In_ HINTERNET h) noexcept {
#pragma warning(suppress: 26477)
ATLASSUME(m_h == nullptr);
m_h = h;
}
HINTERNET Detach() noexcept {
HINTERNET h = m_h;
m_h = nullptr;
return h;
}
void Close() noexcept {
if (m_h != nullptr) {
WinHttpCloseHandle(m_h);
m_h = nullptr;
}
}
HRESULT QueryOption(IN DWORD dwOption, _Out_writes_bytes_to_opt_(dwBufferLength, dwBufferLength) __out_data_source(NETWORK) void* pBuffer, IN OUT DWORD& dwBufferLength) noexcept {
if (!WinHttpQueryOption(m_h, dwOption, pBuffer, &dwBufferLength))
return ATL::AtlHresultFromLastError();
return S_OK;
}
HRESULT SetOption(_In_ DWORD dwOption,
_When_((dwOption == WINHTTP_OPTION_USERNAME ||
dwOption == WINHTTP_OPTION_PASSWORD ||
dwOption == WINHTTP_OPTION_PROXY_USERNAME ||
dwOption == WINHTTP_OPTION_PROXY_PASSWORD ||
dwOption == WINHTTP_OPTION_USER_AGENT),
_At_((LPCWSTR)lpBuffer, _In_reads_(dwBufferLength)))
_When_((dwOption == WINHTTP_OPTION_CLIENT_CERT_CONTEXT),
_In_reads_bytes_opt_(dwBufferLength))
_When_((dwOption != WINHTTP_OPTION_USERNAME &&
dwOption != WINHTTP_OPTION_PASSWORD &&
dwOption != WINHTTP_OPTION_PROXY_USERNAME &&
dwOption != WINHTTP_OPTION_PROXY_PASSWORD &&
dwOption != WINHTTP_OPTION_CLIENT_CERT_CONTEXT &&
dwOption != WINHTTP_OPTION_USER_AGENT),
_In_reads_bytes_(dwBufferLength))
LPVOID lpBuffer, _In_ DWORD dwBufferLength) noexcept {
#pragma warning(suppress: 6387)
if (!WinHttpSetOption(m_h, dwOption, lpBuffer, dwBufferLength))
return ATL::AtlHresultFromLastError();
return S_OK;
}
WINHTTP_STATUS_CALLBACK SetStatusCallback(_In_opt_ WINHTTP_STATUS_CALLBACK lpfnInternetCallback, _In_ DWORD dwNotificationFlags = WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS) noexcept {
return WinHttpSetStatusCallback(m_h, lpfnInternetCallback, dwNotificationFlags, NULL);
}
WINHTTP_STATUS_CALLBACK SetStatusCallback(_In_ DWORD dwNotificationFlags = WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS) noexcept {
return SetStatusCallback(_Callback, dwNotificationFlags);
}
//Member variables
HINTERNET m_h;
protected:
//Methods
static void CALLBACK _Callback(_In_ HINTERNET hInternet, _In_ DWORD_PTR dwContext, _In_ DWORD dwInternetStatus, _In_opt_ LPVOID lpvStatusInformation, _In_ DWORD dwStatusInformationLength) {
//Check to see if we have a context value
if (dwContext != 0) {
//Convert from the SDK world to the C++ world.
#pragma warning(suppress: 26429 26490)
auto pThis = reinterpret_cast<CHandle*>(dwContext);
#pragma warning(suppress: 26477)
ATLASSERT(pThis != nullptr);
//Call the virtual "OnCallback" method
#pragma warning(suppress: 26486)
const HRESULT hr = pThis->OnCallback(hInternet, dwInternetStatus, lpvStatusInformation, dwStatusInformationLength);
//If the "Callback" method failed called the "OnCallbackComplete" method
if (FAILED(hr))
#pragma warning(suppress: 26486)
pThis->OnCallbackComplete(hr, hInternet, dwInternetStatus, lpvStatusInformation, dwStatusInformationLength);
}
}
#ifdef _DEBUG
static void TraceCallback(_In_ HINTERNET hInternet, _In_ DWORD dwInternetStatus, _In_opt_ LPVOID lpvStatusInformation, _In_ DWORD dwStatusInformationLength) {
switch (dwInternetStatus) {
case WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION:
{
ATLTRACE(_T("Closing the connection to the server, Handle:%p\n"), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER:
{
ATLTRACE(_T("Successfully connected to the server:%ls, Handle:%p\n"), static_cast<LPWSTR>(lpvStatusInformation), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER:
{
ATLTRACE(_T("Connecting to the server:%ls, Handle:%p\n"), static_cast<LPWSTR>(lpvStatusInformation), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED:
{
ATLTRACE(_T("Successfully closed the connection to the server, Handle:%p\n"), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
ATLTRACE(_T("Data is available to be retrieved, Handle:%p, Data Available:%u\n"), hInternet, *(static_cast<DWORD*>(lpvStatusInformation)));
break;
}
case WINHTTP_CALLBACK_STATUS_HANDLE_CREATED:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
ATLTRACE(_T("Handle created, Handle:%p\n"), *(static_cast<HINTERNET*>(lpvStatusInformation)));
break;
}
case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
ATLTRACE(_T("Handle closing, Handle:%p\n"), *(static_cast<HINTERNET*>(lpvStatusInformation)));
break;
}
case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
{
ATLTRACE(_T("The response header has been received, Handle:%p\n"), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
ATLTRACE(_T("Received an intermediate (100 level) status code message from the server, Handle:%p, Status:%u\n"), hInternet, *(static_cast<DWORD*>(lpvStatusInformation)));
break;
}
case WINHTTP_CALLBACK_STATUS_NAME_RESOLVED:
{
ATLTRACE(_T("Successfully found the IP address of the server:%ls, Handle:%p\n"), static_cast<LPWSTR>(lpvStatusInformation), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
{
ATLTRACE(_T("Data was successfully read from the server, Data Read:%u, Handle:%p\n"), dwStatusInformationLength, hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE:
{
ATLTRACE(_T("Waiting for the server to respond to a request, Handle:%p\n"), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_REDIRECT:
{
ATLTRACE(_T("An HTTP request is about to automatically redirect the request to %ls, Handle:%p\n"), static_cast<LPWSTR>(lpvStatusInformation), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
auto pResult = static_cast<const WINHTTP_ASYNC_RESULT*>(lpvStatusInformation);
ATLTRACE(_T("An error occurred while sending an HTTP request, Error:%u, Handle:%p\n"), pResult->dwError, hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_REQUEST_SENT:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
ATLTRACE(_T("Successfully sent the information request to the server, Data Sent:%u, Handle:%p\n"), *(static_cast<DWORD*>(lpvStatusInformation)), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_RESOLVING_NAME:
{
ATLTRACE(_T("Looking up the IP address of a server name:%ls, Handle:%p\n"), static_cast<LPWSTR>(lpvStatusInformation), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
ATLTRACE(_T("Successfully received a response from the server, Data Received:%u, Handle:%p\n"), *(static_cast<DWORD*>(lpvStatusInformation)), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
const DWORD dwStatusInformation = *(static_cast<DWORD*>(lpvStatusInformation));
if (dwStatusInformation & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED) {
ATLTRACE(_T("Certification revocation checking has been enabled, but the revocation check failed to verify whether a certificate has been revoked, Handle:%p\n"), hInternet);
}
if (dwStatusInformation & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT) {
ATLTRACE(_T("SSL certificate is invalid, Handle:%p\n"), hInternet);
}
if (dwStatusInformation & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED) {
ATLTRACE(_T("SSL certificate was revoked, Handle:%p\n"), hInternet);
}
if (dwStatusInformation & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA) {
ATLTRACE(_T("The function is unfamiliar with the Certificate Authority that generated the server's certificate, Handle:%p\n"), hInternet);
}
if (dwStatusInformation & WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID) {
ATLTRACE(_T("SSL certificate common name (host name field) is incorrect, Handle:%p\n"), hInternet);
}
if (dwStatusInformation & WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID) {
ATLTRACE(_T("SSL certificate date that was received from the server is bad. The certificate is expired, Handle:%p\n"), hInternet);
}
if (dwStatusInformation & WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR) {
ATLTRACE(_T("The application experienced an internal error loading the SSL libraries, Handle:%p\n"), hInternet);
}
break;
}
case WINHTTP_CALLBACK_STATUS_SENDING_REQUEST:
{
ATLTRACE(_T("Sending the information request to the server, Handle:%p\n"), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
{
ATLTRACE(_T("The request completed successfully, Handle:%p\n"), hInternet);
break;
}
case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
{
#pragma warning(suppress: 26477)
ATLASSUME(lpvStatusInformation != nullptr);
ATLTRACE(_T("Data was successfully written to the server, Data Written:%u, Handle:%p\n"), *(static_cast<DWORD*>(lpvStatusInformation)), hInternet);
break;
}
default:
{
ATLTRACE(_T("Unknown status:%08X, Handle:%p\n"), dwInternetStatus, hInternet);
break;
}
}
}
#endif //#ifdef _DEBUG
#pragma warning(suppress: 26440)
virtual HRESULT OnCallback(_In_ HINTERNET hInternet, _In_ DWORD dwInternetStatus, _In_opt_ LPVOID lpvStatusInformation, _In_ DWORD dwStatusInformationLength) {
UNREFERENCED_PARAMETER(hInternet);
UNREFERENCED_PARAMETER(dwInternetStatus);
UNREFERENCED_PARAMETER(lpvStatusInformation);
UNREFERENCED_PARAMETER(dwStatusInformationLength);
return S_FALSE; //S_FALSE means not handled in our callback
}
#ifdef _DEBUG
static void TraceCallbackComplete(_In_ HRESULT hr, _In_ HINTERNET hInternet, _In_ DWORD dwInternetStatus, _In_opt_ LPVOID lpvStatusInformation, _In_ DWORD dwStatusInformationLength) {
UNREFERENCED_PARAMETER(lpvStatusInformation);
UNREFERENCED_PARAMETER(dwStatusInformationLength);
ATLTRACE(_T("CWinHTTPHandle::TraceCallbackComplete, HRESULT:%08X, InternetStatus:%08X, Handle:%p\n"), hr, dwInternetStatus, hInternet);
}
#endif //#ifdef _DEBUG
#pragma warning(suppress: 26440)
virtual HRESULT OnCallbackComplete(_In_ HRESULT hr, _In_ HINTERNET hInternet, _In_ DWORD dwInternetStatus, _In_opt_ LPVOID lpvStatusInformation, _In_ DWORD dwStatusInformationLength) {
UNREFERENCED_PARAMETER(hr);
UNREFERENCED_PARAMETER(hInternet);
UNREFERENCED_PARAMETER(dwInternetStatus);
UNREFERENCED_PARAMETER(lpvStatusInformation);
UNREFERENCED_PARAMETER(dwStatusInformationLength);
return E_NOTIMPL;
}
};
//Wrapper for a WinHttp resolver HINTERNET handle
class CWINHTTPWRAPPERS_EXT_CLASS CResolver : public CHandle {
public:
//Constructors / Destructors
CResolver() = default;
CResolver(_In_ const CResolver&) = delete;
CResolver(_In_ CResolver&& resolver) noexcept : CHandle(std::move(resolver)) {
}
explicit CResolver(_In_ HINTERNET h) noexcept : CHandle(h) {
}
~CResolver() = default; //NOLINT(modernize-use-override)
//Methods
CResolver& operator=(_In_ const CResolver&) = delete;
#pragma warning(suppress: 26456)
CResolver& operator=(_In_ CResolver&& resolver) noexcept {
__super::operator=(std::move(resolver));
return *this;
}
__if_exists(WinHttpGetProxyForUrlEx)
{
DWORD GetProxyForUrlEx(_In_ PCWSTR pcwszUrl, _In_ WINHTTP_AUTOPROXY_OPTIONS * pAutoProxyOptions, _In_opt_ DWORD_PTR pContext) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpGetProxyForUrlEx(m_h, pcwszUrl, pAutoProxyOptions, pContext);
}
}
__if_exists(WinHttpGetProxyForUrlEx2)
{
DWORD GetProxyForUrlEx2(_In_ PCWSTR pcwszUrl, _In_ WINHTTP_AUTOPROXY_OPTIONS * pAutoProxyOptions, _In_ DWORD cbInterfaceSelectionContext,
_In_reads_bytes_opt_(cbInterfaceSelectionContext) BYTE * pInterfaceSelectionContext, _In_opt_ DWORD_PTR pContext) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpGetProxyForUrlEx2(m_h, pcwszUrl, pAutoProxyOptions, cbInterfaceSelectionContext, pInterfaceSelectionContext, pContext);
}
}
__if_exists(WinHttpGetProxyResult)
{
DWORD GetProxyResult(_Out_ WINHTTP_PROXY_RESULT * pProxyResult) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpGetProxyResult(m_h, pProxyResult);
}
}
__if_exists(WinHttpGetProxyResultEx)
{
DWORD GetProxyResultEx(_Out_ _Out_ WINHTTP_PROXY_RESULT_EX * pProxyResultEx) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpGetProxyResultEx(m_h, pProxyResultEx);
}
}
};
//Wrapper for a WinHttp web socket handle
class CWINHTTPWRAPPERS_EXT_CLASS CWebSocket : public CHandle {
public:
//Constructors / Destructors
CWebSocket() = default;
CWebSocket(_In_ const CWebSocket&) = delete;
#pragma warning(suppress: 26495)
CWebSocket(_In_ CWebSocket&& socket) noexcept : CHandle(std::move(socket)) {
}
#pragma warning(suppress: 26495)
explicit CWebSocket(_In_ HINTERNET h) noexcept : CHandle(h) {
}
~CWebSocket() = default; //NOLINT(modernize-use-override)
//Methods
CWebSocket& operator=(_In_ const CWebSocket&) = delete;
#pragma warning(suppress: 26456)
CWebSocket& operator=(_In_ CWebSocket&& socket) noexcept {
__super::operator=(std::move(socket));
return *this;
}
#pragma warning(suppress: 26812)
DWORD Send(_In_ WINHTTP_WEB_SOCKET_BUFFER_TYPE eBufferType, _In_reads_opt_(dwBufferLength) PVOID pvBuffer, _In_ DWORD dwBufferLength) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpWebSocketSend(m_h, eBufferType, pvBuffer, dwBufferLength);
}
DWORD Receive(_Out_writes_bytes_to_(dwBufferLength, *pdwBytesRead) PVOID pvBuffer, _In_ DWORD dwBufferLength, _Out_range_(0, dwBufferLength) DWORD* pdwBytesRead, _Out_ WINHTTP_WEB_SOCKET_BUFFER_TYPE* peBufferType) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpWebSocketReceive(m_h, pvBuffer, dwBufferLength, pdwBytesRead, peBufferType);
}
DWORD Shutdown(_In_ USHORT usStatus, _In_reads_bytes_opt_(dwReasonLength) PVOID pvReason, _In_range_(0, WINHTTP_WEB_SOCKET_MAX_CLOSE_REASON_LENGTH) DWORD dwReasonLength) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpWebSocketShutdown(m_h, usStatus, pvReason, dwReasonLength);
}
DWORD WebSocketClose(_In_ USHORT usStatus, _In_reads_bytes_opt_(dwReasonLength) PVOID pvReason, _In_range_(0, WINHTTP_WEB_SOCKET_MAX_CLOSE_REASON_LENGTH) DWORD dwReasonLength) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpWebSocketClose(m_h, usStatus, pvReason, dwReasonLength);
}
DWORD QueryCloseStatus(_Out_ USHORT* pusStatus, _Out_writes_bytes_to_opt_(dwReasonLength, *pdwReasonLengthConsumed) PVOID pvReason,
_In_range_(0, WINHTTP_WEB_SOCKET_MAX_CLOSE_REASON_LENGTH) DWORD dwReasonLength, _Out_range_(0, WINHTTP_WEB_SOCKET_MAX_CLOSE_REASON_LENGTH) DWORD* pdwReasonLengthConsumed) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return WinHttpWebSocketQueryCloseStatus(m_h, pusStatus, pvReason, dwReasonLength, pdwReasonLengthConsumed);
}
//Member variables
HINTERNET m_h;
};
//Wrapper for a WinHttp Session HINTERNET handle
class CWINHTTPWRAPPERS_EXT_CLASS CSession : public CHandle {
public:
//Constructors / Destructors
CSession() = default;
CSession(_In_ const CSession&) = delete;
CSession(_In_ CSession&& session) noexcept : CHandle(std::move(session)) {
}
explicit CSession(_In_ HINTERNET h) noexcept : CHandle(h) {
}
~CSession() = default; //NOLINT(modernize-use-override)
//Methods
CSession& operator=(_In_ const CSession&) = delete;
#pragma warning(suppress: 26456)
CSession& operator=(_In_ CSession&& session) noexcept {
__super::operator=(std::move(session));
return *this;
}
HRESULT Initialize(_In_opt_z_ LPCWSTR pwszUserAgent, _In_ DWORD dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _In_opt_z_ LPCWSTR pwszProxyName = WINHTTP_NO_PROXY_NAME,
_In_opt_z_ LPCWSTR pwszProxyBypass = WINHTTP_NO_PROXY_BYPASS, _In_ DWORD dwFlags = WINHTTP_FLAG_ASYNC) noexcept {
HINTERNET hSession = WinHttpOpen(pwszUserAgent, dwAccessType, pwszProxyName, pwszProxyBypass, dwFlags);
if (hSession == nullptr)
return ATL::AtlHresultFromLastError();
Attach(hSession);
return S_OK;
}
HRESULT GetProxyForUrl(_In_ LPCWSTR lpcwszUrl, _In_ WINHTTP_AUTOPROXY_OPTIONS& AutoProxyOptions, _Out_ DWORD& dwAccessType, _Out_ String& sProxy, _Out_ String& sProxyBypass) {
WINHTTP_PROXY_INFO proxyInfo{};
if (!WinHttpGetProxyForUrl(m_h, lpcwszUrl, &AutoProxyOptions, &proxyInfo))
return ATL::AtlHresultFromLastError();
//Update the output parameters
dwAccessType = proxyInfo.dwAccessType;
#pragma warning(suppress: 6387)
sProxy = proxyInfo.lpszProxy;
#pragma warning(suppress: 6387)
sProxyBypass = proxyInfo.lpszProxyBypass;
//Free up the allocated memory
if (proxyInfo.lpszProxy != nullptr)
GlobalFree(proxyInfo.lpszProxy);
if (proxyInfo.lpszProxyBypass != nullptr)
GlobalFree(proxyInfo.lpszProxyBypass);
return S_OK;
}
HRESULT SetTimeouts(_In_ int dwResolveTimeout, _In_ int dwConnectTimeout, _In_ int dwSendTimeout, _In_ int dwReceiveTimeout) noexcept {
if (!WinHttpSetTimeouts(m_h, dwResolveTimeout, dwConnectTimeout, dwSendTimeout, dwReceiveTimeout))
return ATL::AtlHresultFromLastError();
return S_OK;
}
__if_exists(WinHttpCreateProxyResolver)
{
HRESULT CreateProxyResolver(_Inout_ CResolver & resolver) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(resolver.operator HANDLE() == nullptr);
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return ATL::AtlHresultFromWin32(WinHttpCreateProxyResolver(m_h, &resolver.m_h));
}
}
__if_exists(WinHttpResetAutoProxy)
{
HRESULT ResetAutoProxy(_In_ DWORD dwFlags) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return ATL::AtlHresultFromWin32(WinHttpResetAutoProxy(m_h, dwFlags));
}
}
__if_exists(WinHttpWriteProxySettings)
{
HRESULT WriteProxySettings(_In_ BOOL fForceUpdate, _In_ WINHTTP_PROXY_SETTINGS * pWinHttpProxySettings) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return ATL::AtlHresultFromWin32(WinHttpWriteProxySettings(m_h, fForceUpdate, pWinHttpProxySettings));
}
}
__if_exists(WinHttpReadProxySettings)
{
HRESULT ReadProxySettings(_In_opt_ PCWSTR pcwszConnectionName, _In_ BOOL fFallBackToDefaultSettings, _In_ BOOL fSetAutoDiscoverForDefaultSettings,
_Out_ DWORD * pdwSettingsVersion, _Out_ BOOL * pfDefaultSettingsAreReturned, _Out_ WINHTTP_PROXY_SETTINGS * pWinHttpProxySettings) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
return ATL::AtlHresultFromWin32(WinHttpReadProxySettings(m_h, pcwszConnectionName, fFallBackToDefaultSettings, fSetAutoDiscoverForDefaultSettings, pdwSettingsVersion, pfDefaultSettingsAreReturned, pWinHttpProxySettings));
}
}
__if_exists(WinHttpGetProxySettingsVersion)
{
HRESULT GetProxySettingsVersion(_Out_ DWORD * pdwProxySettingsVersion) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSERT(m_h != nullptr);
if (!WinHttpGetProxySettingsVersion(m_h, pdwProxySettingsVersion))
return ATL::AtlHresultFromLastError();
return S_OK;
}
}
};
//Wrapper for a WinHttp connection HINTERNET handle
class CWINHTTPWRAPPERS_EXT_CLASS CConnection : public CHandle {
public:
//Constructors / Destructors
CConnection() = default;
CConnection(_In_ const CConnection&) = delete;
CConnection(_In_ CConnection&& connection) noexcept : CHandle(std::move(connection)) {
}
explicit CConnection(_In_ HINTERNET h) noexcept : CHandle(h) {
}
~CConnection() = default; //NOLINT(modernize-use-override)
//Methods
CConnection& operator=(_In_ const CConnection&) = delete;
#pragma warning(suppress: 26456)
CConnection& operator=(_In_ CConnection&& connection) noexcept {
__super::operator=(std::move(connection));
return *this;
}
HRESULT Initialize(_In_ const CSession& session, _In_z_ LPCWSTR pwszServerName, _In_ INTERNET_PORT nServerPort = INTERNET_DEFAULT_PORT) noexcept {
HINTERNET hConnection = WinHttpConnect(session, pwszServerName, nServerPort, 0);
if (hConnection == nullptr)
return ATL::AtlHresultFromLastError();
Attach(hConnection);
return S_OK;
}
};
//Wrapper for a WinHttp request HINTERNET handle
class CWINHTTPWRAPPERS_EXT_CLASS CRequest : public CHandle {
public:
//Constructors / Destructors
CRequest() = default;
CRequest(_In_ const CRequest&) = delete;
CRequest(_In_ CRequest&& request) noexcept : CHandle(std::move(request)) {
}
explicit CRequest(_In_ HINTERNET h) noexcept : CHandle(h) {
}
~CRequest() = default; //NOLINT(modernize-use-override)
//Methods
CRequest& operator=(_In_ const CRequest&) = delete;
#pragma warning(suppress: 26456)
CRequest& operator=(_In_ CRequest&& request) noexcept {
__super::operator=(std::move(request));
return *this;
}
HRESULT Initialize(_In_ const CConnection& connection, _In_z_ LPCWSTR pwszObjectName, _In_opt_z_ LPCWSTR pwszVerb = nullptr, _In_opt_z_ LPCWSTR pwszVersion = nullptr, _In_opt_z_ LPCWSTR pwszReferrer = WINHTTP_NO_REFERER,
_In_opt_ LPCWSTR* ppwszAcceptTypes = WINHTTP_DEFAULT_ACCEPT_TYPES, _In_ DWORD dwFlags = 0) noexcept {
HINTERNET hRequest = WinHttpOpenRequest(connection, pwszVerb, pwszObjectName, pwszVersion, pwszReferrer, ppwszAcceptTypes, dwFlags);
if (hRequest == nullptr)
return ATL::AtlHresultFromLastError();
Attach(hRequest);
return S_OK;
}
HRESULT AddHeaders(
#ifdef _When_
_When_(dwHeadersLength == (DWORD)-1, _In_z_)
_When_(dwHeadersLength != (DWORD)-1, _In_reads_(dwHeadersLength)) LPCWSTR pwszHeaders,
#else
_In_ LPCWSTR pwszHeaders,
#endif
_In_ DWORD dwHeadersLength, _In_ DWORD dwModifiers) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSUME(m_h != nullptr);
if (!WinHttpAddRequestHeaders(m_h, pwszHeaders, dwHeadersLength, dwModifiers))
return ATL::AtlHresultFromLastError();
return S_OK;
}
__if_exists(WinHttpAddRequestHeadersEx)
{
DWORD AddRequestHeaders(_In_ DWORD dwModifiers, _In_ ULONGLONG ullFlags, _In_ ULONGLONG ullExtra,
_In_ DWORD cHeaders, _In_reads_(cHeaders) WINHTTP_EXTENDED_HEADER * pHeaders) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSUME(m_h != nullptr);
return WinHttpAddRequestHeadersEx(m_h, dwModifiers, ullFlags, ullExtra, cHeaders, pHeaders);
}
}
HRESULT QueryAuthSchemes(_Out_ DWORD& dwSupportedSchemes, _Out_ DWORD& dwFirstScheme, _Out_ DWORD& dwAuthTarget) noexcept {
if (!WinHttpQueryAuthSchemes(m_h, &dwSupportedSchemes, &dwFirstScheme, &dwAuthTarget))
return ATL::AtlHresultFromLastError();
return S_OK;
}
HRESULT QueryDataAvailable(__out_data_source(NETWORK) DWORD* lpdwNumberOfBytesAvailable) noexcept {
if (!WinHttpQueryDataAvailable(m_h, lpdwNumberOfBytesAvailable))
return ATL::AtlHresultFromLastError();
return S_OK;
}
HRESULT QueryHeaders(IN DWORD dwInfoLevel, IN LPCWSTR pwszName OPTIONAL, _Out_writes_bytes_to_opt_(dwBufferLength, dwBufferLength) __out_data_source(NETWORK) LPVOID lpBuffer, IN OUT DWORD& dwBufferLength, IN OUT DWORD* lpdwIndex OPTIONAL) noexcept {
if (!WinHttpQueryHeaders(m_h, dwInfoLevel, pwszName, lpBuffer, &dwBufferLength, lpdwIndex))
return ATL::AtlHresultFromLastError();
return S_OK;
}
__if_exists(WinHttpQueryHeadersEx)
{
#pragma warning(suppress: 26476)
HRESULT QueryHeadersEx(_In_ DWORD dwInfoLevel, _In_ ULONGLONG ullFlags, _In_ UINT uiCodePage, _Inout_opt_ PDWORD pdwIndex, _In_opt_ PWINHTTP_HEADER_NAME pHeaderName, _Out_writes_bytes_to_opt_(*pdwBufferLength, *pdwBufferLength) PVOID pBuffer,
_Inout_ PDWORD pdwBufferLength, _Out_writes_opt_(*pdwHeadersCount) PWINHTTP_EXTENDED_HEADER * ppHeaders, _Out_ PDWORD pdwHeadersCount) noexcept {
#pragma warning(suppress: 6001)
if (!WinHttpQueryHeadersEx(m_h, dwInfoLevel, ullFlags, uiCodePage, pdwIndex, pHeaderName, pBuffer, pdwBufferLength, ppHeaders, pdwHeadersCount))
return ATL::AtlHresultFromLastError();
return S_OK;
}
}
HRESULT ReadData(_Out_writes_bytes_to_(dwNumberOfBytesToRead, *lpdwNumberOfBytesRead) __out_data_source(NETWORK) LPVOID lpBuffer, IN DWORD dwNumberOfBytesToRead, OUT DWORD* lpdwNumberOfBytesRead) noexcept {
if (!WinHttpReadData(m_h, lpBuffer, dwNumberOfBytesToRead, lpdwNumberOfBytesRead))
return ATL::AtlHresultFromLastError();
return S_OK;
}
__if_exists(WinHttpReadDataEx)
{
HRESULT ReadDataEx(_Out_writes_bytes_to_(dwNumberOfBytesToRead, *lpdwNumberOfBytesRead) __out_data_source(NETWORK) LPVOID lpBuffer, IN DWORD dwNumberOfBytesToRead, OUT DWORD * lpdwNumberOfBytesRead,
IN ULONGLONG ullFlags, IN DWORD cbProperty, _In_reads_bytes_opt_(cbProperty) PVOID pvProperty) noexcept {
if (!WinHttpReadDataEx(m_h, lpBuffer, dwNumberOfBytesToRead, lpdwNumberOfBytesRead, ullFlags, cbProperty, pvProperty))
return ATL::AtlHresultFromLastError();
return S_OK;
}
}
HRESULT ReceiveResponse() noexcept {
if (!WinHttpReceiveResponse(m_h, nullptr))
return ATL::AtlHresultFromLastError();
return S_OK;
}
HRESULT SendRequest(_In_reads_opt_(dwHeadersLength) LPCWSTR pwszHeaders = WINHTTP_NO_ADDITIONAL_HEADERS, _In_ DWORD dwHeadersLength = 0, _In_reads_bytes_opt_(dwOptionalLength) LPVOID lpOptional = WINHTTP_NO_REQUEST_DATA, _In_ DWORD dwOptionalLength = 0, _In_ DWORD dwTotalLength = 0, _In_ DWORD_PTR dwContext = 0) noexcept {
if (!WinHttpSendRequest(m_h, pwszHeaders, dwHeadersLength, lpOptional, dwOptionalLength, dwTotalLength, dwContext))
return ATL::AtlHresultFromLastError();
return S_OK;
}
HRESULT SetCredentials(_In_ DWORD AuthTargets, _In_ DWORD AuthScheme, _In_ LPCWSTR pwszUserName, _In_ LPCWSTR pwszPassword) noexcept {
if (!WinHttpSetCredentials(m_h, AuthTargets, AuthScheme, pwszUserName, pwszPassword, nullptr))
return ATL::AtlHresultFromLastError();
return S_OK;
}
HRESULT SetTimeouts(_In_ int dwResolveTimeout, _In_ int dwConnectTimeout, _In_ int dwSendTimeout, _In_ int dwReceiveTimeout) noexcept {
if (!WinHttpSetTimeouts(m_h, dwResolveTimeout, dwConnectTimeout, dwSendTimeout, dwReceiveTimeout))
return ATL::AtlHresultFromLastError();
return S_OK;
}
HRESULT WriteData(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) LPCVOID lpBuffer, _In_ DWORD dwNumberOfBytesToWrite, _Out_opt_ DWORD* lpdwNumberOfBytesWritten) noexcept {
if (!WinHttpWriteData(m_h, lpBuffer, dwNumberOfBytesToWrite, lpdwNumberOfBytesWritten))
return ATL::AtlHresultFromLastError();
return S_OK;
}
CWebSocket WebSocketCompleteUpgrade(_In_opt_ DWORD_PTR pContext) noexcept {
//Validate our parameters
#pragma warning(suppress: 26477)
ATLASSUME(m_h != nullptr);
return CWebSocket(WinHttpWebSocketCompleteUpgrade(m_h, pContext));
}
};
//Wrapper for a simple WinHttp async download
class CWINHTTPWRAPPERS_EXT_CLASS CAsyncDownloader : public CRequest {
public:
//Constructors / Destructors
CAsyncDownloader() noexcept : m_dwProxyPreauthenticationScheme(WINHTTP_AUTH_SCHEME_NEGOTIATE),
m_dwHTTPPreauthenticationScheme(WINHTTP_AUTH_SCHEME_NEGOTIATE),
m_bProxyPreauthentication(true),
m_bHTTPPreauthentication(true),
m_nDownloadStartPos(0),
m_bNoURLRedirect(false),
m_lpRequest(nullptr),
m_dwRequestSize(0),
m_dbLimit(0),
m_dwReadBufferLength(0),
m_dwWriteBufferLength(0),
m_nFileToUploadSize(0),
m_nFileToUploadIndex(0),
m_dwLastStatusCode(0),
m_bValidLastStatusCode(false),
m_nContentLength(-1),
m_pOptionalBuffer(nullptr),
m_dwOptionalBufferLength(0),
m_dwProxyAuthScheme(0),
m_nTotalBytesRead(0),
m_dwStartTicksDownload(0),
m_bUsingObjectStatusCallback(false) {
}
CAsyncDownloader(const CAsyncDownloader&) = delete;
CAsyncDownloader(CAsyncDownloader&&) = delete;
~CAsyncDownloader() //NOLINT(modernize-use-override)
{
if (m_bUsingObjectStatusCallback) {
// SetStatusCallback(nullptr, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS);
m_bUsingObjectStatusCallback = false;
}
}
//Methods
CAsyncDownloader& operator=(const CAsyncDownloader&) = delete;
CAsyncDownloader& operator=(CAsyncDownloader&&) = delete;
#pragma warning(suppress: 26434 26477 26487)
HRESULT Initialize(_In_ const CConnection& connection, _In_z_ LPCWSTR pwszObjectName, _In_opt_z_ LPCWSTR pwszVerb = nullptr, _In_opt_z_ LPCWSTR pwszVersion = nullptr, _In_opt_z_ LPCWSTR pwszReferrer = WINHTTP_NO_REFERER,
_In_opt_ LPCWSTR* ppwszAcceptTypes = WINHTTP_DEFAULT_ACCEPT_TYPES, _In_ DWORD dwFlags = 0, _In_ DWORD dwBufferLength = 8096, _In_ DWORD dwShareMode = 0) {
//Initialize the critical section
HRESULT hr = m_cs.Init();
if (FAILED(hr))
return hr;
//Let the base class do its thing
hr = __super::Initialize(connection, pwszObjectName, pwszVerb, pwszVersion, pwszReferrer, ppwszAcceptTypes, dwFlags);
if (FAILED(hr))
return hr;
//Disable redirects if required
if (m_bNoURLRedirect) {
DWORD dwOptionValue = WINHTTP_DISABLE_REDIRECTS;
hr = SetOption(WINHTTP_DISABLE_REDIRECTS, &dwOptionValue, sizeof(dwOptionValue));
if (FAILED(hr))
return hr;
}
//Hook up the callback function
if (SetStatusCallback() == WINHTTP_INVALID_STATUS_CALLBACK)
return ATL::AtlHresultFromLastError();
//Release our resources if currently in use
ReleaseResources();
//Serialize access to our member variables
ATL::CCritSecLock sl(m_cs.m_sec, true);
m_bUsingObjectStatusCallback = true;
//Allocate the receive buffer
if (!m_ReadBuffer.Allocate(dwBufferLength))
return E_OUTOFMEMORY;
m_dwReadBufferLength = dwBufferLength;
//Open up the file for downloading if necessary