예제 #1
0
NTSTATUS
MonitorCoInsertFlowContext(
   _Inout_ FLOW_DATA* flowContext)
{
   KLOCK_QUEUE_HANDLE lockHandle;
   NTSTATUS status;

   KeAcquireInStackQueuedSpinLock(&flowContextListLock, &lockHandle);

   // Catch the case where we disabled monitoring after we had intended to
   // associate the context to the flow so that we don't bugcheck due to
   // our driver being unloaded and then receiving a call for a particular
   // flow or leak the memory because we unloaded without freeing it.
   if (monitoringEnabled)
   {
      DoTraceMessage(TRACE_FLOW_ESTABLISHED, "Creating flow for traffic.\r\n");

      InsertTailList(&flowContextList, &flowContext->listEntry);
      status = STATUS_SUCCESS;
   }
   else
   {
      DoTraceMessage(TRACE_FLOW_ESTABLISHED, "Unable to create flow, driver shutting down.\r\n");

      // Our driver is shutting down.
      status = STATUS_SHUTDOWN_IN_PROGRESS;
   }

   KeReleaseInStackQueuedSpinLock(&lockHandle);
   return status;
}
예제 #2
0
파일: init.c 프로젝트: kcrazy/winekit
VOID
DriverUnload(
    IN  PDRIVER_OBJECT          driverObject
    )
/*++

Routine Description:

    Called to indicate that we are being unloaded and to cause an orderly
    shutdown

Arguments:

    driverObject            Our driver

Return Value:

    None

--*/
{
   UNREFERENCED_PARAMETER(driverObject);

   MonitorCoUninitialize();

   MonitorNfUninitialize();

   IoDeleteDevice(monitorDeviceObject);
   IoDeleteSymbolicLink(&monitorSymbolicLink);

   DoTraceMessage(TRACE_SHUTDOWN, "MsnMonitor Driver Shutting Down");

   WPP_CLEANUP(driverObject);
}
예제 #3
0
파일: wskudp.c 프로젝트: linuxxiaoyu/wskudp
// Driver unload routine
VOID
WskudpUnload(
    __in PDRIVER_OBJECT DriverObject
    )
{  
    
    UNREFERENCED_PARAMETER(DriverObject);

    PAGED_CODE();

    DoTraceMessage(TRCINFO, "UNLOAD START");

	WSKCleanup();
	
    DoTraceMessage(TRCINFO, "UNLOAD END");

    WPP_CLEANUP(DriverObject);
}
예제 #4
0
//
//Routine Name:
//
//    XPSRasFilter::ShutdownOperation
//
//Routine Description:
//
//    Called asynchronously by the pipeline manager
//    to shutdown filter operation.
//
//Arguments:
//
//    None
//
//Return Value:
//
//    HRESULT
//    S_OK - On success
//
__checkReturn
HRESULT
XPSRasFilter::ShutdownOperation()
{
    DoTraceMessage(XPSRASFILTER_TRACE_INFO, L"Shutting Down Operation");

    m_pLiveness->Cancel();

    return S_OK;
}
예제 #5
0
void
JobParameters::Trace() const
{
	ParamValueMap::const_iterator it;
	for (it = this->values.begin(); it != this->values.end(); ++it)
	{
		DoTraceMessage(
			MSG_INFO, 
			"Job: %lu, %S = %S", 
			this->jobId, it->first.c_str(), it->second.c_str()
		);
	}
}
예제 #6
0
void ThrowHRException(
    HRESULT hr,
    char const *fileName,
    int lineNum
    )
{
    DoTraceMessage(
        XPSRASFILTER_TRACE_ERROR,
        L"Throwing HRESULT Exception from %s:%d (HRESULT=%!HRESULT!)", 
        fileName, 
        lineNum, 
        hr
        );

    throw hr_error(hr);
}
예제 #7
0
//
//Routine Name:
//
//    XPSRasFilter::StartOperation
//
//Routine Description:
//
//    Called by the pipeline manager to start processing
//    a document. Exception boundary for page processing.
//
//Arguments:
//
//    None
//
//Return Value:
//
//    HRESULT
//    S_OK      - On success
//    Otherwise - Failure
//
__checkReturn
HRESULT
XPSRasFilter::StartOperation()
{
    HRESULT hr = S_OK;

    DoTraceMessage(XPSRASFILTER_TRACE_INFO, L"Starting Operation");

    //
    // Process the Xps Package
    //
    try {
        StartOperation_throws();
    }
    CATCH_VARIOUS(hr);

    m_pWriter->Close();

    return hr;
}
예제 #8
0
NTSTATUS
MonitorCtlDriverInit(
    _In_ WDFDEVICE* pDevice
    )
