http.c 44.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * HTTP server driver
 *
 * Copyright 2019 Zebediah Figura
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

21
#include <assert.h>
22 23
#include "ntstatus.h"
#define WIN32_NO_STATUS
24
#include "wine/http.h"
25 26 27
#include "winternl.h"
#include "ddk/wdm.h"
#include "wine/debug.h"
28 29
#include "wine/heap.h"
#include "wine/list.h"
30

31 32 33
static HANDLE directory_obj;
static DEVICE_OBJECT *device_obj;

34 35
WINE_DEFAULT_DEBUG_CHANNEL(http);

36 37 38 39
/* We have to return the HTTP_REQUEST structure to userspace exactly as it will
 * be consumed; httpapi has no opportunity to massage it. Since it contains
 * pointers, this is somewhat nontrivial. */

40 41 42 43 44 45 46 47
struct http_unknown_header_32
{
    USHORT NameLength;
    USHORT RawValueLength;
    ULONG pName; /* char string */
    ULONG pRawValue; /* char string */
};

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
struct http_data_chunk_32
{
    HTTP_DATA_CHUNK_TYPE DataChunkType;
    union
    {
        struct
        {
            ULONG pBuffer; /* char string */
            ULONG BufferLength;
        } FromMemory;
        /* for the struct size */
        struct
        {
            ULARGE_INTEGER StartingOffset;
            ULARGE_INTEGER Length;
            HANDLE FileHandle;
        } FromFileHandle;
    };
};

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
struct http_request_32
{
    ULONG Flags;
    HTTP_CONNECTION_ID ConnectionId;
    HTTP_REQUEST_ID RequestId;
    HTTP_URL_CONTEXT UrlContext;
    HTTP_VERSION Version;
    HTTP_VERB Verb;
    USHORT UnknownVerbLength;
    USHORT RawUrlLength;
    ULONG pUnknownVerb; /* char string */
    ULONG pRawUrl; /* char string */
    struct
    {
        USHORT FullUrlLength;
        USHORT HostLength;
        USHORT AbsPathLength;
        USHORT QueryStringLength;
        ULONG pFullUrl; /* WCHAR string */
        ULONG pHost; /* pointer to above */
        ULONG pAbsPath; /* pointer to above */
        ULONG pQueryString; /* pointer to above */
    } CookedUrl;
    struct
    {
        ULONG pRemoteAddress; /* SOCKADDR */
        ULONG pLocalAddress; /* SOCKADDR */
    } Address;
    struct
    {
        USHORT UnknownHeaderCount;
        ULONG pUnknownHeaders; /* struct http_unknown_header_32 */
        USHORT TrailerCount;
        ULONG pTrailers; /* NULL */
        struct
        {
            USHORT RawValueLength;
            ULONG pRawValue; /* char string */
        } KnownHeaders[HttpHeaderRequestMaximum];
    } Headers;
    ULONGLONG BytesReceived;
    USHORT EntityChunkCount;
    ULONG pEntityChunks; /* struct http_data_chunk_32 */
    HTTP_RAW_CONNECTION_ID RawConnectionId;
    ULONG pSslInfo; /* NULL (FIXME) */
    USHORT RequestInfoCount;
    ULONG pRequestInfo; /* NULL (FIXME) */
};

117 118 119 120 121 122 123 124
struct http_unknown_header_64
{
    USHORT NameLength;
    USHORT RawValueLength;
    ULONGLONG pName; /* char string */
    ULONGLONG pRawValue; /* char string */
};

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
struct http_data_chunk_64
{
    HTTP_DATA_CHUNK_TYPE DataChunkType;
    union
    {
        struct
        {
            ULONGLONG pBuffer; /* char string */
            ULONG BufferLength;
        } FromMemory;
        /* for the struct size */
        struct
        {
            ULARGE_INTEGER StartingOffset;
            ULARGE_INTEGER Length;
            HANDLE FileHandle;
        } FromFileHandle;
    };
};

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
struct http_request_64
{
    ULONG Flags;
    HTTP_CONNECTION_ID ConnectionId;
    HTTP_REQUEST_ID RequestId;
    HTTP_URL_CONTEXT UrlContext;
    HTTP_VERSION Version;
    HTTP_VERB Verb;
    USHORT UnknownVerbLength;
    USHORT RawUrlLength;
    ULONGLONG pUnknownVerb; /* char string */
    ULONGLONG pRawUrl; /* char string */
    struct
    {
        USHORT FullUrlLength;
        USHORT HostLength;
        USHORT AbsPathLength;
        USHORT QueryStringLength;
        ULONGLONG pFullUrl; /* WCHAR string */
        ULONGLONG pHost; /* pointer to above */
        ULONGLONG pAbsPath; /* pointer to above */
        ULONGLONG pQueryString; /* pointer to above */
    } CookedUrl;
    struct
    {
        ULONGLONG pRemoteAddress; /* SOCKADDR */
        ULONGLONG pLocalAddress; /* SOCKADDR */
    } Address;
    struct
    {
        USHORT UnknownHeaderCount;
        ULONGLONG pUnknownHeaders; /* struct http_unknown_header_32 */
        USHORT TrailerCount;
        ULONGLONG pTrailers; /* NULL */
        struct
        {
            USHORT RawValueLength;
            ULONGLONG pRawValue; /* char string */
        } KnownHeaders[HttpHeaderRequestMaximum];
    } Headers;
    ULONGLONG BytesReceived;
    USHORT EntityChunkCount;
    ULONGLONG pEntityChunks; /* struct http_data_chunk_32 */
    HTTP_RAW_CONNECTION_ID RawConnectionId;
    ULONGLONG pSslInfo; /* NULL (FIXME) */
    USHORT RequestInfoCount;
    ULONGLONG pRequestInfo; /* NULL (FIXME) */
};

