Ejemplo n.º 1
0
/** Creates ECQuotaMonitor object and calls
 * ECQuotaMonitor::CheckQuota(). Entry point for this class.
 *
 * @param[in] lpVoid LPECTHREADMONITOR struct
 * @return NULL
 */
void* ECQuotaMonitor::Create(void* lpVoid)
{
	HRESULT				hr = hrSuccess;
	LPECTHREADMONITOR	lpThreadMonitor = (LPECTHREADMONITOR)lpVoid;
	ECQuotaMonitor*		lpecQuotaMonitor = NULL;

	LPMAPISESSION		lpMAPIAdminSession = NULL;
	LPMDB				lpMDBAdmin = NULL;
	time_t				tmStart = 0;
	time_t				tmEnd = 0;

	char* lpPath = lpThreadMonitor->lpConfig->GetSetting("server_socket");

	lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_INFO, "Quota monitor starting");

	//Open admin session
	hr = HrOpenECAdminSession(lpThreadMonitor->lpLogger, &lpMAPIAdminSession, "zarafa-monitor:create", PROJECT_SVN_REV_STR, lpPath, 0, lpThreadMonitor->lpConfig->GetSetting("sslkey_file","",NULL), lpThreadMonitor->lpConfig->GetSetting("sslkey_pass","",NULL));
	if (hr != hrSuccess) {
		lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to open an admin session. Error 0x%X", hr);
		goto exit;
	}

	lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_INFO, "Connection to Zarafa server succeeded");

	// Open admin store
	hr = HrOpenDefaultStore(lpMAPIAdminSession, &lpMDBAdmin);
	if (hr != hrSuccess) {
		lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to open default store for system account");
		goto exit;
	}

	lpecQuotaMonitor = new ECQuotaMonitor(lpThreadMonitor, lpMAPIAdminSession, lpMDBAdmin);

	// Release session and store (Reference on ECQuotaMonitor)
	if(lpMDBAdmin){ lpMDBAdmin->Release(); lpMDBAdmin = NULL;}
	if(lpMAPIAdminSession){ lpMAPIAdminSession->Release(); lpMAPIAdminSession = NULL;}

	// Check the quota of allstores
	tmStart = GetProcessTime();
	hr = lpecQuotaMonitor->CheckQuota();
	tmEnd = GetProcessTime();

	if(hr != hrSuccess)
		lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Quota monitor failed");
	else
		lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_INFO, "Quota monitor done in %lu seconds. Processed: %u, Failed: %u", tmEnd - tmStart, lpecQuotaMonitor->m_ulProcessed, lpecQuotaMonitor->m_ulFailed);
		
