-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWinHttpWrapper.cpp
More file actions
429 lines (382 loc) · 13.4 KB
/
WinHttpWrapper.cpp
File metadata and controls
429 lines (382 loc) · 13.4 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
// The MIT License (MIT)
// WinHTTP Wrapper 1.0
// Copyright (C) 2020, by Wong Shao Voon (shaovoon@yahoo.com)
//
// http://opensource.org/licenses/MIT
#include "WinHttpWrapper.h"
#include <winhttp.h>
// #pragma comment(lib, "Winhttp.lib")
void WinHttpWrapper::HttpRequest::setup(const std::wstring& domain,
int port,
bool secure,
const std::wstring& user_agent,
const std::wstring& proxy_username,
const std::wstring& proxy_password,
const std::wstring& server_username,
const std::wstring& server_password)
{
m_Domain = domain;
m_Port = port;
m_Secure = secure;
m_UserAgent = user_agent;
m_ProxyUsername = proxy_username;
m_ProxyPassword = proxy_password;
m_ServerUsername = server_username;
m_ServerPassword = server_password;
}
bool WinHttpWrapper::HttpRequest::Get(
const std::wstring& rest_of_path,
const std::wstring& requestHeader,
HttpResponse& response)
{
static const std::wstring verb = L"GET";
static std::string body;
return Request(
verb,
rest_of_path,
requestHeader,
body,
response);
}
bool WinHttpWrapper::HttpRequest::Post(
const std::wstring& rest_of_path,
const std::wstring& requestHeader,
const std::string& body,
HttpResponse& response)
{
static const std::wstring verb = L"POST";
return Request(
verb,
rest_of_path,
requestHeader,
body,
response);
}
bool WinHttpWrapper::HttpRequest::Put(
const std::wstring& rest_of_path,
const std::wstring& requestHeader,
const std::string& body,
HttpResponse& response)
{
static const std::wstring verb = L"PUT";
return Request(
verb,
rest_of_path,
requestHeader,
body,
response);
}
bool WinHttpWrapper::HttpRequest::Delete(
const std::wstring& rest_of_path,
const std::wstring& requestHeader,
const std::string& body,
HttpResponse& response)
{
static const std::wstring verb = L"DELETE";
return Request(
verb,
rest_of_path,
requestHeader,
body,
response);
}
bool WinHttpWrapper::HttpRequest::Request(
const std::wstring& verb,
const std::wstring& rest_of_path,
const std::wstring& requestHeader,
const std::string& body,
HttpResponse& response)
{
return http(verb, m_UserAgent, m_Domain,
rest_of_path, m_Port, m_Secure,
requestHeader, body,
response.text, response.header,
response.statusCode, response.error,
m_ProxyUsername, m_ProxyPassword,
m_ServerUsername, m_ServerPassword);
}
bool WinHttpWrapper::HttpRequest::http(const std::wstring& verb, const std::wstring& user_agent, const std::wstring& domain,
const std::wstring& rest_of_path, int port, bool secure,
const std::wstring& requestHeader, const std::string& body,
std::string& text, std::wstring& responseHeader, DWORD& dwStatusCode, std::wstring& error,
const std::wstring& szProxyUsername, const std::wstring& szProxyPassword,
const std::wstring& szServerUsername, const std::wstring& szServerPassword)
{
DWORD dwSupportedSchemes;
DWORD dwFirstScheme;
DWORD dwSelectedScheme;
DWORD dwTarget;
DWORD dwLastStatus = 0;
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
BOOL bResults = FALSE;
HINTERNET hSession = NULL;
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
BOOL bDone = FALSE;
DWORD dwProxyAuthScheme = 0;
dwStatusCode = 0;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen(user_agent.c_str(),
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
// Specify an HTTP server.
if (hSession)
{
hConnect = WinHttpConnect(hSession, domain.c_str(), port, 0);
}
else
{
error = L"WinHttpOpen fails!";
return false;
}
// Create an HTTP request handle.
if (hConnect)
{
DWORD flag = secure ? WINHTTP_FLAG_SECURE : 0;
hRequest = WinHttpOpenRequest(hConnect, verb.c_str(), rest_of_path.c_str(),
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH | flag);
}
else
{
WinHttpCloseHandle(hSession);
error = L"WinHttpConnect fails!";
return false;
}
if (hRequest == NULL)
bDone = TRUE;
while (!bDone)
{
// If a proxy authentication challenge was responded to, reset
// those credentials before each SendRequest, because the proxy
// may require re-authentication after responding to a 401 or
// to a redirect. If you don't, you can get into a
// 407-401-407-401- loop.
if (dwProxyAuthScheme != 0 && szProxyUsername != L"")
{
bResults = WinHttpSetCredentials(hRequest,
WINHTTP_AUTH_TARGET_PROXY,
dwProxyAuthScheme,
szProxyUsername.c_str(),
szProxyPassword.c_str(),
NULL);
if (!bResults)
{
error = L"WinHttpSetCredentials fails!";
}
}
// Send a request.
if (hRequest)
{
if (requestHeader.empty())
{
bResults = WinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
(LPVOID)body.data(), body.size(),
body.size(), 0);
}
else
{
bResults = WinHttpSendRequest(hRequest,
requestHeader.c_str(), requestHeader.size(),
(LPVOID)body.data(), body.size(),
body.size(), 0);
}
if (!bResults)
{
error = L"WinHttpSendRequest fails!";
}
}
// End the request.
if (bResults)
{
bResults = WinHttpReceiveResponse(hRequest, NULL);
if (!bResults)
{
error = L"WinHttpReceiveResponse fails!";
}
}
// Resend the request in case of
// ERROR_WINHTTP_RESEND_REQUEST error.
if (!bResults && GetLastError() == ERROR_WINHTTP_RESEND_REQUEST)
continue;
// Check the status code.
if (bResults)
{
dwSize = sizeof(dwStatusCode);
bResults = WinHttpQueryHeaders(hRequest,
WINHTTP_QUERY_STATUS_CODE |
WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&dwStatusCode,
&dwSize,
WINHTTP_NO_HEADER_INDEX);
if (!bResults)
{
error = L"WinHttpQueryHeaders fails!";
}
// Get response header
WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX, NULL,
&dwSize, WINHTTP_NO_HEADER_INDEX);
// Allocate memory for the buffer.
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
responseHeader.resize(dwSize + 1);
// Now, use WinHttpQueryHeaders to retrieve the header.
bResults = WinHttpQueryHeaders(hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
(LPVOID) responseHeader.data(), &dwSize,
WINHTTP_NO_HEADER_INDEX);
}
}
// Keep checking for data until there is nothing left.
if (bResults)
{
switch (dwStatusCode)
{
case 200:
{
std::string temp;
text = "";
do
{
// Check for available data.
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
{
error = L"Error in WinHttpQueryDataAvailable: ";
error += std::to_wstring(GetLastError());
}
if (dwSize == 0)
break;
// Allocate space for the buffer.
temp = "";
temp.resize(dwSize);
// Read the data.
ZeroMemory((void*)(&temp[0]), dwSize);
if (!WinHttpReadData(hRequest, (LPVOID)(&temp[0]),
dwSize, &dwDownloaded))
{
error = L"Error in WinHttpReadData: ";
error += std::to_wstring(GetLastError());
}
else
{
text += temp;
}
} while (dwSize > 0);
}
bDone = TRUE;
break;
case 401:
// The server requires authentication.
//printf(" The server requires authentication. Sending credentials...\n");
// Obtain the supported and preferred schemes.
bResults = WinHttpQueryAuthSchemes(hRequest,
&dwSupportedSchemes,
&dwFirstScheme,
&dwTarget);
if (!bResults)
{
error = L"WinHttpQueryAuthSchemes in case 401 fails!";
}
// Set the credentials before resending the request.
if (bResults)
{
dwSelectedScheme = ChooseAuthScheme(dwSupportedSchemes);
if (dwSelectedScheme == 0)
bDone = TRUE;
else
{
bResults = WinHttpSetCredentials(hRequest,
dwTarget,
dwSelectedScheme,
szServerUsername.c_str(),
szServerPassword.c_str(),
NULL);
if (!bResults)
{
error = L"WinHttpSetCredentials in case 401 fails!";
}
}
}
// If the same credentials are requested twice, abort the
// request. For simplicity, this sample does not check
// for a repeated sequence of status codes.
if (dwLastStatus == 401)
bDone = TRUE;
break;
case 407:
// The proxy requires authentication.
//printf("The proxy requires authentication. Sending credentials...\n");
// Obtain the supported and preferred schemes.
bResults = WinHttpQueryAuthSchemes(hRequest,
&dwSupportedSchemes,
&dwFirstScheme,
&dwTarget);
if (!bResults)
{
error = L"WinHttpQueryAuthSchemes in case 407 fails!";
}
// Set the credentials before resending the request.
if (bResults)
dwProxyAuthScheme = ChooseAuthScheme(dwSupportedSchemes);
// If the same credentials are requested twice, abort the
// request. For simplicity, this sample does not check
// for a repeated sequence of status codes.
if (dwLastStatus == 407)
bDone = TRUE;
break;
default:
// The status code does not indicate success.
error = L"Error. Status code returned:";
error += std::to_wstring(dwStatusCode);
bDone = TRUE;
}
}
// Keep track of the last status code.
dwLastStatus = dwStatusCode;
// If there are any errors, break out of the loop.
if (!bResults)
bDone = TRUE;
}
// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);
// Report any errors.
if (!bResults)
return false;
return true;
}
DWORD WinHttpWrapper::HttpRequest::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.
//
// Thus, this sample code does not use Basic authentication
// because Basic authentication exposes the client's username
// and password to anyone monitoring the connection.
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;
}