/*++

Routine Description:

   Initializes the request queue for our driver.  This is how 
   DeviceIoControl requests are sent to KMDF drivers.

Arguments:
   
   [in]  WDFDEVICE* pDevice - Our device.

--*/
{
   NTSTATUS status;
   WDF_IO_QUEUE_CONFIG queueConfig;

   DoTraceMessage(TRACE_INIT, "MonitorSample Control Initialization in progress.");

   WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(
      &queueConfig,
      WdfIoQueueDispatchSequential
      );

   queueConfig.EvtIoDeviceControl = MonitorEvtDeviceControl;

   status = WdfIoQueueCreate(
               *pDevice,
               &queueConfig,
               WDF_NO_OBJECT_ATTRIBUTES,
               NULL
               );

   return status;
}
//
//Routine Name:
//
//    PrintTicketHandler::QueryDPI
//
//Routine Description:
//
//    Queries the DPI from the Print Ticket using an XPath query.
//
//Return Value:
//
//    FLOAT
//    DPI from the Print Ticket.
//
FLOAT
PrintTicketHandler::QueryDPI()
{
    //
    // Default DPI: 96 DPI
    //
    FLOAT dpi = 96.0;

    //
    // Perform the page resolution query on the print ticket
    //
    IXMLDOMNodeList_t pNodes;

    //
    // The following XPath query is fairly straightforward, except for the
    // predicate attached to Feature. This is necessary to match both the
    // keyword AND the namespace of the "name" of the Feature as in:
    //
    //  <psf:Feature name="psk:PageResolution">
    //
    // In order to match the keyword, we match the substring after the colon:
    //
    //  [substring-after(@name,':')='PageResolution']
    //
    // We also need to ensure that the namespace refers to the correct
    // printschemakeywords namespace. Thus we get:
    //
    //  [name(namespace::*[.=PRINTSCHEMAKEYWORDNS])=substring-before(@name,':')]
    //
    // where PRINTSCHEMAKEYWORDNS is:
    //
    //  http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords
    //
    BSTR_t query(L"psf:PrintTicket/psf:Feature[substring-after(@name,':')='PageResolution']"
                 L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]"
                 L"/*/*/psf:Value");

    THROW_ON_FAILED_HRESULT(
        m_pDOMDoc->selectNodes(query, &pNodes)
        );

    if (pNodes)
    {
        //
        // The Print Ticket may have both X and Y resolutions defined, but
        // the Xps Rasterization Service only accepts a single resolution.
        // We query for both X and Y resolutions and take the larger of the
        // two as the destination DPI. The resultant raster data could then
        // be scaled down in the other dimension to achieve the non-square
        // pixels.
        //

        LONG numResolutions;

        THROW_ON_FAILED_HRESULT(
            pNodes->get_length(&numResolutions)
            );

        if (numResolutions != 0 &&
            numResolutions != 1 &&
            numResolutions != 2)
        {
            //
            // We expect 0, 1, or 2 resolutions to be set in the Print Ticket.
            // Throw if this is not the case.
            //
            THROW_ON_FAILED_HRESULT(E_UNEXPECTED);
        }

        LONG maxResolution = 0;

        for (INT i = 0; i < numResolutions; i++)
        {
            IXMLDOMNode_t pCurrentNode;

            THROW_ON_FAILED_HRESULT(
                pNodes->get_item(i, &pCurrentNode)
                );

            BSTR_t strResolution;

            THROW_ON_FAILED_HRESULT(
                pCurrentNode->get_text(&strResolution)
                );

            LONG resolution;

            THROW_ON_FAILED_HRESULT(
                ::VarI4FromStr(
                    strResolution,
                    LOCALE_USER_DEFAULT, 
                    0, // no custom flags
                    &resolution
                    )
                );

            if (resolution > maxResolution)
            {
                maxResolution = resolution;
            }
        }

        dpi = static_cast<FLOAT>(maxResolution);
    }

    DoTraceMessage(XPSRASFILTER_TRACE_VERBOSE, L"Got DPI: %f", dpi);

    return dpi;
}
예제 #10
0
//
//Routine Name:
//
//    PrintTicketHandler::QueryPhysicalPageSize
//
//Routine Description:
//
//    Queries the physical page size from the 
//    Print Ticket using an XPath query.
//
//Return Value:
//
//    XPS_SIZE
//    Physical page size from the Print Ticket (in XPS units).
//
XPS_SIZE
PrintTicketHandler::QueryPhysicalPageSize()
{
    //
    // Default page size: 8.5" x 11" at Xps DPI
    //
    XPS_SIZE pageSize = {11.0f * xpsDPI,
                         8.5f  * xpsDPI};

    {
        //
        // Perform the page width query on the print ticket
        //
        IXMLDOMNode_t pNode;

        //
        // See the comment in PrintTicketHandler::QueryDPI() for details
        // about this XPath query.
        //
        BSTR_t query(L"psf:PrintTicket/psf:Feature[substring-after(@name,':')='PageMediaSize']"
                     L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]"
                     L"/*/psf:ScoredProperty[substring-after(@name,':')='MediaSizeWidth']"
                     L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]"
                     L"/psf:Value");

        THROW_ON_FAILED_HRESULT(
            m_pDOMDoc->selectSingleNode(query, &pNode)
            );

        if (pNode)
        {
            BSTR_t strWidth;
            THROW_ON_FAILED_HRESULT(
                pNode->get_text(&strWidth)
                );

            LONG width;
            THROW_ON_FAILED_HRESULT(
                ::VarI4FromStr(
                    strWidth,
                    LOCALE_USER_DEFAULT,
                    0, // no custom flags
                    &width
                    )
                );

            //
            // the page dimensions are in microns; convert to Xps units
            //
            pageSize.width = MicronsToXpsUnits(width);
        }
    }

    {
        //
        // Perform the page height query on the print ticket
        //
        IXMLDOMNode_t pNode;

        //
        // See the comment in PrintTicketHandler::QueryDPI() for details
        // about this XPath query.
        //
        BSTR_t query(L"psf:PrintTicket/psf:Feature[substring-after(@name,':')='PageMediaSize']"
                     L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]"
                     L"/*/psf:ScoredProperty[substring-after(@name,':')='MediaSizeHeight']"
                     L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]"
                     L"/psf:Value");

        THROW_ON_FAILED_HRESULT(
            m_pDOMDoc->selectSingleNode(query, &pNode)
            );

        if (pNode)
        {
            BSTR_t strHeight;
            THROW_ON_FAILED_HRESULT(
                pNode->get_text(&strHeight)
                );

            LONG height;
            THROW_ON_FAILED_HRESULT(
                ::VarI4FromStr(
                    strHeight, 
                    LOCALE_USER_DEFAULT, 
                    0, // no custom flags
                    &height
                    )
                );

            //
            // the page dimensions are in microns; convert to Xps unit
            //
            pageSize.height = MicronsToXpsUnits(height);
        }
    }

    {
        //
        // Perform the landscape query on the print ticket
        //
        IXMLDOMNode_t pNode;

        //
        // See the comment in PrintTicketHandler::QueryDPI() for details
        // about this XPath query.
        //
        BSTR_t query(L"psf:PrintTicket/psf:Feature[substring-after(@name,':')='PageOrientation']"
                     L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]"
                     L"/psf:Option[substring-after(@name,':')='Landscape']"
                     L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]");

        THROW_ON_FAILED_HRESULT(
            m_pDOMDoc->selectSingleNode(query, &pNode)
            );

        if (pNode)
        {
            //
            // landscape. swap height and width.
            //
            FLOAT tmp;

            tmp = pageSize.height;
            pageSize.height = pageSize.width;
            pageSize.width = tmp;
        }

        DoTraceMessage(XPSRASFILTER_TRACE_VERBOSE, L"Physical Page Size: %f x %f", pageSize.width, pageSize.height);
    }

    return pageSize;
}
예제 #11
0
//
//Routine Name:
//
//    XPSRasFilter::StartOperation_throws
//
//Routine Description:
//
//    Iterates over the 'trunk' parts of the document
//    and calls appropriate processing methods.
//
//Arguments:
//
//    None
//
void
XPSRasFilter::StartOperation_throws()
{
    //
    // CoInitialize/CoUninitialize RAII object.
    // COM is inititalized for the lifetime of this method.
    //
    SafeCoInit  coInit;

    IXpsOMObjectFactory_t pOMFactory;

    //
    // Create Xps Object Model Object Factory instance
    //
    THROW_ON_FAILED_HRESULT(
        ::CoCreateInstance(
            __uuidof(XpsOMObjectFactory),
            NULL,
            CLSCTX_INPROC_SERVER,
            __uuidof(IXpsOMObjectFactory),
            reinterpret_cast<LPVOID*>(&pOMFactory)
        )
    );

    IOpcFactory_t pOpcFactory;

    //
    // Create Opc Object Factory instance
    //
    THROW_ON_FAILED_HRESULT(
        ::CoCreateInstance(
            __uuidof(OpcFactory),
            NULL,
            CLSCTX_INPROC_SERVER,
            __uuidof(IOpcFactory),
            reinterpret_cast<LPVOID*>(&pOpcFactory)
        )
    );

    //
    // Create the rasterization interface
    //
    RasterizationInterface_t pRasInterface =
        RasterizationInterface::CreateRasterizationInterface(
            m_pIPropertyBag,
            m_pWriter
        );

    //
    // Create the Print Ticket Handler
    //
    PrintTicketHandler_t pPrintTicketHandler =
        PrintTicketHandler::CreatePrintTicketHandler(
            m_pIPropertyBag
        );

    IUnknown_t pUnk;

    //
    // Get first part
    //
    THROW_ON_FAILED_HRESULT(m_pReader->GetXpsPart(&pUnk));

    while (m_pLiveness->IsAlive() &&
            pUnk != NULL)
    {
        IXpsDocument_t               pDoc;
        IFixedDocumentSequence_t     pFDS;
        IFixedDocument_t             pFD;
        IFixedPage_t                 pFP;

        if (SUCCEEDED(pUnk.QueryInterface(&pFP)))
        {
            DoTraceMessage(XPSRASFILTER_TRACE_VERBOSE, L"Handling a Page");

            pPrintTicketHandler->ProcessPart(pFP);

            ParametersFromPrintTicket printTicketParams =
                pPrintTicketHandler->GetMergedPrintTicketParams();

            pRasInterface->RasterizePage(
                CreateXpsOMPageFromIFixedPage(pFP, pOMFactory, pOpcFactory),
                printTicketParams,
                m_pLiveness
            );
        }
        else if (SUCCEEDED(pUnk.QueryInterface(&pFD)))
        {
            pPrintTicketHandler->ProcessPart(pFD);
        }
        else if (SUCCEEDED(pUnk.QueryInterface(&pFDS)))
        {
            pPrintTicketHandler->ProcessPart(pFDS);
        }
        else if (SUCCEEDED(pUnk.QueryInterface(&pDoc)))
        {
            //
            // Do nothing with the XML Document part
            //
        }
        else
        {
            //
            // Any other document 'trunk' parts are ignored.
            //
        }

        pUnk.Release();

        //
        // Get Next Part
        //
        THROW_ON_FAILED_HRESULT(m_pReader->GetXpsPart(&pUnk));
    }

    pRasInterface->FinishRasterization();
}
예제 #12
0
//
//Routine Name:
//
//    PrintTicketHandler::GetMergedPrintTicketParams
//
//Routine Description:
//
//    Queries a set of parameters from the merged print ticket.
//
//    NOTE: Relies on successful calls to all three PrintTicket
//    processing methods.
//
//Return Value:
//
//    ParametersFromPrintTicket
//    The set of parameters queried from the merged
//    Print Ticket.
//
ParametersFromPrintTicket
PrintTicketHandler::GetMergedPrintTicketParams()
{
    DoTraceMessage(XPSRASFILTER_TRACE_VERBOSE, L"Getting Print Ticket parameters");

    if (!m_pPagePrintTicket)
    {
        DoTraceMessage(XPSRASFILTER_TRACE_ERROR, L"GetMergedPrintTicketParams called before ProcessPagePrintTicket");
        THROW_ON_FAILED_HRESULT(E_FAIL);
    }

    ParametersFromPrintTicket params;

    //
    // Seek the Page-level Print Ticket to 0
    //
    LARGE_INTEGER zero;
    zero.QuadPart = 0;
    THROW_ON_FAILED_HRESULT(
        m_pPagePrintTicket->Seek(zero, SEEK_SET, NULL)
        );

    //
    // Load the print ticket stream into a DOM document
    //
    // NOTE: We are only looking for features at the Page scope for this sample,
    // so we only extract features from the effective page-level PrintTicket.
    //
    Variant_t varStream(m_pPagePrintTicket);
    VARIANT_BOOL success;

    THROW_ON_FAILED_HRESULT(
        m_pDOMDoc->load(varStream, &success)
        );
    if (!success)
    {
        WPP_LOG_ON_FAILED_HRESULT(E_FAIL);
        THROW_ON_FAILED_HRESULT(E_FAIL);
    }

    //
    // Set the DOM Selection namespace to simplify queries
    //
    BSTR_t ns(L"xmlns:psf='http://schemas.microsoft.com/windows/2003/08/printing/printschemaframework'");
    Variant_t nsProp(ns);
    THROW_ON_FAILED_HRESULT(
        m_pDOMDoc->setProperty(L"SelectionNamespaces", nsProp)
        );

    //
    // Query the print ticket for parameters of interest
    //
    params.destDPI =            QueryDPI();
    params.scaling =            QueryScaling();
    params.physicalPageSize =   QueryPhysicalPageSize();
    
    //
    // We simulate imageable area by assuming a constant margin of
    // around the entire page
    //
    params.imageableArea.x =        g_pageMargin * xpsDPI;
    params.imageableArea.y =        g_pageMargin * xpsDPI;
    params.imageableArea.height =   params.physicalPageSize.height 
                                        - 2 * g_pageMargin * xpsDPI;
    params.imageableArea.width =    params.physicalPageSize.width 
                                        - 2 * g_pageMargin * xpsDPI;

    return params;
}
예제 #13
0
NTSTATUS
TracedrvDispatchDeviceControl(
                             IN PDEVICE_OBJECT pDO,
                             IN PIRP Irp
                             )
