http.c 199 KB
Newer Older
1
/*
2
 * Wininet - HTTP Implementation
3 4
 *
 * Copyright 1999 Corel Corporation
5
 * Copyright 2002 CodeWeavers Inc.
6
 * Copyright 2002 TransGaming Technologies Inc.
7
 * Copyright 2004 Mike McCormack for CodeWeavers
8
 * Copyright 2005 Aric Stewart for CodeWeavers
9
 * Copyright 2006 Robert Shearman for CodeWeavers
10
 * Copyright 2011 Jacek Caban for CodeWeavers
11 12
 *
 * Ulrich Czekalla
13
 * David Hammerton
14
 *
15 16 17 18 19 20 21 22 23 24 25 26
 * 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
27
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28 29
 */

Patrik Stridvall's avatar
Patrik Stridvall committed
30
#include "config.h"
31
#include "wine/port.h"
Patrik Stridvall's avatar
Patrik Stridvall committed
32

33 34 35 36
#if defined(__MINGW32__) || defined (_MSC_VER)
#include <ws2tcpip.h>
#endif

37
#include <sys/types.h>
Patrik Stridvall's avatar
Patrik Stridvall committed
38 39 40
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
41 42 43
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
44
#include <stdarg.h>
45 46
#include <stdio.h>
#include <stdlib.h>
47 48 49
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
50
#include <time.h>
51
#include <assert.h>
52 53 54
#ifdef HAVE_ZLIB
#  include <zlib.h>
#endif
55

56 57 58 59
#include "windef.h"
#include "winbase.h"
#include "wininet.h"
#include "winerror.h"
60
#include "winternl.h"
61
#define NO_SHLWAPI_STREAM
62 63 64
#define NO_SHLWAPI_REG
#define NO_SHLWAPI_STRFCNS
#define NO_SHLWAPI_GDI
65
#include "shlwapi.h"
66
#include "sspi.h"
67
#include "wincrypt.h"
68 69
#include "winuser.h"
#include "cryptuiapi.h"
70

71
#include "internet.h"
72
#include "wine/debug.h"
73
#include "wine/exception.h"
74
#include "wine/unicode.h"
75

76
WINE_DEFAULT_DEBUG_CHANNEL(wininet);
77

78
static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
79
static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
80 81
static const WCHAR szOK[] = {'O','K',0};
static const WCHAR szDefaultHeader[] = {'H','T','T','P','/','1','.','0',' ','2','0','0',' ','O','K',0};
82
static const WCHAR hostW[] = { 'H','o','s','t',0 };
83
static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
84 85
static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
86
static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
Jacek Caban's avatar
Jacek Caban committed
87
static const WCHAR szGET[] = { 'G','E','T', 0 };
88
static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
89
static const WCHAR szCrLf[] = {'\r','\n', 0};
90

91 92 93 94 95 96 97 98 99 100
static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
static const WCHAR szAge[] = { 'A','g','e',0 };
static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
101
static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
static const WCHAR szContent_Transfer_Encoding[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
static const WCHAR szDate[] = { 'D','a','t','e',0 };
static const WCHAR szFrom[] = { 'F','r','o','m',0 };
static const WCHAR szETag[] = { 'E','T','a','g',0 };
static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
static const WCHAR szUnless_Modified_Since[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
static const WCHAR szURI[] = { 'U','R','I',0 };
static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
static const WCHAR szVary[] = { 'V','a','r','y',0 };
static const WCHAR szVia[] = { 'V','i','a',0 };
static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };

#define HTTP_REFERER    szReferer
#define HTTP_ACCEPT     szAccept
#define HTTP_USERAGENT  szUser_Agent
148 149 150 151 152 153 154 155 156

#define HTTP_ADDHDR_FLAG_ADD				0x20000000
#define HTTP_ADDHDR_FLAG_ADD_IF_NEW			0x10000000
#define HTTP_ADDHDR_FLAG_COALESCE			0x40000000
#define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA		0x40000000
#define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON	0x01000000
#define HTTP_ADDHDR_FLAG_REPLACE			0x80000000
#define HTTP_ADDHDR_FLAG_REQ				0x02000000

157 158
#define COLLECT_TIME 60000

159 160 161 162 163 164 165 166 167
#define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))

struct HttpAuthInfo
{
    LPWSTR scheme;
    CredHandle cred;
    CtxtHandle ctx;
    TimeStamp exp;
    ULONG attr;
168
    ULONG max_token;
169 170 171 172
    void *auth_data;
    unsigned int auth_data_len;
    BOOL finished; /* finished authenticating */
};
173

174

175
typedef struct _basicAuthorizationData
176 177 178
{
    struct list entry;

179 180 181 182
    LPWSTR host;
    LPWSTR realm;
    LPSTR  authorization;
    UINT   authorizationLen;
183 184 185 186 187 188 189 190 191 192 193 194 195 196
} basicAuthorizationData;

typedef struct _authorizationData
{
    struct list entry;

    LPWSTR host;
    LPWSTR scheme;
    LPWSTR domain;
    UINT   domain_len;
    LPWSTR user;
    UINT   user_len;
    LPWSTR password;
    UINT   password_len;
197 198 199
} authorizationData;

static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
200
static struct list authorizationCache = LIST_INIT(authorizationCache);
201 202 203 204 205 206 207 208 209 210

static CRITICAL_SECTION authcache_cs;
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &authcache_cs,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
};
static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };

211
static BOOL HTTP_GetResponseHeaders(http_request_t *req, BOOL clear);
212
static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
Jacek Caban's avatar
Jacek Caban committed
213
static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
214
static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
215 216
static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
217
static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
218
static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
219
static LPWSTR HTTP_GetRedirectURL(http_request_t *req, LPCWSTR lpszUrl);
220
static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
221
static BOOL HTTP_VerifyValidHeader(http_request_t *req, LPCWSTR field);
222
static BOOL drain_content(http_request_t*,BOOL);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

static CRITICAL_SECTION connection_pool_cs;
static CRITICAL_SECTION_DEBUG connection_pool_debug =
{
    0, 0, &connection_pool_cs,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
};
static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };

static struct list connection_pool = LIST_INIT(connection_pool);
static BOOL collector_running;

void server_addref(server_t *server)
{
    InterlockedIncrement(&server->ref);
}

void server_release(server_t *server)
{
    if(InterlockedDecrement(&server->ref))
        return;

246 247
    list_remove(&server->entry);

248 249
    if(server->cert_chain)
        CertFreeCertificateChain(server->cert_chain);
250 251
    heap_free(server->name);
    heap_free(server);
252 253
}

254
server_t *get_server(const WCHAR *name, INTERNET_PORT port, BOOL do_create)
255 256 257 258 259 260 261 262 263 264 265 266 267
{
    server_t *iter, *server = NULL;

    EnterCriticalSection(&connection_pool_cs);

    LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
        if(iter->port == port && !strcmpW(iter->name, name)) {
            server = iter;
            server_addref(server);
            break;
        }
    }

268 269
    if(!server && do_create) {
        server = heap_alloc_zero(sizeof(*server));
270
        if(server) {
271
            server->ref = 2; /* list reference and return */
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
            server->port = port;
            list_init(&server->conn_pool);
            server->name = heap_strdupW(name);
            if(server->name) {
                list_add_head(&connection_pool, &server->entry);
            }else {
                heap_free(server);
                server = NULL;
            }
        }
    }

    LeaveCriticalSection(&connection_pool_cs);

    return server;
}

289
BOOL collect_connections(collect_type_t collect_type)
290 291 292 293 294 295 296 297 298 299
{
    netconn_t *netconn, *netconn_safe;
    server_t *server, *server_safe;
    BOOL remaining = FALSE;
    DWORD64 now;

    now = GetTickCount64();

    LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
        LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
300
            if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
301 302 303 304 305 306 307 308
                TRACE("freeing %p\n", netconn);
                list_remove(&netconn->pool_entry);
                free_netconn(netconn);
            }else {
                remaining = TRUE;
            }
        }

309
        if(collect_type == COLLECT_CLEANUP) {
310 311 312
            list_remove(&server->entry);
            list_init(&server->entry);
            server_release(server);
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
        }
    }

    return remaining;
}

static DWORD WINAPI collect_connections_proc(void *arg)
{
    BOOL remaining_conns;

    do {
        /* FIXME: Use more sophisticated method */
        Sleep(5000);

        EnterCriticalSection(&connection_pool_cs);

329
        remaining_conns = collect_connections(COLLECT_TIMEOUT);
330 331 332 333 334 335 336 337
        if(!remaining_conns)
            collector_running = FALSE;

        LeaveCriticalSection(&connection_pool_cs);
    }while(remaining_conns);

    FreeLibraryAndExitThread(WININET_hModule, 0);
}
338

339
static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
340 341 342 343 344 345
{
    int HeaderIndex = 0;
    HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
    if (HeaderIndex == -1)
        return NULL;
    else
346
        return &req->custHeaders[HeaderIndex];
347
}
348

349 350 351 352 353 354 355 356 357 358
typedef enum {
    READMODE_SYNC,
    READMODE_ASYNC,
    READMODE_NOBLOCK
} read_mode_t;

struct data_stream_vtbl_t {
    DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
    BOOL (*end_of_data)(data_stream_t*,http_request_t*);
    DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,read_mode_t);
359
    BOOL (*drain_content)(data_stream_t*,http_request_t*);
360 361 362 363 364 365 366 367 368 369 370 371
    void (*destroy)(data_stream_t*);
};

typedef struct {
    data_stream_t data_stream;

    BYTE buf[READ_BUFFER_SIZE];
    DWORD buf_size;
    DWORD buf_pos;
    DWORD chunk_size;
} chunked_stream_t;

372
static inline void destroy_data_stream(data_stream_t *stream)
373 374 375 376 377 378 379 380 381 382 383 384
{
    stream->vtbl->destroy(stream);
}

static void reset_data_stream(http_request_t *req)
{
    destroy_data_stream(req->data_stream);
    req->data_stream = &req->netconn_stream.data_stream;
    req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
    req->read_chunked = req->read_gzip = FALSE;
}

385 386
#ifdef HAVE_ZLIB

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
typedef struct {
    data_stream_t stream;
    data_stream_t *parent_stream;
    z_stream zstream;
    BYTE buf[READ_BUFFER_SIZE];
    DWORD buf_size;
    DWORD buf_pos;
    BOOL end_of_data;
} gzip_stream_t;

static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
{
    /* Allow reading only from read buffer */
    return 0;
}

static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
{
    gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
    return gzip_stream->end_of_data;
}

static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
        DWORD *read, read_mode_t read_mode)
{
    gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
    z_stream *zstream = &gzip_stream->zstream;
    DWORD current_read, ret_read = 0;
    BOOL end;
    int zres;
    DWORD res = ERROR_SUCCESS;

    while(size && !gzip_stream->end_of_data) {
        end = gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req);

        if(gzip_stream->buf_size <= 64 && !end) {
            if(gzip_stream->buf_pos) {
                if(gzip_stream->buf_size)
                    memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
                gzip_stream->buf_pos = 0;
            }
            res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
                    sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, read_mode);
            gzip_stream->buf_size += current_read;
            if(res != ERROR_SUCCESS)
                break;
            end = gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req);
            if(!current_read && !end) {
                if(read_mode != READMODE_NOBLOCK) {
                    WARN("unexpected end of data\n");
                    gzip_stream->end_of_data = TRUE;
                }
                break;
            }
            if(gzip_stream->buf_size <= 64 && !end)
                continue;
        }

        zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
        zstream->avail_in = gzip_stream->buf_size-(end ? 0 : 64);
        zstream->next_out = buf+ret_read;
        zstream->avail_out = size;
        zres = inflate(&gzip_stream->zstream, 0);
        current_read = size - zstream->avail_out;
        size -= current_read;
        ret_read += current_read;
        gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
        gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
        if(zres == Z_STREAM_END) {
            TRACE("end of data\n");
            gzip_stream->end_of_data = TRUE;
            inflateEnd(zstream);
        }else if(zres != Z_OK) {
            WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
            if(!ret_read)
                res = ERROR_INTERNET_DECODING_FAILED;
            break;
        }

        if(ret_read && read_mode == READMODE_ASYNC)
            read_mode = READMODE_NOBLOCK;
    }

    TRACE("read %u bytes\n", ret_read);
    *read = ret_read;
    return res;
}

475 476 477 478 479 480
static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
{
    gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
    return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
static void gzip_destroy(data_stream_t *stream)
{
    gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;

    destroy_data_stream(gzip_stream->parent_stream);

    if(!gzip_stream->end_of_data)
        inflateEnd(&gzip_stream->zstream);
    heap_free(gzip_stream);
}

static const data_stream_vtbl_t gzip_stream_vtbl = {
    gzip_get_avail_data,
    gzip_end_of_data,
    gzip_read,
496
    gzip_drain_content,
497 498 499
    gzip_destroy
};

500 501
static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
{
502
    return heap_alloc(items*size);
503 504 505 506
}

static void wininet_zfree(voidpf opaque, voidpf address)
{
507
    heap_free(address);
508 509
}

510
static DWORD init_gzip_stream(http_request_t *req)
511 512
{
    gzip_stream_t *gzip_stream;
513
    int index, zres;
514

515
    gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
516 517 518 519
    if(!gzip_stream)
        return ERROR_OUTOFMEMORY;

    gzip_stream->stream.vtbl = &gzip_stream_vtbl;
520 521 522 523 524 525
    gzip_stream->zstream.zalloc = wininet_zalloc;
    gzip_stream->zstream.zfree = wininet_zfree;

    zres = inflateInit2(&gzip_stream->zstream, 0x1f);
    if(zres != Z_OK) {
        ERR("inflateInit failed: %d\n", zres);
526
        heap_free(gzip_stream);
527
        return ERROR_OUTOFMEMORY;
528 529
    }

530 531 532
    index = HTTP_GetCustomHeaderIndex(req, szContent_Length, 0, FALSE);
    if(index != -1)
        HTTP_DeleteCustomHeader(req, index);
533

534 535 536 537 538 539 540 541 542 543
    if(req->read_size) {
        memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
        gzip_stream->buf_size = req->read_size;
        req->read_pos = req->read_size = 0;
    }

    req->read_gzip = TRUE;
    gzip_stream->parent_stream = req->data_stream;
    req->data_stream = &gzip_stream->stream;
    return ERROR_SUCCESS;
544 545
}

546 547
#else

548
static DWORD init_gzip_stream(http_request_t *req)
549 550
{
    ERR("gzip stream not supported, missing zlib.\n");
551
    return ERROR_SUCCESS;
552 553
}

554 555
#endif

556 557 558 559 560 561 562 563 564 565 566 567
/***********************************************************************
 *           HTTP_Tokenize (internal)
 *
 *  Tokenize a string, allocating memory for the tokens.
 */
static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
{
    LPWSTR * token_array;
    int tokens = 0;
    int i;
    LPCWSTR next_token;

568 569 570 571
    if (string)
    {
        /* empty string has no tokens */
        if (*string)
572
            tokens++;
573 574 575 576 577 578 579 580 581 582 583 584 585
        /* count tokens */
        for (i = 0; string[i]; i++)
        {
            if (!strncmpW(string+i, token_string, strlenW(token_string)))
            {
                DWORD j;
                tokens++;
                /* we want to skip over separators, but not the null terminator */
                for (j = 0; j < strlenW(token_string) - 1; j++)
                    if (!string[i+j])
                        break;
                i += j;
            }
586
        }
587
    }
588 589

    /* add 1 for terminating NULL */
590
    token_array = heap_alloc((tokens+1) * sizeof(*token_array));
591 592 593 594 595 596 597 598 599
    token_array[tokens] = NULL;
    if (!tokens)
        return token_array;
    for (i = 0; i < tokens; i++)
    {
        int len;
        next_token = strstrW(string, token_string);
        if (!next_token) next_token = string+strlenW(string);
        len = next_token - string;
600
        token_array[i] = heap_alloc((len+1)*sizeof(WCHAR));
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
        memcpy(token_array[i], string, len*sizeof(WCHAR));
        token_array[i][len] = '\0';
        string = next_token+strlenW(token_string);
    }
    return token_array;
}

/***********************************************************************
 *           HTTP_FreeTokens (internal)
 *
 *  Frees memory returned from HTTP_Tokenize.
 */
static void HTTP_FreeTokens(LPWSTR * token_array)
{
    int i;
616 617
    for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
    heap_free(token_array);
618 619
}

620
static void HTTP_FixURL(http_request_t *request)
621 622 623 624 625
{
    static const WCHAR szSlash[] = { '/',0 };
    static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };

    /* If we don't have a path we set it to root */
626 627
    if (NULL == request->path)
        request->path = heap_strdupW(szSlash);
628 629
    else /* remove \r and \n*/
    {
630 631
        int nLen = strlenW(request->path);
        while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
632 633
        {
            nLen--;
634
            request->path[nLen]='\0';
635 636 637 638
        }
        /* Replace '\' with '/' */
        while (nLen>0) {
            nLen--;
639
            if (request->path[nLen] == '\\') request->path[nLen]='/';
640 641 642 643
        }
    }

    if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
644 645
                       request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
       && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
646
    {
647
        WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
648
        *fixurl = '/';
649
        strcpyW(fixurl + 1, request->path);
650
        heap_free( request->path );
651
        request->path = fixurl;
652 653 654
    }
}

655
static LPWSTR HTTP_BuildHeaderRequestString( http_request_t *request, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
656 657 658 659
{
    LPWSTR requestString;
    DWORD len, n;
    LPCWSTR *req;
660
    UINT i;
661 662 663 664 665 666 667
    LPWSTR p;

    static const WCHAR szSpace[] = { ' ',0 };
    static const WCHAR szColon[] = { ':',' ',0 };
    static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};

    /* allocate space for an array of all the string pointers to be added */
668
    len = (request->nCustHeaders)*4 + 10;
669
    req = heap_alloc(len*sizeof(LPCWSTR));
670

671
    /* add the verb, path and HTTP version string */
672
    n = 0;
673
    req[n++] = verb;
674
    req[n++] = szSpace;
675
    req[n++] = path;
676 677
    req[n++] = szSpace;
    req[n++] = version;
678

Austin English's avatar
Austin English committed
679
    /* Append custom request headers */
680
    for (i = 0; i < request->nCustHeaders; i++)
681
    {
682
        if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
683
        {
684
            req[n++] = szCrLf;
685
            req[n++] = request->custHeaders[i].lpszField;
686
            req[n++] = szColon;
687
            req[n++] = request->custHeaders[i].lpszValue;
688 689

            TRACE("Adding custom header %s (%s)\n",
690 691
                   debugstr_w(request->custHeaders[i].lpszField),
                   debugstr_w(request->custHeaders[i].lpszValue));
692 693 694 695 696 697 698 699
        }
    }

    if( n >= len )
        ERR("oops. buffer overrun\n");

    req[n] = NULL;
    requestString = HTTP_build_req( req, 4 );
700
    heap_free( req );
701 702 703 704 705 706 707 708 709 710 711 712 713

    /*
     * Set (header) termination string for request
     * Make sure there's exactly two new lines at the end of the request
     */
    p = &requestString[strlenW(requestString)-1];
    while ( (*p == '\n') || (*p == '\r') )
       p--;
    strcpyW( p+1, sztwocrlf );
    
    return requestString;
}

714
static void HTTP_ProcessCookies( http_request_t *request )
715
{
716
    int HeaderIndex;
717
    int numCookies = 0;
718 719
    LPHTTPHEADERW setCookieHeader;

720 721 722 723
    if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
        return;

    while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
724
    {
725 726 727 728
        HTTPHEADERW *host;
        const WCHAR *data;
        WCHAR *name;

729
        setCookieHeader = &request->custHeaders[HeaderIndex];
730

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
        if (!setCookieHeader->lpszValue)
            continue;

        host = HTTP_GetHeader(request, hostW);
        if(!host)
            continue;

        data = strchrW(setCookieHeader->lpszValue, '=');
        if(!data)
            continue;

        name = heap_strndupW(setCookieHeader->lpszValue, data-setCookieHeader->lpszValue);
        if(!name)
            continue;

        data++;
        set_cookie(host->lpszValue, request->path, name, data);
        heap_free(name);
749 750 751
    }
}

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
static void strip_spaces(LPWSTR start)
{
    LPWSTR str = start;
    LPWSTR end;

    while (*str == ' ' && *str != '\0')
        str++;

    if (str != start)
        memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));

    end = start + strlenW(start) - 1;
    while (end >= start && *end == ' ')
    {
        *end = '\0';
        end--;
    }
}

static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
772 773
{
    static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
774 775 776
    static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
    BOOL is_basic;
    is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
777
        ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
    if (is_basic && pszRealm)
    {
        LPCWSTR token;
        LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
        LPCWSTR realm;
        ptr++;
        *pszRealm=NULL;
        token = strchrW(ptr,'=');
        if (!token)
            return TRUE;
        realm = ptr;
        while (*realm == ' ' && *realm != '\0')
            realm++;
        if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
            (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
        {
            token++;
            while (*token == ' ' && *token != '\0')
                token++;
            if (*token == '\0')
                return TRUE;
            *pszRealm = heap_strdupW(token);
            strip_spaces(*pszRealm);
        }
    }

    return is_basic;
805 806
}

807 808 809 810 811 812 813 814 815
static void destroy_authinfo( struct HttpAuthInfo *authinfo )
{
    if (!authinfo) return;

    if (SecIsValidHandle(&authinfo->ctx))
        DeleteSecurityContext(&authinfo->ctx);
    if (SecIsValidHandle(&authinfo->cred))
        FreeCredentialsHandle(&authinfo->cred);

816 817 818
    heap_free(authinfo->auth_data);
    heap_free(authinfo->scheme);
    heap_free(authinfo);
819 820
}

821 822
static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
{
823
    basicAuthorizationData *ad;
824 825 826 827 828
    UINT rc = 0;

    TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));

    EnterCriticalSection(&authcache_cs);
829
    LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
830
    {
831
        if (!strcmpiW(host,ad->host) && !strcmpW(realm,ad->realm))
832 833
        {
            TRACE("Authorization found in cache\n");
834
            *auth_data = heap_alloc(ad->authorizationLen);
835 836
            memcpy(*auth_data,ad->authorization,ad->authorizationLen);
            rc = ad->authorizationLen;
837 838 839 840 841 842 843 844 845 846
            break;
        }
    }
    LeaveCriticalSection(&authcache_cs);
    return rc;
}

static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
{
    struct list *cursor;
847
    basicAuthorizationData* ad = NULL;
848 849 850 851 852 853

    TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));

    EnterCriticalSection(&authcache_cs);
    LIST_FOR_EACH(cursor, &basicAuthorizationCache)
    {
854
        basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
855
        if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
856 857 858 859 860 861 862 863 864
        {
            ad = check;
            break;
        }
    }

    if (ad)
    {
        TRACE("Found match in cache, replacing\n");
865
        heap_free(ad->authorization);
866
        ad->authorization = heap_alloc(auth_data_len);
867 868
        memcpy(ad->authorization, auth_data, auth_data_len);
        ad->authorizationLen = auth_data_len;
869 870 871
    }
    else
    {
872
        ad = heap_alloc(sizeof(basicAuthorizationData));
873
        ad->host = heap_strdupW(host);
874
        ad->realm = heap_strdupW(realm);
875
        ad->authorization = heap_alloc(auth_data_len);
876 877
        memcpy(ad->authorization, auth_data, auth_data_len);
        ad->authorizationLen = auth_data_len;
878 879 880 881 882 883
        list_add_head(&basicAuthorizationCache,&ad->entry);
        TRACE("authorization cached\n");
    }
    LeaveCriticalSection(&authcache_cs);
}