exit:
	if(lpecQuotaMonitor)
		delete lpecQuotaMonitor;

	if(lpMDBAdmin)
		lpMDBAdmin->Release();

	if(lpMAPIAdminSession)
		lpMAPIAdminSession->Release();

	return NULL;
}
Ejemplo n.º 2
0
/* Like all the other Complete methods this one is called after OnOpen
   has been called for all registered extensions.  FLAGS may have these
   values:

    0 - The open action has not been canceled.

    EEME_FAILED or EEME_COMPLETE_FAILED - both indicate that the
        open action has been canceled.  

    Note that this method may be called more than once for each OnOpen
    and may even occur without an OnOpen (i.e. while setting up a new
    extension).

    The same return values as for OnOpen may be used..
*/ 
STDMETHODIMP 
GpgolItemEvents::OnOpenComplete (LPEXCHEXTCALLBACK eecb, ULONG flags)
{
  HRESULT hr;
  
  log_debug ("%s:%s: received, flags=%#lx", SRCNAME, __func__, flags);

  /* If the message has been processed by us (i.e. in OnOpen), we now
     use our own display code.  */
  if (!flags && m_processed)
    {
      LPMDB mdb = NULL;
      LPMESSAGE message = NULL;
      HWND hwnd = NULL;

      if (FAILED (eecb->GetWindow (&hwnd)))
        hwnd = NULL;
      hr = eecb->GetObject (&mdb, (LPMAPIPROP *)&message);
      if (hr != S_OK || !message) 
        log_error ("%s:%s: error getting message: hr=%#lx",
                   SRCNAME, __func__, hr);
      else
        {
          if (message_display_handler (message, hwnd))
            m_wasencrypted = true;
        }
      if (message)
        message->Release ();
      if (mdb)
        mdb->Release ();
    }
  
  return S_FALSE;
}
Ejemplo n.º 3
0
_Check_return_ HRESULT OpenExchangeOrDefaultMessageStore(
	_In_ LPMAPISESSION lpMAPISession,
	_Deref_out_opt_ LPMDB* lppMDB)
{
	if (!lpMAPISession || !lppMDB) return MAPI_E_INVALID_PARAMETER;
	HRESULT hRes = S_OK;
	LPMDB lpMDB = NULL;
	*lppMDB = NULL;

	WC_H(OpenMessageStoreGUID(lpMAPISession, pbExchangeProviderPrimaryUserGuid, &lpMDB));
	if (FAILED(hRes) || !lpMDB)
	{
		hRes = S_OK;
		WC_H(OpenDefaultMessageStore(lpMAPISession, &lpMDB));
	}

	if (SUCCEEDED(hRes) && lpMDB)
	{
		*lppMDB = lpMDB;
	}
	else
	{
		if (lpMDB) lpMDB->Release();
		if (SUCCEEDED(hRes)) hRes = MAPI_E_CALL_FAILED;
	}
	return hRes;
} // OpenExchangeOrDefaultMessageStore
Ejemplo n.º 4
0
HRESULT RunStoreValidation(char* strHost, char* strUser, char* strPass, char *strAltUser, bool bPublic, CHECKMAP checkmap)
{
	HRESULT hr = hrSuccess;
	LPMAPISESSION lpSession = NULL;
	LPMDB lpStore = NULL;
	LPMDB lpAltStore = NULL;
	LPMDB lpReadStore = NULL;
	LPMAPIFOLDER lpRootFolder = NULL;
	LPMAPITABLE lpHierarchyTable = NULL;
	LPSRowSet lpRows = NULL;
	ULONG ulObjectType;
	ULONG ulCount;
    LPEXCHANGEMANAGESTORE lpIEMS = NULL;
    // user
    ULONG			cbUserStoreEntryID = 0;
    LPENTRYID		lpUserStoreEntryID = NULL;
	wstring strwUsername;
	wstring strwAltUsername;
	wstring strwPassword;
	std::set<std::string> setFolderIgnore;
	LPSPropValue lpAddRenProp = NULL;
	ULONG cbEntryIDSrc = 0;
	LPENTRYID lpEntryIDSrc = NULL;
	ECLogger *const lpLogger = new ECLogger_File(EC_LOGLEVEL_FATAL, 0, "-");

	hr = MAPIInitialize(NULL);
	if (hr != hrSuccess) {
		cout << "Unable to initialize session" << endl;
		goto exit;
	}

	// input from commandline is current locale
	if (strUser)
		strwUsername = convert_to<wstring>(strUser);
	if (strPass)
		strwPassword = convert_to<wstring>(strPass);
	if (strAltUser)
		strwAltUsername = convert_to<wstring>(strAltUser);

	hr = HrOpenECSession(lpLogger, &lpSession, "zarafa-fsck", PROJECT_SVN_REV_STR, strwUsername.c_str(), strwPassword.c_str(), (const char *)strHost, 0, NULL, NULL);
	lpLogger->Release();
	if(hr != hrSuccess) {
		cout << "Wrong username or password." << endl;
		goto exit;
	}
	
	if (bPublic) {
		hr = HrOpenECPublicStore(lpSession, &lpStore);
		if (hr != hrSuccess) {
			cout << "Failed to open public store." << endl;
			goto exit;
		}
	} else {
		hr = HrOpenDefaultStore(lpSession, &lpStore);
		if (hr != hrSuccess) {
			cout << "Failed to open default store." << endl;
			goto exit;
		}
	}

	if (!strwAltUsername.empty()) {
        hr = lpStore->QueryInterface(IID_IExchangeManageStore, (void **)&lpIEMS);
        if (hr != hrSuccess) {
            cout << "Cannot open ExchangeManageStore object" << endl;
            goto exit;
        }

        hr = lpIEMS->CreateStoreEntryID(L"", (LPTSTR)strwAltUsername.c_str(), MAPI_UNICODE | OPENSTORE_HOME_LOGON, &cbUserStoreEntryID, &lpUserStoreEntryID);
        if (hr != hrSuccess) {
            cout << "Cannot get user store id for user" << endl;
            goto exit;
        }

        hr = lpSession->OpenMsgStore(0, cbUserStoreEntryID, lpUserStoreEntryID, NULL, MDB_WRITE | MDB_NO_DIALOG | MDB_NO_MAIL | MDB_TEMPORARY, &lpAltStore);
        if (hr != hrSuccess) {
            cout << "Cannot open user store of user" << endl;
            goto exit;
        }
        
        lpReadStore = lpAltStore;
	} else {
	    lpReadStore = lpStore;
    }

	hr = lpReadStore->OpenEntry(0, NULL, &IID_IMAPIFolder, 0, &ulObjectType, (IUnknown **)&lpRootFolder);
	if(hr != hrSuccess) {
		cout << "Failed to open root folder." << endl;
		goto exit;
	}

	if (HrGetOneProp(lpRootFolder, PR_IPM_OL2007_ENTRYIDS /*PR_ADDITIONAL_REN_ENTRYIDS_EX*/, &lpAddRenProp) == hrSuccess &&
		Util::ExtractSuggestedContactsEntryID(lpAddRenProp, &cbEntryIDSrc, &lpEntryIDSrc) == hrSuccess) {
		setFolderIgnore.insert(string((const char*)lpEntryIDSrc, cbEntryIDSrc));
	}

	hr = lpRootFolder->GetHierarchyTable(CONVENIENT_DEPTH, &lpHierarchyTable);
	if (hr != hrSuccess) {
		cout << "Failed to open hierarchy." << endl;
		goto exit;
	}

	/*
	 * Check if we have found at least *something*.
	 */
	hr = lpHierarchyTable->GetRowCount(0, &ulCount);
	if(hr != hrSuccess) {
		cout << "Failed to count number of rows." << endl;
		goto exit;
	} else if (!ulCount) {
		cout << "No entries inside Calendar." << endl;
		goto exit;
	}

	/*
	 * Loop through each row/entry and validate.
	 */
	while (true) {
		hr = lpHierarchyTable->QueryRows(20, 0, &lpRows);
		if (hr != hrSuccess)
			break;

		if (lpRows->cRows == 0)
			break;

		for (ULONG i = 0; i < lpRows->cRows; i++)
			RunFolderValidation(setFolderIgnore, lpRootFolder, &lpRows->aRow[i], checkmap);

		if (lpRows) {
			FreeProws(lpRows);
			lpRows = NULL;
		}
	}

exit:
    if (lpUserStoreEntryID)
        MAPIFreeBuffer(lpUserStoreEntryID);

    if (lpIEMS)
        lpIEMS->Release();
        
	if (lpRows) {
		FreeProws(lpRows);
		lpRows = NULL;
	}

	if (lpEntryIDSrc)
		MAPIFreeBuffer(lpEntryIDSrc);

	if (lpAddRenProp)
		MAPIFreeBuffer(lpAddRenProp);

	if(lpHierarchyTable)
		lpHierarchyTable->Release();

	if (lpRootFolder)
		lpRootFolder->Release();

    if (lpAltStore)
        lpAltStore->Release();

	if (lpStore)
		lpStore->Release();

	if (lpSession)
		lpSession->Release();

	MAPIUninitialize();

	return hr;
}
Ejemplo n.º 5
0
/** Uses the ECServiceAdmin to get a list of all users within a
 * given company and groups those per zarafa-server instance. Per
 * server it calls ECQuotaMonitor::CheckServerQuota().
 *
 * @param[in] company lpecCompany ECCompany struct
 * @return hrSuccess or any MAPI error code.
 */
