Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2286 lines
65 KiB

  1. /****************************************************************************
  2. Copyright information : Copyright (c) 1998-1999 Microsoft Corporation
  3. File Name : helpers.cpp
  4. Project Name : WMI Command Line
  5. Author Name : Ch.Sriramachandramurthy
  6. Date of Creation (dd/mm/yy) : 27th-September-2000
  7. Version Number : 1.0
  8. Brief Description : This file has all the global function definitions
  9. Revision History :
  10. Last Modified By : Ch Sriramachandramurthy
  11. Last Modified Date : 03-March-2001
  12. *****************************************************************************/
  13. #include "Precomp.h"
  14. #include "CommandSwitches.h"
  15. #include "GlobalSwitches.h"
  16. #include "HelpInfo.h"
  17. #include "ErrorLog.h"
  18. #include "ParsedInfo.h"
  19. #include "CmdTokenizer.h"
  20. #include "CmdAlias.h"
  21. #include "ErrorInfo.h"
  22. #include "WmiCliXMLLog.h"
  23. #include "ParserEngine.h"
  24. #include "ExecEngine.h"
  25. #include "FormatEngine.h"
  26. #include "WmiCmdLn.h"
  27. #include <io.h>
  28. /*----------------------------------------------------------------------------
  29. Name :CompareTokens
  30. Synopsis :It compares the two tokens passed to it as input
  31. arguments and returns a BOOL value ,
  32. TRUE if they are equal
  33. FALSE if not equal.
  34. Type :Global Function
  35. Input parameter(s):
  36. pszToken1- String type, Contains the first string of the two
  37. string to be compared
  38. pszToken2- String type, Contains the second string of the two
  39. string to be compared
  40. Output parameter(s):None
  41. Return Type :BOOL
  42. Global Variables :None
  43. Calling Syntax :CompareTokens(pszToken1,pszToken2)
  44. Notes :None
  45. ----------------------------------------------------------------------------*/
  46. BOOL CompareTokens(_TCHAR* pszToken1, _TCHAR* pszToken2)
  47. {
  48. return (CSTR_EQUAL == CompareString(LOCALE_SYSTEM_DEFAULT,
  49. NORM_IGNORECASE | NORM_IGNOREWIDTH,
  50. pszToken1, (pszToken1) ? lstrlen(pszToken1) : 0,
  51. pszToken2, (pszToken2) ? lstrlen(pszToken2) : 0))
  52. ? TRUE : FALSE;
  53. }
  54. /*----------------------------------------------------------------------------
  55. Name :Connect
  56. Synopsis :To connect to WMI namespace on a given server with the
  57. set of input user credentials.
  58. Type :Global Function
  59. Input parameter(s):
  60. pILocator - Locator object
  61. bstrNS - Namespae to be connected to
  62. bstrUser - User name with which to connect
  63. bstrPwd - Password for the user name with which to connect
  64. bstrLocale - Locale specified
  65. Output parameters :
  66. pISvc - WMI services object
  67. Return Type :HRESULT
  68. Global Variables :None
  69. Calling Syntax :Connect(pILocator, &pISvc, bstrNS, bstrUser, bstPwd,
  70. bstrLocale)
  71. Notes :None
  72. ----------------------------------------------------------------------------*/
  73. HRESULT Connect(IWbemLocator* pILocator, IWbemServices** pISvc,
  74. BSTR bstrNS, BSTR bstrUser, BSTR bstrPwd,
  75. BSTR bstrLocale, CParsedInfo& rParsedInfo)
  76. {
  77. HRESULT hr = S_OK;
  78. BSTR bstrPass = NULL;
  79. // If the user name is not NULL and the password is
  80. // a) NULL, treat the password as BLANK
  81. // b) not NULL, treat the password as it is.
  82. if (bstrUser)
  83. {
  84. if (!bstrPwd)
  85. {
  86. bstrPass = ::SysAllocString(L"");
  87. // Set the credentials flag to TRUE - BLANK password
  88. rParsedInfo.GetCmdSwitchesObject().SetCredentialsFlag(TRUE);
  89. }
  90. }
  91. if (pILocator != NULL)
  92. {
  93. // Call the ConnectServer method of the IWbemLocator
  94. hr = pILocator->ConnectServer(bstrNS,
  95. bstrUser,
  96. (!bstrPass) ? bstrPwd : bstrPass,
  97. bstrLocale,
  98. 0L, NULL, NULL, pISvc);
  99. // If the username is specified and the password is not
  100. // specified (the remote machine also has the same password)
  101. if (FAILED(hr) && bstrUser && (hr == E_ACCESSDENIED))
  102. {
  103. hr = pILocator->ConnectServer(bstrNS,
  104. bstrUser,
  105. NULL,
  106. bstrLocale,
  107. 0L, NULL, NULL, pISvc);
  108. // Set the credentials flag to FALSE - NULL password
  109. rParsedInfo.GetCmdSwitchesObject().SetCredentialsFlag(FALSE);
  110. }
  111. }
  112. else
  113. hr = E_FAIL;
  114. if (bstrPass)
  115. ::SysFreeString(bstrPass);
  116. return hr;
  117. }
  118. /*----------------------------------------------------------------------------
  119. Name :SetSecurity
  120. Synopsis :To set the security privileges at the interface level
  121. Type :Global Function
  122. Input parameter(s):
  123. pIUnknown - Interface pointer
  124. pszDomain - domain name
  125. pszAuthority - authority (always passed as NULL)
  126. pszUser - Username
  127. pszPassword - Password
  128. uAuthLevel - Authentication Level
  129. uImpLevel - Impersonation Level
  130. Output parameter(s):None
  131. Return Type :HRESULT
  132. Global Variables :None
  133. Calling Syntax :SetSecurity(pIUnknown, pszDomain, pszUser,
  134. pszPassword, uAuthLevel, uImpLevel)
  135. Notes :(partly taken from WMI VC samples 'utillib'
  136. ----------------------------------------------------------------------------*/
  137. HRESULT SetSecurity(IUnknown* pIUnknown, _TCHAR* pszAuthority,
  138. _TCHAR* pszDomain, _TCHAR* pszUser,
  139. _TCHAR* pszPassword, UINT uAuthLevel,
  140. UINT uImpLevel) throw(WMICLIINT)
  141. {
  142. SCODE sc = S_OK;
  143. BSTR bstrAuthArg = NULL,
  144. bstrUserArg = NULL;
  145. SEC_WINNT_AUTH_IDENTITY_W* pAuthIdentity = NULL;
  146. try
  147. {
  148. if(pIUnknown == NULL)
  149. return E_INVALIDARG;
  150. // If we are lowering the security, no need to deal with the
  151. // identification information
  152. if(uAuthLevel == RPC_C_AUTHN_LEVEL_NONE)
  153. return CoSetProxyBlanket(pIUnknown, RPC_C_AUTHN_WINNT,
  154. RPC_C_AUTHZ_NONE,
  155. NULL, RPC_C_AUTHN_LEVEL_NONE,
  156. RPC_C_IMP_LEVEL_IDENTIFY,
  157. NULL, EOAC_NONE);
  158. // If we are doing trivial case, just pass in a null authentication
  159. // structure which is used if the current logged in user's credentials
  160. // are OK.
  161. if((pszAuthority == NULL || lstrlen((LPCTSTR)pszAuthority) < 1) &&
  162. (pszUser == NULL || lstrlen((LPCTSTR)pszUser) < 1) &&
  163. (pszPassword == NULL || lstrlen((LPCTSTR)pszPassword) < 1))
  164. return CoSetProxyBlanket(pIUnknown, RPC_C_AUTHN_WINNT,
  165. RPC_C_AUTHZ_NONE, NULL, uAuthLevel,
  166. uImpLevel, NULL, EOAC_NONE);
  167. // If user, or Authority was passed in, the we need
  168. // to create an authority argument for the login
  169. sc = ParseAuthorityUserArgs(bstrAuthArg, bstrUserArg,
  170. pszAuthority, pszUser);
  171. if(FAILED(sc))
  172. return sc;
  173. pAuthIdentity = new SEC_WINNT_AUTH_IDENTITY_W;
  174. // Check whether the memory allocation has been successful
  175. if (pAuthIdentity == NULL)
  176. return WBEM_E_OUT_OF_MEMORY;
  177. ZeroMemory(pAuthIdentity, sizeof(SEC_WINNT_AUTH_IDENTITY_W));
  178. if(bstrUserArg)
  179. {
  180. WMICLIULONG wulUserLen = (WMICLIULONG)
  181. lstrlen((LPWSTR)bstrUserArg);
  182. pAuthIdentity->User = new WCHAR [wulUserLen + 1];
  183. if (pAuthIdentity->User == NULL)
  184. throw OUT_OF_MEMORY;
  185. wcscpy(pAuthIdentity->User, (LPWSTR)bstrUserArg);
  186. pAuthIdentity->UserLength = wulUserLen;
  187. }
  188. if(bstrAuthArg)
  189. {
  190. WMICLIULONG wulDomainLen = (WMICLIULONG)
  191. lstrlen((LPWSTR) bstrAuthArg);
  192. pAuthIdentity->Domain = new WCHAR [wulDomainLen + 1];
  193. if (pAuthIdentity->Domain == NULL)
  194. throw OUT_OF_MEMORY;
  195. wcscpy(pAuthIdentity->Domain, (LPWSTR)bstrAuthArg);
  196. pAuthIdentity->DomainLength = wulDomainLen;
  197. }
  198. if(pszPassword)
  199. {
  200. WMICLIULONG wulPasswordLen = (WMICLIULONG)
  201. lstrlen((LPWSTR) pszPassword);
  202. pAuthIdentity->Password = new WCHAR [wulPasswordLen + 1];
  203. if (pAuthIdentity->Password == NULL)
  204. throw OUT_OF_MEMORY;
  205. wcscpy(pAuthIdentity->Password, pszPassword);
  206. pAuthIdentity->PasswordLength= wulPasswordLen;
  207. }
  208. pAuthIdentity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
  209. sc = CoSetProxyBlanket(pIUnknown, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
  210. NULL, uAuthLevel, uImpLevel, pAuthIdentity, EOAC_NONE);
  211. SAFEDELETE(pAuthIdentity->User);
  212. SAFEDELETE(pAuthIdentity->Domain);
  213. SAFEDELETE(pAuthIdentity->Password);
  214. delete pAuthIdentity;
  215. SAFEBSTRFREE(bstrUserArg);
  216. SAFEBSTRFREE(bstrAuthArg);
  217. }
  218. catch(WMICLIINT nErr)
  219. {
  220. if (nErr == OUT_OF_MEMORY)
  221. sc = WBEM_E_OUT_OF_MEMORY;
  222. SAFEDELETE(pAuthIdentity->User);
  223. SAFEDELETE(pAuthIdentity->Domain);
  224. SAFEDELETE(pAuthIdentity->Password);
  225. if (pAuthIdentity)
  226. delete pAuthIdentity;
  227. SAFEBSTRFREE(bstrUserArg);
  228. SAFEBSTRFREE(bstrAuthArg);
  229. }
  230. return sc;
  231. }
  232. /*----------------------------------------------------------------------------
  233. Name :ConvertWCToMBCS
  234. Synopsis :Converts the wide character string to MBCS string
  235. after applying the codepage settings
  236. Type :Global Function
  237. Input parameters :
  238. lpszMsg - string (widechar string)
  239. uCP - codepage value
  240. Output parameters :
  241. lpszDisp - string (multibyte string)
  242. Return Type :BOOL
  243. Global Variables :None
  244. Calling Syntax :ConvertWCToMBCS(lpszMsg, lpszDisp, uCP)
  245. Notes :None
  246. ----------------------------------------------------------------------------*/
  247. BOOL ConvertWCToMBCS(LPTSTR lpszMsg, LPVOID* lpszDisp, UINT uCP)
  248. {
  249. BOOL bRet = TRUE;
  250. if (lpszMsg != NULL && lpszDisp != NULL)
  251. {
  252. WMICLIINT nRet = 0;
  253. nRet = WideCharToMultiByte(uCP, // code page
  254. 0, // performance and mapping flags
  255. (LPCWSTR)lpszMsg, // wide-character string
  256. -1, // number of chars in string
  257. NULL, // buffer for new string
  258. 0, // size of buffer
  259. NULL, // default for unmappable chars
  260. NULL);
  261. // allocate memory to hold the message
  262. *lpszDisp = (LPSTR) new char [nRet];
  263. if (*lpszDisp)
  264. {
  265. nRet = WideCharToMultiByte(uCP, // code page
  266. 0, // performance and mapping flags
  267. (LPCWSTR)lpszMsg, // wide-character string
  268. -1, // number of chars in string
  269. (LPSTR) *lpszDisp, // buffer for new string
  270. nRet, // size of buffer
  271. NULL, // default for unmappable chars
  272. NULL);
  273. }
  274. else
  275. bRet = FALSE;
  276. }
  277. else
  278. *lpszDisp = NULL;
  279. return bRet;
  280. }
  281. /*----------------------------------------------------------------------------
  282. Name :Find
  283. Synopsis :Searches for a given string in the vector list
  284. Input parameter(s):
  285. cvVector - vector list
  286. pszStrToFind - serach string
  287. Output parameter(s):None
  288. Return Type :BOOL
  289. TRUE - if match is found
  290. FALSE - if no match found
  291. Global Variables :None
  292. Calling Syntax :Find(cvVector, pszStrToFind)
  293. Notes :overloaded function
  294. ----------------------------------------------------------------------------*/
  295. BOOL Find(CHARVECTOR& cvVector,
  296. _TCHAR* pszStrToFind,
  297. CHARVECTOR::iterator& theIterator)
  298. {
  299. BOOL bRet = FALSE;
  300. theIterator = cvVector.begin();
  301. CHARVECTOR ::iterator theEnd = cvVector.end();
  302. while (theIterator != theEnd)
  303. {
  304. if (CompareTokens(*theIterator, pszStrToFind))
  305. {
  306. bRet = TRUE;
  307. break;
  308. }
  309. theIterator++;
  310. }
  311. return bRet;
  312. }
  313. /*----------------------------------------------------------------------------
  314. Name :Find
  315. Synopsis :Find a property name in the property details map
  316. Type :Global Function
  317. Input parameter(s):
  318. pdmPropDetMap - property map
  319. pszPropToFind - property to search for
  320. theIterator - Iterator
  321. bExcludeNumbers - Boolean value
  322. Output parameter(s):None
  323. Return Type :BOOL
  324. Global Variables :None
  325. Calling Syntax :Find(pdmPropDetMap, pszPropToFind, tempIterator)
  326. Notes :overloaded function,
  327. bExcludeNumbers = FALSE by default.
  328. ----------------------------------------------------------------------------*/
  329. BOOL Find(PROPDETMAP& pdmPropDetMap,
  330. _TCHAR* pszPropToFind,
  331. PROPDETMAP::iterator& theIterator,
  332. BOOL bExcludeNumbers)
  333. {
  334. BOOL bRet = FALSE;
  335. theIterator = pdmPropDetMap.begin();
  336. PROPDETMAP::iterator theEnd = pdmPropDetMap.end();
  337. while (theIterator != theEnd)
  338. {
  339. _TCHAR* pszPropName = (*theIterator).first;
  340. if ( bExcludeNumbers == TRUE )
  341. pszPropName = pszPropName + 5;
  342. if (CompareTokens(pszPropName, pszPropToFind))
  343. {
  344. bRet = TRUE;
  345. break;
  346. }
  347. theIterator++;
  348. }
  349. return bRet;
  350. }
  351. /*----------------------------------------------------------------------------
  352. Name :Find
  353. Synopsis :Find a property name in the property details map
  354. Type :Global Function
  355. Input parameter(s):
  356. bmBstrMap - BSTR map
  357. pszStrToFind - property to search for
  358. theIterator - Iterator.
  359. Output parameter(s):None
  360. Return Type :BOOL
  361. Global Variables :None
  362. Calling Syntax :Find(pdmPropDetMap, pszPropToFind)
  363. Notes :overloaded function
  364. ----------------------------------------------------------------------------*/
  365. BOOL Find(BSTRMAP& bmBstrMap,
  366. _TCHAR* pszStrToFind,
  367. BSTRMAP::iterator& theIterator)
  368. {
  369. BOOL bRet = FALSE;
  370. theIterator = bmBstrMap.begin();
  371. BSTRMAP::iterator theEnd = bmBstrMap.end();
  372. while (theIterator != theEnd)
  373. {
  374. if (CompareTokens((*theIterator).first, pszStrToFind))
  375. {
  376. bRet = TRUE;
  377. break;
  378. }
  379. theIterator++;
  380. }
  381. return bRet;
  382. }
  383. /*------------------------------------------------------------------------
  384. Name :FrameFileAndAddToXSLTDetVector
  385. Synopsis :Frames the XSL File Path
  386. Type :Global Function
  387. Input parameter(s):
  388. pszXSLFile - the XSL File
  389. rParsedInfo - reference to object of CParsedInfo
  390. Output parameter(s): None
  391. Return Type :BOOL
  392. Global Variables :None
  393. Calling Syntax :FrameXSLFilePath(pszXSLFile, rParsedInfo)
  394. Notes :None
  395. ------------------------------------------------------------------------*/
  396. BOOL FrameFileAndAddToXSLTDetVector(XSLTDET xdXSLTDet,
  397. CParsedInfo& rParsedInfo)
  398. {
  399. BOOL bRet = TRUE;
  400. _TCHAR* pszBuffer = new _TCHAR [MAX_PATH];
  401. UINT nSize = 0;
  402. try
  403. {
  404. if (pszBuffer != NULL)
  405. {
  406. // Obtain the windows system directory
  407. nSize = GetSystemDirectory(pszBuffer, MAX_PATH);
  408. if (nSize)
  409. {
  410. if (nSize > MAX_PATH)
  411. {
  412. SAFEDELETE(pszBuffer);
  413. pszBuffer = new _TCHAR [nSize + 1];
  414. if(pszBuffer == NULL)
  415. throw OUT_OF_MEMORY;
  416. }
  417. if (!GetSystemDirectory(pszBuffer, nSize))
  418. {
  419. SAFEDELETE(pszBuffer);
  420. throw (::GetLastError());
  421. }
  422. else
  423. {
  424. _bstr_t bstrPath = _bstr_t(pszBuffer);
  425. SAFEDELETE(pszBuffer);
  426. // Append the following path
  427. bstrPath += _bstr_t(WBEM_LOCATION) + _bstr_t(xdXSLTDet.FileName);
  428. xdXSLTDet.FileName = bstrPath;
  429. rParsedInfo.GetCmdSwitchesObject().AddToXSLTDetailsVector(
  430. xdXSLTDet);
  431. }
  432. }
  433. else
  434. {
  435. SAFEDELETE(pszBuffer);
  436. throw (::GetLastError());
  437. }
  438. SAFEDELETE(pszBuffer);
  439. }
  440. else
  441. {
  442. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(OUT_OF_MEMORY);
  443. bRet = FALSE;
  444. }
  445. }
  446. catch(_com_error& e)
  447. {
  448. SAFEDELETE(pszBuffer);
  449. bRet = FALSE;
  450. _com_issue_error(e.Error());
  451. }
  452. catch (DWORD dwError)
  453. {
  454. SAFEDELETE(pszBuffer);
  455. ::SetLastError(dwError);
  456. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(dwError);
  457. DisplayWin32Error();
  458. ::SetLastError(dwError);
  459. bRet = FALSE;
  460. }
  461. return bRet;
  462. }
  463. /*------------------------------------------------------------------------
  464. Name :UnquoteString
  465. Synopsis :Removes the starting and ending quotes of a string
  466. enclosed in double quotes.
  467. Type :Global Function
  468. Input parameter(s):
  469. pszString - string input
  470. Output parameter(s):
  471. pszString - string input
  472. Return Type :void
  473. Global Variables :None
  474. Calling Syntax :UnQuoteString(pszString)
  475. Notes :None
  476. ------------------------------------------------------------------------*/
  477. void UnQuoteString(_TCHAR*& pszString)
  478. {
  479. if ((lstrlen(pszString) - 1) > 0)
  480. {
  481. // Check if the string is enclosed within quotes
  482. if ((pszString[0] == _T('"'))
  483. && (pszString[lstrlen(pszString)-1] == _T('"')))
  484. {
  485. WMICLIINT nLoop = 1, nLen = lstrlen(pszString)-1;
  486. while (nLoop < nLen)
  487. {
  488. pszString[nLoop-1] = pszString[nLoop];
  489. nLoop++;
  490. }
  491. pszString[nLen-1] = _T('\0');
  492. }
  493. }
  494. }
  495. /*------------------------------------------------------------------------
  496. Name :ParseAuthorityUserArgs
  497. Synopsis :Examines the Authority and User argument and
  498. determines the authentication type and possibly
  499. extracts the domain name from the user arugment in the
  500. NTLM case. For NTLM, the domain can be at the end of
  501. the authentication string, or in the front of the
  502. user name, ex: "MSOFT\csriram"
  503. Type :Global Function
  504. Input parameter(s):
  505. ConnType - Returned with the connection type, ie wbem,
  506. ntlm
  507. bstrAuthArg - Output, contains the domain name
  508. bstrUserArg - Output, user name
  509. bstrAuthority - Input
  510. User - Input
  511. Output parameter(s):None
  512. Return Type :
  513. SCODE
  514. Global Variables :None
  515. Calling Syntax :ParseAuthorityUserArgs(bstrAuthArg, bstrUserArg,
  516. bstrAuthority, bstrUser)
  517. Notes :(taken from WMI VC samples 'utillib'
  518. ------------------------------------------------------------------------*/
  519. SCODE ParseAuthorityUserArgs(BSTR& bstrAuthArg, BSTR& bstrUserArg,
  520. BSTR& bstrAuthority, BSTR& bstrUser)
  521. {
  522. // Determine the connection type by examining the Authority string
  523. if(!(bstrAuthority == NULL || lstrlen((LPCTSTR)bstrAuthority) == 0 ||
  524. !_wcsnicmp(bstrAuthority, L"NTLMDOMAIN:",11)))
  525. return E_INVALIDARG;
  526. // The ntlm case is more complex. There are four cases
  527. // 1) Authority = NTLMDOMAIN:name" and User = "User"
  528. // 2) Authority = NULL and User = "User"
  529. // 3) Authority = "NTLMDOMAIN:" User = "domain\user"
  530. // 4) Authority = NULL and User = "domain\user"
  531. // first step is to determine if there is a backslash in the user
  532. // name somewhere between the second and second to last character
  533. WCHAR * pSlashInUser = NULL;
  534. if(bstrUser)
  535. {
  536. WCHAR * pEnd = bstrUser + lstrlen((LPCTSTR)bstrUser) - 1;
  537. for(pSlashInUser = bstrUser; pSlashInUser <= pEnd; pSlashInUser++)
  538. // dont think forward slash is allowed!
  539. if(*pSlashInUser == L'\\')
  540. break;
  541. if(pSlashInUser > pEnd)
  542. pSlashInUser = NULL;
  543. }
  544. if(bstrAuthority && lstrlen((LPCTSTR)bstrAuthority) > 11)
  545. {
  546. if(pSlashInUser)
  547. return E_INVALIDARG;
  548. bstrAuthArg = SysAllocString(bstrAuthority + 11);
  549. if(bstrUser)
  550. bstrUserArg = SysAllocString(bstrUser);
  551. return S_OK;
  552. }
  553. else if(pSlashInUser)
  554. {
  555. WMICLIINT iDomLen = pSlashInUser-bstrUser;
  556. WCHAR *pszTemp = new WCHAR [iDomLen+1];
  557. if ( pszTemp != NULL )
  558. {
  559. wcsncpy(pszTemp, bstrUser, iDomLen);
  560. pszTemp[iDomLen] = 0;
  561. bstrAuthArg = SysAllocString(pszTemp);
  562. if(lstrlen((LPCTSTR)pSlashInUser+1))
  563. bstrUserArg = SysAllocString(pSlashInUser+1);
  564. SAFEDELETE(pszTemp);
  565. }
  566. else
  567. throw OUT_OF_MEMORY;
  568. }
  569. else
  570. if(bstrUser)
  571. bstrUserArg = SysAllocString(bstrUser);
  572. return S_OK;
  573. }
  574. /*----------------------------------------------------------------------------
  575. Name :DisplayVARIANTContent
  576. Synopsis :Displays the content of a VARIANT type data object
  577. Type :Member Function
  578. Input Parameter(s):
  579. vtObject - VARIANT object
  580. Output parameters :None
  581. Return Type :None
  582. Global Variables :None
  583. Calling Syntax :DisplayVARIANTContent(vtObject)
  584. Notes :none
  585. ----------------------------------------------------------------------------*/
  586. void DisplayVARIANTContent(VARIANT vtObject)
  587. {
  588. _TCHAR szMsg[BUFFER255] = NULL_STRING;
  589. switch ( vtObject.vt )
  590. {
  591. case VT_UI1:
  592. _stprintf(szMsg, _T("%c"), vtObject.bVal);
  593. break;
  594. case VT_I2:
  595. _stprintf(szMsg, _T("%i"), vtObject.iVal);
  596. break;
  597. case VT_I4:
  598. _stprintf(szMsg, _T("%li"), vtObject.lVal);
  599. break;
  600. case VT_R4:
  601. _stprintf(szMsg, _T("%f"), vtObject.fltVal);
  602. break;
  603. case VT_R8:
  604. _stprintf(szMsg, _T("%e"), vtObject.dblVal);
  605. break;
  606. case VT_BOOL:
  607. _stprintf(szMsg, _T("%i"), vtObject.boolVal);
  608. break;
  609. case VT_I1:
  610. _stprintf(szMsg, _T("%c"), vtObject.cVal);
  611. break;
  612. case VT_UI2:
  613. _stprintf(szMsg, _T("%i"), vtObject.uiVal);
  614. break;
  615. case VT_UI4:
  616. _stprintf(szMsg, _T("%ld"), vtObject.ulVal);
  617. break;
  618. case VT_INT:
  619. _stprintf(szMsg, _T("%i"), vtObject.intVal);
  620. break;
  621. case VT_UINT:
  622. _stprintf(szMsg, _T("%i"), vtObject.uintVal);
  623. break;
  624. }
  625. DisplayMessage(szMsg, CP_OEMCP, FALSE, TRUE);
  626. }
  627. /*----------------------------------------------------------------------------
  628. Name :GetPropertyAttributes
  629. Synopsis :This function obtains the information about the class
  630. properties
  631. Type :Member Function
  632. Input Parameter(s):
  633. pIObj - pointer to IWbemClassObject object
  634. bstrProp - property name
  635. bTrace - trace flag
  636. Output parameter(s):
  637. pdPropDet - property details structure
  638. Return Type :HRESULT
  639. Global Variables :None
  640. Calling Syntax :GetPropertyAttributes(pIObj, bstrProp,
  641. pdPropDet, bTrace)
  642. Notes :none
  643. ----------------------------------------------------------------------------*/
  644. HRESULT GetPropertyAttributes(IWbemClassObject* pIObj,
  645. BSTR bstrProp,
  646. PROPERTYDETAILS& pdPropDet,
  647. BOOL bTrace)
  648. {
  649. HRESULT hr = S_OK;
  650. IWbemQualifierSet* pIQualSet = NULL;
  651. VARIANT vtType, vtOper, vtDesc;
  652. VariantInit(&vtType);
  653. VariantInit(&vtOper);
  654. VariantInit(&vtDesc);
  655. try
  656. {
  657. // Obtain the property qualifier set for the property
  658. hr = pIObj->GetPropertyQualifierSet(bstrProp, &pIQualSet);
  659. if ( pIQualSet != NULL )
  660. {
  661. // Obtain the CIM type of the property
  662. hr = pIQualSet->Get(_bstr_t(L"CIMTYPE"), 0L, &vtType, NULL);
  663. if (SUCCEEDED(hr))
  664. {
  665. if ( vtType.vt == VT_BSTR )
  666. pdPropDet.Type = _bstr_t(vtType.bstrVal);
  667. else
  668. pdPropDet.Type = _bstr_t("Not Found");
  669. }
  670. else
  671. pdPropDet.Type = _bstr_t("Not Found");
  672. // Should not break here, hence the HRESULT should be set to S_OK
  673. hr = S_OK;
  674. VARIANTCLEAR(vtType);
  675. // Check whether the property has 'read' flag set
  676. _bstr_t bstrOper;
  677. hr = pIQualSet->Get(_bstr_t(L"read"), 0L, &vtOper, NULL);
  678. if (SUCCEEDED(hr))
  679. {
  680. if (vtOper.vt == VT_BOOL && vtOper.boolVal)
  681. bstrOper = _bstr_t(L"Read");
  682. }
  683. VARIANTCLEAR(vtOper);
  684. // Should not break here, hence the HRESULT should be set to S_OK
  685. hr = S_OK;
  686. // Check whether the property has 'write' flag set
  687. VariantInit(&vtOper);
  688. hr = pIQualSet->Get(_bstr_t(L"write"), 0L, &vtOper, NULL);
  689. if (SUCCEEDED(hr))
  690. {
  691. if ((vtOper.vt == VT_BOOL) && vtOper.boolVal)
  692. {
  693. if (!bstrOper)
  694. bstrOper = _bstr_t(L"Write");
  695. else
  696. bstrOper += _bstr_t(L"/Write");
  697. }
  698. }
  699. VARIANTCLEAR(vtOper);
  700. // Should not break here, hence the HRESULT should be set to S_OK
  701. hr = S_OK;
  702. if (!bstrOper)
  703. pdPropDet.Operation = _bstr_t(TOKEN_NA);
  704. else
  705. pdPropDet.Operation = _bstr_t(bstrOper);
  706. // Retrieve the 'Description' text for the property
  707. if (FAILED(pIQualSet->Get(_bstr_t(L"Description"), 0L,
  708. &vtDesc,NULL)))
  709. pdPropDet.Description = _bstr_t("Not Available");
  710. else
  711. pdPropDet.Description = _bstr_t(vtDesc.bstrVal);
  712. VARIANTCLEAR(vtDesc);
  713. SAFEIRELEASE(pIQualSet);
  714. }
  715. else
  716. hr = S_OK;
  717. }
  718. catch(_com_error& e)
  719. {
  720. VARIANTCLEAR(vtType);
  721. VARIANTCLEAR(vtOper);
  722. VARIANTCLEAR(vtDesc);
  723. SAFEIRELEASE(pIQualSet);
  724. hr = e.Error();
  725. }
  726. return hr;
  727. }
  728. /*----------------------------------------------------------------------------
  729. Name :ConvertCIMTYPEToVarType
  730. Synopsis :Does the CIMTYPE to VARIANT conversion
  731. Type :Member Function
  732. Input Parameter(s):
  733. varSrc - VARIANT source
  734. bstrCIMType - CIMTYPE
  735. Output parameters :
  736. varDest - VARIANT destination
  737. Return Type :HRESULT
  738. Global Variables :None
  739. Calling Syntax :ConvertCIMTYPEToVarType(varDest, varSrc, bstrCIMType)
  740. Notes :none
  741. ----------------------------------------------------------------------------*/
  742. HRESULT ConvertCIMTYPEToVarType( VARIANT& varDest, VARIANT& varSrc,
  743. _TCHAR* bstrCIMType )
  744. {
  745. HRESULT hr = S_OK;
  746. if (CompareTokens(varSrc.bstrVal, _T("")))
  747. {
  748. hr = VariantChangeType(&varDest, &varSrc, 0, VT_NULL);
  749. }
  750. else
  751. {
  752. if (CompareTokens(bstrCIMType,_T("string")))
  753. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BSTR);
  754. else if (CompareTokens(bstrCIMType,_T("Sint16")))
  755. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I2);
  756. else if (CompareTokens(bstrCIMType,_T("Sint8")))
  757. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I2);
  758. else if ( CompareTokens(bstrCIMType,_T("Sint32")))
  759. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I4);
  760. else if ( CompareTokens(bstrCIMType,_T("Real32")))
  761. hr = VariantChangeType(&varDest, &varSrc, 0, VT_R4);
  762. else if ( CompareTokens(bstrCIMType,_T("Sint64")))
  763. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BSTR);
  764. else if ( CompareTokens(bstrCIMType,_T("Uint64")))
  765. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BSTR);
  766. else if ( CompareTokens(bstrCIMType,_T("Real64")))
  767. hr = VariantChangeType(&varDest, &varSrc, 0, VT_R8);
  768. else if ( CompareTokens(bstrCIMType,_T("Boolean")))
  769. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BOOL);
  770. else if ( CompareTokens(bstrCIMType,_T("Object")))
  771. hr = VariantChangeType(&varDest, &varSrc, 0, VT_DISPATCH);
  772. else if ( CompareTokens(bstrCIMType,_T("Sint8")))
  773. hr = VariantChangeType(&varDest, &varSrc, 0, VT_INT);
  774. else if ( CompareTokens(bstrCIMType,_T("Uint8")))
  775. hr = VariantChangeType(&varDest, &varSrc, 0, VT_UI1);
  776. else if ( CompareTokens(bstrCIMType,_T("Uint16")))
  777. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I4);
  778. else if ( CompareTokens(bstrCIMType,_T("Uint32")))
  779. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I4);
  780. else if ( CompareTokens(bstrCIMType,_T("Datetime")))
  781. hr = VariantChangeType(&varDest, &varSrc, 0, VT_DATE);
  782. else if ( CompareTokens(bstrCIMType,_T("Reference")))
  783. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BYREF);
  784. else if ( CompareTokens(bstrCIMType,_T("Char16")))
  785. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I2);
  786. else // (CIM_OBJECT)
  787. hr = VariantChangeType(&varDest, &varSrc, 0, VT_NULL);
  788. }
  789. return hr;
  790. }
  791. /*----------------------------------------------------------------------------
  792. Name :DisplayMessage
  793. Synopsis :Displays localized string
  794. Type :Global Function
  795. Input parameter(s):
  796. lszpMsg - string
  797. uCP - codepage value
  798. bIsError - Boolean type specifying error message or not.
  799. bIsLog - Boolean type specifying message to be logged or not .
  800. Output parameter(s):None
  801. Return Type :void
  802. Global Variables :None
  803. Calling Syntax :DisplayMessage(lpszMsg, uCP, TRUE, TRUE)
  804. Notes :bIsError = FALSE, bIsLog = FALSE by default.
  805. ----------------------------------------------------------------------------*/
  806. void DisplayMessage(LPTSTR lpszMsg, UINT uCP, BOOL bIsError, BOOL bIsLog)
  807. {
  808. LPSTR lpszDisp = NULL;
  809. try
  810. {
  811. // Convert the widechar to MBCS string
  812. if (ConvertWCToMBCS(lpszMsg, (LPVOID*) &lpszDisp, uCP))
  813. {
  814. if (bIsLog)
  815. {
  816. // Append to the output string
  817. g_wmiCmd.GetFormatObject().AppendtoOutputString((_TCHAR*)
  818. _bstr_t(lpszDisp));
  819. }
  820. if ( bIsError == TRUE )
  821. {
  822. fprintf(stderr, "%s", lpszDisp);
  823. fflush(stderr);
  824. }
  825. else
  826. {
  827. OUTPUTSPEC opsOutOpt = g_wmiCmd.GetParsedInfoObject().
  828. GetGlblSwitchesObject().
  829. GetOutputOrAppendOption(TRUE);
  830. // OUT for getting append file pointer.
  831. FILE* fpOutFile = g_wmiCmd.GetParsedInfoObject().
  832. GetGlblSwitchesObject().
  833. GetOutputOrAppendFilePointer(TRUE);
  834. if ( opsOutOpt == CLIPBOARD )
  835. g_wmiCmd.AddToClipBoardBuffer(lpszDisp);
  836. else if ( opsOutOpt == FILEOUTPUT )
  837. {
  838. if (fpOutFile != NULL)
  839. {
  840. fprintf(fpOutFile, "%s", lpszDisp);
  841. }
  842. else
  843. {
  844. fprintf(stdout, "%s", lpszDisp);
  845. fflush(stdout);
  846. }
  847. }
  848. else
  849. {
  850. fprintf(stdout, "%s", lpszDisp);
  851. fflush(stdout);
  852. }
  853. // FALSE for getting append file pointer.
  854. FILE* fpAppendFile = g_wmiCmd.GetParsedInfoObject().
  855. GetGlblSwitchesObject().
  856. GetOutputOrAppendFilePointer(FALSE);
  857. if ( fpAppendFile != NULL )
  858. fprintf(fpAppendFile, "%s", lpszDisp);
  859. }
  860. SAFEDELETE(lpszDisp);
  861. }
  862. }
  863. catch(_com_error& e)
  864. {
  865. SAFEDELETE(lpszDisp);
  866. _com_issue_error(e.Error());
  867. }
  868. }
  869. /*----------------------------------------------------------------------------
  870. Name :CleanUpCharVector
  871. Synopsis :Clears the character vector
  872. Type :Global Function
  873. Input parameter(s):
  874. cvCharVector - reference to character vector.
  875. Output parameter(s):None
  876. Return Type :void
  877. Global Variables :None
  878. Calling Syntax :CleanUpCharVector(cvCharVector)
  879. Notes :None
  880. ----------------------------------------------------------------------------*/
  881. void CleanUpCharVector(CHARVECTOR& cvCharVector)
  882. {
  883. if ( !cvCharVector.empty() )
  884. {
  885. CHARVECTOR::iterator theIterator;
  886. for ( theIterator = cvCharVector.begin();
  887. theIterator < cvCharVector.end(); theIterator++ )
  888. {
  889. SAFEDELETE( *theIterator );
  890. }
  891. cvCharVector.clear();
  892. }
  893. }
  894. /*----------------------------------------------------------------------------
  895. Name :FindAndReplaceAll
  896. Synopsis :Search and replace all the occurences of pszFromStr
  897. with pszToStr in the given string strString
  898. Type :Global Function
  899. Input parameter :
  900. strString - string buffer
  901. pszFromStr - string to searched and replaced
  902. pszToStr - string to be replaced by
  903. Output parameters :None
  904. Return Type :void
  905. Global Variables :None
  906. Calling Syntax :CleanUpCharVector(cvCharVector)
  907. Notes :None
  908. ----------------------------------------------------------------------------*/
  909. void FindAndReplaceAll(STRING& strString, _TCHAR* pszFromStr,_TCHAR* pszToStr)
  910. {
  911. if ( pszFromStr != NULL && pszToStr != NULL )
  912. {
  913. STRING::size_type stPos = 0;
  914. STRING::size_type stFromPos = 0;
  915. STRING::size_type stFromStrLen = lstrlen(pszFromStr);
  916. STRING::size_type stToStrLen = lstrlen(pszToStr);
  917. while( TRUE )
  918. {
  919. stPos = strString.find(pszFromStr, stFromPos, stFromStrLen);
  920. if ( stPos == STRING::npos )
  921. break;
  922. strString.replace(stPos, stFromStrLen, pszToStr);
  923. stFromPos = stPos + stToStrLen;
  924. }
  925. }
  926. }
  927. /*----------------------------------------------------------------------------
  928. Name :IsSysProp
  929. Synopsis :Returns true if the input property is a WMI system
  930. property
  931. Type :Global Function
  932. Input parameter :
  933. pszProp - property name
  934. Output parameters :None
  935. Return Type :BOOL
  936. Global Variables :None
  937. Notes :IsSysProp(pszProp)
  938. ----------------------------------------------------------------------------*/
  939. BOOL IsSysProp(_TCHAR* pszProp)
  940. {
  941. BOOL bRet = FALSE;
  942. if (CompareTokens(pszProp, WMISYSTEM_CLASS) ||
  943. CompareTokens(pszProp, WMISYSTEM_DERIVATION) ||
  944. CompareTokens(pszProp, WMISYSTEM_DYNASTY) ||
  945. CompareTokens(pszProp, WMISYSTEM_GENUS) ||
  946. CompareTokens(pszProp, WMISYSTEM_NAMESPACE) ||
  947. CompareTokens(pszProp, WMISYSTEM_PATH) ||
  948. CompareTokens(pszProp, WMISYSTEM_PROPERTYCOUNT) ||
  949. CompareTokens(pszProp, WMISYSTEM_REPLATH) ||
  950. CompareTokens(pszProp, WMISYSTEM_SERVER) ||
  951. CompareTokens(pszProp, WMISYSTEM_SUPERCLASS))
  952. {
  953. bRet = TRUE;
  954. }
  955. return bRet;
  956. }
  957. /*----------------------------------------------------------------------------
  958. Name :EraseMessage
  959. Synopsis :Displays white spaces at the current cursor position
  960. and sets the cursor column to zero
  961. Type :Global Function
  962. Input parameter :None
  963. Output parameters :None
  964. Return Type :None
  965. Global Variables :None
  966. Calling Syntax :EraseMessage(uID)
  967. ----------------------------------------------------------------------------*/
  968. void EraseMessage(UINT uID)
  969. {
  970. COORD coord;
  971. HANDLE hStdOut = NULL;
  972. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  973. WMICLIINT nHeight = 0;
  974. // Obtain the standard output handle
  975. hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  976. // Get the screen buffer size.
  977. GetConsoleScreenBufferInfo(hStdOut, &csbiInfo);
  978. nHeight = csbiInfo.srWindow.Bottom - csbiInfo.srWindow.Top;
  979. // if console size is positive (to address redirection)
  980. if (nHeight > 0)
  981. {
  982. coord.X = 0;
  983. coord.Y = csbiInfo.dwCursorPosition.Y;
  984. SetConsoleCursorPosition(hStdOut, coord);
  985. DisplayString(uID, CP_OEMCP, NULL, TRUE, TRUE);
  986. SetConsoleCursorPosition(hStdOut, coord);
  987. }
  988. }
  989. /*----------------------------------------------------------------------------
  990. Name :IsRedirection
  991. Synopsis :Returns true if the the output is being redirected
  992. Type :Global Function
  993. Input parameter :None
  994. Output parameters :None
  995. Return Type :BOOL
  996. Global Variables :None
  997. Notes :IsRedirection()
  998. ----------------------------------------------------------------------------*/
  999. BOOL IsRedirection()
  1000. {
  1001. HANDLE hStdOut = NULL;
  1002. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  1003. WMICLIINT nHeight = 0;
  1004. BOOL bRet = FALSE;
  1005. // Obtain the standard output handle
  1006. hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1007. if (hStdOut != INVALID_HANDLE_VALUE)
  1008. {
  1009. // Get the screen buffer size.
  1010. GetConsoleScreenBufferInfo(hStdOut, &csbiInfo);
  1011. nHeight = csbiInfo.srWindow.Bottom - csbiInfo.srWindow.Top;
  1012. if (nHeight <= 0)
  1013. bRet = TRUE;
  1014. }
  1015. else
  1016. bRet = TRUE;
  1017. return bRet;
  1018. }
  1019. /*----------------------------------------------------------------------------
  1020. Name :WMITRACEORERRORLOG
  1021. Synopsis :To display the trace of COM methods invoked
  1022. Type :Global Function
  1023. Input parameter :
  1024. hr - HRESULT value
  1025. nLine - the line number of the file.
  1026. pszFile - the file name
  1027. pszMsg - message to be displayed.
  1028. Output parameters :None
  1029. Return Type :None
  1030. Global Variables :None
  1031. Calling Syntax :WMITRACEORERRORLOG(hr, nLine, pszFile, (LPCWSTR)chsMsg,
  1032. eloErrLgOpt, bTrace)
  1033. Note : Default values dwError = 0, pszResult = NULL.
  1034. ----------------------------------------------------------------------------*/
  1035. void WMITRACEORERRORLOG(HRESULT hr, INT nLine, char* pszFile, _bstr_t bstrMsg,
  1036. DWORD dwThreadId, CParsedInfo& rParsedInfo,
  1037. BOOL bTrace, DWORD dwError, _TCHAR* pszResult)
  1038. {
  1039. _TCHAR* pszMsg = bstrMsg;
  1040. try
  1041. {
  1042. if ( bTrace == TRUE && pszMsg != NULL)
  1043. {
  1044. if (_tcsnicmp(pszMsg,_T("COMMAND:"),8) != 0)
  1045. {
  1046. CHString chsMessage;
  1047. CHString chsSInfo;
  1048. if (FAILED (hr))
  1049. chsMessage.Format(L"FAIL: %s\n", pszMsg?pszMsg:L"NULL");
  1050. else
  1051. chsMessage.Format(L"SUCCESS: %s\n",pszMsg?pszMsg:L"NULL");
  1052. _fputts((_TCHAR*)_bstr_t((LPCWSTR)chsMessage), stderr);
  1053. fflush(stderr);
  1054. chsSInfo.Format(L"Line: %6d File: %s\n", nLine,
  1055. (LPCWSTR)CHString(pszFile));
  1056. _fputts((_TCHAR*)_bstr_t((LPCWSTR)chsSInfo), stderr);
  1057. fflush(stderr);
  1058. if ( pszResult != NULL )
  1059. {
  1060. chsMessage.Format(L"Result: %s\n\n", pszResult);
  1061. _fputts((_TCHAR*)_bstr_t((LPCWSTR)chsMessage), stderr);
  1062. fflush(stderr);
  1063. }
  1064. else
  1065. {
  1066. _fputts(_T("\n"), stderr);
  1067. fflush(stderr);
  1068. }
  1069. }
  1070. }
  1071. }
  1072. catch(_com_error& e)
  1073. {
  1074. _com_issue_error(e.Error());
  1075. }
  1076. catch(CHeap_Exception)
  1077. {
  1078. _com_issue_error(WBEM_E_OUT_OF_MEMORY);
  1079. }
  1080. if ( rParsedInfo.GetErrorLogObject().GetErrLogOption() != NO_LOGGING )
  1081. {
  1082. try
  1083. {
  1084. rParsedInfo.GetErrorLogObject().
  1085. LogErrorOrOperation(hr, pszFile, nLine, pszMsg,
  1086. dwThreadId, dwError);
  1087. }
  1088. catch(DWORD dwError)
  1089. {
  1090. ::SetLastError(dwError);
  1091. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(dwError);
  1092. }
  1093. }
  1094. }
  1095. /*----------------------------------------------------------------------------
  1096. Name :DisplayWin32Error
  1097. Synopsis :Displays the formatted error message for the Win32
  1098. function calls failure
  1099. Type :Global Function
  1100. Input parameter :None
  1101. Output parameters :None
  1102. Return Type :BOOL
  1103. Global Variables :None
  1104. Calling Syntax :DisplayWin32Error()
  1105. Notes :None
  1106. ----------------------------------------------------------------------------*/
  1107. void DisplayWin32Error()
  1108. {
  1109. LPVOID lpMessage = NULL;
  1110. DWORD dwError = ::GetLastError();
  1111. try
  1112. {
  1113. // If there was an error, create a text message for it
  1114. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1115. FORMAT_MESSAGE_FROM_SYSTEM |
  1116. FORMAT_MESSAGE_IGNORE_INSERTS,
  1117. NULL,
  1118. dwError,
  1119. 0,
  1120. (LPTSTR) &lpMessage,
  1121. 0,
  1122. NULL);
  1123. _bstr_t bstrMsg;
  1124. WMIFormatMessage(IDS_I_ERROR_WIN32, 1, bstrMsg,
  1125. (LPWSTR) lpMessage);
  1126. // Display the error message
  1127. DisplayMessage((LPWSTR)bstrMsg, CP_OEMCP, TRUE, TRUE);
  1128. // Free the memory used up the error message
  1129. // and then exit
  1130. LocalFree(lpMessage);
  1131. // Used for returning the error level
  1132. ::SetLastError(dwError);
  1133. }
  1134. catch(_com_error& e)
  1135. {
  1136. if ( lpMessage != NULL )
  1137. LocalFree(lpMessage);
  1138. _com_issue_error(e.Error());
  1139. }
  1140. }
  1141. /*----------------------------------------------------------------------------
  1142. Name :AcceptPassword
  1143. Synopsis :Prompts for the password when user name alone is
  1144. specified with the command
  1145. Type :Global Function
  1146. Input parameter :None
  1147. Output parameters :
  1148. pszPassword - password string
  1149. Return Type :void
  1150. Global Variables :None
  1151. Calling Syntax :AcceptPassword(pszPassword)
  1152. Notes :None
  1153. ----------------------------------------------------------------------------*/
  1154. void AcceptPassword(_TCHAR* pszPassword)
  1155. {
  1156. // local variables
  1157. TCHAR ch;
  1158. DWORD dwIndex = 0;
  1159. DWORD dwCharsRead = 0;
  1160. DWORD dwCharsWritten = 0;
  1161. DWORD dwPrevConsoleMode = 0;
  1162. HANDLE hStdIn = NULL;
  1163. _TCHAR szBuffer[BUFFER32] = NULL_STRING;
  1164. // Get the handle for the standard input
  1165. hStdIn = GetStdHandle( STD_INPUT_HANDLE );
  1166. // Get the current input mode of the input buffer
  1167. GetConsoleMode( hStdIn, &dwPrevConsoleMode );
  1168. // Set the mode such that the control keys are processed by the system
  1169. SetConsoleMode( hStdIn, ENABLE_PROCESSED_INPUT );
  1170. // Read the characters until a carriage return is hit
  1171. while( TRUE )
  1172. {
  1173. if ( !ReadConsole( hStdIn, &ch, 1, &dwCharsRead, NULL ))
  1174. {
  1175. // Set the original console settings
  1176. SetConsoleMode( hStdIn, dwPrevConsoleMode );
  1177. return;
  1178. }
  1179. // Check for carraige return
  1180. if ( ch == CARRIAGE_RETURN )
  1181. {
  1182. // break from the loop
  1183. break;
  1184. }
  1185. // Check id back space is hit
  1186. if ( ch == BACK_SPACE )
  1187. {
  1188. if ( dwIndex != 0 )
  1189. {
  1190. //
  1191. // Remove a asterik from the console
  1192. // move the cursor one character back
  1193. FORMAT_STRING( szBuffer, _T( "%c" ), BACK_SPACE );
  1194. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), szBuffer, 1,
  1195. &dwCharsWritten, NULL );
  1196. // replace the existing character with space
  1197. FORMAT_STRING( szBuffer, _T( "%c" ), BLANK_CHAR );
  1198. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), szBuffer, 1,
  1199. &dwCharsWritten, NULL );
  1200. // now set the cursor at back position
  1201. FORMAT_STRING( szBuffer, _T( "%c" ), BACK_SPACE );
  1202. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), szBuffer, 1,
  1203. &dwCharsWritten, NULL );
  1204. // decrement the index
  1205. dwIndex--;
  1206. }
  1207. // process the next character
  1208. continue;
  1209. }
  1210. // if the max password length has been reached then sound a beep
  1211. if ( dwIndex == ( MAXPASSWORDSIZE - 1 ) )
  1212. {
  1213. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), BEEP_SOUND, 1,
  1214. &dwCharsWritten, NULL );
  1215. }
  1216. else
  1217. {
  1218. // store the input character
  1219. *( pszPassword + dwIndex ) = ch;
  1220. dwIndex++;
  1221. // display asterix onto the console
  1222. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), ASTERIX, 1,
  1223. &dwCharsWritten, NULL );
  1224. }
  1225. }
  1226. // Add the NULL terminator
  1227. *( pszPassword + dwIndex ) = NULL_CHAR;
  1228. //Set the original console settings
  1229. SetConsoleMode( hStdIn, dwPrevConsoleMode );
  1230. // display the character ( new line character )
  1231. FORMAT_STRING( szBuffer, _T( "%s" ), _T( "\n\n" ) );
  1232. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), szBuffer, 2,
  1233. &dwCharsWritten, NULL );
  1234. }
  1235. /*----------------------------------------------------------------------------
  1236. Name :IsValueSet
  1237. Synopsis :Checks string passed in pszFromValue, Is a value set
  1238. or not.
  1239. Type :Global Function
  1240. Input parameter :
  1241. pszFromValue - string to be checked.
  1242. Output parameters :
  1243. cValue1 - <value1> of value set.
  1244. cValue2 - <value2> of value set.
  1245. Return Type :BOOL
  1246. Global Variables :None
  1247. Calling Syntax :IsValueSet(pszFromValue,cValue1,cValue2)
  1248. Notes :None
  1249. ----------------------------------------------------------------------------*/
  1250. BOOL IsValueSet(_TCHAR* pszFromValue, _TCHAR& cValue1, _TCHAR& cValue2)
  1251. {
  1252. BOOL bValueSet = FALSE;
  1253. if ( pszFromValue != NULL )
  1254. {
  1255. _TCHAR cV1 = _T('\0'), cV2 = _T('\0');
  1256. if ( lstrlen(pszFromValue) == 3 && pszFromValue[1] == _T('-') )
  1257. {
  1258. bValueSet = TRUE;
  1259. cV1 = pszFromValue[0];
  1260. cV2 = pszFromValue[2];
  1261. cValue1 = ( cV1 < cV2 ) ? cV1 : cV2 ;
  1262. cValue2 = ( cV1 > cV2 ) ? cV1 : cV2 ;
  1263. }
  1264. }
  1265. else
  1266. cValue1 = cValue2 = _T('\0');
  1267. return bValueSet;
  1268. }
  1269. /*----------------------------------------------------------------------------
  1270. Name :DisplayString
  1271. Synopsis :Displays localized string
  1272. Type :Global Function
  1273. Input parameter(s):
  1274. uID - string table identifier
  1275. uCP - codepage value
  1276. lpszParam - String to be used as parameter in resource string.
  1277. bIsError - Boolean type specifying error message or not.
  1278. bIsLog - Boolean type specifying message to be logged or not.
  1279. Output parameter(s):None
  1280. Return Type :void
  1281. Global Variables :None
  1282. Calling Syntax :DisplayString(uID, CP_OEMCP, NULL, TRUE, TRUE)
  1283. Notes :lpszParam = NULL, bIsError = FALSE, and bIsLog = FALSE
  1284. by default.
  1285. ----------------------------------------------------------------------------*/
  1286. void DisplayString(UINT uID, UINT uCP, LPTSTR lpszParam,
  1287. BOOL bIsError, BOOL bIsLog) throw(WMICLIINT)
  1288. {
  1289. LPTSTR lpszMsg = NULL;
  1290. LPSTR lpszDisp = NULL;
  1291. lpszMsg = new _TCHAR [BUFFER1024];
  1292. try
  1293. {
  1294. if (lpszMsg)
  1295. {
  1296. LoadString(NULL, uID, lpszMsg, BUFFER1024);
  1297. LPVOID lpMsgBuf = NULL;
  1298. if (lpszParam)
  1299. {
  1300. char* pvaInsertStrs[1];
  1301. pvaInsertStrs[0] = (char*) lpszParam;
  1302. DWORD dwRet = FormatMessage(
  1303. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1304. FORMAT_MESSAGE_FROM_STRING |
  1305. FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1306. lpszMsg,
  1307. 0,
  1308. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1309. (LPTSTR) &lpMsgBuf,
  1310. 0,
  1311. pvaInsertStrs);
  1312. if (dwRet == 0)
  1313. {
  1314. SAFEDELETE(lpszMsg);
  1315. throw (::GetLastError());
  1316. }
  1317. }
  1318. if ( lpMsgBuf != NULL )
  1319. {
  1320. if (!ConvertWCToMBCS((LPTSTR)lpMsgBuf, (LPVOID*) &lpszDisp,
  1321. uCP))
  1322. {
  1323. LocalFree(lpMsgBuf);
  1324. throw OUT_OF_MEMORY;
  1325. }
  1326. }
  1327. else
  1328. {
  1329. if (!ConvertWCToMBCS(lpszMsg, (LPVOID*) &lpszDisp, uCP))
  1330. {
  1331. SAFEDELETE(lpszMsg);
  1332. throw OUT_OF_MEMORY;
  1333. }
  1334. }
  1335. if (bIsLog)
  1336. {
  1337. // Append to the output string
  1338. g_wmiCmd.GetFormatObject().AppendtoOutputString((_TCHAR*)
  1339. _bstr_t(lpszDisp));
  1340. }
  1341. if ( bIsError == TRUE )
  1342. {
  1343. fprintf(stderr, "%s", lpszDisp);
  1344. fflush(stderr);
  1345. }
  1346. else
  1347. {
  1348. OUTPUTSPEC opsOutOpt = g_wmiCmd.GetParsedInfoObject().
  1349. GetGlblSwitchesObject().
  1350. GetOutputOrAppendOption(TRUE);
  1351. // OUT for getting append file pointer.
  1352. FILE* fpOutFile = g_wmiCmd.GetParsedInfoObject().
  1353. GetGlblSwitchesObject().
  1354. GetOutputOrAppendFilePointer(TRUE);
  1355. if (opsOutOpt == CLIPBOARD )
  1356. g_wmiCmd.AddToClipBoardBuffer(lpszDisp);
  1357. else if (opsOutOpt == FILEOUTPUT )
  1358. {
  1359. if (fpOutFile != NULL)
  1360. {
  1361. fprintf(fpOutFile, "%s", lpszDisp);
  1362. }
  1363. else
  1364. {
  1365. fprintf(stdout, "%s", lpszDisp);
  1366. fflush(stdout);
  1367. }
  1368. }
  1369. else
  1370. {
  1371. fprintf(stdout,"%s", lpszDisp);
  1372. fflush(stdout);
  1373. }
  1374. // FALSE for getting append file pointer.
  1375. FILE* fpAppendFile = g_wmiCmd.GetParsedInfoObject().
  1376. GetGlblSwitchesObject().
  1377. GetOutputOrAppendFilePointer(FALSE);
  1378. if ( fpAppendFile != NULL )
  1379. fprintf(fpAppendFile, "%s", lpszDisp);
  1380. }
  1381. SAFEDELETE(lpszDisp);
  1382. SAFEDELETE(lpszMsg);
  1383. // Free the memory used up the error message
  1384. // and then exit
  1385. if ( lpMsgBuf != NULL )
  1386. LocalFree(lpMsgBuf);
  1387. }
  1388. else
  1389. throw OUT_OF_MEMORY;
  1390. }
  1391. catch(_com_error& e)
  1392. {
  1393. SAFEDELETE(lpszDisp);
  1394. SAFEDELETE(lpszMsg);
  1395. _com_issue_error(e.Error());
  1396. }
  1397. catch(CHeap_Exception)
  1398. {
  1399. SAFEDELETE(lpszDisp);
  1400. SAFEDELETE(lpszMsg);
  1401. _com_issue_error(WBEM_E_OUT_OF_MEMORY);
  1402. }
  1403. }
  1404. /*----------------------------------------------------------------------------
  1405. Name :SubstituteEscapeChars
  1406. Synopsis :Substitue escape character i.e '\' before the
  1407. specified substring
  1408. Type :Global Function
  1409. Input parameter :
  1410. sSource - source string
  1411. lpszSub - substring to be searched for
  1412. Output parameters :
  1413. sSource - source string
  1414. Return Type :void
  1415. Global Variables :None
  1416. Calling Syntax :SubstituteEscapeChars(sTemp, lpszSub)
  1417. Notes :None
  1418. ----------------------------------------------------------------------------*/
  1419. void SubstituteEscapeChars(CHString& sTemp, LPCWSTR lpszSub)
  1420. {
  1421. try
  1422. {
  1423. CHString str(sTemp);
  1424. sTemp.Empty();
  1425. while ( str.GetLength() > 0 )
  1426. {
  1427. //LONG lPos = str.Find( L"\"" );
  1428. LONG lPos = str.Find(lpszSub);
  1429. if ( lPos != -1 )
  1430. {
  1431. sTemp += str.Left( lPos ) + L"\\\"";
  1432. str = str.Mid( lPos + 1 );
  1433. }
  1434. else
  1435. {
  1436. sTemp += str;
  1437. str.Empty();
  1438. }
  1439. }
  1440. }
  1441. catch(CHeap_Exception)
  1442. {
  1443. _com_issue_error(WBEM_E_OUT_OF_MEMORY);
  1444. }
  1445. }
  1446. /*----------------------------------------------------------------------------
  1447. Name :RemoveEscapeChars
  1448. Synopsis :Remove escape character i.e '\' before any of the
  1449. following characters
  1450. Type :Global Function
  1451. Input parameter(s):
  1452. sSource - source string
  1453. Output parameter(s):
  1454. sSource - source string
  1455. Return Type :void
  1456. Global Variables :None
  1457. Calling Syntax :RemoveEscapeChars(sTemp)
  1458. Notes :None
  1459. ----------------------------------------------------------------------------*/
  1460. void RemoveEscapeChars(CHString& sTemp)
  1461. {
  1462. try
  1463. {
  1464. CHString str(sTemp);
  1465. sTemp.Empty();
  1466. while ( str.GetLength() > 0 )
  1467. {
  1468. LONG lPos = str.Find(L"\\");
  1469. if ( lPos != -1 )
  1470. {
  1471. if (str.GetAt(lPos+1) == L'"')
  1472. {
  1473. sTemp += str.Left( lPos );
  1474. }
  1475. else
  1476. {
  1477. sTemp += str.Left( lPos ) + L"\\";
  1478. }
  1479. str = str.Mid( lPos + 1 );
  1480. }
  1481. else
  1482. {
  1483. sTemp += str;
  1484. str.Empty();
  1485. }
  1486. }
  1487. }
  1488. catch(CHeap_Exception)
  1489. {
  1490. throw OUT_OF_MEMORY;
  1491. }
  1492. }
  1493. /*----------------------------------------------------------------------------
  1494. Name :FrameNamespace
  1495. Synopsis :Frame the new namespace
  1496. Type :Global Function
  1497. Input parameter(s):
  1498. pszRoleOrNS - old namespace
  1499. pszRoleOrNSToUpdate - string to be appended/replaced
  1500. Output parameter(s):
  1501. pszRoleOrNSToUpdate - new namespace
  1502. Return Type :void
  1503. Global Variables :None
  1504. Calling Syntax :FrameNamespace(pszRoleOrNS, pszRoleOrNSToUpdate)
  1505. Notes :None
  1506. ----------------------------------------------------------------------------*/
  1507. void FrameNamespace(_TCHAR* pszRoleOrNS, _TCHAR* pszRoleOrNSToUpdate)
  1508. {
  1509. if ( pszRoleOrNS != NULL && pszRoleOrNSToUpdate != NULL )
  1510. {
  1511. LONG lRoleOrNSLen = lstrlen(pszRoleOrNS);
  1512. LONG lRoleOrNSToUpdate = lstrlen(pszRoleOrNSToUpdate);
  1513. _TCHAR *pszTemp = new _TCHAR[lRoleOrNSLen + lRoleOrNSToUpdate +
  1514. MAX_BUFFER];
  1515. if ( pszTemp != NULL )
  1516. {
  1517. if (!CompareTokens(pszRoleOrNS, CLI_TOKEN_NULL))
  1518. {
  1519. //if the role does not begin with a '\\' it should be assumed
  1520. //to be relative to the current role
  1521. if ( _tcsncmp(pszRoleOrNS, CLI_TOKEN_2BSLASH, 2) == 0 )
  1522. lstrcpy(pszTemp, pszRoleOrNS+2);
  1523. else if (_tcsncmp(pszRoleOrNS, CLI_TOKEN_2DOT, 2) == 0 )
  1524. {
  1525. _TCHAR *lp = NULL;
  1526. for (lp = &pszRoleOrNSToUpdate[lstrlen(pszRoleOrNSToUpdate) - 1];
  1527. lp > pszRoleOrNSToUpdate; lp--)
  1528. {
  1529. if (_tcsncmp(lp,CLI_TOKEN_2BSLASH,1) == 0)
  1530. { lstrcpy(lp,NULL_STRING);
  1531. break;
  1532. }
  1533. }
  1534. lstrcpy(pszTemp, pszRoleOrNSToUpdate);
  1535. if (_tcsncmp(pszRoleOrNS + 2, NULL_STRING, 1))
  1536. {
  1537. lstrcat(pszTemp, pszRoleOrNS + 2);
  1538. }
  1539. }
  1540. else
  1541. {
  1542. lstrcpy(pszTemp, pszRoleOrNSToUpdate);
  1543. lstrcat(pszTemp, CLI_TOKEN_BSLASH);
  1544. lstrcat(pszTemp, pszRoleOrNS);
  1545. }
  1546. //if the last character in the string pszRoleOrNS terminates
  1547. //with '\' terminate the string.
  1548. //this case occurs when namespace is specified as "xyz\"
  1549. if(CompareTokens(pszTemp + (WMICLIINT)lstrlen(pszTemp)-1,
  1550. CLI_TOKEN_BSLASH ) &&
  1551. !CompareTokens(pszTemp, CLI_TOKEN_2BSLASH))
  1552. {
  1553. pszTemp[lstrlen(pszTemp) - 1] = _T('\0');
  1554. }
  1555. }
  1556. else
  1557. lstrcpy(pszTemp, CLI_TOKEN_NULL);
  1558. lstrcpy(pszRoleOrNSToUpdate, pszTemp);
  1559. SAFEDELETE(pszTemp);
  1560. }
  1561. else
  1562. throw OUT_OF_MEMORY;
  1563. }
  1564. else
  1565. throw OUT_OF_MEMORY;
  1566. }
  1567. /*----------------------------------------------------------------------------
  1568. Name :SetScreenBuffer
  1569. Synopsis :Set the buffer size of the command line to the
  1570. following:
  1571. 1) Width - 500
  1572. 2) Height - 3000
  1573. Type :Global Function
  1574. Input parameter(s):
  1575. nHeight - height of the console buffer
  1576. nWidth - width of the console buffer
  1577. Output parameter(s):None
  1578. Return Type :void
  1579. Global Variables :None
  1580. Calling Syntax :SetScreenBuffer(nHeight, nWidth)
  1581. Notes :None
  1582. ----------------------------------------------------------------------------*/
  1583. void SetScreenBuffer(SHORT nHeight, SHORT nWidth)
  1584. {
  1585. HANDLE hStdOut = NULL;
  1586. COORD coord;
  1587. coord.X = nWidth;
  1588. coord.Y = nHeight;
  1589. hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1590. if ( hStdOut != INVALID_HANDLE_VALUE &&
  1591. hStdOut != (HANDLE)0x00000013 ) // For telnet
  1592. {
  1593. // Set the console screen buffer info
  1594. SetConsoleScreenBufferSize(hStdOut, coord);
  1595. }
  1596. }
  1597. /*----------------------------------------------------------------------------
  1598. Name :GetScreenBuffer
  1599. Synopsis :Get the buffer size of the command line
  1600. Type :Global Function
  1601. Input parameter(s):None
  1602. Output parameter(s):
  1603. nHeight - height of the console buffer
  1604. nWidth - width of the console buffer
  1605. Return Type :void
  1606. Global Variables :None
  1607. Calling Syntax :GetScreenBuffer(nHeight, nWidth)
  1608. Notes :None
  1609. ----------------------------------------------------------------------------*/
  1610. void GetScreenBuffer(SHORT& nHeight, SHORT& nWidth)
  1611. {
  1612. HANDLE hStdOut = NULL;
  1613. hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1614. if ( hStdOut != INVALID_HANDLE_VALUE &&
  1615. hStdOut != (HANDLE)0x00000013 ) // For telnet
  1616. {
  1617. CONSOLE_SCREEN_BUFFER_INFO csbConsoleScreenBufferInfo;
  1618. // Set the console screen buffer info
  1619. GetConsoleScreenBufferInfo(hStdOut, &csbConsoleScreenBufferInfo);
  1620. nHeight = csbConsoleScreenBufferInfo.dwSize.Y;
  1621. nWidth = csbConsoleScreenBufferInfo.dwSize.X;
  1622. }
  1623. }
  1624. /*----------------------------------------------------------------------------
  1625. Name :WMIFormatMessage
  1626. Synopsis :This function loads the resource string using the
  1627. ID of the string and does parameter substituion using
  1628. the FormatMessage() function.
  1629. Type :Global Function
  1630. Input parameter(s):
  1631. uID - resource ID
  1632. nParamCount - no. of. parameter(s) to be substituted.
  1633. lpszParam - first parameter. (%1)
  1634. ... - variable number of arguments (%2, %3, ...)
  1635. Output parameter(s):
  1636. bstrMSG - formatted message
  1637. Return Type :void
  1638. Global Variables :None
  1639. Calling Syntax :WMIFormatMessage(uID, nParamCount, bstrMsg,
  1640. lpszParam,)
  1641. Notes :None
  1642. ----------------------------------------------------------------------------*/
  1643. void WMIFormatMessage(UINT uID, WMICLIINT nParamCount, _bstr_t& bstrMsg,
  1644. LPTSTR lpszParam, ...)
  1645. {
  1646. // Load the resource string
  1647. _TCHAR pszMsg[BUFFER1024];
  1648. LoadString(NULL, uID, pszMsg, BUFFER1024);
  1649. // If parameters are specified.
  1650. if (lpszParam)
  1651. {
  1652. LPTSTR lpszTemp = lpszParam;
  1653. INT nLoop = 0;
  1654. char* pvaInsertStrs[5];
  1655. va_list marker;
  1656. va_start(marker, lpszParam);
  1657. while (TRUE)
  1658. {
  1659. pvaInsertStrs[nLoop++] = (char*) lpszTemp;
  1660. lpszTemp = va_arg(marker, LPTSTR);
  1661. if (nLoop == nParamCount)
  1662. break;
  1663. }
  1664. va_end(marker);
  1665. LPVOID lpMsgBuf = NULL;
  1666. FormatMessage(
  1667. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1668. FORMAT_MESSAGE_FROM_STRING |
  1669. FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1670. pszMsg,
  1671. 0,
  1672. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1673. (LPTSTR) &lpMsgBuf,
  1674. 0,
  1675. pvaInsertStrs);
  1676. bstrMsg = (WCHAR*)lpMsgBuf;
  1677. // Free the memory used for the message and then exit
  1678. LocalFree(lpMsgBuf);
  1679. }
  1680. else
  1681. bstrMsg = pszMsg;
  1682. }
  1683. /*----------------------------------------------------------------------------
  1684. Name :InitWinsock
  1685. Synopsis :This function initiates the windows sockets interface.
  1686. Type :Global Function
  1687. Input parameter :None
  1688. Output parameters :None
  1689. Return Type :BOOL
  1690. Global Variables :None
  1691. Calling Syntax :InitWinsock ()
  1692. Notes :None
  1693. ----------------------------------------------------------------------------*/
  1694. BOOL InitWinsock ()
  1695. {
  1696. BOOL bSuccess = TRUE;
  1697. int nRes;
  1698. WSADATA wsaData;
  1699. WORD wVerRequested = 0x0101; // ver 1.1
  1700. // The Windows Sockets WSAStartup function initiates use of Ws2_32.dll
  1701. // by a process.
  1702. // Init the sockets interface
  1703. nRes = WSAStartup (wVerRequested, &wsaData);
  1704. if (nRes)
  1705. bSuccess = FALSE;
  1706. return bSuccess;
  1707. }
  1708. /*----------------------------------------------------------------------------
  1709. Name :TermWinsock
  1710. Synopsis :This function uninitializes the windows sockets
  1711. interface.
  1712. Type :Global Function
  1713. Input parameter :None
  1714. Output parameters :None
  1715. Return Type :BOOL
  1716. Global Variables :None
  1717. Calling Syntax :TermWinsock ()
  1718. Notes :None
  1719. ----------------------------------------------------------------------------*/
  1720. BOOL TermWinsock ()
  1721. {
  1722. // Uninitailize windows socket interface.
  1723. BOOL bSuccess = TRUE;
  1724. if (SOCKET_ERROR == WSACleanup ())
  1725. bSuccess = FALSE;
  1726. return bSuccess;
  1727. }
  1728. /*----------------------------------------------------------------------------
  1729. Name :PingNode
  1730. Synopsis :Pings a node to validate availibility of node using
  1731. windows socket functions.
  1732. Type :Global Function
  1733. Input parameter :
  1734. pszNode - Pointer to a string specifing node name.
  1735. Output parameters :None
  1736. Return Type :BOOL
  1737. Global Variables :None
  1738. Calling Syntax :PingNode(pszNode)
  1739. Notes :None
  1740. ----------------------------------------------------------------------------*/
  1741. BOOL PingNode(_TCHAR* pszNode)
  1742. {
  1743. BOOL bRet = TRUE;
  1744. try
  1745. {
  1746. if ( pszNode )
  1747. {
  1748. // pszNode can be IPAddress of node or node name itself.
  1749. _bstr_t bstrNodeNameOrIPAddr(pszNode);
  1750. // Initialize windows socket interface.
  1751. if ( g_wmiCmd.GetInitWinSock() == FALSE )
  1752. {
  1753. bRet = InitWinsock();
  1754. g_wmiCmd.SetInitWinSock(bRet);
  1755. }
  1756. if ( bRet )
  1757. {
  1758. // Get IPAddress.
  1759. ULONG ulINAddr = inet_addr(bstrNodeNameOrIPAddr);
  1760. // If not an IP address. then it may be computername.
  1761. if ( ulINAddr == INADDR_NONE )
  1762. {
  1763. if ( gethostbyname(bstrNodeNameOrIPAddr) == NULL )
  1764. bRet = FALSE; // "computername" is not found.
  1765. }
  1766. else // It is an valid IP Address.
  1767. {
  1768. if ( gethostbyaddr((char*) &ulINAddr, sizeof(ulINAddr), AF_INET) == NULL )
  1769. bRet = FALSE;
  1770. }
  1771. }
  1772. }
  1773. else
  1774. bRet = FALSE; // Null nodename pointer.
  1775. }
  1776. catch(_com_error& e)
  1777. {
  1778. bRet = FALSE;
  1779. _com_issue_error(e.Error());
  1780. }
  1781. return bRet;
  1782. }
  1783. /*----------------------------------------------------------------------------
  1784. Name :IsFailFastAndNodeExist
  1785. Synopsis :Validates node if FailFast is on, If pszNodeName == NULL
  1786. then check for GetNode() else pszNodeName itself.
  1787. Type :Global Function
  1788. Input parameter(s):
  1789. rParsedInfo - reference to object of CParsedInfo.
  1790. pszNode - Pointer to a string specifing node name.
  1791. Output parameter(s):None
  1792. Return Type :BOOL
  1793. Global Variables :None
  1794. Calling Syntax :IsFailFastAndNodeExist(rParsedInfo, pszNode)
  1795. Notes :None
  1796. ----------------------------------------------------------------------------*/
  1797. BOOL IsFailFastAndNodeExist(CParsedInfo& rParsedInfo, _TCHAR* pszNode)
  1798. {
  1799. BOOL bRet = TRUE;
  1800. // If FailFast is on.
  1801. if ( rParsedInfo.GetGlblSwitchesObject().GetFailFast() == TRUE )
  1802. {
  1803. // Form the appropriate node name. If pszNodeName != NULL pszNode
  1804. // should be validated. Else Node stored should be validated.
  1805. _TCHAR* pszNodeName = NULL;
  1806. if (pszNode == NULL)
  1807. pszNodeName = rParsedInfo.GetGlblSwitchesObject().GetNode();
  1808. else
  1809. pszNodeName = pszNode;
  1810. // "." node name specifies local machine and need not to be validated.
  1811. if ( CompareTokens(pszNodeName, CLI_TOKEN_DOT) == FALSE )
  1812. {
  1813. // If pinging node fails then node is unavialable.
  1814. if ( PingNode(pszNodeName) == FALSE )
  1815. {
  1816. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(
  1817. IDS_E_RPC_SERVER_NOT_AVAILABLE);
  1818. bRet = FALSE;
  1819. }
  1820. }
  1821. }
  1822. return bRet;
  1823. }
  1824. /*----------------------------------------------------------------------------
  1825. Name :GetBstrTFromVariant
  1826. Synopsis :Get _bstr_t object equivalent to Varaint passed.
  1827. Type :Global Function
  1828. Input parameter(s):
  1829. vtVar - variant object
  1830. pszType - Pointer to string specifying type of the object passed.
  1831. Output parameter(s):
  1832. bstrObj - BSTR object
  1833. Return Type :BOOL
  1834. Global Variables :None
  1835. Calling Syntax :GetBstrTFromVariant(vtVar, bstrObj)
  1836. Notes :None
  1837. ----------------------------------------------------------------------------*/
  1838. void GetBstrTFromVariant(VARIANT& vtVar, _bstr_t& bstrObj,
  1839. _TCHAR* pszType)
  1840. {
  1841. VARTYPE vType;
  1842. VARIANT vtDest;
  1843. VariantInit(&vtDest);
  1844. try
  1845. {
  1846. if ( vtVar.vt != VT_NULL && vtVar.vt != VT_EMPTY )
  1847. {
  1848. if ( VariantChangeType(&vtDest, &vtVar,0 , VT_BSTR) == S_OK )
  1849. {
  1850. bstrObj = _bstr_t(vtDest);
  1851. }
  1852. else
  1853. {
  1854. // The following line assures that
  1855. // if an exception is thrown (say
  1856. // in the bstr_t allocation below)
  1857. // VariantClear in the catch statement
  1858. // won't try to clear anything.
  1859. V_VT(&vtDest) = VT_EMPTY;
  1860. if ( vtVar.vt == VT_UNKNOWN )
  1861. {
  1862. if ( pszType != NULL )
  1863. {
  1864. bstrObj = _bstr_t(pszType);
  1865. }
  1866. else
  1867. {
  1868. bstrObj = _bstr_t("<Embeded Object>");
  1869. }
  1870. }
  1871. else if ( SafeArrayGetVartype(vtVar.parray, &vType) == S_OK )
  1872. {
  1873. if ( pszType != NULL )
  1874. {
  1875. bstrObj = _bstr_t("<Array of ") + _bstr_t(pszType) +
  1876. _bstr_t(">");
  1877. }
  1878. else
  1879. {
  1880. bstrObj = _bstr_t("<Array>");
  1881. }
  1882. }
  1883. else
  1884. {
  1885. bstrObj = _bstr_t("UNKNOWN");
  1886. }
  1887. }
  1888. }
  1889. else
  1890. {
  1891. bstrObj = _bstr_t(_T("<null>"));
  1892. }
  1893. VARIANTCLEAR(vtDest);
  1894. }
  1895. catch(_com_error& e)
  1896. {
  1897. VARIANTCLEAR(vtDest);
  1898. _com_issue_error(e.Error());
  1899. }
  1900. }
  1901. /*----------------------------------------------------------------------------
  1902. Name :IsValidFile
  1903. Synopsis :This functions checks if a given file name is
  1904. Valid.
  1905. Type :Global Function
  1906. Input parameter(s):
  1907. pszFileName - String type, Name of the file to be validated
  1908. Output parameter(s):None
  1909. Return Type :RETCODE
  1910. Global Variables :None
  1911. Calling Syntax :IsValidFile(pszFileName)
  1912. Notes :None
  1913. ----------------------------------------------------------------------------*/
  1914. RETCODE IsValidFile(_TCHAR* pszFileName)
  1915. {
  1916. RETCODE bRet = PARSER_ERROR;
  1917. BOOL bValidFileName = TRUE;
  1918. LONG lFileNameLen = lstrlen(pszFileName);
  1919. LONG lCount = lFileNameLen;
  1920. while( lCount >= 0 )
  1921. {
  1922. if (pszFileName[lCount] == _T('\\'))
  1923. break;
  1924. lCount--;
  1925. }
  1926. if(lCount != 0)
  1927. lCount++;
  1928. while( lCount <= lFileNameLen )
  1929. {
  1930. if( pszFileName[lCount] == _T('/') ||
  1931. pszFileName[lCount] == _T('\\') ||
  1932. pszFileName[lCount] == _T(':') ||
  1933. pszFileName[lCount] == _T('*') ||
  1934. pszFileName[lCount] == _T('?') ||
  1935. pszFileName[lCount] == _T('\"') ||
  1936. pszFileName[lCount] == _T('<') ||
  1937. pszFileName[lCount] == _T('>') ||
  1938. pszFileName[lCount] == _T('|') )
  1939. {
  1940. bValidFileName = FALSE;
  1941. break;
  1942. }
  1943. lCount++;
  1944. }
  1945. if ( pszFileName != NULL && bValidFileName == TRUE)
  1946. {
  1947. FILE *fpFile = _tfopen(pszFileName, _T("a"));
  1948. if ( fpFile != NULL )
  1949. {
  1950. LONG lFileHandle = _fileno(fpFile);
  1951. if ( _filelength(lFileHandle) == 0)
  1952. {
  1953. if ( fclose(fpFile) == 0 )
  1954. {
  1955. if ( _tremove(pszFileName) == 0 )
  1956. bRet = PARSER_CONTINUE;
  1957. else
  1958. {
  1959. DisplayWin32Error();
  1960. bRet = PARSER_ERRMSG;
  1961. }
  1962. }
  1963. }
  1964. else if ( fclose(fpFile) == 0 )
  1965. bRet = PARSER_CONTINUE;
  1966. }
  1967. }
  1968. return bRet;
  1969. }
  1970. /*----------------------------------------------------------------------------
  1971. Name :FindAndReplaceEntityReferences
  1972. Synopsis :Search and replace all the occurences of entity
  1973. references.
  1974. Type :Global Function
  1975. Input parameter(s):
  1976. strString - string buffer
  1977. Output parameter(s):None
  1978. Return Type :void
  1979. Global Variables :None
  1980. Calling Syntax :FindAndReplaceEntityReferences(strString);
  1981. Notes :None
  1982. ----------------------------------------------------------------------------*/
  1983. void FindAndReplaceEntityReferences(_bstr_t& bstrString)
  1984. {
  1985. STRING strString((_TCHAR*)bstrString);
  1986. FindAndReplaceAll(strString, _T("&"), _T("&amp;"));
  1987. FindAndReplaceAll(strString, _T("<"), _T("&lt;"));
  1988. FindAndReplaceAll(strString, _T(">"), _T("&gt;"));
  1989. FindAndReplaceAll(strString, _T("\'"), _T("&apos;"));
  1990. FindAndReplaceAll(strString, _T("\""), _T("&quot;"));
  1991. try
  1992. {
  1993. bstrString = _bstr_t((LPTSTR)strString.data());
  1994. }
  1995. catch(_com_error& e)
  1996. {
  1997. _com_issue_error(e.Error());
  1998. }
  1999. }
  2000. /*----------------------------------------------------------------------------
  2001. Name :IsOption
  2002. Synopsis :It checks whether the current token indicates option. An
  2003. option can start with '/' or '-'
  2004. Type :Global Function
  2005. Input Parameter(s):
  2006. pszToken - pointer to token.
  2007. Output Parameter(s):None
  2008. Return Type :BOOL
  2009. Global Variables :None
  2010. Calling Syntax :IsOption(pszToken)
  2011. Notes :None
  2012. ----------------------------------------------------------------------------*/
  2013. BOOL IsOption(_TCHAR* pszToken)
  2014. {
  2015. BOOL bRet = TRUE;
  2016. if ( pszToken != NULL )
  2017. {
  2018. bRet = (CompareTokens(pszToken, CLI_TOKEN_FSLASH)
  2019. || CompareTokens(pszToken, CLI_TOKEN_HYPHEN))
  2020. ? TRUE : FALSE;
  2021. }
  2022. else
  2023. bRet = FALSE;
  2024. return bRet;
  2025. }
  2026. /*----------------------------------------------------------------------------
  2027. Name :IsClassOperation
  2028. Synopsis :It checks whether the current operation is class
  2029. level operation or instance level operation
  2030. Type :Global Function
  2031. Input Parameter(s):
  2032. rParsedInfo - reference to CParsedInfo class object
  2033. Output Parameter(s):None
  2034. Return Type :BOOL
  2035. Global Variables :None
  2036. Calling Syntax :IsClassOperation(rParsedInfo)
  2037. Notes :None
  2038. ----------------------------------------------------------------------------*/
  2039. BOOL IsClassOperation(CParsedInfo& rParsedInfo)
  2040. {
  2041. BOOL bClass = FALSE;
  2042. if ( rParsedInfo.GetCmdSwitchesObject().GetAliasName() == NULL
  2043. && (rParsedInfo.GetCmdSwitchesObject().
  2044. GetWhereExpression() == NULL)
  2045. && (rParsedInfo.GetCmdSwitchesObject().
  2046. GetPathExpression() == NULL))
  2047. {
  2048. bClass = TRUE;
  2049. }
  2050. return bClass;
  2051. }
  2052. /*-------------------------------------------------------------------------
  2053. Name :ModifyPrivileges
  2054. Synopsis :This function enables/disables all the token privileges
  2055. for current process token.
  2056. Type :Global Function
  2057. Input Parameter(s):
  2058. bEnable - Enable|Disable privileges flag
  2059. Output Parameter(s):None
  2060. Return Type :HRESULT
  2061. Global Variables :None
  2062. Calling Syntax :ModifyPrivileges(bEnable)
  2063. Notes :none
  2064. -------------------------------------------------------------------------*/
  2065. HRESULT ModifyPrivileges(BOOL bEnable)
  2066. {
  2067. HANDLE hToken = NULL;
  2068. DWORD dwError = ERROR_SUCCESS,
  2069. dwLen = 0;
  2070. BOOL bRes = TRUE;
  2071. TOKEN_USER tu;
  2072. HRESULT hr = WBEM_S_NO_ERROR;
  2073. BYTE *pBuffer = NULL;
  2074. // Open the access token associated with the current process.
  2075. bRes = OpenProcessToken(GetCurrentProcess(),
  2076. TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
  2077. &hToken);
  2078. if (bRes)
  2079. {
  2080. // If disable privilges
  2081. if (!bEnable)
  2082. {
  2083. // Store the information back into the token,after disabling all
  2084. // the privileges
  2085. bRes = AdjustTokenPrivileges(hToken, TRUE, NULL, 0, NULL, NULL);
  2086. if (!bRes)
  2087. hr = WBEM_E_ACCESS_DENIED;
  2088. }
  2089. else // If enable privileges
  2090. {
  2091. // Get the privileges
  2092. memset(&tu,0,sizeof(TOKEN_USER));
  2093. bRes = GetTokenInformation(hToken, TokenPrivileges, &tu,
  2094. sizeof(TOKEN_USER), &dwLen);
  2095. pBuffer = new BYTE[dwLen];
  2096. if(pBuffer != NULL)
  2097. {
  2098. bRes = GetTokenInformation(hToken, TokenPrivileges,
  2099. pBuffer, dwLen, &dwLen);
  2100. if (bRes)
  2101. {
  2102. // Iterate through all the privileges and enable them all
  2103. TOKEN_PRIVILEGES* pPrivs = (TOKEN_PRIVILEGES*)pBuffer;
  2104. for (DWORD i = 0; i < pPrivs->PrivilegeCount; i++)
  2105. {
  2106. pPrivs->Privileges[i].Attributes
  2107. |= SE_PRIVILEGE_ENABLED;
  2108. }
  2109. // Store the information back into the token
  2110. bRes = AdjustTokenPrivileges(hToken, FALSE, pPrivs, 0,
  2111. NULL, NULL);
  2112. if (!bRes)
  2113. hr = WBEM_E_ACCESS_DENIED;
  2114. }
  2115. else
  2116. hr = WBEM_E_ACCESS_DENIED;
  2117. SAFEDELETE(pBuffer);
  2118. }
  2119. else
  2120. hr = WBEM_E_OUT_OF_MEMORY;
  2121. }
  2122. CloseHandle(hToken);
  2123. }
  2124. else
  2125. hr = WBEM_E_ACCESS_DENIED;
  2126. return hr;
  2127. }