884 885 886 887 888 889 890 891 892 893 894 895 896 897
static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
        SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
{
    authorizationData *ad;

    TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));

    EnterCriticalSection(&authcache_cs);
    LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
        if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
            TRACE("Authorization found in cache\n");

            nt_auth_identity->User = heap_strdupW(ad->user);
            nt_auth_identity->Password = heap_strdupW(ad->password);
898
            nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
899 900
            if(!nt_auth_identity->User || !nt_auth_identity->Password ||
                    (!nt_auth_identity->Domain && ad->domain_len)) {
901 902 903
                heap_free(nt_auth_identity->User);
                heap_free(nt_auth_identity->Password);
                heap_free(nt_auth_identity->Domain);
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
                break;
            }

            nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
            nt_auth_identity->UserLength = ad->user_len;
            nt_auth_identity->PasswordLength = ad->password_len;
            memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
            nt_auth_identity->DomainLength = ad->domain_len;
            LeaveCriticalSection(&authcache_cs);
            return TRUE;
        }
    }
    LeaveCriticalSection(&authcache_cs);

    return FALSE;
}

static void cache_authorization(LPWSTR host, LPWSTR scheme,
        SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
{
    authorizationData *ad;
    BOOL found = FALSE;

    TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));

    EnterCriticalSection(&authcache_cs);
    LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
        if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
            found = TRUE;
            break;
        }

    if(found) {
937 938 939
        heap_free(ad->user);
        heap_free(ad->password);
        heap_free(ad->domain);
940
    } else {
941
        ad = heap_alloc(sizeof(authorizationData));
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
        if(!ad) {
            LeaveCriticalSection(&authcache_cs);
            return;
        }

        ad->host = heap_strdupW(host);
        ad->scheme = heap_strdupW(scheme);
        list_add_head(&authorizationCache, &ad->entry);
    }

    ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
    ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
    ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
    ad->user_len = nt_auth_identity->UserLength;
    ad->password_len = nt_auth_identity->PasswordLength;
    ad->domain_len = nt_auth_identity->DomainLength;

    if(!ad->host || !ad->scheme || !ad->user || !ad->password
            || (nt_auth_identity->Domain && !ad->domain)) {
961 962 963 964 965
        heap_free(ad->host);
        heap_free(ad->scheme);
        heap_free(ad->user);
        heap_free(ad->password);
        heap_free(ad->domain);
966
        list_remove(&ad->entry);
967
        heap_free(ad);
968 969 970 971 972
    }

    LeaveCriticalSection(&authcache_cs);
}

973
static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
974
                                  struct HttpAuthInfo **ppAuthInfo,
975 976
                                  LPWSTR domain_and_username, LPWSTR password,
                                  LPWSTR host )
977 978
{
    SECURITY_STATUS sec_status;
979
    struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
980
    BOOL first = FALSE;
981
    LPWSTR szRealm = NULL;
982 983 984 985 986 987 988

    TRACE("%s\n", debugstr_w(pszAuthValue));

    if (!pAuthInfo)
    {
        TimeStamp exp;

989
        first = TRUE;
990
        pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
991 992 993 994 995 996 997 998 999 1000 1001
        if (!pAuthInfo)
            return FALSE;

        SecInvalidateHandle(&pAuthInfo->cred);
        SecInvalidateHandle(&pAuthInfo->ctx);
        memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
        pAuthInfo->attr = 0;
        pAuthInfo->auth_data = NULL;
        pAuthInfo->auth_data_len = 0;
        pAuthInfo->finished = FALSE;

1002
        if (is_basic_auth_value(pszAuthValue,NULL))
1003 1004
        {
            static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1005
            pAuthInfo->scheme = heap_strdupW(szBasic);
1006 1007
            if (!pAuthInfo->scheme)
            {
1008
                heap_free(pAuthInfo);
1009 1010 1011 1012
                return FALSE;
            }
        }
        else
1013
        {
1014
            PVOID pAuthData;
1015 1016
            SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;

1017
            pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1018 1019
            if (!pAuthInfo->scheme)
            {
1020
                heap_free(pAuthInfo);
1021 1022 1023
                return FALSE;
            }

1024
            if (domain_and_username)
1025
            {
1026 1027
                WCHAR *user = strchrW(domain_and_username, '\\');
                WCHAR *domain = domain_and_username;
1028

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
                /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */

                pAuthData = &nt_auth_identity;

                if (user) user++;
                else
                {
                    user = domain_and_username;
                    domain = NULL;
                }

                nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
                nt_auth_identity.User = user;
                nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
                nt_auth_identity.Domain = domain;
                nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
                nt_auth_identity.Password = password;
                nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1047 1048

                cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1049
            }
1050 1051
            else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
                pAuthData = &nt_auth_identity;
1052 1053 1054
            else
                /* use default credentials */
                pAuthData = NULL;
1055 1056 1057

            sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
                                                   SECPKG_CRED_OUTBOUND, NULL,
1058
                                                   pAuthData, NULL,
1059 1060
                                                   NULL, &pAuthInfo->cred,
                                                   &exp);
1061 1062

            if(pAuthData && !domain_and_username) {
1063 1064 1065
                heap_free(nt_auth_identity.User);
                heap_free(nt_auth_identity.Domain);
                heap_free(nt_auth_identity.Password);
1066 1067
            }

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
            if (sec_status == SEC_E_OK)
            {
                PSecPkgInfoW sec_pkg_info;
                sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
                if (sec_status == SEC_E_OK)
                {
                    pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
                    FreeContextBuffer(sec_pkg_info);
                }
            }
1078 1079 1080 1081
            if (sec_status != SEC_E_OK)
            {
                WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
                     debugstr_w(pAuthInfo->scheme), sec_status);
1082 1083
                heap_free(pAuthInfo->scheme);
                heap_free(pAuthInfo);
1084 1085 1086
                return FALSE;
            }
        }
1087
        *ppAuthInfo = pAuthInfo;
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    }
    else if (pAuthInfo->finished)
        return FALSE;

    if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
        strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
    {
        ERR("authentication scheme changed from %s to %s\n",
            debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
        return FALSE;
    }

1100
    if (is_basic_auth_value(pszAuthValue,&szRealm))
1101
    {
1102 1103
        int userlen;
        int passlen;
1104 1105
        char *auth_data = NULL;
        UINT auth_data_len = 0;
1106

1107
        TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1108

1109 1110 1111 1112 1113 1114
        if (!domain_and_username)
        {
            if (host && szRealm)
                auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
            if (auth_data_len == 0)
            {
1115
                heap_free(szRealm);
1116 1117 1118 1119 1120 1121 1122
                return FALSE;
            }
        }
        else
        {
            userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
            passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1123

1124
            /* length includes a nul terminator, which will be re-used for the ':' */
1125
            auth_data = heap_alloc(userlen + 1 + passlen);
1126 1127
            if (!auth_data)
            {
1128
                heap_free(szRealm);
1129 1130
                return FALSE;
            }
1131

1132 1133 1134 1135 1136 1137 1138
            WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
            auth_data[userlen] = ':';
            WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
            auth_data_len = userlen + 1 + passlen;
            if (host && szRealm)
                cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
        }
1139 1140

        pAuthInfo->auth_data = auth_data;
1141
        pAuthInfo->auth_data_len = auth_data_len;
1142
        pAuthInfo->finished = TRUE;
1143
        heap_free(szRealm);
1144
        return TRUE;
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
    }
    else
    {
        LPCWSTR pszAuthData;
        SecBufferDesc out_desc, in_desc;
        SecBuffer out, in;
        unsigned char *buffer;
        ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
            ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;

        in.BufferType = SECBUFFER_TOKEN;
        in.cbBuffer = 0;
        in.pvBuffer = NULL;

        in_desc.ulVersion = 0;
        in_desc.cBuffers = 1;
        in_desc.pBuffers = &in;

        pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
        if (*pszAuthData == ' ')
        {
            pszAuthData++;
            in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1168
            in.pvBuffer = heap_alloc(in.cbBuffer);
1169 1170 1171
            HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
        }

1172
        buffer = heap_alloc(pAuthInfo->max_token);
1173 1174

        out.BufferType = SECBUFFER_TOKEN;
1175
        out.cbBuffer = pAuthInfo->max_token;
1176 1177 1178 1179 1180 1181
        out.pvBuffer = buffer;

        out_desc.ulVersion = 0;
        out_desc.cBuffers = 1;
        out_desc.pBuffers = &out;

1182
        sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1183
                                                first ? NULL : &pAuthInfo->ctx,
1184
                                                first ? request->server->name : NULL,
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
                                                context_req, 0, SECURITY_NETWORK_DREP,
                                                in.pvBuffer ? &in_desc : NULL,
                                                0, &pAuthInfo->ctx, &out_desc,
                                                &pAuthInfo->attr, &pAuthInfo->exp);
        if (sec_status == SEC_E_OK)
        {
            pAuthInfo->finished = TRUE;
            pAuthInfo->auth_data = out.pvBuffer;
            pAuthInfo->auth_data_len = out.cbBuffer;
            TRACE("sending last auth packet\n");
        }
        else if (sec_status == SEC_I_CONTINUE_NEEDED)
        {
            pAuthInfo->auth_data = out.pvBuffer;
            pAuthInfo->auth_data_len = out.cbBuffer;
            TRACE("sending next auth packet\n");
        }
        else
        {
            ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1205
            heap_free(out.pvBuffer);
1206 1207
            destroy_authinfo(pAuthInfo);
            *ppAuthInfo = NULL;
1208 1209 1210 1211 1212 1213 1214
            return FALSE;
        }
    }

    return TRUE;
}

1215
/***********************************************************************
1216
 *           HTTP_HttpAddRequestHeadersW (internal)
1217
 */
1218
static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1219
	LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1220
{
1221 1222 1223
    LPWSTR lpszStart;
    LPWSTR lpszEnd;
    LPWSTR buffer;
1224
    DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1225

1226
    TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1227

1228
    if( dwHeaderLength == ~0U )
1229 1230 1231
        len = strlenW(lpszHeader);
    else
        len = dwHeaderLength;
1232
    buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1233
    lstrcpynW( buffer, lpszHeader, len + 1);
1234

1235 1236 1237 1238
    lpszStart = buffer;

    do
    {
1239 1240
        LPWSTR * pFieldAndValue;

1241 1242 1243 1244
        lpszEnd = lpszStart;

        while (*lpszEnd != '\0')
        {
1245
            if (*lpszEnd == '\r' || *lpszEnd == '\n')
1246 1247 1248 1249
                 break;
            lpszEnd++;
        }

1250
        if (*lpszStart == '\0')
1251 1252
	    break;

1253
        if (*lpszEnd == '\r' || *lpszEnd == '\n')
1254 1255
        {
            *lpszEnd = '\0';
1256
            lpszEnd++; /* Jump over newline */
1257
        }
1258
        TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1259 1260 1261 1262
        if (*lpszStart == '\0')
        {
            /* Skip 0-length headers */
            lpszStart = lpszEnd;
1263
            res = ERROR_SUCCESS;
1264 1265
            continue;
        }
1266 1267 1268
        pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
        if (pFieldAndValue)
        {
1269
            res = HTTP_VerifyValidHeader(request, pFieldAndValue[0]);
1270
            if (res == ERROR_SUCCESS)
1271
                res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1272
                    pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1273 1274
            HTTP_FreeTokens(pFieldAndValue);
        }
1275

1276
        lpszStart = lpszEnd;
1277
    } while (res == ERROR_SUCCESS);
1278

1279
    heap_free(buffer);
1280
    return res;
1281 1282 1283 1284 1285 1286 1287
}

/***********************************************************************
 *           HttpAddRequestHeadersW (WININET.@)
 *
 * Adds one or more HTTP header to the request handler
 *
1288 1289 1290
 * NOTE
 * On Windows if dwHeaderLength includes the trailing '\0', then
 * HttpAddRequestHeadersW() adds it too. However this results in an
1291
 * invalid HTTP header which is rejected by some servers so we probably
1292 1293
 * don't need to match Windows on that point.
 *
1294 1295 1296 1297 1298 1299 1300 1301
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
	LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
{
1302
    http_request_t *request;
1303
    DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1304

1305
    TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1306 1307 1308 1309

    if (!lpszHeader) 
      return TRUE;

1310 1311 1312 1313 1314
    request = (http_request_t*) get_handle_object( hHttpRequest );
    if (request && request->hdr.htype == WH_HHTTPREQ)
        res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
    if( request )
        WININET_Release( &request->hdr );
1315

1316 1317 1318
    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
1319 1320
}

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
/***********************************************************************
 *           HttpAddRequestHeadersA (WININET.@)
 *
 * Adds one or more HTTP header to the request handler
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
	LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
{
    DWORD len;
    LPWSTR hdr;
    BOOL r;

1338
    TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1339 1340

    len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
1341
    hdr = heap_alloc(len*sizeof(WCHAR));
1342
    MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
1343
    if( dwHeaderLength != ~0U )
1344 1345 1346 1347
        dwHeaderLength = len;

    r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );

1348
    heap_free( hdr );
1349 1350 1351
    return r;
}

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
static void free_accept_types( WCHAR **accept_types )
{
    WCHAR *ptr, **types = accept_types;

    if (!types) return;
    while ((ptr = *types))
    {
        heap_free( ptr );
        types++;
    }
    heap_free( accept_types );
}

static WCHAR **convert_accept_types( const char **accept_types )
{
    unsigned int count;
    const char **types = accept_types;
    WCHAR **typesW;
    BOOL invalid_pointer = FALSE;

    if (!types) return NULL;
    count = 0;
    while (*types)
    {
        __TRY
        {
            /* find out how many there are */
            if (*types && **types)
            {
                TRACE("accept type: %s\n", debugstr_a(*types));
                count++;
            }
        }
        __EXCEPT_PAGE_FAULT
        {
            WARN("invalid accept type pointer\n");
            invalid_pointer = TRUE;
        }
        __ENDTRY;
        types++;
    }
    if (invalid_pointer) return NULL;
    if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
    count = 0;
    types = accept_types;
    while (*types)
    {
        if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
        types++;
    }
    typesW[count] = NULL;
    return typesW;
}

1406
/***********************************************************************
1407
 *           HttpOpenRequestA (WININET.@)
1408 1409 1410 1411 1412 1413 1414 1415
 *
 * Open a HTTP request handle
 *
 * RETURNS
 *    HINTERNET  a HTTP request handle on success
 *    NULL 	 on failure
 *
 */
1416 1417 1418
HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
	LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
	LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1419
	DWORD dwFlags, DWORD_PTR dwContext)
1420
{
1421 1422
    LPWSTR szVerb = NULL, szObjectName = NULL;
    LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1423
    HINTERNET rc = FALSE;
1424

1425
    TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1426 1427
          debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
          debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1428 1429 1430 1431
          dwFlags, dwContext);

    if (lpszVerb)
    {
1432
        szVerb = heap_strdupAtoW(lpszVerb);
1433
        if ( !szVerb )
1434 1435
            goto end;
    }
1436

1437 1438
    if (lpszObjectName)
    {
1439
        szObjectName = heap_strdupAtoW(lpszObjectName);
1440
        if ( !szObjectName )
1441 1442 1443 1444 1445
            goto end;
    }

    if (lpszVersion)
    {
1446
        szVersion = heap_strdupAtoW(lpszVersion);
1447
        if ( !szVersion )
1448 1449 1450 1451 1452
            goto end;
    }

    if (lpszReferrer)
    {
1453
        szReferrer = heap_strdupAtoW(lpszReferrer);
1454
        if ( !szReferrer )
1455 1456 1457
            goto end;
    }

1458 1459 1460
    szAcceptTypes = convert_accept_types( lpszAcceptTypes );
    rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
                          (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1461 1462

end:
1463
    free_accept_types(szAcceptTypes);
1464 1465 1466 1467
    heap_free(szReferrer);
    heap_free(szVersion);
    heap_free(szObjectName);
    heap_free(szVerb);
1468
    return rc;
1469
}
1470

1471
/***********************************************************************
1472
 *  HTTP_EncodeBase64
1473
 */
1474
static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1475 1476
{
    UINT n = 0, x;
1477
    static const CHAR HTTP_Base64Enc[] =
1478 1479
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

1480
    while( len > 0 )
1481 1482 1483 1484 1485 1486
    {
        /* first 6 bits, all from bin[0] */
        base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
        x = (bin[0] & 3) << 4;

        /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1487
        if( len == 1 )
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
        {
            base64[n++] = HTTP_Base64Enc[x];
            base64[n++] = '=';
            base64[n++] = '=';
            break;
        }
        base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
        x = ( bin[1] & 0x0f ) << 2;

        /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1498
        if( len == 2 )
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
        {
            base64[n++] = HTTP_Base64Enc[x];
            base64[n++] = '=';
            break;
        }
        base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];

        /* last 6 bits, all from bin [2] */
        base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
        bin += 3;
1509
        len -= 3;
1510 1511 1512 1513 1514
    }
    base64[n] = 0;
    return n;
}

1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
#define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
               ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
               ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
               ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
static const signed char HTTP_Base64Dec[256] =
{
    CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
    CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
    CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
    CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
    CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
    CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
    CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
    CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
    CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
    CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
    CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
    CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
    CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
    CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
    CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
    CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
    CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
    CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
    CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
    CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
    CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
    CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
    CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
    CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
    CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
    CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
};
#undef CH

/***********************************************************************
 *  HTTP_DecodeBase64
 */
static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
{
    unsigned int n = 0;

    while(*base64)
    {
        signed char in[4];

1561
        if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1562
            ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1563
            base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
            ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
        {
            WARN("invalid base64: %s\n", debugstr_w(base64));
            return 0;
        }
        if (bin)
            bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
        n++;

        if ((base64[2] == '=') && (base64[3] == '='))
            break;
        if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
            ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
        {
            WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
            return 0;
        }
        if (bin)
            bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
        n++;

        if (base64[3] == '=')
            break;
        if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
            ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
        {
            WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
            return 0;
        }
        if (bin)
            bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
        n++;

        base64 += 4;
    }

    return n;
}

1603
/***********************************************************************
1604
 *  HTTP_InsertAuthorization
1605 1606 1607
 *
 *   Insert or delete the authorization field in the request header.
 */
1608
static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1609
{
1610
    if (pAuthInfo)
1611 1612
    {
        static const WCHAR wszSpace[] = {' ',0};
1613
        static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1614
        unsigned int len;
1615
        WCHAR *authorization = NULL;
1616

1617 1618 1619 1620
        if (pAuthInfo->auth_data_len)
        {
            /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
            len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1621
            authorization = heap_alloc((len+1)*sizeof(WCHAR));
1622 1623
            if (!authorization)
                return FALSE;
1624

1625 1626 1627 1628 1629
            strcpyW(authorization, pAuthInfo->scheme);
            strcatW(authorization, wszSpace);
            HTTP_EncodeBase64(pAuthInfo->auth_data,
                              pAuthInfo->auth_data_len,
                              authorization+strlenW(authorization));
1630

1631 1632 1633 1634 1635
            /* clear the data as it isn't valid now that it has been sent to the
             * server, unless it's Basic authentication which doesn't do
             * connection tracking */
            if (strcmpiW(pAuthInfo->scheme, wszBasic))
            {
1636
                heap_free(pAuthInfo->auth_data);
1637 1638 1639
                pAuthInfo->auth_data = NULL;
                pAuthInfo->auth_data_len = 0;
            }
1640
        }
1641

1642
        TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1643

1644
        HTTP_ProcessHeader(request, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1645
        heap_free(authorization);
1646
    }
1647 1648 1649
    return TRUE;
}

1650
static WCHAR *HTTP_BuildProxyRequestUrl(http_request_t *req)
1651
{
1652 1653 1654 1655
    static const WCHAR slash[] = { '/',0 };
    static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','u',0 };
    static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','u',0 };
    http_session_t *session = req->session;
1656
    WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1657 1658 1659
    DWORD size;

    size = sizeof(new_location);
1660
    if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL) == ERROR_SUCCESS)
1661
    {
1662 1663
        URL_COMPONENTSW UrlComponents;

1664
        if (!(url = heap_alloc(size + sizeof(WCHAR)))) return NULL;
1665
        strcpyW( url, new_location );
1666 1667 1668 1669

        ZeroMemory(&UrlComponents,sizeof(URL_COMPONENTSW));
        if(InternetCrackUrlW(url, 0, 0, &UrlComponents)) goto done;
        heap_free(url);
1670 1671
    }

1672 1673
    size = 16; /* "https://" + sizeof(port#) + ":/\0" */
    size += strlenW( session->hostName ) + strlenW( req->path );
1674

1675
    if (!(url = heap_alloc(size * sizeof(WCHAR)))) return NULL;
1676

1677 1678 1679 1680 1681 1682 1683 1684
    if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
        sprintfW( url, formatSSL, session->hostName, session->hostPort );
    else
        sprintfW( url, format, session->hostName, session->hostPort );
    if (req->path[0] != '/') strcatW( url, slash );
    strcatW( url, req->path );

done:
1685 1686 1687 1688
    TRACE("url=%s\n", debugstr_w(url));
    return url;
}

1689 1690 1691
/***********************************************************************
 *           HTTP_DealWithProxy
 */
1692
static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1693
{
1694 1695 1696 1697
    WCHAR buf[INTERNET_MAX_HOST_NAME_LENGTH];
    WCHAR protoProxy[INTERNET_MAX_URL_LENGTH];
    DWORD protoProxyLen = INTERNET_MAX_URL_LENGTH;
    WCHAR proxy[INTERNET_MAX_URL_LENGTH];
1698
    static WCHAR szNul[] = { 0 };
1699
    URL_COMPONENTSW UrlComponents;
1700
    server_t *new_server;
1701
    static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1702 1703
    static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
    static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1704 1705 1706 1707

    memset( &UrlComponents, 0, sizeof UrlComponents );
    UrlComponents.dwStructSize = sizeof UrlComponents;
    UrlComponents.lpszHostName = buf;
1708
    UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
1709

1710
    if (!INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp, protoProxy, &protoProxyLen))
1711
        return FALSE;
1712
    if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1713 1714
                                 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
        sprintfW(proxy, szFormat, protoProxy);
1715
    else
1716
	strcpyW(proxy, protoProxy);
1717
    if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1718 1719 1720 1721
        return FALSE;
    if( UrlComponents.dwHostNameLength == 0 )
        return FALSE;

1722 1723
    if( !request->path )
        request->path = szNul;
1724 1725 1726 1727

    if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
        UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;

1728
    new_server = get_server(UrlComponents.lpszHostName, UrlComponents.nPort, TRUE);
1729 1730 1731 1732 1733
    if(!new_server)
        return FALSE;

    server_release(request->server);
    request->server = new_server;
1734

1735
    TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1736 1737 1738
    return TRUE;
}

1739
static DWORD HTTP_ResolveName(http_request_t *request)
1740
{
1741
    server_t *server = request->server;
1742
    socklen_t addr_len;
1743
    void *addr;
1744

1745 1746 1747
    if(server->addr_len)
        return ERROR_SUCCESS;

1748
    INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1749
                          INTERNET_STATUS_RESOLVING_NAME,
1750 1751
                          server->name,
                          (strlenW(server->name)+1) * sizeof(WCHAR));
1752

1753 1754
    addr_len = sizeof(server->addr);
    if (!GetAddress(server->name, server->port, (struct sockaddr *)&server->addr, &addr_len))
1755
        return ERROR_INTERNET_NAME_NOT_RESOLVED;
1756