HRESULT ECQuotaMonitor::CheckCompanyQuota(LPECCOMPANY lpecCompany)
{
	HRESULT				hr = hrSuccess;
	/* Service object */
	IECServiceAdmin		*lpServiceAdmin = NULL;
	LPSPropValue		lpsObject = NULL;
	/* Userlist */
	LPECUSER			lpsUserList = NULL;
	ULONG				cUsers = 0;
	/* 2nd Server connection */
	LPMAPISESSION		lpSession = NULL;
	LPMDB				lpAdminStore = NULL;

	set<string> setServers;
	char *lpszServersConfig;
	std::set<string, stricmp_comparison> setServersConfig;
	set<string>::iterator iServers;
	char *lpszConnection = NULL;
	bool bIsPeer = false;

	m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_INFO, "Checking quota for company %s", (char*)lpecCompany->lpszCompanyname);

	/* Obtain Service object */
	hr = HrGetOneProp(m_lpMDBAdmin, PR_EC_OBJECT, &lpsObject);
	if(hr != hrSuccess) {
		m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get internal object, error code: 0x%08X", hr);
		goto exit;
	}

	hr = ((IECUnknown *)lpsObject->Value.lpszA)->QueryInterface(IID_IECServiceAdmin, (void **)&lpServiceAdmin);
	if(hr != hrSuccess) {
		m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get service admin, error code: 0x%08X", hr);
		goto exit;
	}

	/* Get userlist */
	hr = lpServiceAdmin->GetUserList(lpecCompany->sCompanyId.cb, (LPENTRYID)lpecCompany->sCompanyId.lpb, 0, &cUsers, &lpsUserList);
	if (hr != hrSuccess) {
		m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get userlist for company %s, error code 0x%08X", (LPSTR)lpecCompany->lpszCompanyname, hr);
		goto exit;
	}

	for (ULONG i = 0; i < cUsers; i++) {
		if (lpsUserList[i].lpszServername && lpsUserList[i].lpszServername[0] != '\0')
			setServers.insert((char*)lpsUserList[i].lpszServername);
	}

	if (setServers.empty()) {
		// call server function with current lpMDBAdmin / lpServiceAdmin
		
		hr = CheckServerQuota(cUsers, lpsUserList, lpecCompany, m_lpMDBAdmin);
		if (hr != hrSuccess) {
			m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to check server quota, error code 0x%08X", hr);
			goto exit;
		}

	} else {
		lpszServersConfig = m_lpThreadMonitor->lpConfig->GetSetting("servers","",NULL);
		if(lpszServersConfig) {
			// split approach taken from varafa-backup/backup.cpp
			boost::algorithm::split(setServersConfig, lpszServersConfig, boost::algorithm::is_any_of("\t "), boost::algorithm::token_compress_on);
			setServersConfig.erase(string());
		}

		for (iServers = setServers.begin(); iServers != setServers.end(); iServers++)
		{
                        if(!setServersConfig.empty() && (setServersConfig.find((*iServers).c_str()) == setServersConfig.end()))
                                continue;
 
			hr = lpServiceAdmin->ResolvePseudoUrl((char*)string("pseudo://"+ (*iServers)).c_str(), &lpszConnection, &bIsPeer);
			if (hr != hrSuccess) {
				m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to resolve servername %s, error code 0x%08X", iServers->c_str(), hr);
				m_ulFailed++;
				goto next;
			}

			m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_INFO, "Connecting to server %s using url %s", iServers->c_str(), lpszConnection);

			// call server function with new lpMDBAdmin / lpServiceAdmin
			if (bIsPeer) {
				// query interface
				hr = m_lpMDBAdmin->QueryInterface(IID_IMsgStore, (void**)&lpAdminStore);
				if (hr != hrSuccess) {
					m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get service interface again, error code 0x%08X", hr);
					m_ulFailed++;
					goto next;
				}
			} else {				
				hr = HrOpenECAdminSession(m_lpThreadMonitor->lpLogger, &lpSession, "zarafa-monitor:check-company", PROJECT_SVN_REV_STR, lpszConnection, 0, m_lpThreadMonitor->lpConfig->GetSetting("sslkey_file","",NULL), m_lpThreadMonitor->lpConfig->GetSetting("sslkey_pass","",NULL));
				if (hr != hrSuccess) {
					m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to connect to server %s, error code 0x%08X", lpszConnection, hr);
					m_ulFailed++;
					goto next;
				}

				hr = HrOpenDefaultStore(lpSession, &lpAdminStore);
				if (hr != hrSuccess) {
					m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to open admin store on server %s, error code 0x%08X", lpszConnection, hr);
					m_ulFailed++;
					goto next;
				}
			}

			hr = CheckServerQuota(cUsers, lpsUserList, lpecCompany, lpAdminStore);
			if (hr != hrSuccess) {
				m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to check quota on server %s, error code 0x%08X", lpszConnection, hr);
				m_ulFailed++;
			}

next:
			if (lpszConnection)
				MAPIFreeBuffer(lpszConnection);
			lpszConnection = NULL;

			if (lpSession)
				lpSession->Release();
			lpSession = NULL;

			if (lpAdminStore)
				lpAdminStore->Release();
			lpAdminStore = NULL;
		}
	}

