int main(int argc, char* argv[]) { IADs *pRoot=NULL; VARIANT varDSRoot; HRESULT hr; hr = CoInitialize(NULL); ///////////////////////////////////////////////////////////////////////////// // NOTE: If your client is NT 4.0 or Win 9.x without the DS Client, you // must put the server name in front of the LDAP://. For example // ADsGetObject(L"LDAP://myDC/RootDSE") // If your client is Windows 2000, you don't need to specify the servername. // The locator service in Windows 2000 will automatically locate the best DC for you ///////////////////////////////////////////////////////////////////////////////////// // Get the Directory Object on the root DSE, to get to the server configuration hr = ADsGetObject(L"LDAP://RootDSE",IID_IADs,(void**)&pRoot); if(SUCCEEDED(hr) && pRoot != NULL) { hr = pRoot->Get(L"defaultNamingContext",&varDSRoot); if(SUCCEEDED(hr)) printf("\nDefault Naming Context:%S\n",varDSRoot.bstrVal); VariantClear(&varDSRoot); hr = pRoot->Get(L"rootDomainNamingContext",&varDSRoot); if(SUCCEEDED(hr)) printf("\nRoot Domain Naming Context:%S\n",varDSRoot.bstrVal); VariantClear(&varDSRoot); hr = pRoot->Get(L"configurationNamingContext",&varDSRoot); if(SUCCEEDED(hr)) printf("\nConfiguration Naming Context :%S\n",varDSRoot.bstrVal); VariantClear(&varDSRoot); hr = pRoot->Get(L"schemaNamingContext",&varDSRoot); if(SUCCEEDED(hr)) printf("\nSchema Naming context :%S\n",varDSRoot.bstrVal); VariantClear(&varDSRoot); } if (pRoot) pRoot->Release(); CoUninitialize(); return 0; }
void StartAppPool(std::ofstream_t& oLogStream, LPCWSTR lpcwstrAppPool) { HRESULT hr; CComPtr<IISApplicationPool> spAppPool = NULL; std::wstring wsPath = L"IIS://LocalHost/W3SVC/AppPools/"; wsPath+=lpcwstrAppPool; hr = ADsGetObject(wsPath.c_str(), __uuidof(IISApplicationPool), (void**)&spAppPool); oLogStream << _T("ADsGetObject('") << wsPath.c_str() << _T("') returned ") << hr << _T(".") << std::endl; if (SUCCEEDED(hr)) { hr = spAppPool->Start(); oLogStream << _T("spAppPool->Start() '") << wsPath.c_str() << _T("' returned ") << hr << _T(".") << std::endl; } }
HRESULT CreateUserIDirectoryObject(void) { /////////////////////////////////////////////////////////// // Use IDirectoryObject to create an object //////////////////////////////////////////////////////////// HRESULT hr; IDispatch *pDisp=NULL; IDirectoryObject *pDirObject=NULL; ADSVALUE sAMValue; ADSVALUE uPNValue; ADSVALUE classValue; ADS_ATTR_INFO attrInfo[] = { { L"objectClass", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &classValue, 1 }, {L"sAMAccountName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &sAMValue, 1}, {L"userPrincipalName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &uPNValue, 1}, }; DWORD dwAttrs = sizeof(attrInfo)/sizeof(ADS_ATTR_INFO); classValue.dwType = ADSTYPE_CASE_IGNORE_STRING; classValue.CaseIgnoreString = L"user"; sAMValue.dwType=ADSTYPE_CASE_IGNORE_STRING; sAMValue.CaseIgnoreString = L"mikes"; uPNValue.dwType=ADSTYPE_CASE_IGNORE_STRING; uPNValue.CaseIgnoreString = L"*****@*****.**"; // Create this user in an organizational unit hr = ADsGetObject(L"LDAP://OU=MyOU,DC=fabrikam,DC=com", IID_IDirectoryObject, (void**) &pDirObject ); if ( SUCCEEDED(hr) ) { hr = pDirObject->CreateDSObject( L"CN=Mike Smith", attrInfo, dwAttrs, &pDisp ); if ( SUCCEEDED(hr) ) { pDisp->Release(); } pDirObject->Release(); } return hr; }
void DeleteWebApp(std::ofstream_t& oLogStream, LPCWSTR lpcwstrAppPath) { HRESULT hr; CComPtr<IADs> spADs; hr = ADsGetObject(lpcwstrAppPath, IID_IADs, (void**)&spADs); if(FAILED(hr)) { oLogStream << _T("ADsGetObject '") << lpcwstrAppPath << _T("' failed; result is: ") << hr << _T(".") << std::endl; return; } CComPtr<IISApp> spApp; hr = spADs.QueryInterface(&spApp); if(FAILED(hr)) { oLogStream << _T("QI for IISApp on '") << lpcwstrAppPath << _T("' failed; result is: ") << hr << _T(".") << std::endl; return; } hr = spApp->AppDeleteRecursive(); if(FAILED(hr)) { oLogStream << _T("AppDeleteRecursive for IISApp on '") << lpcwstrAppPath << _T("' failed; result is: ") << hr << _T(".") << std::endl; return; } hr = spApp->SetInfo(); if(FAILED(hr)) { oLogStream << _T("SetInfo for IISApp on '") << lpcwstrAppPath << _T("' failed; result is: ") << hr << _T(".") << std::endl; return; } if(SUCCEEDED(hr)) { oLogStream << _T("DeleteWebApp '") << lpcwstrAppPath << _T("' succeeded.") << std::endl; } }
int main(int argc, char* argv[]) { HRESULT hr; CoInitialize(NULL); IADsContainer *pCont=NULL; hr = ADsGetObject(L"LDAP://DC=mydomain2,DC=mydomain1,DC=microsoft,DC=com", IID_IADsContainer, (void**) &pCont ); RETURN_ON_FAILURE(hr); ///////////////////////////////////////////////////////////// // Get the child from the container // Note in the LDAP provider you can go down more than one level /////////////////////////////////////////////////////////////// IDispatch *pDisp = NULL; IADs *pADs = NULL; hr = pCont->GetObject(L"user", L"CN=Mike Smith, OU=myou1", &pDisp ); pCont->Release(); RETURN_ON_FAILURE(hr); hr = pDisp->QueryInterface( IID_IADs, (void**) &pADs ); pDisp->Release(); RETURN_ON_FAILURE(hr); // ... do something with pADs here . pADs->Release(); CoUninitialize(); return 0; }
void DeleteAppPool(std::ofstream_t& oLogStream, LPCWSTR lpcwstrAppPool) { HRESULT hr; CComPtr<IADsContainer> spADsContainer; hr = ADsGetObject(L"IIS://localhost/w3svc/AppPools", IID_IADsContainer, (void**)&spADsContainer); if(FAILED(hr)) { oLogStream << _T("ADsGetObject '") << L"IIS://localhost/w3svc/AppPools" << _T("' failed; result is: ") << hr << _T(".") << std::endl; return; } hr = spADsContainer->Delete(CComBSTR(L"IIsApplicationPool"), CComBSTR(lpcwstrAppPool)); if(FAILED(hr)) { oLogStream << _T("Delete IIsApplicationPool'") << lpcwstrAppPool << _T("' failed; result is: ") << hr << _T(".") << std::endl; return; } if(SUCCEEDED(hr)) { oLogStream << _T("DeleteAppPool '") << lpcwstrAppPool << _T("' succeeded.") << std::endl; } }
void DeleteVirtualDir(std::ofstream_t& oLogStream, LPCWSTR lpcwstrAppPath) { HRESULT hr; CComPtr<IADsContainer> spADsContainer; hr = ADsGetObject(L"IIS://localhost/w3svc/1/root", IID_IADsContainer, (void**)&spADsContainer); if(FAILED(hr)) { oLogStream << _T("ADsGetObject '") << L"IIS://localhost/w3svc/1/root" << _T("' failed; result is: ") << hr << _T(".") << std::endl; return; } hr = spADsContainer->Delete(CComBSTR(L"IIsWebVirtualDir"), CComBSTR(lpcwstrAppPath)); if(FAILED(hr)) { oLogStream << _T("Delete IIsWebVirtualDir'") << lpcwstrAppPath << _T("' failed; result is: ") << hr << _T(".") << std::endl; return; } if(SUCCEEDED(hr)) { oLogStream << _T("DeleteVirtualDir '") << lpcwstrAppPath << _T("' succeeded.") << std::endl; } }
HRESULT CreateUserIADsContainer(void) { HRESULT hr; IADsContainer *pCont = NULL; IDispatch *pDisp=NULL; IADsUser *pIADsUser=NULL; /////////////////////////////////////////////////// // Create a user using IADsContainer::Create //////////////////////////////////////////////////// hr = ADsGetObject( L"WinNT://seyitb-dev", IID_IADsContainer, (void**) &pCont ); if (FAILED(hr) ) return hr; hr = pCont->Create(L"user", L"AliceW", &pDisp ); pCont->Release(); if(FAILED(hr) ) return hr; hr = pDisp->QueryInterface( IID_IADsUser, (void**) &pIADsUser ); if (FAILED(hr)) return hr; //do NOT hard code your password into the source code in production code //take user input instead pIADsUser->SetPassword(L"MysEcret1"); hr = pIADsUser->SetInfo(); // Commit if(SUCCEEDED(hr)) wprintf(L"User created successfully\n"); pIADsUser->Release(); return hr; }
int main(int argc, char* argv[]) { HRESULT hr; IADsContainer *pCont=NULL; CoInitialize(NULL); /////////////////////////////////// // Bind to the object ///////////////////////////////// hr = ADsGetObject(L"WinNT://INDEPENDENCE", IID_IADsContainer, (void**) &pCont ); if ( !SUCCEEDED(hr) ) { return hr; } /////////////////////////////////// // Build variant filter ///////////////////////////////// LPWSTR pszFilter[] = { L"user", L"group" }; DWORD dwNumber = sizeof( pszFilter ) /sizeof(LPWSTR); VARIANT var; hr = ADsBuildVarArrayStr( pszFilter, dwNumber, &var ); if ( !SUCCEEDED(hr) ) { pCont->Release(); return hr; } /////////////////////////////////// // Set the filter ///////////////////////////////// hr = pCont->put_Filter(var); VariantClear(&var); if (!SUCCEEDED(hr) ) { pCont->Release(); return hr; } //////////////////////////////////////////// // Enumerate the result /////////////////////////////////////////////// IEnumVARIANT *pEnum = NULL; hr = ADsBuildEnumerator( pCont, &pEnum ); pCont->Release(); // no longer needed, since we have the enumerator already if ( SUCCEEDED(hr) ) { VARIANT var; ULONG lFetch; IADs *pChild=NULL; VariantInit(&var); while( SUCCEEDED(ADsEnumerateNext( pEnum, 1, &var, &lFetch )) && lFetch == 1 ) { hr = V_DISPATCH(&var)->QueryInterface( IID_IADs, (void**) &pChild ); if ( SUCCEEDED(hr) ) { BSTR bstrName; BSTR bstrClass; // Get more information on the child classes pChild->get_Name(&bstrName); pChild->get_Class(&bstrClass); printf("%S\t\t(%S)\n", bstrName, bstrClass ); // Clean-up SysFreeString(bstrName); SysFreeString(bstrClass); pChild->Release(); } VariantClear(&var); } } if ( pEnum ) { ADsFreeEnumerator( pEnum ); } CoUninitialize(); return 0; }
HRESULT ExchangeAdmin::CreateExchangeMailBox(LPCWSTR lpwstrNewUser, LPCWSTR lpwstrNewUserPwd, LPCWSTR lpwstrlogonuser, LPCWSTR lpwstrLogonUsrPwd) { HRESULT hr = S_OK; // Get Logon user DN wstring LogonUserDN; wstring legacyName; wstring msExchHomeSvrName; Zimbra::MAPI::Util::GetUserDNAndLegacyName(m_strServer.c_str(), lpwstrlogonuser, lpwstrLogonUsrPwd, LogonUserDN, legacyName); Zimbra::MAPI::Util::GetmsExchHomeServerName(m_strServer.c_str(), lpwstrlogonuser, lpwstrLogonUsrPwd, msExchHomeSvrName); Zimbra::Util::ScopedInterface<IDirectoryObject> pLogonContainer; Zimbra::Util::ScopedInterface<IADsUser> pIAdUser; Zimbra::Util::ScopedInterface<IADs> pIAds; wstring strContainer = L"LDAP://"; strContainer += LogonUserDN.c_str(); dloge("strContainer %S msExchHomeSvrName: %S", strContainer.c_str(), msExchHomeSvrName.c_str()); // Get loggedin user container hr = ADsOpenObject(strContainer.c_str(), NULL, NULL, ADS_SECURE_AUTHENTICATION, IID_IDirectoryObject, (void **)pLogonContainer.getptr()); if (FAILED(hr)) { if (hr == 0x8007052e) // credentials are not valid { hr = ADsOpenObject((LPTSTR)strContainer.c_str(), lpwstrlogonuser, lpwstrLogonUsrPwd, ADS_SECURE_AUTHENTICATION, IID_IDirectoryObject, (void **)pLogonContainer.getptr()); if (FAILED(hr)||(pLogonContainer.get()==NULL)) throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): ADsOpenObject Failed.", ERR_ADOBJECT_OPEN, __LINE__, __FILE__); } else { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsOpenObject Failed.", ERR_ADOBJECT_OPEN, __LINE__, __FILE__); } } ADS_ATTR_INFO *pAttrInfo = NULL; DWORD dwReturn; LPWSTR pAttrNames[] = { L"mail", L"homeMDB", L"homeMTA" }; DWORD dwNumAttr = sizeof (pAttrNames) / sizeof (LPWSTR); wstring strLogonHomeMDB; wstring strLogonHomeMTA; wstring strLogonMail; // Get attribute values requested. Its not necessary the order is same as requested. if (FAILED(hr = pLogonContainer->GetObjectAttributes(pAttrNames, dwNumAttr, &pAttrInfo, &dwReturn))) throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): GetObjectAttributes Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); for (DWORD idx = 0; idx < dwReturn; idx++) { if (_wcsicmp(pAttrInfo[idx].pszAttrName, L"mail") == 0) strLogonMail = pAttrInfo[idx].pADsValues->Email.Address; else if (_wcsicmp(pAttrInfo[idx].pszAttrName, L"homeMTA") == 0) strLogonHomeMTA = pAttrInfo[idx].pADsValues->DNString; else if (_wcsicmp(pAttrInfo[idx].pszAttrName, L"homeMDB") == 0) strLogonHomeMDB = pAttrInfo[idx].pADsValues->DNString; } // Use FreeADsMem for all memory obtained from the ADSI call. FreeADsMem(pAttrInfo); wstring twtsrlogonuserDN = LogonUserDN; size_t nPos = twtsrlogonuserDN.find(_T("DC="), 0); wstring wstrServerDN = twtsrlogonuserDN.substr(nPos); wstring wstrADSPath = _T("LDAP://CN=Users,") + wstrServerDN; ADSVALUE cnValue; ADSVALUE classValue; ADSVALUE sAMValue; ADSVALUE uPNValue; ADSVALUE controlValue; ADS_ATTR_INFO attrInfo[] = { { L"objectClass", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &classValue, 1 }, { L"cn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &cnValue, 1 }, { L"sAMAccountName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &sAMValue, 1 }, { L"userPrincipalName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, &uPNValue, 1 }, {L"userAccountControl", ADS_ATTR_UPDATE, ADSTYPE_INTEGER,&controlValue, 1}, }; DWORD dwAttrs = sizeof (attrInfo) / sizeof (ADS_ATTR_INFO); classValue.dwType = ADSTYPE_CASE_IGNORE_STRING; classValue.CaseIgnoreString = L"user"; //int UF_ACCOUNTDISABLE = 0x0002; int UF_PASSWD_NOTREQD = 0x0020; //int UF_PASSWD_CANT_CHANGE = 0x0040; int UF_NORMAL_ACCOUNT = 0x0200; int UF_DONT_EXPIRE_PASSWD = 0x10000; //int UF_PASSWORD_EXPIRED = 0x800000; controlValue.dwType = ADSTYPE_INTEGER; controlValue.Integer=UF_NORMAL_ACCOUNT | UF_PASSWD_NOTREQD |UF_DONT_EXPIRE_PASSWD; cnValue.dwType = ADSTYPE_CASE_IGNORE_STRING; cnValue.CaseIgnoreString = (LPWSTR)lpwstrNewUser; sAMValue.dwType = ADSTYPE_CASE_IGNORE_STRING; sAMValue.CaseIgnoreString = (LPWSTR)lpwstrNewUser; wstring wstrMail; size_t nPosMail = strLogonMail.find(_T("@"), 0); wstrMail = strLogonMail.substr(nPosMail); wstrMail = lpwstrNewUser + wstrMail; LPWSTR upnval = (LPWSTR)wstrMail.c_str(); uPNValue.dwType = ADSTYPE_CASE_IGNORE_STRING; uPNValue.CaseIgnoreString = upnval; Zimbra::Util::ScopedInterface<IDirectoryObject> pDirContainer; Zimbra::Util::ScopedInterface<IDispatch> pDisp; Zimbra::Util::ScopedInterface<IADsUser> pIADNewUser; wstring wstrLoggedUserName(LogonUserDN); size_t snPos = 0; size_t enPos = 0; if ((snPos = wstrLoggedUserName.find(L"CN=")) != wstring::npos) { if ((enPos = wstrLoggedUserName.find(L",", snPos)) != wstring::npos) wstrLoggedUserName = wstrLoggedUserName.substr(snPos + 3, (enPos - (snPos + 3))); } // get dir container if (FAILED(hr = ADsOpenObject(wstrADSPath.c_str(), wstrLoggedUserName.c_str(), lpwstrLogonUsrPwd, ADS_SECURE_AUTHENTICATION, IID_IDirectoryObject, (void **)pDirContainer.getptr()))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsOpenObject Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); wstring wstrUserCN = L"CN="; wstrUserCN += lpwstrNewUser; dloge("CreateDSObject: %S",wstrUserCN.c_str()); if (FAILED(hr = pDirContainer->CreateDSObject((LPWSTR)wstrUserCN.c_str(), attrInfo, dwAttrs, pDisp.getptr()))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): CreateDSObject Failed.", ERR_CREATE_EXCHMBX,__LINE__, __FILE__); if (FAILED(hr = pDisp->QueryInterface(IID_IADsUser, (void **)pIADNewUser.getptr()))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): QueryInterface Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); CComVariant varProp; varProp.Clear(); // set samAccount varProp = lpwstrNewUser; if (FAILED(hr = pIADNewUser->Put(CComBSTR(L"sAMAccountName"), varProp))) throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): Put(sAMAccountName) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); if(FAILED(hr = pIADNewUser->SetInfo())) throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): Put(sAMAccountName) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); // set userAccountControl varProp.Clear(); hr = pIADNewUser->Get(CComBSTR(L"userAccountControl"), &varProp); varProp = varProp.lVal & ~(ADS_UF_ACCOUNTDISABLE); if (FAILED(hr = pIADNewUser->Put(CComBSTR(L"userAccountControl"), varProp))) throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): Put(userAccountControl) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - Put(userAccountControl) Failed."); // set Account enabled if (FAILED(hr = pIADNewUser->put_AccountDisabled(VARIANT_FALSE))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): put_AccountDisabled Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - put_AccountDisabled Failed."); // set password if (FAILED(hr = pIADNewUser->SetPassword(CComBSTR(lpwstrNewUserPwd)))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): SetPassword Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - SetPassword Failed."); // user account password does not expire varProp.Clear(); VARIANT var; VariantInit(&var); if (!FAILED(hr = pIADNewUser->Get(CComBSTR(L"userAccountControl"), &var))) { V_I4(&var) |= ADS_UF_DONT_EXPIRE_PASSWD; if (FAILED(hr = pIADNewUser->Put(CComBSTR(L"userAccountControl"), var))) { throw ExchangeAdminException(hr,L"CreateExchangeMailBox(): Put(userAccountControl) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - userAccountControl Failed."); varProp.Clear(); // set the homeMDB; if (!strLogonHomeMDB.empty()) { varProp = strLogonHomeMDB.c_str(); if (FAILED(hr = pIADNewUser->Put(CComBSTR("homeMDB"), varProp))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(homeMDB) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - Put(homeMDB) Failed."); varProp.Clear(); if (!strLogonHomeMTA.empty()) { varProp = strLogonHomeMTA.c_str(); if (FAILED(hr = pIADNewUser->Put(CComBSTR("homeMTA"), varProp))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(homeMTA) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - Put(homeMTA) Failed."); varProp.Clear(); if (!msExchHomeSvrName.empty()) { varProp = msExchHomeSvrName.c_str(); if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchHomeServerName"), varProp))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(msExchHomeServerName) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - Put(msExchHomeServerName) Failed."); varProp.Clear(); varProp.Clear(); wstring newUsrLegacyName=legacyName; size_t nwpos=newUsrLegacyName.rfind(L"cn="); if(nwpos !=wstring::npos) { newUsrLegacyName = newUsrLegacyName.substr(0,nwpos); newUsrLegacyName += L"cn="; newUsrLegacyName += lpwstrNewUser; } if (!newUsrLegacyName.empty()) { varProp = newUsrLegacyName.c_str(); if (FAILED(hr = pIADNewUser->Put(CComBSTR("legacyExchangeDN"), varProp))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(legacyExchangeDN) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - Put(legacyExchangeDN) Failed."); // set nickname varProp.Clear(); varProp = lpwstrNewUser; if (FAILED(hr = pIADNewUser->Put(CComBSTR("mailNickname"), varProp))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(mailNickname) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - Put(mailNickname) Failed."); // set the displayName varProp.Clear(); varProp = lpwstrNewUser; if (FAILED(hr = pIADNewUser->Put(CComBSTR("displayName"), varProp))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(displayName) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - Put(displayName) Failed."); // set the mail atrribute varProp.Clear(); varProp = wstrMail.c_str(); if (FAILED(hr = pIADNewUser->Put(CComBSTR("mail"), varProp))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put(mail) Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - Put(mail) Failed."); // set email if (FAILED(hr = pIADNewUser->put_EmailAddress(CComBSTR(wstrMail.c_str())))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): put_EmailAddress Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - put_EmailAddress Failed."); varProp.Clear(); wstrMail=L"SMTP:"+wstrMail; varProp = wstrMail.c_str(); if (FAILED(hr = pIADNewUser->Put(CComBSTR("proxyAddresses"),varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): proxyAddressess Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - proxyAddressess Failed."); // add to Domain Admins group BSTR bstrADSPath; if (FAILED(hr = pIADNewUser->get_ADsPath(&bstrADSPath))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): get_ADsPath Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); wstring wstrGroup = _T("LDAP://CN=Domain Admins,CN=Users,") + wstrServerDN; Zimbra::Util::ScopedInterface<IADsGroup> pGroup; if (FAILED(hr = ADsGetObject(wstrGroup.c_str(), IID_IADsGroup, (void **)pGroup.getptr()))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsGetObject Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); if (FAILED(hr = ADsOpenObject(wstrGroup.c_str(), wstrLoggedUserName.c_str(), lpwstrLogonUsrPwd, ADS_SECURE_AUTHENTICATION, IID_IADsGroup, (void **)pGroup.getptr()))) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsOpenObject Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); if (SUCCEEDED(hr = pGroup->Add(bstrADSPath))) { if (FAILED(hr = pGroup->SetInfo())) throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): pGroup SetInfo Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } else { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): pGroup Add Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } GUID guid; if(FAILED(hr = CoCreateGuid(&guid))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): CoCreateGuid Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } BYTE *str; hr = UuidToString((UUID *)&guid, (RPC_WSTR *)&str); if (hr != RPC_S_OK) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): UuidToString Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } varProp.Clear(); //BYTE bytArr[]="3429bb3084703348b8023e94fabf16ea"; PutBinaryIntoVariant(&varProp,str,16); RpcStringFree((RPC_WSTR *)&str); if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchMailboxGuid"), varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put msExchMailboxGuid Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - msExchMailboxGuid Failed."); if (FAILED(hr = ADsOpenObject(strContainer.c_str(), NULL, NULL, ADS_SECURE_AUTHENTICATION, IID_IDirectoryObject, (void **)pIAdUser.getptr()))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): ADsOpenObject2 Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if (FAILED(hr = pIAdUser->QueryInterface(IID_IADs, (void**) pIAds.getptr()))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): pIAdUser->QueryInterface Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } varProp.Clear(); if( FAILED(hr= pIAds->Get(CComBSTR("msExchMailboxSecurityDescriptor"),&varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Get msExchMailboxSecurityDescriptor Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchMailboxSecurityDescriptor"), varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put msExchMailboxSecurityDescriptor Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - msExchMailboxSecurityDescriptor Failed."); varProp.Clear(); if( FAILED(hr=pIAds->Get(CComBSTR("msExchPoliciesIncluded"),&varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Get msExchPoliciesIncluded Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchPoliciesIncluded"), varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put msExchPoliciesIncluded Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - msExchPoliciesIncluded Failed."); varProp.Clear(); if( FAILED(hr= pIAds->Get(CComBSTR("msExchUserAccountControl"),&varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Get msExchUserAccountControl Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if (FAILED(hr = pIADNewUser->Put(CComBSTR("msExchUserAccountControl"), varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put msExchUserAccountControl Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - msExchUserAccountControl Failed."); varProp.Clear(); if(FAILED(hr = pIAds->GetEx(CComBSTR("showInAddressBook"), &varProp ))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Get showInAddressBook Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->Put(CComBSTR("showInAddressBook"), varProp))) { throw ExchangeAdminException(hr, L"CreateExchangeMailBox(): Put showInAddressBook Failed.", ERR_CREATE_EXCHMBX, __LINE__, __FILE__); } if(FAILED(hr = pIADNewUser->SetInfo())) ThrowSetInfoException(hr, L"SetInfo - showInAddressBook Failed."); return hr; }
/* Note: Using the UNICODE version of main(). this removes the need for the sample to include UNICODE-ANSI conversion routines */ void wmain( int argc, wchar_t *argv[ ]) { WCHAR pwszTemp[4096]; // We have now scanned PAST whitespace- so copy the string: wcscpy_s(pwszTemp,4096,L" A String"); Trim(pwszTemp); HRESULT hr; IDirectoryObject * pDirObjectContainer = NULL; IDirectoryObject * pDirObjRet = NULL; if (!ParseCommandLine(argc,argv)) return; // Initialize COM CoInitialize(0); // Bind to the container passed // If USER and PASS passed in, use ADsOpenObject() if (bsUSER) hr = ADsOpenObject(bsLDAP, bsUSER, bsPASS, ADS_SECURE_AUTHENTICATION,IID_IDirectoryObject, (void**) &pDirObjectContainer); else hr = ADsGetObject( bsLDAP, IID_IDirectoryObject,(void **)&pDirObjectContainer); if (SUCCEEDED(hr)) { // if a file is NOT passed in- Do the simple version if (!bsFILE) { // Call the helper funtion to create the User hr = CreateUser(pDirObjectContainer, bsUNAME,bsSAMNAME, &pDirObjRet); } else // file was passed in { // Call the helper funtion to create the User hr = CreateUserFromFile(pDirObjectContainer, bsUNAME,bsSAMNAME, &pDirObjRet,bsFILE); } if (SUCCEEDED(hr)) { _putws(L"\n\n New User created with the following properties:\n"); IADs * pIADsNewGoup = NULL; // User succeeded- now get an IADs interface to it // and print some properties hr = pDirObjRet->QueryInterface(IID_IADs,(void**)&pIADsNewGoup); if (SUCCEEDED(hr)) { PrintIADSObject(pIADsNewGoup); pIADsNewGoup->Release(); pIADsNewGoup = NULL; } else CheckADHRESULT(hr,L"QueryInterface() - New User for IADs"); pDirObjRet->Release(); pDirObjRet = NULL; } else CheckADHRESULT(hr,L"CreateUser()"); pDirObjectContainer->Release(); pDirObjectContainer = NULL; } else if (bsUSER) CheckADHRESULT(hr,L"ADsOpenObject()"); else CheckADHRESULT(hr,L"ADsGetObject()"); if ( bsLDAP ) ::SysFreeString(bsLDAP); if ( bsUNAME ) ::SysFreeString(bsUNAME); if ( bsSAMNAME ) ::SysFreeString(bsSAMNAME); if ( bsFILE ) ::SysFreeString(bsFILE); if ( bsUSER ) ::SysFreeString(bsUSER); if ( bsPASS ) ::SysFreeString(bsPASS); CoUninitialize(); }
BOOL RecursiveIsMember(IADsGroup * pADsGroup,LPWSTR pwszMemberGUID,LPWSTR pwszMemberPath, BOOL bVerbose, LPOLESTR pwszUser, LPOLESTR pwszPassword) { HRESULT hr = S_OK; // COM Result Code IADsMembers * pADsMembers = NULL; // Ptr to Members of the IADsGroup BOOL fContinue = TRUE; // Looping Variable IEnumVARIANT * pEnumVariant = NULL; // Ptr to the Enum variant IUnknown * pUnknown = NULL; // IUnknown for getting the ENUM initially VARIANT VariantArray[FETCH_NUM]; // Variant array for temp holding returned data ULONG ulElementsFetched = NULL; // Number of elements retrieved BSTR bsGroupPath = NULL; BOOL bRet = FALSE; if(!pADsGroup || !pwszMemberGUID || !pwszMemberPath) { return FALSE; } // Get the path of the object passed in hr = pADsGroup->get_ADsPath(&bsGroupPath); if (!SUCCEEDED(hr)) return hr; if (bVerbose) { WCHAR pwszOutput[2048]; wsprintf(pwszOutput,L"Checking the Group:\n\n%s\n\n for the member:\n\n%s\n\n",bsGroupPath,pwszMemberPath); PrintBanner(pwszOutput); } // Get an interface pointer to the IADsCollection of members hr = pADsGroup->Members(&pADsMembers); if (SUCCEEDED(hr)) { // Query the IADsCollection of members for a new ENUM Interface // Be aware that the enum comes back as an IUnknown * hr = pADsMembers->get__NewEnum(&pUnknown); if (SUCCEEDED(hr)) { // QI the IUnknown * for an IEnumVARIANT interface hr = pUnknown->QueryInterface(IID_IEnumVARIANT, (void **)&pEnumVariant); if (SUCCEEDED(hr)) { // While have not hit errors or end of data.... while (fContinue) { ulElementsFetched = 0; // Get a "batch" number of group members-number of rows specified by FETCH_NUM hr = ADsEnumerateNext(pEnumVariant, FETCH_NUM, VariantArray, &ulElementsFetched); if (ulElementsFetched ) { // Loop through the current batch-printing the path for each member. for (ULONG i = 0; i < ulElementsFetched; i++ ) { IDispatch * pDispatch = NULL; // ptr for holding dispath of element BSTR bstrCurrentPath = NULL; // Holds path of object BSTR bstrGuidCurrent = NULL; // Holds path of object IDirectoryObject * pIDOCurrent = NULL;// Holds the current object // Get the dispatch ptr for the variant pDispatch = VariantArray[i].pdispVal; // assert(HAS_BIT_STYLE(VariantArray[i].vt,VT_DISPATCH)); // Get the IADs interface for the "member" of this group hr = pDispatch->QueryInterface(IID_IDirectoryObject, (VOID **) &pIDOCurrent ) ; if (SUCCEEDED(hr)) { // Get the GUID for the current object hr = GetObjectGuid(pIDOCurrent,bstrGuidCurrent); if (FAILED(hr)) return hr; IADs * pIADsCurrent = NULL; // Retrieve the IADs Interface for the current object hr = pIDOCurrent->QueryInterface(IID_IADs,(void**)&pIADsCurrent); if (FAILED(hr)) return hr; // Get the ADsPath property for this member hr = pIADsCurrent->get_ADsPath(&bstrCurrentPath); if (SUCCEEDED(hr)) { if (bVerbose) wprintf(L"Comparing:\n\n%s\nWITH:\n%s\n\n",bstrGuidCurrent,pwszMemberGUID); // Verify that the member of this group is Equal to passed. if (_wcsicmp(bstrGuidCurrent,pwszMemberGUID)==0) { if (bVerbose) wprintf(L"!!!!!Object:\n\n%s\n\nIs a member of\n\n%s\n\n",pwszMemberPath,bstrGuidCurrent); bRet = TRUE; break; } else // Otherwise, bind to this and see if it is a group. { // If is it a group then the QI to IADsGroup succeeds IADsGroup * pIADsGroupAsMember = NULL; if (pwszUser) hr = ADsOpenObject( bstrCurrentPath, pwszUser, pwszPassword, ADS_SECURE_AUTHENTICATION, IID_IADsGroup, (void**) &pIADsGroupAsMember); else hr = ADsGetObject( bstrCurrentPath, IID_IADsGroup,(void **)&pIADsGroupAsMember); // If bind was completed, then this is a group. if (SUCCEEDED(hr)) { // Recursively call this group to verify this group. BOOL bRetRecurse; bRetRecurse = RecursiveIsMember(pIADsGroupAsMember,pwszMemberGUID,pwszMemberPath,bVerbose,pwszUser ,pwszPassword ); if (bRetRecurse) { bRet = TRUE; break; } pIADsGroupAsMember->Release(); pIADsGroupAsMember = NULL; } } SysFreeString(bstrCurrentPath); bstrCurrentPath = NULL; SysFreeString(bstrGuidCurrent); bstrGuidCurrent = NULL; } // Release pIDOCurrent->Release(); pIDOCurrent = NULL; if (pIADsCurrent) { pIADsCurrent->Release(); pIADsCurrent = NULL; } } } // Clear the variant array. memset(VariantArray, 0, sizeof(VARIANT)*FETCH_NUM); } else fContinue = FALSE; } pEnumVariant->Release(); pEnumVariant = NULL; } pUnknown->Release(); pUnknown = NULL; } pADsMembers ->Release(); pADsMembers = NULL; } // Free the group path if retrieved. if (bsGroupPath) { SysFreeString(bsGroupPath); bsGroupPath = NULL; } return bRet; }
int main(int argc, char* argv[]) { IADs *pNS = NULL, *pRoot=NULL, *pAuth=NULL; IADsOpenDSObject *pDSObj=NULL; VARIANT varDSRoot; TCHAR adspath[MAX_PATH],username[255],password[255]; HRESULT hr; hr = CoInitialize(NULL); // Get the name of the root container for this domain. // Read the Root DSE from the default DS, which will be the DS for // the local domain. This will get us the name of the schema container, // which is stored in the "defaultNamingContext" operational attribute. hr = ADsGetObject(TEXT("LDAP://RootDSE"), IID_IADs, (void**)&pRoot); if ( FAILED(hr) ) { ::CoUninitialize(); _tprintf(TEXT("\nError in ADsGetObject")); return 1; } hr = pRoot->Get(TEXT("defaultNamingContext"),&varDSRoot); if ( FAILED(hr) ) { ::CoUninitialize(); pRoot->Release(); _tprintf(TEXT("\nError in reading defaultNamingContext")); return 1; } _tprintf(TEXT("\nDomain Name is :%s\n"),varDSRoot.bstrVal); pRoot->Release(); _tcscpy_s(adspath,MAX_PATH, TEXT("LDAP://")); // get the remaining buffer size; make sure it copies, avoid buffer overrun int rem = (sizeof(adspath)/sizeof(TCHAR)) - _tcslen(adspath) -1; //-1 is for NULL int len = wcslen(varDSRoot.bstrVal); if ( rem >= len ) { _tcsncat_s(adspath,MAX_PATH,varDSRoot.bstrVal, len); } else { pRoot->Release(); VariantClear(&varDSRoot); return 1; } hr = ADsGetObject(TEXT("LDAP:"), IID_IADs, (void**)&pNS); if ( FAILED(hr) ) { ::CoUninitialize(); _tprintf(TEXT("\nError in ADsGetObject")); return 1; } hr = pNS->QueryInterface(IID_IADsOpenDSObject,(void**)&pDSObj); if ( FAILED(hr) ) { ::CoUninitialize(); pNS->Release(); _tprintf(TEXT("\nError in QueryInterface")); return 1; } // // Collect the username and password and bind to the Domain using these. // if SUCCEEDED(hr) { pNS->Release(); _tprintf(TEXT("\nusername:"******"\"%s\""), username); _tprintf(TEXT("\npassword:"******"Bind Failed"),(DWORD)hr); } else { _tprintf(TEXT("Successfully logon!")); } }
void SMTPServersNT( CCFXRequest* pRequest ) { USES_CONVERSION; #ifdef _DEBUG CString tmp; pRequest->Write("DEBUGGING: ENTRY: SMTPServersNT<br>"); #endif // fields CCFXStringSet* pColumns = pRequest->CreateStringSet(); int iServer = pColumns->AddString( "Server" ); int iState = pColumns->AddString( "State" ); int iDescription = pColumns->AddString( "Description" ); int iBindings = pColumns->AddString( "Bindings" ); int iVersion = pColumns->AddString( "Version" ); int iMessageSizeLimit = pColumns->AddString( "MessageSizeLimit" ); int iSessionSizeLimit = pColumns->AddString( "SessionSizeLimit" ); int iMessagesPerConnectionLimit = pColumns->AddString( "MessagesPerConnectionLimit" ); int iRecipientsPerMessageLimit = pColumns->AddString( "RecipientsPerMessageLimit" ); int iBadMailDirectory = pColumns->AddString( "BadMailDirectory" ); int iNonDeliveryMailTo = pColumns->AddString( "NonDeliveryMailTo" ); int iBadMailTo = pColumns->AddString( "BadMailTo" ); int iRetryInterval = pColumns->AddString( "RetryInterval" ); int iDelayNotification = pColumns->AddString( "DelayNotification" ); int iExpirationTimeout = pColumns->AddString( "ExpirationTimeout" ); int iHopCount = pColumns->AddString( "HopCount" ); int iMasqueradeDomain = pColumns->AddString( "MasqueradeDomain" ); int iFullyQualifiedDomainName = pColumns->AddString( "FullyQualifiedDomainName" ); int iSmartHost = pColumns->AddString( "SmartHost" ); int iEnableReverseDnsLookup = pColumns->AddString( "EnableReverseDnsLookup" ); CCFXQuery* pQuery = pRequest->AddQuery( get_query_variable(), pColumns ); // optional CString strinComputer = pRequest->GetAttribute( "COMPUTER" ); pRequest->SetVariable( "IISComputer", strinComputer ); CString computer; if( strinComputer.IsEmpty() ) computer="LocalHost"; else computer=strinComputer; // HRESULT hr,hr2,hrw; CString pathe; // pathe.Format("IIS://%s/SmtpSVC",computer); #ifdef _DEBUG tmp.Format("DEBUGGING: Trying container %s...<br>",pathe); pRequest->Write(tmp); #endif IADsContainer *pContainer=NULL; hr=ADsGetObject(A2W(pathe), IID_IADsContainer, (void**)&pContainer); log_COMError(__LINE__,hr); // if(SUCCEEDED(hr)) { #ifdef _DEBUG pRequest->Write("DEBUGGING: success<br>"); #endif #ifdef _DEBUG pRequest->Write("DEBUGGING: enumerating container...<br>"); #endif // IEnumVARIANT *pEnum=NULL; hrw = ADsBuildEnumerator(pContainer, &pEnum); log_COMError(__LINE__,hrw); // hr2=pContainer->Release(); log_COMError(__LINE__,hr2); // if(SUCCEEDED(hrw)) { #ifdef _DEBUG pRequest->Write("DEBUGGING: success<br>"); #endif // VARIANT var; ULONG ulElements=1; // while ( (SUCCEEDED(hrw)) && (ulElements==1) ) { #ifdef _DEBUG tmp.Format("DEBUGGING: enumerating %d elements...<br>",ulElements); pRequest->Write(tmp); #endif // hrw = ADsEnumerateNext(pEnum, 1, &var, &ulElements); log_COMError(__LINE__,hrw); // if(SUCCEEDED(hrw) && (ulElements==1) ) { #ifdef _DEBUG pRequest->Write("DEBUGGING: success<br>"); #endif // CString strServer; CString strState; CString strDescription; CString strBindings; CString strVersion; CString strMessageSizeLimit; CString strSessionSizeLimit; CString strMessagesPerConnectionLimit; CString strRecipientsPerMessageLimit; CString strBadMailDirectory; CString strNonDeliveryMailTo; CString strBadMailTo; CString strRetryInterval; CString strDelayNotification; CString strExpirationTimeout; CString strHopCount; CString strMasqueradeDomain; CString strFullyQualifiedDomainName; CString strSmartHost; CString strEnableReverseDnsLookup; // IADs *pADs=(IADs*)var.pdispVal; // BSTR bstrName; hr2 = pADs->get_Name(&bstrName); log_COMError(__LINE__,hr2); if(SUCCEEDED(hr2)) strServer=bstrName; BSTR bstrClass; hr2 = pADs->get_Class(&bstrClass); log_COMError(__LINE__,hr2); CString strClass; if(SUCCEEDED(hr2)) strClass=bstrClass; #ifdef _DEBUG tmp.Format("DEBUGGING: server %s class %s...<br>",strServer,strClass); pRequest->Write(tmp); #endif // if(strClass.Compare("IIsSmtpServer")==0) { #ifdef _DEBUG pRequest->Write("DEBUGGING: success<br>"); #endif // VARIANT var; VariantInit(&var); // hr2 = pADs->Get(L"ServerState",&var); if(SUCCEEDED(hr2)) { switch(V_INT(&var)) { case MD_SERVER_STATE_STARTING: strState="Starting"; break; case MD_SERVER_STATE_STARTED: strState="Started"; break; case MD_SERVER_STATE_STOPPING: strState="Stopping"; break; case MD_SERVER_STATE_STOPPED: strState="Stopped"; break; case MD_SERVER_STATE_PAUSING: strState="Pausing"; break; case MD_SERVER_STATE_PAUSED: strState="Paused"; break; case MD_SERVER_STATE_CONTINUING: strState="Continuing"; break; default: strState="Unknown"; } } VariantClear(&var); hr2 = pADs->Get(L"ServerComment",&var); if(SUCCEEDED(hr2)) strDescription = V_BSTR(&var) ; VariantClear(&var); hr2 = pADs->Get(L"ServerBindings",&var); if(SUCCEEDED(hr2)) { VARIANTARRAYtoCString(var,strBindings,pRequest,';'); } VariantClear(&var); hr2 = pADs->Get(L"SmtpServiceVersion",&var); if(SUCCEEDED(hr2)) strVersion.Format("%d",V_INT(&var)); VariantClear(&var); hr2 = pADs->Get(L"MaxMessageSize",&var); if(SUCCEEDED(hr2)) strMessageSizeLimit.Format("%d",V_INT(&var)); VariantClear(&var); hr2 = pADs->Get(L"MaxSessionSize",&var); if(SUCCEEDED(hr2)) strSessionSizeLimit.Format("%d",V_INT(&var)); VariantClear(&var); hr2 = pADs->Get(L"MaxBatchedMessages",&var); if(SUCCEEDED(hr2)) strMessagesPerConnectionLimit.Format("%d",V_INT(&var)); VariantClear(&var); hr2 = pADs->Get(L"MaxRecipients",&var); if(SUCCEEDED(hr2)) strRecipientsPerMessageLimit.Format("%d",V_INT(&var)); VariantClear(&var); hr2 = pADs->Get(L"BadMailDirectory",&var); if(SUCCEEDED(hr2)) strBadMailDirectory = V_BSTR(&var) ; VariantClear(&var); hr2 = pADs->Get(L"SendNdrTo",&var); if(SUCCEEDED(hr2)) strNonDeliveryMailTo = V_BSTR(&var) ; VariantClear(&var); hr2 = pADs->Get(L"SendBadTo",&var); if(SUCCEEDED(hr2)) strBadMailTo = V_BSTR(&var) ; VariantClear(&var); hr2 = pADs->Get(L"SmtpRemoteProgressiveRetry",&var); if(SUCCEEDED(hr2)) strRetryInterval = V_BSTR(&var) ; VariantClear(&var); hr2 = pADs->Get(L"SmtpLocalDelayExpireMinutes",&var); if(SUCCEEDED(hr2)) strDelayNotification.Format("%d",V_INT(&var)); VariantClear(&var); hr2 = pADs->Get(L"SmtpLocalNDRExpireMinutes",&var); if(SUCCEEDED(hr2)) strExpirationTimeout.Format("%d",V_INT(&var)); VariantClear(&var); hr2 = pADs->Get(L"HopCount",&var); if(SUCCEEDED(hr2)) strHopCount.Format("%d",V_INT(&var)); VariantClear(&var); hr2 = pADs->Get(L"MasqueradeDomain",&var); if(SUCCEEDED(hr2)) strMasqueradeDomain = V_BSTR(&var) ; VariantClear(&var); hr2 = pADs->Get(L"FullyQualifiedDomainName",&var); if(SUCCEEDED(hr2)) strFullyQualifiedDomainName = V_BSTR(&var) ; VariantClear(&var); hr2 = pADs->Get(L"SmartHost",&var); if(SUCCEEDED(hr2)) strSmartHost = V_BSTR(&var) ; VariantClear(&var); hr2 = pADs->Get(L"EnableReverseDnsLookup",&var); if(SUCCEEDED(hr2)) strEnableReverseDnsLookup.Format("%d",abs(V_BOOL(&var))); VariantClear(&var); // int iRow = pQuery->AddRow(); pQuery->SetData( iRow, iServer, strServer ); pQuery->SetData( iRow, iState, strState ); pQuery->SetData( iRow, iDescription, strDescription ); pQuery->SetData( iRow, iBindings, strBindings ); pQuery->SetData( iRow, iVersion, strVersion ); pQuery->SetData( iRow, iMessageSizeLimit, strMessageSizeLimit ); pQuery->SetData( iRow, iSessionSizeLimit, strSessionSizeLimit ); pQuery->SetData( iRow, iMessagesPerConnectionLimit, strMessagesPerConnectionLimit ); pQuery->SetData( iRow, iRecipientsPerMessageLimit, strRecipientsPerMessageLimit ); pQuery->SetData( iRow, iBadMailDirectory, strBadMailDirectory ); pQuery->SetData( iRow, iNonDeliveryMailTo, strNonDeliveryMailTo ); pQuery->SetData( iRow, iBadMailTo, strBadMailTo ); pQuery->SetData( iRow, iRetryInterval, strRetryInterval ); pQuery->SetData( iRow, iDelayNotification, strDelayNotification ); pQuery->SetData( iRow, iExpirationTimeout, strExpirationTimeout ); pQuery->SetData( iRow, iHopCount, strHopCount ); pQuery->SetData( iRow, iMasqueradeDomain, strMasqueradeDomain ); pQuery->SetData( iRow, iFullyQualifiedDomainName, strFullyQualifiedDomainName ); pQuery->SetData( iRow, iSmartHost, strSmartHost ); pQuery->SetData( iRow, iEnableReverseDnsLookup, strEnableReverseDnsLookup ); } // hr2=pADs->Release(); log_COMError(__LINE__,hr2); // SysFreeString(bstrClass); SysFreeString(bstrName); } } } // hr2 = ADsFreeEnumerator(pEnum); log_COMError(__LINE__,hr2); } #ifdef _DEBUG pRequest->Write("DEBUGGING: EXIT: SMTPServersNT<br>"); #endif }
eResult CSecRunAsUser::PrepareUser(){ CoInitialize(NULL); bool bResult = false; if (!LoadAPI()) return RES_FAILED; try{ IADsContainerPtr pUsers; try{ IADsWinNTSystemInfoPtr pNTsys; if (CoCreateInstance(CLSID_WinNTSystemInfo,NULL,CLSCTX_INPROC_SERVER,IID_IADsWinNTSystemInfo,(void**)&pNTsys) != S_OK) throw CString(_T("Failed to create IADsWinNTSystemInfo")); // check if we are already running on our eMule Account // todo: check if the current account is an administrator CComBSTR bstrUserName; pNTsys->get_UserName(&bstrUserName); m_strCurrentUser = bstrUserName; if (m_strCurrentUser == EMULEACCOUNTW){ m_bRunningAsEmule = true; throw CString(_T("Already running as eMule_Secure Account (everything is fine)")); } CComBSTR bstrCompName; pNTsys->get_ComputerName(&bstrCompName); CStringW cscompName = bstrCompName; CComBSTR bstrDomainName; pNTsys->get_DomainName(&bstrDomainName); m_strDomain = bstrDomainName; ADSPath.Format(L"WinNT://%s,computer",cscompName); if ( !SUCCEEDED(ADsGetObject(ADSPath.AllocSysString(),IID_IADsContainer,(void **)&pUsers)) ) throw CString(_T("Failed ADsGetObject()")); IEnumVARIANTPtr pEnum; ADsBuildEnumerator (pUsers,&pEnum); IADsUserPtr pChild; _variant_t vChild; while( ADsEnumerateNext (pEnum,1,&vChild,NULL) == S_OK ) { if (vChild.pdispVal->QueryInterface(IID_IADsUser,(void **)&pChild) != S_OK) continue; //If the object in the container is user then get properties CComBSTR bstrName; pChild->get_Name(&bstrName); CStringW csName= bstrName; // find the emule user account if possible if ( csName == EMULEACCOUNTW ){ // account found, set new random password and save it m_strPassword = CreateRandomPW(); if ( !SUCCEEDED(pChild->SetPassword(m_strPassword.AllocSysString())) ) throw CString(_T("Failed to set password")); bResult = true; break; } } } catch(CString error){ // clean up and abort theApp.QueueDebugLogLine(false, _T("Run as unpriveleged user: Exception while preparing user account: %s!"), error); CoUninitialize(); if (m_bRunningAsEmule) return RES_OK; else return RES_FAILED; } if (bResult || CreateEmuleUser(pUsers) ){ bResult = SetDirectoryPermissions(); } } catch(...){ // clean up and abort theApp.QueueDebugLogLine(false, _T("Run as unpriveleged user: Unexpected fatal error while preparing user account!")); CoUninitialize(); return RES_FAILED; } CoUninitialize(); FreeAPI(); if (bResult) return RES_OK_NEED_RESTART; else return RES_FAILED; }
int main(int argc, char* argv[]) { HRESULT hr; IADs *pADs=NULL; LPWSTR pszADsPath = L"LDAP://CN=Jane Johnson,OU=testOU,DC=testDom1,DC=testDom2,DC=microsoft,DC=com"; CoInitialize(NULL); /////////////////////////////////// // Modifying attributes via IADs //////////////////////////////////// hr = ADsGetObject(pszADsPath, IID_IADs, (void**) &pADs ); if (!SUCCEEDED(hr) ) { return hr; } VARIANT var; // we omit checking result for brevity.. // First Name VariantInit(&var); V_BSTR(&var) = SysAllocString(L"Janet"); V_VT(&var) = VT_BSTR; hr = pADs->Put( L"givenName", var ); // Last Name VariantClear(&var); V_BSTR(&var) = SysAllocString(L"Johns"); V_VT(&var) = VT_BSTR; hr = pADs->Put( L"sn", var ); VariantClear(&var); // Other Telephones LPWSTR pszPhones[] = { L"425 844 1234", L"425 924 4321" }; DWORD dwNumber = sizeof( pszPhones ) /sizeof(LPWSTR); hr = ADsBuildVarArrayStr( pszPhones, dwNumber, &var ); hr = pADs->Put( L"otherTelephone", var ); VariantClear(&var); hr = pADs->SetInfo(); pADs->Release(); if (!SUCCEEDED(hr) ) { return hr; } ///////////////////////////////////////////////// // Alternatively, you can use IDirectoryObject ////////////////////////////////////////////////// IDirectoryObject *pDir=NULL; hr = ADsGetObject(pszADsPath, IID_IDirectoryObject, (void**) &pDir ); if ( !SUCCEEDED(hr) ) { return hr; } DWORD dwReturn; ADSVALUE snValue; ADSVALUE fNameValue; ADSVALUE phoneValue[2]; ADS_ATTR_INFO attrInfo[] = { {L"givenName",ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING,&snValue,1}, {L"sn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING,&fNameValue,1 }, {L"otherTelephone", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, phoneValue,2 } }; DWORD dwAttrs = sizeof(attrInfo)/sizeof(ADS_ATTR_INFO); ///// First Name /////////// fNameValue.dwType=ADSTYPE_CASE_IGNORE_STRING; fNameValue.CaseIgnoreString = L"Janet"; ///// Last Name /////////// snValue.dwType= ADSTYPE_CASE_IGNORE_STRING; snValue.CaseIgnoreString = L"Johns"; ///// Other Telephone /////////// phoneValue[0].dwType = ADSTYPE_CASE_IGNORE_STRING; phoneValue[0].CaseIgnoreString = L"425 844 1234"; phoneValue[1].dwType = ADSTYPE_CASE_IGNORE_STRING; phoneValue[1].CaseIgnoreString = L"425 924 4321"; hr = pDir->SetObjectAttributes(attrInfo, dwAttrs, &dwReturn); pDir->Release(); if ( !SUCCEEDED(hr) ) { return hr; } CoUninitialize(); return 0; }
HRESULT Recursive_Memberof(IADs * pObj) { VARIANT var; long lBound, uBound; HRESULT hr; VariantInit(&var); hr = pObj->lpVtbl->Get(pObj, L "memberOf", &var); if (SUCCEEDED(hr)) { if (VT_BSTR == var.n1.n2.vt) { if (add_User_Group(var.n1.n2.n3.bstrVal)) { wchar_t *Group_Path; IADs *pGrp; Group_Path = GetLDAPPath(var.n1.n2.n3.bstrVal, GC_MODE); hr = ADsGetObject(Group_Path, &IID_IADs, (void **) &pGrp); if (SUCCEEDED(hr)) { hr = Recursive_Memberof(pGrp); pGrp->lpVtbl->Release(pGrp); safe_free(Group_Path); Group_Path = GetLDAPPath(var.n1.n2.n3.bstrVal, LDAP_MODE); hr = ADsGetObject(Group_Path, &IID_IADs, (void **) &pGrp); if (SUCCEEDED(hr)) { hr = Recursive_Memberof(pGrp); pGrp->lpVtbl->Release(pGrp); } else debug("Recursive_Memberof: ERROR ADsGetObject for %S failed: %s\n", Group_Path, Get_WIN32_ErrorMessage(hr)); } else debug("Recursive_Memberof: ERROR ADsGetObject for %S failed: %s\n", Group_Path, Get_WIN32_ErrorMessage(hr)); safe_free(Group_Path); } } else { if (SUCCEEDED(SafeArrayGetLBound(V_ARRAY(&var), 1, &lBound)) && SUCCEEDED(SafeArrayGetUBound(V_ARRAY(&var), 1, &uBound))) { VARIANT elem; while (lBound <= uBound) { hr = SafeArrayGetElement(V_ARRAY(&var), &lBound, &elem); if (SUCCEEDED(hr)) { if (add_User_Group(elem.n1.n2.n3.bstrVal)) { wchar_t *Group_Path; IADs *pGrp; Group_Path = GetLDAPPath(elem.n1.n2.n3.bstrVal, GC_MODE); hr = ADsGetObject(Group_Path, &IID_IADs, (void **) &pGrp); if (SUCCEEDED(hr)) { hr = Recursive_Memberof(pGrp); pGrp->lpVtbl->Release(pGrp); safe_free(Group_Path); Group_Path = GetLDAPPath(elem.n1.n2.n3.bstrVal, LDAP_MODE); hr = ADsGetObject(Group_Path, &IID_IADs, (void **) &pGrp); if (SUCCEEDED(hr)) { hr = Recursive_Memberof(pGrp); pGrp->lpVtbl->Release(pGrp); safe_free(Group_Path); } else debug("Recursive_Memberof: ERROR ADsGetObject for %S failed: %s\n", Group_Path, Get_WIN32_ErrorMessage(hr)); } else debug("Recursive_Memberof: ERROR ADsGetObject for %S failed: %s\n", Group_Path, Get_WIN32_ErrorMessage(hr)); safe_free(Group_Path); } VariantClear(&elem); } else { debug("Recursive_Memberof: ERROR SafeArrayGetElement failed: %s\n", Get_WIN32_ErrorMessage(hr)); VariantClear(&elem); } ++lBound; } } else debug("Recursive_Memberof: ERROR SafeArrayGetxBound failed: %s\n", Get_WIN32_ErrorMessage(hr)); } VariantClear(&var); } else { if (hr != E_ADS_PROPERTY_NOT_FOUND) debug("Recursive_Memberof: ERROR getting memberof attribute: %s\n", Get_WIN32_ErrorMessage(hr)); } return hr; }
/* returns 1 on success, 0 on failure */ int Valid_Global_Groups(char *UserName, const char **Groups) { int result = 0; int input_format = 0; WCHAR wszUser[DNLEN + UNLEN + 2]; /* Unicode user name */ char NTDomain[DNLEN + UNLEN + 2]; char *domain_qualify = NULL; char User[DNLEN + UNLEN + 2]; size_t j; wchar_t *User_DN, *User_LDAP_path, *User_PrimaryGroup; wchar_t **wszGroups, **tmp; IADs *pUser; HRESULT hr; if (Convert_UPN(UserName, NTDomain, sizeof(NTDomain)) == NULL) return result; for (j = 0; j < strlen(NTV_VALID_DOMAIN_SEPARATOR); j++) { if ((domain_qualify = strchr(NTDomain, NTV_VALID_DOMAIN_SEPARATOR[j])) != NULL) break; } if (domain_qualify == NULL) { strncpy(User, DefaultDomain, DNLEN); strcat(User, "\\"); strncat(User, UserName, UNLEN); strncpy(NTDomain, DefaultDomain, DNLEN); } else { domain_qualify[0] = '\\'; strncpy(User, NTDomain, DNLEN + UNLEN + 2); domain_qualify[0] = '\0'; } debug("Valid_Global_Groups: checking group membership of '%s'.\n", User); /* Convert ANSI User Name to Unicode */ MultiByteToWideChar(CP_ACP, 0, User, strlen(User) + 1, wszUser, sizeof(wszUser) / sizeof(wszUser[0])); /* Get CN of User */ if ((User_DN = My_NameTranslate(wszUser, ADS_NAME_TYPE_NT4, ADS_NAME_TYPE_1779)) == NULL) { debug("Valid_Global_Groups: cannot get DN for '%s'.\n", User); return result; } wszGroups = build_groups_DN_array(Groups, NTDomain); User_LDAP_path = GetLDAPPath(User_DN, GC_MODE); hr = ADsGetObject(User_LDAP_path, &IID_IADs, (void **) &pUser); if (SUCCEEDED(hr)) { wchar_t *User_PrimaryGroup_Path; IADs *pGrp; User_PrimaryGroup = Get_primaryGroup(pUser); if (User_PrimaryGroup == NULL) debug("Valid_Global_Groups: cannot get Primary Group for '%s'.\n", User); else { add_User_Group(User_PrimaryGroup); User_PrimaryGroup_Path = GetLDAPPath(User_PrimaryGroup, GC_MODE); hr = ADsGetObject(User_PrimaryGroup_Path, &IID_IADs, (void **) &pGrp); if (SUCCEEDED(hr)) { hr = Recursive_Memberof(pGrp); pGrp->lpVtbl->Release(pGrp); safe_free(User_PrimaryGroup_Path); User_PrimaryGroup_Path = GetLDAPPath(User_PrimaryGroup, LDAP_MODE); hr = ADsGetObject(User_PrimaryGroup_Path, &IID_IADs, (void **) &pGrp); if (SUCCEEDED(hr)) { hr = Recursive_Memberof(pGrp); pGrp->lpVtbl->Release(pGrp); } else debug("Valid_Global_Groups: ADsGetObject for %S failed, ERROR: %s\n", User_PrimaryGroup_Path, Get_WIN32_ErrorMessage(hr)); } else debug("Valid_Global_Groups: ADsGetObject for %S failed, ERROR: %s\n", User_PrimaryGroup_Path, Get_WIN32_ErrorMessage(hr)); safe_free(User_PrimaryGroup_Path); } hr = Recursive_Memberof(pUser); pUser->lpVtbl->Release(pUser); safe_free(User_LDAP_path); User_LDAP_path = GetLDAPPath(User_DN, LDAP_MODE); hr = ADsGetObject(User_LDAP_path, &IID_IADs, (void **) &pUser); if (SUCCEEDED(hr)) { hr = Recursive_Memberof(pUser); pUser->lpVtbl->Release(pUser); } else debug("Valid_Global_Groups: ADsGetObject for %S failed, ERROR: %s\n", User_LDAP_path, Get_WIN32_ErrorMessage(hr)); tmp = User_Groups; while (*tmp) { if (wccmparray(*tmp, wszGroups) == 0) { result = 1; break; } tmp++; } } else debug("Valid_Global_Groups: ADsGetObject for %S failed, ERROR: %s\n", User_LDAP_path, Get_WIN32_ErrorMessage(hr)); safe_free(User_DN); safe_free(User_LDAP_path); safe_free(User_PrimaryGroup); tmp = wszGroups; while (*tmp) { safe_free(*tmp); tmp++; } safe_free(wszGroups); tmp = User_Groups; while (*tmp) { safe_free(*tmp); tmp++; } safe_free(User_Groups); User_Groups_Count = 0; return result; }
static int smpd_build_spn_list() { HRESULT hr; IDirectoryObject *pSCP = NULL; ADS_ATTR_INFO *pPropEntries = NULL; IDirectorySearch *pSearch = NULL; ADS_SEARCH_HANDLE hSearch = NULL; LPWSTR pszDN; /* distinguished name of SCP. */ LPWSTR pszServiceDNSName; /* service DNS name. */ LPWSTR pszClass; /* name of service class. */ USHORT usPort; /* service port. */ WCHAR pszSearchString[SMPD_MAX_NAME_LENGTH]; char temp_str[SMPD_MAX_NAME_LENGTH]; char temp_str2[SMPD_MAX_NAME_LENGTH]; smpd_host_spn_node_t *iter; /* double t1, t2; */ static int initialized = 0; if (initialized) { return SMPD_SUCCESS; } initialized = 1; /* t1 = PMPI_Wtime(); */ CoInitialize(NULL); /* Get an IDirectorySearch pointer for the Global Catalog. */ hr = GetGCSearch(&pSearch); if (FAILED(hr) || pSearch == NULL) { smpd_err_printf("GetGC failed 0x%x\n", hr); goto Cleanup; } /* Set up a deep search. Thousands of objects are not expected in this example, therefore query for 1000 rows per page.*/ ADS_SEARCHPREF_INFO SearchPref[2]; DWORD dwPref = sizeof(SearchPref)/sizeof(ADS_SEARCHPREF_INFO); SearchPref[0].dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE; SearchPref[0].vValue.dwType = ADSTYPE_INTEGER; SearchPref[0].vValue.Integer = ADS_SCOPE_SUBTREE; SearchPref[1].dwSearchPref = ADS_SEARCHPREF_PAGESIZE; SearchPref[1].vValue.dwType = ADSTYPE_INTEGER; SearchPref[1].vValue.Integer = 1000; hr = pSearch->SetSearchPreference(SearchPref, dwPref); if (FAILED(hr)) { smpd_err_printf("Failed to set search prefs: hr:0x%x\n", hr); goto Cleanup; } /* Execute the search. From the GC get the distinguished name of the SCP. Use the DN to bind to the SCP and get the other properties. */ LPWSTR rgszDN[] = {L"distinguishedName"}; /* Search for a match of the product GUID. */ swprintf(pszSearchString, L"keywords=%s", SMPD_SERVICE_VENDOR_GUIDW); hr = pSearch->ExecuteSearch(pszSearchString, rgszDN, 1, &hSearch); /*hr = pSearch->ExecuteSearch(L"keywords=5722fe5f-cf46-4594-af7c-0997ca2e9d72", rgszDN, 1, &hSearch);*/ if (FAILED(hr)) { smpd_err_printf("ExecuteSearch failed: hr:0x%x\n", hr); goto Cleanup; } /* Loop through the results. Each row should be an instance of the service identified by the product GUID. Add logic to select from multiple service instances. */ while (SUCCEEDED(hr = pSearch->GetNextRow(hSearch))) { if (hr == S_ADS_NOMORE_ROWS) { DWORD dwError = ERROR_SUCCESS; WCHAR szError[512]; WCHAR szProvider[512]; ADsGetLastError(&dwError, szError, 512, szProvider, 512); if (ERROR_MORE_DATA == dwError) { continue; } goto Cleanup; } ADS_SEARCH_COLUMN Col; hr = pSearch->GetColumn(hSearch, L"distinguishedName", &Col); pszDN = AllocADsStr(Col.pADsValues->CaseIgnoreString); pSearch->FreeColumn(&Col); /* Bind to the DN to get the other properties. */ LPWSTR lpszLDAPPrefix = L"LDAP://"; DWORD dwSCPPathLength = (DWORD)(wcslen(lpszLDAPPrefix) + wcslen(pszDN) + 1); LPWSTR pwszSCPPath = (LPWSTR)malloc(sizeof(WCHAR) * dwSCPPathLength); if (pwszSCPPath) { wcscpy(pwszSCPPath, lpszLDAPPrefix); wcscat(pwszSCPPath, pszDN); } else { smpd_err_printf("Failed to allocate a buffer\n"); goto Cleanup; } /*wprintf(L"pszDN = %s\n", pszDN);*/ /*FreeADsStr(pszDN);*/ hr = ADsGetObject(pwszSCPPath, IID_IDirectoryObject, (void**)&pSCP); free(pwszSCPPath); if (SUCCEEDED(hr)) { /* Properties to retrieve from the SCP object. */ LPWSTR rgszAttribs[]= { {L"serviceClassName"}, {L"serviceDNSName"}, /*{L"serviceDNSNameType"},*/ {L"serviceBindingInformation"} }; DWORD dwAttrs = sizeof(rgszAttribs)/sizeof(LPWSTR); DWORD dwNumAttrGot; hr = pSCP->GetObjectAttributes(rgszAttribs, dwAttrs, &pPropEntries, &dwNumAttrGot); if (FAILED(hr)) { smpd_err_printf("GetObjectAttributes Failed. hr:0x%x\n", hr); goto Cleanup; } pszServiceDNSName = NULL; pszClass = NULL; iter = (smpd_host_spn_node_t*)malloc(sizeof(smpd_host_spn_node_t)); if (iter == NULL) { smpd_err_printf("Unable to allocate memory to store an SPN entry.\n"); goto Cleanup; } iter->next = NULL; iter->host[0] = '\0'; iter->spn[0] = '\0'; iter->dnshost[0] = '\0'; /* Loop through the entries returned by GetObjectAttributes and save the values in the appropriate buffers. */ for (int i = 0; i < (LONG)dwAttrs; i++) { if ((wcscmp(L"serviceDNSName", pPropEntries[i].pszAttrName) == 0) && (pPropEntries[i].dwADsType == ADSTYPE_CASE_IGNORE_STRING)) { pszServiceDNSName = AllocADsStr(pPropEntries[i].pADsValues->CaseIgnoreString); /*wprintf(L"pszServiceDNSName = %s\n", pszServiceDNSName);*/ } /* if ((wcscmp(L"serviceDNSNameType", pPropEntries[i].pszAttrName) == 0) && (pPropEntries[i].dwADsType == ADSTYPE_CASE_IGNORE_STRING)) { pszServiceDNSNameType = AllocADsStr(pPropEntries[i].pADsValues->CaseIgnoreString); wprintf(L"pszServiceDNSNameType = %s\n", pszServiceDNSNameType); } */ if ((wcscmp(L"serviceClassName", pPropEntries[i].pszAttrName) == 0) && (pPropEntries[i].dwADsType == ADSTYPE_CASE_IGNORE_STRING)) { pszClass = AllocADsStr(pPropEntries[i].pADsValues->CaseIgnoreString); /*wprintf(L"pszClass = %s\n", pszClass);*/ } if ((wcscmp(L"serviceBindingInformation", pPropEntries[i].pszAttrName) == 0) && (pPropEntries[i].dwADsType == ADSTYPE_CASE_IGNORE_STRING)) { usPort=(USHORT)_wtoi(pPropEntries[i].pADsValues->CaseIgnoreString); /*wprintf(L"usPort = %d\n", usPort);*/ } } wcstombs(iter->dnshost, pszServiceDNSName, SMPD_MAX_NAME_LENGTH); wcstombs(temp_str, pszClass, SMPD_MAX_NAME_LENGTH); /*MPIU_Snprintf(iter->spn, SMPD_MAX_NAME_LENGTH, "%s/%s:%d", temp_str, iter->dnshost, usPort);*/ wcstombs(temp_str2, pszDN, SMPD_MAX_NAME_LENGTH); MPIU_Snprintf(iter->spn, SMPD_MAX_NAME_LENGTH, "%s/%s/%s", temp_str, iter->dnshost, temp_str2); MPIU_Strncpy(iter->host, iter->dnshost, SMPD_MAX_NAME_LENGTH); strtok(iter->host, "."); iter->next = spn_list; spn_list = iter; if (pszServiceDNSName != NULL) { FreeADsStr(pszServiceDNSName); } if (pszClass != NULL) { FreeADsStr(pszClass); } } FreeADsStr(pszDN); } Cleanup: /* iter = spn_list; while (iter != NULL) { printf("host : %s\n", iter->host); printf("dnshost: %s\n", iter->dnshost); printf("spn : %s\n", iter->spn); iter = iter->next; } fflush(stdout); */ if (pSCP) { pSCP->Release(); pSCP = NULL; } if (pPropEntries) { FreeADsMem(pPropEntries); pPropEntries = NULL; } if (pSearch) { if (hSearch) { pSearch->CloseSearchHandle(hSearch); hSearch = NULL; } pSearch->Release(); pSearch = NULL; } CoUninitialize(); /* t2 = PMPI_Wtime(); smpd_dbg_printf("build_spn_list took %0.6f seconds\n", t2-t1); */ return SMPD_SUCCESS; }
int main(int argc, char* argv[]) { IADsContainer *pSchema=NULL; HRESULT hr; CoInitialize(NULL); hr = ADsGetObject(L"WinNT://INDEPENDENCE/Schema", IID_IADsContainer, (void**) &pSchema ); if ( !SUCCEEDED(hr) ) { return hr; } ////////////// Enumerate Schema objects /////////////////////////////////// IEnumVARIANT *pEnum = NULL; hr = ADsBuildEnumerator( pSchema, &pEnum ); pSchema->Release(); // no longer needed, since we have the enumerator already if ( SUCCEEDED(hr) ) { VARIANT var; ULONG lFetch; IADs *pChild=NULL; VariantInit(&var); while( SUCCEEDED(ADsEnumerateNext( pEnum, 1, &var, &lFetch )) && lFetch == 1 ) { hr = V_DISPATCH(&var)->QueryInterface( IID_IADs, (void**) &pChild ); if ( SUCCEEDED(hr) ) { BSTR bstrName; BSTR bstrClass; // Get more information on the child classes pChild->get_Name(&bstrName); pChild->get_Class(&bstrClass); printf("%S\t\t(%S)\n", bstrName, bstrClass ); // Clean-up SysFreeString(bstrName); SysFreeString(bstrClass); pChild->Release(); } VariantClear(&var); } } //Release the enumerator. if (pEnum != NULL) { ADsFreeEnumerator(pEnum); } CoUninitialize(); return 0; }