/*++

Routine Description:

   Dispatch routine to handle IOCTL IRPs.

Arguments:

   DeviceObject - pointer to a device object.

   Irp - pointer to an I/O Request Packet.

Return Value:

   NT status code

--*/
{
    NTSTATUS status = STATUS_SUCCESS;
    PIO_STACK_LOCATION irpStack =  IoGetCurrentIrpStackLocation( Irp );
    ULONG ControlCode =  irpStack->Parameters.DeviceIoControl.IoControlCode;
    ULONG i=0;
    static ULONG ioctlCount = 0;
    MachineState CurrentState = Offline; 
    

    PAGED_CODE();
    UNREFERENCED_PARAMETER(pDO);

    Irp->IoStatus.Information = 
                            irpStack->Parameters.DeviceIoControl.OutputBufferLength;

    switch ( ControlCode ) {
    case IOCTL_TRACEKMP_TRACE_EVENT:
        //
        // Every time we get this IOCTL, we also log a trace Message if
        // Trace flag one is enabled. This is used
        // to illustrate that the event can be caused by user-mode.
        //
        
        ioctlCount++;

        // 
        // Log a simple Message
        //

        DoTraceMessage(FLAG_ONE, "IOCTL = %d", ioctlCount);

        while (i++ < MAXEVENTS) {
            //
            // Trace events in a loop.
            //
            DoTraceMessage(FLAG_ONE,  "Hello, %d %s", i, "Hi" );

            if ( !(i%MAXEVENTS)){
                //
                // Trace if level >=2 and 2 bit set by -level 2 -flags 2 in tracelog
                // Uses the format string for the defined enum MachineState in the 
                // scanned header file
                //
                DoTraceLevelMessage(
                    TRACE_LEVEL_ERROR,          // ETW Level defined in evntrace.h
                    FLAG_TWO,                   // Flag defined in WPP_CONTROL_GUIDS
                    "Machine State :: %!state!",
                    CurrentState                // enum parameter 
                    );
            }
        }

        //
        // Set a fake error status to fire the TRACE_RETURN macro below
        //
        status = STATUS_DEVICE_POWERED_OFF;

        Irp->IoStatus.Information = 0;
        break;

        //
        // Not one we recognize. Error.
        //
    default:
        status = STATUS_INVALID_PARAMETER; 
        Irp->IoStatus.Information = 0;
        break;
    }

    //
    // Trace the return status using the TRACE_RETURN macro wich includes PRE/POST
    // macros. The value could be either the fake error or invalid parameter
    //
    TRACE_RETURN(status);

    if (status != STATUS_INVALID_PARAMETER) {
        //
        // Set the status back to success
        //
        status = STATUS_SUCCESS;
    }

    //
    // Get rid of this request
    //
    Irp->IoStatus.Status = status;
    IoCompleteRequest( Irp, IO_NO_INCREMENT );
        
    return status;
}
예제 #14
0
파일: init.c 프로젝트: kcrazy/winekit
NTSTATUS
DriverEntry(
    IN  PDRIVER_OBJECT          driverObject,
    IN  PUNICODE_STRING         registryPath
    )