exit:
	if (lpszConnection)
		MAPIFreeBuffer(lpszConnection);

	if(lpServiceAdmin)
		lpServiceAdmin->Release();

	if(lpsObject)
		MAPIFreeBuffer(lpsObject);

    if(lpsUserList)
		MAPIFreeBuffer(lpsUserList);

	return hr;
}
Ejemplo n.º 6
0
/** Gets a list of companies and checks the quota. Then it calls
 * ECQuotaMonitor::CheckCompanyQuota() to check quota of the users
 * in the company. If the server is not running in hosted mode,
 * the default company 0 will be used.
 *
 * @return hrSuccess or any MAPI error code.
 */
HRESULT ECQuotaMonitor::CheckQuota()
{
	HRESULT 			hr = hrSuccess;

	/* Service object */
	IECServiceAdmin		*lpServiceAdmin = NULL;
	LPSPropValue		lpsObject = NULL;
	IExchangeManageStore *lpIEMS = NULL;

	/* Companylist */
	LPECCOMPANY			lpsCompanyList = NULL;
	LPECCOMPANY			lpsCompanyListAlloc = NULL;
	ECCOMPANY			sRootCompany = {{g_cbSystemEid, g_lpSystemEid}, (LPTSTR)"Default", NULL, {0, NULL}};
    ULONG				cCompanies = 0;

	/* Company store */
	LPMDB				lpMsgStore = NULL;

	/* Quota information */
	LPECQUOTA			lpsQuota = NULL;
	LPECQUOTASTATUS		lpsQuotaStatus = NULL;

	/* Obtain Service object */
	hr = HrGetOneProp(m_lpMDBAdmin, PR_EC_OBJECT, &lpsObject);
	if(hr != hrSuccess) {
		m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get internal object, error code: 0x%08X", hr);
		goto exit;
	}

	hr = ((IECUnknown *)lpsObject->Value.lpszA)->QueryInterface(IID_IECServiceAdmin, (void **)&lpServiceAdmin);
	if(hr != hrSuccess) {
		m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get service admin, error code: 0x%08X", hr);
		goto exit;
	}

	/* Get companylist */
	hr = lpServiceAdmin->GetCompanyList(0, &cCompanies, &lpsCompanyListAlloc);
	if (hr == MAPI_E_NO_SUPPORT) {
		lpsCompanyList = &sRootCompany;
		cCompanies = 1;
		hr = hrSuccess;
	} else if (hr != hrSuccess) {
		m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get companylist, error code 0x%08X", hr);
		goto exit;
	} else
		lpsCompanyList = lpsCompanyListAlloc;

	hr = m_lpMDBAdmin->QueryInterface(IID_IExchangeManageStore, (void **)&lpIEMS);
	if (hr != hrSuccess) {
		m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get admin interface, error code 0x%08X", hr);
		goto exit;
	}

	for (ULONG i = 0; i < cCompanies; i++) {
		/* Check company quota for non-default company */
		if (lpsCompanyList[i].sCompanyId.cb != 0 && lpsCompanyList[i].sCompanyId.lpb != NULL) {
			m_ulProcessed++;
		
			hr = lpServiceAdmin->GetQuota(lpsCompanyList[i].sCompanyId.cb, (LPENTRYID)lpsCompanyList[i].sCompanyId.lpb, false, &lpsQuota);
			if (hr != hrSuccess) {
				m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get quota information for company %s, error code: 0x%08X", (LPSTR)lpsCompanyList[i].lpszCompanyname, hr);
				hr = hrSuccess;
				m_ulFailed++;
				goto check_stores;
			}

			hr = OpenUserStore(lpsCompanyList[i].lpszCompanyname, &lpMsgStore);
			if (hr != hrSuccess) {
				hr = hrSuccess;
				m_ulFailed++;
				goto check_stores;
			}

			hr = Util::HrGetQuotaStatus(lpMsgStore, lpsQuota, &lpsQuotaStatus);
			if (hr != hrSuccess) {
				m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Unable to get quotastatus for company %s, error code: 0x%08X", (LPSTR)lpsCompanyList[i].lpszCompanyname, hr);
				hr = hrSuccess;
				m_ulFailed++;
				goto check_stores;
			}

			if (lpsQuotaStatus->quotaStatus != QUOTA_OK) {
				m_lpThreadMonitor->lpLogger->Log(EC_LOGLEVEL_FATAL, "Storage size of company %s has exceeded one or more size limits", (LPSTR)lpsCompanyList[i].lpszCompanyname);
				Notify(NULL, &lpsCompanyList[i], lpsQuotaStatus, lpMsgStore);
			}
		}

check_stores:
		/* Whatever the status of the company quota, we should also check the quota of the users */
		CheckCompanyQuota(&lpsCompanyList[i]);

		if (lpsQuotaStatus) {
			MAPIFreeBuffer(lpsQuotaStatus);
			lpsQuotaStatus = NULL;
		}

		if (lpMsgStore) {
			lpMsgStore->Release();
			lpMsgStore = NULL;
		}

		if (lpsQuota) {
			MAPIFreeBuffer(lpsQuota);
			lpsQuota = NULL;
		}
	}

exit:
	if (lpIEMS)
		lpIEMS->Release();

	if (lpServiceAdmin)
		lpServiceAdmin->Release();

	if (lpsObject)
		MAPIFreeBuffer(lpsObject);

	if (lpsCompanyListAlloc)
		 MAPIFreeBuffer(lpsCompanyListAlloc);

	if (lpsQuotaStatus)
		MAPIFreeBuffer(lpsQuotaStatus);

	if (lpMsgStore) 
		lpMsgStore->Release();

	if (lpsQuota) 
		MAPIFreeBuffer(lpsQuota);

	return hr;
}
/// <summary>
/// <para name='Name'>GetEID</para>
/// <para name='Purpose'>Resolve the EID from the email address</para>
/// </summary>
/// <param name='szEmailAddress'>Email address to resolve</param>
/// <param name='sbEID'>[out]SBinary EID to return</param>
/// <returns>HRESULT</returns>
/// <remarks>
/// <para name='Notes'></para>
/// <para name='Author'>Kenn Guilstorf</para>
/// <para name='LastModified'>28Jan2016</para>
/// </remarks>
STDMETHODIMP ZybraxiSoft::CMailbox::GetEID(const TSTRING sEmailAddress, SBinary &sbEID)
{
	FBEG;
	HRESULT hr = S_OK;
	LPMDB lpDefaultMDB = NULL;
	LPEXCHANGEMANAGESTORE lpExStore = NULL;
	TSTRING sServerName;
	TSTRING sServerPre = TSTRING(SERVER_PRE);
	TSTRING sServerPost = TSTRING(SERVER_POST);
	TSTRING sServerDN = wstring();
	std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
	string sTempEmailAddress;
	string sTempServerDN;


	// Clean our sbEID
	sbEID.cb = 0;

	// Get a pointer to the default message store
	if (FAILED(hr = OpenDefaultMessageStore(
		&lpDefaultMDB)))
	{
		ERROR_MSG_W_HR("OpenDefaultMessageStore failed", hr);
		goto CLEANUP;
	}

	// Use the pointer to the default message store to
	// Get a pointer to the Manage Store interface
	if (FAILED(hr = lpDefaultMDB->QueryInterface(
		IID_IExchangeManageStore,
		(LPVOID*)&lpExStore)))
	{
		ERROR_MSG_W_HR("Getting the Exchange store manager failed", hr);
		goto CLEANUP;
	}

	// Get our Server Name
	if (FAILED(hr = this->GetServerNameFromProfile(sServerName)))
	{
		ERROR_MSG_W_HR("Getting the server name failed", hr);
		goto CLEANUP;
	}

	// Go ahead and build our server dn
	sServerDN.append(sServerPre.c_str());
	sServerDN.append(sServerName.c_str());
	sServerDN.append(sServerPost.c_str());

	// if we're in UNICODE, we need to convert; we can only pass ASCII
#if defined(UNICODE) || defined(_UNICODE)
	sTempServerDN = converter.to_bytes(sServerDN);
	sTempEmailAddress = converter.to_bytes(sEmailAddress);
#else
	sTempServerDN = sServerDN;
	sTempEmailAddress = sEmailAddress;
#endif

	// Get the EID
	if (FAILED(hr = lpExStore->CreateStoreEntryID(
		(LPSTR)sTempServerDN.c_str(),
		(LPSTR)sTempEmailAddress.c_str(),
		OPENSTORE_TAKE_OWNERSHIP,
		&sbEID.cb,
		(LPENTRYID*)&sbEID.lpb)))
	{
		ERROR_MSG_W_HR("CreateStoreEntryID failed", hr);
		goto CLEANUP;
	}

	// Check to make sure we got an actual EID
	if (sbEID.cb == 0)
	{
		hr = MAPI_E_NOT_FOUND;
		ERROR_MSG_W_HR("Failed to resolve the mailbox", hr);
		goto CLEANUP;
	}
	
CLEANUP:
	if (lpExStore)
	{
		lpExStore->Release();
		lpExStore = NULL;
	}

	if (lpDefaultMDB)
	{
		lpDefaultMDB->Release();
		lpDefaultMDB = NULL;
	}

	FEND;
	return hr;
}
Ejemplo n.º 8
0
void Test(){
	
	HRESULT hr = 0;
	LPMAPISESSION lpMapiSession = NULL;
	LPMDB lpMdb = NULL;
	IMAPITable* pIStoreTable = NULL;
	LPSRowSet pRows = NULL;
	IUnknown* lpExchManageStroe = NULL;
	SPropValue*	pAllFoldersPropValue = NULL;
	
	do{
		MAPIINIT_0 mapiInit = { 0, MAPI_MULTITHREAD_NOTIFICATIONS };
		hr = MAPIInitialize(&mapiInit);

		DEFINE_IF_HR_NT_OK_BREAK(hr);
		//L"Outlook"
		hr = MAPILogonEx(0, NULL , NULL, MAPI_NEW_SESSION | MAPI_USE_DEFAULT | MAPI_EXTENDED, &lpMapiSession);
		
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		enum{ PR_DEFAULT_STORE_, PR_ENTRYID_, PR_RESOURCE_FLAGS_, PR_MDB_PROVIDER_, PR_DISPLAY_NAME_, COUNT };
		SizedSPropTagArray(COUNT, storeEntryID) = { COUNT, { PR_DEFAULT_STORE, PR_ENTRYID, PR_RESOURCE_FLAGS, PR_MDB_PROVIDER, PR_DISPLAY_NAME} };
		
		ULONG ulRowCount = 0;
		
		ULONG ulRowIndex = 0;
		BOOL bFind = FALSE;
		hr = lpMapiSession->GetMsgStoresTable(0, &pIStoreTable);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		hr = pIStoreTable->SetColumns((LPSPropTagArray)&storeEntryID, 0);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		hr = pIStoreTable->GetRowCount(0, &ulRowCount);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		hr = pIStoreTable->QueryRows(ulRowCount, 0, &pRows);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		ulRowIndex = 0;
		while (ulRowIndex<pRows->cRows)
		{
			_SRow row = pRows->aRow[ulRowIndex];
			if (row.lpProps[PR_DEFAULT_STORE_].Value.b == TRUE && (row.lpProps[PR_RESOURCE_FLAGS_].Value.ul & STATUS_DEFAULT_STORE) )
			{
				bFind = TRUE;
				break;
			}

			ulRowIndex++;
		}

		if (bFind)
		{
			hr = lpMapiSession->OpenMsgStore(0, pRows->aRow[ulRowIndex].lpProps[PR_ENTRYID_].Value.bin.cb,
				(ENTRYID*)pRows->aRow[ulRowIndex].lpProps[PR_ENTRYID_].Value.bin.lpb, NULL,
				MDB_WRITE | MAPI_BEST_ACCESS | MDB_NO_DIALOG, (IMsgStore**)&lpMdb);
			DEFINE_IF_HR_NT_OK_BREAK(hr);
		}
		else {
			break;
		}
		
		enum { PR_IPM_OUTBOX_ENTRYID_, PR_VALID_FOLDER_MASK_, COUNT_ };
		SizedSPropTagArray(COUNT_, rgPropTag) = { COUNT_, { PR_IPM_OUTBOX_ENTRYID, PR_VALID_FOLDER_MASK } };
		
		ULONG ulValues = 0;
		hr = lpMdb->GetProps((LPSPropTagArray)&rgPropTag, 0, &ulValues, &pAllFoldersPropValue);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		ULONG lpObjType = 0;
		IMAPIFolder* lpMapiFolder = NULL;
		if (pAllFoldersPropValue[PR_VALID_FOLDER_MASK_].Value.ul & FOLDER_IPM_OUTBOX_VALID){
			hr = lpMdb->OpenEntry(pAllFoldersPropValue[PR_IPM_OUTBOX_ENTRYID_].Value.bin.cb, (ENTRYID*)pAllFoldersPropValue[PR_IPM_OUTBOX_ENTRYID_].Value.bin.lpb,
				NULL, MAPI_BEST_ACCESS | MAPI_MODIFY, &lpObjType, (IUnknown**)&lpMapiFolder);
			DEFINE_IF_HR_NT_OK_BREAK(hr);
		}

		hr = AddMailW(lpMapiSession, lpMapiFolder, L"ceshi测试12", L"lhy测试12", L"*****@*****.**", false, false, true, false);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

	} while (0);

	DWORD dError = GetLastError();

	if (pAllFoldersPropValue){
		MAPIFREEBUFFER(pAllFoldersPropValue);
	}

	if (lpExchManageStroe)
	{
		lpExchManageStroe->Release();
		lpExchManageStroe = NULL;
	}

	if (lpMdb)
	{
		ULONG ulLogOffTag = LOGOFF_NO_WAIT;
		lpMdb->StoreLogoff(&ulLogOffTag);
		lpMdb->Release();
		lpMdb = NULL;
	}

	if (pRows)
	{
		FreeProws(pRows);
		pRows = NULL;
	}

	if (pIStoreTable)
	{
		pIStoreTable->Release();
		pIStoreTable = NULL;
	}

	if (lpMapiSession){
		lpMapiSession->Logoff(0, 0, 0);
		lpMapiSession->Release();
		lpMapiSession = NULL;
	}

	MAPIUninitialize();
}