1757
    switch(server->addr.ss_family) {
1758
    case AF_INET:
1759
        addr = &((struct sockaddr_in *)&server->addr)->sin_addr;
1760
        break;
1761
    case AF_INET6:
1762
        addr = &((struct sockaddr_in6 *)&server->addr)->sin6_addr;
1763
        break;
1764
    default:
1765
        WARN("unsupported family %d\n", server->addr.ss_family);
1766
        return ERROR_INTERNET_NAME_NOT_RESOLVED;
1767
    }
1768 1769 1770

    server->addr_len = addr_len;
    inet_ntop(server->addr.ss_family, addr, server->addr_str, sizeof(server->addr_str));
1771
    INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1772
                          INTERNET_STATUS_NAME_RESOLVED,
1773
                          server->addr_str, strlen(server->addr_str)+1);
1774

1775
    TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1776
    return ERROR_SUCCESS;
1777 1778
}

1779 1780
static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
{
1781 1782 1783
    static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
    static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
    static const WCHAR slash[] = { '/',0 };
1784
    LPHTTPHEADERW host_header;
1785
    LPCWSTR scheme;
1786 1787 1788 1789 1790

    host_header = HTTP_GetHeader(req, hostW);
    if(!host_header)
        return FALSE;

1791 1792 1793 1794 1795 1796 1797 1798 1799
    if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
        scheme = https;
    else
        scheme = http;
    strcpyW(buf, scheme);
    strcatW(buf, host_header->lpszValue);
    if (req->path[0] != '/')
        strcatW(buf, slash);
    strcatW(buf, req->path);
1800 1801 1802
    return TRUE;
}

1803 1804 1805 1806 1807 1808 1809

/***********************************************************************
 *           HTTPREQ_Destroy (internal)
 *
 * Deallocate request handle
 *
 */
1810
static void HTTPREQ_Destroy(object_header_t *hdr)
1811
{
1812
    http_request_t *request = (http_request_t*) hdr;
1813 1814 1815 1816
    DWORD i;

    TRACE("\n");

1817
    if(request->hCacheFile) {
1818 1819
        WCHAR url[INTERNET_MAX_URL_LENGTH];

1820
        CloseHandle(request->hCacheFile);
1821

1822
        if(HTTP_GetRequestURL(request, url)) {
1823 1824 1825
            DWORD headersLen;

            headersLen = request->rawHeaders ? strlenW(request->rawHeaders) : 0;
1826
            CommitUrlCacheEntryW(url, request->cacheFile, request->expires,
1827 1828
                    request->last_modified, NORMAL_CACHE_ENTRY,
                    request->rawHeaders, headersLen, NULL, 0);
1829 1830
        }
    }
1831
    heap_free(request->cacheFile);
1832

1833
    request->read_section.DebugInfo->Spare[0] = 0;
1834
    DeleteCriticalSection( &request->read_section );
1835
    WININET_Release(&request->session->hdr);
1836

1837 1838
    destroy_authinfo(request->authInfo);
    destroy_authinfo(request->proxyAuthInfo);
1839

1840 1841 1842
    if(request->server)
        server_release(request->server);

1843 1844 1845 1846 1847
    heap_free(request->path);
    heap_free(request->verb);
    heap_free(request->rawHeaders);
    heap_free(request->version);
    heap_free(request->statusText);
1848

1849
    for (i = 0; i < request->nCustHeaders; i++)
1850
    {
1851 1852
        heap_free(request->custHeaders[i].lpszField);
        heap_free(request->custHeaders[i].lpszValue);
1853
    }
1854
    destroy_data_stream(request->data_stream);
1855
    heap_free(request->custHeaders);
1856 1857
}

1858
static void http_release_netconn(http_request_t *req, BOOL reuse)
1859
{
1860 1861 1862 1863 1864 1865 1866 1867 1868
    TRACE("%p %p\n",req, req->netconn);

    if(!req->netconn)
        return;

    if(reuse && req->netconn->keep_alive) {
        BOOL run_collector;

        EnterCriticalSection(&connection_pool_cs);
1869

1870 1871 1872
        list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
        req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
        req->netconn = NULL;
1873

1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
        run_collector = !collector_running;
        collector_running = TRUE;

        LeaveCriticalSection(&connection_pool_cs);

        if(run_collector) {
            HANDLE thread = NULL;
            HMODULE module;

            GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
            if(module)
                thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
            if(!thread) {
                EnterCriticalSection(&connection_pool_cs);
                collector_running = FALSE;
                LeaveCriticalSection(&connection_pool_cs);

                if(module)
                    FreeLibrary(module);
            }
1894 1895
            else
                CloseHandle(thread);
1896
        }
1897
        return;
1898
    }
1899

1900
    INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1901 1902
                          INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);

1903 1904
    free_netconn(req->netconn);
    req->netconn = NULL;
1905

1906
    INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1907 1908 1909
                          INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
}

1910
static BOOL HTTP_KeepAlive(http_request_t *request)
1911 1912 1913 1914 1915 1916 1917 1918
{
    WCHAR szVersion[10];
    WCHAR szConnectionResponse[20];
    DWORD dwBufferSize = sizeof(szVersion);
    BOOL keepalive = FALSE;

    /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
     * the connection is keep-alive by default */
1919
    if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1920
        && !strcmpiW(szVersion, g_szHttp1_1))
1921 1922 1923 1924 1925
    {
        keepalive = TRUE;
    }

    dwBufferSize = sizeof(szConnectionResponse);
1926 1927
    if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
        || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
1928 1929 1930 1931 1932 1933 1934
    {
        keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
    }

    return keepalive;
}

1935 1936 1937 1938
static void HTTPREQ_CloseConnection(object_header_t *hdr)
{
    http_request_t *req = (http_request_t*)hdr;

1939
    http_release_netconn(req, drain_content(req, FALSE));
1940 1941
}

1942
static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1943
{
1944
    http_request_t *req = (http_request_t*)hdr;
1945

1946
    switch(option) {
1947 1948
    case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
    {
1949
        http_session_t *session = req->session;
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
        INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;

        FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");

        if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
            return ERROR_INSUFFICIENT_BUFFER;
        *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
        /* FIXME: can't get a SOCKET from our connection since we don't use
         * winsock
         */
        info->Socket = 0;
        /* FIXME: get source port from req->netConnection */
        info->SourcePort = 0;
1963
        info->DestPort = session->hostPort;
1964 1965 1966
        info->Flags = 0;
        if (HTTP_KeepAlive(req))
            info->Flags |= IDSI_FLAG_KEEP_ALIVE;
1967
        if (session->appInfo->proxy && session->appInfo->proxy[0] != 0)
1968
            info->Flags |= IDSI_FLAG_PROXY;
1969
        if (req->netconn->useSSL)
1970 1971 1972 1973 1974
            info->Flags |= IDSI_FLAG_SECURE;

        return ERROR_SUCCESS;
    }

1975 1976 1977
    case 98:
        TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
        /* fall through */
1978 1979
    case INTERNET_OPTION_SECURITY_FLAGS:
    {
1980
        DWORD flags;
1981 1982 1983 1984 1985

        if (*size < sizeof(ULONG))
            return ERROR_INSUFFICIENT_BUFFER;

        *size = sizeof(DWORD);
1986
        flags = req->netconn ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
1987
        *(DWORD *)buffer = flags;
1988 1989

        TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
1990 1991 1992
        return ERROR_SUCCESS;
    }

1993 1994 1995 1996 1997 1998 1999 2000 2001
    case INTERNET_OPTION_HANDLE_TYPE:
        TRACE("INTERNET_OPTION_HANDLE_TYPE\n");

        if (*size < sizeof(ULONG))
            return ERROR_INSUFFICIENT_BUFFER;

        *size = sizeof(DWORD);
        *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
        return ERROR_SUCCESS;
2002 2003 2004 2005 2006

    case INTERNET_OPTION_URL: {
        WCHAR url[INTERNET_MAX_URL_LENGTH];
        HTTPHEADERW *host;
        DWORD len;
2007
        WCHAR *pch;
2008

2009
        static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
2010 2011 2012 2013

        TRACE("INTERNET_OPTION_URL\n");

        host = HTTP_GetHeader(req, hostW);
2014 2015 2016 2017
        strcpyW(url, httpW);
        strcatW(url, host->lpszValue);
        if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
            *pch = 0;
2018
        strcatW(url, req->path);
2019

2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
        TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));

        if(unicode) {
            len = (strlenW(url)+1) * sizeof(WCHAR);
            if(*size < len)
                return ERROR_INSUFFICIENT_BUFFER;

            *size = len;
            strcpyW(buffer, url);
            return ERROR_SUCCESS;
        }else {
            len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
            if(len > *size)
                return ERROR_INSUFFICIENT_BUFFER;

            *size = len;
            return ERROR_SUCCESS;
        }
    }
2039

2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
    case INTERNET_OPTION_CACHE_TIMESTAMPS: {
        INTERNET_CACHE_ENTRY_INFOW *info;
        INTERNET_CACHE_TIMESTAMPS *ts = buffer;
        WCHAR url[INTERNET_MAX_URL_LENGTH];
        DWORD nbytes, error;
        BOOL ret;

        TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");

        if (*size < sizeof(*ts))
        {
            *size = sizeof(*ts);
            return ERROR_INSUFFICIENT_BUFFER;
        }
        nbytes = 0;
        HTTP_GetRequestURL(req, url);
        ret = GetUrlCacheEntryInfoW(url, NULL, &nbytes);
        error = GetLastError();
        if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
        {
2060
            if (!(info = heap_alloc(nbytes)))
2061 2062 2063 2064 2065 2066 2067
                return ERROR_OUTOFMEMORY;

            GetUrlCacheEntryInfoW(url, info, &nbytes);

            ts->ftExpires = info->ExpireTime;
            ts->ftLastModified = info->LastModifiedTime;

2068
            heap_free(info);
2069 2070 2071 2072 2073 2074
            *size = sizeof(*ts);
            return ERROR_SUCCESS;
        }
        return error;
    }

2075 2076 2077 2078 2079
    case INTERNET_OPTION_DATAFILE_NAME: {
        DWORD req_size;

        TRACE("INTERNET_OPTION_DATAFILE_NAME\n");

2080
        if(!req->cacheFile) {
2081 2082 2083 2084 2085
            *size = 0;
            return ERROR_INTERNET_ITEM_NOT_FOUND;
        }

        if(unicode) {
2086
            req_size = (lstrlenW(req->cacheFile)+1) * sizeof(WCHAR);
2087 2088 2089 2090
            if(*size < req_size)
                return ERROR_INSUFFICIENT_BUFFER;

            *size = req_size;
2091
            memcpy(buffer, req->cacheFile, *size);
2092 2093
            return ERROR_SUCCESS;
        }else {
2094
            req_size = WideCharToMultiByte(CP_ACP, 0, req->cacheFile, -1, NULL, 0, NULL, NULL);
2095 2096 2097
            if (req_size > *size)
                return ERROR_INSUFFICIENT_BUFFER;

2098
            *size = WideCharToMultiByte(CP_ACP, 0, req->cacheFile,
2099 2100 2101 2102
                    -1, buffer, *size, NULL, NULL);
            return ERROR_SUCCESS;
        }
    }
2103 2104 2105 2106

    case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
        PCCERT_CONTEXT context;

2107 2108
        if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
            *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2109 2110 2111
            return ERROR_INSUFFICIENT_BUFFER;
        }

2112
        context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2113
        if(context) {
2114
            INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2115 2116
            DWORD len;

2117
            memset(info, 0, sizeof(*info));
2118 2119
            info->ftExpiry = context->pCertInfo->NotAfter;
            info->ftStart = context->pCertInfo->NotBefore;
2120
            len = CertNameToStrA(context->dwCertEncodingType,
2121
                     &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2122 2123 2124
            info->lpszSubjectInfo = LocalAlloc(0, len);
            if(info->lpszSubjectInfo)
                CertNameToStrA(context->dwCertEncodingType,
2125
                         &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2126 2127
                         info->lpszSubjectInfo, len);
            len = CertNameToStrA(context->dwCertEncodingType,
2128
                     &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2129 2130 2131
            info->lpszIssuerInfo = LocalAlloc(0, len);
            if(info->lpszIssuerInfo)
                CertNameToStrA(context->dwCertEncodingType,
2132
                         &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2133
                         info->lpszIssuerInfo, len);
2134
            info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2135 2136 2137
            CertFreeCertificateContext(context);
            return ERROR_SUCCESS;
        }
2138
        return ERROR_NOT_SUPPORTED;
2139
    }
2140 2141 2142 2143 2144 2145
    case INTERNET_OPTION_CONNECT_TIMEOUT:
        if (*size < sizeof(DWORD))
            return ERROR_INSUFFICIENT_BUFFER;

        *size = sizeof(DWORD);
        *(DWORD *)buffer = req->connect_timeout;
2146
        return ERROR_SUCCESS;
2147 2148
    case INTERNET_OPTION_REQUEST_FLAGS: {
        DWORD flags = 0;
2149 2150 2151 2152

        if (*size < sizeof(DWORD))
            return ERROR_INSUFFICIENT_BUFFER;

2153 2154 2155 2156 2157 2158 2159 2160 2161
        /* FIXME: Add support for:
         * INTERNET_REQFLAG_FROM_CACHE
         * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
         */

        if(req->session->appInfo->proxy)
            flags |= INTERNET_REQFLAG_VIA_PROXY;
        if(!req->rawHeaders)
            flags |= INTERNET_REQFLAG_NO_HEADERS;
2162

2163 2164 2165 2166
        TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);

        *size = sizeof(DWORD);
        *(DWORD*)buffer = flags;
2167
        return ERROR_SUCCESS;
2168
    }
2169
    }
2170

2171
    return INET_QueryOption(hdr, option, buffer, size, unicode);
2172 2173
}

2174
static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2175
{
2176
    http_request_t *req = (http_request_t*)hdr;
2177 2178

    switch(option) {
2179 2180 2181 2182 2183 2184 2185 2186 2187
    case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
        TRACE("Undocumented option 99\n");

        if (!buffer || size != sizeof(DWORD))
            return ERROR_INVALID_PARAMETER;
        if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
            return ERROR_INTERNET_OPTION_NOT_SETTABLE;

        /* fall through */
2188 2189 2190 2191 2192 2193 2194
    case INTERNET_OPTION_SECURITY_FLAGS:
    {
        DWORD flags;

        if (!buffer || size != sizeof(DWORD))
            return ERROR_INVALID_PARAMETER;
        flags = *(DWORD *)buffer;
2195 2196 2197
        TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
        flags &= SECURITY_SET_MASK;
        req->security_flags |= flags;
2198
        if(req->netconn)
2199
            req->netconn->security_flags |= flags;
2200 2201
        return ERROR_SUCCESS;
    }
2202
    case INTERNET_OPTION_CONNECT_TIMEOUT:
2203
        if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2204 2205 2206
        req->connect_timeout = *(DWORD *)buffer;
        return ERROR_SUCCESS;

2207
    case INTERNET_OPTION_SEND_TIMEOUT:
2208 2209 2210
        if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
        req->send_timeout = *(DWORD *)buffer;
        return ERROR_SUCCESS;
2211

2212 2213 2214 2215
    case INTERNET_OPTION_RECEIVE_TIMEOUT:
        if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
        req->receive_timeout = *(DWORD *)buffer;
        return ERROR_SUCCESS;
2216 2217

    case INTERNET_OPTION_USERNAME:
2218
        heap_free(req->session->userName);
2219
        if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2220 2221 2222
        return ERROR_SUCCESS;

    case INTERNET_OPTION_PASSWORD:
2223
        heap_free(req->session->password);
2224
        if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2225
        return ERROR_SUCCESS;
2226 2227 2228 2229 2230
    case INTERNET_OPTION_HTTP_DECODING:
        if(size != sizeof(BOOL))
            return ERROR_INVALID_PARAMETER;
        req->decoding = *(BOOL*)buffer;
        return ERROR_SUCCESS;
2231 2232
    }

2233
    return INET_SetOption(hdr, option, buffer, size);
2234 2235
}

2236
/* read some more data into the read buffer (the read section must be held) */
2237
static DWORD read_more_data( http_request_t *req, int maxlen )
2238
{
2239
    DWORD res;
2240
    int len;
2241

2242
    if (req->read_pos)
2243 2244
    {
        /* move existing data to the start of the buffer */
2245 2246
        if(req->read_size)
            memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2247
        req->read_pos = 0;
2248 2249
    }

2250
    if (maxlen == -1) maxlen = sizeof(req->read_buf);
2251

2252
    res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2253
                       maxlen - req->read_size, 0, &len );
2254 2255
    if(res == ERROR_SUCCESS)
        req->read_size += len;
2256

2257
    return res;
2258 2259
}

2260
/* remove some amount of data from the read buffer (the read section must be held) */
2261
static void remove_data( http_request_t *req, int count )
2262
{
2263 2264 2265
    if (!(req->read_size -= count)) req->read_pos = 0;
    else req->read_pos += count;
}
2266

2267
static BOOL read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2268 2269
{
    int count, bytes_read, pos = 0;
2270
    DWORD res;
2271

2272
    EnterCriticalSection( &req->read_section );
2273 2274
    for (;;)
    {
2275
        BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2276

2277 2278 2279 2280 2281 2282
        if (eol)
        {
            count = eol - (req->read_buf + req->read_pos);
            bytes_read = count + 1;
        }
        else count = bytes_read = req->read_size;
2283

2284 2285 2286 2287 2288
        count = min( count, *len - pos );
        memcpy( buffer + pos, req->read_buf + req->read_pos, count );
        pos += count;
        remove_data( req, bytes_read );
        if (eol) break;
2289

2290
        if ((res = read_more_data( req, -1 )) != ERROR_SUCCESS || !req->read_size)
2291 2292
        {
            *len = 0;
2293
            TRACE( "returning empty string %u\n", res);
2294
            LeaveCriticalSection( &req->read_section );
2295
            INTERNET_SetLastError(res);
2296 2297
            return FALSE;
        }
2298
    }
2299
    LeaveCriticalSection( &req->read_section );
2300

2301 2302 2303 2304 2305 2306 2307 2308
    if (pos < *len)
    {
        if (pos && buffer[pos - 1] == '\r') pos--;
        *len = pos + 1;
    }
    buffer[*len - 1] = 0;
    TRACE( "returning %s\n", debugstr_a(buffer));
    return TRUE;
2309 2310
}

2311 2312 2313 2314 2315 2316 2317
/* check if we have reached the end of the data to read (the read section must be held) */
static BOOL end_of_read_data( http_request_t *req )
{
    return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
}

/* fetch some more data into the read buffer (the read section must be held) */
2318
static DWORD refill_read_buffer(http_request_t *req, read_mode_t read_mode, DWORD *read_bytes)
2319
{
2320
    DWORD res, read=0, want;
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330

    if(req->read_size == sizeof(req->read_buf))
        return ERROR_SUCCESS;

    if(req->read_pos) {
        if(req->read_size)
            memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
        req->read_pos = 0;
    }

2331
    want = sizeof(req->read_buf) - req->read_size;
2332
    res = req->data_stream->vtbl->read(req->data_stream, req, req->read_buf+req->read_size,
2333 2334
            want, &read, read_mode);
    assert(read <= want);
2335 2336 2337
    req->read_size += read;

    TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2338 2339
    if(read_bytes)
        *read_bytes = read;
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
    return res;
}

/* return the size of data available to be read immediately (the read section must be held) */
static DWORD get_avail_data( http_request_t *req )
{
    return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
}

static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
{
2351
    netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2352 2353
    DWORD avail = 0;

2354 2355 2356 2357 2358
    if(req->netconn)
        NETCON_query_data_available(req->netconn, &avail);
    return netconn_stream->content_length == ~0u
        ? avail
        : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2359 2360 2361 2362 2363
}

static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
{
    netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2364
    return netconn_stream->content_read == netconn_stream->content_length || !req->netconn;
2365 2366 2367 2368 2369 2370
}

static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
        DWORD *read, read_mode_t read_mode)
{
    netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2371
    int len = 0;
2372 2373 2374

    size = min(size, netconn_stream->content_length-netconn_stream->content_read);

2375 2376 2377 2378 2379
    if(read_mode == READMODE_NOBLOCK) {
        DWORD avail = netconn_get_avail_data(stream, req);
        if (size > avail)
            size = avail;
    }
2380

2381 2382
    if(size && req->netconn) {
        if(NETCON_recv(req->netconn, buf, size, read_mode == READMODE_SYNC ? MSG_WAITALL : 0, &len) != ERROR_SUCCESS)
2383
            len = 0;
2384 2385
        if(!len)
            netconn_stream->content_length = netconn_stream->content_read;
2386 2387
    }

2388 2389
    netconn_stream->content_read += *read = len;
    TRACE("read %u bytes\n", len);
2390 2391 2392
    return ERROR_SUCCESS;
}

2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
{
    netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
    BYTE buf[1024];
    DWORD avail;
    int len;

    if(netconn_end_of_data(stream, req))
        return TRUE;

    do {
        avail = netconn_get_avail_data(stream, req);
        if(!avail)
            return FALSE;

        if(NETCON_recv(req->netconn, buf, min(avail, sizeof(buf)), 0, &len) != ERROR_SUCCESS)
            return FALSE;

        netconn_stream->content_read += len;
    }while(netconn_stream->content_read < netconn_stream->content_length);

    return TRUE;
}

2417 2418 2419 2420 2421 2422 2423 2424
static void netconn_destroy(data_stream_t *stream)
{
}

static const data_stream_vtbl_t netconn_stream_vtbl = {
    netconn_get_avail_data,
    netconn_end_of_data,
    netconn_read,
2425
    netconn_drain_content,
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
    netconn_destroy
};

/* read some more data into the read buffer (the read section must be held) */
static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
{
    DWORD res;
    int len;

    if (stream->buf_pos)
    {
        /* move existing data to the start of the buffer */
        if(stream->buf_size)
            memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
        stream->buf_pos = 0;
    }

    if (maxlen == -1) maxlen = sizeof(stream->buf);

2445
    res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
                       maxlen - stream->buf_size, 0, &len );
    if(res == ERROR_SUCCESS)
        stream->buf_size += len;

    return res;
}

/* remove some amount of data from the read buffer (the read section must be held) */
static void remove_chunked_data(chunked_stream_t *stream, int count)
{
    if (!(stream->buf_size -= count)) stream->buf_pos = 0;
    else stream->buf_pos += count;
}

2460
/* discard data contents until we reach end of line (the read section must be held) */
2461
static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2462
{
2463 2464
    DWORD res;

2465
    do
2466
    {
2467
        BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2468 2469
        if (eol)
        {
2470
            remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2471 2472
            break;
        }
2473 2474 2475
        stream->buf_pos = stream->buf_size = 0;  /* discard everything */
        if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
    } while (stream->buf_size);
2476
    return ERROR_SUCCESS;
2477 2478
}

