Поделиться через


Функция DnsQueryRaw (windns.h)

Важно!

Некоторые сведения относятся к предварительной версии продукта, который может быть существенно изменен до его коммерческого выпуска. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Позволяет выполнять запрос DNS, который принимает необработанный пакет, содержащий запрос DNS, или имя и тип запроса. Вы можете дополнить запрос параметрами и конфигурацией из хост-системы.

  • Вы можете применить новые параметры запроса и пользовательские серверы к уже отформатированным необработанным пакетам запросов DNS.
  • Или вместо этого можно указать имя и тип запроса, а также получить проанализированные записи и необработанный пакет результатов (что позволяет клиентам взаимодействовать со всеми сведениями, полученными с сервера).

Запросы выполняются асинхронно; Результаты и передаются в DNS_QUERY_RAW_COMPLETION_ROUTINE асинхронную функцию обратного вызова, которую вы реализуете. Чтобы отменить запрос, вызовите DnsCancelQueryRaw.

Синтаксис

DNS_STATUS DnsQueryRaw(
  DNS_QUERY_RAW_REQUEST *queryRequest,
  DNS_QUERY_RAW_CANCEL  *cancelHandle
);

Параметры

queryRequest

Тип: _In_ DNS_QUERY_RAW_REQUEST*

Запрос.

cancelHandle

Тип: _Inout_ DNS_QUERY_RAW_CANCEL*

Используется для получения дескриптора отмены, который можно передать в DnsCancelQueryRaw , если потребуется отменить запрос.

Возвращаемое значение

Значение DNS_STATUS , указывающее на успешное или неудачное выполнение. Если возвращается DNS_REQUEST_PENDING , то по завершении запроса система вызывает реализацию DNS_QUERY_RAW_COMPLETION_ROUTINE , переданную в элемент queryCompletionCallbackобъекта queryRequest. Этот обратный вызов получит результаты запроса в случае успешного выполнения, а также какие-либо сбои или отмены.

Комментарии

Структура необработанного пакета — это представление запроса и ответа DNS по сети, как описано в документе RFC 1035. За 12-байтным заголовком DNS следует раздел вопроса для запроса или переменный номер (может быть 0) записей для ответа. Если используется ПРОТОКОЛ TCP, то необработанный пакет должен иметь префикс поля длиной 2 байта. Этот API можно использовать, среди прочего, для применения правил NRPT узла или для выполнения зашифрованных запросов DNS.

Примеры

Пример 1

В этом примере необработанный запрос считывается из сокета с помощью вспомогательной функции, а ответ отправляется обратно через тот же сокет.

struct QUERY_RAW_CALLBACK_CONTEXT
{  
    DNS_QUERY_RAW_RESULT    *queryResults;
    HANDLE                  event;
};

VOID
CALLBACK
QueryRawCallback(
    _In_    VOID                  *queryContext,
    _In_    DNS_QUERY_RAW_RESULT  *queryResults
)
{
    QUERY_RAW_CALLBACK_CONTEXT *context = static_cast<QUERY_RAW_CALLBACK_CONTEXT *>(queryContext);

    //
    //  Capture the results of the query. Note that the DNS_QUERY_RAW_RESULT structure needs to
    //  be freed later with DnsQueryRawResultFree.
    //

    context->queryResults = queryResults;   

    SetEvent(context->event);
}

DWORD
HandleDnsQueryFromSocket(
    _In_ SOCKET socket
)
{
    DWORD errorStatus = ERROR_SUCCESS;
    DWORD waitStatus = 0;
    DNS_QUERY_RAW_REQUEST request = {0};
    DNS_QUERY_RAW_CANCEL cancel = {0};
    QUERY_RAW_CALLBACK_CONTEXT context = {0};
    CHAR opaqueSourceAddr[DNS_ADDR_MAX_SOCKADDR_LENGTH];
    ULONG opaqueSourceAddrSize = sizeof(opaqueSourceAddr);

    //
    //  ReceiveDnsQueryBytesFromSocket is a function that reads bytes from a socket
    //  that contains a wire-format DNS query, and gets information about the source
    //  address. It allocates the raw query buffer with HeapAlloc of size
    //  request.dnsQueryRawSize. Note that this function is just an example, and does
    //  not exist in the API.
    //
    errorStatus = ReceiveDnsQueryBytesFromSocket(socket,
                                                 &request.dnsQueryRaw,
                                                 &request.dnsQueryRawSize,
                                                 opaqueSourceAddr,
                                                 opaqueSourceAddrSize);
    if (errorStatus != ERROR_SUCCESS)
    {
        goto Exit;
    }

    context.event = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (context.event == NULL)
    {
        errorStatus = GetLastError();
        goto Exit;
    }

    //
    //  dnsQueryRaw is being used instead of dnsQueryName and dnsQueryType.
    //
    request.dnsQueryName = NULL;
    request.dnsQueryType = 0;

    request.version = DNS_QUERY_RAW_REQUEST_VERSION1; 
    request.resultsVersion = DNS_QUERY_RAW_RESULTS_VERSION1; 
    request.queryOptions = DNS_QUERY_BYPASS_CACHE;
    request.interfaceIndex = 0;
    request.queryCompletionCallback = &QueryRawCallback;
    request.queryContext = &context;
    request.queryRawOptions = 0;
    request.customServersSize = 0;
    request.customServers = NULL;
    request.protocol = DNS_PROTOCOL_UDP;
    memcpy_s(request.maxSa,
             sizeof(request.maxSa),
             opaqueSourceAddr,
             opaqueSourceAddrSize);

    errorStatus = DnsQueryRaw(&request, &cancel);
    if (errorStatus != DNS_REQUEST_PENDING)
    {
        goto Exit;
    }

    waitStatus = WaitForSingleObject(context.event, INFINITE);
    if (waitStatus != WAIT_OBJECT_0)
    {
        errorStatus = GetLastError();
        goto Exit;
    }

    //
    //  SendDnsResponseBytesToSocket is a function that writes a buffer containing a
    //  DNS response to a socket. Depending on the queryStatus, it can send other
    //  messages on the socket to indicate whether the socket should be closed, such as if
    //  the queryStatus indicates an internal DNS failure. Note that this function is
    //  just an example, and does not exist in the API.
    //
    errorStatus = SendDnsResponseBytesToSocket(socket,
                                               context.queryResults->queryStatus,
                                               context.queryResults->queryRawResponse,
                                               context.queryResults->queryRawResponseSize);

Exit:
    if (request.dnsQueryRaw != NULL)
    {
        HeapFree(GetProcessHeap(), 0, request.dnsQueryRaw);
        request.dnsQueryRaw = NULL;
    }

    if (context.queryResults != NULL)
    {
        DnsQueryRawResultFree(context.queryResults);
        context.queryResults = NULL;
    }

    if (context.event != NULL)
    {
        CloseHandle(context.event);
        context.event = NULL;
    }

    return errorStatus;
}

