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

687 lines
15 KiB

  1. /**********************************************************************/
  2. /** Microsoft Windows/NT **/
  3. /** Copyright(c) Microsoft Corporation, 1997 - 1999 **/
  4. /**********************************************************************/
  5. /*
  6. helper.cpp
  7. Implementation of the following helper classes:
  8. CDlgHelper -- enable, check, getcheck of dialog items
  9. CStrArray -- manages an array of CString*
  10. It doesn't duplicate the string when add
  11. It deletes the pointers during destruction
  12. It imports and exports SAFEARRAY of BSTRs
  13. It has copy operatators
  14. CManagedPage -- provide a middle layer between CpropertyPage and
  15. real property page class to manage: readonly, set modify, and
  16. context help info.
  17. CHelpDialog -- implments context help
  18. And global functions:
  19. BOOL CheckADsError() -- check error code from ADSI
  20. void DecorateName() -- make new name to "CN=name" for LDAP
  21. FILE HISTORY:
  22. */
  23. #include "stdafx.h"
  24. #include <afxtempl.h>
  25. #include <shlobj.h>
  26. #include <dsclient.h>
  27. #include <winldap.h>
  28. #include <dsgetdc.h>
  29. #include <mmc.h>
  30. #include "helper.h"
  31. #include "resource.h"
  32. #include <dsrole.h>
  33. #include <lm.h>
  34. #include <lmserver.h>
  35. // helper function -- enable a dialog button
  36. void CDlgHelper::EnableDlgItem(CDialog* pDialog, int id, bool bEnable)
  37. {
  38. CWnd* pWnd = pDialog->GetDlgItem(id);
  39. ASSERT(pWnd);
  40. pWnd->EnableWindow(bEnable);
  41. }
  42. // helper function -- set check status of a dialog button
  43. void CDlgHelper::SetDlgItemCheck(CDialog* pDialog, int id, int nCheck)
  44. {
  45. CButton* pButton = (CButton*)pDialog->GetDlgItem(id);
  46. ASSERT(pButton);
  47. pButton->SetCheck(nCheck);
  48. }
  49. // helper function -- get check status of a dialog button
  50. int CDlgHelper::GetDlgItemCheck(CDialog* pDialog, int id)
  51. {
  52. CButton* pButton = (CButton*)(pDialog->GetDlgItem(id));
  53. ASSERT(pButton);
  54. return pButton->GetCheck();
  55. }
  56. CStrArray& CStrArray::operator = (const CStrArray& sarray)
  57. {
  58. int count = GetSize();
  59. CString* pString;
  60. // remove existing members
  61. while(count --)
  62. {
  63. pString = GetAt(0);
  64. RemoveAt(0);
  65. delete pString;
  66. }
  67. // copy new
  68. count = sarray.GetSize();
  69. for(int i = 0; i < count; i++)
  70. {
  71. pString = new CString(*sarray[i]);
  72. Add(pString);
  73. }
  74. return *this;
  75. }
  76. // convert an array of CString to SAFEARRAY
  77. CStrArray::operator SAFEARRAY*()
  78. {
  79. USES_CONVERSION;
  80. int count = GetSize();
  81. if(count == 0) return NULL;
  82. SAFEARRAYBOUND bound[1];
  83. SAFEARRAY* pSA = NULL;
  84. CString* pStr = NULL;
  85. long l[2];
  86. VARIANT v;
  87. VariantInit(&v);
  88. bound[0].cElements = count;
  89. bound[0].lLbound = 0;
  90. try{
  91. // creat empty right size array
  92. pSA = SafeArrayCreate(VT_VARIANT, 1, bound);
  93. if(NULL == pSA) return NULL;
  94. // put in each element
  95. for (long i = 0; i < count; i++)
  96. {
  97. pStr = GetAt(i);
  98. V_VT(&v) = VT_BSTR;
  99. V_BSTR(&v) = T2BSTR((LPTSTR)(LPCTSTR)(*pStr));
  100. l[0] = i;
  101. SafeArrayPutElement(pSA, l, &v);
  102. VariantClear(&v);
  103. }
  104. }
  105. catch(CMemoryException&)
  106. {
  107. SafeArrayDestroy(pSA);
  108. pSA = NULL;
  109. VariantClear(&v);
  110. throw;
  111. }
  112. return pSA;
  113. }
  114. //build a StrArray from another array
  115. CStrArray::CStrArray(const CStrArray& sarray)
  116. {
  117. int count = sarray.GetSize();
  118. CString* pString = NULL;
  119. for(int i = 0; i < count; i++)
  120. {
  121. try{
  122. pString = new CString(*sarray[i]);
  123. Add(pString);
  124. }
  125. catch(CMemoryException&)
  126. {
  127. delete pString;
  128. throw;
  129. }
  130. }
  131. }
  132. //build a StrArray from a safe array
  133. CStrArray::CStrArray(SAFEARRAY* pSA)
  134. {
  135. if(pSA) AppendSA(pSA);
  136. }
  137. //remove the elements from the array and delete them
  138. int CStrArray::DeleteAll()
  139. {
  140. int ret, count;
  141. CString* pStr;
  142. ret = count = GetSize();
  143. while(count--)
  144. {
  145. pStr = GetAt(0);
  146. RemoveAt(0);
  147. delete pStr;
  148. }
  149. return ret;
  150. }
  151. CString* CStrArray::AddByRID(UINT id)
  152. {
  153. AFX_MANAGE_STATE(AfxGetStaticModuleState());
  154. CString* pStr = NULL;
  155. try
  156. {
  157. pStr = new CString();
  158. pStr->LoadString(id);
  159. Add(pStr);
  160. }
  161. catch(CMemoryException&)
  162. {
  163. delete pStr;
  164. pStr = NULL;
  165. }
  166. return pStr;
  167. }
  168. //build a StrArray from a safe array
  169. bool CStrArray::AppendSA(SAFEARRAY* pSA)
  170. {
  171. if(!pSA) return false;
  172. CString* pString = NULL;
  173. long lIter;
  174. long lBound, uBound;
  175. VARIANT v;
  176. bool bSuc = true; // ser return value to true;
  177. USES_CONVERSION;
  178. VariantInit(&v);
  179. try{
  180. SafeArrayGetLBound(pSA, 1, &lBound);
  181. SafeArrayGetUBound(pSA, 1, &uBound);
  182. for(lIter = lBound; lIter <= uBound; lIter++)
  183. {
  184. if(SUCCEEDED(SafeArrayGetElement(pSA, &lIter, &v)))
  185. {
  186. if(V_VT(&v) == VT_BSTR)
  187. {
  188. pString = new CString;
  189. (*pString) = (LPCTSTR)W2T(V_BSTR(&v));
  190. Add(pString);
  191. }
  192. }
  193. }
  194. }
  195. catch(CMemoryException&)
  196. {
  197. delete pString;
  198. VariantClear(&v);
  199. bSuc = false;
  200. throw;
  201. }
  202. return bSuc;
  203. }
  204. //build a StrArray from a safe array
  205. CStrArray::~CStrArray()
  206. {
  207. DeleteAll();
  208. }
  209. // return index if found, otherwise -1;
  210. int CStrArray::Find(const CString& Str) const
  211. {
  212. int count = GetSize();
  213. while(count--)
  214. {
  215. if(*GetAt(count) == Str) break;
  216. }
  217. return count;
  218. }
  219. //build a DWArray from another array
  220. CDWArray::CDWArray(const CDWArray& dwarray)
  221. {
  222. int count = dwarray.GetSize();
  223. for(int i = 0; i < count; i++)
  224. {
  225. try{
  226. Add(dwarray[i]);
  227. }
  228. catch(CMemoryException&)
  229. {
  230. throw;
  231. }
  232. }
  233. }
  234. // return index if found, otherwise -1;
  235. int CDWArray::Find(const DWORD dw) const
  236. {
  237. int count = GetSize();
  238. while(count--)
  239. {
  240. if(GetAt(count) == dw) break;
  241. }
  242. return count;
  243. }
  244. CDWArray& CDWArray::operator = (const CDWArray& dwarray)
  245. {
  246. int count;
  247. RemoveAll();
  248. // copy new
  249. count = dwarray.GetSize();
  250. for(int i = 0; i < count; i++)
  251. {
  252. Add(dwarray[i]);
  253. }
  254. return *this;
  255. }
  256. /////////////////////////////////////////////////////////////////////////////
  257. // CManagedPage property page
  258. IMPLEMENT_DYNCREATE(CManagedPage, CPropertyPage)
  259. BEGIN_MESSAGE_MAP(CManagedPage, CPropertyPage)
  260. //{{AFX_MSG_MAP(CManagedPage)
  261. ON_WM_HELPINFO()
  262. ON_WM_CONTEXTMENU()
  263. //}}AFX_MSG_MAP
  264. END_MESSAGE_MAP()
  265. void CManagedPage::OnContextMenu(CWnd* pWnd, CPoint point)
  266. {
  267. if (m_pHelpTable)
  268. ::WinHelp (pWnd->m_hWnd, AfxGetApp()->m_pszHelpFilePath,
  269. HELP_CONTEXTMENU, (LPARAM)(LPVOID)m_pHelpTable);
  270. }
  271. BOOL CManagedPage::OnHelpInfo(HELPINFO* pHelpInfo)
  272. {
  273. if (pHelpInfo->iContextType == HELPINFO_WINDOW && m_pHelpTable)
  274. {
  275. ::WinHelp ((HWND)pHelpInfo->hItemHandle,
  276. AfxGetApp()->m_pszHelpFilePath,
  277. HELP_WM_HELP,
  278. (LPARAM)(LPVOID)m_pHelpTable);
  279. }
  280. return TRUE;
  281. }
  282. //---------------------------------------------------------------------------
  283. // This is our self deleting callback function. If you have more than a
  284. // a few property sheets, it might be a good idea to implement this in a
  285. // base class and derive your MFC property sheets from the base class
  286. //
  287. UINT CALLBACK CManagedPage::PropSheetPageProc
  288. (
  289. HWND hWnd, // [in] Window handle - always null
  290. UINT uMsg, // [in,out] Either the create or delete message
  291. LPPROPSHEETPAGE pPsp // [in,out] Pointer to the property sheet struct
  292. )
  293. {
  294. ASSERT( NULL != pPsp );
  295. // We need to recover a pointer to the current instance. We can't just use
  296. // "this" because we are in a static function
  297. CManagedPage* pMe = reinterpret_cast<CManagedPage*>(pPsp->lParam);
  298. ASSERT( NULL != pMe );
  299. switch( uMsg )
  300. {
  301. case PSPCB_CREATE:
  302. break;
  303. case PSPCB_RELEASE:
  304. // Since we are deleting ourselves, save a callback on the stack
  305. // so we can callback the base class
  306. LPFNPSPCALLBACK pfnOrig = pMe->m_pfnOriginalCallback;
  307. delete pMe;
  308. return 1; //(pfnOrig)(hWnd, uMsg, pPsp);
  309. }
  310. // Must call the base class callback function or none of the MFC
  311. // message map stuff will work
  312. return (pMe->m_pfnOriginalCallback)(hWnd, uMsg, pPsp);
  313. } // end PropSheetPageProc()
  314. //+----------------------------------------------------------------------------
  315. //
  316. // Function: CheckADsError
  317. //
  318. // Sysnopsis: Checks the result code from an ADSI call.
  319. //
  320. // Returns: TRUE if no error.
  321. //
  322. //-----------------------------------------------------------------------------
  323. BOOL CheckADsError(HRESULT hr, BOOL fIgnoreAttrNotFound, PSTR file,
  324. int line)
  325. {
  326. if (SUCCEEDED(hr))
  327. return TRUE;
  328. if( hr == E_ADS_PROPERTY_NOT_FOUND && fIgnoreAttrNotFound)
  329. return TRUE;
  330. if (hr == HRESULT_FROM_WIN32(ERROR_EXTENDED_ERROR))
  331. {
  332. DWORD dwErr;
  333. WCHAR wszErrBuf[MAX_PATH+1];
  334. WCHAR wszNameBuf[MAX_PATH+1];
  335. ADsGetLastError(&dwErr, wszErrBuf, MAX_PATH, wszNameBuf, MAX_PATH);
  336. if ((LDAP_RETCODE)dwErr == LDAP_NO_SUCH_ATTRIBUTE && fIgnoreAttrNotFound)
  337. {
  338. return TRUE;
  339. }
  340. TRACE(_T("Extended Error 0x%x: %ws %ws (%s @line %d).\n"), dwErr,
  341. wszErrBuf, wszNameBuf, file, line);
  342. }
  343. else
  344. TRACE(_T("Error %08lx (%s @line %d)\n"), hr, file, line);
  345. return FALSE;
  346. }
  347. void DecorateName(LPWSTR outString, LPCWSTR inString)
  348. {
  349. wcscpy (outString, L"CN=");
  350. wcscat(outString, inString);
  351. }
  352. void FindNameByDN(LPWSTR outString, LPCWSTR inString)
  353. {
  354. LPWSTR p = wcsstr(inString, L"CN=");
  355. if(!p)
  356. p = wcsstr(inString, L"cn=");
  357. if(!p)
  358. wcscpy(outString, inString);
  359. else
  360. {
  361. p+=3;
  362. LPWSTR p1 = outString;
  363. while(*p == L' ') p++;
  364. while(*p != L',')
  365. *p1++ = *p++;
  366. *p1 = L'\0';
  367. }
  368. }
  369. #ifdef ___DS
  370. static CString __DSRoot;
  371. HRESULT GetDSRoot(CString& RootString)
  372. {
  373. if(__DSRoot.GetLength() == 0)
  374. {
  375. CString sADsPath;
  376. BSTR bstrDomainFolder = NULL;
  377. HRESULT hr;
  378. IADs* pDomainObject = NULL;
  379. DOMAIN_CONTROLLER_INFO *pInfo = NULL;
  380. // get the name of the Domain Controller
  381. DsGetDcName(NULL, NULL, NULL, NULL, 0, &pInfo);
  382. ASSERT(pInfo->DomainControllerName);
  383. // strip off any backslashes or slashes
  384. CString sDCName = pInfo->DomainControllerName;
  385. while(!sDCName.IsEmpty())
  386. {
  387. if ('\\' == sDCName.GetAt(0) || '/' == sDCName.GetAt(0))
  388. sDCName = sDCName.Mid(1);
  389. else
  390. break;
  391. }
  392. int index = sDCName.Find(_T('.'));
  393. if(-1 != index)
  394. sDCName = sDCName.Left(index);
  395. sADsPath = _T("LDAP://") + sDCName;
  396. // Get the DC root DS object
  397. hr = ADsGetObject(T2W((LPTSTR)(LPCTSTR)sADsPath), IID_IADs, (void**)&pDomainObject);
  398. if(FAILED(hr))
  399. return hr;
  400. // find the ADsPath of the DC root
  401. hr = pDomainObject->get_ADsPath(&bstrDomainFolder);
  402. if(FAILED(hr))
  403. return hr;
  404. pDomainObject->Release();
  405. pDomainObject = NULL;
  406. // construct the DN for the object where to put the registration information
  407. __DSRoot = W2T(bstrDomainFolder);
  408. SysFreeString(bstrDomainFolder);
  409. index = __DSRoot.ReverseFind(_T('/'));
  410. __DSRoot = __DSRoot.Mid(index + 1); // strip off the ADsPath prefix to get the X500 DN
  411. }
  412. RootString = __DSRoot;
  413. return S_OK;
  414. }
  415. #endif //___DS
  416. /////////////////////////////////////////////////////////////////////////////
  417. // Min Chars Dialog Data Validation
  418. void AFXAPI DDV_MinChars(CDataExchange* pDX, CString const& value, int nChars)
  419. {
  420. ASSERT(nChars >= 1); // allow them something
  421. if (pDX->m_bSaveAndValidate && value.GetLength() < nChars)
  422. {
  423. TCHAR szT[32];
  424. wsprintf(szT, _T("%d"), nChars);
  425. CString prompt;
  426. AfxFormatString1(prompt, IDS_MIN_CHARS, szT);
  427. AfxMessageBox(prompt, MB_ICONEXCLAMATION, IDS_MIN_CHARS);
  428. prompt.Empty(); // exception prep
  429. pDX->Fail();
  430. }
  431. }
  432. #define MAX_STRING 1024
  433. //+----------------------------------------------------------------------------
  434. //
  435. // Function: ReportError
  436. //
  437. // Sysnopsis: Attempts to get a user-friendly error message from the system.
  438. //
  439. //-----------------------------------------------------------------------------
  440. void ReportError(HRESULT hr, int nStr, HWND hWnd)
  441. {
  442. PTSTR ptzSysMsg;
  443. int cch;
  444. CString AppStr;
  445. CString SysStr;
  446. CString ErrTitle;
  447. CString ErrMsg;
  448. TRACE (_T("*+*+* ReportError called with hr = %lx"), hr);
  449. if (!hWnd)
  450. {
  451. hWnd = GetDesktopWindow();
  452. }
  453. try{
  454. if (nStr)
  455. {
  456. AppStr.LoadString(nStr);
  457. }
  458. cch = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  459. NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  460. (PTSTR)&ptzSysMsg, 0, NULL);
  461. if (!cch) { //try ads errors
  462. HMODULE adsMod;
  463. adsMod = GetModuleHandle(_T("activeds.dll"));
  464. cch = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
  465. adsMod, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  466. (PTSTR)&ptzSysMsg, 0, NULL);
  467. }
  468. if (!cch)
  469. {
  470. CString str;
  471. str.LoadString(IDS_ERR_ERRORCODE);
  472. SysStr.Format(str, hr);
  473. }
  474. else
  475. {
  476. SysStr = ptzSysMsg;
  477. LocalFree(ptzSysMsg);
  478. }
  479. ErrTitle.LoadString(IDS_ERR_TITLE);
  480. if(!AppStr.IsEmpty())
  481. {
  482. ErrMsg.Format(AppStr, (LPCTSTR)SysStr);
  483. }
  484. else
  485. {
  486. ErrMsg = SysStr;
  487. }
  488. MessageBox(hWnd, (LPCTSTR)ErrMsg, (LPCTSTR)ErrTitle, MB_OK | MB_ICONINFORMATION);
  489. }catch(CMemoryException&)
  490. {
  491. MessageBox(hWnd, _T("No enought memory, please close other applications and try again."), _T("ACS Snapin Error"), MB_OK | MB_ICONINFORMATION);
  492. }
  493. }
  494. BOOL CPageManager::OnApply()
  495. {
  496. if (!GetModified()) return FALSE;
  497. SetModified(FALSE); // prevent from doing this more than once
  498. std::list<CManagedPage*>::iterator i;
  499. for(i = m_listPages.begin(); i != m_listPages.end(); i++)
  500. {
  501. if ((*i)->GetModified())
  502. (*i)->OnApply();
  503. }
  504. return TRUE;
  505. }
  506. void CPageManager::AddPage(CManagedPage* pPage)
  507. {
  508. m_listPages.push_back(pPage);
  509. pPage->SetManager(this);
  510. }
  511. /*!--------------------------------------------------------------------------
  512. HrIsStandaloneServer
  513. Returns S_OK if the machine name passed in is a standalone server,
  514. or if pszMachineName is S_FALSE.
  515. Returns FALSE otherwise.
  516. Author: WeiJiang
  517. ---------------------------------------------------------------------------*/
  518. HRESULT HrIsStandaloneServer(LPCWSTR pMachineName)
  519. {
  520. DWORD netRet = 0;
  521. HRESULT hr = S_OK;
  522. DSROLE_PRIMARY_DOMAIN_INFO_BASIC* pdsRole = NULL;
  523. netRet = DsRoleGetPrimaryDomainInformation(pMachineName, DsRolePrimaryDomainInfoBasic, (LPBYTE*)&pdsRole);
  524. if(netRet != 0)
  525. {
  526. hr = HRESULT_FROM_WIN32(netRet);
  527. goto L_ERR;
  528. }
  529. ASSERT(pdsRole);
  530. // if the machine is not a standalone server
  531. if(pdsRole->MachineRole != DsRole_RoleStandaloneServer)
  532. {
  533. hr = S_FALSE;
  534. }
  535. L_ERR:
  536. if(pdsRole)
  537. DsRoleFreeMemory(pdsRole);
  538. return hr;
  539. }
  540. /*!--------------------------------------------------------------------------
  541. HrIsNTServer
  542. Author:
  543. ---------------------------------------------------------------------------*/
  544. HRESULT HrIsNTServer(LPCWSTR pMachineName, DWORD* pMajorVersion)
  545. {
  546. HRESULT hr = S_OK;
  547. SERVER_INFO_102* pServerInfo102 = NULL;
  548. NET_API_STATUS netRet = 0;
  549. netRet = NetServerGetInfo((LPWSTR)pMachineName, 102, (LPBYTE*)&pServerInfo102);
  550. if(netRet != 0)
  551. {
  552. hr = HRESULT_FROM_WIN32(netRet);
  553. goto L_ERR;
  554. }
  555. ASSERT(pServerInfo102);
  556. // check if the machine focused on is a standalone server
  557. //
  558. *pMajorVersion = (pServerInfo102->sv102_version_major & MAJOR_VERSION_MASK);
  559. if (!(pServerInfo102->sv102_type & SV_TYPE_SERVER_NT))
  560. {
  561. hr = S_FALSE;
  562. }
  563. L_ERR:
  564. if(pServerInfo102)
  565. NetApiBufferFree(pServerInfo102);
  566. return hr;
  567. }