2479
/* read the size of the next chunk (the read section must be held) */
2480
static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2481
{
2482
    /* TODOO */
2483
    DWORD chunk_size = 0, res;
2484

2485 2486 2487
    if(stream->chunk_size != ~0u && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
        return res;

2488 2489
    for (;;)
    {
2490
        while (stream->buf_size)
2491
        {
2492
            char ch = stream->buf[stream->buf_pos];
2493 2494 2495 2496
            if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
            else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
            else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
            else if (ch == ';' || ch == '\r' || ch == '\n')
2497
            {
2498
                TRACE( "reading %u byte chunk\n", chunk_size );
2499 2500 2501
                stream->chunk_size = chunk_size;
                req->contentLength += chunk_size;
                return discard_chunked_eol(stream, req);
2502
            }
2503
            remove_chunked_data(stream, 1);
2504
        }
2505 2506
        if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
        if (!stream->buf_size)
2507
        {
2508
            stream->chunk_size = 0;
2509
            return ERROR_SUCCESS;
2510
        }
2511 2512
    }
}
2513

2514
static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2515
{
2516 2517
    /* Allow reading only from read buffer */
    return 0;
2518
}
2519

2520
static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2521
{
2522 2523 2524
    chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
    return !chunked_stream->chunk_size;
}
2525

2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
        DWORD *read, read_mode_t read_mode)
{
    chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
    DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;

    if(chunked_stream->chunk_size == ~0u) {
        res = start_next_chunk(chunked_stream, req);
        if(res != ERROR_SUCCESS)
            return res;
2536
    }
2537

2538 2539 2540
    while(size && chunked_stream->chunk_size) {
        if(chunked_stream->buf_size) {
            read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2541

2542 2543 2544
            /* this could block */
            if(read_mode == READMODE_NOBLOCK && read_bytes == chunked_stream->chunk_size)
                break;
2545

2546 2547 2548 2549
            memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
            remove_chunked_data(chunked_stream, read_bytes);
        }else {
            read_bytes = min(size, chunked_stream->chunk_size);
2550

2551 2552
            if(read_mode == READMODE_NOBLOCK) {
                DWORD avail;
2553

2554
                if(!NETCON_query_data_available(req->netconn, &avail) || !avail)
2555 2556 2557
                    break;
                if(read_bytes > avail)
                    read_bytes = avail;
2558

2559 2560 2561 2562
                /* this could block */
                if(read_bytes == chunked_stream->chunk_size)
                    break;
            }
2563

2564
            res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, 0, (int*)&read_bytes);
2565 2566 2567
            if(res != ERROR_SUCCESS)
                break;
        }
2568

2569 2570 2571 2572 2573 2574 2575 2576
        chunked_stream->chunk_size -= read_bytes;
        size -= read_bytes;
        ret_read += read_bytes;
        if(!chunked_stream->chunk_size) {
            assert(read_mode != READMODE_NOBLOCK);
            res = start_next_chunk(chunked_stream, req);
            if(res != ERROR_SUCCESS)
                break;
2577
        }
2578 2579 2580

        if(read_mode == READMODE_ASYNC)
            read_mode = READMODE_NOBLOCK;
2581 2582
    }

2583 2584 2585
    TRACE("read %u bytes\n", ret_read);
    *read = ret_read;
    return res;
2586 2587
}

2588 2589 2590 2591 2592 2593 2594 2595
static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
{
    chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;

    /* FIXME: we can do better */
    return !chunked_stream->chunk_size;
}

2596
static void chunked_destroy(data_stream_t *stream)
2597
{
2598 2599 2600
    chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
    heap_free(chunked_stream);
}
2601

2602 2603 2604 2605
static const data_stream_vtbl_t chunked_stream_vtbl = {
    chunked_get_avail_data,
    chunked_end_of_data,
    chunked_read,
2606
    chunked_drain_content,
2607 2608 2609 2610
    chunked_destroy
};

/* set the request content length based on the headers */
2611
static DWORD set_content_length(http_request_t *request)
2612 2613 2614 2615
{
    static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
    WCHAR encoding[20];
    DWORD size;
2616

2617
    if(request->status_code == HTTP_STATUS_NO_CONTENT) {
2618 2619 2620 2621
        request->contentLength = request->netconn_stream.content_length = 0;
        return ERROR_SUCCESS;
    }

2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
    size = sizeof(request->contentLength);
    if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
                            &request->contentLength, &size, NULL) != ERROR_SUCCESS)
        request->contentLength = ~0u;
    request->netconn_stream.content_length = request->contentLength;
    request->netconn_stream.content_read = request->read_size;

    size = sizeof(encoding);
    if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
        !strcmpiW(encoding, szChunked))
    {
        chunked_stream_t *chunked_stream;

        chunked_stream = heap_alloc(sizeof(*chunked_stream));
        if(!chunked_stream)
            return ERROR_OUTOFMEMORY;

        chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
        chunked_stream->buf_size = chunked_stream->buf_pos = 0;
        chunked_stream->chunk_size = ~0u;

        if(request->read_size) {
            memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
            chunked_stream->buf_size = request->read_size;
            request->read_size = request->read_pos = 0;
        }

        request->data_stream = &chunked_stream->data_stream;
        request->contentLength = ~0u;
        request->read_chunked = TRUE;
2652 2653
    }

2654 2655
    if(request->decoding) {
        int encoding_idx;
2656

2657
        static const WCHAR gzipW[] = {'g','z','i','p',0};
2658

2659 2660 2661 2662
        encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
        if(encoding_idx != -1 && !strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW))
            return init_gzip_stream(request);
    }
2663

2664
    return ERROR_SUCCESS;
2665 2666
}

2667
static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2668 2669
{
    INTERNET_ASYNC_RESULT iar;
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680

    iar.dwResult = result;
    iar.dwError = error;

    INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
            sizeof(INTERNET_ASYNC_RESULT));
}

static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif)
{
    DWORD res, read = 0, avail = 0;
2681
    read_mode_t mode;
2682 2683 2684

    TRACE("%p\n", req);

2685
    EnterCriticalSection( &req->read_section );
2686 2687 2688

    mode = first_notif && req->read_size ? READMODE_NOBLOCK : READMODE_ASYNC;
    res = refill_read_buffer(req, mode, &read);
2689 2690
    if(res == ERROR_SUCCESS && !first_notif)
        avail = get_avail_data(req);
2691

2692
    LeaveCriticalSection( &req->read_section );
2693

2694 2695 2696 2697 2698
    if(res != ERROR_SUCCESS || (mode != READMODE_NOBLOCK && !read)) {
        WARN("res %u read %u, closing connection\n", res, read);
        http_release_netconn(req, FALSE);
    }

2699
    if(res == ERROR_SUCCESS)
2700
        send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
2701 2702
    else
        send_request_complete(req, 0, res);
2703 2704
}

2705
/* read data from the http connection (the read section must be held) */
2706
static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
2707
{
2708 2709 2710 2711 2712
    DWORD current_read = 0, ret_read = 0;
    read_mode_t read_mode;
    DWORD res = ERROR_SUCCESS;

    read_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? READMODE_ASYNC : READMODE_SYNC;
2713

2714
    EnterCriticalSection( &req->read_section );
2715

2716 2717 2718 2719 2720 2721 2722
    if(req->read_size) {
        ret_read = min(size, req->read_size);
        memcpy(buffer, req->read_buf+req->read_pos, ret_read);
        req->read_size -= ret_read;
        req->read_pos += ret_read;
        if(read_mode == READMODE_ASYNC)
            read_mode = READMODE_NOBLOCK;
2723 2724
    }

2725 2726 2727
    if(ret_read < size) {
        res = req->data_stream->vtbl->read(req->data_stream, req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, read_mode);
        ret_read += current_read;
2728 2729
    }

2730 2731
    LeaveCriticalSection( &req->read_section );

2732 2733 2734 2735
    *read = ret_read;
    TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );

    if(req->hCacheFile && res == ERROR_SUCCESS && ret_read) {
2736
        BOOL res;
2737
        DWORD written;
2738

2739
        res = WriteFile(req->hCacheFile, buffer, ret_read, &written, NULL);
2740 2741 2742 2743
        if(!res)
            WARN("WriteFile failed: %u\n", GetLastError());
    }

2744 2745
    if(size && !ret_read)
        http_release_netconn(req, res == ERROR_SUCCESS);
2746

2747
    return res;
2748 2749
}

2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
static BOOL drain_content(http_request_t *req, BOOL blocking)
{
    BOOL ret;

    if(!req->netconn || req->contentLength == -1)
        return FALSE;

    if(!strcmpW(req->verb, szHEAD))
        return TRUE;

    if(!blocking)
        return req->data_stream->vtbl->drain_content(req->data_stream, req);

    EnterCriticalSection( &req->read_section );

    while(1) {
        DWORD bytes_read, res;
        BYTE buf[4096];

        res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
        if(res != ERROR_SUCCESS) {
            ret = FALSE;
            break;
        }
        if(!bytes_read) {
            ret = TRUE;
            break;
        }
    }

    LeaveCriticalSection( &req->read_section );
    return ret;
}
2783

2784
static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
2785
{
2786
    http_request_t *req = (http_request_t*)hdr;
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
    DWORD res;

    EnterCriticalSection( &req->read_section );
    if(hdr->dwError == INTERNET_HANDLE_IN_USE)
        hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;

    res = HTTPREQ_Read(req, buffer, size, read, TRUE);
    if(res == ERROR_SUCCESS)
        res = hdr->dwError;
    LeaveCriticalSection( &req->read_section );

    return res;
2799 2800
}

2801
static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
2802 2803
{
    struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
2804
    http_request_t *req = (http_request_t*)workRequest->hdr;
2805 2806 2807 2808 2809 2810 2811
    DWORD res;

    TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);

    res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
            data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);

2812
    send_request_complete(req, res == ERROR_SUCCESS, res);
2813 2814
}

2815
static DWORD HTTPREQ_ReadFileExA(object_header_t *hdr, INTERNET_BUFFERSA *buffers,
2816 2817
        DWORD flags, DWORD_PTR context)
{
2818
    http_request_t *req = (http_request_t*)hdr;
2819
    DWORD res, size, read, error = ERROR_SUCCESS;
2820 2821 2822 2823 2824 2825 2826 2827 2828

    if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
        FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));

    if (buffers->dwStructSize != sizeof(*buffers))
        return ERROR_INVALID_PARAMETER;

    INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);

2829
    if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
2830 2831
    {
        WORKREQUEST workRequest;
2832

2833 2834 2835 2836 2837 2838
        if (TryEnterCriticalSection( &req->read_section ))
        {
            if (get_avail_data(req))
            {
                res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength,
                                   &buffers->dwBufferLength, FALSE);
2839
                size = buffers->dwBufferLength;
2840 2841 2842 2843 2844 2845
                LeaveCriticalSection( &req->read_section );
                goto done;
            }
            LeaveCriticalSection( &req->read_section );
        }

2846 2847 2848
        workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
        workRequest.hdr = WININET_AddRef(&req->hdr);
        workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
2849

2850
        INTERNET_AsyncCall(&workRequest);
2851

2852
        return ERROR_IO_PENDING;
2853 2854
    }

2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
    read = 0;
    size = buffers->dwBufferLength;

    EnterCriticalSection( &req->read_section );
    if(hdr->dwError == ERROR_SUCCESS)
        hdr->dwError = INTERNET_HANDLE_IN_USE;
    else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
        hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;

    while(1) {
        res = HTTPREQ_Read(req, (char*)buffers->lpvBuffer+read, size-read,
                &buffers->dwBufferLength, !(flags & IRF_NO_WAIT));
2867
        if(res != ERROR_SUCCESS)
2868 2869
            break;

2870 2871
        read += buffers->dwBufferLength;
        if(read == size || end_of_read_data(req))
2872
            break;
2873

2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
        LeaveCriticalSection( &req->read_section );

        INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
                &buffers->dwBufferLength, sizeof(buffers->dwBufferLength));
        INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
                INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);

        EnterCriticalSection( &req->read_section );
    }

    if(hdr->dwError == INTERNET_HANDLE_IN_USE)
        hdr->dwError = ERROR_SUCCESS;
    else
        error = hdr->dwError;

    LeaveCriticalSection( &req->read_section );
    size = buffers->dwBufferLength;
    buffers->dwBufferLength = read;
2892

2893
done:
2894 2895 2896 2897 2898
    if (res == ERROR_SUCCESS) {
        INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
                &size, sizeof(size));
    }

2899
    return res==ERROR_SUCCESS ? error : res;
2900 2901
}

2902 2903 2904
static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
2905
    http_request_t *req = (http_request_t*)workRequest->hdr;
2906 2907 2908 2909 2910 2911 2912
    DWORD res;

    TRACE("INTERNETREADFILEEXW %p\n", workRequest->hdr);

    res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
            data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);

2913
    send_request_complete(req, res == ERROR_SUCCESS, res);
2914 2915
}

2916
static DWORD HTTPREQ_ReadFileExW(object_header_t *hdr, INTERNET_BUFFERSW *buffers,
2917 2918 2919
        DWORD flags, DWORD_PTR context)
{

2920
    http_request_t *req = (http_request_t*)hdr;
2921
    DWORD res, size, read, error = ERROR_SUCCESS;
2922 2923 2924 2925 2926 2927 2928 2929 2930

    if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
        FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));

    if (buffers->dwStructSize != sizeof(*buffers))
        return ERROR_INVALID_PARAMETER;

    INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);

2931
    if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
2932 2933
    {
        WORKREQUEST workRequest;
2934

2935 2936 2937 2938 2939 2940
        if (TryEnterCriticalSection( &req->read_section ))
        {
            if (get_avail_data(req))
            {
                res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength,
                                   &buffers->dwBufferLength, FALSE);
2941
                size = buffers->dwBufferLength;
2942 2943 2944 2945 2946 2947
                LeaveCriticalSection( &req->read_section );
                goto done;
            }
            LeaveCriticalSection( &req->read_section );
        }

2948 2949 2950
        workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
        workRequest.hdr = WININET_AddRef(&req->hdr);
        workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
2951

2952
        INTERNET_AsyncCall(&workRequest);
2953

2954
        return ERROR_IO_PENDING;
2955 2956
    }

2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
    read = 0;
    size = buffers->dwBufferLength;

    EnterCriticalSection( &req->read_section );
    if(hdr->dwError == ERROR_SUCCESS)
        hdr->dwError = INTERNET_HANDLE_IN_USE;
    else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
        hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;

    while(1) {
        res = HTTPREQ_Read(req, (char*)buffers->lpvBuffer+read, size-read,
                &buffers->dwBufferLength, !(flags & IRF_NO_WAIT));
2969
        if(res != ERROR_SUCCESS)
2970 2971
            break;

2972 2973
        read += buffers->dwBufferLength;
        if(read == size || end_of_read_data(req))
2974
            break;
2975

2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
        LeaveCriticalSection( &req->read_section );

        INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
                &buffers->dwBufferLength, sizeof(buffers->dwBufferLength));
        INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
                INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);

        EnterCriticalSection( &req->read_section );
    }

    if(hdr->dwError == INTERNET_HANDLE_IN_USE)
        hdr->dwError = ERROR_SUCCESS;
    else
        error = hdr->dwError;

    LeaveCriticalSection( &req->read_section );
    size = buffers->dwBufferLength;
    buffers->dwBufferLength = read;
2994

2995
done:
2996 2997 2998 2999 3000
    if (res == ERROR_SUCCESS) {
        INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
                &size, sizeof(size));
    }

3001
    return res==ERROR_SUCCESS ? error : res;
3002 3003
}

3004
static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3005
{
3006
    DWORD res;
3007
    http_request_t *request = (http_request_t*)hdr;
3008

3009
    INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3010

3011
    *written = 0;
3012
    res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3013
    if (res == ERROR_SUCCESS)
3014
        request->bytesWritten += *written;
3015

3016
    INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3017
    return res;
3018 3019
}

3020 3021
static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
{
3022
    http_request_t *req = (http_request_t*)workRequest->hdr;
3023

3024
    HTTP_ReceiveRequestData(req, FALSE);
3025 3026
}

3027
static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3028
{
3029
    http_request_t *req = (http_request_t*)hdr;
3030 3031 3032

    TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);

3033
    if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3034
    {
3035
        WORKREQUEST workRequest;
3036

3037 3038
        /* never wait, if we can't enter the section we queue an async request right away */
        if (TryEnterCriticalSection( &req->read_section ))
3039
        {
3040
            refill_read_buffer(req, READMODE_NOBLOCK, NULL);
3041 3042 3043 3044
            if ((*available = get_avail_data( req ))) goto done;
            if (end_of_read_data( req )) goto done;
            LeaveCriticalSection( &req->read_section );
        }
3045

3046 3047
        workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
        workRequest.hdr = WININET_AddRef( &req->hdr );
3048

3049
        INTERNET_AsyncCall(&workRequest);
3050

3051
        return ERROR_IO_PENDING;
3052
    }
3053

3054 3055 3056 3057
    EnterCriticalSection( &req->read_section );

    if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
    {
3058
        refill_read_buffer( req, READMODE_ASYNC, NULL );
3059 3060 3061 3062 3063
        *available = get_avail_data( req );
    }

done:
    LeaveCriticalSection( &req->read_section );
3064

3065
    TRACE( "returning %u\n", *available );
3066 3067 3068
    return ERROR_SUCCESS;
}

3069
static const object_vtbl_t HTTPREQVtbl = {
3070
    HTTPREQ_Destroy,
3071
    HTTPREQ_CloseConnection,
3072
    HTTPREQ_QueryOption,
3073
    HTTPREQ_SetOption,
3074
    HTTPREQ_ReadFile,
3075
    HTTPREQ_ReadFileExA,
3076
    HTTPREQ_ReadFileExW,
3077
    HTTPREQ_WriteFile,
3078
    HTTPREQ_QueryDataAvailable,
3079
    NULL
3080 3081
};

3082
/***********************************************************************
3083
 *           HTTP_HttpOpenRequestW (internal)
3084 3085 3086 3087 3088 3089 3090 3091
 *
 * Open a HTTP request handle
 *
 * RETURNS
 *    HINTERNET  a HTTP request handle on success
 *    NULL 	 on failure
 *
 */
3092
static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3093 3094 3095
        LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
        LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
        DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3096
{
3097
    appinfo_t *hIC = session->appInfo;
3098
    http_request_t *request;
3099
    INTERNET_PORT port;
3100
    DWORD len, res = ERROR_SUCCESS;
3101

3102
    TRACE("-->\n");
3103

3104 3105
    request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
    if(!request)
3106 3107
        return ERROR_OUTOFMEMORY;

3108 3109 3110
    request->hdr.htype = WH_HHTTPREQ;
    request->hdr.dwFlags = dwFlags;
    request->hdr.dwContext = dwContext;
3111
    request->contentLength = ~0u;
3112

3113 3114
    request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
    request->data_stream = &request->netconn_stream.data_stream;
3115
    request->connect_timeout = session->connect_timeout;
3116 3117
    request->send_timeout = session->send_timeout;
    request->receive_timeout = session->receive_timeout;
3118

3119
    InitializeCriticalSection( &request->read_section );
3120
    request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3121

3122
    WININET_AddRef( &session->hdr );
3123
    request->session = session;
3124
    list_add_head( &session->hdr.children, &request->hdr.entry );
3125

3126
    port = session->hostPort;
3127 3128 3129
    if(port == INTERNET_INVALID_PORT_NUMBER)
        port = dwFlags & INTERNET_FLAG_SECURE ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;

3130
    request->server = get_server(session->hostName, port, TRUE);
3131 3132 3133 3134 3135
    if(!request->server) {
        WININET_Release(&request->hdr);
        return ERROR_OUTOFMEMORY;
    }

3136
    if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3137
        request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3138
    if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3139
        request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3140

Jacek Caban's avatar
Jacek Caban committed
3141
    if (lpszObjectName && *lpszObjectName) {
3142
        HRESULT rc;
3143 3144 3145

        len = 0;
        rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3146
        if (rc != E_POINTER)
3147
            len = strlenW(lpszObjectName)+1;
3148
        request->path = heap_alloc(len*sizeof(WCHAR));
3149
        rc = UrlEscapeW(lpszObjectName, request->path, &len,
3150
                   URL_ESCAPE_SPACES_ONLY);
3151
        if (rc != S_OK)
3152
        {
3153
            ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3154
            strcpyW(request->path,lpszObjectName);
3155
        }
3156 3157 3158
    }else {
        static const WCHAR slashW[] = {'/',0};

3159
        request->path = heap_strdupW(slashW);
3160
    }
3161

Jacek Caban's avatar
Jacek Caban committed
3162
    if (lpszReferrer && *lpszReferrer)
3163
        HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3164

3165
    if (lpszAcceptTypes)
3166 3167
    {
        int i;
3168 3169 3170
        for (i = 0; lpszAcceptTypes[i]; i++)
        {
            if (!*lpszAcceptTypes[i]) continue;
3171
            HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3172 3173 3174 3175
                               HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
                               HTTP_ADDHDR_FLAG_REQ |
                               (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
        }
3176
    }
3177

3178 3179
    request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
    request->version = heap_strdupW(lpszVersion ? lpszVersion : g_szHttp1_1);
3180

3181 3182 3183
    if (session->hostPort != INTERNET_INVALID_PORT_NUMBER &&
        session->hostPort != INTERNET_DEFAULT_HTTP_PORT &&
        session->hostPort != INTERNET_DEFAULT_HTTPS_PORT)
3184
    {
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197
        WCHAR *host_name;

        static const WCHAR host_formatW[] = {'%','s',':','%','u',0};

        host_name = heap_alloc((strlenW(session->hostName) + 7 /* length of ":65535" + 1 */) * sizeof(WCHAR));
        if (!host_name) {
            res = ERROR_OUTOFMEMORY;
            goto lend;
        }

        sprintfW(host_name, host_formatW, session->hostName, session->hostPort);
        HTTP_ProcessHeader(request, hostW, host_name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
        heap_free(host_name);
3198 3199
    }
    else
3200
        HTTP_ProcessHeader(request, hostW, session->hostName,
3201
                HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3202

3203 3204
    if (session->hostPort == INTERNET_INVALID_PORT_NUMBER)
        session->hostPort = (dwFlags & INTERNET_FLAG_SECURE ?
3205 3206
                        INTERNET_DEFAULT_HTTPS_PORT :
                        INTERNET_DEFAULT_HTTP_PORT);
3207

3208
    if (hIC->proxy && hIC->proxy[0])
3209
        HTTP_DealWithProxy( hIC, session, request );
3210

3211 3212
    INTERNET_SendCallback(&session->hdr, dwContext,
                          INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3213
                          sizeof(HINTERNET));
3214

3215
lend:
3216
    TRACE("<-- %u (%p)\n", res, request);
3217 3218

    if(res != ERROR_SUCCESS) {
3219
        WININET_Release( &request->hdr );
3220 3221 3222
        *ret = NULL;
        return res;
    }
3223

3224
    *ret = request->hdr.hInternet;
3225
    return ERROR_SUCCESS;
3226 3227
}

3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
/***********************************************************************
 *           HttpOpenRequestW (WININET.@)
 *
 * Open a HTTP request handle
 *
 * RETURNS
 *    HINTERNET  a HTTP request handle on success
 *    NULL 	 on failure
 *
 */
HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
	LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
	LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
	DWORD dwFlags, DWORD_PTR dwContext)
{
3243
    http_session_t *session;
3244
    HINTERNET handle = NULL;
3245
    DWORD res;
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257

    TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
          debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
          debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
          dwFlags, dwContext);
    if(lpszAcceptTypes!=NULL)
    {
        int i;
        for(i=0;lpszAcceptTypes[i]!=NULL;i++)
            TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
    }

3258 3259
    session = (http_session_t*) get_handle_object( hHttpSession );
    if (NULL == session ||  session->hdr.htype != WH_HHTTPSESSION)
3260
    {
3261 3262
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
3263 3264 3265 3266 3267 3268 3269 3270 3271
    }

    /*
     * My tests seem to show that the windows version does not
     * become asynchronous until after this point. And anyhow
     * if this call was asynchronous then how would you get the
     * necessary HINTERNET pointer returned by this function.
     *
     */
3272
    res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3273 3274
                                lpszVersion, lpszReferrer, lpszAcceptTypes,
                                dwFlags, dwContext, &handle);
3275
lend:
3276 3277
    if( session )
        WININET_Release( &session->hdr );
3278
    TRACE("returning %p\n", handle);
3279 3280
    if(res != ERROR_SUCCESS)
        SetLastError(res);
3281 3282 3283
    return handle;
}