Пример 2

В этом примере запрос инициируется с именем и типом запроса, но затем отменяется с помощью DnsCancelQueryRaw.

struct QUERY_RAW_CALLBACK_CONTEXT
{
    DNS_QUERY_RAW_RESULT    *queryResults;
    HANDLE                  event;
};

VOID
CALLBACK
QueryRawCallback(
    _In_    VOID                  *queryContext,
    _In_    DNS_QUERY_RAW_RESULT  *queryResults
)
{
    QUERY_RAW_CALLBACK_CONTEXT *context = static_cast<QUERY_RAW_CALLBACK_CONTEXT *>(queryContext);

    //
    //  Capture the results of the query. Note that this structure needs to
    //  be freed later with DnsQueryRawResultFree.
    //

    context->queryResults = queryResults;

    SetEvent(context->event);
}

DWORD
CallDnsQueryRawAndCancel(
    _In_    PWSTR                       queryName,
    _In_    USHORT                      queryType,
    _In_    ULONG                       interfaceIndex,
    _In_    SOCKADDR_INET               *sourceAddr,
    _In_    ULONG                       protocol,
    _In_    DNS_CUSTOM_SERVER           *customServers,
    _In_    ULONG                       customServersSize,
    _Inout_ QUERY_RAW_CALLBACK_CONTEXT  *context
)
{
    DWORD errorStatus = ERROR_SUCCESS;
    DWORD waitStatus = 0;
    DNS_QUERY_RAW_REQUEST request = {0};
    DNS_QUERY_RAW_CANCEL cancel = {0};

    request.version = DNS_QUERY_RAW_REQUEST_VERSION1;
    request.resultsVersion = DNS_QUERY_RAW_RESULTS_VERSION1; 
    request.dnsQueryRawSize = 0;
    request.dnsQueryRaw = NULL;
    request.dnsQueryName = queryName;
    request.dnsQueryType = queryType;
    request.queryOptions = DNS_QUERY_BYPASS_CACHE;
    request.interfaceIndex = interfaceIndex;
    request.queryCompletionCallback = &QueryRawCallback;
    request.queryContext = context;
    request.queryRawOptions = 0;
    request.customServersSize = customServersSize;
    request.customServers = customServers;
    request.protocol = protocol;
    request.sourceAddr = *sourceAddr;

    errorStatus = DnsQueryRaw(&request, &cancel);
    if (errorStatus != DNS_REQUEST_PENDING)
    {
        goto Exit;
    }

    //
    //  Cancel the query with the provided cancel handle.
    //

    errorStatus = DnsCancelQueryRaw(&cancel);
    if (errorStatus != ERROR_SUCCESS)
    {
        goto Exit;
    }

    //
    //  Wait for the callback to indicate that the query has completed. Note that it
    //  is possible for the query to complete successfully or fail for another reason
    //  before the DnsCancelQueryRaw call is made, so the queryStatus member of
    //  DNS_QUERY_RAW_RESULT can be used to determine what happened.
    //

    waitStatus = WaitForSingleObject(context->event, INFINITE);
    if (waitStatus != WAIT_OBJECT_0)
    {
        errorStatus = GetLastError();
        goto Exit;
    }

    errorStatus = context.queryResults->queryStatus;

    if (errorStatus == ERROR_CANCELLED)
    {
        //
	    //  DNS query was successfully cancelled.
	    //
    }	
    else if (errorStatus != ERROR_SUCCESS)
    {
        //
	    //  DNS query failed before it was cancelled.
	    //
    }
    else
    {
        //
	    //  DNS query succeeded before it was cancelled, and can contain valid results.
        //  The other fields of context.queryResults to be processed as in Example 1.
	    //
    }

    //
    //  The context is owned by the caller of this function, and it will be cleaned up there.
    //

Exit:
    return errorStatus;
}

Требования

Требование Значение
Целевая платформа Windows
Header windns.h
Библиотека dnsapi.lib
DLL dnsapi.dll