File: CimWinHttp.cpp

package info (click to toggle)
sblim-wbemcli 1.6.3-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,084 kB
  • sloc: cpp: 28,424; sh: 3,892; python: 2,094; makefile: 108
file content (481 lines) | stat: -rw-r--r-- 11,669 bytes parent folder | download | duplicates (3)
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
/*
 * $Id: CimWinHttp.cpp,v 1.5 2008/12/12 00:51:59 tyreld Exp $
 *
 * CimWinHttp.cpp
 *
 * (C) Copyright IBM Corp. 2004, 2008
 *
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 *
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Author:       Adrian Schuur <schuur@de.ibm.com>
 * Contributors: Viktor Mihajlovski <mihajlov@de.ibm.com>
 *               Markus Mueller <markus_mueller@de.ibm.com>
 *               Steve Shepherd <steve.shepherd@configuresoft.com>
 *               Heidi Neumann  <heidineu@de.ibm.com>
 *
 * Description: Line command interface to DMTF conforming WBEM servers
*/
#include "stdafx.h"
#include "CimWinHttp.h"

////////////////////////////////////////////////////////////////////////
//
//  CimomWinHttp::CimomWinHttp( )
//  CimomWinHttp::~CimomWinHttp( )
//
//  Default constructor & destructor.
//
////////////////////////////////////////////////////////////////////////
extern int useNl;

CimomWinHttp::CimomWinHttp()
{
	m_hSession = NULL;
	m_hConnect = NULL;
	m_hRequest = NULL;
	m_lpPayload = NULL;
	m_dwPayloadSize = 0;
}

CimomWinHttp::~CimomWinHttp()
{
	if (m_lpPayload) delete m_lpPayload;
	if (m_hRequest)	::WinHttpCloseHandle(m_hRequest);
	if (m_hConnect)	::WinHttpCloseHandle(m_hConnect);
	if (m_hSession)	::WinHttpCloseHandle(m_hSession);
}

////////////////////////////////////////////////////////////////////////
//
//  CimomWinHttp::SetTimeouts( )
//
//  Change the timeouts for HTTP messages.
//
////////////////////////////////////////////////////////////////////////
bool CimomWinHttp::SetTimeouts(int Connect, int Send, int Receive)
{
	bool bReturn = false;

	if (m_hSession)
	{
		if (WinHttpSetTimeouts(m_hSession, 0, Connect, Send, Receive))
		{
			bReturn = true;
		}
	}

	return bReturn;
}

////////////////////////////////////////////////////////////////////////
//
//  CimomWinHttp::addPayload( )
//
//  Add the message payload to the HTTP message.
//
////////////////////////////////////////////////////////////////////////
void CimomWinHttp::addPayload(char *pl)
{
	addPayload(pl, strlen(pl));
}

void CimomWinHttp::addPayload(LPCVOID lpPayload, DWORD dwSize)
{
	if (m_lpPayload) delete m_lpPayload;
	m_lpPayload = new char[dwSize];
	m_dwPayloadSize = dwSize;
	if (m_lpPayload)
	{
		memcpy(m_lpPayload, lpPayload, dwSize);
	}
	else
	{
		throw("addPayload failed: could not allocate a buffer.");
	}
}