3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
static const LPCWSTR header_lookup[] = {
    szMime_Version,		/* HTTP_QUERY_MIME_VERSION = 0 */
    szContent_Type,		/* HTTP_QUERY_CONTENT_TYPE = 1 */
    szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
    szContent_ID,		/* HTTP_QUERY_CONTENT_ID = 3 */
    NULL,			/* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
    szContent_Length,		/* HTTP_QUERY_CONTENT_LENGTH =  5 */
    szContent_Language,		/* HTTP_QUERY_CONTENT_LANGUAGE =  6 */
    szAllow,			/* HTTP_QUERY_ALLOW = 7 */
    szPublic,			/* HTTP_QUERY_PUBLIC = 8 */
    szDate,			/* HTTP_QUERY_DATE = 9 */
    szExpires,			/* HTTP_QUERY_EXPIRES = 10 */
    szLast_Modified,		/* HTTP_QUERY_LAST_MODIFIED = 11 */
    NULL,			/* HTTP_QUERY_MESSAGE_ID = 12 */
    szURI,			/* HTTP_QUERY_URI = 13 */
    szFrom,			/* HTTP_QUERY_DERIVED_FROM = 14 */
    NULL,			/* HTTP_QUERY_COST = 15 */
    NULL,			/* HTTP_QUERY_LINK = 16 */
    szPragma,			/* HTTP_QUERY_PRAGMA = 17 */
    NULL,			/* HTTP_QUERY_VERSION = 18 */
    szStatus,			/* HTTP_QUERY_STATUS_CODE = 19 */
    NULL,			/* HTTP_QUERY_STATUS_TEXT = 20 */
    NULL,			/* HTTP_QUERY_RAW_HEADERS = 21 */
    NULL,			/* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
    szConnection,		/* HTTP_QUERY_CONNECTION = 23 */
    szAccept,			/* HTTP_QUERY_ACCEPT = 24 */
    szAccept_Charset,		/* HTTP_QUERY_ACCEPT_CHARSET = 25 */
    szAccept_Encoding,		/* HTTP_QUERY_ACCEPT_ENCODING = 26 */
    szAccept_Language,		/* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
    szAuthorization,		/* HTTP_QUERY_AUTHORIZATION = 28 */
    szContent_Encoding,		/* HTTP_QUERY_CONTENT_ENCODING = 29 */
    NULL,			/* HTTP_QUERY_FORWARDED = 30 */
    NULL,			/* HTTP_QUERY_FROM = 31 */
    szIf_Modified_Since,	/* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
    szLocation,			/* HTTP_QUERY_LOCATION = 33 */
    NULL,			/* HTTP_QUERY_ORIG_URI = 34 */
    szReferer,			/* HTTP_QUERY_REFERER = 35 */
    szRetry_After,		/* HTTP_QUERY_RETRY_AFTER = 36 */
    szServer,			/* HTTP_QUERY_SERVER = 37 */
    NULL,			/* HTTP_TITLE = 38 */
    szUser_Agent,		/* HTTP_QUERY_USER_AGENT = 39 */
    szWWW_Authenticate,		/* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
    szProxy_Authenticate,	/* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
    szAccept_Ranges,		/* HTTP_QUERY_ACCEPT_RANGES = 42 */
    szSet_Cookie,		/* HTTP_QUERY_SET_COOKIE = 43 */
    szCookie,			/* HTTP_QUERY_COOKIE = 44 */
    NULL,			/* HTTP_QUERY_REQUEST_METHOD = 45 */
    NULL,			/* HTTP_QUERY_REFRESH = 46 */
3332
    szContent_Disposition,	/* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3333 3334 3335 3336 3337 3338 3339
    szAge,			/* HTTP_QUERY_AGE = 48 */
    szCache_Control,		/* HTTP_QUERY_CACHE_CONTROL = 49 */
    szContent_Base,		/* HTTP_QUERY_CONTENT_BASE = 50 */
    szContent_Location,		/* HTTP_QUERY_CONTENT_LOCATION = 51 */
    szContent_MD5,		/* HTTP_QUERY_CONTENT_MD5 = 52 */
    szContent_Range,		/* HTTP_QUERY_CONTENT_RANGE = 53 */
    szETag,			/* HTTP_QUERY_ETAG = 54 */
3340
    hostW,			/* HTTP_QUERY_HOST = 55 */
3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355
    szIf_Match,			/* HTTP_QUERY_IF_MATCH = 56 */
    szIf_None_Match,		/* HTTP_QUERY_IF_NONE_MATCH = 57 */
    szIf_Range,			/* HTTP_QUERY_IF_RANGE = 58 */
    szIf_Unmodified_Since,	/* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
    szMax_Forwards,		/* HTTP_QUERY_MAX_FORWARDS = 60 */
    szProxy_Authorization,	/* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
    szRange,			/* HTTP_QUERY_RANGE = 62 */
    szTransfer_Encoding,	/* HTTP_QUERY_TRANSFER_ENCODING = 63 */
    szUpgrade,			/* HTTP_QUERY_UPGRADE = 64 */
    szVary,			/* HTTP_QUERY_VARY = 65 */
    szVia,			/* HTTP_QUERY_VIA = 66 */
    szWarning,			/* HTTP_QUERY_WARNING = 67 */
    szExpect,			/* HTTP_QUERY_EXPECT = 68 */
    szProxy_Connection,		/* HTTP_QUERY_PROXY_CONNECTION = 69 */
    szUnless_Modified_Since,	/* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3356 3357
};

3358 3359
#define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))

3360
/***********************************************************************
3361
 *           HTTP_HttpQueryInfoW (internal)
3362
 */
3363
static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3364
        LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3365
{
3366
    LPHTTPHEADERW lphttpHdr = NULL;
3367
    BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3368
    INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3369
    DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3370
    INT index = -1;
3371

3372
    /* Find requested header structure */
3373
    switch (level)
3374
    {
3375
    case HTTP_QUERY_CUSTOM:
3376
        if (!lpBuffer) return ERROR_INVALID_PARAMETER;
3377
        index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3378 3379
        break;
    case HTTP_QUERY_RAW_HEADERS_CRLF:
3380
        {
3381
            LPWSTR headers;
3382
            DWORD len = 0;
3383
            DWORD res = ERROR_INVALID_PARAMETER;
3384 3385

            if (request_only)
3386
                headers = HTTP_BuildHeaderRequestString(request, request->verb, request->path, request->version);
3387
            else
3388
                headers = request->rawHeaders;
3389

3390 3391 3392
            if (headers)
                len = strlenW(headers) * sizeof(WCHAR);

3393
            if (len + sizeof(WCHAR) > *lpdwBufferLength)
3394
            {
3395
                len += sizeof(WCHAR);
3396
                res = ERROR_INSUFFICIENT_BUFFER;
3397 3398
            }
            else if (lpBuffer)
3399
            {
3400 3401 3402 3403
                if (headers)
                    memcpy(lpBuffer, headers, len + sizeof(WCHAR));
                else
                {
3404 3405
                    len = strlenW(szCrLf) * sizeof(WCHAR);
                    memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
3406
                }
3407
                TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3408
                res = ERROR_SUCCESS;
3409
            }
3410
            *lpdwBufferLength = len;
3411

3412
            if (request_only) heap_free(headers);
3413
            return res;
3414
        }
3415
    case HTTP_QUERY_RAW_HEADERS:
3416
        {
3417
            LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(request->rawHeaders, szCrLf);
3418
            DWORD i, size = 0;
3419
            LPWSTR pszString = lpBuffer;
3420 3421 3422 3423 3424 3425 3426 3427

            for (i = 0; ppszRawHeaderLines[i]; i++)
                size += strlenW(ppszRawHeaderLines[i]) + 1;

            if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
            {
                HTTP_FreeTokens(ppszRawHeaderLines);
                *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
3428
                return ERROR_INSUFFICIENT_BUFFER;
3429
            }
3430
            if (pszString)
3431
            {
3432 3433 3434 3435 3436 3437 3438 3439
                for (i = 0; ppszRawHeaderLines[i]; i++)
                {
                    DWORD len = strlenW(ppszRawHeaderLines[i]);
                    memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
                    pszString += len+1;
                }
                *pszString = '\0';
                TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
3440
            }
3441
            *lpdwBufferLength = size * sizeof(WCHAR);
3442 3443
            HTTP_FreeTokens(ppszRawHeaderLines);

3444
            return ERROR_SUCCESS;
3445
        }
3446
    case HTTP_QUERY_STATUS_TEXT:
3447
        if (request->statusText)
3448
        {
3449
            DWORD len = strlenW(request->statusText);
3450 3451 3452
            if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
            {
                *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3453
                return ERROR_INSUFFICIENT_BUFFER;
3454
            }
3455 3456
            if (lpBuffer)
            {
3457
                memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3458 3459
                TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
            }
3460
            *lpdwBufferLength = len * sizeof(WCHAR);
3461
            return ERROR_SUCCESS;
3462
        }
3463
        break;
3464
    case HTTP_QUERY_VERSION:
3465
        if (request->version)
3466
        {
3467
            DWORD len = strlenW(request->version);
3468 3469 3470
            if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
            {
                *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3471
                return ERROR_INSUFFICIENT_BUFFER;
3472
            }
3473 3474
            if (lpBuffer)
            {
3475
                memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3476 3477
                TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
            }
3478
            *lpdwBufferLength = len * sizeof(WCHAR);
3479
            return ERROR_SUCCESS;
3480
        }
3481
        break;
3482
    case HTTP_QUERY_CONTENT_ENCODING:
3483
        index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3484 3485
                requested_index,request_only);
        break;
3486 3487 3488
    case HTTP_QUERY_STATUS_CODE: {
        DWORD res = ERROR_SUCCESS;

3489 3490 3491 3492
        if(request_only)
            return ERROR_HTTP_INVALID_QUERY_REQUEST;

        if(requested_index)
3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505
            break;

        if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
            if(*lpdwBufferLength >= sizeof(DWORD))
                *(DWORD*)lpBuffer = request->status_code;
            else
                res = ERROR_INSUFFICIENT_BUFFER;
            *lpdwBufferLength = sizeof(DWORD);
        }else {
            WCHAR buf[12];
            DWORD size;
            static const WCHAR formatW[] = {'%','u',0};

3506
            size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3507

3508 3509 3510 3511
            if(size <= *lpdwBufferLength) {
                memcpy(lpBuffer, buf, size+sizeof(WCHAR));
            }else {
                size += sizeof(WCHAR);
3512
                res = ERROR_INSUFFICIENT_BUFFER;
3513
            }
3514 3515 3516 3517 3518

            *lpdwBufferLength = size;
        }
        return res;
    }
3519
    default:
3520 3521
        assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));

3522
        if (level < LAST_TABLE_HEADER && header_lookup[level])
3523
            index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3524
                                              requested_index,request_only);
3525 3526
    }

3527
    if (index >= 0)
3528
        lphttpHdr = &request->custHeaders[index];
3529

Austin English's avatar
Austin English committed
3530
    /* Ensure header satisfies requested attributes */
3531 3532 3533
    if (!lphttpHdr ||
        ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
         (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3534
    {
3535
        return ERROR_HTTP_HEADER_NOT_FOUND;
3536
    }
3537

3538
    if (lpdwIndex) (*lpdwIndex)++;
3539

Austin English's avatar
Austin English committed
3540
    /* coalesce value to requested type */
3541
    if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3542
    {
3543 3544
        *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
        TRACE(" returning number: %d\n", *(int *)lpBuffer);
3545
     }
3546
    else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3547 3548 3549 3550
    {
        time_t tmpTime;
        struct tm tmpTM;
        SYSTEMTIME *STHook;
3551

3552 3553 3554
        tmpTime = ConvertTimeString(lphttpHdr->lpszValue);

        tmpTM = *gmtime(&tmpTime);
3555 3556 3557 3558 3559 3560 3561 3562 3563
        STHook = (SYSTEMTIME *)lpBuffer;
        STHook->wDay = tmpTM.tm_mday;
        STHook->wHour = tmpTM.tm_hour;
        STHook->wMilliseconds = 0;
        STHook->wMinute = tmpTM.tm_min;
        STHook->wDayOfWeek = tmpTM.tm_wday;
        STHook->wMonth = tmpTM.tm_mon + 1;
        STHook->wSecond = tmpTM.tm_sec;
        STHook->wYear = tmpTM.tm_year;
3564

3565 3566 3567
        TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
              STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
              STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3568
    }
3569
    else if (lphttpHdr->lpszValue)
3570
    {
3571
        DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3572

3573
        if (len > *lpdwBufferLength)
3574
        {
3575
            *lpdwBufferLength = len;
3576
            return ERROR_INSUFFICIENT_BUFFER;
3577
        }
3578 3579 3580
        if (lpBuffer)
        {
            memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3581
            TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3582
        }
3583
        *lpdwBufferLength = len - sizeof(WCHAR);
3584
    }
3585
    return ERROR_SUCCESS;
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
}

/***********************************************************************
 *           HttpQueryInfoW (WININET.@)
 *
 * Queries for information about an HTTP request
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3599
        LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3600
{
3601
    http_request_t *request;
3602
    DWORD res;
3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649

    if (TRACE_ON(wininet)) {
#define FE(x) { x, #x }
	static const wininet_flag_info query_flags[] = {
	    FE(HTTP_QUERY_MIME_VERSION),
	    FE(HTTP_QUERY_CONTENT_TYPE),
	    FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
	    FE(HTTP_QUERY_CONTENT_ID),
	    FE(HTTP_QUERY_CONTENT_DESCRIPTION),
	    FE(HTTP_QUERY_CONTENT_LENGTH),
	    FE(HTTP_QUERY_CONTENT_LANGUAGE),
	    FE(HTTP_QUERY_ALLOW),
	    FE(HTTP_QUERY_PUBLIC),
	    FE(HTTP_QUERY_DATE),
	    FE(HTTP_QUERY_EXPIRES),
	    FE(HTTP_QUERY_LAST_MODIFIED),
	    FE(HTTP_QUERY_MESSAGE_ID),
	    FE(HTTP_QUERY_URI),
	    FE(HTTP_QUERY_DERIVED_FROM),
	    FE(HTTP_QUERY_COST),
	    FE(HTTP_QUERY_LINK),
	    FE(HTTP_QUERY_PRAGMA),
	    FE(HTTP_QUERY_VERSION),
	    FE(HTTP_QUERY_STATUS_CODE),
	    FE(HTTP_QUERY_STATUS_TEXT),
	    FE(HTTP_QUERY_RAW_HEADERS),
	    FE(HTTP_QUERY_RAW_HEADERS_CRLF),
	    FE(HTTP_QUERY_CONNECTION),
	    FE(HTTP_QUERY_ACCEPT),
	    FE(HTTP_QUERY_ACCEPT_CHARSET),
	    FE(HTTP_QUERY_ACCEPT_ENCODING),
	    FE(HTTP_QUERY_ACCEPT_LANGUAGE),
	    FE(HTTP_QUERY_AUTHORIZATION),
	    FE(HTTP_QUERY_CONTENT_ENCODING),
	    FE(HTTP_QUERY_FORWARDED),
	    FE(HTTP_QUERY_FROM),
	    FE(HTTP_QUERY_IF_MODIFIED_SINCE),
	    FE(HTTP_QUERY_LOCATION),
	    FE(HTTP_QUERY_ORIG_URI),
	    FE(HTTP_QUERY_REFERER),
	    FE(HTTP_QUERY_RETRY_AFTER),
	    FE(HTTP_QUERY_SERVER),
	    FE(HTTP_QUERY_TITLE),
	    FE(HTTP_QUERY_USER_AGENT),
	    FE(HTTP_QUERY_WWW_AUTHENTICATE),
	    FE(HTTP_QUERY_PROXY_AUTHENTICATE),
	    FE(HTTP_QUERY_ACCEPT_RANGES),
3650 3651
        FE(HTTP_QUERY_SET_COOKIE),
        FE(HTTP_QUERY_COOKIE),
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
	    FE(HTTP_QUERY_REQUEST_METHOD),
	    FE(HTTP_QUERY_REFRESH),
	    FE(HTTP_QUERY_CONTENT_DISPOSITION),
	    FE(HTTP_QUERY_AGE),
	    FE(HTTP_QUERY_CACHE_CONTROL),
	    FE(HTTP_QUERY_CONTENT_BASE),
	    FE(HTTP_QUERY_CONTENT_LOCATION),
	    FE(HTTP_QUERY_CONTENT_MD5),
	    FE(HTTP_QUERY_CONTENT_RANGE),
	    FE(HTTP_QUERY_ETAG),
	    FE(HTTP_QUERY_HOST),
	    FE(HTTP_QUERY_IF_MATCH),
	    FE(HTTP_QUERY_IF_NONE_MATCH),
	    FE(HTTP_QUERY_IF_RANGE),
	    FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
	    FE(HTTP_QUERY_MAX_FORWARDS),
	    FE(HTTP_QUERY_PROXY_AUTHORIZATION),
	    FE(HTTP_QUERY_RANGE),
	    FE(HTTP_QUERY_TRANSFER_ENCODING),
	    FE(HTTP_QUERY_UPGRADE),
	    FE(HTTP_QUERY_VARY),
	    FE(HTTP_QUERY_VIA),
	    FE(HTTP_QUERY_WARNING),
	    FE(HTTP_QUERY_CUSTOM)
	};
	static const wininet_flag_info modifier_flags[] = {
	    FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
	    FE(HTTP_QUERY_FLAG_SYSTEMTIME),
	    FE(HTTP_QUERY_FLAG_NUMBER),
	    FE(HTTP_QUERY_FLAG_COALESCE)
	};
#undef FE
	DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
	DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3686
	DWORD i;
3687

3688
	TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3689 3690 3691
	TRACE("  Attribute:");
	for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
	    if (query_flags[i].val == info) {
Diego Pettenò's avatar
Diego Pettenò committed
3692
		TRACE(" %s", query_flags[i].name);
3693 3694 3695 3696
		break;
	    }
	}
	if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3697
	    TRACE(" Unknown (%08x)", info);
3698 3699
	}

Diego Pettenò's avatar
Diego Pettenò committed
3700
	TRACE(" Modifier:");
3701 3702
	for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
	    if (modifier_flags[i].val & info_mod) {
Diego Pettenò's avatar
Diego Pettenò committed
3703
		TRACE(" %s", modifier_flags[i].name);
3704 3705 3706 3707 3708
		info_mod &= ~ modifier_flags[i].val;
	    }
	}
	
	if (info_mod) {
3709
	    TRACE(" Unknown (%08x)", info_mod);
3710
	}
Diego Pettenò's avatar
Diego Pettenò committed
3711
	TRACE("\n");
3712 3713
    }
    
3714 3715
    request = (http_request_t*) get_handle_object( hHttpRequest );
    if (NULL == request ||  request->hdr.htype != WH_HHTTPREQ)
3716
    {
3717 3718
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
3719 3720
    }

3721 3722
    if (lpBuffer == NULL)
        *lpdwBufferLength = 0;
3723
    res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3724
                               lpBuffer, lpdwBufferLength, lpdwIndex);
3725

3726
lend:
3727 3728
    if( request )
         WININET_Release( &request->hdr );
3729

3730 3731 3732 3733
    TRACE("%u <--\n", res);
    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
3734 3735
}

3736
/***********************************************************************
3737
 *           HttpQueryInfoA (WININET.@)
3738 3739 3740 3741 3742 3743 3744 3745
 *
 * Queries for information about an HTTP request
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
3746
BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3747 3748 3749
	LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
{
    BOOL result;
3750 3751 3752
    DWORD len;
    WCHAR* bufferW;

3753 3754 3755
    if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
       (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
    {
3756 3757
        return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
                               lpdwBufferLength, lpdwIndex );
3758
    }
3759

3760 3761
    if (lpBuffer)
    {
3762
        DWORD alloclen;
3763
        len = (*lpdwBufferLength)*sizeof(WCHAR);
3764 3765 3766 3767 3768 3769 3770 3771
        if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
        {
            alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
            if (alloclen < len)
                alloclen = len;
        }
        else
            alloclen = len;
3772
        bufferW = heap_alloc(alloclen);
3773 3774
        /* buffer is in/out because of HTTP_QUERY_CUSTOM */
        if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3775
            MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3776 3777 3778 3779 3780 3781
    } else
    {
        bufferW = NULL;
        len = 0;
    }

3782 3783 3784
    result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
                           &len, lpdwIndex );
    if( result )
3785
    {
3786
        len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3787
                                     lpBuffer, *lpdwBufferLength, NULL, NULL );
3788 3789 3790
        *lpdwBufferLength = len - 1;

        TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3791
    }
3792 3793 3794 3795 3796
    else
        /* since the strings being returned from HttpQueryInfoW should be
         * only ASCII characters, it is reasonable to assume that all of
         * the Unicode characters can be reduced to a single byte */
        *lpdwBufferLength = len / sizeof(WCHAR);
3797

3798
    heap_free( bufferW );
3799 3800
    return result;
}
3801 3802

/***********************************************************************
3803
 *           HTTP_GetRedirectURL (internal)
3804
 */