194 195 196 197 198 199 200 201 202
#define DECLARE_CRITICAL_SECTION(cs) \
    static CRITICAL_SECTION cs; \
    static CRITICAL_SECTION_DEBUG cs##_debug = \
    { 0, 0, &cs, { &cs##_debug.ProcessLocksList, &cs##_debug.ProcessLocksList }, \
      0, 0, { (DWORD_PTR)(__FILE__ ": " # cs) }}; \
    static CRITICAL_SECTION cs = { &cs##_debug, -1, 0, 0, 0, 0 };

DECLARE_CRITICAL_SECTION(http_cs);

203 204 205
static HANDLE request_thread, request_event;
static BOOL thread_stop;

206 207
static HTTP_REQUEST_ID req_id_counter;

208 209 210 211
struct connection
{
    struct list entry; /* in "connections" below */

212
    SOCKET socket;
213 214 215

    char *buffer;
    unsigned int len, size;
216

217 218 219 220 221 222 223 224 225 226 227
    /* If there is a request fully received and waiting to be read, the
     * "available" parameter will be TRUE. Either there is no queue matching
     * the URL of this request yet ("queue" is NULL), there is a queue but no
     * IRPs have arrived for this request yet ("queue" is non-NULL and "req_id"
     * is HTTP_NULL_ID), or an IRP has arrived but did not provide a large
     * enough buffer to read the whole request ("queue" is non-NULL and
     * "req_id" is not HTTP_NULL_ID).
     *
     * If "available" is FALSE, either we are waiting for a new request
     * ("req_id" is HTTP_NULL_ID), or we are waiting for the user to send a
     * response ("req_id" is not HTTP_NULL_ID). */
228
    BOOL available;
229
    struct request_queue *queue;
230
    HTTP_REQUEST_ID req_id;
231 232 233

    /* Things we already parsed out of the request header in parse_request().
     * These are valid only if "available" is TRUE. */
234 235 236 237 238
    unsigned int req_len;
    HTTP_VERB verb;
    HTTP_VERSION version;
    const char *url, *host;
    ULONG unk_verb_len, url_len, content_len;
239 240 241 242
};

static struct list connections = LIST_INIT(connections);

243 244 245
struct request_queue
{
    struct list entry;
246
    LIST_ENTRY irp_queue;
247 248
    HTTP_URL_CONTEXT context;
    char *url;
249
    SOCKET socket;
250 251 252 253
};

static struct list request_queues = LIST_INIT(request_queues);

254
static void accept_connection(SOCKET socket)
255 256 257
{
    struct connection *conn;
    ULONG true = 1;
258
    SOCKET peer;
259

260
    if ((peer = accept(socket, NULL, NULL)) == INVALID_SOCKET)
261 262 263 264 265 266 267 268 269
        return;

    if (!(conn = heap_alloc_zero(sizeof(*conn))))
    {
        ERR("Failed to allocate memory.\n");
        shutdown(peer, SD_BOTH);
        closesocket(peer);
        return;
    }
270 271 272 273 274 275 276 277 278
    if (!(conn->buffer = heap_alloc(8192)))
    {
        ERR("Failed to allocate buffer memory.\n");
        heap_free(conn);
        shutdown(peer, SD_BOTH);
        closesocket(peer);
        return;
    }
    conn->size = 8192;
279 280 281 282 283 284 285 286
    WSAEventSelect(peer, request_event, FD_READ | FD_CLOSE);
    ioctlsocket(peer, FIONBIO, &true);
    conn->socket = peer;
    list_add_head(&connections, &conn->entry);
}

static void close_connection(struct connection *conn)
{
287
    heap_free(conn->buffer);
288 289 290 291 292 293
    shutdown(conn->socket, SD_BOTH);
    closesocket(conn->socket);
    list_remove(&conn->entry);
    heap_free(conn);
}

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
static HTTP_VERB parse_verb(const char *verb, int len)
{
    static const char *const verbs[] =
    {
        "OPTIONS",
        "GET",
        "HEAD",
        "POST",
        "PUT",
        "DELETE",
        "TRACE",
        "CONNECT",
        "TRACK",
        "MOVE",
        "COPY",
        "PROPFIND",
        "PROPPATCH",
        "MKCOL",
        "LOCK",
        "UNLOCK",
        "SEARCH",
    };
    unsigned int i;

    for (i = 0; i < ARRAY_SIZE(verbs); ++i)
    {
        if (!strncmp(verb, verbs[i], len))
            return HttpVerbOPTIONS + i;
    }
    return HttpVerbUnknown;
}

/* Return the length of a token, as defined in RFC 2616 section 2.2. */
static int parse_token(const char *str, const char *end)
{
    const char *p;
    for (p = str; !end || p < end; ++p)
    {
        if (!isgraph(*p) || strchr("()<>@,;:\\\"/[]?={}", *p))
            break;
    }
    return p - str;
}

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
static HTTP_HEADER_ID parse_header_name(const char *header, int len)
{
    static const char *const headers[] =
    {
        "Cache-Control",
        "Connection",
        "Date",
        "Keep-Alive",
        "Pragma",
        "Trailer",
        "Transfer-Encoding",
        "Upgrade",
        "Via",
        "Warning",
        "Allow",
        "Content-Length",
        "Content-Type",
        "Content-Encoding",
        "Content-Language",
        "Content-Location",
        "Content-MD5",
        "Content-Range",
        "Expires",
        "Last-Modified",
        "Accept",
        "Accept-Charset",
        "Accept-Encoding",
        "Accept-Language",
        "Authorization",
        "Cookie",
        "Expect",
        "From",
        "Host",
        "If-Match",
        "If-Modified-Since",
        "If-None-Match",
        "If-Range",
        "If-Unmodified-Since",
        "Max-Forwards",
        "Proxy-Authorization",
        "Referer",
        "Range",
        "TE",
        "Translate",
        "User-Agent",
    };
    unsigned int i;

    for (i = 0; i < ARRAY_SIZE(headers); ++i)
    {
        if (!strncmp(header, headers[i], len))
            return i;
    }
    return HttpHeaderRequestMaximum;
}

static void parse_header(const char *name, int *name_len, const char **value, int *value_len)
{
    const char *p = name;
    *name_len = parse_token(name, NULL);
    p += *name_len;
    while (*p == ' ' || *p == '\t') ++p;
    ++p; /* skip colon */
    while (*p == ' ' || *p == '\t') ++p;
    *value = p;
    while (isprint(*p) || *p == '\t') ++p;
    while (isspace(*p)) --p; /* strip trailing LWS */
    *value_len = p - *value + 1;
}

408 409
static NTSTATUS complete_irp(struct connection *conn, IRP *irp)
{
410
    static const WCHAR httpW[] = {'h','t','t','p',':','/','/'};
411 412 413
    const struct http_receive_request_params params
            = *(struct http_receive_request_params *)irp->AssociatedIrp.SystemBuffer;
    DWORD irp_size = (params.bits == 32) ? sizeof(struct http_request_32) : sizeof(struct http_request_64);
414
    ULONG cooked_len, host_len, abs_path_len, query_len, chunk_len = 0, offset, processed;
415 416
    IO_STACK_LOCATION *stack = IoGetCurrentIrpStackLocation(irp);
    const DWORD output_len = stack->Parameters.DeviceIoControl.OutputBufferLength;
417 418 419
    const char *p, *name, *value, *host, *abs_path, *query;
    USHORT unk_headers_count = 0, unk_header_idx;
    int name_len, value_len, len;
420
    struct sockaddr_in addr;
421 422 423

    TRACE("Completing IRP %p.\n", irp);

424 425 426
    if (!conn->req_id)
        conn->req_id = ++req_id_counter;

427 428
    /* First calculate the total buffer size needed for this IRP. */

429 430
    if (conn->unk_verb_len)
        irp_size += conn->unk_verb_len + 1;
431
    irp_size += conn->url_len + 1;
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    /* cooked URL */
    if (conn->url[0] == '/')
    {
        p = host = conn->host;
        while (isgraph(*p)) ++p;
        host_len = p - conn->host;
        abs_path = conn->url;
        abs_path_len = conn->url_len;
    }
    else
    {
        host = conn->url + 7;
        abs_path = strchr(host, '/');
        host_len = abs_path - host;
        abs_path_len = (conn->url + conn->url_len) - abs_path;
    }
    if ((query = memchr(abs_path, '?', abs_path_len)))
    {
        query_len = (abs_path + abs_path_len) - query;
        abs_path_len = query - abs_path;
    }
    else
        query_len = 0;
    cooked_len = (7 /* scheme */ + host_len + abs_path_len + query_len) * sizeof(WCHAR);
    irp_size += cooked_len + sizeof(WCHAR);

459 460 461
    /* addresses */
    irp_size += 2 * sizeof(addr);

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    /* headers */
    p = strstr(conn->buffer, "\r\n") + 2;
    while (memcmp(p, "\r\n", 2))
    {
        name = p;
        parse_header(name, &name_len, &value, &value_len);
        if (parse_header_name(name, name_len) == HttpHeaderRequestMaximum)
        {
            irp_size += name_len + 1;
            ++unk_headers_count;
        }
        irp_size += value_len + 1;
        p = strstr(p, "\r\n") + 2;
    }
    p += 2;

    if (params.bits == 32)
        irp_size += unk_headers_count * sizeof(struct http_unknown_header_32);
    else
        irp_size += unk_headers_count * sizeof(struct http_unknown_header_64);

483 484 485 486 487 488 489 490 491 492 493
    TRACE("Need %u bytes, have %u.\n", irp_size, output_len);
    irp->IoStatus.Information = irp_size;

    memset(irp->AssociatedIrp.SystemBuffer, 0, output_len);

    if (output_len < irp_size)
    {
        if (params.bits == 32)
        {
            struct http_request_32 *req = irp->AssociatedIrp.SystemBuffer;
            req->ConnectionId = (ULONG_PTR)conn;
494
            req->RequestId = conn->req_id;
495 496 497 498 499
        }
        else
        {
            struct http_request_64 *req = irp->AssociatedIrp.SystemBuffer;
            req->ConnectionId = (ULONG_PTR)conn;
500
            req->RequestId = conn->req_id;
501 502 503 504 505 506 507
        }
        return STATUS_BUFFER_OVERFLOW;
    }

    if (params.bits == 32)
    {
        struct http_request_32 *req = irp->AssociatedIrp.SystemBuffer;
508
        struct http_unknown_header_32 *unk_headers = NULL;
509
        char *buffer = irp->AssociatedIrp.SystemBuffer;
510
        struct http_data_chunk_32 *chunk = NULL;
511 512 513 514

        offset = sizeof(*req);

        req->ConnectionId = (ULONG_PTR)conn;
515
        req->RequestId = conn->req_id;
516 517 518
        req->UrlContext = conn->queue->context;
        req->Version = conn->version;
        req->Verb = conn->verb;
519
        req->UnknownVerbLength = conn->unk_verb_len;
520
        req->RawUrlLength = conn->url_len;
521 522 523 524 525 526 527 528 529

        if (conn->unk_verb_len)
        {
            req->pUnknownVerb = params.addr + offset;
            memcpy(buffer + offset, conn->buffer, conn->unk_verb_len);
            offset += conn->unk_verb_len;
            buffer[offset++] = 0;
        }

530 531 532 533 534
        req->pRawUrl = params.addr + offset;
        memcpy(buffer + offset, conn->url, conn->url_len);
        offset += conn->url_len;
        buffer[offset++] = 0;

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        req->CookedUrl.FullUrlLength = cooked_len;
        req->CookedUrl.HostLength = host_len * sizeof(WCHAR);
        req->CookedUrl.AbsPathLength = abs_path_len * sizeof(WCHAR);
        req->CookedUrl.QueryStringLength = query_len * sizeof(WCHAR);
        req->CookedUrl.pFullUrl = params.addr + offset;
        req->CookedUrl.pHost = req->CookedUrl.pFullUrl + 7 * sizeof(WCHAR);
        req->CookedUrl.pAbsPath = req->CookedUrl.pHost + host_len * sizeof(WCHAR);
        if (query)
            req->CookedUrl.pQueryString = req->CookedUrl.pAbsPath + abs_path_len * sizeof(WCHAR);

        memcpy(buffer + offset, httpW, sizeof(httpW));
        offset += 7 * sizeof(WCHAR);
        MultiByteToWideChar(CP_ACP, 0, host, host_len, (WCHAR *)(buffer + offset), host_len * sizeof(WCHAR));
        offset += host_len * sizeof(WCHAR);
        MultiByteToWideChar(CP_ACP, 0, abs_path, abs_path_len + query_len,
                (WCHAR *)(buffer + offset), (abs_path_len + query_len) * sizeof(WCHAR));
        offset += (abs_path_len + query_len) * sizeof(WCHAR);
        buffer[offset++] = 0;
        buffer[offset++] = 0;

555 556 557 558 559 560 561 562 563 564 565 566
        req->Address.pRemoteAddress = params.addr + offset;
        len = sizeof(addr);
        getpeername(conn->socket, (struct sockaddr *)&addr, &len);
        memcpy(buffer + offset, &addr, sizeof(addr));
        offset += sizeof(addr);

        req->Address.pLocalAddress = params.addr + offset;
        len = sizeof(addr);
        getsockname(conn->socket, (struct sockaddr *)&addr, &len);
        memcpy(buffer + offset, &addr, sizeof(addr));
        offset += sizeof(addr);

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
        req->Headers.UnknownHeaderCount = unk_headers_count;
        if (unk_headers_count)
        {
            req->Headers.pUnknownHeaders = params.addr + offset;
            unk_headers = (struct http_unknown_header_32 *)(buffer + offset);
            offset += unk_headers_count * sizeof(*unk_headers);
        }

        unk_header_idx = 0;
        p = strstr(conn->buffer, "\r\n") + 2;
        while (memcmp(p, "\r\n", 2))
        {
            HTTP_HEADER_ID id;

            name = p;
            parse_header(name, &name_len, &value, &value_len);
            if ((id = parse_header_name(name, name_len)) == HttpHeaderRequestMaximum)
            {
                unk_headers[unk_header_idx].NameLength = name_len;
                unk_headers[unk_header_idx].RawValueLength = value_len;
                unk_headers[unk_header_idx].pName = params.addr + offset;
                memcpy(buffer + offset, name, name_len);
                offset += name_len;
                buffer[offset++] = 0;
                unk_headers[unk_header_idx].pRawValue = params.addr + offset;
                memcpy(buffer + offset, value, value_len);
                offset += value_len;
                buffer[offset++] = 0;
                ++unk_header_idx;
            }
            else
            {
                req->Headers.KnownHeaders[id].RawValueLength = value_len;
                req->Headers.KnownHeaders[id].pRawValue = params.addr + offset;
                memcpy(buffer + offset, value, value_len);
                offset += value_len;
                buffer[offset++] = 0;
            }
            p = strstr(p, "\r\n") + 2;
        }
        p += 2;

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
        if (irp_size + sizeof(*chunk) < output_len && (params.flags & HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY))
            chunk_len = min(conn->content_len, output_len - (irp_size + sizeof(*chunk)));
        if (chunk_len)
        {
            req->EntityChunkCount = 1;
            req->pEntityChunks = params.addr + offset;
            chunk = (struct http_data_chunk_32 *)(buffer + offset);
            offset += sizeof(*chunk);
            chunk->DataChunkType = HttpDataChunkFromMemory;
            chunk->FromMemory.BufferLength = chunk_len;
            chunk->FromMemory.pBuffer = params.addr + offset;
            memcpy(buffer + offset, p, chunk_len);
            offset += chunk_len;

            irp->IoStatus.Information = irp_size + sizeof(*chunk) + chunk_len;
        }

        if (chunk_len < conn->content_len)
            req->Flags |= HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS;

629 630 631 632 633
        req->BytesReceived = conn->req_len;
    }
    else
    {
        struct http_request_64 *req = irp->AssociatedIrp.SystemBuffer;
634
        struct http_unknown_header_64 *unk_headers = NULL;
635
        char *buffer = irp->AssociatedIrp.SystemBuffer;
636
        struct http_data_chunk_64 *chunk = NULL;
637 638 639 640

        offset = sizeof(*req);

        req->ConnectionId = (ULONG_PTR)conn;
641
        req->RequestId = conn->req_id;
642 643 644
        req->UrlContext = conn->queue->context;
        req->Version = conn->version;
        req->Verb = conn->verb;
645
        req->UnknownVerbLength = conn->unk_verb_len;
646
        req->RawUrlLength = conn->url_len;
647 648 649 650 651 652 653 654 655

        if (conn->unk_verb_len)
        {
            req->pUnknownVerb = params.addr + offset;
            memcpy(buffer + offset, conn->buffer, conn->unk_verb_len);
            offset += conn->unk_verb_len;
            buffer[offset++] = 0;
        }

656 657 658 659 660
        req->pRawUrl = params.addr + offset;
        memcpy(buffer + offset, conn->url, conn->url_len);
        offset += conn->url_len;
        buffer[offset++] = 0;

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
        req->CookedUrl.FullUrlLength = cooked_len;
        req->CookedUrl.HostLength = host_len * sizeof(WCHAR);
        req->CookedUrl.AbsPathLength = abs_path_len * sizeof(WCHAR);
        req->CookedUrl.QueryStringLength = query_len * sizeof(WCHAR);
        req->CookedUrl.pFullUrl = params.addr + offset;
        req->CookedUrl.pHost = req->CookedUrl.pFullUrl + 7 * sizeof(WCHAR);
        req->CookedUrl.pAbsPath = req->CookedUrl.pHost + host_len * sizeof(WCHAR);
        if (query)
            req->CookedUrl.pQueryString = req->CookedUrl.pAbsPath + abs_path_len * sizeof(WCHAR);

        memcpy(buffer + offset, httpW, sizeof(httpW));
        offset += 7 * sizeof(WCHAR);
        MultiByteToWideChar(CP_ACP, 0, host, host_len, (WCHAR *)(buffer + offset), host_len * sizeof(WCHAR));
        offset += host_len * sizeof(WCHAR);
        MultiByteToWideChar(CP_ACP, 0, abs_path, abs_path_len + query_len,
                (WCHAR *)(buffer + offset), (abs_path_len + query_len) * sizeof(WCHAR));
        offset += (abs_path_len + query_len) * sizeof(WCHAR);
        buffer[offset++] = 0;
        buffer[offset++] = 0;

681 682 683 684 685 686 687 688 689 690 691 692
        req->Address.pRemoteAddress = params.addr + offset;
        len = sizeof(addr);
        getpeername(conn->socket, (struct sockaddr *)&addr, &len);
        memcpy(buffer + offset, &addr, sizeof(addr));
        offset += sizeof(addr);

        req->Address.pLocalAddress = params.addr + offset;
        len = sizeof(addr);
        getsockname(conn->socket, (struct sockaddr *)&addr, &len);
        memcpy(buffer + offset, &addr, sizeof(addr));
        offset += sizeof(addr);

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
        req->Headers.UnknownHeaderCount = unk_headers_count;
        if (unk_headers_count)
        {
            req->Headers.pUnknownHeaders = params.addr + offset;
            unk_headers = (struct http_unknown_header_64 *)(buffer + offset);
            offset += unk_headers_count * sizeof(*unk_headers);
        }

        unk_header_idx = 0;
        p = strstr(conn->buffer, "\r\n") + 2;
        while (memcmp(p, "\r\n", 2))
        {
            HTTP_HEADER_ID id;

            name = p;
            parse_header(name, &name_len, &value, &value_len);
            if ((id = parse_header_name(name, name_len)) == HttpHeaderRequestMaximum)
            {
                unk_headers[unk_header_idx].NameLength = name_len;
                unk_headers[unk_header_idx].RawValueLength = value_len;
                unk_headers[unk_header_idx].pName = params.addr + offset;
                memcpy(buffer + offset, name, name_len);
                offset += name_len;
                buffer[offset++] = 0;
                unk_headers[unk_header_idx].pRawValue = params.addr + offset;
                memcpy(buffer + offset, value, value_len);
                offset += value_len;
                buffer[offset++] = 0;
                ++unk_header_idx;
            }
            else
            {
                req->Headers.KnownHeaders[id].RawValueLength = value_len;
                req->Headers.KnownHeaders[id].pRawValue = params.addr + offset;
                memcpy(buffer + offset, value, value_len);
                offset += value_len;
                buffer[offset++] = 0;
            }
            p = strstr(p, "\r\n") + 2;
        }
        p += 2;

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
        if (irp_size + sizeof(*chunk) < output_len && (params.flags & HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY))
            chunk_len = min(conn->content_len, output_len - (irp_size + sizeof(*chunk)));
        if (chunk_len)
        {
            req->EntityChunkCount = 1;
            req->pEntityChunks = params.addr + offset;
            chunk = (struct http_data_chunk_64 *)(buffer + offset);
            offset += sizeof(*chunk);
            chunk->DataChunkType = HttpDataChunkFromMemory;
            chunk->FromMemory.BufferLength = chunk_len;
            chunk->FromMemory.pBuffer = params.addr + offset;
            memcpy(buffer + offset, p, chunk_len);
            offset += chunk_len;

            irp->IoStatus.Information = irp_size + sizeof(*chunk) + chunk_len;
        }

        if (chunk_len < conn->content_len)
            req->Flags |= HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS;

755 756 757 758 759 760
        req->BytesReceived = conn->req_len;
    }

    assert(offset == irp->IoStatus.Information);

    conn->available = FALSE;
761 762 763 764
    processed = conn->req_len - (conn->content_len - chunk_len);
    memmove(conn->buffer, conn->buffer + processed, conn->len - processed);
    conn->content_len -= chunk_len;
    conn->len -= processed;
765 766 767 768

    return STATUS_SUCCESS;
}

769 770 771 772 773 774 775 776 777 778 779 780
/* Complete an IOCTL_HTTP_RECEIVE_REQUEST IRP if there is one to complete. */
static void try_complete_irp(struct connection *conn)
{
    LIST_ENTRY *entry;
    if (conn->queue && (entry = RemoveHeadList(&conn->queue->irp_queue)) != &conn->queue->irp_queue)
    {
        IRP *irp = CONTAINING_RECORD(entry, IRP, Tail.Overlay.ListEntry);
        irp->IoStatus.Status = complete_irp(conn, irp);
        IoCompleteRequest(irp, IO_NO_INCREMENT);
    }
}

781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
/* Return 1 if str matches expect, 0 if str is incomplete, -1 if they don't match. */
static int compare_exact(const char *str, const char *expect, const char *end)
{
    while (*expect)
    {
        if (str >= end) return 0;
        if (*str++ != *expect++) return -1;
    }
    return 1;
}

static int parse_number(const char *str, const char **endptr, const char *end)
{
    int n = 0;
    while (str < end && isdigit(*str))
        n = n * 10 + (*str++ - '0');
    *endptr = str;
    return n;
}

801 802 803 804 805 806 807
static BOOL host_matches(const struct connection *conn, const struct request_queue *queue)
{
    const char *conn_host = (conn->url[0] == '/') ? conn->host : conn->url + 7;

    return !memicmp(queue->url + 7, conn_host, strlen(queue->url) - 8 /* strip final slash */);
}

808 809 810 811 812
/* Upon receiving a request, parse it to ensure that it is a valid HTTP request,
 * and mark down some information that we will use later. Returns 1 if we parsed
 * a complete request, 0 if incomplete, -1 if invalid. */
static int parse_request(struct connection *conn)
{
813
    const char *const req = conn->buffer, *const end = conn->buffer + conn->len;
814
    struct request_queue *queue;
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    const char *p = req, *q;
    int len, ret;

    if (!conn->len) return 0;

    TRACE("%s\n", wine_dbgstr_an(conn->buffer, conn->len));

    len = parse_token(p, end);
    if (p + len >= end) return 0;
    if (!len || p[len] != ' ') return -1;

    /* verb */
    if ((conn->verb = parse_verb(p, len)) == HttpVerbUnknown)
        conn->unk_verb_len = len;
    p += len + 1;

    TRACE("Got verb %u (%s).\n", conn->verb, debugstr_an(req, len));

    /* URL */
    conn->url = p;
    while (p < end && isgraph(*p)) ++p;
    conn->url_len = p - conn->url;
    if (p >= end) return 0;
    if (!conn->url_len) return -1;

    TRACE("Got URI %s.\n", debugstr_an(conn->url, conn->url_len));

    /* version */
    if ((ret = compare_exact(p, " HTTP/", end)) <= 0) return ret;
    p += 6;
    conn->version.MajorVersion = parse_number(p, &q, end);
    if (q >= end) return 0;
    if (q == p || *q != '.') return -1;
    p = q + 1;
    if (p >= end) return 0;
    conn->version.MinorVersion = parse_number(p, &q, end);
    if (q >= end) return 0;
    if (q == p) return -1;
    p = q;
    if ((ret = compare_exact(p, "\r\n", end)) <= 0) return ret;
    p += 2;

    TRACE("Got version %hu.%hu.\n", conn->version.MajorVersion, conn->version.MinorVersion);

    /* headers */
    conn->host = NULL;
    conn->content_len = 0;
    for (;;)
    {
        const char *name = p;

        if (!(ret = compare_exact(p, "\r\n", end))) return 0;
        else if (ret > 0) break;

        len = parse_token(p, end);
        if (p + len >= end) return 0;
        if (!len) return -1;
        p += len;
        while (p < end && (*p == ' ' || *p == '\t')) ++p;
        if (p >= end) return 0;
        if (*p != ':') return -1;
        ++p;
        while (p < end && (*p == ' ' || *p == '\t')) ++p;

        TRACE("Got %s header.\n", debugstr_an(name, len));

        if (!strncmp(name, "Host", len))
            conn->host = p;
        else if (!strncmp(name, "Content-Length", len))
        {
            conn->content_len = parse_number(p, &q, end);
            if (q >= end) return 0;
            if (q == p) return -1;
        }
        else if (!strncmp(name, "Transfer-Encoding", len))
            FIXME("Unhandled Transfer-Encoding header.\n");
        while (p < end && (isprint(*p) || *p == '\t')) ++p;
        if ((ret = compare_exact(p, "\r\n", end)) <= 0) return ret;
        p += 2;
    }
    p += 2;
    if (conn->url[0] == '/' && !conn->host) return -1;

    if (end - p < conn->content_len) return 0;

    conn->req_len = (p - req) + conn->content_len;

    TRACE("Received a full request, length %u bytes.\n", conn->req_len);

904 905 906 907 908 909 910 911 912 913 914 915
    conn->queue = NULL;
    /* Find a queue which can receive this request. */
    LIST_FOR_EACH_ENTRY(queue, &request_queues, struct request_queue, entry)
    {
        if (host_matches(conn, queue))
        {
            TRACE("Assigning request to queue %p.\n", queue);
            conn->queue = queue;
            break;
        }
    }

916 917 918 919
    /* Stop selecting on incoming data until a response is queued. */
    WSAEventSelect(conn->socket, request_event, FD_CLOSE);

    conn->available = TRUE;
920
    try_complete_irp(conn);
921

922
    return 1;
923 924
}

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
static void format_date(char *buffer)
{
    static const char day_names[7][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    static const char month_names[12][4] =
            {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    SYSTEMTIME date;
    GetSystemTime(&date);
    sprintf(buffer + strlen(buffer), "Date: %s, %02u %s %u %02u:%02u:%02u GMT\r\n",
            day_names[date.wDayOfWeek], date.wDay, month_names[date.wMonth - 1],
            date.wYear, date.wHour, date.wMinute, date.wSecond);
}

/* Send a 400 Bad Request response. */
static void send_400(struct connection *conn)
{
    static const char response_header[] = "HTTP/1.1 400 Bad Request\r\n";
    static const char response_body[] =
        "Content-Type: text/html; charset=utf-8\r\n"
        "Content-Language: en\r\n"
        "Connection: close\r\n";
    char buffer[sizeof(response_header) + sizeof(response_body) + 37];

    strcpy(buffer, response_header);
    format_date(buffer + strlen(buffer));
    strcat(buffer, response_body);
    if (send(conn->socket, buffer, strlen(buffer), 0) < 0)
        ERR("Failed to send 400 response, error %u.\n", WSAGetLastError());
}

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
static void receive_data(struct connection *conn)
{
    int len, ret;

    /* We might be waiting for an IRP, but always call recv() anyway, since we
     * might have been woken up by the socket closing. */
    if ((len = recv(conn->socket, conn->buffer + conn->len, conn->size - conn->len, 0)) <= 0)
    {
        if (WSAGetLastError() == WSAEWOULDBLOCK)
            return; /* nothing to receive */
        else if (!len)
            TRACE("Connection was shut down by peer.\n");
        else
            ERR("Got error %u; shutting down connection.\n", WSAGetLastError());
        close_connection(conn);
        return;
    }
    conn->len += len;

973 974
    if (conn->available)
        return; /* waiting for an HttpReceiveHttpRequest() call */
975 976
    if (conn->req_id != HTTP_NULL_ID)
        return; /* waiting for an HttpSendHttpResponse() call */
977

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    TRACE("Received %u bytes of data.\n", len);

    if (!(ret = parse_request(conn)))
    {
        ULONG available;
        ioctlsocket(conn->socket, FIONREAD, &available);
        if (available)
        {
            TRACE("%u more bytes of data available, trying with larger buffer.\n", available);
            if (!(conn->buffer = heap_realloc(conn->buffer, conn->len + available)))
            {
                ERR("Failed to allocate %u bytes of memory.\n", conn->len + available);
                close_connection(conn);
                return;
            }
            conn->size = conn->len + available;

            if ((len = recv(conn->socket, conn->buffer + conn->len, conn->size - conn->len, 0)) < 0)
            {
                ERR("Got error %u; shutting down connection.\n", WSAGetLastError());
                close_connection(conn);
                return;
            }
            TRACE("Received %u bytes of data.\n", len);
            conn->len += len;
            ret = parse_request(conn);
        }
    }
    if (!ret)
        TRACE("Request is incomplete, waiting for more data.\n");
    else if (ret < 0)
    {
        WARN("Failed to parse request; shutting down connection.\n");
1011
        send_400(conn);
1012 1013 1014 1015
        close_connection(conn);
    }
}

1016 1017
static DWORD WINAPI request_thread_proc(void *arg)
{
1018
    struct connection *conn, *cursor;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    struct request_queue *queue;

    TRACE("Starting request thread.\n");

    while (!WaitForSingleObject(request_event, INFINITE))
    {
        EnterCriticalSection(&http_cs);

        LIST_FOR_EACH_ENTRY(queue, &request_queues, struct request_queue, entry)
        {
            if (queue->socket != -1)
                accept_connection(queue->socket);
        }

1033 1034 1035 1036 1037
        LIST_FOR_EACH_ENTRY_SAFE(conn, cursor, &connections, struct connection, entry)
        {
            receive_data(conn);
        }

1038 1039 1040 1041 1042 1043 1044
        LeaveCriticalSection(&http_cs);
    }

    TRACE("Stopping request thread.\n");

    return 0;
}
1045 1046 1047 1048

static NTSTATUS http_add_url(struct request_queue *queue, IRP *irp)
{
    const struct http_add_url_params *params = irp->AssociatedIrp.SystemBuffer;
1049
    struct sockaddr_in addr;
1050
    struct connection *conn;
1051
    unsigned int count = 0;
1052
    char *url, *endptr;
1053
    ULONG true = 1;
1054
    const char *p;
1055
    SOCKET s;
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

    TRACE("host %s, context %s.\n", debugstr_a(params->url), wine_dbgstr_longlong(params->context));

    if (!strncmp(params->url, "https://", 8))
    {
        FIXME("HTTPS is not implemented.\n");
        return STATUS_NOT_IMPLEMENTED;
    }
    else if (strncmp(params->url, "http://", 7) || !strchr(params->url + 7, ':')
            || params->url[strlen(params->url) - 1] != '/')
        return STATUS_INVALID_PARAMETER;
1067
    if (!(addr.sin_port = htons(strtol(strchr(params->url + 7, ':') + 1, &endptr, 10))) || *endptr != '/')
1068 1069
        return STATUS_INVALID_PARAMETER;

1070
    if (!(url = heap_alloc(strlen(params->url)+1)))
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
        return STATUS_NO_MEMORY;
    strcpy(url, params->url);

    for (p = url; *p; ++p)
        if (*p == '/') ++count;
    if (count > 3)
        FIXME("Binding to relative URIs is not implemented; binding to all URIs instead.\n");

    EnterCriticalSection(&http_cs);

    if (queue->url && !strcmp(queue->url, url))
    {
        LeaveCriticalSection(&http_cs);
        heap_free(url);
        return STATUS_OBJECT_NAME_COLLISION;
    }
    else if (queue->url)
    {
        FIXME("Binding to multiple URLs is not implemented.\n");
        LeaveCriticalSection(&http_cs);
        heap_free(url);
        return STATUS_NOT_IMPLEMENTED;
    }

1095
    if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
    {
        ERR("Failed to create socket, error %u.\n", WSAGetLastError());
        LeaveCriticalSection(&http_cs);
        heap_free(url);
        return STATUS_UNSUCCESSFUL;
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.S_un.S_addr = INADDR_ANY;
    if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1)
    {
        LeaveCriticalSection(&http_cs);
        closesocket(s);
        heap_free(url);
1110 1111 1112 1113 1114 1115
        if (WSAGetLastError() == WSAEADDRINUSE)
        {
            WARN("Address %s is already in use.\n", debugstr_a(params->url));
            return STATUS_SHARING_VIOLATION;
        }
        ERR("Failed to bind socket, error %u.\n", WSAGetLastError());
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
        return STATUS_UNSUCCESSFUL;
    }

    if (listen(s, SOMAXCONN) == -1)
    {
        ERR("Failed to listen to port %u, error %u.\n", addr.sin_port, WSAGetLastError());
        LeaveCriticalSection(&http_cs);
        closesocket(s);
        heap_free(url);
        return STATUS_OBJECT_NAME_COLLISION;
    }

    ioctlsocket(s, FIONBIO, &true);
    WSAEventSelect(s, request_event, FD_ACCEPT);
    queue->socket = s;
1131 1132 1133
    queue->url = url;
    queue->context = params->context;

1134 1135 1136 1137
    /* See if any pending requests now match this queue. */
    LIST_FOR_EACH_ENTRY(conn, &connections, struct connection, entry)
    {
        if (conn->available && !conn->queue && host_matches(conn, queue))
1138
        {
1139
            conn->queue = queue;
1140 1141
            try_complete_irp(conn);
        }
1142 1143
    }

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    LeaveCriticalSection(&http_cs);

    return STATUS_SUCCESS;
}

static NTSTATUS http_remove_url(struct request_queue *queue, IRP *irp)
{
    const char *url = irp->AssociatedIrp.SystemBuffer;

    TRACE("host %s.\n", debugstr_a(url));

    EnterCriticalSection(&http_cs);

    if (!queue->url || strcmp(url, queue->url))
    {
        LeaveCriticalSection(&http_cs);
        return STATUS_OBJECT_NAME_NOT_FOUND;
    }
    heap_free(queue->url);
    queue->url = NULL;

    LeaveCriticalSection(&http_cs);
    return STATUS_SUCCESS;
}

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
static struct connection *get_connection(HTTP_REQUEST_ID req_id)
{
    struct connection *conn;

    LIST_FOR_EACH_ENTRY(conn, &connections, struct connection, entry)
    {
        if (conn->req_id == req_id)
            return conn;
    }
    return NULL;
}

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
static NTSTATUS http_receive_request(struct request_queue *queue, IRP *irp)
{
    const struct http_receive_request_params *params = irp->AssociatedIrp.SystemBuffer;
    struct connection *conn;
    NTSTATUS ret;

    TRACE("addr %s, id %s, flags %#x, bits %u.\n", wine_dbgstr_longlong(params->addr),
            wine_dbgstr_longlong(params->id), params->flags, params->bits);

    EnterCriticalSection(&http_cs);

1192
    if ((conn = get_connection(params->id)) && conn->available && conn->queue == queue)
1193
    {
1194 1195 1196
        ret = complete_irp(conn, irp);
        LeaveCriticalSection(&http_cs);
        return ret;
1197 1198
    }

1199
    if (params->id == HTTP_NULL_ID)
1200 1201 1202
    {
        TRACE("Queuing IRP %p.\n", irp);
        InsertTailList(&queue->irp_queue, &irp->Tail.Overlay.ListEntry);
1203
        ret = STATUS_PENDING;
1204
    }
1205 1206 1207
    else
        ret = STATUS_CONNECTION_INVALID;

1208 1209
    LeaveCriticalSection(&http_cs);

1210
    return ret;
1211 1212
}

1213 1214 1215 1216 1217 1218 1219 1220 1221
static NTSTATUS http_send_response(struct request_queue *queue, IRP *irp)
{
    const struct http_response *response = irp->AssociatedIrp.SystemBuffer;
    struct connection *conn;

    TRACE("id %s, len %d.\n", wine_dbgstr_longlong(response->id), response->len);

    EnterCriticalSection(&http_cs);

1222
    if ((conn = get_connection(response->id)))
1223
    {
1224
        if (send(conn->socket, response->buffer, response->len, 0) >= 0)
1225
        {
1226 1227 1228 1229 1230 1231 1232
            if (conn->content_len)
            {
                /* Discard whatever entity body is left. */
                memmove(conn->buffer, conn->buffer + conn->content_len, conn->len - conn->content_len);
                conn->len -= conn->content_len;
            }

1233 1234 1235 1236 1237 1238
            conn->queue = NULL;
            conn->req_id = HTTP_NULL_ID;
            WSAEventSelect(conn->socket, request_event, FD_READ | FD_CLOSE);
            irp->IoStatus.Information = response->len;
            /* We might have another request already in the buffer. */
            if (parse_request(conn) < 0)
1239
            {
1240 1241
                WARN("Failed to parse request; shutting down connection.\n");
                send_400(conn);
1242 1243 1244
                close_connection(conn);
            }
        }
1245 1246 1247 1248 1249 1250 1251 1252
        else
        {
            ERR("Got error %u; shutting down connection.\n", WSAGetLastError());
            close_connection(conn);
        }

        LeaveCriticalSection(&http_cs);
        return STATUS_SUCCESS;
1253 1254 1255 1256 1257 1258
    }

    LeaveCriticalSection(&http_cs);
    return STATUS_CONNECTION_INVALID;
}

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
static NTSTATUS http_receive_body(struct request_queue *queue, IRP *irp)
{
    const struct http_receive_body_params *params = irp->AssociatedIrp.SystemBuffer;
    IO_STACK_LOCATION *stack = IoGetCurrentIrpStackLocation(irp);
    const DWORD output_len = stack->Parameters.DeviceIoControl.OutputBufferLength;
    struct connection *conn;
    NTSTATUS ret;

    TRACE("id %s, bits %u.\n", wine_dbgstr_longlong(params->id), params->bits);

    EnterCriticalSection(&http_cs);

    if ((conn = get_connection(params->id)))
    {
        TRACE("%u bits remaining.\n", conn->content_len);

        if (conn->content_len)
        {
            ULONG len = min(conn->content_len, output_len);
            memcpy(irp->AssociatedIrp.SystemBuffer, conn->buffer, len);
            memmove(conn->buffer, conn->buffer + len, conn->len - len);
            conn->content_len -= len;
            conn->len -= len;

            irp->IoStatus.Information = len;
            ret = STATUS_SUCCESS;
        }
        else
            ret = STATUS_END_OF_FILE;
    }
    else
        ret = STATUS_CONNECTION_INVALID;

    LeaveCriticalSection(&http_cs);

    return ret;
}

1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
static NTSTATUS WINAPI dispatch_ioctl(DEVICE_OBJECT *device, IRP *irp)
{
    IO_STACK_LOCATION *stack = IoGetCurrentIrpStackLocation(irp);
    struct request_queue *queue = stack->FileObject->FsContext;
    NTSTATUS ret;

    switch (stack->Parameters.DeviceIoControl.IoControlCode)
    {
    case IOCTL_HTTP_ADD_URL:
        ret = http_add_url(queue, irp);
        break;
    case IOCTL_HTTP_REMOVE_URL:
        ret = http_remove_url(queue, irp);
        break;
1311 1312 1313
    case IOCTL_HTTP_RECEIVE_REQUEST:
        ret = http_receive_request(queue, irp);
        break;
1314 1315 1316
    case IOCTL_HTTP_SEND_RESPONSE:
        ret = http_send_response(queue, irp);
        break;
1317 1318 1319
    case IOCTL_HTTP_RECEIVE_BODY:
        ret = http_receive_body(queue, irp);
        break;
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
    default:
        FIXME("Unhandled ioctl %#x.\n", stack->Parameters.DeviceIoControl.IoControlCode);
        ret = STATUS_NOT_IMPLEMENTED;
    }

    if (ret != STATUS_PENDING)
    {
        irp->IoStatus.Status = ret;
        IoCompleteRequest(irp, IO_NO_INCREMENT);
    }
    else
        IoMarkIrpPending(irp);
    return ret;
}

1335 1336
static NTSTATUS WINAPI dispatch_create(DEVICE_OBJECT *device, IRP *irp)
{
1337 1338 1339 1340 1341 1342
    IO_STACK_LOCATION *stack = IoGetCurrentIrpStackLocation(irp);
    struct request_queue *queue;

    if (!(queue = heap_alloc_zero(sizeof(*queue))))
        return STATUS_NO_MEMORY;
    stack->FileObject->FsContext = queue;
1343
    InitializeListHead(&queue->irp_queue);
1344 1345 1346 1347 1348 1349 1350

    EnterCriticalSection(&http_cs);
    list_add_head(&request_queues, &queue->entry);
    LeaveCriticalSection(&http_cs);

    TRACE("Created queue %p.\n", queue);

1351 1352 1353 1354 1355
    irp->IoStatus.Status = STATUS_SUCCESS;
    IoCompleteRequest(irp, IO_NO_INCREMENT);
    return STATUS_SUCCESS;
}

1356 1357 1358 1359
static void close_queue(struct request_queue *queue)
{
    EnterCriticalSection(&http_cs);
    list_remove(&queue->entry);
1360 1361 1362 1363 1364
    if (queue->socket != -1)
    {
        shutdown(queue->socket, SD_BOTH);
        closesocket(queue->socket);
    }
1365 1366
    LeaveCriticalSection(&http_cs);

1367
    heap_free(queue->url);
1368 1369 1370
    heap_free(queue);
}

1371 1372
static NTSTATUS WINAPI dispatch_close(DEVICE_OBJECT *device, IRP *irp)
{
1373 1374 1375 1376 1377 1378
    IO_STACK_LOCATION *stack = IoGetCurrentIrpStackLocation(irp);
    struct request_queue *queue = stack->FileObject->FsContext;

    TRACE("Closing queue %p.\n", queue);
    close_queue(queue);

1379 1380 1381 1382 1383 1384 1385
    irp->IoStatus.Status = STATUS_SUCCESS;
    IoCompleteRequest(irp, IO_NO_INCREMENT);
    return STATUS_SUCCESS;
}

static void WINAPI unload(DRIVER_OBJECT *driver)
{
1386
    struct request_queue *queue, *queue_next;
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
    struct connection *conn, *conn_next;

    thread_stop = TRUE;
    SetEvent(request_event);
    WaitForSingleObject(request_thread, INFINITE);
    CloseHandle(request_thread);
    CloseHandle(request_event);

    LIST_FOR_EACH_ENTRY_SAFE(conn, conn_next, &connections, struct connection, entry)
    {
        close_connection(conn);
    }
1399 1400 1401 1402 1403 1404

    LIST_FOR_EACH_ENTRY_SAFE(queue, queue_next, &request_queues, struct request_queue, entry)
    {
        close_queue(queue);
    }

1405 1406
    WSACleanup();

1407 1408 1409 1410
    IoDeleteDevice(device_obj);
    NtClose(directory_obj);
}

1411 1412
NTSTATUS WINAPI DriverEntry(DRIVER_OBJECT *driver, UNICODE_STRING *path)
{
1413 1414 1415 1416
    static const WCHAR device_nameW[] = {'\\','D','e','v','i','c','e','\\','H','t','t','p','\\','R','e','q','Q','u','e','u','e',0};
    static const WCHAR directory_nameW[] = {'\\','D','e','v','i','c','e','\\','H','t','t','p',0};
    OBJECT_ATTRIBUTES attr = {sizeof(attr)};
    UNICODE_STRING string;
1417
    WSADATA wsadata;
1418 1419
    NTSTATUS ret;

1420 1421
    TRACE("driver %p, path %s.\n", driver, debugstr_w(path->Buffer));

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    RtlInitUnicodeString(&string, directory_nameW);
    attr.ObjectName = &string;
    if ((ret = NtCreateDirectoryObject(&directory_obj, 0, &attr)) && ret != STATUS_OBJECT_NAME_COLLISION)
        ERR("Failed to create \\Device\\Http directory, status %#x.\n", ret);

    RtlInitUnicodeString(&string, device_nameW);
    if ((ret = IoCreateDevice(driver, 0, &string, FILE_DEVICE_UNKNOWN, 0, FALSE, &device_obj)))
    {
        ERR("Failed to create request queue device, status %#x.\n", ret);
        NtClose(directory_obj);
        return ret;
    }

    driver->MajorFunction[IRP_MJ_CREATE] = dispatch_create;
    driver->MajorFunction[IRP_MJ_CLOSE] = dispatch_close;
1437
    driver->MajorFunction[IRP_MJ_DEVICE_CONTROL] = dispatch_ioctl;
1438 1439
    driver->DriverUnload = unload;

1440 1441 1442 1443 1444
    WSAStartup(MAKEWORD(1,1), &wsadata);

    request_event = CreateEventW(NULL, FALSE, FALSE, NULL);
    request_thread = CreateThread(NULL, 0, request_thread_proc, NULL, 0, NULL);

1445 1446
    return STATUS_SUCCESS;
}