/*++

Routine Description:

    Main driver entry point. Called at driver load time

Arguments:

    driverObject            Our driver
    registryPath            A reg key where we can keep parameters

Return Value:

    status of our initialization. A status != STATUS_SUCCESS aborts the
    driver load and we don't get called again.

    Each component is responsible for logging any error that causes the
    driver load to fail.

--*/
{
   NTSTATUS          status;
   UNICODE_STRING    deviceName;
   BOOLEAN           validSymbolicLink = FALSE;
   BOOLEAN           initializedCallouts = FALSE;

   //
   // This macro is required to initialize software tracing on XP and beyond
   // For XP and beyond use the DriverObject as the first argument.
   // 
   
   WPP_INIT_TRACING(driverObject,registryPath);

   DoTraceMessage(TRACE_INIT, "Initializing MsnMonitor Driver");

   monitorDeviceObject = NULL;

   UNREFERENCED_PARAMETER(registryPath);

   driverObject->DriverUnload = DriverUnload;

   status = MonitorCtlDriverInit(driverObject);

   if (!NT_SUCCESS(status))
   {
      goto cleanup;
   }

   RtlInitUnicodeString(&deviceName,
                        MONITOR_DEVICE_NAME);

   status = IoCreateDevice(driverObject, 0, &deviceName, FILE_DEVICE_NETWORK, 0, FALSE, &monitorDeviceObject);
   if (!NT_SUCCESS(status))
   {
      goto cleanup;
   }

   status = MonitorCoInitialize(monitorDeviceObject);
   if (!NT_SUCCESS(status))
   {
      initializedCallouts = TRUE;
      goto cleanup;
   }

   RtlInitUnicodeString(&monitorSymbolicLink, MONITOR_SYMBOLIC_NAME);

   status = IoCreateSymbolicLink(&monitorSymbolicLink, &deviceName);

   if (!NT_SUCCESS(status))
   {
      goto cleanup;
   }
   validSymbolicLink = TRUE;

   status = MonitorNfInitialize(monitorDeviceObject);
   if (!NT_SUCCESS(status))
   {
      goto cleanup;
   }

cleanup:
   if (!NT_SUCCESS(status))
   {
      DoTraceMessage(TRACE_INIT, "MsnMonitor Initialization Failed.");

      WPP_CLEANUP(driverObject);

      if (initializedCallouts)
      if (validSymbolicLink)
      {
         IoDeleteSymbolicLink(&monitorSymbolicLink);
      }

      if (monitorDeviceObject)
      {
         IoDeleteDevice(monitorDeviceObject);
      }
   }

   return status;
}
예제 #15
0
파일: sub.c 프로젝트: airhigh/wdrbd
void _printk(const char * func, const char * format, ...)
{
	int ret = 0;
	va_list args;

	char * buf = (char *) ExAllocateFromNPagedLookasideList(&drbd_printk_msg);
	if (!buf)
	{
		return;
	}
	RtlZeroMemory(buf, MAX_ELOG_BUF);

	va_start(args, format);
	ret = vsprintf(buf, format, args); // DRBD_DOC: improve vsnprintf 
	va_end(args);

	int length = strlen(buf);
	if (length > MAX_ELOG_BUF)
	{
		length = MAX_ELOG_BUF - 1;
		buf[MAX_ELOG_BUF - 1] = 0;
	}
	else
	{
		// TODO: chekc min?
	}

	ULONG msgid = PRINTK_INFO;
	int level_index = format[1] - '0';
	int printLevel = 0;
	CHAR szTempBuf[MAX_ELOG_BUF] = "";
	BOOLEAN bSysEventLog = FALSE;
	BOOLEAN bServiceLog = FALSE;
	BOOLEAN bDbgLog = FALSE;
	extern atomic_t g_syslog_lv_min;
	extern atomic_t g_svclog_lv_min;
	extern atomic_t g_dbglog_lv_min;

	ASSERT((level_index >= 0) && (level_index < 8));
	
#ifdef _WIN32_WPP
	DoTraceMessage(TRCINFO, "%s", buf);
	WriteEventLogEntryData(msgids[level_index], 0, 0, 1, L"%S", buf + 3);
	DbgPrintEx(FLTR_COMPONENT, DPFLTR_INFO_LEVEL, "WDRBD_INFO: [%s] %s", func, buf + 3);
	ExFreeToNPagedLookasideList(&drbd_printk_msg, buf);
#else
	// to write system event log.
	if (level_index <= atomic_read(&g_syslog_lv_min))
		bSysEventLog = TRUE;
	// to send to drbd service.	
	if (level_index <= atomic_read(&g_svclog_lv_min))
		bServiceLog = TRUE;
	// to print through debugger.
	if (level_index <= atomic_read(&g_dbglog_lv_min))
		bDbgLog = TRUE;

	// nothing to log.
	if (!bSysEventLog &&
		!bServiceLog &&
		!bDbgLog)
	{
		ExFreeToNPagedLookasideList(&drbd_printk_msg, buf);
		return;
	}

	if (bSysEventLog)
	{
		save_to_system_event(buf, length, level_index);
	}

	switch (level_index)
	{
	case KERN_EMERG_NUM:
	case KERN_ALERT_NUM:
	case KERN_CRIT_NUM:
		printLevel = DPFLTR_ERROR_LEVEL;
		sprintf(szTempBuf, "<%d>%s: [%s] %s", level_index, "WDRBD_FATA", func, buf + 3);
		break;
	case KERN_ERR_NUM:
		printLevel = DPFLTR_ERROR_LEVEL;
		sprintf(szTempBuf, "<%d>%s: [%s] %s", level_index, "WDRBD_ERRO", func, buf + 3);
		break;
	case KERN_WARNING_NUM:
		printLevel = DPFLTR_WARNING_LEVEL;
		sprintf(szTempBuf, "<%d>%s: [%s] %s", level_index, "WDRBD_WARN", func, buf + 3);
		break;
	case KERN_NOTICE_NUM:
	case KERN_INFO_NUM:
		printLevel = DPFLTR_INFO_LEVEL;
		sprintf(szTempBuf, "<%d>%s: [%s] %s", level_index, "WDRBD_INFO", func, buf + 3);
		break;
	case KERN_DEBUG_NUM:
		printLevel = DPFLTR_TRACE_LEVEL;
		sprintf(szTempBuf, "<%d>%s: [%s] %s", level_index, "WDRBD_TRAC", func, buf + 3);
		break;
	default:
		printLevel = DPFLTR_TRACE_LEVEL;
		sprintf(szTempBuf, "<%d>%s: [%s] %s", level_index, "WDRBD_UNKN", func, buf + 3);
		break;
	}

	strcpy_s(buf, MAX_ELOG_BUF, szTempBuf);

	if (bDbgLog)
		DbgPrintEx(FLTR_COMPONENT, printLevel, buf + 3);

#ifdef _WIN32_LOGLINK
	if (FALSE == bServiceLog ||
		FALSE == LogLink_IsUsable() ||
		STATUS_SUCCESS != LogLink_QueueBuffer(buf))
	{
		// buf will be freed by loglink sender thread if it's queued, otherwise free it here.
		ExFreeToNPagedLookasideList(&drbd_printk_msg, buf);
	}
#else
    // WriteEventLogEntryData(msgids[level_index], 0, 0, 1, L"%S", buf + 3); //old style
    DbgPrintEx(FLTR_COMPONENT, DPFLTR_INFO_LEVEL, "WDRBD_INFO: [%s] %s", func, buf + 3);

	ExFreeToNPagedLookasideList(&drbd_printk_msg, buf);
#endif
#endif
}
예제 #16
0
VOID
MonitorEvtDeviceControl (
    _In_ WDFQUEUE Queue,
    _In_ WDFREQUEST Request,
    _In_ size_t OutputBufferLength,
    _In_ size_t InputBufferLength,
    _In_ ULONG IoControlCode
    )