3805
static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
3806
{
3807 3808
    static WCHAR szHttp[] = {'h','t','t','p',0};
    static WCHAR szHttps[] = {'h','t','t','p','s',0};
3809
    http_session_t *session = request->session;
3810 3811 3812 3813
    URL_COMPONENTSW urlComponents;
    DWORD url_length = 0;
    LPWSTR orig_url;
    LPWSTR combined_url;
3814

3815
    urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3816
    urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3817
    urlComponents.dwSchemeLength = 0;
3818
    urlComponents.lpszHostName = session->hostName;
3819
    urlComponents.dwHostNameLength = 0;
3820 3821
    urlComponents.nPort = session->hostPort;
    urlComponents.lpszUserName = session->userName;
3822 3823 3824
    urlComponents.dwUserNameLength = 0;
    urlComponents.lpszPassword = NULL;
    urlComponents.dwPasswordLength = 0;
3825
    urlComponents.lpszUrlPath = request->path;
3826 3827 3828
    urlComponents.dwUrlPathLength = 0;
    urlComponents.lpszExtraInfo = NULL;
    urlComponents.dwExtraInfoLength = 0;
3829

3830 3831 3832
    if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
        (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
        return NULL;
3833

3834
    orig_url = heap_alloc(url_length);
3835

3836 3837 3838 3839
    /* convert from bytes to characters */
    url_length = url_length / sizeof(WCHAR) - 1;
    if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
    {
3840
        heap_free(orig_url);
3841 3842
        return NULL;
    }
3843

3844 3845 3846 3847
    url_length = 0;
    if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
        (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
    {
3848
        heap_free(orig_url);
3849 3850
        return NULL;
    }
3851
    combined_url = heap_alloc(url_length * sizeof(WCHAR));
3852

3853 3854
    if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
    {
3855 3856
        heap_free(orig_url);
        heap_free(combined_url);
3857 3858
        return NULL;
    }
3859
    heap_free(orig_url);
3860 3861
    return combined_url;
}
3862 3863


3864 3865 3866
/***********************************************************************
 *           HTTP_HandleRedirect (internal)
 */
3867
static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
3868
{
3869
    http_session_t *session = request->session;
3870
    appinfo_t *hIC = session->appInfo;
3871
    BOOL using_proxy = hIC->proxy && hIC->proxy[0];
3872
    WCHAR path[INTERNET_MAX_PATH_LENGTH];
3873
    int index;
3874

3875
    if(lpszUrl[0]=='/')
3876
    {
3877 3878
        /* if it's an absolute path, keep the same session info */
        lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
3879
    }
3880 3881 3882
    else
    {
        URL_COMPONENTSW urlComponents;
3883 3884 3885
        WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
        WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
        WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
3886 3887 3888 3889
        BOOL custom_port = FALSE;

        static WCHAR httpW[] = {'h','t','t','p',0};
        static WCHAR httpsW[] = {'h','t','t','p','s',0};
3890

3891 3892 3893
        userName[0] = 0;
        hostName[0] = 0;
        protocol[0] = 0;
3894

3895 3896
        urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
        urlComponents.lpszScheme = protocol;
3897
        urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
3898
        urlComponents.lpszHostName = hostName;
3899
        urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
3900
        urlComponents.lpszUserName = userName;
3901
        urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
3902 3903 3904
        urlComponents.lpszPassword = NULL;
        urlComponents.dwPasswordLength = 0;
        urlComponents.lpszUrlPath = path;
3905
        urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
3906 3907 3908
        urlComponents.lpszExtraInfo = NULL;
        urlComponents.dwExtraInfoLength = 0;
        if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
3909
            return INTERNET_GetLastError();
3910

3911 3912 3913 3914 3915 3916
        if(!strcmpiW(protocol, httpW)) {
            if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
                TRACE("redirect from secure page to non-secure page\n");
                /* FIXME: warn about from secure redirect to non-secure page */
                request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
            }
3917

3918
            if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3919
                urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3920 3921 3922 3923 3924 3925 3926 3927
            else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
                custom_port = TRUE;
        }else if(!strcmpiW(protocol, httpsW)) {
            if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
                TRACE("redirect from non-secure page to secure page\n");
                /* FIXME: notify about redirect to secure page */
                request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
            }
3928

3929 3930 3931 3932 3933
            if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
                urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
            else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
                custom_port = TRUE;
        }
3934

3935
        heap_free(session->hostName);
3936 3937

        if(custom_port) {
3938
            int len;
3939
            static const WCHAR fmt[] = {'%','s',':','%','u',0};
3940 3941
            len = lstrlenW(hostName);
            len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3942
            session->hostName = heap_alloc(len*sizeof(WCHAR));
3943
            sprintfW(session->hostName, fmt, hostName, urlComponents.nPort);
3944
        }
3945
        else
3946
            session->hostName = heap_strdupW(hostName);
3947

3948
        HTTP_ProcessHeader(request, hostW, session->hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3949

3950
        heap_free(session->userName);
3951
        session->userName = NULL;
3952
        if (userName[0])
3953
            session->userName = heap_strdupW(userName);
3954

3955
        reset_data_stream(request);
3956

3957 3958 3959
        if(!using_proxy && (strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort)) {
            server_t *new_server;

3960
            new_server = get_server(hostName, urlComponents.nPort, TRUE);
3961 3962
            server_release(request->server);
            request->server = new_server;
3963
        }
3964
    }
3965
    heap_free(request->path);
3966
    request->path=NULL;
3967
    if (*path)
3968
    {
3969 3970 3971 3972 3973 3974
        DWORD needed = 0;
        HRESULT rc;

        rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
        if (rc != E_POINTER)
            needed = strlenW(path)+1;
3975
        request->path = heap_alloc(needed*sizeof(WCHAR));
3976
        rc = UrlEscapeW(path, request->path, &needed,
3977 3978 3979 3980
                        URL_ESCAPE_SPACES_ONLY);
        if (rc != S_OK)
        {
            ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3981
            strcpyW(request->path,path);
3982
        }
3983
    }
3984

3985
    /* Remove custom content-type/length headers on redirects.  */
3986
    index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
3987
    if (0 <= index)
3988 3989
        HTTP_DeleteCustomHeader(request, index);
    index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
3990
    if (0 <= index)
3991
        HTTP_DeleteCustomHeader(request, index);
3992

3993
    return ERROR_SUCCESS;
3994 3995
}

3996
/***********************************************************************
3997
 *           HTTP_build_req (internal)
3998
 *
3999
 *  concatenate all the strings in the request together
4000
 */
4001
static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4002
{
4003 4004
    LPCWSTR *t;
    LPWSTR str;
4005

4006 4007 4008
    for( t = list; *t ; t++  )
        len += strlenW( *t );
    len++;
4009

4010
    str = heap_alloc(len*sizeof(WCHAR));
4011
    *str = 0;
4012

4013 4014
    for( t = list; *t ; t++ )
        strcatW( str, *t );
4015

4016 4017
    return str;
}
4018

4019
static DWORD HTTP_SecureProxyConnect(http_request_t *request)
4020 4021 4022 4023 4024 4025 4026 4027 4028
{
    LPWSTR lpszPath;
    LPWSTR requestString;
    INT len;
    INT cnt;
    INT responseLen;
    char *ascii_req;
    DWORD res;
    static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
4029
    static const WCHAR szFormat[] = {'%','s',':','%','u',0};
4030
    http_session_t *session = request->session;
4031

4032
    TRACE("\n");
4033

4034
    lpszPath = heap_alloc((lstrlenW( session->hostName ) + 13)*sizeof(WCHAR));
4035
    sprintfW( lpszPath, szFormat, session->hostName, session->hostPort );
4036
    requestString = HTTP_BuildHeaderRequestString( request, szConnect, lpszPath, g_szHttp1_1 );
4037
    heap_free( lpszPath );
4038

4039 4040 4041
    len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
                                NULL, 0, NULL, NULL );
    len--; /* the nul terminator isn't needed */
4042
    ascii_req = heap_alloc(len);
4043 4044
    WideCharToMultiByte( CP_ACP, 0, requestString, -1, ascii_req, len, NULL, NULL );
    heap_free( requestString );
4045

4046 4047
    TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );

4048
    NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4049
    res = NETCON_send( request->netconn, ascii_req, len, 0, &cnt );
4050
    heap_free( ascii_req );
4051 4052 4053
    if (res != ERROR_SUCCESS)
        return res;

4054
    responseLen = HTTP_GetResponseHeaders( request, TRUE );
4055 4056 4057 4058 4059 4060
    if (!responseLen)
        return ERROR_HTTP_INVALID_HEADER;

    return ERROR_SUCCESS;
}

4061
static void HTTP_InsertCookies(http_request_t *request)
4062
{
4063 4064 4065
    DWORD cookie_size, size, cnt = 0;
    HTTPHEADERW *host;
    WCHAR *cookies;
4066

4067
    static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' ',0};
4068

4069 4070 4071
    host = HTTP_GetHeader(request, hostW);
    if(!host)
        return;
4072

4073 4074
    if(!get_cookie(host->lpszValue, request->path, NULL, &cookie_size))
        return;
4075

4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086
    size = sizeof(cookieW) + cookie_size * sizeof(WCHAR) + sizeof(szCrLf);
    if(!(cookies = heap_alloc(size)))
        return;

    cnt += sprintfW(cookies, cookieW);
    get_cookie(host->lpszValue, request->path, cookies+cnt, &cookie_size);
    strcatW(cookies, szCrLf);

    HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);

    heap_free(cookies);
4087 4088
}

4089
static WORD HTTP_ParseWkday(LPCWSTR day)
4090
{
4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102
    static const WCHAR days[7][4] = {{ 's','u','n',0 },
                                     { 'm','o','n',0 },
                                     { 't','u','e',0 },
                                     { 'w','e','d',0 },
                                     { 't','h','u',0 },
                                     { 'f','r','i',0 },
                                     { 's','a','t',0 }};
    int i;
    for (i = 0; i < sizeof(days)/sizeof(*days); i++)
        if (!strcmpiW(day, days[i]))
            return i;

4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137
    /* Invalid */
    return 7;
}

static WORD HTTP_ParseMonth(LPCWSTR month)
{
    static const WCHAR jan[] = { 'j','a','n',0 };
    static const WCHAR feb[] = { 'f','e','b',0 };
    static const WCHAR mar[] = { 'm','a','r',0 };
    static const WCHAR apr[] = { 'a','p','r',0 };
    static const WCHAR may[] = { 'm','a','y',0 };
    static const WCHAR jun[] = { 'j','u','n',0 };
    static const WCHAR jul[] = { 'j','u','l',0 };
    static const WCHAR aug[] = { 'a','u','g',0 };
    static const WCHAR sep[] = { 's','e','p',0 };
    static const WCHAR oct[] = { 'o','c','t',0 };
    static const WCHAR nov[] = { 'n','o','v',0 };
    static const WCHAR dec[] = { 'd','e','c',0 };

    if (!strcmpiW(month, jan)) return 1;
    if (!strcmpiW(month, feb)) return 2;
    if (!strcmpiW(month, mar)) return 3;
    if (!strcmpiW(month, apr)) return 4;
    if (!strcmpiW(month, may)) return 5;
    if (!strcmpiW(month, jun)) return 6;
    if (!strcmpiW(month, jul)) return 7;
    if (!strcmpiW(month, aug)) return 8;
    if (!strcmpiW(month, sep)) return 9;
    if (!strcmpiW(month, oct)) return 10;
    if (!strcmpiW(month, nov)) return 11;
    if (!strcmpiW(month, dec)) return 12;
    /* Invalid */
    return 0;
}

4138 4139 4140 4141
/* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
 * optionally preceded by whitespace.
 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
 * st, and sets *str to the first character after the time format.
4142
 */
4143
static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4144
{
4145 4146
    LPCWSTR ptr = *str;
    WCHAR *nextPtr;
4147 4148
    unsigned long num;

4149 4150 4151 4152 4153
    while (isspaceW(*ptr))
        ptr++;

    num = strtoulW(ptr, &nextPtr, 10);
    if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4154
    {
4155
        ERR("unexpected time format %s\n", debugstr_w(ptr));
4156 4157
        return FALSE;
    }
4158
    if (num > 23)
4159
    {
4160
        ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4161 4162
        return FALSE;
    }
4163 4164 4165 4166
    ptr = nextPtr + 1;
    st->wHour = (WORD)num;
    num = strtoulW(ptr, &nextPtr, 10);
    if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4167
    {
4168
        ERR("unexpected time format %s\n", debugstr_w(ptr));
4169 4170
        return FALSE;
    }
4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
    if (num > 59)
    {
        ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
        return FALSE;
    }
    ptr = nextPtr + 1;
    st->wMinute = (WORD)num;
    num = strtoulW(ptr, &nextPtr, 10);
    if (!nextPtr || nextPtr <= ptr)
    {
        ERR("unexpected time format %s\n", debugstr_w(ptr));
        return FALSE;
    }
    if (num > 59)
    {
        ERR("unexpected second in time format %s\n", debugstr_w(ptr));
        return FALSE;
    }
    ptr = nextPtr + 1;
    *str = ptr;
    st->wSecond = (WORD)num;
    return TRUE;
}
4194

4195 4196 4197 4198 4199 4200 4201
static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
{
    static const WCHAR gmt[]= { 'G','M','T',0 };
    WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
    LPCWSTR ptr;
    SYSTEMTIME st = { 0 };
    unsigned long num;
4202

4203 4204 4205 4206
    for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
         dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
        *dayPtr = *ptr;
    *dayPtr = 0;
4207
    st.wDayOfWeek = HTTP_ParseWkday(day);
4208
    if (st.wDayOfWeek >= 7)
4209
    {
4210
        ERR("unexpected weekday %s\n", debugstr_w(day));
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
        return FALSE;
    }

    while (isspaceW(*ptr))
        ptr++;

    for (monthPtr = month; !isspace(*ptr) &&
         monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
         monthPtr++, ptr++)
        *monthPtr = *ptr;
    *monthPtr = 0;
    st.wMonth = HTTP_ParseMonth(month);
    if (!st.wMonth || st.wMonth > 12)
    {
        ERR("unexpected month %s\n", debugstr_w(month));
        return FALSE;
    }

    while (isspaceW(*ptr))
        ptr++;

    num = strtoulW(ptr, &nextPtr, 10);
4233
    if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4234
    {
4235
        ERR("unexpected day %s\n", debugstr_w(ptr));
4236 4237 4238
        return FALSE;
    }
    ptr = nextPtr;
4239 4240 4241 4242 4243 4244 4245
    st.wDay = (WORD)num;

    while (isspaceW(*ptr))
        ptr++;

    if (!HTTP_ParseTime(&st, &ptr))
        return FALSE;
4246 4247 4248 4249 4250

    while (isspaceW(*ptr))
        ptr++;

    num = strtoulW(ptr, &nextPtr, 10);
4251
    if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4252
    {
4253
        ERR("unexpected year %s\n", debugstr_w(ptr));
4254 4255
        return FALSE;
    }
4256 4257 4258 4259 4260 4261 4262 4263 4264 4265
    ptr = nextPtr;
    st.wYear = (WORD)num;

    while (isspaceW(*ptr))
        ptr++;

    /* asctime() doesn't report a timezone, but some web servers do, so accept
     * with or without GMT.
     */
    if (*ptr && strcmpW(ptr, gmt))
4266
    {
4267
        ERR("unexpected timezone %s\n", debugstr_w(ptr));
4268 4269
        return FALSE;
    }
4270 4271 4272 4273 4274 4275 4276 4277 4278
    return SystemTimeToFileTime(&st, ft);
}

static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
{
    static const WCHAR gmt[]= { 'G','M','T',0 };
    WCHAR *nextPtr, day[4], month[4], *monthPtr;
    LPCWSTR ptr;
    unsigned long num;
4279
    SYSTEMTIME st = { 0 };
4280 4281 4282 4283 4284

    ptr = strchrW(value, ',');
    if (!ptr)
        return FALSE;
    if (ptr - value != 3)
4285
    {
4286
        WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4287 4288
        return FALSE;
    }
4289 4290
    memcpy(day, value, (ptr - value) * sizeof(WCHAR));
    day[3] = 0;
4291
    st.wDayOfWeek = HTTP_ParseWkday(day);
4292
    if (st.wDayOfWeek > 6)
4293
    {
4294
        WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4295 4296
        return FALSE;
    }
4297 4298 4299 4300 4301
    ptr++;

    while (isspaceW(*ptr))
        ptr++;

4302
    num = strtoulW(ptr, &nextPtr, 10);
4303
    if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4304
    {
4305
        WARN("unexpected day %s\n", debugstr_w(value));
4306 4307
        return FALSE;
    }
4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
    ptr = nextPtr;
    st.wDay = (WORD)num;

    while (isspaceW(*ptr))
        ptr++;

    for (monthPtr = month; !isspace(*ptr) &&
         monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
         monthPtr++, ptr++)
        *monthPtr = *ptr;
    *monthPtr = 0;
    st.wMonth = HTTP_ParseMonth(month);
    if (!st.wMonth || st.wMonth > 12)
4321
    {
4322
        WARN("unexpected month %s\n", debugstr_w(month));
4323 4324
        return FALSE;
    }
4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339

    while (isspaceW(*ptr))
        ptr++;

    num = strtoulW(ptr, &nextPtr, 10);
    if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
    {
        ERR("unexpected year %s\n", debugstr_w(value));
        return FALSE;
    }
    ptr = nextPtr;
    st.wYear = (WORD)num;

    if (!HTTP_ParseTime(&st, &ptr))
        return FALSE;
4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351

    while (isspaceW(*ptr))
        ptr++;

    if (strcmpW(ptr, gmt))
    {
        ERR("unexpected time zone %s\n", debugstr_w(ptr));
        return FALSE;
    }
    return SystemTimeToFileTime(&st, ft);
}

4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391
static WORD HTTP_ParseWeekday(LPCWSTR day)
{
    static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
                                     { 'm','o','n','d','a','y',0 },
                                     { 't','u','e','s','d','a','y',0 },
                                     { 'w','e','d','n','e','s','d','a','y',0 },
                                     { 't','h','u','r','s','d','a','y',0 },
                                     { 'f','r','i','d','a','y',0 },
                                     { 's','a','t','u','r','d','a','y',0 }};
    int i;
    for (i = 0; i < sizeof(days)/sizeof(*days); i++)
        if (!strcmpiW(day, days[i]))
            return i;

    /* Invalid */
    return 7;
}

static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
{
    static const WCHAR gmt[]= { 'G','M','T',0 };
    WCHAR *nextPtr, day[10], month[4], *monthPtr;
    LPCWSTR ptr;
    unsigned long num;
    SYSTEMTIME st = { 0 };

    ptr = strchrW(value, ',');
    if (!ptr)
        return FALSE;
    if (ptr - value == 3)
    {
        memcpy(day, value, (ptr - value) * sizeof(WCHAR));
        day[3] = 0;
        st.wDayOfWeek = HTTP_ParseWkday(day);
        if (st.wDayOfWeek > 6)
        {
            ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
            return FALSE;
        }
    }
4392
    else if (ptr - value < sizeof(day) / sizeof(day[0]))
4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470
    {
        memcpy(day, value, (ptr - value) * sizeof(WCHAR));
        day[ptr - value + 1] = 0;
        st.wDayOfWeek = HTTP_ParseWeekday(day);
        if (st.wDayOfWeek > 6)
        {
            ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
            return FALSE;
        }
    }
    else
    {
        ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
        return FALSE;
    }
    ptr++;

    while (isspaceW(*ptr))
        ptr++;

    num = strtoulW(ptr, &nextPtr, 10);
    if (!nextPtr || nextPtr <= ptr || !num || num > 31)
    {
        ERR("unexpected day %s\n", debugstr_w(value));
        return FALSE;
    }
    ptr = nextPtr;
    st.wDay = (WORD)num;

    if (*ptr != '-')
    {
        ERR("unexpected month format %s\n", debugstr_w(ptr));
        return FALSE;
    }
    ptr++;

    for (monthPtr = month; *ptr != '-' &&
         monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
         monthPtr++, ptr++)
        *monthPtr = *ptr;
    *monthPtr = 0;
    st.wMonth = HTTP_ParseMonth(month);
    if (!st.wMonth || st.wMonth > 12)
    {
        ERR("unexpected month %s\n", debugstr_w(month));
        return FALSE;
    }

    if (*ptr != '-')
    {
        ERR("unexpected year format %s\n", debugstr_w(ptr));
        return FALSE;
    }
    ptr++;

    num = strtoulW(ptr, &nextPtr, 10);
    if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
    {
        ERR("unexpected year %s\n", debugstr_w(value));
        return FALSE;
    }
    ptr = nextPtr;
    st.wYear = (WORD)num;

    if (!HTTP_ParseTime(&st, &ptr))
        return FALSE;

    while (isspaceW(*ptr))
        ptr++;

    if (strcmpW(ptr, gmt))
    {
        ERR("unexpected time zone %s\n", debugstr_w(ptr));
        return FALSE;
    }
    return SystemTimeToFileTime(&st, ft);
}

4471 4472
static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
{
4473
    static const WCHAR zero[] = { '0',0 };
4474 4475
    BOOL ret;

4476 4477 4478 4479 4480 4481
    if (!strcmpW(value, zero))
    {
        ft->dwLowDateTime = ft->dwHighDateTime = 0;
        ret = TRUE;
    }
    else if (strchrW(value, ','))
4482
    {
4483
        ret = HTTP_ParseRfc1123Date(value, ft);
4484 4485 4486 4487 4488 4489 4490
        if (!ret)
        {
            ret = HTTP_ParseRfc850Date(value, ft);
            if (!ret)
                ERR("unexpected date format %s\n", debugstr_w(value));
        }
    }
4491 4492 4493 4494 4495 4496 4497 4498 4499
    else
    {
        ret = HTTP_ParseDateAsAsctime(value, ft);
        if (!ret)
            ERR("unexpected date format %s\n", debugstr_w(value));
    }
    return ret;
}

4500 4501
static void HTTP_ProcessExpires(http_request_t *request)
{
4502
    BOOL expirationFound = FALSE;
4503 4504
    int headerIndex;

4505 4506 4507 4508
    /* Look for a Cache-Control header with a max-age directive, as it takes
     * precedence over the Expires header.
     */
    headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4509 4510
    if (headerIndex != -1)
    {
4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
        LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
        LPWSTR ptr;

        for (ptr = ccHeader->lpszValue; ptr && *ptr; )
        {
            LPWSTR comma = strchrW(ptr, ','), end, equal;

            if (comma)
                end = comma;
            else
                end = ptr + strlenW(ptr);
            for (equal = end - 1; equal > ptr && *equal != '='; equal--)
                ;
            if (*equal == '=')
            {
                static const WCHAR max_age[] = {
                    'm','a','x','-','a','g','e',0 };
4528

4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563
                if (!strncmpiW(ptr, max_age, equal - ptr - 1))
                {
                    LPWSTR nextPtr;
                    unsigned long age;

                    age = strtoulW(equal + 1, &nextPtr, 10);
                    if (nextPtr > equal + 1)
                    {
                        LARGE_INTEGER ft;

                        NtQuerySystemTime( &ft );
                        /* Age is in seconds, FILETIME resolution is in
                         * 100 nanosecond intervals.
                         */
                        ft.QuadPart += age * (ULONGLONG)1000000;
                        request->expires.dwLowDateTime = ft.u.LowPart;
                        request->expires.dwHighDateTime = ft.u.HighPart;
                        expirationFound = TRUE;
                    }
                }
            }
            if (comma)
            {
                ptr = comma + 1;
                while (isspaceW(*ptr))
                    ptr++;
            }
            else
                ptr = NULL;
        }
    }
    if (!expirationFound)
    {
        headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
        if (headerIndex != -1)
4564
        {
4565 4566 4567 4568 4569 4570 4571 4572
            LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
            FILETIME ft;

            if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
            {
                expirationFound = TRUE;
                request->expires = ft;
            }
4573 4574 4575 4576
        }
    }
    if (!expirationFound)
    {
4577
        LARGE_INTEGER t;
4578 4579

        /* With no known age, default to 10 minutes until expiration. */
4580 4581 4582 4583
        NtQuerySystemTime( &t );
        t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
        request->expires.dwLowDateTime = t.u.LowPart;
        request->expires.dwHighDateTime = t.u.HighPart;
4584 4585 4586
    }
}

4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601
static void HTTP_ProcessLastModified(http_request_t *request)
{
    int headerIndex;

    headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
    if (headerIndex != -1)
    {
        LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
        FILETIME ft;

        if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
            request->last_modified = ft;
    }
}

4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612
static void http_process_keep_alive(http_request_t *req)
{
    int index;

    index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE);
    if(index != -1)
        req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
    else
        req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
}

