Example #1
0
/******************************************************************
 RemovePortExceptionFromCurrentProfile

********************************************************************/
static HRESULT RemovePortExceptionFromCurrentProfile(
    __in int iPort,
    __in int iProtocol,
    __in BOOL fIgnoreFailures
    )
{
    HRESULT hr = S_OK;
    INetFwProfile* pfwProfile = NULL;
    INetFwOpenPorts* pfwPorts = NULL;

    // get the firewall profile, which is our entry point for adding exceptions
    hr = GetCurrentFirewallProfile(fIgnoreFailures, &pfwProfile);
    ExitOnFailure(hr, "failed to get firewall profile");
    if (S_FALSE == hr) // user or package author chose to ignore missing firewall
    {
        ExitFunction();
    }

    hr = pfwProfile->get_GloballyOpenPorts(&pfwPorts);
    ExitOnFailure(hr, "failed to get open ports");

    hr = pfwPorts->Remove(iPort, static_cast<NET_FW_IP_PROTOCOL>(iProtocol));
    ExitOnFailure2(hr, "failed to remove open port %d, protocol %d", iPort, iProtocol);

LExit:
    return fIgnoreFailures ? S_OK : hr;
}
FW_ERROR_CODE WinXPSP2FireWall::RemovePort( LONG lPortNumber, NET_FW_IP_PROTOCOL ipProtocol )
{
	FW_ERROR_CODE ret = FW_NOERROR;
	INetFwOpenPorts* pFWOpenPorts = nullptr;
	HRESULT hr;

	try
	{
		if( m_pFireWallProfile == nullptr )
			throw FW_ERR_INITIALIZED;
		BOOL bEnablePort;
		FW_ERROR_CODE nError = IsPortEnabled( lPortNumber, ipProtocol, bEnablePort);
		if( nError != FW_NOERROR)
			throw nError;

		// Only remove the port, if it is on the collection
		if( bEnablePort == TRUE )
		{
			// Retrieve the collection of globally open ports
			hr = m_pFireWallProfile->get_GloballyOpenPorts( &pFWOpenPorts );
			if( FAILED( hr ))
				throw FW_ERR_GLOBAL_OPEN_PORTS;

			hr = pFWOpenPorts->Remove( lPortNumber, ipProtocol );
			if (FAILED( hr ))
				throw FW_ERR_REMOVE_FROM_COLLECTION;
		}

	}
	catch( FW_ERROR_CODE nError)
	{
		ret = nError;
	}

	if( pFWOpenPorts )
		pFWOpenPorts->Release();

	return ret;
}