/*++

   Handles device IO control requests. This callback drives all communication
   between the usermode exe and this driver.

--*/
{
   NTSTATUS status = STATUS_SUCCESS;

   UNREFERENCED_PARAMETER(Queue);
   UNREFERENCED_PARAMETER(OutputBufferLength);

   DoTraceMessage(TRACE_DEVICE_CONTROL, "MonitorSample Dispatch Device Control: 0x%x", IoControlCode);

   switch (IoControlCode)
   {
      case MONITOR_IOCTL_ENABLE_MONITOR:
      {
         WDFMEMORY pMemory;
         void* pBuffer;

         if (InputBufferLength < sizeof(MONITOR_SETTINGS))
         {
            status = STATUS_INVALID_PARAMETER;
         }
         else
         {
            status = WdfRequestRetrieveInputMemory(Request, &pMemory);

            if (NT_SUCCESS(status))
            {
               pBuffer = WdfMemoryGetBuffer(pMemory, NULL);
               status = MonitorCoEnableMonitoring((MONITOR_SETTINGS*) pBuffer);
            }
         }
         break;
      }

      case MONITOR_IOCTL_DISABLE_MONITOR:
      {
         status = STATUS_SUCCESS;
         
         MonitorCoDisableMonitoring();

         break;
      }

      default:
      {
         status = STATUS_INVALID_PARAMETER;
      }
   }

   WdfRequestComplete(Request, status);
}
예제 #17
0
파일: wskudp.c 프로젝트: linuxxiaoyu/wskudp
// Driver entry routine
NTSTATUS
DriverEntry(
    __in PDRIVER_OBJECT DriverObject,
    __in PUNICODE_STRING RegistryPath
    )
{
    NTSTATUS 		status = STATUS_SUCCESS;
	SOCKADDR_IN 	LocalAddress = {0,};
	SOCKADDR_IN 	RemoteAddress = {0,};
	
    LONG    		BufferSize = 0;
    CHAR    		GreetMessage[] = "Hello there\r\n";
	
    //PWSK_SOCKET 	Socket = NULL;
    	
    UNREFERENCED_PARAMETER(RegistryPath);

    PAGED_CODE();

	

    DriverObject->DriverUnload = WskudpUnload;

	status = WSKStartup();

    g_UdpSocket = CreateSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, WSK_FLAG_DATAGRAM_SOCKET);
    if (g_UdpSocket == NULL) {
        DbgPrint("DriverEntry(): CreateSocket() returned NULL\n");
		return (status = STATUS_UNSUCCESSFUL);
    }

    LocalAddress.sin_family = AF_INET;
    LocalAddress.sin_addr.s_addr = INADDR_ANY;
    //LocalAddress.sin_port = INADDR_PORT;
	
	// Bind Required
	status = Bind(g_UdpSocket, (PSOCKADDR)&LocalAddress);
	if (!NT_SUCCESS(status)) {
		DbgPrint("Bind() failed with status 0x%08X\n", status);
		CloseSocket(g_UdpSocket);
		return status;
	}
	
	RemoteAddress.sin_family = AF_INET;
    RemoteAddress.sin_addr.s_addr = HTON_LONG(INADDR_LOOPBACK);//HTON_LONG(0xc0a802a2);//HTON_LONG(INADDR_LOOPBACK);
    RemoteAddress.sin_port = HTON_SHORT(LOG_PORT);
	

    if (SendTo(g_UdpSocket, GreetMessage, sizeof(GreetMessage)-1, (PSOCKADDR)&RemoteAddress) == sizeof(GreetMessage)-1) {
	} else {
		
	}

	CloseSocket(g_UdpSocket);
		
    // Initialize software tracing
    WPP_INIT_TRACING(DriverObject, RegistryPath);
    
    DoTraceMessage(TRCINFO, "LOADED");
    
    return status;
}