4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624
static void HTTP_CacheRequest(http_request_t *request)
{
    WCHAR url[INTERNET_MAX_URL_LENGTH];
    WCHAR cacheFileName[MAX_PATH+1];
    BOOL b;

    b = HTTP_GetRequestURL(request, url);
    if(!b) {
        WARN("Could not get URL\n");
        return;
    }

4625
    b = CreateUrlCacheEntryW(url, request->contentLength, NULL, cacheFileName, 0);
4626
    if(b) {
4627
        heap_free(request->cacheFile);
4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641
        CloseHandle(request->hCacheFile);

        request->cacheFile = heap_strdupW(cacheFileName);
        request->hCacheFile = CreateFileW(request->cacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
                  NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if(request->hCacheFile == INVALID_HANDLE_VALUE) {
            WARN("Could not create file: %u\n", GetLastError());
            request->hCacheFile = NULL;
        }
    }else {
        WARN("Could not create cache entry: %08x\n", GetLastError());
    }
}

4642 4643 4644 4645 4646 4647 4648 4649 4650
static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
{
    const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
    netconn_t *netconn = NULL;
    DWORD res;

    assert(!request->netconn);
    reset_data_stream(request);

4651 4652
    res = HTTP_ResolveName(request);
    if(res != ERROR_SUCCESS)
4653 4654 4655 4656
        return res;

    EnterCriticalSection(&connection_pool_cs);

4657 4658
    while(!list_empty(&request->server->conn_pool)) {
        netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679
        list_remove(&netconn->pool_entry);

        if(NETCON_is_alive(netconn))
            break;

        TRACE("connection %p closed during idle\n", netconn);
        free_netconn(netconn);
        netconn = NULL;
    }

    LeaveCriticalSection(&connection_pool_cs);

    if(netconn) {
        TRACE("<-- reusing %p netconn\n", netconn);
        request->netconn = netconn;
        *reusing = TRUE;
        return ERROR_SUCCESS;
    }

    INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
                          INTERNET_STATUS_CONNECTING_TO_SERVER,
4680 4681
                          request->server->addr_str,
                          strlen(request->server->addr_str)+1);
4682

4683 4684 4685
    res = create_netconn(is_https, request->server, request->security_flags,
                         (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
                         request->connect_timeout, &netconn);
4686 4687 4688 4689 4690 4691 4692 4693 4694
    if(res != ERROR_SUCCESS) {
        ERR("create_netconn failed: %u\n", res);
        return res;
    }

    request->netconn = netconn;

    INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
            INTERNET_STATUS_CONNECTED_TO_SERVER,
4695
            request->server->addr_str, strlen(request->server->addr_str)+1);
4696 4697 4698 4699 4700 4701 4702 4703

    if(is_https) {
        /* Note: we differ from Microsoft's WinINet here. they seem to have
         * a bug that causes no status callbacks to be sent when starting
         * a tunnel to a proxy server using the CONNECT verb. i believe our
         * behaviour to be more correct and to not cause any incompatibilities
         * because using a secure connection through a proxy server is a rare
         * case that would be hard for anyone to depend on */
4704
        if(request->session->appInfo->proxy)
4705 4706
            res = HTTP_SecureProxyConnect(request);
        if(res == ERROR_SUCCESS)
4707
            res = NETCON_secure_connect(request->netconn);
4708 4709 4710 4711 4712 4713 4714 4715
    }

    if(res != ERROR_SUCCESS) {
        http_release_netconn(request, FALSE);
        return res;
    }

    *reusing = FALSE;
4716
    TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4717 4718 4719
    return ERROR_SUCCESS;
}

4720
/***********************************************************************
4721
 *           HTTP_HttpSendRequestW (internal)
4722 4723 4724 4725
 *
 * Sends the specified request to the HTTP server
 *
 * RETURNS
Juan Lang's avatar
Juan Lang committed
4726 4727
 *    ERROR_SUCCESS on success
 *    win32 error code on failure
4728 4729
 *
 */
4730
static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4731 4732
	DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
	DWORD dwContentLength, BOOL bEndRequest)
4733
{
4734
    INT cnt;
4735
    BOOL redirected = FALSE;
4736 4737 4738 4739 4740 4741 4742 4743
    LPWSTR requestString = NULL;
    INT responseLen;
    BOOL loop_next;
    static const WCHAR szPost[] = { 'P','O','S','T',0 };
    static const WCHAR szContentLength[] =
        { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
    WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
    DWORD res;
4744

4745
    TRACE("--> %p\n", request);
4746

4747
    assert(request->hdr.htype == WH_HHTTPREQ);
4748

4749
    /* if the verb is NULL default to GET */
4750 4751
    if (!request->verb)
        request->verb = heap_strdupW(szGET);
4752

4753
    if (dwContentLength || strcmpW(request->verb, szGET))
4754
    {
4755
        sprintfW(contentLengthStr, szContentLength, dwContentLength);
4756
        HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
4757
        request->bytesToWrite = dwContentLength;
4758
    }
4759
    if (request->session->appInfo->agent)
4760
    {
4761 4762 4763
        WCHAR *agent_header;
        static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
        int len;
4764

4765
        len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4766
        agent_header = heap_alloc(len * sizeof(WCHAR));
4767
        sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4768

4769
        HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4770
        heap_free(agent_header);
4771
    }
4772
    if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4773
    {
4774
        static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4775
        HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4776
    }
4777
    if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(request->verb, szPost))
4778
    {
4779 4780
        static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
                                              ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4781
        HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4782
    }
4783

4784 4785 4786 4787
    /* add the headers the caller supplied */
    if( lpszHeaders && dwHeaderLength )
        HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);

4788
    do
4789
    {
4790
        DWORD len;
4791
        BOOL reusing_connection;
4792
        char *ascii_req;
4793

4794
        loop_next = FALSE;
4795
        reusing_connection = request->netconn != NULL;
4796

4797
        if(redirected) {
4798 4799
            request->contentLength = ~0u;
            request->bytesToWrite = 0;
4800
        }
4801

4802
        if (TRACE_ON(wininet))
4803
        {
4804
            LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4805
            TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(request->path));
4806 4807
        }

4808 4809
        HTTP_FixURL(request);
        if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4810
        {
4811
            HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4812
        }
4813 4814
        HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
        HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4815

4816 4817
        if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
            HTTP_InsertCookies(request);
4818

4819
        if (request->session->appInfo->proxy && request->session->appInfo->proxy[0])
4820
        {
4821
            WCHAR *url = HTTP_BuildProxyRequestUrl(request);
4822
            requestString = HTTP_BuildHeaderRequestString(request, request->verb, url, request->version);
4823
            heap_free(url);
4824 4825
        }
        else
4826
            requestString = HTTP_BuildHeaderRequestString(request, request->verb, request->path, request->version);
4827

4828 4829
 
        TRACE("Request header -> %s\n", debugstr_w(requestString) );
4830

4831
        if (!reusing_connection && (res = open_http_connection(request, &reusing_connection)) != ERROR_SUCCESS)
4832
            break;
4833

4834 4835 4836 4837 4838
        /* send the request as ASCII, tack on the optional data */
        if (!lpOptional || redirected)
            dwOptionalLength = 0;
        len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
                                   NULL, 0, NULL, NULL );
4839
        ascii_req = heap_alloc(len + dwOptionalLength);
4840 4841 4842 4843 4844 4845 4846
        WideCharToMultiByte( CP_ACP, 0, requestString, -1,
                             ascii_req, len, NULL, NULL );
        if( lpOptional )
            memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
        len = (len + dwOptionalLength - 1);
        ascii_req[len] = 0;
        TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4847

4848
        INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4849
                              INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4850

4851
        NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4852
        res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4853
        heap_free( ascii_req );
4854 4855 4856 4857 4858 4859 4860 4861
        if(res != ERROR_SUCCESS) {
            TRACE("send failed: %u\n", res);
            if(!reusing_connection)
                break;
            http_release_netconn(request, FALSE);
            loop_next = TRUE;
            continue;
        }
4862

4863
        request->bytesWritten = dwOptionalLength;
4864

4865
        INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4866 4867
                              INTERNET_STATUS_REQUEST_SENT,
                              &len, sizeof(DWORD));
4868

4869 4870 4871
        if (bEndRequest)
        {
            DWORD dwBufferSize;
4872

4873
            INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4874 4875
                                INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
    
4876
            responseLen = HTTP_GetResponseHeaders(request, TRUE);
4877 4878 4879 4880
            /* FIXME: We should know that connection is closed before sending
             * headers. Otherwise wrong callbacks are executed */
            if(!responseLen && reusing_connection) {
                TRACE("Connection closed by server, reconnecting\n");
4881
                http_release_netconn(request, FALSE);
4882 4883 4884
                loop_next = TRUE;
                continue;
            }
4885

4886
            INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4887 4888
                                INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
                                sizeof(DWORD));
4889

4890
            http_process_keep_alive(request);
4891
            HTTP_ProcessCookies(request);
4892
            HTTP_ProcessExpires(request);
4893
            HTTP_ProcessLastModified(request);
4894

4895
            res = set_content_length(request);
4896 4897 4898 4899 4900
            if(res != ERROR_SUCCESS)
                goto lend;
            if(!request->contentLength)
                http_release_netconn(request, TRUE);

4901
            if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
4902
            {
4903
                WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
4904
                dwBufferSize=sizeof(szNewLocation);
4905 4906 4907 4908 4909 4910 4911 4912
                switch(request->status_code) {
                case HTTP_STATUS_REDIRECT:
                case HTTP_STATUS_MOVED:
                case HTTP_STATUS_REDIRECT_KEEP_VERB:
                case HTTP_STATUS_REDIRECT_METHOD:
                    if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
                        break;

4913
                    if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
4914
                        request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
4915
                    {
4916
                        heap_free(request->verb);
4917
                        request->verb = heap_strdupW(szGET);
4918
                    }
4919
                    http_release_netconn(request, drain_content(request, FALSE));
4920
                    if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
4921
                    {
4922
                        INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
4923
                                              new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
4924
                        res = HTTP_HandleRedirect(request, new_url);
4925
                        if (res == ERROR_SUCCESS)
4926
                        {
4927
                            heap_free(requestString);
4928 4929
                            loop_next = TRUE;
                        }
4930
                        heap_free( new_url );
4931
                    }
4932
                    redirected = TRUE;
4933 4934
                }
            }
4935
            if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
4936 4937 4938
            {
                WCHAR szAuthValue[2048];
                dwBufferSize=2048;
4939
                if (request->status_code == HTTP_STATUS_DENIED)
4940
                {
4941
                    LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4942
                    DWORD dwIndex = 0;
4943
                    while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
4944
                    {
4945
                        if (HTTP_DoAuthorization(request, szAuthValue,
4946 4947 4948
                                                 &request->authInfo,
                                                 request->session->userName,
                                                 request->session->password,
4949
                                                 Host->lpszValue))
4950
                        {
4951
                            heap_free(requestString);
4952 4953 4954 4955
                            if(!drain_content(request, TRUE)) {
                                FIXME("Could not drain content\n");
                                http_release_netconn(request, FALSE);
                            }
4956 4957 4958 4959
                            loop_next = TRUE;
                            break;
                        }
                    }
4960 4961 4962

                    if(!loop_next) {
                        TRACE("Cleaning wrong authorization data\n");
4963 4964
                        destroy_authinfo(request->authInfo);
                        request->authInfo = NULL;
4965
                    }
4966
                }
4967
                if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
4968 4969
                {
                    DWORD dwIndex = 0;
4970
                    while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
4971
                    {
4972
                        if (HTTP_DoAuthorization(request, szAuthValue,
4973 4974 4975
                                                 &request->proxyAuthInfo,
                                                 request->session->appInfo->proxyUsername,
                                                 request->session->appInfo->proxyPassword,
4976
                                                 NULL))
4977
                        {
4978 4979 4980 4981
                            if(!drain_content(request, TRUE)) {
                                FIXME("Could not drain content\n");
                                http_release_netconn(request, FALSE);
                            }
4982 4983 4984 4985
                            loop_next = TRUE;
                            break;
                        }
                    }
4986 4987 4988

                    if(!loop_next) {
                        TRACE("Cleaning wrong proxy authorization data\n");
4989 4990
                        destroy_authinfo(request->proxyAuthInfo);
                        request->proxyAuthInfo = NULL;
4991
                    }
4992 4993
                }
            }
4994 4995
        }
        else
4996
            res = ERROR_SUCCESS;
4997 4998
    }
    while (loop_next);
4999

5000 5001
    if(res == ERROR_SUCCESS)
        HTTP_CacheRequest(request);
5002

5003
lend:
5004
    heap_free(requestString);
5005

5006
    /* TODO: send notification for P3P header */
5007

5008
    if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5009
    {
5010
        if (res == ERROR_SUCCESS) {
5011
            if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5012 5013 5014 5015 5016 5017 5018
                HTTP_ReceiveRequestData(request, TRUE);
            else
                send_request_complete(request,
                        request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
        }else {
                send_request_complete(request, 0, res);
        }
5019
    }
5020 5021

    TRACE("<--\n");
5022
    return res;
5023 5024
}

5025 5026 5027 5028 5029 5030 5031 5032
/***********************************************************************
 *
 * Helper functions for the HttpSendRequest(Ex) functions
 *
 */
static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
5033
    http_request_t *request = (http_request_t*) workRequest->hdr;
5034

5035
    TRACE("%p\n", request);
5036

5037
    HTTP_HttpSendRequestW(request, req->lpszHeader,
5038 5039 5040
            req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
            req->dwContentLength, req->bEndRequest);

5041
    heap_free(req->lpszHeader);
5042 5043 5044
}


5045
static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5046 5047
{
    DWORD dwBufferSize;
5048
    INT responseLen;
5049
    DWORD res = ERROR_SUCCESS;
5050

5051 5052 5053 5054 5055 5056
    if(!request->netconn) {
        WARN("Not connected\n");
        send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
        return ERROR_INTERNET_OPERATION_CANCELLED;
    }

5057
    INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5058 5059
                  INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);

5060
    responseLen = HTTP_GetResponseHeaders(request, TRUE);
5061 5062
    if (!responseLen)
        res = ERROR_HTTP_HEADER_NOT_FOUND;
5063

5064
    INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5065 5066 5067
                  INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));

    /* process cookies here. Is this right? */
5068
    http_process_keep_alive(request);
5069
    HTTP_ProcessCookies(request);
5070
    HTTP_ProcessExpires(request);
5071
    HTTP_ProcessLastModified(request);
5072

5073
    if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5074
        if(!request->contentLength)
5075
            http_release_netconn(request, TRUE);
5076
    }
5077

5078
    if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5079
    {
5080 5081 5082 5083 5084
        switch(request->status_code) {
        case HTTP_STATUS_REDIRECT:
        case HTTP_STATUS_MOVED:
        case HTTP_STATUS_REDIRECT_METHOD:
        case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5085 5086
            WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
            dwBufferSize=sizeof(szNewLocation);
5087 5088 5089 5090 5091
            if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
                break;

            if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
                request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5092
            {
5093 5094
                heap_free(request->verb);
                request->verb = heap_strdupW(szGET);
5095
            }
5096
            http_release_netconn(request, drain_content(request, FALSE));
5097 5098 5099 5100 5101 5102 5103 5104 5105 5106
            if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
            {
                INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
                                      new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
                res = HTTP_HandleRedirect(request, new_url);
                if (res == ERROR_SUCCESS)
                    res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
                heap_free( new_url );
            }
        }
5107 5108 5109
        }
    }

5110
    if (res == ERROR_SUCCESS && request->contentLength)
5111
        HTTP_ReceiveRequestData(request, TRUE);
5112
    else
5113
        send_request_complete(request, res == ERROR_SUCCESS, res);
5114

5115
    return res;
5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134
}

/***********************************************************************
 *           HttpEndRequestA (WININET.@)
 *
 * Ends an HTTP request that was started by HttpSendRequestEx
 *
 * RETURNS
 *    TRUE	if successful
 *    FALSE	on failure
 *
 */
BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
        LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
{
    TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);

    if (lpBuffersOut)
    {
5135
        SetLastError(ERROR_INVALID_PARAMETER);
5136 5137 5138 5139 5140 5141 5142 5143 5144
        return FALSE;
    }

    return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
}

static void AsyncHttpEndRequestProc(WORKREQUEST *work)
{
    struct WORKREQ_HTTPENDREQUESTW const *req = &work->u.HttpEndRequestW;
5145
    http_request_t *request = (http_request_t*)work->hdr;
5146

5147
    TRACE("%p\n", request);
5148

5149
    HTTP_HttpEndRequestW(request, req->dwFlags, req->dwContext);
5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164
}

/***********************************************************************
 *           HttpEndRequestW (WININET.@)
 *
 * Ends an HTTP request that was started by HttpSendRequestEx
 *
 * RETURNS
 *    TRUE	if successful
 *    FALSE	on failure
 *
 */
BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
        LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
{
5165
    http_request_t *request;
5166
    DWORD res;
5167

5168
    TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5169 5170 5171

    if (lpBuffersOut)
    {
5172
        SetLastError(ERROR_INVALID_PARAMETER);
5173 5174 5175
        return FALSE;
    }

5176
    request = (http_request_t*) get_handle_object( hRequest );
5177

5178
    if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5179
    {
5180
        SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5181 5182
        if (request)
            WININET_Release( &request->hdr );
5183 5184
        return FALSE;
    }
5185
    request->hdr.dwFlags |= dwFlags;
5186

5187
    if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5188 5189
    {
        WORKREQUEST work;
5190
        struct WORKREQ_HTTPENDREQUESTW *work_endrequest;
5191 5192

        work.asyncproc = AsyncHttpEndRequestProc;
5193
        work.hdr = WININET_AddRef( &request->hdr );
5194

5195 5196 5197
        work_endrequest = &work.u.HttpEndRequestW;
        work_endrequest->dwFlags = dwFlags;
        work_endrequest->dwContext = dwContext;
5198 5199

        INTERNET_AsyncCall(&work);
5200
        res = ERROR_IO_PENDING;
5201 5202
    }
    else
5203
        res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5204

5205
    WININET_Release( &request->hdr );
5206 5207 5208 5209
    TRACE("%u <--\n", res);
    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241
}

/***********************************************************************
 *           HttpSendRequestExA (WININET.@)
 *
 * Sends the specified request to the HTTP server and allows chunked
 * transfers.
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE, call GetLastError() for more information.
 */
BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
			       LPINTERNET_BUFFERSA lpBuffersIn,
			       LPINTERNET_BUFFERSA lpBuffersOut,
			       DWORD dwFlags, DWORD_PTR dwContext)
{
    INTERNET_BUFFERSW BuffersInW;
    BOOL rc = FALSE;
    DWORD headerlen;
    LPWSTR header = NULL;

    TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
	    lpBuffersOut, dwFlags, dwContext);

    if (lpBuffersIn)
    {
        BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
        if (lpBuffersIn->lpcszHeader)
        {
            headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
                    lpBuffersIn->dwHeadersLength,0,0);
5242
            header = heap_alloc(headerlen*sizeof(WCHAR));
5243 5244
            if (!(BuffersInW.lpcszHeader = header))
            {
5245
                SetLastError(ERROR_OUTOFMEMORY);
5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262
                return FALSE;
            }
            BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
                    lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
                    header, headerlen);
        }
        else
            BuffersInW.lpcszHeader = NULL;
        BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
        BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
        BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
        BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
        BuffersInW.Next = NULL;
    }

    rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);

5263
    heap_free(header);
5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281
    return rc;
}

/***********************************************************************
 *           HttpSendRequestExW (WININET.@)
 *
 * Sends the specified request to the HTTP server and allows chunked
 * transfers
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE, call GetLastError() for more information.
 */
BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
                   LPINTERNET_BUFFERSW lpBuffersIn,
                   LPINTERNET_BUFFERSW lpBuffersOut,
                   DWORD dwFlags, DWORD_PTR dwContext)
{
5282 5283
    http_request_t *request;
    http_session_t *session;
5284
    appinfo_t *hIC;
5285
    DWORD res;
5286 5287 5288 5289

    TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
            lpBuffersOut, dwFlags, dwContext);

5290
    request = (http_request_t*) get_handle_object( hRequest );
5291

5292
    if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5293
    {
5294
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5295 5296 5297
        goto lend;
    }

5298
    session = request->session;
5299
    assert(session->hdr.htype == WH_HHTTPSESSION);
5300
    hIC = session->appInfo;
5301 5302 5303 5304 5305 5306 5307 5308
    assert(hIC->hdr.htype == WH_HINIT);

    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
        struct WORKREQ_HTTPSENDREQUESTW *req;

        workRequest.asyncproc = AsyncHttpSendRequestProc;
5309
        workRequest.hdr = WININET_AddRef( &request->hdr );
5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321
        req = &workRequest.u.HttpSendRequestW;
        if (lpBuffersIn)
        {
            DWORD size = 0;

            if (lpBuffersIn->lpcszHeader)
            {
                if (lpBuffersIn->dwHeadersLength == ~0u)
                    size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
                else
                    size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);

5322
                req->lpszHeader = heap_alloc(size);
5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346
                memcpy( req->lpszHeader, lpBuffersIn->lpcszHeader, size );
            }
            else req->lpszHeader = NULL;

            req->dwHeaderLength = size / sizeof(WCHAR);
            req->lpOptional = lpBuffersIn->lpvBuffer;
            req->dwOptionalLength = lpBuffersIn->dwBufferLength;
            req->dwContentLength = lpBuffersIn->dwBufferTotal;
        }
        else
        {
            req->lpszHeader = NULL;
            req->dwHeaderLength = 0;
            req->lpOptional = NULL;
            req->dwOptionalLength = 0;
            req->dwContentLength = 0;
        }

        req->bEndRequest = FALSE;

        INTERNET_AsyncCall(&workRequest);
        /*
         * This is from windows.
         */
5347
        res = ERROR_IO_PENDING;
5348 5349 5350 5351
    }
    else
    {
        if (lpBuffersIn)
5352
            res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5353 5354 5355
                                        lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
                                        lpBuffersIn->dwBufferTotal, FALSE);
        else
5356
            res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5357 5358 5359
    }

lend:
5360 5361
    if ( request )
        WININET_Release( &request->hdr );
5362 5363

    TRACE("<---\n");
5364
    SetLastError(res);
5365
    return res == ERROR_SUCCESS;
5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380
}

/***********************************************************************
 *           HttpSendRequestW (WININET.@)
 *
 * Sends the specified request to the HTTP server
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
	DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
{
5381 5382
    http_request_t *request;
    http_session_t *session = NULL;
5383 5384 5385 5386 5387 5388
    appinfo_t *hIC = NULL;
    DWORD res = ERROR_SUCCESS;

    TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
            debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);

5389 5390
    request = (http_request_t*) get_handle_object( hHttpRequest );
    if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5391 5392 5393 5394 5395
    {
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
    }

5396
    session = request->session;
5397
    if (NULL == session ||  session->hdr.htype != WH_HHTTPSESSION)
5398 5399 5400 5401 5402
    {
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
    }

5403
    hIC = session->appInfo;
5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415
    if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT)
    {
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
    }

    if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST workRequest;
        struct WORKREQ_HTTPSENDREQUESTW *req;

        workRequest.asyncproc = AsyncHttpSendRequestProc;
5416
        workRequest.hdr = WININET_AddRef( &request->hdr );
5417 5418 5419 5420 5421 5422 5423 5424
        req = &workRequest.u.HttpSendRequestW;
        if (lpszHeaders)
        {
            DWORD size;

            if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
            else size = dwHeaderLength * sizeof(WCHAR);

5425
            req->lpszHeader = heap_alloc(size);
5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443
            memcpy(req->lpszHeader, lpszHeaders, size);
        }
        else
            req->lpszHeader = 0;
        req->dwHeaderLength = dwHeaderLength;
        req->lpOptional = lpOptional;
        req->dwOptionalLength = dwOptionalLength;
        req->dwContentLength = dwOptionalLength;
        req->bEndRequest = TRUE;

        INTERNET_AsyncCall(&workRequest);
        /*
         * This is from windows.
         */
        res = ERROR_IO_PENDING;
    }
    else
    {
5444
	res = HTTP_HttpSendRequestW(request, lpszHeaders,
5445 5446 5447 5448
		dwHeaderLength, lpOptional, dwOptionalLength,
		dwOptionalLength, TRUE);
    }
