/*++

Module Name:

    driver.c

Abstract:

    This file contains the driver entry points and callbacks.

Environment:

    Kernel-mode Driver Framework

--*/

#include "precomp.h"
#include "driver.h"
#include "driver.tmh"

#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#pragma alloc_text (PAGE, dnsfirewallDeviceAdd)
#pragma alloc_text (PAGE, dnsfirewallEvtDriverContextCleanup)
#pragma alloc_text (PAGE, dnsfirewallEvtDriverUnload)
#endif


NTSTATUS
DriverEntry(
    _In_ PDRIVER_OBJECT  DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    )
/*++

Routine Description:
    DriverEntry initializes the driver and is the first routine called by the
    system after the driver is loaded. DriverEntry specifies the other entry
    points in the function driver, such as EvtDevice and DriverUnload.

Parameters Description:

    DriverObject - represents the instance of the function driver that is loaded
    into memory. DriverEntry must initialize members of DriverObject before it
    returns to the caller. DriverObject is allocated by the system before the
    driver is loaded, and it is released by the system after the system unloads
    the function driver from memory.

    RegistryPath - represents the driver specific path in the Registry.
    The function driver can use the path to store driver related data between
    reboots. The path does not store hardware instance specific data.

Return Value:

    STATUS_SUCCESS if successful,
    STATUS_UNSUCCESSFUL otherwise.

--*/
{
    WDF_DRIVER_CONFIG       config;
    NTSTATUS                status;
    WDF_OBJECT_ATTRIBUTES   attributes;
    PWDFDEVICE_INIT         pInit = NULL;
    WDFDRIVER               hDriver;
    PDEVICE_OBJECT          pDeviceObject = NULL;
    NET_BUFFER_LIST_POOL_PARAMETERS nblPoolParams = { 0 };
    NET_BUFFER_POOL_PARAMETERS      nbPoolParams = { 0 };
    //
    // Initialize WPP Tracing
    //
    WPP_INIT_TRACING( DriverObject, RegistryPath );
    TraceEvents(
        TRACE_LEVEL_INFORMATION,
        TRACE_DRIVER,
        "%!FUNC! line:%!LINE! %!LEVEL! Entry"
        );
    //
    // Register a cleanup callback so that we can call WPP_CLEANUP when
    // the framework driver object is deleted during driver unload.
    //
    WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
    attributes.EvtCleanupCallback = dnsfirewallEvtDriverContextCleanup;
    WDF_DRIVER_CONFIG_INIT(
        &config,
        WDF_NO_EVENT_CALLBACK // This is a non-pnp driver. dnsfirewallDeviceAdd
        );
    //
    // Tell the framework that this is non-pnp driver so that it doesn't
    // set the default AddDevice routine.
    //
    config.DriverInitFlags |= WdfDriverInitNonPnpDriver;
    //
    // NonPnp driver must explicitly register an unload routine for
    // the driver to be unloaded.
    //
    config.EvtDriverUnload = dnsfirewallEvtDriverUnload;
    //
    // Create a framework driver object to represent our driver.
    //
    status = WdfDriverCreate(
        DriverObject,
        RegistryPath,
        &attributes,
        &config,
        &hDriver
        );

    if (!NT_SUCCESS(status))
    {
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "WdfDriverCreate failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    //
    //
    // In order to create a control device, we first need to allocate a
    // WDFDEVICE_INIT structure and set all properties.
    //
    pInit = WdfControlDeviceInitAllocate(
        hDriver,
        &SDDL_DEVOBJ_SYS_ALL_ADM_RWX_WORLD_RW_RES_R
        );
    if (pInit == NULL)
    {
        status = STATUS_INSUFFICIENT_RESOURCES;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! line:%!LINE! %!LEVEL! WdfControlDeviceInitAllocate failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    //
    // Call dnsfirewallDeviceAdd to create a deviceobject to represent our
    // software device.
    //
    status = dnsfirewallDeviceAdd(hDriver, pInit);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! line:%!LINE! %!LEVEL! dnsfirewallDeviceAdd failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    pDeviceObject = WdfDeviceWdmGetDeviceObject(g_wdfControlDevice);
    g_pNdisGenericObj = NdisAllocateGenericObject(
        DriverObject,
        POOL_TAG,
        0
        );
    if (NULL == g_pNdisGenericObj)
    {
        status = STATUS_NO_MEMORY;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! line:%!LINE! %!LEVEL! NdisAllocateGenericObject failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    nblPoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
    nblPoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
    nblPoolParams.Header.Size = NDIS_SIZEOF_NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
    nblPoolParams.fAllocateNetBuffer = TRUE;
    nblPoolParams.DataSize = 0;
    nblPoolParams.PoolTag = POOL_TAG;
    g_hNetBufferListPool = NdisAllocateNetBufferListPool(
        g_pNdisGenericObj,
        &nblPoolParams
        );
    if (NULL == g_hNetBufferListPool)
    {
        status = STATUS_NO_MEMORY;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! line:%!LINE! %!LEVEL! NdisAllocateNetBufferListPool failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    nbPoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
    nbPoolParams.Header.Revision = NET_BUFFER_POOL_PARAMETERS_REVISION_1;
    nbPoolParams.Header.Size = NDIS_SIZEOF_NET_BUFFER_POOL_PARAMETERS_REVISION_1;
    nbPoolParams.DataSize = 0;
    nbPoolParams.PoolTag = POOL_TAG;
    g_hNetBufferPool = NdisAllocateNetBufferPool(
        g_pNdisGenericObj,
        &nbPoolParams
        );
    if (NULL == g_hNetBufferPool)
    {
        status = STATUS_NO_MEMORY;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! line:%!LINE! %!LEVEL! NdisAllocateNetBufferPool failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    status = dnsfirewallCoInitialize(pDeviceObject);
    if (!NT_SUCCESS(status))
    {
        status = STATUS_NO_MEMORY;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! line:%!LINE! %!LEVEL! dnsfirewallCoInitialize failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    TraceEvents(
        TRACE_LEVEL_INFORMATION,
        TRACE_DRIVER,
        "%!FUNC! line:%!LINE! %!LEVEL! Exit"
        );
    return status;
}

NTSTATUS
dnsfirewallDeviceAdd(
    _In_    WDFDRIVER       Driver,
    _Inout_ PWDFDEVICE_INIT DeviceInit
    )
/*++
Routine Description:

    EvtDeviceAdd is called by the framework in response to AddDevice
    call from the PnP manager. We create and initialize a device object to
    represent a new instance of the device.

Arguments:

    Driver - Handle to a framework driver object created in DriverEntry

    DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure.

Return Value:

    NTSTATUS

--*/
{
    NTSTATUS status;
    UNREFERENCED_PARAMETER(Driver);
    PAGED_CODE();
    TraceEvents(
        TRACE_LEVEL_INFORMATION,
        TRACE_DRIVER,
        "%!FUNC! line:%!LINE! %!LEVEL! Entry"
        );
    status = dnsfirewallCreateDevice(DeviceInit);
    TraceEvents(
        TRACE_LEVEL_INFORMATION,
        TRACE_DRIVER,
        "%!FUNC! line:%!LINE! %!LEVEL! Exit"
        );
    return status;
}

VOID
dnsfirewallEvtDriverContextCleanup(
    _In_ WDFOBJECT DriverObject
    )
{
    UNREFERENCED_PARAMETER(DriverObject);
    PAGED_CODE ();
    TraceEvents(
        TRACE_LEVEL_INFORMATION,
        TRACE_DRIVER,
        "%!FUNC! line:%!LINE! %!LEVEL! Enter"
        );
    //
    // Stop WPP Tracing
    //
    WPP_CLEANUP( WdfDriverWdmGetDriverObject(DriverObject) );

}

VOID dnsfirewallEvtDriverUnload(
    __in  WDFDRIVER Driver
    )
{
    BOOLEAN                 bSignalWorkerThread;
    PADDRESSES_DESCRIPTOR   pDeviceAddressesDescriptor = NULL;
    NTSTATUS                status = STATUS_SUCCESS;
    UNREFERENCED_PARAMETER(Driver);
    PAGED_CODE();
    TraceEvents(
        TRACE_LEVEL_INFORMATION,
        TRACE_DRIVER,
        "%!FUNC! line:%!LINE! %!LEVEL! Enter"
        );
    WdfObjectAcquireLock(g_wdfControlDevice);
    if (!g_bDriverUnload)
    {
        bSignalWorkerThread = IsListEmpty(&g_stPendedPacketsQueue);
        g_bDriverUnload = TRUE;
        WdfObjectReleaseLock(g_wdfControlDevice);
        if (bSignalWorkerThread)
        {
            KeSetEvent(
                &g_oWorkerEvent,
                0,
                FALSE
                );
        }
        KeWaitForSingleObject(
            &g_oWorkerDoneEvent,
            Executive,
            KernelMode,
            FALSE,
            NULL
            );
        WdfObjectAcquireLock(g_wdfControlDevice);
    }
    if ((!IsListEmpty(&g_stFlowedFileList))
        || (!IsListEmpty(&g_stUdpALEFlowEstablishList))
        || (!IsListEmpty(&g_stUdpALEAcceptPendedList))
        || (!IsListEmpty(&g_stUdpALEAcceptRecvList))
        || (!IsListEmpty(&g_stUdpAcceptNotifyList))
        || (!IsListEmpty(&g_stUdpInboundList))
        || (!IsListEmpty(&g_stAcceptableList))
        || (!IsListEmpty(&g_stWaitForSetFilterFileList))
        || (!IsListEmpty(&g_stWaitForQuery2FileList))
        || (!IsListEmpty(&g_stWaitForDoneFileList)))
    {
        TraceEvents(
            TRACE_LEVEL_WARNING,
            TRACE_DRIVER,
            "%!FUNC! line:%!LINE! %!LEVEL! DNSFIREWALL Filters files not Cleared"
            );
        g_bFiltersChangeInProgress = TRUE;
        pDeviceAddressesDescriptor = WdfObjectGetTypedContext(
            g_wdfControlDevice,
            ADDRESSES_DESCRIPTOR
            );
        if (NULL != pDeviceAddressesDescriptor)
        {
            FilterDataCleanup(pDeviceAddressesDescriptor);
        }
        else
        {
            ASSERT(FALSE);
        }
    }
    WdfObjectReleaseLock(g_wdfControlDevice);
    status = FwpsCalloutUnregisterById(
        g_nDatagramIdV6
        );
    status = FwpsCalloutUnregisterById(
        g_nDatagramIdV4
        );
    status = FwpsCalloutUnregisterById(
        g_nStreamIdV6
        );
    status = FwpsCalloutUnregisterById(
        g_nStreamIdV4
        );
    status = FwpsCalloutUnregisterById(
        g_nAleFlowEstablishedV6Id
        );
    status = FwpsCalloutUnregisterById(
        g_nAleFlowEstablishedV4Id
        );
    status = FwpsCalloutUnregisterById(
        g_nInboundTransportV6Id
        );
    status = FwpsCalloutUnregisterById(
        g_nAleAcceptRecvV4Id
        );
    status = FwpsCalloutUnregisterById(
        g_nAleAcceptRecvV6Id
        );
    status = FwpsCalloutUnregisterById(
        g_nInboundTransportV4Id
        );
    status = FwpsInjectionHandleDestroy(
        g_hInjectionHandleV6
        );
    status = FwpsInjectionHandleDestroy(
        g_hInjectionHandleV4
        );
    if (NULL != g_hNetBufferPool)
    {
        NdisFreeNetBufferPool(g_hNetBufferPool);
        g_hNetBufferPool = NULL;
    }
    if (NULL != g_hNetBufferListPool)
    {
        NdisFreeNetBufferListPool(g_hNetBufferListPool);
        g_hNetBufferListPool = NULL;
    }
    if (NULL != g_pNdisGenericObj)
    {
        NdisFreeGenericObject(g_pNdisGenericObj);
        g_pNdisGenericObj = NULL;
    }
    TraceEvents(
        TRACE_LEVEL_INFORMATION,
        TRACE_DRIVER,
        "%!FUNC! line:%!LINE! %!LEVEL! Exit"
        );
}
