Leaked source code of windows server 2003
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.

3087 lines
88 KiB

  1. /****************************************************************************
  2. Copyright information : Copyright (c) 1998-2002 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. /*----------------------------------------------------------------------------
  28. Name :CompareTokens
  29. Synopsis :It compares the two tokens passed to it as input
  30. arguments and returns a BOOL value ,
  31. TRUE if they are equal
  32. FALSE if not equal.
  33. Type :Global Function
  34. Input parameter(s):
  35. pszToken1- String type, Contains the first string of the two
  36. string to be compared
  37. pszToken2- String type, Contains the second string of the two
  38. string to be compared
  39. Output parameter(s):None
  40. Return Type :BOOL
  41. Global Variables :None
  42. Calling Syntax :CompareTokens(pszToken1,pszToken2)
  43. Notes :None
  44. ----------------------------------------------------------------------------*/
  45. BOOL CompareTokens(_TCHAR* pszToken1, _TCHAR* pszToken2)
  46. {
  47. return (CSTR_EQUAL == CompareString(LOCALE_SYSTEM_DEFAULT,
  48. NORM_IGNORECASE | NORM_IGNOREWIDTH,
  49. pszToken1, (pszToken1) ? lstrlen(pszToken1) : 0,
  50. pszToken2, (pszToken2) ? lstrlen(pszToken2) : 0))
  51. ? TRUE : FALSE;
  52. }
  53. /*----------------------------------------------------------------------------
  54. Name :CompareTokensChars
  55. Synopsis :It compares the two tokens passed to it as input
  56. arguments and returns a BOOL value ,
  57. TRUE if they are equal
  58. FALSE if not equal.
  59. Type :Global Function
  60. Input parameter(s):
  61. pszToken1- String type, Contains the first string of the two
  62. string to be compared
  63. pszToken2- String type, Contains the second string of the two
  64. string to be compared
  65. cchToken- number of characters to compare
  66. Output parameter(s):None
  67. Return Type :BOOL
  68. Global Variables :None
  69. Calling Syntax :CompareTokensChars(pszToken1,pszToken2,cchToken)
  70. Notes :None
  71. ----------------------------------------------------------------------------*/
  72. BOOL CompareTokensChars(_TCHAR* pszToken1, _TCHAR* pszToken2, DWORD cchToken)
  73. {
  74. DWORD cchSize = cchToken ;
  75. cchSize = min ( (pszToken1) ? lstrlen(pszToken1) : 0, cchSize ) ;
  76. cchSize = min ( (pszToken2) ? lstrlen(pszToken2) : 0, cchSize ) ;
  77. return (CSTR_EQUAL == CompareString ( LOCALE_SYSTEM_DEFAULT,
  78. NORM_IGNORECASE | NORM_IGNOREWIDTH,
  79. pszToken1,
  80. cchSize,
  81. pszToken2,
  82. cchSize
  83. )
  84. ) ? TRUE : FALSE;
  85. }
  86. /*----------------------------------------------------------------------------
  87. Name :Connect
  88. Synopsis :To connect to WMI namespace on a given server with the
  89. set of input user credentials.
  90. Type :Global Function
  91. Input parameter(s):
  92. pILocator - Locator object
  93. bstrNS - Namespae to be connected to
  94. bstrUser - User name with which to connect
  95. bstrPwd - Password for the user name with which to connect
  96. bstrLocale - Locale specified
  97. Output parameters :
  98. pISvc - WMI services object
  99. Return Type :HRESULT
  100. Global Variables :None
  101. Calling Syntax :Connect(pILocator, &pISvc, bstrNS, bstrUser, bstPwd,
  102. bstrLocale)
  103. Notes :None
  104. ----------------------------------------------------------------------------*/
  105. HRESULT Connect(IWbemLocator* pILocator, IWbemServices** pISvc,
  106. BSTR bstrNS, BSTR bstrUser, BSTR bstrPwd,
  107. BSTR bstrLocale, CParsedInfo& rParsedInfo)
  108. {
  109. HRESULT hr = S_OK;
  110. BSTR bstrPass = NULL;
  111. BSTR bstrAuthorityPrinciple = NULL;
  112. // If the user name is not NULL and the password is
  113. // a) NULL, treat the password as BLANK
  114. // b) not NULL, treat the password as it is.
  115. try
  116. {
  117. // Get the <authority principle> specified, and pass in with ConnectServer
  118. if(NULL != rParsedInfo.GetAuthorityPrinciple())
  119. {
  120. bstrAuthorityPrinciple =
  121. ::SysAllocString(rParsedInfo.GetAuthorityPrinciple());
  122. if (bstrAuthorityPrinciple == NULL)
  123. throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
  124. }
  125. if (bstrUser)
  126. {
  127. if (!bstrPwd)
  128. {
  129. bstrPass = ::SysAllocString(L"");
  130. if (bstrPass == NULL)
  131. throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
  132. // Set the credentials flag to TRUE - BLANK password
  133. rParsedInfo.GetCmdSwitchesObject().SetCredentialsFlag(TRUE);
  134. }
  135. }
  136. if (pILocator != NULL)
  137. {
  138. // Call the ConnectServer method of the IWbemLocator
  139. hr = pILocator->ConnectServer(bstrNS,
  140. bstrUser,
  141. (!bstrPass) ? bstrPwd : bstrPass,
  142. bstrLocale,
  143. 0L, bstrAuthorityPrinciple, NULL, pISvc);
  144. // If the username is specified and the password is not
  145. // specified (the remote machine also has the same password)
  146. if (FAILED(hr) && bstrUser && (hr == E_ACCESSDENIED))
  147. {
  148. hr = pILocator->ConnectServer(bstrNS,
  149. bstrUser,
  150. NULL,
  151. bstrLocale,
  152. 0L, bstrAuthorityPrinciple, NULL, pISvc);
  153. // Set the credentials flag to FALSE - NULL password
  154. rParsedInfo.GetCmdSwitchesObject().SetCredentialsFlag(FALSE);
  155. }
  156. }
  157. else
  158. hr = E_FAIL;
  159. if (bstrPass)
  160. ::SysFreeString(bstrPass);
  161. if (bstrAuthorityPrinciple)
  162. ::SysFreeString(bstrAuthorityPrinciple);
  163. }
  164. catch(CHeap_Exception)
  165. {
  166. if (bstrAuthorityPrinciple)
  167. ::SysFreeString(bstrAuthorityPrinciple);
  168. if (bstrPass)
  169. ::SysFreeString(bstrPass);
  170. hr = E_FAIL;
  171. }
  172. return hr;
  173. }
  174. /*----------------------------------------------------------------------------
  175. Name :SetSecurity
  176. Synopsis :To set the security privileges at the interface level
  177. Type :Global Function
  178. Input parameter(s):
  179. pIUnknown - Interface pointer
  180. pszDomain - domain name
  181. pszAuthority - authority (always passed as NULL)
  182. pszUser - Username
  183. pszPassword - Password
  184. uAuthLevel - Authentication Level
  185. uImpLevel - Impersonation Level
  186. Output parameter(s):None
  187. Return Type :HRESULT
  188. Global Variables :None
  189. Calling Syntax :SetSecurity(pIUnknown, pszDomain, pszUser,
  190. pszPassword, uAuthLevel, uImpLevel)
  191. Notes :(partly taken from WMI VC samples 'utillib'
  192. ----------------------------------------------------------------------------*/
  193. HRESULT SetSecurity(IUnknown* pIUnknown, _TCHAR* pszAuthority,
  194. _TCHAR* pszDomain, _TCHAR* pszUser,
  195. _TCHAR* pszPassword, UINT uAuthLevel,
  196. UINT uImpLevel) throw(WMICLIINT)
  197. {
  198. SCODE sc = S_OK;
  199. BSTR bstrAuthArg = NULL,
  200. bstrUserArg = NULL;
  201. SEC_WINNT_AUTH_IDENTITY_W* pAuthIdentity = NULL;
  202. try
  203. {
  204. if(pIUnknown == NULL)
  205. return E_INVALIDARG;
  206. // If we are lowering the security, no need to deal with the
  207. // identification information
  208. if(uAuthLevel == RPC_C_AUTHN_LEVEL_NONE)
  209. return CoSetProxyBlanket(pIUnknown, RPC_C_AUTHN_WINNT,
  210. RPC_C_AUTHZ_NONE,
  211. NULL, RPC_C_AUTHN_LEVEL_NONE,
  212. RPC_C_IMP_LEVEL_IDENTIFY,
  213. NULL, EOAC_NONE);
  214. // If we are doing trivial case, just pass in a null authentication
  215. // structure which is used if the current logged in user's credentials
  216. // are OK.
  217. if((pszAuthority == NULL || lstrlen((LPCTSTR)pszAuthority) < 1) &&
  218. (pszUser == NULL || lstrlen((LPCTSTR)pszUser) < 1) &&
  219. (pszPassword == NULL || lstrlen((LPCTSTR)pszPassword) < 1))
  220. return CoSetProxyBlanket(pIUnknown, RPC_C_AUTHN_WINNT,
  221. RPC_C_AUTHZ_NONE, NULL, uAuthLevel,
  222. uImpLevel, NULL, EOAC_NONE);
  223. // If user, or Authority was passed in, the we need
  224. // to create an authority argument for the login
  225. sc = ParseAuthorityUserArgs(bstrAuthArg, bstrUserArg,
  226. pszAuthority, pszUser);
  227. if(FAILED(sc))
  228. return sc;
  229. pAuthIdentity = new SEC_WINNT_AUTH_IDENTITY_W;
  230. // Check whether the memory allocation has been successful
  231. if (pAuthIdentity == NULL)
  232. return WBEM_E_OUT_OF_MEMORY;
  233. ZeroMemory(pAuthIdentity, sizeof(SEC_WINNT_AUTH_IDENTITY_W));
  234. if(bstrUserArg)
  235. {
  236. WMICLIULONG wulUserLen = (WMICLIULONG)
  237. lstrlen((LPWSTR)bstrUserArg);
  238. pAuthIdentity->User = new WCHAR [wulUserLen + 1];
  239. if (pAuthIdentity->User == NULL)
  240. throw OUT_OF_MEMORY;
  241. wcscpy(pAuthIdentity->User, (LPWSTR)bstrUserArg);
  242. pAuthIdentity->UserLength = wulUserLen;
  243. }
  244. if(bstrAuthArg)
  245. {
  246. WMICLIULONG wulDomainLen = (WMICLIULONG)
  247. lstrlen((LPWSTR) bstrAuthArg);
  248. pAuthIdentity->Domain = new WCHAR [wulDomainLen + 1];
  249. if (pAuthIdentity->Domain == NULL)
  250. throw OUT_OF_MEMORY;
  251. wcscpy(pAuthIdentity->Domain, (LPWSTR)bstrAuthArg);
  252. pAuthIdentity->DomainLength = wulDomainLen;
  253. }
  254. if(pszPassword)
  255. {
  256. WMICLIULONG wulPasswordLen = (WMICLIULONG)
  257. lstrlen((LPWSTR) pszPassword);
  258. pAuthIdentity->Password = new WCHAR [wulPasswordLen + 1];
  259. if (pAuthIdentity->Password == NULL)
  260. throw OUT_OF_MEMORY;
  261. wcscpy(pAuthIdentity->Password, pszPassword);
  262. pAuthIdentity->PasswordLength= wulPasswordLen;
  263. }
  264. pAuthIdentity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
  265. if( pszAuthority != NULL &&
  266. _tcslen(pszAuthority) > 9 &&
  267. _tcsnicmp(pszAuthority, _T("KERBEROS:"), 9) == 0)
  268. {
  269. // get the <principal name> that is passed with <authority type>
  270. // and send it to CoSetProxyBlanket()
  271. BSTR bstrPrincipalName = ::SysAllocString(&pszAuthority[9]);
  272. sc = CoSetProxyBlanket(pIUnknown,
  273. RPC_C_AUTHN_GSS_KERBEROS,
  274. RPC_C_AUTHZ_NONE ,
  275. bstrPrincipalName,
  276. uAuthLevel,
  277. uImpLevel,
  278. pAuthIdentity,
  279. EOAC_NONE);
  280. SAFEBSTRFREE(bstrPrincipalName);
  281. }
  282. else
  283. {
  284. sc = CoSetProxyBlanket(pIUnknown, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
  285. NULL, uAuthLevel, uImpLevel, pAuthIdentity, EOAC_NONE);
  286. }
  287. SAFEDELETE(pAuthIdentity->User);
  288. SAFEDELETE(pAuthIdentity->Domain);
  289. SAFEDELETE(pAuthIdentity->Password);
  290. delete pAuthIdentity;
  291. SAFEBSTRFREE(bstrUserArg);
  292. SAFEBSTRFREE(bstrAuthArg);
  293. }
  294. catch(WMICLIINT nErr)
  295. {
  296. if (nErr == OUT_OF_MEMORY)
  297. sc = WBEM_E_OUT_OF_MEMORY;
  298. SAFEDELETE(pAuthIdentity->User);
  299. SAFEDELETE(pAuthIdentity->Domain);
  300. SAFEDELETE(pAuthIdentity->Password);
  301. if (pAuthIdentity)
  302. delete pAuthIdentity;
  303. SAFEBSTRFREE(bstrUserArg);
  304. SAFEBSTRFREE(bstrAuthArg);
  305. }
  306. return sc;
  307. }
  308. /*----------------------------------------------------------------------------
  309. Name :ConvertWCToMBCS
  310. Synopsis :Converts the wide character string to MBCS string
  311. after applying the codepage settings
  312. Type :Global Function
  313. Input parameters :
  314. lpszMsg - string (widechar string)
  315. uCP - codepage value
  316. Output parameters :
  317. lpszDisp - string (multibyte string)
  318. Return Type :BOOL
  319. Global Variables :None
  320. Calling Syntax :ConvertWCToMBCS(lpszMsg, lpszDisp, uCP)
  321. Notes :None
  322. ----------------------------------------------------------------------------*/
  323. BOOL ConvertWCToMBCS(LPTSTR lpszMsg, LPVOID* lpszDisp, UINT uCP)
  324. {
  325. BOOL bRet = TRUE;
  326. if (lpszMsg != NULL && lpszDisp != NULL)
  327. {
  328. WMICLIINT nRet = 0;
  329. nRet = WideCharToMultiByte(uCP, // code page
  330. 0, // performance and mapping flags
  331. (LPCWSTR)lpszMsg, // wide-character string
  332. -1, // number of chars in string
  333. NULL, // buffer for new string
  334. 0, // size of buffer
  335. NULL, // default for unmappable chars
  336. NULL);
  337. // allocate memory to hold the message
  338. *lpszDisp = (LPSTR) new char [nRet];
  339. if (*lpszDisp)
  340. {
  341. nRet = WideCharToMultiByte(uCP, // code page
  342. 0, // performance and mapping flags
  343. (LPCWSTR)lpszMsg, // wide-character string
  344. -1, // number of chars in string
  345. (LPSTR) *lpszDisp, // buffer for new string
  346. nRet, // size of buffer
  347. NULL, // default for unmappable chars
  348. NULL);
  349. }
  350. else
  351. bRet = FALSE;
  352. }
  353. else
  354. {
  355. if ( lpszDisp )
  356. {
  357. *lpszDisp = NULL;
  358. }
  359. }
  360. return bRet;
  361. }
  362. /*----------------------------------------------------------------------------
  363. Name :ConvertMBCSToWC
  364. Synopsis :Converts the MBCS string to wide character string
  365. after applying the codepage settings
  366. Type :Global Function
  367. Input parameters :
  368. lpszMsg - string (MBCS string)
  369. uCP - codepage value
  370. Output parameters :
  371. lpszDisp - string (multibyte string)
  372. Return Type :BOOL
  373. Global Variables :None
  374. Calling Syntax :ConvertMBCSToWC(lpszMsg, lpszDisp, uCP)
  375. Notes :None
  376. ----------------------------------------------------------------------------*/
  377. BOOL ConvertMBCSToWC(LPSTR lpszMsg, LPVOID* lpszDisp, UINT uCP)
  378. {
  379. BOOL bRet = TRUE;
  380. if (lpszMsg != NULL && lpszDisp != NULL)
  381. {
  382. WMICLIINT nRet = 0;
  383. nRet = MultiByteToWideChar (
  384. uCP, // code page
  385. 0, // performance and mapping flags
  386. (LPCSTR)lpszMsg, // wide-character string
  387. -1, // number of chars in string
  388. NULL, // buffer for new string
  389. 0
  390. );
  391. // allocate memory to hold the message
  392. *lpszDisp = (LPWSTR) new WCHAR [nRet];
  393. if (*lpszDisp)
  394. {
  395. nRet = MultiByteToWideChar (
  396. uCP, // code page
  397. 0, // performance and mapping flags
  398. (LPCSTR)lpszMsg, // wide-character string
  399. -1, // number of chars in string
  400. (LPWSTR) *lpszDisp, // buffer for new string
  401. nRet // size of buffer
  402. );
  403. }
  404. else
  405. bRet = FALSE;
  406. }
  407. else
  408. {
  409. if ( lpszDisp )
  410. {
  411. *lpszDisp = NULL;
  412. }
  413. }
  414. return bRet;
  415. }
  416. /*----------------------------------------------------------------------------
  417. Name :Revert_mbtowc
  418. Synopsis :Reverts string when created by mbtowc
  419. Type :Global Function
  420. Input parameters :
  421. wszBuffer - string
  422. Output parameters :
  423. szBuffer - output
  424. Return Type :BOOL
  425. Global Variables :None
  426. Calling Syntax :Revert_mbtowc(wszBuffer, &szBuffer)
  427. Notes :None
  428. ----------------------------------------------------------------------------*/
  429. BOOL Revert_mbtowc ( LPCWSTR wszBuffer, LPSTR* szBuffer )
  430. {
  431. BOOL bRet = FALSE ;
  432. LPWSTR help = const_cast < LPWSTR > ( wszBuffer ) ;
  433. int helpi = lstrlen ( wszBuffer ) ;
  434. (*szBuffer) = new char [ helpi + 1 ] ;
  435. if ( NULL != (*szBuffer) )
  436. {
  437. for ( int i = 0; i < helpi+1; i++ )
  438. {
  439. (*szBuffer)[ i ] = 0 ;
  440. }
  441. for ( int i = 0; i < helpi; i++ )
  442. {
  443. wctomb ( & (*szBuffer)[i], *help ) ;
  444. help++;
  445. }
  446. bRet = TRUE ;
  447. }
  448. return bRet ;
  449. }
  450. /*----------------------------------------------------------------------------
  451. Name :Find
  452. Synopsis :Searches for a given string in the vector list
  453. Input parameter(s):
  454. cvVector - vector list
  455. pszStrToFind - serach string
  456. Output parameter(s):None
  457. Return Type :BOOL
  458. TRUE - if match is found
  459. FALSE - if no match found
  460. Global Variables :None
  461. Calling Syntax :Find(cvVector, pszStrToFind)
  462. Notes :overloaded function
  463. ----------------------------------------------------------------------------*/
  464. BOOL Find(CHARVECTOR& cvVector,
  465. _TCHAR* pszStrToFind,
  466. CHARVECTOR::iterator& theIterator)
  467. {
  468. BOOL bRet = FALSE;
  469. theIterator = cvVector.begin();
  470. CHARVECTOR ::iterator theEnd = cvVector.end();
  471. while (theIterator != theEnd)
  472. {
  473. if (CompareTokens(*theIterator, pszStrToFind))
  474. {
  475. bRet = TRUE;
  476. break;
  477. }
  478. theIterator++;
  479. }
  480. return bRet;
  481. }
  482. /*----------------------------------------------------------------------------
  483. Name :Find
  484. Synopsis :Find a property name in the property details map
  485. Type :Global Function
  486. Input parameter(s):
  487. pdmPropDetMap - property map
  488. pszPropToFind - property to search for
  489. theIterator - Iterator
  490. bExcludeNumbers - Boolean value
  491. Output parameter(s):None
  492. Return Type :BOOL
  493. Global Variables :None
  494. Calling Syntax :Find(pdmPropDetMap, pszPropToFind, tempIterator)
  495. Notes :overloaded function,
  496. bExcludeNumbers = FALSE by default.
  497. ----------------------------------------------------------------------------*/
  498. BOOL Find(PROPDETMAP& pdmPropDetMap,
  499. _TCHAR* pszPropToFind,
  500. PROPDETMAP::iterator& theIterator,
  501. BOOL bExcludeNumbers)
  502. {
  503. BOOL bRet = FALSE;
  504. theIterator = pdmPropDetMap.begin();
  505. PROPDETMAP::iterator theEnd = pdmPropDetMap.end();
  506. while (theIterator != theEnd)
  507. {
  508. _TCHAR* pszPropName = (*theIterator).first;
  509. if ( bExcludeNumbers == TRUE )
  510. pszPropName = pszPropName + 5;
  511. if (CompareTokens(pszPropName, pszPropToFind))
  512. {
  513. bRet = TRUE;
  514. break;
  515. }
  516. theIterator++;
  517. }
  518. return bRet;
  519. }
  520. /*----------------------------------------------------------------------------
  521. Name :Find
  522. Synopsis :Find a property name in the property details map
  523. Type :Global Function
  524. Input parameter(s):
  525. bmBstrMap - BSTR map
  526. pszStrToFind - property to search for
  527. theIterator - Iterator.
  528. Output parameter(s):None
  529. Return Type :BOOL
  530. Global Variables :None
  531. Calling Syntax :Find(pdmPropDetMap, pszPropToFind)
  532. Notes :overloaded function
  533. ----------------------------------------------------------------------------*/
  534. BOOL Find(BSTRMAP& bmBstrMap,
  535. _TCHAR* pszStrToFind,
  536. BSTRMAP::iterator& theIterator)
  537. {
  538. BOOL bRet = FALSE;
  539. theIterator = bmBstrMap.begin();
  540. BSTRMAP::iterator theEnd = bmBstrMap.end();
  541. while (theIterator != theEnd)
  542. {
  543. if (CompareTokens((*theIterator).first, pszStrToFind))
  544. {
  545. bRet = TRUE;
  546. break;
  547. }
  548. theIterator++;
  549. }
  550. return bRet;
  551. }
  552. /*------------------------------------------------------------------------
  553. Name :FrameFileAndAddToXSLTDetVector
  554. Synopsis :Frames the XSL File Path
  555. Type :Global Function
  556. Input parameter(s):
  557. stylesheet - name of XSL File
  558. keyword - name of keyword from mapping which could be possibly used
  559. rParsedInfo - reference to object of CParsedInfo
  560. Output parameter(s): None
  561. Return Type :BOOL
  562. Global Variables :None
  563. Calling Syntax :FrameXSLFilePath(stylesheet, keyword, rParsedInfo)
  564. Notes :None
  565. ------------------------------------------------------------------------*/
  566. BOOL FrameFileAndAddToXSLTDetVector(LPCWSTR stylesheet,
  567. LPCWSTR keyword,
  568. CParsedInfo& rParsedInfo)
  569. {
  570. BOOL bRet = FALSE;
  571. _TCHAR* pszBuffer = new _TCHAR [MAX_PATH+1];
  572. UINT nSize = 0;
  573. try
  574. {
  575. if (pszBuffer != NULL)
  576. {
  577. // Obtain the windows system directory
  578. nSize = GetSystemDirectory(pszBuffer, MAX_PATH+1);
  579. if (nSize)
  580. {
  581. if (nSize > MAX_PATH)
  582. {
  583. SAFEDELETE(pszBuffer);
  584. pszBuffer = new _TCHAR [nSize + 1];
  585. if(pszBuffer == NULL)
  586. {
  587. throw OUT_OF_MEMORY;
  588. }
  589. if (!GetSystemDirectory(pszBuffer, nSize+1))
  590. {
  591. SAFEDELETE(pszBuffer);
  592. throw (::GetLastError());
  593. }
  594. }
  595. _bstr_t bstrPath = pszBuffer;
  596. SAFEDELETE(pszBuffer);
  597. bstrPath += WBEM_LOCATION;
  598. //
  599. // we have %windir%\system32\wbem in bstrPath now
  600. //
  601. BOOL bStyleSheet = TRUE;
  602. _bstr_t bstrFile = bstrPath;
  603. BSTRMAP::iterator theMapIterator = NULL;
  604. const BSTRMAP* pMap = g_wmiCmd.GetMappingsMap();
  605. if ( pMap )
  606. {
  607. if ( Find (
  608. *( const_cast < BSTRMAP*> ( pMap ) ) ,
  609. const_cast < LPWSTR > ( keyword ) ,
  610. theMapIterator
  611. )
  612. )
  613. {
  614. bstrFile += (*theMapIterator).second;
  615. //
  616. // check for existence
  617. //
  618. SmartCloseHandle hCheckFile = CreateFile (
  619. bstrFile,
  620. 0,
  621. FILE_SHARE_READ ,
  622. NULL,
  623. OPEN_EXISTING,
  624. 0,
  625. NULL
  626. );
  627. if (hCheckFile != INVALID_HANDLE_VALUE)
  628. {
  629. bStyleSheet = FALSE;
  630. bRet = TRUE;
  631. }
  632. else
  633. {
  634. bstrFile = bstrPath;
  635. }
  636. }
  637. }
  638. else
  639. {
  640. //
  641. // there is no mapping ?
  642. // critical and very strange
  643. // we can still try shipped file
  644. //
  645. }
  646. if ( bStyleSheet && NULL != stylesheet )
  647. {
  648. bstrFile += stylesheet;
  649. //
  650. // check for existence
  651. //
  652. SmartCloseHandle hCheckFile = CreateFile (
  653. bstrFile,
  654. 0,
  655. FILE_SHARE_READ ,
  656. NULL,
  657. OPEN_EXISTING,
  658. 0,
  659. NULL
  660. );
  661. if (hCheckFile != INVALID_HANDLE_VALUE)
  662. {
  663. bRet = TRUE;
  664. }
  665. else
  666. {
  667. bstrFile = bstrPath;
  668. }
  669. }
  670. //
  671. // stylesheet structure to be added to vector
  672. // it is used by transform function
  673. //
  674. //
  675. // there is possibly adding "directory path" as path to file
  676. // hence: LOAD method of DOM will fail during transform
  677. //
  678. // this is intented as we are not really checking file validity
  679. // when /format has used and we wait for transform to deal with it
  680. //
  681. XSLTDET xdXSLTDet;
  682. xdXSLTDet.FileName = bstrFile;
  683. rParsedInfo.GetCmdSwitchesObject().AddToXSLTDetailsVector(xdXSLTDet);
  684. }
  685. else
  686. {
  687. SAFEDELETE(pszBuffer);
  688. throw (::GetLastError());
  689. }
  690. SAFEDELETE(pszBuffer);
  691. }
  692. else
  693. {
  694. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(OUT_OF_MEMORY);
  695. bRet = FALSE;
  696. }
  697. }
  698. catch(_com_error& e)
  699. {
  700. SAFEDELETE(pszBuffer);
  701. bRet = FALSE;
  702. _com_issue_error(e.Error());
  703. }
  704. catch (DWORD dwError)
  705. {
  706. SAFEDELETE(pszBuffer);
  707. ::SetLastError(dwError);
  708. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(dwError);
  709. DisplayWin32Error();
  710. ::SetLastError(dwError);
  711. bRet = FALSE;
  712. }
  713. return bRet;
  714. }
  715. /*------------------------------------------------------------------------
  716. Name :FrameFileAndAddToXSLTDetVector
  717. Synopsis :Frames the XSL File Path
  718. Type :Global Function
  719. Input parameter(s):
  720. pszXSLFile - the XSL File
  721. rParsedInfo - reference to object of CParsedInfo
  722. Output parameter(s): None
  723. Return Type :BOOL
  724. Global Variables :None
  725. Calling Syntax :FrameXSLFilePath(pszXSLFile, rParsedInfo)
  726. Notes :None
  727. ------------------------------------------------------------------------*/
  728. BOOL FrameFileAndAddToXSLTDetVector(XSLTDET& xdXSLTDet,
  729. CParsedInfo& rParsedInfo)
  730. {
  731. BOOL bRet = TRUE;
  732. _TCHAR* pszBuffer = new _TCHAR [MAX_PATH+1];
  733. UINT nSize = 0;
  734. try
  735. {
  736. if (pszBuffer != NULL)
  737. {
  738. // Obtain the windows system directory
  739. nSize = GetSystemDirectory(pszBuffer, MAX_PATH+1);
  740. if (nSize)
  741. {
  742. if (nSize > MAX_PATH)
  743. {
  744. SAFEDELETE(pszBuffer);
  745. pszBuffer = new _TCHAR [nSize + 1];
  746. if(pszBuffer == NULL)
  747. {
  748. throw OUT_OF_MEMORY;
  749. }
  750. if (!GetSystemDirectory(pszBuffer, nSize+1))
  751. {
  752. SAFEDELETE(pszBuffer);
  753. throw (::GetLastError());
  754. }
  755. }
  756. _bstr_t bstrPath = _bstr_t(pszBuffer);
  757. SAFEDELETE(pszBuffer);
  758. // Append the following path
  759. // if (xdXSLTDet.FileName != NULL)
  760. if (!(!xdXSLTDet.FileName))
  761. {
  762. bstrPath += _bstr_t(WBEM_LOCATION) + _bstr_t(xdXSLTDet.FileName);
  763. xdXSLTDet.FileName = bstrPath;
  764. rParsedInfo.GetCmdSwitchesObject().AddToXSLTDetailsVector(
  765. xdXSLTDet);
  766. }
  767. }
  768. else
  769. {
  770. SAFEDELETE(pszBuffer);
  771. throw (::GetLastError());
  772. }
  773. SAFEDELETE(pszBuffer);
  774. }
  775. else
  776. {
  777. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(OUT_OF_MEMORY);
  778. bRet = FALSE;
  779. }
  780. }
  781. catch(_com_error& e)
  782. {
  783. SAFEDELETE(pszBuffer);
  784. bRet = FALSE;
  785. _com_issue_error(e.Error());
  786. }
  787. catch (DWORD dwError)
  788. {
  789. SAFEDELETE(pszBuffer);
  790. ::SetLastError(dwError);
  791. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(dwError);
  792. DisplayWin32Error();
  793. ::SetLastError(dwError);
  794. bRet = FALSE;
  795. }
  796. return bRet;
  797. }
  798. /*------------------------------------------------------------------------
  799. Name :UnquoteString
  800. Synopsis :Removes the starting and ending quotes of a string
  801. enclosed in double quotes.
  802. Type :Global Function
  803. Input parameter(s):
  804. pszString - string input
  805. Output parameter(s):
  806. pszString - string input
  807. Return Type :void
  808. Global Variables :None
  809. Calling Syntax :UnQuoteString(pszString)
  810. Notes :None
  811. ------------------------------------------------------------------------*/
  812. void UnQuoteString(_TCHAR*& pszString)
  813. {
  814. if ((lstrlen(pszString) - 1) > 0)
  815. {
  816. if(_tcsicmp(pszString, _T("\"NULL\"")) == 0) return;
  817. // Check if the string is enclosed within quotes
  818. if ((pszString[0] == _T('"') && (pszString[lstrlen(pszString)-1] == _T('"'))) ||
  819. (pszString[0] == _T('\'') && (pszString[lstrlen(pszString)-1] == _T('\''))))
  820. {
  821. WMICLIINT nLoop = 1, nLen = lstrlen(pszString)-1;
  822. while (nLoop < nLen)
  823. {
  824. pszString[nLoop-1] = pszString[nLoop];
  825. nLoop++;
  826. }
  827. pszString[nLen-1] = _T('\0');
  828. }
  829. }
  830. }
  831. /*------------------------------------------------------------------------
  832. Name :ParseAuthorityUserArgs
  833. Synopsis :Examines the Authority and User argument and
  834. determines the authentication type and possibly
  835. extracts the domain name from the user arugment in the
  836. NTLM case. For NTLM, the domain can be at the end of
  837. the authentication string, or in the front of the
  838. user name, ex: "MSOFT\csriram"
  839. Type :Global Function
  840. Input parameter(s):
  841. ConnType - Returned with the connection type, ie wbem,
  842. ntlm
  843. bstrAuthArg - Output, contains the domain name
  844. bstrUserArg - Output, user name
  845. bstrAuthority - Input
  846. User - Input
  847. Output parameter(s):None
  848. Return Type :
  849. SCODE
  850. Global Variables :None
  851. Calling Syntax :ParseAuthorityUserArgs(bstrAuthArg, bstrUserArg,
  852. bstrAuthority, bstrUser)
  853. Notes :(taken from WMI VC samples 'utillib'
  854. ------------------------------------------------------------------------*/
  855. SCODE ParseAuthorityUserArgs(BSTR& bstrAuthArg, BSTR& bstrUserArg,
  856. BSTR& bstrAuthority, BSTR& bstrUser)
  857. {
  858. // Determine the connection type by examining the Authority string
  859. // The ntlm case is more complex. There are four cases
  860. // 1) Authority = NTLMDOMAIN:name" and User = "User"
  861. // 2) Authority = NULL and User = "User"
  862. // 3) Authority = "NTLMDOMAIN:" User = "domain\user"
  863. // 4) Authority = NULL and User = "domain\user"
  864. // first step is to determine if there is a backslash in the user
  865. // name somewhere between the second and second to last character
  866. try
  867. {
  868. WCHAR * pSlashInUser = NULL;
  869. if(bstrUser)
  870. {
  871. WCHAR * pEnd = bstrUser + lstrlen((LPCTSTR)bstrUser) - 1;
  872. for(pSlashInUser = bstrUser; pSlashInUser <= pEnd; pSlashInUser++)
  873. // dont think forward slash is allowed!
  874. if(*pSlashInUser == L'\\')
  875. break;
  876. if(pSlashInUser > pEnd)
  877. pSlashInUser = NULL;
  878. }
  879. if(bstrAuthority && lstrlen((LPCTSTR)bstrAuthority) > 11 &&
  880. _tcsnicmp((LPCTSTR)bstrAuthority, _T("NTLMDOMAIN:"), 11) == 0)
  881. {
  882. if(pSlashInUser)
  883. return E_INVALIDARG;
  884. bstrAuthArg = SysAllocString(bstrAuthority + 11);
  885. if (bstrAuthArg == NULL)
  886. throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
  887. if(bstrUser)
  888. {
  889. bstrUserArg = SysAllocString(bstrUser);
  890. if (bstrUserArg == NULL)
  891. throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
  892. }
  893. return S_OK;
  894. }
  895. else if(pSlashInUser)
  896. {
  897. WMICLIINT iDomLen = pSlashInUser-bstrUser;
  898. WCHAR *pszTemp = new WCHAR [iDomLen+1];
  899. if ( pszTemp != NULL )
  900. {
  901. wcsncpy(pszTemp, bstrUser, iDomLen);
  902. pszTemp[iDomLen] = 0;
  903. bstrAuthArg = SysAllocString(pszTemp);
  904. if (bstrAuthArg == NULL){
  905. delete pszTemp;
  906. throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
  907. }
  908. if(lstrlen((LPCTSTR)pSlashInUser+1))
  909. {
  910. bstrUserArg = SysAllocString(pSlashInUser+1);
  911. if (bstrAuthArg == NULL){
  912. delete pszTemp;
  913. throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
  914. }
  915. }
  916. SAFEDELETE(pszTemp);
  917. }
  918. else
  919. throw OUT_OF_MEMORY;
  920. }
  921. else
  922. if(bstrUser)
  923. {
  924. bstrUserArg = SysAllocString(bstrUser);
  925. if (bstrUserArg == NULL)
  926. throw CHeap_Exception(CHeap_Exception::E_ALLOCATION_ERROR);
  927. }
  928. }
  929. catch(CHeap_Exception)
  930. {
  931. if(bstrAuthArg) SysFreeString(bstrAuthArg); bstrAuthArg = NULL;
  932. if(bstrUserArg) SysFreeString(bstrUserArg); bstrUserArg = NULL;
  933. throw OUT_OF_MEMORY;
  934. }
  935. return S_OK;
  936. }
  937. /*----------------------------------------------------------------------------
  938. Name :DisplayVARIANTContent
  939. Synopsis :Displays the content of a VARIANT type data object
  940. Type :Member Function
  941. Input Parameter(s):
  942. vtObject - VARIANT object
  943. Output parameters :None
  944. Return Type :None
  945. Global Variables :None
  946. Calling Syntax :DisplayVARIANTContent(vtObject)
  947. Notes :none
  948. ----------------------------------------------------------------------------*/
  949. void DisplayVARIANTContent(VARIANT vtObject)
  950. {
  951. _TCHAR szMsg[BUFFER255] = NULL_STRING;
  952. switch ( vtObject.vt )
  953. {
  954. case VT_UI1:
  955. _stprintf(szMsg, _T("%c"), vtObject.bVal);
  956. break;
  957. case VT_I2:
  958. _stprintf(szMsg, _T("%i"), vtObject.iVal);
  959. break;
  960. case VT_I4:
  961. _stprintf(szMsg, _T("%li"), vtObject.lVal);
  962. break;
  963. case VT_R4:
  964. _stprintf(szMsg, _T("%f"), vtObject.fltVal);
  965. break;
  966. case VT_R8:
  967. _stprintf(szMsg, _T("%e"), vtObject.dblVal);
  968. break;
  969. case VT_BOOL:
  970. _stprintf(szMsg, _T("%i"), vtObject.boolVal);
  971. break;
  972. case VT_I1:
  973. _stprintf(szMsg, _T("%c"), vtObject.cVal);
  974. break;
  975. case VT_UI2:
  976. _stprintf(szMsg, _T("%i"), vtObject.uiVal);
  977. break;
  978. case VT_UI4:
  979. _stprintf(szMsg, _T("%ld"), vtObject.ulVal);
  980. break;
  981. case VT_INT:
  982. _stprintf(szMsg, _T("%i"), vtObject.intVal);
  983. break;
  984. case VT_UINT:
  985. _stprintf(szMsg, _T("%i"), vtObject.uintVal);
  986. break;
  987. }
  988. DisplayMessage(szMsg, CP_OEMCP, FALSE, TRUE);
  989. }
  990. /*----------------------------------------------------------------------------
  991. Name :GetPropertyAttributes
  992. Synopsis :This function obtains the information about the class
  993. properties
  994. Type :Member Function
  995. Input Parameter(s):
  996. pIObj - pointer to IWbemClassObject object
  997. bstrProp - property name
  998. bTrace - trace flag
  999. Output parameter(s):
  1000. pdPropDet - property details structure
  1001. Return Type :HRESULT
  1002. Global Variables :None
  1003. Calling Syntax :GetPropertyAttributes(pIObj, bstrProp,
  1004. pdPropDet, bTrace)
  1005. Notes :none
  1006. ----------------------------------------------------------------------------*/
  1007. HRESULT GetPropertyAttributes(IWbemClassObject* pIObj,
  1008. BSTR bstrProp,
  1009. PROPERTYDETAILS& pdPropDet,
  1010. BOOL bTrace)
  1011. {
  1012. HRESULT hr = S_OK;
  1013. IWbemQualifierSet* pIQualSet = NULL;
  1014. VARIANT vtType, vtOper, vtDesc, vtTypeProp;
  1015. CIMTYPE ctCimType;
  1016. VariantInit(&vtType);
  1017. VariantInit(&vtOper);
  1018. VariantInit(&vtDesc);
  1019. VariantInit(&vtTypeProp);
  1020. try
  1021. {
  1022. // Obtain the property qualifier set for the property
  1023. hr = pIObj->GetPropertyQualifierSet(bstrProp, &pIQualSet);
  1024. if ( pIQualSet != NULL )
  1025. {
  1026. // Obtain the CIM type of the property
  1027. hr = pIQualSet->Get(_bstr_t(L"CIMTYPE"), 0L, &vtType, NULL);
  1028. if (SUCCEEDED(hr))
  1029. {
  1030. if ( vtType.vt == VT_BSTR )
  1031. {
  1032. pdPropDet.Type = _bstr_t(vtType.bstrVal);
  1033. // Obtain the CIM type of the property
  1034. hr = pIObj->Get(bstrProp, 0L, &vtTypeProp, &ctCimType, NULL);
  1035. if (SUCCEEDED(hr))
  1036. {
  1037. if ( ctCimType & VT_ARRAY )
  1038. {
  1039. pdPropDet.Type = _bstr_t("array of ") +
  1040. pdPropDet.Type;
  1041. }
  1042. VARIANTCLEAR(vtTypeProp);
  1043. }
  1044. }
  1045. else
  1046. pdPropDet.Type = _bstr_t("Not Found");
  1047. }
  1048. else
  1049. pdPropDet.Type = _bstr_t("Not Found");
  1050. // Should not break here, hence the HRESULT should be set to S_OK
  1051. hr = S_OK;
  1052. VARIANTCLEAR(vtType);
  1053. // Check whether the property has 'read' flag set
  1054. _bstr_t bstrOper;
  1055. hr = pIQualSet->Get(_bstr_t(L"read"), 0L, &vtOper, NULL);
  1056. if (SUCCEEDED(hr))
  1057. {
  1058. if (vtOper.vt == VT_BOOL && vtOper.boolVal)
  1059. bstrOper = _bstr_t(L"Read");
  1060. }
  1061. VARIANTCLEAR(vtOper);
  1062. // Should not break here, hence the HRESULT should be set to S_OK
  1063. hr = S_OK;
  1064. // Check whether the property has 'write' flag set
  1065. VariantInit(&vtOper);
  1066. hr = pIQualSet->Get(_bstr_t(L"write"), 0L, &vtOper, NULL);
  1067. if (SUCCEEDED(hr))
  1068. {
  1069. if ((vtOper.vt == VT_BOOL) && vtOper.boolVal)
  1070. {
  1071. if (!bstrOper)
  1072. bstrOper = _bstr_t(L"Write");
  1073. else
  1074. bstrOper += _bstr_t(L"/Write");
  1075. }
  1076. }
  1077. VARIANTCLEAR(vtOper);
  1078. // Should not break here, hence the HRESULT should be set to S_OK
  1079. hr = S_OK;
  1080. if (!bstrOper)
  1081. pdPropDet.Operation = _bstr_t(TOKEN_NA);
  1082. else
  1083. pdPropDet.Operation = _bstr_t(bstrOper);
  1084. // Retrieve the 'Description' text for the property
  1085. if (FAILED(pIQualSet->Get(_bstr_t(L"Description"), 0L,
  1086. &vtDesc,NULL)))
  1087. pdPropDet.Description = _bstr_t("Not Available");
  1088. else
  1089. pdPropDet.Description = _bstr_t(vtDesc.bstrVal);
  1090. VARIANTCLEAR(vtDesc);
  1091. SAFEIRELEASE(pIQualSet);
  1092. }
  1093. else
  1094. hr = S_OK;
  1095. }
  1096. catch(_com_error& e)
  1097. {
  1098. VARIANTCLEAR(vtType);
  1099. VARIANTCLEAR(vtOper);
  1100. VARIANTCLEAR(vtDesc);
  1101. SAFEIRELEASE(pIQualSet);
  1102. hr = e.Error();
  1103. }
  1104. return hr;
  1105. }
  1106. /*----------------------------------------------------------------------------
  1107. Name :GetNumber
  1108. Synopsis :converts string to number
  1109. Input Parameter(s):string
  1110. Output parameters :
  1111. Return Type :WMICLIINT
  1112. Global Variables :None
  1113. Calling Syntax :GetNumber(string)
  1114. Notes :none
  1115. ----------------------------------------------------------------------------*/
  1116. WMICLIINT GetNumber ( WCHAR* wsz )
  1117. {
  1118. WMICLIINT iResult = -1;
  1119. if ( wsz )
  1120. {
  1121. WCHAR* wszTemp = wsz;
  1122. if ( *wszTemp == L'0' )
  1123. {
  1124. wszTemp++;
  1125. if ( *wszTemp )
  1126. {
  1127. if ( towlower ( *wszTemp ) == L'x' )
  1128. {
  1129. WMICLIINT i = 0;
  1130. i = swscanf ( wsz, L"%x", &iResult );
  1131. if ( !i || i == EOF )
  1132. {
  1133. iResult = -1;
  1134. }
  1135. }
  1136. else
  1137. {
  1138. // do not support octal strings
  1139. }
  1140. }
  1141. else
  1142. {
  1143. // this is plain 0
  1144. iResult = 0;
  1145. }
  1146. }
  1147. else
  1148. {
  1149. WMICLIINT i = 0;
  1150. i = swscanf ( wsz, L"%d", &iResult );
  1151. if ( !i || i == EOF )
  1152. {
  1153. iResult = -1;
  1154. }
  1155. }
  1156. }
  1157. return iResult;
  1158. }
  1159. /*----------------------------------------------------------------------------
  1160. Name :ReturnFileType
  1161. Synopsis :type of file
  1162. Input Parameter(s):FILE*
  1163. Output parameters :none
  1164. Return Type :FILETYPE
  1165. Global Variables :None
  1166. Calling Syntax :ReturnFileType(file)
  1167. Notes :none
  1168. ----------------------------------------------------------------------------*/
  1169. FILETYPE ReturnFileType ( FILE* fpFile )
  1170. {
  1171. FILETYPE eftFileType = ANSI_FILE ;
  1172. // Indentifing the file type whether Unicode or ANSI.
  1173. char szFirstTwoBytes [2] = { '\0' } ;
  1174. if( fread(szFirstTwoBytes, 2, 1, fpFile) )
  1175. {
  1176. if ( memcmp(szFirstTwoBytes, UNICODE_SIGNATURE, 2) == 0 )
  1177. {
  1178. eftFileType = UNICODE_FILE;
  1179. }
  1180. else if (memcmp(szFirstTwoBytes, UNICODE_BIGEND_SIGNATURE, 2) == 0 )
  1181. {
  1182. eftFileType = UNICODE_BIGENDIAN_FILE;
  1183. }
  1184. else if( memcmp(szFirstTwoBytes, UTF8_SIGNATURE, 2) == 0 )
  1185. {
  1186. eftFileType = UTF8_FILE;
  1187. }
  1188. fseek(fpFile, 0, SEEK_SET);
  1189. }
  1190. return eftFileType ;
  1191. }
  1192. /*----------------------------------------------------------------------------
  1193. Name :ReturnVarType
  1194. Synopsis :Does the CIMTYPE to VARIANT conversion
  1195. Input Parameter(s):
  1196. bstrCIMType - CIMTYPE
  1197. Output parameters :
  1198. Return Type :VARTYPE
  1199. Global Variables :None
  1200. Calling Syntax :ReturnVarType(bstrCIMType)
  1201. Notes :none
  1202. ----------------------------------------------------------------------------*/
  1203. VARTYPE ReturnVarType( _TCHAR* bstrCIMType )
  1204. {
  1205. if (CompareTokens(bstrCIMType, _T("")))
  1206. return VT_NULL;
  1207. else if (CompareTokens(bstrCIMType,_T("string")))
  1208. return VT_BSTR;
  1209. else if (CompareTokens(bstrCIMType,_T("Sint16")))
  1210. return VT_I2;
  1211. else if (CompareTokens(bstrCIMType,_T("Sint8")))
  1212. return VT_I2;
  1213. else if ( CompareTokens(bstrCIMType,_T("Sint32")))
  1214. return VT_I4;
  1215. else if ( CompareTokens(bstrCIMType,_T("Real32")))
  1216. return VT_R4;
  1217. else if ( CompareTokens(bstrCIMType,_T("Sint64")))
  1218. return VT_BSTR;
  1219. else if ( CompareTokens(bstrCIMType,_T("Uint64")))
  1220. return VT_BSTR;
  1221. else if ( CompareTokens(bstrCIMType,_T("Real64")))
  1222. return VT_R8;
  1223. else if ( CompareTokens(bstrCIMType,_T("Boolean")))
  1224. return VT_BOOL;
  1225. else if ( CompareTokens(bstrCIMType,_T("Object")))
  1226. return VT_DISPATCH;
  1227. else if ( CompareTokens(bstrCIMType,_T("Sint8")))
  1228. return VT_INT;
  1229. else if ( CompareTokens(bstrCIMType,_T("Uint8")))
  1230. return VT_UI1;
  1231. else if ( CompareTokens(bstrCIMType,_T("Uint16")))
  1232. return VT_I4;
  1233. else if ( CompareTokens(bstrCIMType,_T("Uint32")))
  1234. return VT_I4;
  1235. else if ( CompareTokens(bstrCIMType,_T("Datetime")))
  1236. return VT_BSTR; // In WMI Date is treated as string
  1237. else if ( CompareTokensChars(bstrCIMType,_T("ref:"),lstrlen(_T("ref:"))))
  1238. return VT_BSTR; // In WMI ref is treated as string
  1239. else if ( CompareTokens(bstrCIMType,_T("Char16")))
  1240. return VT_I2;
  1241. else // (CIM_OBJECT)
  1242. return VT_NULL;
  1243. return VT_EMPTY;
  1244. }
  1245. /*----------------------------------------------------------------------------
  1246. Name :ConvertCIMTYPEToVarType
  1247. Synopsis :Does the CIMTYPE to VARIANT conversion
  1248. Type :Member Function
  1249. Input Parameter(s):
  1250. varSrc - VARIANT source
  1251. bstrCIMType - CIMTYPE
  1252. Output parameters :
  1253. varDest - VARIANT destination
  1254. Return Type :HRESULT
  1255. Global Variables :None
  1256. Calling Syntax :ConvertCIMTYPEToVarType(varDest, varSrc, bstrCIMType)
  1257. Notes :none
  1258. ----------------------------------------------------------------------------*/
  1259. HRESULT ConvertCIMTYPEToVarType( VARIANT& varDest, VARIANT& varSrc,
  1260. _TCHAR* bstrCIMType )
  1261. {
  1262. HRESULT hr = S_OK;
  1263. if (CompareTokens(bstrCIMType,_T("string")))
  1264. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BSTR);
  1265. else if (CompareTokens(bstrCIMType,_T("Sint16")))
  1266. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I2);
  1267. else if (CompareTokens(bstrCIMType,_T("Sint8")))
  1268. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I2);
  1269. else if ( CompareTokens(bstrCIMType,_T("Sint32")))
  1270. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I4);
  1271. else if ( CompareTokens(bstrCIMType,_T("Real32")))
  1272. hr = VariantChangeType(&varDest, &varSrc, 0, VT_R4);
  1273. else if ( CompareTokens(bstrCIMType,_T("Sint64")))
  1274. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BSTR);
  1275. else if ( CompareTokens(bstrCIMType,_T("Uint64")))
  1276. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BSTR);
  1277. else if ( CompareTokens(bstrCIMType,_T("Real64")))
  1278. hr = VariantChangeType(&varDest, &varSrc, 0, VT_R8);
  1279. else if ( CompareTokens(bstrCIMType,_T("Boolean")))
  1280. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BOOL);
  1281. else if ( CompareTokens(bstrCIMType,_T("Object")))
  1282. hr = VariantChangeType(&varDest, &varSrc, 0, VT_DISPATCH);
  1283. else if ( CompareTokens(bstrCIMType,_T("Sint8")))
  1284. hr = VariantChangeType(&varDest, &varSrc, 0, VT_INT);
  1285. else if ( CompareTokens(bstrCIMType,_T("Uint8")))
  1286. hr = VariantChangeType(&varDest, &varSrc, 0, VT_UI1);
  1287. else if ( CompareTokens(bstrCIMType,_T("Uint16")))
  1288. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I4);
  1289. else if ( CompareTokens(bstrCIMType,_T("Uint32")))
  1290. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I4);
  1291. else if ( CompareTokens(bstrCIMType,_T("Datetime")))
  1292. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BSTR); // In WMI Date is treated as string
  1293. else if ( CompareTokensChars(bstrCIMType,_T("ref:"),lstrlen(_T("ref:"))))
  1294. hr = VariantChangeType(&varDest, &varSrc, 0, VT_BSTR); // In WMI ref is treated as string
  1295. else if ( CompareTokens(bstrCIMType,_T("Char16")))
  1296. hr = VariantChangeType(&varDest, &varSrc, 0, VT_I2);
  1297. else // (CIM_OBJECT)
  1298. hr = VariantChangeType(&varDest, &varSrc, 0, VT_NULL);
  1299. return hr;
  1300. }
  1301. /*----------------------------------------------------------------------------
  1302. Name :DisplayMessage
  1303. Synopsis :Displays localized string
  1304. Type :Global Function
  1305. Input parameter(s):
  1306. lszpMsg - string
  1307. uCP - codepage value
  1308. bIsError - Boolean type specifying error message or not.
  1309. bIsLog - Boolean type specifying message to be logged or not .
  1310. Output parameter(s):None
  1311. Return Type :void
  1312. Global Variables :None
  1313. Calling Syntax :DisplayMessage(lpszMsg, uCP, TRUE, TRUE)
  1314. Notes :bIsError = FALSE, bIsLog = FALSE by default.
  1315. ----------------------------------------------------------------------------*/
  1316. void DisplayMessage ( LPTSTR lpszMsg, UINT uCP, BOOL bIsError, BOOL bIsLog, BOOL bIsStream )
  1317. {
  1318. LPSTR lpszDisp = NULL;
  1319. try
  1320. {
  1321. // Convert the widechar to MBCS string
  1322. if ( lpszMsg && lpszMsg[0] )
  1323. {
  1324. OUTPUTSPEC opsOutOpt = g_wmiCmd.GetParsedInfoObject().
  1325. GetGlblSwitchesObject().
  1326. GetOutputOrAppendOption(TRUE);
  1327. if ( bIsError || ( STDOUT == opsOutOpt ) )
  1328. {
  1329. if ( ! ConvertWCToMBCS ( lpszMsg, (LPVOID*) &lpszDisp, uCP ) )
  1330. {
  1331. _com_issue_error(WBEM_E_OUT_OF_MEMORY);
  1332. }
  1333. }
  1334. if (bIsLog)
  1335. {
  1336. // Append to the output string
  1337. g_wmiCmd.GetFormatObject().AppendtoOutputString ( lpszMsg ) ;
  1338. }
  1339. if ( bIsError == TRUE )
  1340. {
  1341. fprintf(stderr, "%s", lpszDisp);
  1342. fflush(stderr);
  1343. }
  1344. else
  1345. {
  1346. // OUT for getting append file pointer.
  1347. FILE* fpOutFile = g_wmiCmd.GetParsedInfoObject().
  1348. GetGlblSwitchesObject().
  1349. GetOutputOrAppendFilePointer(TRUE);
  1350. if ( opsOutOpt == CLIPBOARD )
  1351. {
  1352. g_wmiCmd.AddToClipBoardBuffer ( lpszMsg ) ;
  1353. }
  1354. else if ( opsOutOpt == FILEOUTPUT )
  1355. {
  1356. if (fpOutFile != NULL)
  1357. {
  1358. fwprintf( fpOutFile, L"%s", lpszMsg ) ;
  1359. }
  1360. }
  1361. else
  1362. {
  1363. if ( FALSE == bIsStream )
  1364. {
  1365. fprintf(stdout, "%s", lpszDisp);
  1366. fflush(stdout);
  1367. }
  1368. }
  1369. // FALSE for getting append file pointer.
  1370. FILE* fpAppendFile = g_wmiCmd.GetParsedInfoObject().
  1371. GetGlblSwitchesObject().
  1372. GetOutputOrAppendFilePointer(FALSE);
  1373. if ( fpAppendFile != NULL )
  1374. {
  1375. FILETYPE eftOpt = g_wmiCmd.GetParsedInfoObject().
  1376. GetGlblSwitchesObject().
  1377. GetFileType () ;
  1378. if ( ANSI_FILE == eftOpt )
  1379. {
  1380. fprintf ( fpAppendFile, "%S", lpszMsg ) ;
  1381. }
  1382. else
  1383. {
  1384. fwprintf( fpAppendFile, L"%s", lpszMsg ) ;
  1385. }
  1386. }
  1387. }
  1388. SAFEDELETE(lpszDisp);
  1389. }
  1390. }
  1391. catch(_com_error& e)
  1392. {
  1393. SAFEDELETE(lpszDisp);
  1394. _com_issue_error(e.Error());
  1395. }
  1396. catch(CHeap_Exception)
  1397. {
  1398. SAFEDELETE(lpszDisp);
  1399. _com_issue_error(WBEM_E_OUT_OF_MEMORY);
  1400. }
  1401. }
  1402. /*----------------------------------------------------------------------------
  1403. Name :CleanUpCharVector
  1404. Synopsis :Clears the character vector
  1405. Type :Global Function
  1406. Input parameter(s):
  1407. cvCharVector - reference to character vector.
  1408. Output parameter(s):None
  1409. Return Type :void
  1410. Global Variables :None
  1411. Calling Syntax :CleanUpCharVector(cvCharVector)
  1412. Notes :None
  1413. ----------------------------------------------------------------------------*/
  1414. void CleanUpCharVector(CHARVECTOR& cvCharVector)
  1415. {
  1416. if ( !cvCharVector.empty() )
  1417. {
  1418. CHARVECTOR::iterator theIterator;
  1419. for ( theIterator = cvCharVector.begin();
  1420. theIterator < cvCharVector.end(); theIterator++ )
  1421. {
  1422. SAFEDELETE( *theIterator );
  1423. }
  1424. cvCharVector.clear();
  1425. }
  1426. }
  1427. /*----------------------------------------------------------------------------
  1428. Name :FindAndReplaceAll
  1429. Synopsis :Search and replace all the occurences of pszFromStr
  1430. with pszToStr in the given string strString
  1431. Type :Global Function
  1432. Input parameter :
  1433. strString - string buffer
  1434. pszFromStr - string to searched and replaced
  1435. pszToStr - string to be replaced by
  1436. Output parameters :None
  1437. Return Type :void
  1438. Global Variables :None
  1439. Calling Syntax :CleanUpCharVector(cvCharVector)
  1440. Notes :None
  1441. ----------------------------------------------------------------------------*/
  1442. void FindAndReplaceAll(STRING& strString, _TCHAR* pszFromStr,_TCHAR* pszToStr)
  1443. {
  1444. if ( pszFromStr != NULL && pszToStr != NULL )
  1445. {
  1446. STRING::size_type stPos = 0;
  1447. STRING::size_type stFromPos = 0;
  1448. STRING::size_type stFromStrLen = lstrlen(pszFromStr);
  1449. STRING::size_type stToStrLen = lstrlen(pszToStr);
  1450. while( TRUE )
  1451. {
  1452. stPos = strString.find(pszFromStr, stFromPos, stFromStrLen);
  1453. if ( stPos == STRING::npos )
  1454. break;
  1455. strString.replace(stPos, stFromStrLen, pszToStr);
  1456. stFromPos = stPos + stToStrLen;
  1457. }
  1458. }
  1459. }
  1460. /*----------------------------------------------------------------------------
  1461. Name :IsSysProp
  1462. Synopsis :Returns true if the input property is a WMI system
  1463. property
  1464. Type :Global Function
  1465. Input parameter :
  1466. pszProp - property name
  1467. Output parameters :None
  1468. Return Type :BOOL
  1469. Global Variables :None
  1470. Notes :IsSysProp(pszProp)
  1471. ----------------------------------------------------------------------------*/
  1472. BOOL IsSysProp(_TCHAR* pszProp)
  1473. {
  1474. BOOL bRet = FALSE;
  1475. if (CompareTokens(pszProp, WMISYSTEM_CLASS) ||
  1476. CompareTokens(pszProp, WMISYSTEM_DERIVATION) ||
  1477. CompareTokens(pszProp, WMISYSTEM_DYNASTY) ||
  1478. CompareTokens(pszProp, WMISYSTEM_GENUS) ||
  1479. CompareTokens(pszProp, WMISYSTEM_NAMESPACE) ||
  1480. CompareTokens(pszProp, WMISYSTEM_PATH) ||
  1481. CompareTokens(pszProp, WMISYSTEM_PROPERTYCOUNT) ||
  1482. CompareTokens(pszProp, WMISYSTEM_REPLATH) ||
  1483. CompareTokens(pszProp, WMISYSTEM_SERVER) ||
  1484. CompareTokens(pszProp, WMISYSTEM_SUPERCLASS))
  1485. {
  1486. bRet = TRUE;
  1487. }
  1488. return bRet;
  1489. }
  1490. /*----------------------------------------------------------------------------
  1491. Name :EraseConsoleString
  1492. Synopsis :Displays white spaces at the current cursor position
  1493. and sets the cursor column to zero
  1494. Type :Global Function
  1495. Input parameter :String ID wich has to be wiped out, Console information prior to
  1496. writing the string.
  1497. Output parameters :None
  1498. Return Type :None
  1499. Global Variables :None
  1500. ----------------------------------------------------------------------------*/
  1501. void EraseConsoleString(CONSOLE_SCREEN_BUFFER_INFO* csbiInfo)
  1502. {
  1503. COORD coord;
  1504. HANDLE hStdOut = NULL;
  1505. WMICLIINT nHeight = 0;
  1506. DWORD dWritten = 0;
  1507. CONSOLE_SCREEN_BUFFER_INFO lcsbiInfo;
  1508. DWORD XCordW = 0;
  1509. DWORD YCordW = 0;
  1510. LPTSTR lpszMsg = new _TCHAR [BUFFER1024];
  1511. if( NULL == lpszMsg ) return; // NO MEMORY
  1512. // Obtain the standard output handle
  1513. hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1514. GetConsoleScreenBufferInfo(hStdOut, &lcsbiInfo);
  1515. XCordW = lcsbiInfo.dwCursorPosition.X - csbiInfo->dwCursorPosition.X;
  1516. YCordW = lcsbiInfo.dwCursorPosition.Y - csbiInfo->dwCursorPosition.Y;
  1517. dWritten = XCordW + ( YCordW * lcsbiInfo.dwMaximumWindowSize.X);
  1518. if( dWritten > BUFFER1024 ) dWritten = BUFFER1024;
  1519. FillMemory(lpszMsg, dWritten * sizeof(_TCHAR), '\0');
  1520. // Get the screen buffer size.
  1521. if (hStdOut != INVALID_HANDLE_VALUE )
  1522. nHeight = csbiInfo->srWindow.Bottom - csbiInfo->srWindow.Top;
  1523. else
  1524. nHeight = 0;
  1525. // if console size is positive (to address redirection)
  1526. if (nHeight > 0)
  1527. {
  1528. coord.X = 0;
  1529. coord.Y = csbiInfo->dwCursorPosition.Y;
  1530. SetConsoleCursorPosition(hStdOut, coord);
  1531. WriteConsole(hStdOut,lpszMsg,dWritten,&dWritten,NULL);
  1532. SetConsoleCursorPosition(hStdOut, coord);
  1533. }
  1534. SAFEDELETE(lpszMsg);
  1535. }
  1536. /*----------------------------------------------------------------------------
  1537. Name :IsRedirection
  1538. Synopsis :Returns true if the the output is being redirected
  1539. Type :Global Function
  1540. Input parameter :None
  1541. Output parameters :None
  1542. Return Type :BOOL
  1543. Global Variables :None
  1544. Notes :IsRedirection()
  1545. ----------------------------------------------------------------------------*/
  1546. BOOL IsRedirection()
  1547. {
  1548. HANDLE hStdOut = NULL;
  1549. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  1550. WMICLIINT nHeight = 0;
  1551. BOOL bRet = FALSE;
  1552. // Obtain the standard output handle
  1553. hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1554. if (hStdOut != INVALID_HANDLE_VALUE)
  1555. {
  1556. // Get the screen buffer size.
  1557. if ( GetConsoleScreenBufferInfo(hStdOut, &csbiInfo) == TRUE )
  1558. nHeight = csbiInfo.srWindow.Bottom - csbiInfo.srWindow.Top;
  1559. else
  1560. nHeight = 0;
  1561. if (nHeight <= 0)
  1562. bRet = TRUE;
  1563. }
  1564. else
  1565. bRet = TRUE;
  1566. return bRet;
  1567. }
  1568. /*----------------------------------------------------------------------------
  1569. Name :WMITRACEORERRORLOG
  1570. Synopsis :To display the trace of COM methods invoked
  1571. Type :Global Function
  1572. Input parameter :
  1573. hr - HRESULT value
  1574. nLine - the line number of the file.
  1575. pszFile - the file name
  1576. pszMsg - message to be displayed.
  1577. Output parameters :None
  1578. Return Type :None
  1579. Global Variables :None
  1580. Calling Syntax :WMITRACEORERRORLOG(hr, nLine, pszFile, (LPCWSTR)chsMsg,
  1581. eloErrLgOpt, bTrace)
  1582. Note : Default values dwError = 0, pszResult = NULL.
  1583. ----------------------------------------------------------------------------*/
  1584. void WMITRACEORERRORLOG(HRESULT hr, INT nLine, char* pszFile, _bstr_t bstrMsg,
  1585. DWORD dwThreadId, CParsedInfo& rParsedInfo,
  1586. BOOL bTrace, DWORD dwError, _TCHAR* pszResult)
  1587. {
  1588. _TCHAR* pszMsg = bstrMsg;
  1589. if ( pszMsg )
  1590. {
  1591. try
  1592. {
  1593. if ( bTrace == TRUE )
  1594. {
  1595. if (_tcsnicmp(pszMsg,_T("COMMAND:"),8) != 0)
  1596. {
  1597. CHString chsMessage;
  1598. CHString chsSInfo;
  1599. if (FAILED (hr))
  1600. chsMessage.Format(L"FAIL: %s\n", pszMsg?pszMsg:L"NULL");
  1601. else
  1602. chsMessage.Format(L"SUCCESS: %s\n",pszMsg?pszMsg:L"NULL");
  1603. _fputts((_TCHAR*)_bstr_t((LPCWSTR)chsMessage), stderr);
  1604. fflush(stderr);
  1605. chsSInfo.Format(L"Line: %6d File: %s\n", nLine,
  1606. (LPCWSTR)CHString(pszFile));
  1607. _fputts((_TCHAR*)_bstr_t((LPCWSTR)chsSInfo), stderr);
  1608. fflush(stderr);
  1609. if ( pszResult != NULL )
  1610. {
  1611. chsMessage.Format(L"Result: %s\n\n", pszResult);
  1612. _fputts((_TCHAR*)_bstr_t((LPCWSTR)chsMessage), stderr);
  1613. fflush(stderr);
  1614. }
  1615. else
  1616. {
  1617. _fputts(_T("\n"), stderr);
  1618. fflush(stderr);
  1619. }
  1620. }
  1621. }
  1622. }
  1623. catch(_com_error& e)
  1624. {
  1625. _com_issue_error(e.Error());
  1626. }
  1627. catch(CHeap_Exception)
  1628. {
  1629. _com_issue_error(WBEM_E_OUT_OF_MEMORY);
  1630. }
  1631. if ( rParsedInfo.GetErrorLogObject().GetErrLogOption() != NO_LOGGING )
  1632. {
  1633. try
  1634. {
  1635. rParsedInfo.GetErrorLogObject().
  1636. LogErrorOrOperation(hr, pszFile, nLine, pszMsg,
  1637. dwThreadId, dwError);
  1638. }
  1639. catch(DWORD dwError)
  1640. {
  1641. ::SetLastError(dwError);
  1642. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(dwError);
  1643. }
  1644. }
  1645. }
  1646. }
  1647. /*----------------------------------------------------------------------------
  1648. Name :DisplayWin32Error
  1649. Synopsis :Displays the formatted error message for the Win32
  1650. function calls failure
  1651. Type :Global Function
  1652. Input parameter :None
  1653. Output parameters :None
  1654. Return Type :BOOL
  1655. Global Variables :None
  1656. Calling Syntax :DisplayWin32Error()
  1657. Notes :None
  1658. ----------------------------------------------------------------------------*/
  1659. void DisplayWin32Error()
  1660. {
  1661. LPVOID lpMessage = NULL;
  1662. DWORD dwError = ::GetLastError();
  1663. try
  1664. {
  1665. // If there was an error, create a text message for it
  1666. DWORD dwRet = FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1667. FORMAT_MESSAGE_FROM_SYSTEM |
  1668. FORMAT_MESSAGE_IGNORE_INSERTS,
  1669. NULL,
  1670. dwError,
  1671. 0,
  1672. (LPTSTR) &lpMessage,
  1673. 0,
  1674. NULL
  1675. );
  1676. if ( 0 != dwRet )
  1677. {
  1678. _bstr_t bstrMsg;
  1679. WMIFormatMessage(IDS_I_ERROR_WIN32, 1, bstrMsg, (LPWSTR) lpMessage);
  1680. // Free the memory used up the error message
  1681. // and then exit
  1682. if ( NULL != lpMessage )
  1683. {
  1684. LocalFree(lpMessage);
  1685. lpMessage = NULL ;
  1686. }
  1687. // Display the error message
  1688. DisplayMessage((LPWSTR)bstrMsg, CP_OEMCP, TRUE, TRUE);
  1689. }
  1690. // Used for returning the error level
  1691. ::SetLastError(dwError);
  1692. }
  1693. catch(_com_error& e)
  1694. {
  1695. if ( lpMessage != NULL )
  1696. {
  1697. LocalFree(lpMessage);
  1698. lpMessage = NULL ;
  1699. }
  1700. _com_issue_error(e.Error());
  1701. }
  1702. }
  1703. /*----------------------------------------------------------------------------
  1704. Name :AcceptPassword
  1705. Synopsis :Prompts for the password when user name alone is
  1706. specified with the command
  1707. Type :Global Function
  1708. Input parameter :None
  1709. Output parameters :
  1710. pszPassword - password string
  1711. Return Type :void
  1712. Global Variables :None
  1713. Calling Syntax :AcceptPassword(pszPassword)
  1714. Notes :None
  1715. ----------------------------------------------------------------------------*/
  1716. void AcceptPassword(_TCHAR* pszPassword)
  1717. {
  1718. // local variables
  1719. TCHAR ch;
  1720. DWORD dwIndex = 0;
  1721. DWORD dwCharsRead = 0;
  1722. DWORD dwCharsWritten = 0;
  1723. DWORD dwPrevConsoleMode = 0;
  1724. HANDLE hStdIn = NULL;
  1725. _TCHAR szBuffer[BUFFER32] = NULL_STRING;
  1726. // Get the handle for the standard input
  1727. hStdIn = GetStdHandle( STD_INPUT_HANDLE );
  1728. // Get the current input mode of the input buffer
  1729. GetConsoleMode( hStdIn, &dwPrevConsoleMode );
  1730. // Set the mode such that the control keys are processed by the system
  1731. SetConsoleMode( hStdIn, ENABLE_PROCESSED_INPUT );
  1732. // Read the characters until a carriage return is hit
  1733. while( TRUE )
  1734. {
  1735. if ( !ReadConsole( hStdIn, &ch, 1, &dwCharsRead, NULL ))
  1736. {
  1737. // Set the original console settings
  1738. SetConsoleMode( hStdIn, dwPrevConsoleMode );
  1739. return;
  1740. }
  1741. // Check for carraige return
  1742. if ( ch == CARRIAGE_RETURN )
  1743. {
  1744. // break from the loop
  1745. break;
  1746. }
  1747. // Check id back space is hit
  1748. if ( ch == BACK_SPACE )
  1749. {
  1750. if ( dwIndex != 0 )
  1751. {
  1752. //
  1753. // Remove a asterik from the console
  1754. // move the cursor one character back
  1755. FORMAT_STRING( szBuffer, _T( "%c" ), BACK_SPACE );
  1756. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), szBuffer, 1,
  1757. &dwCharsWritten, NULL );
  1758. // replace the existing character with space
  1759. FORMAT_STRING( szBuffer, _T( "%c" ), BLANK_CHAR );
  1760. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), szBuffer, 1,
  1761. &dwCharsWritten, NULL );
  1762. // now set the cursor at back position
  1763. FORMAT_STRING( szBuffer, _T( "%c" ), BACK_SPACE );
  1764. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), szBuffer, 1,
  1765. &dwCharsWritten, NULL );
  1766. // decrement the index
  1767. dwIndex--;
  1768. }
  1769. // process the next character
  1770. continue;
  1771. }
  1772. // if the max password length has been reached then sound a beep
  1773. if ( dwIndex == ( MAXPASSWORDSIZE - 1 ) )
  1774. {
  1775. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), BEEP_SOUND, 1,
  1776. &dwCharsWritten, NULL );
  1777. }
  1778. else
  1779. {
  1780. // store the input character
  1781. *( pszPassword + dwIndex ) = ch;
  1782. dwIndex++;
  1783. // display asterix onto the console
  1784. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), ASTERIX, 1,
  1785. &dwCharsWritten, NULL );
  1786. }
  1787. }
  1788. // Add the NULL terminator
  1789. *( pszPassword + dwIndex ) = NULL_CHAR;
  1790. //Set the original console settings
  1791. SetConsoleMode( hStdIn, dwPrevConsoleMode );
  1792. // display the character ( new line character )
  1793. FORMAT_STRING( szBuffer, _T( "%s" ), _T( "\n\n" ) );
  1794. WriteConsole( GetStdHandle( STD_OUTPUT_HANDLE ), szBuffer, 2,
  1795. &dwCharsWritten, NULL );
  1796. }
  1797. /*----------------------------------------------------------------------------
  1798. Name :IsValueSet
  1799. Synopsis :Checks string passed in pszFromValue, Is a value set
  1800. or not.
  1801. Type :Global Function
  1802. Input parameter :
  1803. pszFromValue - string to be checked.
  1804. Output parameters :
  1805. cValue1 - <value1> of value set.
  1806. cValue2 - <value2> of value set.
  1807. Return Type :BOOL
  1808. Global Variables :None
  1809. Calling Syntax :IsValueSet(pszFromValue,cValue1,cValue2)
  1810. Notes :None
  1811. ----------------------------------------------------------------------------*/
  1812. BOOL IsValueSet(_TCHAR* pszFromValue, _TCHAR& cValue1, _TCHAR& cValue2)
  1813. {
  1814. BOOL bValueSet = FALSE;
  1815. if ( pszFromValue != NULL )
  1816. {
  1817. _TCHAR cV1 = _T('\0'), cV2 = _T('\0');
  1818. if ( lstrlen(pszFromValue) == 3 && pszFromValue[1] == _T('-') )
  1819. {
  1820. bValueSet = TRUE;
  1821. cV1 = pszFromValue[0];
  1822. cV2 = pszFromValue[2];
  1823. cValue1 = ( cV1 < cV2 ) ? cV1 : cV2 ;
  1824. cValue2 = ( cV1 > cV2 ) ? cV1 : cV2 ;
  1825. }
  1826. }
  1827. else
  1828. cValue1 = cValue2 = _T('\0');
  1829. return bValueSet;
  1830. }
  1831. /*----------------------------------------------------------------------------
  1832. Name :DisplayString
  1833. Synopsis :Displays localized string
  1834. Type :Global Function
  1835. Input parameter(s):
  1836. uID - string table identifier
  1837. uCP - codepage value
  1838. lpszParam - String to be used as parameter in resource string.
  1839. bIsError - Boolean type specifying error message or not.
  1840. bIsLog - Boolean type specifying message to be logged or not.
  1841. Output parameter(s):None
  1842. Return Type :void
  1843. Global Variables :None
  1844. Calling Syntax :DisplayString(uID, CP_OEMCP, NULL, TRUE, TRUE)
  1845. Notes :lpszParam = NULL, bIsError = FALSE, and bIsLog = FALSE
  1846. by default.
  1847. ----------------------------------------------------------------------------*/
  1848. void DisplayString(UINT uID, UINT uCP, LPTSTR lpszParam,
  1849. BOOL bIsError, BOOL bIsLog) throw(WMICLIINT)
  1850. {
  1851. LPVOID lpMsgBuf = NULL;
  1852. LPTSTR lpszMsg = NULL;
  1853. lpszMsg = new _TCHAR [BUFFER1024];
  1854. try
  1855. {
  1856. if (lpszMsg)
  1857. {
  1858. LoadString(NULL, uID, lpszMsg, BUFFER1024);
  1859. if (lpszParam)
  1860. {
  1861. char* pvaInsertStrs[1];
  1862. pvaInsertStrs[0] = (char*) lpszParam;
  1863. DWORD dwRet = FormatMessage(
  1864. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1865. FORMAT_MESSAGE_FROM_STRING |
  1866. FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1867. lpszMsg,
  1868. 0,
  1869. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1870. (LPTSTR) &lpMsgBuf,
  1871. 0,
  1872. pvaInsertStrs);
  1873. if (dwRet == 0)
  1874. {
  1875. SAFEDELETE(lpszMsg);
  1876. throw (::GetLastError());
  1877. }
  1878. }
  1879. DisplayMessage (
  1880. ( lpMsgBuf ) ? ( LPTSTR ) lpMsgBuf : lpszMsg,
  1881. uCP,
  1882. bIsError,
  1883. bIsLog
  1884. ) ;
  1885. SAFEDELETE(lpszMsg);
  1886. // Free the memory used up the error message
  1887. // and then exit
  1888. if ( lpMsgBuf != NULL )
  1889. {
  1890. LocalFree(lpMsgBuf);
  1891. lpMsgBuf = NULL ;
  1892. }
  1893. }
  1894. else
  1895. throw OUT_OF_MEMORY;
  1896. }
  1897. catch(_com_error& e)
  1898. {
  1899. if ( lpMsgBuf != NULL )
  1900. {
  1901. LocalFree(lpMsgBuf);
  1902. lpMsgBuf = NULL ;
  1903. }
  1904. SAFEDELETE(lpszMsg);
  1905. _com_issue_error(e.Error());
  1906. }
  1907. catch(CHeap_Exception)
  1908. {
  1909. if ( lpMsgBuf != NULL )
  1910. {
  1911. LocalFree(lpMsgBuf);
  1912. lpMsgBuf = NULL ;
  1913. }
  1914. SAFEDELETE(lpszMsg);
  1915. _com_issue_error(WBEM_E_OUT_OF_MEMORY);
  1916. }
  1917. }
  1918. /*----------------------------------------------------------------------------
  1919. Name :SubstituteEscapeChars
  1920. Synopsis :Substitue escape character i.e '\' before the
  1921. specified substring
  1922. Type :Global Function
  1923. Input parameter :
  1924. sSource - source string
  1925. lpszSub - substring to be searched for
  1926. Output parameters :
  1927. sSource - source string
  1928. Return Type :void
  1929. Global Variables :None
  1930. Calling Syntax :SubstituteEscapeChars(sTemp, lpszSub)
  1931. Notes :None
  1932. ----------------------------------------------------------------------------*/
  1933. void SubstituteEscapeChars(CHString& sTemp, LPCWSTR lpszSub)
  1934. {
  1935. try
  1936. {
  1937. CHString str(sTemp);
  1938. sTemp.Empty();
  1939. while ( str.GetLength() > 0 )
  1940. {
  1941. //LONG lPos = str.Find( L"\"" );
  1942. LONG lPos = str.Find(lpszSub);
  1943. if ( lPos != -1 )
  1944. {
  1945. sTemp += str.Left( lPos ) + L"\\\"";
  1946. str = str.Mid( lPos + 1 );
  1947. }
  1948. else
  1949. {
  1950. sTemp += str;
  1951. str.Empty();
  1952. }
  1953. }
  1954. }
  1955. catch(CHeap_Exception)
  1956. {
  1957. _com_issue_error(WBEM_E_OUT_OF_MEMORY);
  1958. }
  1959. }
  1960. /*----------------------------------------------------------------------------
  1961. Name :RemoveEscapeChars
  1962. Synopsis :Remove escape character i.e '\' before any of the
  1963. following characters
  1964. Type :Global Function
  1965. Input parameter(s):
  1966. sSource - source string
  1967. Output parameter(s):
  1968. sSource - source string
  1969. Return Type :void
  1970. Global Variables :None
  1971. Calling Syntax :RemoveEscapeChars(sTemp)
  1972. Notes :None
  1973. ----------------------------------------------------------------------------*/
  1974. void RemoveEscapeChars(CHString& sTemp)
  1975. {
  1976. try
  1977. {
  1978. CHString str(sTemp);
  1979. sTemp.Empty();
  1980. while ( str.GetLength() > 0 )
  1981. {
  1982. LONG lPos = str.Find(L"\\");
  1983. if ( lPos != -1 )
  1984. {
  1985. if (str.GetAt(lPos+1) == L'"')
  1986. {
  1987. sTemp += str.Left( lPos );
  1988. }
  1989. else
  1990. {
  1991. sTemp += str.Left( lPos ) + L"\\";
  1992. }
  1993. str = str.Mid( lPos + 1 );
  1994. }
  1995. else
  1996. {
  1997. sTemp += str;
  1998. str.Empty();
  1999. }
  2000. }
  2001. }
  2002. catch(CHeap_Exception)
  2003. {
  2004. throw OUT_OF_MEMORY;
  2005. }
  2006. }
  2007. /*----------------------------------------------------------------------------
  2008. Name :FrameNamespace
  2009. Synopsis :Frame the new namespace
  2010. Type :Global Function
  2011. Input parameter(s):
  2012. pszRoleOrNS - old namespace
  2013. pszRoleOrNSToUpdate - string to be appended/replaced
  2014. Output parameter(s):
  2015. pszRoleOrNSToUpdate - new namespace
  2016. Return Type :void
  2017. Global Variables :None
  2018. Calling Syntax :FrameNamespace(pszRoleOrNS, pszRoleOrNSToUpdate)
  2019. Notes :None
  2020. ----------------------------------------------------------------------------*/
  2021. void FrameNamespace(_TCHAR* pszRoleOrNS, _TCHAR* pszRoleOrNSToUpdate)
  2022. {
  2023. if ( pszRoleOrNS != NULL && pszRoleOrNSToUpdate != NULL )
  2024. {
  2025. LONG lRoleOrNSLen = lstrlen(pszRoleOrNS);
  2026. LONG lRoleOrNSToUpdate = lstrlen(pszRoleOrNSToUpdate);
  2027. _TCHAR *pszTemp = new _TCHAR[lRoleOrNSLen + lRoleOrNSToUpdate +
  2028. MAX_BUFFER];
  2029. if ( pszTemp != NULL )
  2030. {
  2031. if (!CompareTokens(pszRoleOrNS, CLI_TOKEN_NULL))
  2032. {
  2033. //if the role does not begin with a '\\' it should be assumed
  2034. //to be relative to the current role
  2035. if ( _tcsncmp(pszRoleOrNS, CLI_TOKEN_2BSLASH, 2) == 0 )
  2036. lstrcpy(pszTemp, pszRoleOrNS+2);
  2037. else if (_tcsncmp(pszRoleOrNS, CLI_TOKEN_2DOT, 2) == 0 )
  2038. {
  2039. _TCHAR *lp = NULL;
  2040. for (lp = &pszRoleOrNSToUpdate[lstrlen(pszRoleOrNSToUpdate) - 1];
  2041. lp > pszRoleOrNSToUpdate; lp--)
  2042. {
  2043. if (_tcsncmp(lp,CLI_TOKEN_2BSLASH,1) == 0)
  2044. { lstrcpy(lp,NULL_STRING);
  2045. break;
  2046. }
  2047. }
  2048. lstrcpy(pszTemp, pszRoleOrNSToUpdate);
  2049. if (_tcsncmp(pszRoleOrNS + 2, NULL_STRING, 1))
  2050. {
  2051. lstrcat(pszTemp, pszRoleOrNS + 2);
  2052. }
  2053. }
  2054. else
  2055. {
  2056. lstrcpy(pszTemp, pszRoleOrNSToUpdate);
  2057. lstrcat(pszTemp, CLI_TOKEN_BSLASH);
  2058. lstrcat(pszTemp, pszRoleOrNS);
  2059. }
  2060. //if the last character in the string pszRoleOrNS terminates
  2061. //with '\' terminate the string.
  2062. //this case occurs when namespace is specified as "xyz\"
  2063. if(CompareTokens(pszTemp + (WMICLIINT)lstrlen(pszTemp)-1,
  2064. CLI_TOKEN_BSLASH ) &&
  2065. !CompareTokens(pszTemp, CLI_TOKEN_2BSLASH))
  2066. {
  2067. pszTemp[lstrlen(pszTemp) - 1] = _T('\0');
  2068. }
  2069. }
  2070. else
  2071. lstrcpy(pszTemp, CLI_TOKEN_NULL);
  2072. lstrcpy(pszRoleOrNSToUpdate, pszTemp);
  2073. SAFEDELETE(pszTemp);
  2074. }
  2075. else
  2076. throw OUT_OF_MEMORY;
  2077. }
  2078. else
  2079. throw OUT_OF_MEMORY;
  2080. }
  2081. /*----------------------------------------------------------------------------
  2082. Name :SetScreenBuffer
  2083. Synopsis :Set the buffer size of the command line to the
  2084. following:
  2085. 1) Width - 500
  2086. 2) Height - 3000
  2087. Type :Global Function
  2088. Input parameter(s):
  2089. nHeight - height of the console buffer
  2090. nWidth - width of the console buffer
  2091. Output parameter(s):None
  2092. Return Type :void
  2093. Global Variables :None
  2094. Calling Syntax :SetScreenBuffer(nHeight, nWidth)
  2095. Notes :None
  2096. ----------------------------------------------------------------------------*/
  2097. BOOL SetScreenBuffer(SHORT nHeight, SHORT nWidth)
  2098. {
  2099. BOOL bResult = FALSE;
  2100. COORD coord;
  2101. coord.X = nWidth;
  2102. coord.Y = nHeight;
  2103. HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  2104. if ( hStdOut != INVALID_HANDLE_VALUE &&
  2105. hStdOut != (HANDLE)0x00000013 ) // For telnet
  2106. {
  2107. // Set the console screen buffer info
  2108. bResult = SetConsoleScreenBufferSize(hStdOut, coord);
  2109. }
  2110. return bResult;
  2111. }
  2112. /*----------------------------------------------------------------------------
  2113. Name :GetScreenBuffer
  2114. Synopsis :Get the buffer size of the command line
  2115. Type :Global Function
  2116. Input parameter(s):None
  2117. Output parameter(s):
  2118. nHeight - height of the console buffer
  2119. nWidth - width of the console buffer
  2120. Return Type :void
  2121. Global Variables :None
  2122. Calling Syntax :GetScreenBuffer(nHeight, nWidth)
  2123. Notes :None
  2124. ----------------------------------------------------------------------------*/
  2125. BOOL GetScreenBuffer(SHORT& nHeight, SHORT& nWidth)
  2126. {
  2127. BOOL bResult = FALSE;
  2128. HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  2129. if ( hStdOut != INVALID_HANDLE_VALUE &&
  2130. hStdOut != (HANDLE)0x00000013 ) // For telnet
  2131. {
  2132. CONSOLE_SCREEN_BUFFER_INFO csbConsoleScreenBufferInfo;
  2133. // Set the console screen buffer info
  2134. if ( GetConsoleScreenBufferInfo(hStdOut, &csbConsoleScreenBufferInfo) == TRUE )
  2135. {
  2136. nHeight = csbConsoleScreenBufferInfo.dwSize.Y;
  2137. nWidth = csbConsoleScreenBufferInfo.dwSize.X;
  2138. bResult = TRUE;
  2139. }
  2140. else
  2141. {
  2142. nHeight = 0;
  2143. nWidth = 0;
  2144. }
  2145. }
  2146. return bResult;
  2147. }
  2148. /*----------------------------------------------------------------------------
  2149. Name :WMIFormatMessage
  2150. Synopsis :This function loads the resource string using the
  2151. ID of the string and does parameter substituion using
  2152. the FormatMessage() function.
  2153. Type :Global Function
  2154. Input parameter(s):
  2155. uID - resource ID
  2156. nParamCount - no. of. parameter(s) to be substituted.
  2157. lpszParam - first parameter. (%1)
  2158. ... - variable number of arguments (%2, %3, ...)
  2159. Output parameter(s):
  2160. bstrMSG - formatted message
  2161. Return Type :void
  2162. Global Variables :None
  2163. Calling Syntax :WMIFormatMessage(uID, nParamCount, bstrMsg,
  2164. lpszParam,)
  2165. Notes :None
  2166. ----------------------------------------------------------------------------*/
  2167. void WMIFormatMessage(UINT uID, WMICLIINT nParamCount, _bstr_t& bstrMsg,
  2168. LPTSTR lpszParam, ...)
  2169. {
  2170. // Load the resource string
  2171. _TCHAR pszMsg[BUFFER1024];
  2172. LoadString(NULL, uID, pszMsg, BUFFER1024);
  2173. // If parameters are specified.
  2174. if (lpszParam)
  2175. {
  2176. LPTSTR lpszTemp = lpszParam;
  2177. INT nLoop = 0;
  2178. char* pvaInsertStrs[5];
  2179. va_list marker;
  2180. va_start(marker, lpszParam);
  2181. while (TRUE)
  2182. {
  2183. pvaInsertStrs[nLoop++] = (char*) lpszTemp;
  2184. lpszTemp = va_arg(marker, LPTSTR);
  2185. if (nLoop == nParamCount)
  2186. break;
  2187. }
  2188. va_end(marker);
  2189. LPVOID lpMsgBuf = NULL;
  2190. DWORD dwRet = FormatMessage (
  2191. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2192. FORMAT_MESSAGE_FROM_STRING |
  2193. FORMAT_MESSAGE_ARGUMENT_ARRAY,
  2194. pszMsg,
  2195. 0,
  2196. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2197. (LPTSTR) &lpMsgBuf,
  2198. 0,
  2199. pvaInsertStrs
  2200. );
  2201. if ( 0 != dwRet )
  2202. {
  2203. if ( lpMsgBuf )
  2204. {
  2205. bstrMsg = (WCHAR*)lpMsgBuf;
  2206. // Free the memory used for the message and then exit
  2207. LocalFree(lpMsgBuf);
  2208. lpMsgBuf = NULL ;
  2209. }
  2210. }
  2211. else
  2212. {
  2213. bstrMsg = pszMsg;
  2214. }
  2215. }
  2216. else
  2217. {
  2218. bstrMsg = pszMsg;
  2219. }
  2220. }
  2221. /*----------------------------------------------------------------------------
  2222. Name :InitWinsock
  2223. Synopsis :This function initiates the windows sockets interface.
  2224. Type :Global Function
  2225. Input parameter :None
  2226. Output parameters :None
  2227. Return Type :BOOL
  2228. Global Variables :None
  2229. Calling Syntax :InitWinsock ()
  2230. Notes :None
  2231. ----------------------------------------------------------------------------*/
  2232. BOOL InitWinsock ()
  2233. {
  2234. BOOL bSuccess = TRUE;
  2235. WMICLIINT nRes;
  2236. WSADATA wsaData;
  2237. WORD wVerRequested = 0x0101; // ver 1.1
  2238. // The Windows Sockets WSAStartup function initiates use of Ws2_32.dll
  2239. // by a process.
  2240. // Init the sockets interface
  2241. nRes = WSAStartup (wVerRequested, &wsaData);
  2242. if (nRes)
  2243. bSuccess = FALSE;
  2244. return bSuccess;
  2245. }
  2246. /*----------------------------------------------------------------------------
  2247. Name :TermWinsock
  2248. Synopsis :This function uninitializes the windows sockets
  2249. interface.
  2250. Type :Global Function
  2251. Input parameter :None
  2252. Output parameters :None
  2253. Return Type :BOOL
  2254. Global Variables :None
  2255. Calling Syntax :TermWinsock ()
  2256. Notes :None
  2257. ----------------------------------------------------------------------------*/
  2258. BOOL TermWinsock ()
  2259. {
  2260. // Uninitailize windows socket interface.
  2261. BOOL bSuccess = TRUE;
  2262. if (SOCKET_ERROR == WSACleanup ())
  2263. bSuccess = FALSE;
  2264. return bSuccess;
  2265. }
  2266. /*----------------------------------------------------------------------------
  2267. Name :PingNode
  2268. Synopsis :Pings a node to validate availibility of node using
  2269. windows socket functions.
  2270. Type :Global Function
  2271. Input parameter :
  2272. pszNode - Pointer to a string specifing node name.
  2273. Output parameters :None
  2274. Return Type :BOOL
  2275. Global Variables :None
  2276. Calling Syntax :PingNode(pszNode)
  2277. Notes :None
  2278. ----------------------------------------------------------------------------*/
  2279. BOOL PingNode(_TCHAR* pszNode)
  2280. {
  2281. BOOL bRet = TRUE;
  2282. HOSTENT *pNodeEnt = NULL;
  2283. HANDLE hIcmpHandle = NULL;
  2284. char *pszSendBuffer = NULL;
  2285. char *pszRcvBuffer = NULL;
  2286. UINT nSendSize = DEFAULT_SEND_SIZE;
  2287. UINT nRcvSize = DEFAULT_BUFFER_SIZE;
  2288. ULONG nTimeout = PING_TIMEOUT;
  2289. UCHAR *pszOpt = NULL;
  2290. UINT nOptLength = 0;
  2291. ULONG ulINAddr = INADDR_NONE;
  2292. UCHAR uFlags = 0;
  2293. DWORD dwNumOfReplies = 1; // Set 1 for finding error
  2294. IP_OPTION_INFORMATION ioiSendOpts;
  2295. try
  2296. {
  2297. if ( pszNode )
  2298. {
  2299. // pszNode can be IPAddress of node or node name itself.
  2300. _bstr_t bstrNodeNameOrIPAddr(pszNode);
  2301. // Initialize windows socket interface.
  2302. if ( g_wmiCmd.GetInitWinSock() == FALSE )
  2303. {
  2304. bRet = InitWinsock();
  2305. g_wmiCmd.SetInitWinSock(bRet);
  2306. }
  2307. if ( bRet == TRUE )
  2308. {
  2309. // Get IPAddress.
  2310. ulINAddr = inet_addr((char*)bstrNodeNameOrIPAddr);
  2311. // If not an IP address. then it may be computername.
  2312. if ( ulINAddr == INADDR_NONE )
  2313. {
  2314. pNodeEnt = gethostbyname((char*)bstrNodeNameOrIPAddr);
  2315. if ( pNodeEnt == NULL)
  2316. {
  2317. bRet = FALSE; // "computername" is not found.
  2318. }
  2319. else
  2320. {
  2321. ulINAddr = *(DWORD *)pNodeEnt->h_addr ;
  2322. }
  2323. }
  2324. }
  2325. if ( bRet == TRUE )
  2326. {
  2327. // Create IcmpFile
  2328. hIcmpHandle = IcmpCreateFile();
  2329. if ( hIcmpHandle == INVALID_HANDLE_VALUE )
  2330. throw GetLastError();
  2331. // Alloc memory to send buffer
  2332. pszSendBuffer = (char*)LocalAlloc(LMEM_FIXED, nSendSize);
  2333. if ( pszSendBuffer == NULL )
  2334. throw GetLastError();
  2335. // Fill Some data in send buffer
  2336. for (WMICLIINT i = 0; i < nSendSize; i++)
  2337. {
  2338. pszSendBuffer[i] = 'a' + (i % 23);
  2339. }
  2340. // Initialize the send options
  2341. ioiSendOpts.OptionsData = pszOpt;
  2342. ioiSendOpts.OptionsSize = (UCHAR)nOptLength;
  2343. ioiSendOpts.Ttl = DEFAULT_TTL;
  2344. ioiSendOpts.Tos = DEFAULT_TOS;
  2345. ioiSendOpts.Flags = uFlags;
  2346. // Alloc memory to receive buffer
  2347. pszRcvBuffer = (char*)LocalAlloc(LMEM_FIXED, nRcvSize);
  2348. if ( pszRcvBuffer == NULL )
  2349. throw GetLastError();
  2350. dwNumOfReplies = IcmpSendEcho(hIcmpHandle,
  2351. (IPAddr)ulINAddr,
  2352. pszSendBuffer,
  2353. (unsigned short) nSendSize,
  2354. &ioiSendOpts,
  2355. pszRcvBuffer,
  2356. nRcvSize,
  2357. nTimeout);
  2358. if ( dwNumOfReplies == 0 )
  2359. throw GetLastError();
  2360. // Free memory
  2361. LocalFree(pszSendBuffer);
  2362. LocalFree(pszRcvBuffer);
  2363. IcmpCloseHandle(hIcmpHandle);
  2364. }
  2365. }
  2366. else
  2367. bRet = FALSE; // Null nodename pointer.
  2368. }
  2369. catch(_com_error& e)
  2370. {
  2371. // Free memory
  2372. if ( hIcmpHandle != NULL )
  2373. IcmpCloseHandle(hIcmpHandle);
  2374. if ( pszSendBuffer != NULL )
  2375. LocalFree(pszSendBuffer);
  2376. if ( pszRcvBuffer != NULL )
  2377. LocalFree(pszRcvBuffer);
  2378. bRet = FALSE;
  2379. _com_issue_error(e.Error());
  2380. }
  2381. catch (DWORD dwError)
  2382. {
  2383. // if ping failed then don't display win32 error
  2384. if ( dwNumOfReplies != 0 )
  2385. {
  2386. ::SetLastError(dwError);
  2387. DisplayWin32Error();
  2388. ::SetLastError(dwError);
  2389. }
  2390. bRet = FALSE;
  2391. // Free memory
  2392. if ( hIcmpHandle != NULL )
  2393. IcmpCloseHandle(hIcmpHandle);
  2394. if ( pszSendBuffer != NULL )
  2395. LocalFree(pszSendBuffer);
  2396. if ( pszRcvBuffer != NULL )
  2397. LocalFree(pszRcvBuffer);
  2398. }
  2399. catch (CHeap_Exception)
  2400. {
  2401. // Free memory
  2402. if ( pszSendBuffer != NULL )
  2403. LocalFree(pszSendBuffer);
  2404. if ( hIcmpHandle != NULL )
  2405. IcmpCloseHandle(hIcmpHandle);
  2406. if ( pszRcvBuffer != NULL )
  2407. LocalFree(pszRcvBuffer);
  2408. bRet = FALSE;
  2409. }
  2410. return bRet;
  2411. }
  2412. /*----------------------------------------------------------------------------
  2413. Name :IsFailFastAndNodeExist
  2414. Synopsis :Validates node if FailFast is on, If pszNodeName == NULL
  2415. then check for GetNode() else pszNodeName itself.
  2416. Type :Global Function
  2417. Input parameter(s):
  2418. rParsedInfo - reference to object of CParsedInfo.
  2419. pszNode - Pointer to a string specifing node name.
  2420. Output parameter(s):None
  2421. Return Type :BOOL
  2422. Global Variables :None
  2423. Calling Syntax :IsFailFastAndNodeExist(rParsedInfo, pszNode)
  2424. Notes :None
  2425. ----------------------------------------------------------------------------*/
  2426. BOOL IsFailFastAndNodeExist(CParsedInfo& rParsedInfo, _TCHAR* pszNode)
  2427. {
  2428. BOOL bRet = TRUE;
  2429. // If FailFast is on.
  2430. if ( rParsedInfo.GetGlblSwitchesObject().GetFailFast() == TRUE )
  2431. {
  2432. // Form the appropriate node name. If pszNodeName != NULL pszNode
  2433. // should be validated. Else Node stored should be validated.
  2434. _TCHAR* pszNodeName = NULL;
  2435. if (pszNode == NULL)
  2436. pszNodeName = rParsedInfo.GetGlblSwitchesObject().GetNode();
  2437. else
  2438. pszNodeName = pszNode;
  2439. // "." node name specifies local machine and need not to be validated.
  2440. if ( CompareTokens(pszNodeName, CLI_TOKEN_DOT) == FALSE )
  2441. {
  2442. // If pinging node fails then node is unavialable.
  2443. if ( PingNode(pszNodeName) == FALSE )
  2444. {
  2445. rParsedInfo.GetCmdSwitchesObject().SetErrataCode(
  2446. IDS_E_RPC_SERVER_NOT_AVAILABLE);
  2447. bRet = FALSE;
  2448. }
  2449. }
  2450. }
  2451. return bRet;
  2452. }
  2453. /*----------------------------------------------------------------------------
  2454. Name :GetBstrTFromVariant
  2455. Synopsis :Get _bstr_t object equivalent to Varaint passed.
  2456. Type :Global Function
  2457. Input parameter(s):
  2458. vtVar - variant object
  2459. pszType - Pointer to string specifying type of the object passed.
  2460. Output parameter(s):
  2461. bstrObj - BSTR object
  2462. Return Type :BOOL
  2463. Global Variables :None
  2464. Calling Syntax :GetBstrTFromVariant(vtVar, bstrObj)
  2465. Notes :None
  2466. ----------------------------------------------------------------------------*/
  2467. void GetBstrTFromVariant(VARIANT& vtVar, _bstr_t& bstrObj,
  2468. _TCHAR* pszType)
  2469. {
  2470. VARTYPE vType;
  2471. VARIANT vtDest;
  2472. VariantInit(&vtDest);
  2473. try
  2474. {
  2475. if ( vtVar.vt != VT_NULL && vtVar.vt != VT_EMPTY )
  2476. {
  2477. if ( VariantChangeType(&vtDest, &vtVar,0 , VT_BSTR) == S_OK )
  2478. {
  2479. bstrObj = _bstr_t(vtDest);
  2480. }
  2481. else
  2482. {
  2483. // The following line assures that
  2484. // if an exception is thrown (say
  2485. // in the bstr_t allocation below)
  2486. // VariantClear in the catch statement
  2487. // won't try to clear anything.
  2488. V_VT(&vtDest) = VT_EMPTY;
  2489. if ( vtVar.vt == VT_UNKNOWN )
  2490. {
  2491. if ( pszType != NULL )
  2492. {
  2493. bstrObj = _bstr_t(pszType);
  2494. }
  2495. else
  2496. {
  2497. bstrObj = _bstr_t("<Embeded Object>");
  2498. }
  2499. }
  2500. else if ( SafeArrayGetVartype(vtVar.parray, &vType) == S_OK )
  2501. {
  2502. if ( pszType != NULL )
  2503. {
  2504. bstrObj = _bstr_t("<Array of ") + _bstr_t(pszType) +
  2505. _bstr_t(">");
  2506. }
  2507. else
  2508. {
  2509. bstrObj = _bstr_t("<Array>");
  2510. }
  2511. }
  2512. else
  2513. {
  2514. bstrObj = _bstr_t("UNKNOWN");
  2515. }
  2516. }
  2517. }
  2518. else
  2519. {
  2520. bstrObj = _bstr_t(_T("<null>"));
  2521. }
  2522. VARIANTCLEAR(vtDest);
  2523. }
  2524. catch(_com_error& e)
  2525. {
  2526. VARIANTCLEAR(vtDest);
  2527. _com_issue_error(e.Error());
  2528. }
  2529. }
  2530. /*----------------------------------------------------------------------------
  2531. Name :IsValidFile
  2532. Synopsis :This functions checks if a given file name is
  2533. Valid.
  2534. Type :Global Function
  2535. Input parameter(s):
  2536. pszFileName - String type, Name of the file to be validated
  2537. Output parameter(s):None
  2538. Return Type :RETCODE
  2539. Global Variables :None
  2540. Calling Syntax :IsValidFile(pszFileName)
  2541. Notes :None
  2542. ----------------------------------------------------------------------------*/
  2543. RETCODE IsValidFile(_TCHAR* pszFileName)
  2544. {
  2545. RETCODE bRet = PARSER_ERROR;
  2546. BOOL bValidFileName = TRUE;
  2547. LONG lFileNameLen = lstrlen(pszFileName);
  2548. LONG lCount = lFileNameLen;
  2549. while( lCount >= 0 )
  2550. {
  2551. if (pszFileName[lCount] == _T('\\'))
  2552. break;
  2553. lCount--;
  2554. }
  2555. if(lCount != 0)
  2556. lCount++;
  2557. while( lCount <= lFileNameLen )
  2558. {
  2559. if( pszFileName[lCount] == _T('/') ||
  2560. pszFileName[lCount] == _T('\\') ||
  2561. pszFileName[lCount] == _T(':') ||
  2562. pszFileName[lCount] == _T('*') ||
  2563. pszFileName[lCount] == _T('?') ||
  2564. pszFileName[lCount] == _T('\"') ||
  2565. pszFileName[lCount] == _T('<') ||
  2566. pszFileName[lCount] == _T('>') ||
  2567. pszFileName[lCount] == _T('|') )
  2568. {
  2569. bValidFileName = FALSE;
  2570. break;
  2571. }
  2572. lCount++;
  2573. }
  2574. if ( pszFileName != NULL && bValidFileName == TRUE)
  2575. {
  2576. FILE *fpFile = _tfopen(pszFileName, _T("a"));
  2577. if ( fpFile != NULL )
  2578. {
  2579. LONG lFileHandle = _fileno(fpFile);
  2580. if ( _filelength(lFileHandle) == 0)
  2581. {
  2582. if ( fclose(fpFile) == 0 )
  2583. {
  2584. if ( _tremove(pszFileName) == 0 )
  2585. bRet = PARSER_CONTINUE;
  2586. else
  2587. {
  2588. DisplayWin32Error();
  2589. bRet = PARSER_ERRMSG;
  2590. }
  2591. }
  2592. }
  2593. else if ( fclose(fpFile) == 0 )
  2594. bRet = PARSER_CONTINUE;
  2595. }
  2596. }
  2597. return bRet;
  2598. }
  2599. /*----------------------------------------------------------------------------
  2600. Name :FindAndReplaceEntityReferences
  2601. Synopsis :Search and replace all the occurences of entity
  2602. references.
  2603. Type :Global Function
  2604. Input parameter(s):
  2605. strString - string buffer
  2606. Output parameter(s):None
  2607. Return Type :void
  2608. Global Variables :None
  2609. Calling Syntax :FindAndReplaceEntityReferences(strString);
  2610. Notes :None
  2611. ----------------------------------------------------------------------------*/
  2612. void FindAndReplaceEntityReferences(_bstr_t& bstrString)
  2613. {
  2614. STRING strString((_TCHAR*)bstrString);
  2615. FindAndReplaceAll(strString, _T("&"), _T("&amp;"));
  2616. FindAndReplaceAll(strString, _T("<"), _T("&lt;"));
  2617. FindAndReplaceAll(strString, _T(">"), _T("&gt;"));
  2618. FindAndReplaceAll(strString, _T("\'"), _T("&apos;"));
  2619. FindAndReplaceAll(strString, _T("\""), _T("&quot;"));
  2620. try
  2621. {
  2622. bstrString = _bstr_t((LPTSTR)strString.data());
  2623. }
  2624. catch(_com_error& e)
  2625. {
  2626. _com_issue_error(e.Error());
  2627. }
  2628. }
  2629. /*----------------------------------------------------------------------------
  2630. Name :IsOption
  2631. Synopsis :It checks whether the current token indicates option. An
  2632. option can start with '/' or '-'
  2633. Type :Global Function
  2634. Input Parameter(s):
  2635. pszToken - pointer to token.
  2636. Output Parameter(s):None
  2637. Return Type :BOOL
  2638. Global Variables :None
  2639. Calling Syntax :IsOption(pszToken)
  2640. Notes :None
  2641. ----------------------------------------------------------------------------*/
  2642. BOOL IsOption(_TCHAR* pszToken)
  2643. {
  2644. BOOL bRet = TRUE;
  2645. if ( pszToken != NULL )
  2646. {
  2647. bRet = (CompareTokens(pszToken, CLI_TOKEN_FSLASH)
  2648. || CompareTokens(pszToken, CLI_TOKEN_HYPHEN))
  2649. ? TRUE : FALSE;
  2650. }
  2651. else
  2652. bRet = FALSE;
  2653. return bRet;
  2654. }
  2655. /*----------------------------------------------------------------------------
  2656. Name :IsClassOperation
  2657. Synopsis :It checks whether the current operation is class
  2658. level operation or instance level operation
  2659. Type :Global Function
  2660. Input Parameter(s):
  2661. rParsedInfo - reference to CParsedInfo class object
  2662. Output Parameter(s):None
  2663. Return Type :BOOL
  2664. Global Variables :None
  2665. Calling Syntax :IsClassOperation(rParsedInfo)
  2666. Notes :None
  2667. ----------------------------------------------------------------------------*/
  2668. BOOL IsClassOperation(CParsedInfo& rParsedInfo)
  2669. {
  2670. BOOL bClass = FALSE;
  2671. if ( rParsedInfo.GetCmdSwitchesObject().GetAliasName() == NULL
  2672. && (rParsedInfo.GetCmdSwitchesObject().
  2673. GetWhereExpression() == NULL)
  2674. && (rParsedInfo.GetCmdSwitchesObject().
  2675. GetPathExpression() == NULL))
  2676. {
  2677. bClass = TRUE;
  2678. }
  2679. return bClass;
  2680. }
  2681. /*-------------------------------------------------------------------------
  2682. Name :ModifyPrivileges
  2683. Synopsis :This function enables/disables all the token privileges
  2684. for current process token.
  2685. Type :Global Function
  2686. Input Parameter(s):
  2687. bEnable - Enable|Disable privileges flag
  2688. Output Parameter(s):None
  2689. Return Type :HRESULT
  2690. Global Variables :None
  2691. Calling Syntax :ModifyPrivileges(bEnable)
  2692. Notes :none
  2693. -------------------------------------------------------------------------*/
  2694. HRESULT ModifyPrivileges(BOOL bEnable)
  2695. {
  2696. HANDLE hToken = NULL;
  2697. DWORD dwError = ERROR_SUCCESS,
  2698. dwLen = 0;
  2699. BOOL bRes = TRUE;
  2700. TOKEN_USER tu;
  2701. HRESULT hr = WBEM_S_NO_ERROR;
  2702. BYTE *pBuffer = NULL;
  2703. // Open the access token associated with the current process.
  2704. bRes = OpenProcessToken(GetCurrentProcess(),
  2705. TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
  2706. &hToken);
  2707. if (bRes)
  2708. {
  2709. // If disable privilges
  2710. if (!bEnable)
  2711. {
  2712. // Store the information back into the token,after disabling all
  2713. // the privileges
  2714. bRes = AdjustTokenPrivileges(hToken, TRUE, NULL, 0, NULL, NULL);
  2715. if (!bRes)
  2716. hr = WBEM_E_ACCESS_DENIED;
  2717. }
  2718. else // If enable privileges
  2719. {
  2720. // Get the privileges
  2721. memset(&tu,0,sizeof(TOKEN_USER));
  2722. bRes = GetTokenInformation(hToken, TokenPrivileges, &tu,
  2723. sizeof(TOKEN_USER), &dwLen);
  2724. pBuffer = new BYTE[dwLen];
  2725. if(pBuffer != NULL)
  2726. {
  2727. bRes = GetTokenInformation(hToken, TokenPrivileges,
  2728. pBuffer, dwLen, &dwLen);
  2729. if (bRes)
  2730. {
  2731. // Iterate through all the privileges and enable them all
  2732. TOKEN_PRIVILEGES* pPrivs = (TOKEN_PRIVILEGES*)pBuffer;
  2733. for (DWORD i = 0; i < pPrivs->PrivilegeCount; i++)
  2734. {
  2735. pPrivs->Privileges[i].Attributes
  2736. |= SE_PRIVILEGE_ENABLED;
  2737. }
  2738. // Store the information back into the token
  2739. bRes = AdjustTokenPrivileges(hToken, FALSE, pPrivs, 0,
  2740. NULL, NULL);
  2741. if (!bRes)
  2742. hr = WBEM_E_ACCESS_DENIED;
  2743. }
  2744. else
  2745. hr = WBEM_E_ACCESS_DENIED;
  2746. SAFEDELETE(pBuffer);
  2747. }
  2748. else
  2749. hr = WBEM_E_OUT_OF_MEMORY;
  2750. }
  2751. CloseHandle(hToken);
  2752. }
  2753. else
  2754. hr = WBEM_E_ACCESS_DENIED;
  2755. return hr;
  2756. }
  2757. /*-------------------------------------------------------------------------
  2758. Name :RemoveParanthesis
  2759. Synopsis :This function removes the opening and closing
  2760. paranthesis in the given string.
  2761. Type :Global Function
  2762. Input Parameter(s):
  2763. pszString - String which has paranthesis.
  2764. Output Parameter(s):None
  2765. Return Type :void
  2766. Global Variables :None
  2767. Calling Syntax :RemoveParanthesis(pszString)
  2768. Notes :none
  2769. -------------------------------------------------------------------------*/
  2770. void RemoveParanthesis(_TCHAR*& pszString)
  2771. {
  2772. if ((lstrlen(pszString) - 1) > 0)
  2773. {
  2774. // Check if the string is enclosed within quotes
  2775. if ((pszString[0] == _T('('))
  2776. && (pszString[lstrlen(pszString)-1] == _T(')')))
  2777. {
  2778. WMICLIINT nLoop = 1, nLen = lstrlen(pszString)-1;
  2779. while (nLoop < nLen)
  2780. {
  2781. pszString[nLoop-1] = pszString[nLoop];
  2782. nLoop++;
  2783. }
  2784. pszString[nLen-1] = _T('\0');
  2785. }
  2786. }
  2787. }
  2788. /*-------------------------------------------------------------------------
  2789. Name :TrimBlankSpaces
  2790. Synopsis :This function removes the leading and trailing blank
  2791. spaces in the given string.
  2792. Type :Global Function
  2793. Input Parameter(s):
  2794. pszString - String in which leading and trailing spaces to be
  2795. removed..
  2796. Output Parameter(s):None
  2797. Return Type :void
  2798. Global Variables :None
  2799. Calling Syntax :TrimBlankSpaces(pszString)
  2800. Notes :none
  2801. -------------------------------------------------------------------------*/
  2802. void TrimBlankSpaces(_TCHAR *pszString)
  2803. {
  2804. if ((lstrlen(pszString) - 1) > 0)
  2805. {
  2806. WMICLIINT nLengthOfString = lstrlen(pszString);
  2807. WMICLIINT nNoOfBlanksAtBegin = 0;
  2808. WMICLIINT nNoOfBlanksAtEnd = 0;
  2809. // find the noof blank chars at begining
  2810. for(WMICLIINT i=0; i<nLengthOfString; ++i)
  2811. {
  2812. if( pszString[i] != _T(' ') )
  2813. break;
  2814. else
  2815. nNoOfBlanksAtBegin++;
  2816. }
  2817. // find the noof blank chars at end
  2818. for(WMICLIINT i=nLengthOfString - 1; i>=0; --i)
  2819. {
  2820. if( pszString[i] != _T(' ') )
  2821. break;
  2822. else
  2823. nNoOfBlanksAtEnd++;
  2824. }
  2825. // Remove the blanks at begining
  2826. if( nNoOfBlanksAtBegin > 0 )
  2827. {
  2828. // Shift the chars front
  2829. WMICLIINT nLoop = nNoOfBlanksAtBegin;
  2830. while ( nLoop < nLengthOfString )
  2831. {
  2832. pszString[nLoop - nNoOfBlanksAtBegin] = pszString[nLoop];
  2833. nLoop++;
  2834. }
  2835. pszString[nLengthOfString-nNoOfBlanksAtBegin] = _T('\0');
  2836. }
  2837. // Remove the blanks at end
  2838. if ( nNoOfBlanksAtEnd > 0)
  2839. pszString[lstrlen(pszString) - nNoOfBlanksAtEnd] = _T('\0');
  2840. }
  2841. }