示例#1
1
/******************************************************************
 AddPortException

********************************************************************/
static HRESULT AddPortException(
    __in LPCWSTR wzName,
    __in int iProfile,
    __in_opt LPCWSTR wzRemoteAddresses,
    __in BOOL fIgnoreFailures,
    __in LPCWSTR wzPort,
    __in int iProtocol,
    __in LPCWSTR wzDescription
    )
{
    HRESULT hr = S_OK;
    BSTR bstrName = NULL;
    INetFwRules* pNetFwRules = NULL;
    INetFwRule* pNetFwRule = NULL;

    // convert to BSTRs to make COM happy
    bstrName = ::SysAllocString(wzName);
    ExitOnNull(bstrName, hr, E_OUTOFMEMORY, "failed SysAllocString for name");

    // get the collection of firewall rules
    hr = GetFirewallRules(fIgnoreFailures, &pNetFwRules);
    ExitOnFailure(hr, "failed to get firewall rules object");
    if (S_FALSE == hr) // user or package author chose to ignore missing firewall
    {
        ExitFunction();
    }

    // try to find it (i.e., support reinstall)
    hr = pNetFwRules->Item(bstrName, &pNetFwRule);
    if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr)
    {
        hr = CreateFwRuleObject(bstrName, iProfile, wzRemoteAddresses, wzPort, iProtocol, wzDescription, &pNetFwRule);
        ExitOnFailure(hr, "failed to create FwRule object");

        // enable it
        hr = pNetFwRule->put_Enabled(VARIANT_TRUE);
        ExitOnFailure(hr, "failed to to enable port exception");

        // add it to the list of authorized ports
        hr = pNetFwRules->Add(pNetFwRule);
        ExitOnFailure(hr, "failed to add app to the authorized ports list");
    }
    else
    {
        // we found an existing port exception (if we succeeded, that is)
        ExitOnFailure(hr, "failed trying to find existing port rule");

        // enable it (just in case it was disabled)
        pNetFwRule->put_Enabled(VARIANT_TRUE);
    }

LExit:
    ReleaseBSTR(bstrName);
    ReleaseObject(pNetFwRules);
    ReleaseObject(pNetFwRule);

    return fIgnoreFailures ? S_OK : hr;
}