lend:
5449 5450
    if( request )
        WININET_Release( &request->hdr );
5451

5452
    SetLastError(res);
5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474
    return res == ERROR_SUCCESS;
}

/***********************************************************************
 *           HttpSendRequestA (WININET.@)
 *
 * Sends the specified request to the HTTP server
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
	DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
{
    BOOL result;
    LPWSTR szHeaders=NULL;
    DWORD nLen=dwHeaderLength;
    if(lpszHeaders!=NULL)
    {
        nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5475
        szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5476 5477
        MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
    }
5478 5479
    result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
    heap_free(szHeaders);
5480 5481 5482
    return result;
}

5483 5484 5485 5486 5487 5488
/***********************************************************************
 *           HTTPSESSION_Destroy (internal)
 *
 * Deallocate session handle
 *
 */
5489
static void HTTPSESSION_Destroy(object_header_t *hdr)
5490
{
5491
    http_session_t *session = (http_session_t*) hdr;
5492

5493
    TRACE("%p\n", session);
5494

5495
    WININET_Release(&session->appInfo->hdr);
5496

5497 5498 5499
    heap_free(session->hostName);
    heap_free(session->password);
    heap_free(session->userName);
5500 5501
}

5502
static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5503
{
5504 5505
    http_session_t *ses = (http_session_t *)hdr;

5506 5507 5508 5509 5510 5511 5512 5513 5514 5515
    switch(option) {
    case INTERNET_OPTION_HANDLE_TYPE:
        TRACE("INTERNET_OPTION_HANDLE_TYPE\n");

        if (*size < sizeof(ULONG))
            return ERROR_INSUFFICIENT_BUFFER;

        *size = sizeof(DWORD);
        *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
        return ERROR_SUCCESS;
5516 5517 5518 5519 5520 5521 5522 5523 5524
    case INTERNET_OPTION_CONNECT_TIMEOUT:
        TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");

        if (*size < sizeof(DWORD))
            return ERROR_INSUFFICIENT_BUFFER;

        *size = sizeof(DWORD);
        *(DWORD *)buffer = ses->connect_timeout;
        return ERROR_SUCCESS;
5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544

    case INTERNET_OPTION_SEND_TIMEOUT:
        TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");

        if (*size < sizeof(DWORD))
            return ERROR_INSUFFICIENT_BUFFER;

        *size = sizeof(DWORD);
        *(DWORD *)buffer = ses->send_timeout;
        return ERROR_SUCCESS;

    case INTERNET_OPTION_RECEIVE_TIMEOUT:
        TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");

        if (*size < sizeof(DWORD))
            return ERROR_INSUFFICIENT_BUFFER;

        *size = sizeof(DWORD);
        *(DWORD *)buffer = ses->receive_timeout;
        return ERROR_SUCCESS;
5545 5546
    }

5547
    return INET_QueryOption(hdr, option, buffer, size, unicode);
5548
}
5549

5550
static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5551
{
5552
    http_session_t *ses = (http_session_t*)hdr;
5553 5554 5555 5556

    switch(option) {
    case INTERNET_OPTION_USERNAME:
    {
5557
        heap_free(ses->userName);
5558
        if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5559 5560 5561 5562
        return ERROR_SUCCESS;
    }
    case INTERNET_OPTION_PASSWORD:
    {
5563
        heap_free(ses->password);
5564
        if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5565 5566
        return ERROR_SUCCESS;
    }
5567 5568
    case INTERNET_OPTION_CONNECT_TIMEOUT:
    {
5569
        if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5570 5571 5572
        ses->connect_timeout = *(DWORD *)buffer;
        return ERROR_SUCCESS;
    }
5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584
    case INTERNET_OPTION_SEND_TIMEOUT:
    {
        if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
        ses->send_timeout = *(DWORD *)buffer;
        return ERROR_SUCCESS;
    }
    case INTERNET_OPTION_RECEIVE_TIMEOUT:
    {
        if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
        ses->receive_timeout = *(DWORD *)buffer;
        return ERROR_SUCCESS;
    }
5585 5586 5587
    default: break;
    }

5588
    return INET_SetOption(hdr, option, buffer, size);
5589 5590
}

5591
static const object_vtbl_t HTTPSESSIONVtbl = {
5592
    HTTPSESSION_Destroy,
5593
    NULL,
5594
    HTTPSESSION_QueryOption,
5595
    HTTPSESSION_SetOption,
5596
    NULL,
5597
    NULL,
5598
    NULL,
5599
    NULL,
5600
    NULL
5601 5602 5603
};


5604 5605 5606 5607 5608 5609 5610 5611 5612 5613
/***********************************************************************
 *           HTTP_Connect  (internal)
 *
 * Create http session handle
 *
 * RETURNS
 *   HINTERNET a session handle on success
 *   NULL on failure
 *
 */
5614
DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5615
        INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5616 5617
        LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
        DWORD dwInternalFlags, HINTERNET *ret)
5618
{
5619
    http_session_t *session = NULL;
5620

5621
    TRACE("-->\n");
5622

5623
    if (!lpszServerName || !lpszServerName[0])
5624
        return ERROR_INVALID_PARAMETER;
5625

5626
    assert( hIC->hdr.htype == WH_HINIT );
5627

5628 5629
    session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
    if (!session)
5630
        return ERROR_OUTOFMEMORY;
5631

5632 5633 5634
   /*
    * According to my tests. The name is not resolved until a request is sent
    */
5635

5636 5637 5638 5639
    session->hdr.htype = WH_HHTTPSESSION;
    session->hdr.dwFlags = dwFlags;
    session->hdr.dwContext = dwContext;
    session->hdr.dwInternalFlags |= dwInternalFlags;
5640

5641
    WININET_AddRef( &hIC->hdr );
5642
    session->appInfo = hIC;
5643
    list_add_head( &hIC->hdr.children, &session->hdr.entry );
5644

5645 5646
    if(hIC->proxy && hIC->accessType == INTERNET_OPEN_TYPE_PROXY) {
        if(hIC->proxyBypass)
5647 5648
            FIXME("Proxy bypass is ignored.\n");
    }
5649
    session->hostName = heap_strdupW(lpszServerName);
5650
    if (lpszUserName && lpszUserName[0])
5651
        session->userName = heap_strdupW(lpszUserName);
5652
    if (lpszPassword && lpszPassword[0])
5653 5654
        session->password = heap_strdupW(lpszPassword);
    session->hostPort = serverPort;
5655
    session->connect_timeout = hIC->connect_timeout;
5656 5657
    session->send_timeout = INFINITE;
    session->receive_timeout = INFINITE;
5658

5659
    /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5660
    if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5661
    {
5662
        INTERNET_SendCallback(&hIC->hdr, dwContext,
5663
                              INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5664
                              sizeof(HINTERNET));
5665 5666
    }

5667
/*
5668
 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5669 5670
 * windows
 */
5671

5672
    TRACE("%p --> %p\n", hIC, session);
5673

5674
    *ret = session->hdr.hInternet;
5675
    return ERROR_SUCCESS;
5676 5677
}

5678 5679 5680 5681 5682
/***********************************************************************
 *           HTTP_clear_response_headers (internal)
 *
 * clear out any old response headers
 */
5683
static void HTTP_clear_response_headers( http_request_t *request )
5684 5685 5686
{
    DWORD i;

5687
    for( i=0; i<request->nCustHeaders; i++)
5688
    {
5689
        if( !request->custHeaders[i].lpszField )
5690
            continue;
5691
        if( !request->custHeaders[i].lpszValue )
5692
            continue;
5693
        if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5694
            continue;
5695
        HTTP_DeleteCustomHeader( request, i );
5696
        i--;
5697 5698 5699
    }
}

5700 5701 5702 5703 5704 5705 5706 5707 5708 5709
/***********************************************************************
 *           HTTP_GetResponseHeaders (internal)
 *
 * Read server response
 *
 * RETURNS
 *
 *   TRUE  on success
 *   FALSE on error
 */
5710
static INT HTTP_GetResponseHeaders(http_request_t *request, BOOL clear)
5711 5712
{
    INT cbreaks = 0;
5713
    WCHAR buffer[MAX_REPLY_LEN];
5714 5715
    DWORD buflen = MAX_REPLY_LEN;
    BOOL bSuccess = FALSE;
5716
    INT  rc = 0;
5717
    char bufferA[MAX_REPLY_LEN];
5718
    LPWSTR status_code = NULL, status_text = NULL;
5719
    DWORD cchMaxRawHeaders = 1024;
5720
    LPWSTR lpszRawHeaders = NULL;
5721
    LPWSTR temp;
5722
    DWORD cchRawHeaders = 0;
5723
    BOOL codeHundred = FALSE;
5724

5725
    TRACE("-->\n");
5726

5727
    if(!request->netconn)
5728 5729
        goto lend;

5730
    NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5731
    do {
5732
        static const WCHAR szHundred[] = {'1','0','0',0};
5733 5734 5735
        /*
         * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
         */
5736
        buflen = MAX_REPLY_LEN;
5737
        if (!read_line(request, bufferA, &buflen))
5738
            goto lend;
5739 5740 5741

        /* clear old response headers (eg. from a redirect response) */
        if (clear) {
5742
            HTTP_clear_response_headers( request );
5743 5744 5745
            clear = FALSE;
        }

5746
        rc += buflen;
5747
        MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5748 5749 5750 5751 5752 5753 5754 5755
        /* check is this a status code line? */
        if (!strncmpW(buffer, g_szHttp1_0, 4))
        {
            /* split the version from the status code */
            status_code = strchrW( buffer, ' ' );
            if( !status_code )
                goto lend;
            *status_code++=0;
5756

5757 5758 5759 5760 5761
            /* split the status code from the status text */
            status_text = strchrW( status_code, ' ' );
            if( !status_text )
                goto lend;
            *status_text++=0;
5762

5763 5764
            request->status_code = atoiW(status_code);

5765 5766
            TRACE("version [%s] status code [%s] status text [%s]\n",
               debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5767

5768 5769 5770 5771
            codeHundred = (!strcmpW(status_code, szHundred));
        }
        else if (!codeHundred)
        {
5772 5773
            WARN("No status line at head of response (%s)\n", debugstr_w(buffer));

5774 5775
            heap_free(request->version);
            heap_free(request->statusText);
5776

5777
            request->status_code = HTTP_STATUS_OK;
5778 5779
            request->version = heap_strdupW(g_szHttp1_0);
            request->statusText = heap_strdupW(szOK);
5780

5781
            heap_free(request->rawHeaders);
5782
            request->rawHeaders = heap_strdupW(szDefaultHeader);
5783 5784

            bSuccess = TRUE;
5785
            goto lend;
5786 5787
        }
    } while (codeHundred);
5788

5789
    /* Add status code */
5790
    HTTP_ProcessHeader(request, szStatus, status_code,
5791 5792
            HTTP_ADDHDR_FLAG_REPLACE);

5793 5794
    heap_free(request->version);
    heap_free(request->statusText);
5795

5796 5797
    request->version = heap_strdupW(buffer);
    request->statusText = heap_strdupW(status_text);
5798 5799 5800 5801 5802

    /* Restore the spaces */
    *(status_code-1) = ' ';
    *(status_text-1) = ' ';

5803
    /* regenerate raw headers */
5804
    lpszRawHeaders = heap_alloc((cchMaxRawHeaders + 1) * sizeof(WCHAR));
5805 5806
    if (!lpszRawHeaders) goto lend;

5807 5808
    while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
        cchMaxRawHeaders *= 2;
5809
    temp = heap_realloc(lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
5810 5811
    if (temp == NULL) goto lend;
    lpszRawHeaders = temp;
5812 5813 5814 5815 5816 5817
    memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
    cchRawHeaders += (buflen-1);
    memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
    cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
    lpszRawHeaders[cchRawHeaders] = '\0';

5818 5819 5820 5821
    /* Parse each response line */
    do
    {
	buflen = MAX_REPLY_LEN;
5822
        if (read_line(request, bufferA, &buflen))
5823 5824 5825
        {
            LPWSTR * pFieldAndValue;

5826
            TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5827 5828

            if (!bufferA[0]) break;
5829
            MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5830

5831
            pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5832 5833 5834 5835
            if (pFieldAndValue)
            {
                while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
                    cchMaxRawHeaders *= 2;
5836
                temp = heap_realloc(lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
5837 5838 5839 5840 5841 5842 5843 5844
                if (temp == NULL) goto lend;
                lpszRawHeaders = temp;
                memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
                cchRawHeaders += (buflen-1);
                memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
                cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
                lpszRawHeaders[cchRawHeaders] = '\0';

5845
                HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5846 5847 5848 5849 5850
                                   HTTP_ADDREQ_FLAG_ADD );

                HTTP_FreeTokens(pFieldAndValue);
            }
        }
5851 5852 5853 5854 5855 5856 5857 5858
	else
	{
	    cbreaks++;
	    if (cbreaks >= 2)
	       break;
	}
    }while(1);

5859 5860 5861 5862 5863 5864
    /* make sure the response header is terminated with an empty line.  Some apps really
       truly care about that empty line being there for some reason.  Just add it to the
       header. */
    if (cchRawHeaders + strlenW(szCrLf) > cchMaxRawHeaders)
    {
        cchMaxRawHeaders = cchRawHeaders + strlenW(szCrLf);
5865
        temp = heap_realloc(lpszRawHeaders, (cchMaxRawHeaders + 1) * sizeof(WCHAR));
5866 5867 5868 5869 5870 5871
        if (temp == NULL) goto lend;
        lpszRawHeaders = temp;
    }

    memcpy(&lpszRawHeaders[cchRawHeaders], szCrLf, sizeof(szCrLf));

5872
    heap_free(request->rawHeaders);
5873
    request->rawHeaders = lpszRawHeaders;
5874
    TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
5875 5876 5877 5878
    bSuccess = TRUE;

lend:

5879 5880 5881 5882
    TRACE("<--\n");
    if (bSuccess)
        return rc;
    else
5883
    {
5884
        heap_free(lpszRawHeaders);
5885
        return 0;
5886
    }
5887 5888 5889 5890 5891 5892 5893 5894 5895
}

/***********************************************************************
 *           HTTP_InterpretHttpHeader (internal)
 *
 * Parse server response
 *
 * RETURNS
 *
5896 5897
 *   Pointer to array of field, value, NULL on success.
 *   NULL on error.
5898
 */
Jacek Caban's avatar
Jacek Caban committed
5899
static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
5900
{
5901 5902 5903
    LPWSTR * pTokenPair;
    LPWSTR pszColon;
    INT len;
5904

5905
    pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
5906

5907 5908 5909
    pszColon = strchrW(buffer, ':');
    /* must have two tokens */
    if (!pszColon)
5910
    {
5911
        HTTP_FreeTokens(pTokenPair);
5912 5913
        if (buffer[0])
            TRACE("No ':' in line: %s\n", debugstr_w(buffer));
5914
        return NULL;
5915 5916
    }

5917
    pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
5918 5919 5920 5921 5922 5923 5924
    if (!pTokenPair[0])
    {
        HTTP_FreeTokens(pTokenPair);
        return NULL;
    }
    memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
    pTokenPair[0][pszColon - buffer] = '\0';
5925

5926 5927 5928
    /* skip colon */
    pszColon++;
    len = strlenW(pszColon);
5929
    pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
5930
    if (!pTokenPair[1])
5931
    {
5932 5933
        HTTP_FreeTokens(pTokenPair);
        return NULL;
5934
    }
5935
    memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
5936

5937 5938 5939 5940 5941
    strip_spaces(pTokenPair[0]);
    strip_spaces(pTokenPair[1]);

    TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
    return pTokenPair;
5942 5943 5944 5945 5946 5947 5948 5949 5950
}

/***********************************************************************
 *           HTTP_ProcessHeader (internal)
 *
 * Stuff header into header tables according to <dwModifier>
 *
 */

Juan Lang's avatar
Juan Lang committed
5951
#define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
5952

5953
static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
5954
{
5955
    LPHTTPHEADERW lphttpHdr = NULL;
5956 5957
    INT index = -1;
    BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
5958
    DWORD res = ERROR_HTTP_INVALID_HEADER;
5959

5960
    TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
5961

5962 5963 5964 5965 5966 5967 5968
    /* REPLACE wins out over ADD */
    if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
        dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
    
    if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
        index = -1;
    else
5969
        index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
5970 5971

    if (index >= 0)
5972
    {
5973
        if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
5974
            return ERROR_HTTP_INVALID_HEADER;
5975
        lphttpHdr = &request->custHeaders[index];
5976 5977 5978 5979
    }
    else if (value)
    {
        HTTPHEADERW hdr;
5980

5981 5982 5983
        hdr.lpszField = (LPWSTR)field;
        hdr.lpszValue = (LPWSTR)value;
        hdr.wFlags = hdr.wCount = 0;
5984

5985 5986
        if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
            hdr.wFlags |= HDR_ISREQUEST;
5987

5988
        return HTTP_InsertCustomHeader(request, &hdr);
5989
    }
5990
    /* no value to delete */
5991
    else return ERROR_SUCCESS;
5992

5993
    if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
5994
	    lphttpHdr->wFlags |= HDR_ISREQUEST;
5995 5996
    else
        lphttpHdr->wFlags &= ~HDR_ISREQUEST;
5997

5998
    if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
5999
    {
6000
        HTTP_DeleteCustomHeader( request, index );
6001

6002
        if (value)
6003
        {
6004 6005 6006 6007 6008
            HTTPHEADERW hdr;

            hdr.lpszField = (LPWSTR)field;
            hdr.lpszValue = (LPWSTR)value;
            hdr.wFlags = hdr.wCount = 0;
6009 6010

            if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6011 6012
                hdr.wFlags |= HDR_ISREQUEST;

6013
            return HTTP_InsertCustomHeader(request, &hdr);
6014 6015
        }

6016
        return ERROR_SUCCESS;
6017
    }
Juan Lang's avatar
Juan Lang committed
6018
    else if (dwModifier & COALESCEFLAGS)
6019 6020 6021 6022 6023 6024 6025 6026
    {
        LPWSTR lpsztmp;
        WCHAR ch = 0;
        INT len = 0;
        INT origlen = strlenW(lphttpHdr->lpszValue);
        INT valuelen = strlenW(value);

        if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6027
        {
6028 6029
            ch = ',';
            lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6030
        }
6031
        else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6032
        {
6033 6034
            ch = ';';
            lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6035 6036
        }

6037
        len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6038

6039
        lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6040 6041 6042 6043 6044
        if (lpsztmp)
        {
            lphttpHdr->lpszValue = lpsztmp;
    /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
            if (ch > 0)
6045
            {
6046 6047 6048 6049
                lphttpHdr->lpszValue[origlen] = ch;
                origlen++;
                lphttpHdr->lpszValue[origlen] = ' ';
                origlen++;
6050
            }
6051 6052 6053

            memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
            lphttpHdr->lpszValue[len] = '\0';
6054
            res = ERROR_SUCCESS;
6055 6056 6057
        }
        else
        {
6058
            WARN("heap_realloc (%d bytes) failed\n",len+1);
6059
            res = ERROR_OUTOFMEMORY;
6060 6061
        }
    }
6062 6063
    TRACE("<-- %d\n", res);
    return res;
6064 6065 6066 6067 6068 6069 6070 6071
}

/***********************************************************************
 *           HTTP_GetCustomHeaderIndex (internal)
 *
 * Return index of custom header from header array
 *
 */
6072
static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6073
                                     int requested_index, BOOL request_only)
6074
{
6075
    DWORD index;
6076

6077
    TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6078

6079
    for (index = 0; index < request->nCustHeaders; index++)
6080
    {
6081
        if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6082 6083
            continue;

6084
        if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6085 6086
            continue;

6087
        if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6088
            continue;
6089

6090
        if (requested_index == 0)
6091 6092
            break;
        requested_index --;
6093 6094
    }

6095
    if (index >= request->nCustHeaders)
6096 6097
	index = -1;

6098
    TRACE("Return: %d\n", index);
6099 6100 6101 6102 6103 6104 6105 6106 6107 6108
    return index;
}


/***********************************************************************
 *           HTTP_InsertCustomHeader (internal)
 *
 * Insert header into array
 *
 */
6109
static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6110 6111
{
    INT count;
6112
    LPHTTPHEADERW lph = NULL;
6113

6114
    TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6115
    count = request->nCustHeaders + 1;
6116
    if (count > 1)
6117
	lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6118
    else
6119
	lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6120

6121 6122
    if (!lph)
        return ERROR_OUTOFMEMORY;
6123

6124 6125 6126 6127 6128
    request->custHeaders = lph;
    request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
    request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
    request->custHeaders[count-1].wFlags = lpHdr->wFlags;
    request->custHeaders[count-1].wCount= lpHdr->wCount;
6129
    request->nCustHeaders++;
6130 6131

    return ERROR_SUCCESS;
6132 6133 6134 6135 6136 6137 6138
}


/***********************************************************************
 *           HTTP_DeleteCustomHeader (internal)
 *
 * Delete header from array
6139
 *  If this function is called, the indexs may change.
6140
 */
6141
static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6142
{
6143
    if( request->nCustHeaders <= 0 )
6144
        return FALSE;
6145
    if( index >= request->nCustHeaders )
6146
        return FALSE;
6147
    request->nCustHeaders--;
6148

6149 6150
    heap_free(request->custHeaders[index].lpszField);
    heap_free(request->custHeaders[index].lpszValue);
6151

6152
    memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6153
             (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6154
    memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6155 6156

    return TRUE;
6157
}
6158

6159 6160 6161 6162 6163 6164 6165

/***********************************************************************
 *           HTTP_VerifyValidHeader (internal)
 *
 * Verify the given header is not invalid for the given http request
 *
 */
6166
static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6167 6168
{
    /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6169
    if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6170
        return ERROR_HTTP_INVALID_HEADER;
6171

6172
    return ERROR_SUCCESS;
6173 6174
}

6175 6176 6177 6178 6179 6180 6181 6182
/***********************************************************************
 *          IsHostInProxyBypassList (@)
 *
 * Undocumented
 *
 */
BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
{
6183
   FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6184 6185
   return FALSE;
}
6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203

/***********************************************************************
 *           InternetShowSecurityInfoByURLA (@)
 */
BOOL WINAPI InternetShowSecurityInfoByURLA(LPCSTR url, HWND window)
{
   FIXME("stub: %s %p\n", url, window);
   return FALSE;
}

/***********************************************************************
 *           InternetShowSecurityInfoByURLW (@)
 */
BOOL WINAPI InternetShowSecurityInfoByURLW(LPCWSTR url, HWND window)
{
   FIXME("stub: %s %p\n", debugstr_w(url), window);
   return FALSE;
}
6204 6205 6206 6207 6208 6209

/***********************************************************************
 *           ShowX509EncodedCertificate (@)
 */
DWORD WINAPI ShowX509EncodedCertificate(HWND parent, LPBYTE cert, DWORD len)
{
6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229
    PCCERT_CONTEXT certContext = CertCreateCertificateContext(X509_ASN_ENCODING,
        cert, len);
    DWORD ret;

    if (certContext)
    {
        CRYPTUI_VIEWCERTIFICATE_STRUCTW view;

        memset(&view, 0, sizeof(view));
        view.hwndParent = parent;
        view.pCertContext = certContext;
        if (CryptUIDlgViewCertificateW(&view, NULL))
            ret = ERROR_SUCCESS;
        else
            ret = GetLastError();
        CertFreeCertificateContext(certContext);
    }
    else
        ret = GetLastError();
    return ret;
6230
}