////////////////////////////////////////////////////////////////////////
//
//  CimomWinHttp::genRequest( )
//
//  Create the HTTP message.
//
////////////////////////////////////////////////////////////////////////
void CimomWinHttp::genRequest(URL &url, const char *op, bool cls, bool keys)
{
	if (!supportsSSL() && url.scheme == "https")
		throw HttpException("WinHttp does not support https urls.");
	
	DWORD dwLen, dwMBLen;
	WCHAR pszSingle[512];
	BOOL  bResult = FALSE;
	LPCWSTR sHeaders =	L"Content-type: application/xml; charset=\"utf-8\"\r\n"
						L"Connection: Keep-Alive, TE\r\n"
						L"CIMProtocolVersion: 1.0\r\n"
						L"CIMOperation: MethodCall\r\n";

	m_hSession = ::WinHttpOpen(L"EcmXpdTool", WINHTTP_ACCESS_TYPE_NO_PROXY,
						WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);

	if (!m_hSession)
	{
		throw("::WinHttpOpen failed");
	}


	INTERNET_PORT iPort;

	if (sscanf(url.port, "%hui", &iPort) != 1)
	{
		iPort = 5988;
	}

	dwLen = strlen(url.host) + 1;
	wchar_t *wpHost = static_cast<wchar_t*>(malloc((dwLen+1)*sizeof(wchar_t)));
	if (!wpHost)
	{
		throw("Insufficient memory available");
	}
	dwMBLen = MultiByteToWideChar(CP_UTF8, 0, url.host, dwLen, wpHost, dwLen);
	m_hConnect = ::WinHttpConnect(m_hSession, wpHost, iPort, 0);
	free(wpHost);

	if (!m_hConnect || dwMBLen == 0)
	{
		throw("::WinHttpConnect failed");
	}

	// Create an HTTP Request handle.
	m_hRequest = ::WinHttpOpenRequest(m_hConnect, L"POST", L"/cimom",
									   NULL, WINHTTP_NO_REFERER,
									   WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
	if (!m_hRequest)
	{
		throw("::WinHttpOpenRequest failed");
	}

	bResult = ::WinHttpAddRequestHeaders(m_hRequest, sHeaders,
									ULONG_MAX, WINHTTP_ADDREQ_FLAG_ADD);


	dwLen = strlen(op) + 1;
	wchar_t *wpCimOp = static_cast<wchar_t*>(malloc((dwLen+1)*sizeof(wchar_t)));
	if (!wpCimOp)
	{
		throw("Insufficient memory available");
	}
	dwMBLen = MultiByteToWideChar(CP_UTF8, 0, op, dwLen, wpCimOp, dwLen);

	memset(pszSingle, '\0', sizeof(pszSingle));
	wcscat(pszSingle, L"CIMMethod: ");
	wcscat(pszSingle, wpCimOp);
	wcscat(pszSingle, L"\r\n");
	free(wpCimOp);

	bResult = ::WinHttpAddRequestHeaders(m_hRequest, pszSingle,
									ULONG_MAX, WINHTTP_ADDREQ_FLAG_ADD);

	string sb;
	url.ns.toStringBuffer(sb,"%2F");
 	if (cls)
	{
		sb = sb + "%3A" + url.cName;
		if (keys)
		{
			char sep = '.';
			int t=useNl;
			useNl=0;
			for ( unsigned i = 0 ; i < url.keys.size() ; i++ )
			{
				string sk;
				url.keys[i].toStringBuffer(sk, "");
				sb = sb + sep + sk;
				sep = ',';
			}
			useNl=t;
		}
	}
	dwLen = strlen(sb.c_str()) + 1;
	wchar_t *wpNS = static_cast<wchar_t*>(malloc((dwLen+1)*sizeof(wchar_t)));
	if (!wpNS)
	{
		throw("Insufficient memory available");
	}
	dwMBLen = MultiByteToWideChar(CP_UTF8, 0, sb.c_str(), dwLen, wpNS, dwLen);

	memset(pszSingle, '\0', sizeof(pszSingle));
	wcscat(pszSingle, L"CIMObject: ");
	wcscat(pszSingle, wpNS);
	wcscat(pszSingle, L"\r\n");
	free(wpNS);

	bResult = ::WinHttpAddRequestHeaders(m_hRequest, pszSingle,
									ULONG_MAX, WINHTTP_ADDREQ_FLAG_ADD);

	dwLen = strlen(url.password) + 1;
	wchar_t *wpPswd = static_cast<wchar_t*>(malloc((dwLen+1)*sizeof(wchar_t)));
	if (!wpPswd)
	{
		throw("Insufficient memory available");
	}
	dwMBLen = MultiByteToWideChar(CP_UTF8, 0, url.password, dwLen, wpPswd, dwLen);

	dwLen = strlen(url.user) + 1;
	wchar_t *wpUser = static_cast<wchar_t*>(malloc((dwLen+1)*sizeof(wchar_t)));
	if (!wpUser)
	{
		throw("Insufficient memory available");
	}
	dwMBLen = MultiByteToWideChar(CP_UTF8, 0, url.user, dwLen, wpUser, dwLen);

	bResult = WinHttpSetCredentials(m_hRequest, WINHTTP_AUTH_TARGET_SERVER,
									WINHTTP_AUTH_SCHEME_BASIC,
									wpUser, wpPswd, NULL);
	free(wpPswd);
	free(wpUser);
}

////////////////////////////////////////////////////////////////////////
//
//  CimomWinHttp::getResponse( )
//
//  Send the message and get the response.
//
////////////////////////////////////////////////////////////////////////
#ifdef OLD
string CimomWinHttp::getResponse()
{
	BOOL bResult;
	LPSTR pszOutBuffer = NULL;

    if (m_hRequest)
	{
        bResult = WinHttpSendRequest(m_hRequest,
                                       WINHTTP_NO_ADDITIONAL_HEADERS, 0,
                                       WINHTTP_NO_REQUEST_DATA, 0,
                                       m_dwPayloadSize, 0);

		// Write data to the server.
		if (bResult)
		{
			DWORD dwBytesWritten = 0;
			bResult = WinHttpWriteData(m_hRequest, m_lpPayload,
										m_dwPayloadSize, &dwBytesWritten);
		}

		// End the request.
		if (bResult)
		{
			bResult = WinHttpReceiveResponse(m_hRequest, NULL);
		}

		// Keep checking for data until there is nothing left.
		if (bResult)
		{
			DWORD dwContentLength = 0;
			DWORD dwCLSize = sizeof(dwContentLength);

			if (!WinHttpQueryHeaders(m_hRequest,
					WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER,
					WINHTTP_HEADER_NAME_BY_INDEX, &dwContentLength, &dwCLSize,
					WINHTTP_NO_HEADER_INDEX))
			{
				DWORD dwLastError = ::GetLastError();
				LPVOID lpvMessageBuffer = NULL;
				DWORD dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
								FORMAT_MESSAGE_FROM_HMODULE |
								FORMAT_MESSAGE_FROM_SYSTEM;

				if (::FormatMessage(dwFlags, m_hRequest, dwLastError, 0,
									(LPTSTR)&lpvMessageBuffer, 10, NULL) > 0)
				{
					throw((char *)lpvMessageBuffer);
				}
				else
				{
					throw("WinHttpQueryHeaders() failed");
				}
			}

			if (dwContentLength > 0)
			{
				DWORD dwSize = 0;
				DWORD dwTotal = 0;

				// Allocate space for the buffer.
				pszOutBuffer = new char[dwContentLength+1];
				if (!pszOutBuffer)
				{
					throw("Out of memory");
				}
				else
				{
					::ZeroMemory(pszOutBuffer, dwContentLength+1);
					do
					{
						// Check for available data.
						dwSize = 0;
						if (!WinHttpQueryDataAvailable(m_hRequest, &dwSize))
						{
							throw("WinHttpQueryDataAvailable failed");
						}

						// Read the Data.
						DWORD dwDownloaded = 0;
						if (!WinHttpReadData(m_hRequest,
												(LPVOID)(pszOutBuffer+dwTotal),
												dwSize, &dwDownloaded))
						{
							throw("WinHttpReadData failed");
						}
						else
						{
							dwTotal += dwSize;
						}

					} while (dwSize>0);

					// NULL terminate
					pszOutBuffer[dwTotal] = '\0';
				}
			}
		}

		// Report any errors.
		if (!bResult)
		{
			throw("GetResponse failed");
		}
	}
	else
	{
		throw("GetResponse failed: Request object not prepared.");
	}

   return (char *)(pszOutBuffer ? pszOutBuffer : "");
}
#endif	/* OLD */

////////////////////////////////////////////////////////////////////////
//
//  CimomWinHttp::getResponse( )
//
//  Send the message and get the response.
//
////////////////////////////////////////////////////////////////////////
string CimomWinHttp::getResponse()
{
	BOOL bResult;
    LPSTR pszOutBuffer = NULL;

	if (m_hRequest)
	{
        bResult = WinHttpSendRequest(m_hRequest,
                                       WINHTTP_NO_ADDITIONAL_HEADERS, 0,
                                       WINHTTP_NO_REQUEST_DATA, 0,
                                       m_dwPayloadSize, 0);

		// Write data to the server.
		if (bResult)
		{
			DWORD dwBytesWritten = 0;
			bResult = WinHttpWriteData(m_hRequest, m_lpPayload,
										m_dwPayloadSize, &dwBytesWritten);
		}

		// End the request.
		if (bResult)
		{
			bResult = WinHttpReceiveResponse(m_hRequest, NULL);
		}

		// Keep checking for data until there is nothing left.
		if (bResult)
		{
			DWORD dwSize = 0;
			DWORD dwTotal = 0;

			do 
			{
				// Check for available data.
				dwSize = 0;
				if (!WinHttpQueryDataAvailable(m_hRequest, &dwSize))
				{
					throw("WinHttpQueryDataAvailable failed");
				}

				if (dwSize <= 0)
				{
					continue;
				}

				// Allocate space for the buffer.
				LPSTR pszNewBuffer = new char[dwSize + 1];
				if (!pszNewBuffer)
				{
					throw("Out of memory");
				}
				else
				{
					DWORD dwDownloaded = 0;

					// Read the Data.
					::ZeroMemory(pszNewBuffer, dwSize + 1);

					if (!WinHttpReadData(m_hRequest, (LPVOID)pszNewBuffer, 
										  dwSize, &dwDownloaded))
					{
						throw("WinHttpReadData failed");
					}

					if (!pszOutBuffer)
					{
						pszOutBuffer = pszNewBuffer;
					}
					else
					{
						LPSTR pszTmpBuffer = new char[dwTotal + dwSize + 1];
						if (!pszTmpBuffer)
						{
							throw("Out of memory");
						}

						::CopyMemory(pszTmpBuffer, pszOutBuffer, dwTotal);
						::CopyMemory(pszTmpBuffer + dwTotal, pszNewBuffer, dwSize);

						delete [] pszOutBuffer;
						delete [] pszNewBuffer;

						pszOutBuffer = pszTmpBuffer;
					}
					dwTotal += dwSize;
				}
			} while (dwSize > 0);
		}

		// Report any errors.
		if (!bResult)
		{
			throw("GetResponse failed");
		}
	}
	else
	{
		throw("GetResponse failed: Request object not prepared.");
	}

   return (char *)(pszOutBuffer ? pszOutBuffer : "");
}

void CimomWinHttp::setClientCertificates(const char * cacert, int noverify,
					 const char * certificate,
					 const char * key) 
{
   if (!supportsSSL())
      throw HttpException("CimWinHttp does not support https urls.");
}