http.c 164 KB
Newer Older
1
/*
2 3 4
 * Wininet - Http Implementation
 *
 * 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 11
 *
 * Ulrich Czekalla
12
 * David Hammerton
13
 *
14 15 16 17 18 19 20 21 22 23 24 25
 * 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
26
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 28
 */

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

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

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

55 56 57 58
#include "windef.h"
#include "winbase.h"
#include "wininet.h"
#include "winerror.h"
59
#define NO_SHLWAPI_STREAM
60 61 62
#define NO_SHLWAPI_REG
#define NO_SHLWAPI_STRFCNS
#define NO_SHLWAPI_GDI
63
#include "shlwapi.h"
64
#include "sspi.h"
65
#include "wincrypt.h"
66

67
#include "internet.h"
68
#include "wine/debug.h"
69
#include "wine/exception.h"
70
#include "wine/unicode.h"
71

72
WINE_DEFAULT_DEBUG_CHANNEL(wininet);
73

74
static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
75
static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
76 77
static const WCHAR szOK[] = {'O','K',0};
static const WCHAR szDefaultHeader[] = {'H','T','T','P','/','1','.','0',' ','2','0','0',' ','O','K',0};
78
static const WCHAR hostW[] = { 'H','o','s','t',0 };
79
static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
80 81
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 };
82
static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
Jacek Caban's avatar
Jacek Caban committed
83
static const WCHAR szGET[] = { 'G','E','T', 0 };
84
static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
85
static const WCHAR szCrLf[] = {'\r','\n', 0};
86

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
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 };
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 };

140 141 142 143
#define MAXHOSTNAME 100
#define MAX_FIELD_VALUE_LEN 256
#define MAX_FIELD_LEN 256

144 145 146
#define HTTP_REFERER    szReferer
#define HTTP_ACCEPT     szAccept
#define HTTP_USERAGENT  szUser_Agent
147 148 149 150 151 152 153 154 155

#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

156 157 158 159 160 161 162 163 164
#define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))

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

171 172

struct gzip_stream_t {
173
#ifdef HAVE_ZLIB
174 175
    z_stream zstream;
#endif
176 177 178 179 180
    BYTE buf[8192];
    DWORD buf_size;
    DWORD buf_pos;
    BOOL end_of_data;
};
181

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
typedef struct _authorizationData
{
    struct list entry;

    LPWSTR lpszwHost;
    LPWSTR lpszwRealm;
    LPSTR  lpszAuthorization;
    UINT   AuthorizationLen;
} authorizationData;

static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);

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 };

203
static DWORD HTTP_OpenConnection(http_request_t *req);
204
static BOOL HTTP_GetResponseHeaders(http_request_t *req, BOOL clear);
205
static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
Jacek Caban's avatar
Jacek Caban committed
206
static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
207
static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
208 209
static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
210
static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
211
static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
212
static LPWSTR HTTP_GetRedirectURL(http_request_t *req, LPCWSTR lpszUrl);
213
static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
214 215 216
static BOOL HTTP_VerifyValidHeader(http_request_t *req, LPCWSTR field);
static void HTTP_DrainContent(http_request_t *req);
static BOOL HTTP_FinishedReading(http_request_t *req);
217

218
static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
219 220 221 222 223 224 225 226
{
    int HeaderIndex = 0;
    HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
    if (HeaderIndex == -1)
        return NULL;
    else
        return &req->pCustHeaders[HeaderIndex];
}
227

228 229 230 231 232 233 234 235 236 237 238 239
#ifdef HAVE_ZLIB

static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
{
    return HeapAlloc(GetProcessHeap(), 0, items*size);
}

static void wininet_zfree(voidpf opaque, voidpf address)
{
    HeapFree(GetProcessHeap(), 0, address);
}

240
static void init_gzip_stream(http_request_t *req)
241 242
{
    gzip_stream_t *gzip_stream;
243
    int index, zres;
244 245 246 247 248 249 250

    gzip_stream = HeapAlloc(GetProcessHeap(), 0, sizeof(gzip_stream_t));
    gzip_stream->zstream.zalloc = wininet_zalloc;
    gzip_stream->zstream.zfree = wininet_zfree;
    gzip_stream->zstream.opaque = NULL;
    gzip_stream->zstream.next_in = NULL;
    gzip_stream->zstream.avail_in = 0;
251 252 253 254 255
    gzip_stream->zstream.next_out = NULL;
    gzip_stream->zstream.avail_out = 0;
    gzip_stream->buf_pos = 0;
    gzip_stream->buf_size = 0;
    gzip_stream->end_of_data = FALSE;
256 257 258 259 260 261 262 263 264

    zres = inflateInit2(&gzip_stream->zstream, 0x1f);
    if(zres != Z_OK) {
        ERR("inflateInit failed: %d\n", zres);
        HeapFree(GetProcessHeap(), 0, gzip_stream);
        return;
    }

    req->gzip_stream = gzip_stream;
265 266 267 268

    index = HTTP_GetCustomHeaderIndex(req, szContent_Length, 0, FALSE);
    if(index != -1)
        HTTP_DeleteCustomHeader(req, index);
269 270 271 272
}

#else

273
static void init_gzip_stream(http_request_t *req)
274 275 276 277 278 279
{
    ERR("gzip stream not supported, missing zlib.\n");
}

#endif

280
/* set the request content length based on the headers */
281
static DWORD set_content_length( http_request_t *lpwhr )
282 283 284 285 286 287
{
    static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
    WCHAR encoding[20];
    DWORD size;

    size = sizeof(lpwhr->dwContentLength);
288 289
    if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
                            &lpwhr->dwContentLength, &size, NULL) != ERROR_SUCCESS)
290 291 292
        lpwhr->dwContentLength = ~0u;

    size = sizeof(encoding);
293
    if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
294 295 296 297 298 299
        !strcmpiW(encoding, szChunked))
    {
        lpwhr->dwContentLength = ~0u;
        lpwhr->read_chunked = TRUE;
    }

300 301 302 303 304 305 306 307 308 309
    if(lpwhr->decoding) {
        int encoding_idx;

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

        encoding_idx = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Encoding, 0, FALSE);
        if(encoding_idx != -1 && !strcmpiW(lpwhr->pCustHeaders[encoding_idx].lpszValue, gzipW))
            init_gzip_stream(lpwhr);
    }

310 311 312
    return lpwhr->dwContentLength;
}

313 314 315 316 317 318 319 320 321 322 323 324
/***********************************************************************
 *           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;

325 326 327 328
    if (string)
    {
        /* empty string has no tokens */
        if (*string)
329
            tokens++;
330 331 332 333 334 335 336 337 338 339 340 341 342
        /* 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;
            }
343
        }
344
    }
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

    /* add 1 for terminating NULL */
    token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
    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;
        token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
        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;
    for (i = 0; token_array[i]; i++)
        HeapFree(GetProcessHeap(), 0, token_array[i]);
    HeapFree(GetProcessHeap(), 0, token_array);
}

378
static void HTTP_FixURL(http_request_t *lpwhr)
379 380 381 382 383 384
{
    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 */
    if (NULL == lpwhr->lpszPath)
385
        lpwhr->lpszPath = heap_strdupW(szSlash);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    else /* remove \r and \n*/
    {
        int nLen = strlenW(lpwhr->lpszPath);
        while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
        {
            nLen--;
            lpwhr->lpszPath[nLen]='\0';
        }
        /* Replace '\' with '/' */
        while (nLen>0) {
            nLen--;
            if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
        }
    }

    if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
Juan Lang's avatar
Juan Lang committed
402
                       lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
403 404 405 406 407 408 409 410 411 412 413
       && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
    {
        WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0, 
                             (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
        *fixurl = '/';
        strcpyW(fixurl + 1, lpwhr->lpszPath);
        HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
        lpwhr->lpszPath = fixurl;
    }
}

414
static LPWSTR HTTP_BuildHeaderRequestString( http_request_t *lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
415 416 417 418
{
    LPWSTR requestString;
    DWORD len, n;
    LPCWSTR *req;
419
    UINT i;
420 421 422 423 424 425 426
    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 */
427
    len = (lpwhr->nCustHeaders)*4 + 10;
428 429
    req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );

430
    /* add the verb, path and HTTP version string */
431
    n = 0;
432
    req[n++] = verb;
433
    req[n++] = szSpace;
434
    req[n++] = path;
435 436
    req[n++] = szSpace;
    req[n++] = version;
437

Austin English's avatar
Austin English committed
438
    /* Append custom request headers */
439 440 441 442
    for (i = 0; i < lpwhr->nCustHeaders; i++)
    {
        if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
        {
443
            req[n++] = szCrLf;
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
            req[n++] = lpwhr->pCustHeaders[i].lpszField;
            req[n++] = szColon;
            req[n++] = lpwhr->pCustHeaders[i].lpszValue;

            TRACE("Adding custom header %s (%s)\n",
                   debugstr_w(lpwhr->pCustHeaders[i].lpszField),
                   debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
        }
    }

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

    req[n] = NULL;
    requestString = HTTP_build_req( req, 4 );
    HeapFree( GetProcessHeap(), 0, req );

    /*
     * 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;
}

473
static void HTTP_ProcessCookies( http_request_t *lpwhr )
474
{
475
    int HeaderIndex;
476
    int numCookies = 0;
477 478
    LPHTTPHEADERW setCookieHeader;

479
    while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
480
    {
481
        setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
482

483
        if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
484
        {
485 486 487 488
            int len;
            static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','%','s',0};
            LPWSTR buf_url;
            LPHTTPHEADERW Host;
489

490
            Host = HTTP_GetHeader(lpwhr, hostW);
491 492 493 494
            len = lstrlenW(Host->lpszValue) + 9 + lstrlenW(lpwhr->lpszPath);
            buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
            sprintfW(buf_url, szFmt, Host->lpszValue, lpwhr->lpszPath);
            InternetSetCookieW(buf_url, NULL, setCookieHeader->lpszValue);
495

496
            HeapFree(GetProcessHeap(), 0, buf_url);
497
        }
498
        numCookies++;
499 500 501
    }
}

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
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 )
522 523
{
    static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
524 525 526
    static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
    BOOL is_basic;
    is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
527
        ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    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;
555 556
}

557 558 559 560 561 562 563 564 565 566 567 568 569 570
static void destroy_authinfo( struct HttpAuthInfo *authinfo )
{
    if (!authinfo) return;

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

    HeapFree(GetProcessHeap(), 0, authinfo->auth_data);
    HeapFree(GetProcessHeap(), 0, authinfo->scheme);
    HeapFree(GetProcessHeap(), 0, authinfo);
}

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
{
    authorizationData *ad;
    UINT rc = 0;

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

    EnterCriticalSection(&authcache_cs);
    LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, authorizationData, entry)
    {
        if (!strcmpiW(host,ad->lpszwHost) && !strcmpW(realm,ad->lpszwRealm))
        {
            TRACE("Authorization found in cache\n");
            *auth_data = HeapAlloc(GetProcessHeap(),0,ad->AuthorizationLen);
            memcpy(*auth_data,ad->lpszAuthorization,ad->AuthorizationLen);
            rc = ad->AuthorizationLen;
            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;
    authorizationData* ad = NULL;

    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)
    {
        authorizationData *check = LIST_ENTRY(cursor,authorizationData,entry);
        if (!strcmpiW(host,check->lpszwHost) && !strcmpW(realm,check->lpszwRealm))
        {
            ad = check;
            break;
        }
    }

    if (ad)
    {
        TRACE("Found match in cache, replacing\n");
        HeapFree(GetProcessHeap(),0,ad->lpszAuthorization);
        ad->lpszAuthorization = HeapAlloc(GetProcessHeap(),0,auth_data_len);
        memcpy(ad->lpszAuthorization, auth_data, auth_data_len);
        ad->AuthorizationLen = auth_data_len;
    }
    else
    {
        ad = HeapAlloc(GetProcessHeap(),0,sizeof(authorizationData));
        ad->lpszwHost = heap_strdupW(host);
        ad->lpszwRealm = heap_strdupW(realm);
        ad->lpszAuthorization = HeapAlloc(GetProcessHeap(),0,auth_data_len);
        memcpy(ad->lpszAuthorization, auth_data, auth_data_len);
        ad->AuthorizationLen = auth_data_len;
        list_add_head(&basicAuthorizationCache,&ad->entry);
        TRACE("authorization cached\n");
    }
    LeaveCriticalSection(&authcache_cs);
}

634
static BOOL HTTP_DoAuthorization( http_request_t *lpwhr, LPCWSTR pszAuthValue,
635
                                  struct HttpAuthInfo **ppAuthInfo,
636 637
                                  LPWSTR domain_and_username, LPWSTR password,
                                  LPWSTR host )
638 639
{
    SECURITY_STATUS sec_status;
640
    struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
641
    BOOL first = FALSE;
642
    LPWSTR szRealm = NULL;
643 644 645 646 647 648 649

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

    if (!pAuthInfo)
    {
        TimeStamp exp;

650
        first = TRUE;
651 652 653 654 655 656 657 658 659 660 661 662
        pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
        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;

663
        if (is_basic_auth_value(pszAuthValue,NULL))
664 665
        {
            static const WCHAR szBasic[] = {'B','a','s','i','c',0};
666
            pAuthInfo->scheme = heap_strdupW(szBasic);
667 668 669 670 671 672 673
            if (!pAuthInfo->scheme)
            {
                HeapFree(GetProcessHeap(), 0, pAuthInfo);
                return FALSE;
            }
        }
        else
674
        {
675
            PVOID pAuthData;
676 677
            SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;

678
            pAuthInfo->scheme = heap_strdupW(pszAuthValue);
679 680 681 682 683 684
            if (!pAuthInfo->scheme)
            {
                HeapFree(GetProcessHeap(), 0, pAuthInfo);
                return FALSE;
            }

685
            if (domain_and_username)
686
            {
687 688
                WCHAR *user = strchrW(domain_and_username, '\\');
                WCHAR *domain = domain_and_username;
689

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
                /* 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);
            }
            else
                /* use default credentials */
                pAuthData = NULL;
712 713 714

            sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
                                                   SECPKG_CRED_OUTBOUND, NULL,
715
                                                   pAuthData, NULL,
716 717
                                                   NULL, &pAuthInfo->cred,
                                                   &exp);
718 719 720 721 722 723 724 725 726 727
            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);
                }
            }
728 729 730 731 732 733 734 735 736
            if (sec_status != SEC_E_OK)
            {
                WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
                     debugstr_w(pAuthInfo->scheme), sec_status);
                HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
                HeapFree(GetProcessHeap(), 0, pAuthInfo);
                return FALSE;
            }
        }
737
        *ppAuthInfo = pAuthInfo;
738 739 740 741 742 743 744 745 746 747 748 749
    }
    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;
    }

750
    if (is_basic_auth_value(pszAuthValue,&szRealm))
751
    {
752 753
        int userlen;
        int passlen;
754 755
        char *auth_data = NULL;
        UINT auth_data_len = 0;
756

757
        TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
758

759 760 761 762 763 764 765 766 767 768 769 770 771 772
        if (!domain_and_username)
        {
            if (host && szRealm)
                auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
            if (auth_data_len == 0)
            {
                HeapFree(GetProcessHeap(),0,szRealm);
                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);
773

774 775 776 777 778 779 780
            /* length includes a nul terminator, which will be re-used for the ':' */
            auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
            if (!auth_data)
            {
                HeapFree(GetProcessHeap(),0,szRealm);
                return FALSE;
            }
781

782 783 784 785 786 787 788
            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);
        }
789 790

        pAuthInfo->auth_data = auth_data;
791
        pAuthInfo->auth_data_len = auth_data_len;
792
        pAuthInfo->finished = TRUE;
793
        HeapFree(GetProcessHeap(),0,szRealm);
794 795

        return TRUE;
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    }
    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);
            in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
            HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
        }

823
        buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
824 825

        out.BufferType = SECBUFFER_TOKEN;
826
        out.cbBuffer = pAuthInfo->max_token;
827 828 829 830 831 832
        out.pvBuffer = buffer;

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

833
        sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
834 835
                                                first ? NULL : &pAuthInfo->ctx,
                                                first ? lpwhr->lpHttpSession->lpszServerName : NULL,
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
                                                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);
            HeapFree(GetProcessHeap(), 0, out.pvBuffer);
857 858
            destroy_authinfo(pAuthInfo);
            *ppAuthInfo = NULL;
859 860 861 862 863 864 865
            return FALSE;
        }
    }

    return TRUE;
}

866
/***********************************************************************
867
 *           HTTP_HttpAddRequestHeadersW (internal)
868
 */
869
static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *lpwhr,
870
	LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
871
{
872 873 874
    LPWSTR lpszStart;
    LPWSTR lpszEnd;
    LPWSTR buffer;
875
    DWORD len, res = ERROR_HTTP_INVALID_HEADER;
876

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

879
    if( dwHeaderLength == ~0U )
880 881 882 883
        len = strlenW(lpszHeader);
    else
        len = dwHeaderLength;
    buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
884
    lstrcpynW( buffer, lpszHeader, len + 1);
885

886 887 888 889
    lpszStart = buffer;

    do
    {
890 891
        LPWSTR * pFieldAndValue;

892 893 894 895
        lpszEnd = lpszStart;

        while (*lpszEnd != '\0')
        {
896
            if (*lpszEnd == '\r' || *lpszEnd == '\n')
897 898 899 900
                 break;
            lpszEnd++;
        }

901
        if (*lpszStart == '\0')
902 903
	    break;

904
        if (*lpszEnd == '\r' || *lpszEnd == '\n')
905 906
        {
            *lpszEnd = '\0';
907
            lpszEnd++; /* Jump over newline */
908
        }
909
        TRACE("interpreting header %s\n", debugstr_w(lpszStart));
910 911 912 913
        if (*lpszStart == '\0')
        {
            /* Skip 0-length headers */
            lpszStart = lpszEnd;
914
            res = ERROR_SUCCESS;
915 916
            continue;
        }
917 918 919
        pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
        if (pFieldAndValue)
        {
920 921 922
            res = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
            if (res == ERROR_SUCCESS)
                res = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
923
                    pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
924 925
            HTTP_FreeTokens(pFieldAndValue);
        }
926

927
        lpszStart = lpszEnd;
928
    } while (res == ERROR_SUCCESS);
929 930

    HeapFree(GetProcessHeap(), 0, buffer);
931

932
    return res;
933 934 935 936 937 938 939
}

/***********************************************************************
 *           HttpAddRequestHeadersW (WININET.@)
 *
 * Adds one or more HTTP header to the request handler
 *
940 941 942 943 944 945
 * NOTE
 * On Windows if dwHeaderLength includes the trailing '\0', then
 * HttpAddRequestHeadersW() adds it too. However this results in an
 * invalid Http header which is rejected by some servers so we probably
 * don't need to match Windows on that point.
 *
946 947 948 949 950 951 952 953
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
	LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
{
954
    http_request_t *lpwhr;
955
    DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
956

957
    TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
958 959 960 961

    if (!lpszHeader) 
      return TRUE;

962
    lpwhr = (http_request_t*) WININET_GetObject( hHttpRequest );
963 964
    if (lpwhr && lpwhr->hdr.htype == WH_HHTTPREQ)
        res = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
965 966
    if( lpwhr )
        WININET_Release( &lpwhr->hdr );
967

968 969 970
    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
971 972
}

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
/***********************************************************************
 *           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;

990
    TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
991 992 993 994

    len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
    hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
    MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
995
    if( dwHeaderLength != ~0U )
996 997 998 999 1000 1001 1002 1003 1004
        dwHeaderLength = len;

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

    HeapFree( GetProcessHeap(), 0, hdr );

    return r;
}

1005
/***********************************************************************
1006
 *           HttpOpenRequestA (WININET.@)
1007 1008 1009 1010 1011 1012 1013 1014
 *
 * Open a HTTP request handle
 *
 * RETURNS
 *    HINTERNET  a HTTP request handle on success
 *    NULL 	 on failure
 *
 */
1015 1016 1017
HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
	LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
	LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1018
	DWORD dwFlags, DWORD_PTR dwContext)
1019
{
1020 1021
    LPWSTR szVerb = NULL, szObjectName = NULL;
    LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1022
    INT acceptTypesCount;
1023
    HINTERNET rc = FALSE;
1024 1025
    LPCSTR *types;

1026
    TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1027 1028
          debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
          debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1029 1030 1031 1032
          dwFlags, dwContext);

    if (lpszVerb)
    {
1033
        szVerb = heap_strdupAtoW(lpszVerb);
1034
        if ( !szVerb )
1035 1036
            goto end;
    }
1037

1038 1039
    if (lpszObjectName)
    {
1040
        szObjectName = heap_strdupAtoW(lpszObjectName);
1041
        if ( !szObjectName )
1042 1043 1044 1045 1046
            goto end;
    }

    if (lpszVersion)
    {
1047
        szVersion = heap_strdupAtoW(lpszVersion);
1048
        if ( !szVersion )
1049 1050 1051 1052 1053
            goto end;
    }

    if (lpszReferrer)
    {
1054
        szReferrer = heap_strdupAtoW(lpszReferrer);
1055
        if ( !szReferrer )
1056 1057 1058 1059 1060
            goto end;
    }

    if (lpszAcceptTypes)
    {
1061 1062 1063 1064
        acceptTypesCount = 0;
        types = lpszAcceptTypes;
        while (*types)
        {
1065
            __TRY
1066
            {
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
                /* find out how many there are */
                if (*types && **types)
                {
                    TRACE("accept type: %s\n", debugstr_a(*types));
                    acceptTypesCount++;
                }
            }
            __EXCEPT_PAGE_FAULT
            {
                WARN("invalid accept type pointer\n");
1077
            }
1078
            __ENDTRY;
1079 1080
            types++;
        }
1081
        szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1082 1083
        if (!szAcceptTypes) goto end;

1084
        acceptTypesCount = 0;
1085 1086
        types = lpszAcceptTypes;
        while (*types)
1087
        {
1088
            __TRY
1089
            {
1090
                if (*types && **types)
1091
                    szAcceptTypes[acceptTypesCount++] = heap_strdupAtoW(*types);
1092 1093 1094 1095
            }
            __EXCEPT_PAGE_FAULT
            {
                /* ignore invalid pointer */
1096
            }
1097
            __ENDTRY;
1098
            types++;
1099
        }
1100
        szAcceptTypes[acceptTypesCount] = NULL;
1101 1102
    }

1103 1104 1105
    rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
                          szVersion, szReferrer,
                          (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117

end:
    if (szAcceptTypes)
    {
        acceptTypesCount = 0;
        while (szAcceptTypes[acceptTypesCount])
        {
            HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
            acceptTypesCount++;
        }
        HeapFree(GetProcessHeap(), 0, szAcceptTypes);
    }
1118 1119 1120 1121
    HeapFree(GetProcessHeap(), 0, szReferrer);
    HeapFree(GetProcessHeap(), 0, szVersion);
    HeapFree(GetProcessHeap(), 0, szObjectName);
    HeapFree(GetProcessHeap(), 0, szVerb);
1122 1123

    return rc;
1124
}
1125

1126
/***********************************************************************
1127
 *  HTTP_EncodeBase64
1128
 */
1129
static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1130 1131
{
    UINT n = 0, x;
1132
    static const CHAR HTTP_Base64Enc[] =
1133 1134
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

1135
    while( len > 0 )
1136 1137 1138 1139 1140 1141
    {
        /* 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] */
1142
        if( len == 1 )
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
        {
            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] */
1153
        if( len == 2 )
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
        {
            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;
1164
        len -= 3;
1165 1166 1167 1168 1169
    }
    base64[n] = 0;
    return n;
}

1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
#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];

1216
        if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1217
            ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1218
            base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
            ((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;
}

1258
/***********************************************************************
1259
 *  HTTP_InsertAuthorization
1260 1261 1262
 *
 *   Insert or delete the authorization field in the request header.
 */
1263
static BOOL HTTP_InsertAuthorization( http_request_t *lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1264
{
1265
    if (pAuthInfo)
1266 1267
    {
        static const WCHAR wszSpace[] = {' ',0};
1268
        static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1269
        unsigned int len;
1270
        WCHAR *authorization = NULL;
1271

1272 1273 1274 1275 1276 1277 1278
        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;
            authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
            if (!authorization)
                return FALSE;
1279

1280 1281 1282 1283 1284
            strcpyW(authorization, pAuthInfo->scheme);
            strcatW(authorization, wszSpace);
            HTTP_EncodeBase64(pAuthInfo->auth_data,
                              pAuthInfo->auth_data_len,
                              authorization+strlenW(authorization));
1285

1286 1287 1288 1289 1290 1291 1292 1293 1294
            /* 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))
            {
                HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
                pAuthInfo->auth_data = NULL;
                pAuthInfo->auth_data_len = 0;
            }
1295
        }
1296

1297
        TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1298

1299
        HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1300

1301 1302
        HeapFree(GetProcessHeap(), 0, authorization);
    }
1303 1304 1305
    return TRUE;
}

1306
static WCHAR *HTTP_BuildProxyRequestUrl(http_request_t *req)
1307
{
1308
    WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1309 1310 1311
    DWORD size;

    size = sizeof(new_location);
1312
    if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL) == ERROR_SUCCESS)
1313 1314 1315 1316 1317 1318 1319 1320
    {
        if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
        strcpyW( url, new_location );
    }
    else
    {
        static const WCHAR slash[] = { '/',0 };
        static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1321
        static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1322
        http_session_t *session = req->lpHttpSession;
1323

1324
        size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1325 1326
        size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );

1327
        if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1328

1329 1330 1331 1332
        if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
            sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
        else
            sprintfW( url, format, session->lpszHostName, session->nHostPort );
1333 1334 1335 1336 1337 1338 1339
        if (req->lpszPath[0] != '/') strcatW( url, slash );
        strcatW( url, req->lpszPath );
    }
    TRACE("url=%s\n", debugstr_w(url));
    return url;
}

1340 1341 1342
/***********************************************************************
 *           HTTP_DealWithProxy
 */
1343
static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *lpwhs, http_request_t *lpwhr)
1344
{
1345
    WCHAR buf[MAXHOSTNAME];
1346 1347
    WCHAR protoProxy[MAXHOSTNAME + 15];
    DWORD protoProxyLen = sizeof(protoProxy) / sizeof(protoProxy[0]);
1348
    WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1349
    static WCHAR szNul[] = { 0 };
1350
    URL_COMPONENTSW UrlComponents;
1351
    static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1352 1353
    static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
    static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1354 1355 1356 1357 1358 1359

    memset( &UrlComponents, 0, sizeof UrlComponents );
    UrlComponents.dwStructSize = sizeof UrlComponents;
    UrlComponents.lpszHostName = buf;
    UrlComponents.dwHostNameLength = MAXHOSTNAME;

1360 1361
    if (!INTERNET_FindProxyForProtocol(hIC->lpszProxy, protoHttp, protoProxy, &protoProxyLen))
        return FALSE;
1362
    if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1363 1364
                                 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
        sprintfW(proxy, szFormat, protoProxy);
1365
    else
1366
	strcpyW(proxy, protoProxy);
1367
    if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1368 1369 1370 1371 1372
        return FALSE;
    if( UrlComponents.dwHostNameLength == 0 )
        return FALSE;

    if( !lpwhr->lpszPath )
1373
        lpwhr->lpszPath = szNul;
1374 1375 1376 1377

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

1378
    HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1379
    lpwhs->lpszServerName = heap_strdupW(UrlComponents.lpszHostName);
1380 1381
    lpwhs->nServerPort = UrlComponents.nPort;

1382
    TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1383 1384 1385
    return TRUE;
}

1386 1387 1388 1389
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 46
#endif

1390
static DWORD HTTP_ResolveName(http_request_t *lpwhr)
1391
{
1392
    char szaddr[INET6_ADDRSTRLEN];
1393
    http_session_t *lpwhs = lpwhr->lpHttpSession;
1394
    const void *addr;
1395 1396 1397 1398

    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                          INTERNET_STATUS_RESOLVING_NAME,
                          lpwhs->lpszServerName,
1399
                          (strlenW(lpwhs->lpszServerName)+1) * sizeof(WCHAR));
1400

1401
    lpwhs->sa_len = sizeof(lpwhs->socketAddress);
1402
    if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1403
                    (struct sockaddr *)&lpwhs->socketAddress, &lpwhs->sa_len))
1404
        return ERROR_INTERNET_NAME_NOT_RESOLVED;
1405

1406 1407 1408 1409 1410
    switch (lpwhs->socketAddress.ss_family)
    {
    case AF_INET:
        addr = &((struct sockaddr_in *)&lpwhs->socketAddress)->sin_addr;
        break;
1411 1412 1413
    case AF_INET6:
        addr = &((struct sockaddr_in6 *)&lpwhs->socketAddress)->sin6_addr;
        break;
1414 1415
    default:
        WARN("unsupported family %d\n", lpwhs->socketAddress.ss_family);
1416
        return ERROR_INTERNET_NAME_NOT_RESOLVED;
1417 1418
    }
    inet_ntop(lpwhs->socketAddress.ss_family, addr, szaddr, sizeof(szaddr));
1419 1420 1421
    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                          INTERNET_STATUS_NAME_RESOLVED,
                          szaddr, strlen(szaddr)+1);
1422 1423

    TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1424
    return ERROR_SUCCESS;
1425 1426
}

1427 1428 1429 1430 1431 1432 1433

/***********************************************************************
 *           HTTPREQ_Destroy (internal)
 *
 * Deallocate request handle
 *
 */
1434
static void HTTPREQ_Destroy(object_header_t *hdr)
1435
{
1436
    http_request_t *lpwhr = (http_request_t*) hdr;
1437 1438 1439 1440 1441 1442 1443
    DWORD i;

    TRACE("\n");

    if(lpwhr->hCacheFile)
        CloseHandle(lpwhr->hCacheFile);

1444
    HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1445

1446
    DeleteCriticalSection( &lpwhr->read_section );
1447 1448
    WININET_Release(&lpwhr->lpHttpSession->hdr);

1449 1450
    destroy_authinfo(lpwhr->pAuthInfo);
    destroy_authinfo(lpwhr->pProxyAuthInfo);
1451

1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
    HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
    HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
    HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
    HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);

    for (i = 0; i < lpwhr->nCustHeaders; i++)
    {
        HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
        HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
    }

1464 1465 1466 1467 1468 1469 1470 1471
#ifdef HAVE_ZLIB
    if(lpwhr->gzip_stream) {
        if(!lpwhr->gzip_stream->end_of_data)
            inflateEnd(&lpwhr->gzip_stream->zstream);
        HeapFree(GetProcessHeap(), 0, lpwhr->gzip_stream);
    }
#endif

1472 1473 1474 1475
    HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
    HeapFree(GetProcessHeap(), 0, lpwhr);
}

1476
static void HTTPREQ_CloseConnection(object_header_t *hdr)
1477
{
1478
    http_request_t *lpwhr = (http_request_t*) hdr;
1479 1480 1481 1482 1483 1484

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

    if (!NETCON_connected(&lpwhr->netConnection))
        return;

1485 1486 1487 1488 1489 1490 1491 1492 1493
    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                          INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);

    NETCON_close(&lpwhr->netConnection);

    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                          INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
}

1494
static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
{
    LPHTTPHEADERW host_header;

    static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};

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

    sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
    return TRUE;
}

1508 1509 1510 1511 1512 1513 1514 1515 1516
static BOOL HTTP_KeepAlive(http_request_t *lpwhr)
{
    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 */
1517 1518
    if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
        && !strcmpiW(szVersion, g_szHttp1_1))
1519 1520 1521 1522 1523
    {
        keepalive = TRUE;
    }

    dwBufferSize = sizeof(szConnectionResponse);
1524 1525
    if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
        || HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
1526 1527 1528 1529 1530 1531 1532
    {
        keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
    }

    return keepalive;
}

1533
static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1534
{
1535
    http_request_t *req = (http_request_t*)hdr;
1536

1537
    switch(option) {
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
    {
        http_session_t *lpwhs = req->lpHttpSession;
        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;
        info->DestPort = lpwhs->nHostPort;
        info->Flags = 0;
        if (HTTP_KeepAlive(req))
            info->Flags |= IDSI_FLAG_KEEP_ALIVE;
        if (lpwhs->lpAppInfo->lpszProxy && lpwhs->lpAppInfo->lpszProxy[0] != 0)
            info->Flags |= IDSI_FLAG_PROXY;
        if (req->netConnection.useSSL)
            info->Flags |= IDSI_FLAG_SECURE;

        return ERROR_SUCCESS;
    }

1566 1567
    case INTERNET_OPTION_SECURITY_FLAGS:
    {
1568
        http_session_t *lpwhs;
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
        lpwhs = req->lpHttpSession;

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

        *size = sizeof(DWORD);
        if (lpwhs->hdr.dwFlags & INTERNET_FLAG_SECURE)
            *(DWORD*)buffer = SECURITY_FLAG_SECURE;
        else
            *(DWORD*)buffer = 0;
        FIXME("Semi-STUB INTERNET_OPTION_SECURITY_FLAGS: %x\n",*(DWORD*)buffer);
        return ERROR_SUCCESS;
    }

1583 1584 1585 1586 1587 1588 1589 1590 1591
    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;
1592 1593 1594 1595 1596

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

1599
        static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1600 1601 1602 1603

        TRACE("INTERNET_OPTION_URL\n");

        host = HTTP_GetHeader(req, hostW);
1604 1605 1606 1607 1608 1609
        strcpyW(url, httpW);
        strcatW(url, host->lpszValue);
        if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
            *pch = 0;
        strcatW(url, req->lpszPath);

1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
        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;
        }
    }
1629

1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
    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)
        {
            if (!(info = HeapAlloc(GetProcessHeap(), 0, nbytes)))
                return ERROR_OUTOFMEMORY;

            GetUrlCacheEntryInfoW(url, info, &nbytes);

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

            HeapFree(GetProcessHeap(), 0, info);
            *size = sizeof(*ts);
            return ERROR_SUCCESS;
        }
        return error;
    }

1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
    case INTERNET_OPTION_DATAFILE_NAME: {
        DWORD req_size;

        TRACE("INTERNET_OPTION_DATAFILE_NAME\n");

        if(!req->lpszCacheFile) {
            *size = 0;
            return ERROR_INTERNET_ITEM_NOT_FOUND;
        }

        if(unicode) {
            req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
            if(*size < req_size)
                return ERROR_INSUFFICIENT_BUFFER;

            *size = req_size;
            memcpy(buffer, req->lpszCacheFile, *size);
            return ERROR_SUCCESS;
        }else {
            req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
            if (req_size > *size)
                return ERROR_INSUFFICIENT_BUFFER;

            *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
                    -1, buffer, *size, NULL, NULL);
            return ERROR_SUCCESS;
        }
    }
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754

    case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
        PCCERT_CONTEXT context;

        if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
            *size = sizeof(INTERNET_CERTIFICATE_INFOW);
            return ERROR_INSUFFICIENT_BUFFER;
        }

        context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
        if(context) {
            INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
            DWORD len;

            memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
            info->ftExpiry = context->pCertInfo->NotAfter;
            info->ftStart = context->pCertInfo->NotBefore;
            if(unicode) {
                len = CertNameToStrW(context->dwCertEncodingType,
                        &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
                info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
                if(info->lpszSubjectInfo)
                    CertNameToStrW(context->dwCertEncodingType,
                             &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
                             info->lpszSubjectInfo, len);
                len = CertNameToStrW(context->dwCertEncodingType,
                         &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
                info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
                if (info->lpszIssuerInfo)
                    CertNameToStrW(context->dwCertEncodingType,
                             &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
                             info->lpszIssuerInfo, len);
            }else {
                INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;

                len = CertNameToStrA(context->dwCertEncodingType,
                         &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
                infoA->lpszSubjectInfo = LocalAlloc(0, len);
                if(infoA->lpszSubjectInfo)
                    CertNameToStrA(context->dwCertEncodingType,
                             &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
                             infoA->lpszSubjectInfo, len);
                len = CertNameToStrA(context->dwCertEncodingType,
                         &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
                infoA->lpszIssuerInfo = LocalAlloc(0, len);
                if(infoA->lpszIssuerInfo)
                    CertNameToStrA(context->dwCertEncodingType,
                             &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
                             infoA->lpszIssuerInfo, len);
            }

            /*
             * Contrary to MSDN, these do not appear to be set.
             * lpszProtocolName
             * lpszSignatureAlgName
             * lpszEncryptionAlgName
             * dwKeySize
             */
            CertFreeCertificateContext(context);
            return ERROR_SUCCESS;
        }
    }
1755 1756
    }

1757
    return INET_QueryOption(hdr, option, buffer, size, unicode);
1758 1759
}

1760
static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
1761
{
1762
    http_request_t *req = (http_request_t*)hdr;
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773

    switch(option) {
    case INTERNET_OPTION_SEND_TIMEOUT:
    case INTERNET_OPTION_RECEIVE_TIMEOUT:
        TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");

        if (size != sizeof(DWORD))
            return ERROR_INVALID_PARAMETER;

        return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
                    *(DWORD*)buffer);
1774 1775 1776

    case INTERNET_OPTION_USERNAME:
        HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1777
        if (!(req->lpHttpSession->lpszUserName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1778 1779 1780 1781
        return ERROR_SUCCESS;

    case INTERNET_OPTION_PASSWORD:
        HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1782
        if (!(req->lpHttpSession->lpszPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1783
        return ERROR_SUCCESS;
1784 1785 1786 1787 1788
    case INTERNET_OPTION_HTTP_DECODING:
        if(size != sizeof(BOOL))
            return ERROR_INVALID_PARAMETER;
        req->decoding = *(BOOL*)buffer;
        return ERROR_SUCCESS;
1789 1790 1791 1792 1793
    }

    return ERROR_INTERNET_INVALID_OPTION;
}

1794
/* read some more data into the read buffer (the read section must be held) */
1795
static DWORD read_more_data( http_request_t *req, int maxlen )
1796
{
1797
    DWORD res;
1798
    int len;
1799

1800
    if (req->read_pos)
1801 1802
    {
        /* move existing data to the start of the buffer */
1803 1804
        if(req->read_size)
            memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
1805
        req->read_pos = 0;
1806 1807
    }

1808
    if (maxlen == -1) maxlen = sizeof(req->read_buf);
1809

1810 1811
    res = NETCON_recv( &req->netConnection, req->read_buf + req->read_size,
                       maxlen - req->read_size, 0, &len );
1812 1813
    if(res == ERROR_SUCCESS)
        req->read_size += len;
1814

1815
    return res;
1816 1817
}

1818
/* remove some amount of data from the read buffer (the read section must be held) */
1819
static void remove_data( http_request_t *req, int count )
1820
{
1821 1822 1823
    if (!(req->read_size -= count)) req->read_pos = 0;
    else req->read_pos += count;
}
1824

1825
static BOOL read_line( http_request_t *req, LPSTR buffer, DWORD *len )
1826 1827
{
    int count, bytes_read, pos = 0;
1828
    DWORD res;
1829

1830
    EnterCriticalSection( &req->read_section );
1831 1832
    for (;;)
    {
1833
        BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
1834

1835 1836 1837 1838 1839 1840
        if (eol)
        {
            count = eol - (req->read_buf + req->read_pos);
            bytes_read = count + 1;
        }
        else count = bytes_read = req->read_size;
1841

1842 1843 1844 1845 1846
        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;
1847

1848
        if ((res = read_more_data( req, -1 )) != ERROR_SUCCESS || !req->read_size)
1849 1850 1851
        {
            *len = 0;
            TRACE( "returning empty string\n" );
1852
            LeaveCriticalSection( &req->read_section );
1853
            INTERNET_SetLastError(res);
1854 1855
            return FALSE;
        }
1856
    }
1857
    LeaveCriticalSection( &req->read_section );
1858

1859 1860 1861 1862 1863 1864 1865 1866
    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;
1867 1868
}

1869
/* discard data contents until we reach end of line (the read section must be held) */
1870
static DWORD discard_eol( http_request_t *req )
1871
{
1872 1873
    DWORD res;

1874
    do
1875
    {
1876
        BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
1877 1878 1879 1880 1881 1882
        if (eol)
        {
            remove_data( req, (eol + 1) - (req->read_buf + req->read_pos) );
            break;
        }
        req->read_pos = req->read_size = 0;  /* discard everything */
1883
        if ((res = read_more_data( req, -1 )) != ERROR_SUCCESS) return res;
1884
    } while (req->read_size);
1885
    return ERROR_SUCCESS;
1886 1887
}

1888
/* read the size of the next chunk (the read section must be held) */
1889
static DWORD start_next_chunk( http_request_t *req )
1890
{
1891
    DWORD chunk_size = 0, res;
1892

1893
    if (!req->dwContentLength) return ERROR_SUCCESS;
1894 1895 1896
    if (req->dwContentLength == req->dwContentRead)
    {
        /* read terminator for the previous chunk */
1897
        if ((res = discard_eol( req )) != ERROR_SUCCESS) return res;
1898 1899 1900
        req->dwContentLength = ~0u;
        req->dwContentRead = 0;
    }
1901 1902
    for (;;)
    {
1903
        while (req->read_size)
1904
        {
1905 1906 1907 1908 1909
            char ch = req->read_buf[req->read_pos];
            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')
1910
            {
1911 1912 1913
                TRACE( "reading %u byte chunk\n", chunk_size );
                req->dwContentLength = chunk_size;
                req->dwContentRead = 0;
1914
                return discard_eol( req );
1915
            }
1916
            remove_data( req, 1 );
1917
        }
1918
        if ((res = read_more_data( req, -1 )) != ERROR_SUCCESS) return res;
1919
        if (!req->read_size)
1920
        {
1921
            req->dwContentLength = req->dwContentRead = 0;
1922
            return ERROR_SUCCESS;
1923
        }
1924 1925
    }
}
1926

1927
/* check if we have reached the end of the data to read (the read section must be held) */
1928
static BOOL end_of_read_data( http_request_t *req )
1929
{
1930
    if (req->gzip_stream) return req->gzip_stream->end_of_data && !req->gzip_stream->buf_size;
1931 1932 1933 1934
    if (req->read_chunked) return (req->dwContentLength == 0);
    if (req->dwContentLength == ~0u) return FALSE;
    return (req->dwContentLength == req->dwContentRead);
}
1935

1936
/* fetch some more data into the read buffer (the read section must be held) */
1937
static DWORD refill_buffer( http_request_t *req )
1938 1939
{
    int len = sizeof(req->read_buf);
1940
    DWORD res;
1941

1942 1943
    if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
    {
1944
        if ((res = start_next_chunk( req )) != ERROR_SUCCESS) return res;
1945
    }
1946

1947
    if (req->dwContentLength != ~0u) len = min( len, req->dwContentLength - req->dwContentRead );
1948
    if (len <= req->read_size) return ERROR_SUCCESS;
1949

1950
    if ((res = read_more_data( req, len )) != ERROR_SUCCESS) return res;
1951
    if (!req->read_size) req->dwContentLength = req->dwContentRead = 0;
1952
    return ERROR_SUCCESS;
1953 1954
}

1955
static DWORD read_gzip_data(http_request_t *req, BYTE *buf, int size, BOOL sync, int *read_ret)
1956 1957 1958 1959 1960 1961
{
    DWORD ret = ERROR_SUCCESS;
    int read = 0;

#ifdef HAVE_ZLIB
    z_stream *zstream = &req->gzip_stream->zstream;
1962
    DWORD buf_avail;
1963 1964 1965 1966
    int zres;

    while(read < size && !req->gzip_stream->end_of_data) {
        if(!req->read_size) {
1967
            if(!sync || refill_buffer(req) != ERROR_SUCCESS)
1968 1969 1970
                break;
        }

1971 1972
        buf_avail = req->dwContentLength == ~0 ? req->read_size : min(req->read_size, req->dwContentLength-req->dwContentRead);

1973
        zstream->next_in = req->read_buf+req->read_pos;
1974
        zstream->avail_in = buf_avail;
1975 1976 1977 1978
        zstream->next_out = buf+read;
        zstream->avail_out = size-read;
        zres = inflate(zstream, Z_FULL_FLUSH);
        read = size - zstream->avail_out;
1979 1980
        req->dwContentRead += buf_avail-zstream->avail_in;
        remove_data(req, buf_avail-zstream->avail_in);
1981 1982 1983
        if(zres == Z_STREAM_END) {
            TRACE("end of data\n");
            req->gzip_stream->end_of_data = TRUE;
1984
            inflateEnd(&req->gzip_stream->zstream);
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
        }else if(zres != Z_OK) {
            WARN("inflate failed %d\n", zres);
            if(!read)
                ret = ERROR_INTERNET_DECODING_FAILED;
            break;
        }
    }
#endif

    *read_ret = read;
    return ret;
}

1998
static void refill_gzip_buffer(http_request_t *req)
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
{
    DWORD res;
    int len;

    if(!req->gzip_stream || !req->read_size || req->gzip_stream->buf_size == sizeof(req->gzip_stream->buf))
        return;

    if(req->gzip_stream->buf_pos) {
        if(req->gzip_stream->buf_size)
            memmove(req->gzip_stream->buf, req->gzip_stream->buf + req->gzip_stream->buf_pos, req->gzip_stream->buf_size);
        req->gzip_stream->buf_pos = 0;
    }

    res = read_gzip_data(req, req->gzip_stream->buf + req->gzip_stream->buf_size,
            sizeof(req->gzip_stream->buf) - req->gzip_stream->buf_size, FALSE, &len);
    if(res == ERROR_SUCCESS)
        req->gzip_stream->buf_size += len;
}

/* return the size of data available to be read immediately (the read section must be held) */
2019
static DWORD get_avail_data( http_request_t *req )
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
{
    if (req->gzip_stream) {
        refill_gzip_buffer(req);
        return req->gzip_stream->buf_size;
    }
    if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
        return 0;
    return min( req->read_size, req->dwContentLength - req->dwContentRead );
}

2030
static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif)
2031 2032
{
    INTERNET_ASYNC_RESULT iar;
2033
    DWORD res;
2034 2035 2036

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

2037
    EnterCriticalSection( &req->read_section );
2038
    if ((res = refill_buffer( req )) == ERROR_SUCCESS) {
2039 2040 2041 2042
        iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
        iar.dwError = first_notif ? 0 : get_avail_data(req);
    }else {
        iar.dwResult = 0;
2043
        iar.dwError = res;
2044
    }
2045
    LeaveCriticalSection( &req->read_section );
2046 2047 2048

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

2051
/* read data from the http connection (the read section must be held) */
2052
static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
2053
{
2054
    BOOL finished_reading = FALSE;
2055
    int len, bytes_read = 0;
2056
    DWORD ret = ERROR_SUCCESS;
2057

2058
    EnterCriticalSection( &req->read_section );
2059

2060 2061
    if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
    {
2062
        if (start_next_chunk( req ) != ERROR_SUCCESS) goto done;
2063 2064
    }

2065 2066 2067 2068 2069 2070 2071 2072 2073
    if(req->gzip_stream) {
        if(req->gzip_stream->buf_size) {
            bytes_read = min(req->gzip_stream->buf_size, size);
            memcpy(buffer, req->gzip_stream->buf + req->gzip_stream->buf_pos, bytes_read);
            req->gzip_stream->buf_pos += bytes_read;
            req->gzip_stream->buf_size -= bytes_read;
        }else if(!req->read_size && !req->gzip_stream->end_of_data) {
            refill_buffer(req);
        }
2074

2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
        if(size > bytes_read) {
            ret = read_gzip_data(req, (BYTE*)buffer+bytes_read, size-bytes_read, sync, &len);
            if(ret == ERROR_SUCCESS)
                bytes_read += len;
        }

        finished_reading = req->gzip_stream->end_of_data && !req->gzip_stream->buf_size;
    }else {
        if (req->dwContentLength != ~0u) size = min( size, req->dwContentLength - req->dwContentRead );

        if (req->read_size) {
            bytes_read = min( req->read_size, size );
            memcpy( buffer, req->read_buf + req->read_pos, bytes_read );
            remove_data( req, bytes_read );
        }

        if (size > bytes_read && (!bytes_read || sync)) {
2092
            if (NETCON_recv( &req->netConnection, (char *)buffer + bytes_read, size - bytes_read,
2093
                             sync ? MSG_WAITALL : 0, &len) == ERROR_SUCCESS)
2094 2095 2096
                bytes_read += len;
            /* always return success, even if the network layer returns an error */
        }
2097 2098

        finished_reading = !bytes_read && req->dwContentRead == req->dwContentLength;
2099
        req->dwContentRead += bytes_read;
2100 2101 2102 2103 2104
    }
done:
    *read = bytes_read;

    TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, req->dwContentRead, req->dwContentLength );
2105 2106
    LeaveCriticalSection( &req->read_section );

2107
    if(ret == ERROR_SUCCESS && req->lpszCacheFile) {
2108 2109 2110 2111 2112 2113 2114 2115
        BOOL res;
        DWORD dwBytesWritten;

        res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
        if(!res)
            WARN("WriteFile failed: %u\n", GetLastError());
    }

2116
    if(finished_reading)
2117 2118
        HTTP_FinishedReading(req);

2119
    return ret;
2120 2121
}

2122

2123
static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
2124
{
2125
    http_request_t *req = (http_request_t*)hdr;
2126
    return HTTPREQ_Read(req, buffer, size, read, TRUE);
2127 2128
}

2129
static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
2130 2131
{
    struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
2132
    http_request_t *req = (http_request_t*)workRequest->hdr;
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
    INTERNET_ASYNC_RESULT iar;
    DWORD res;

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

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

    iar.dwResult = res == ERROR_SUCCESS;
    iar.dwError = res;

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

2149
static DWORD HTTPREQ_ReadFileExA(object_header_t *hdr, INTERNET_BUFFERSA *buffers,
2150 2151
        DWORD flags, DWORD_PTR context)
{
2152
    http_request_t *req = (http_request_t*)hdr;
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
    DWORD res;

    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);

2163 2164 2165
    if ((hdr->dwFlags & INTERNET_FLAG_ASYNC) && !get_avail_data(req))
    {
        WORKREQUEST workRequest;
2166

2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
        if (TryEnterCriticalSection( &req->read_section ))
        {
            if (get_avail_data(req))
            {
                res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength,
                                   &buffers->dwBufferLength, FALSE);
                LeaveCriticalSection( &req->read_section );
                goto done;
            }
            LeaveCriticalSection( &req->read_section );
        }

2179 2180 2181
        workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
        workRequest.hdr = WININET_AddRef(&req->hdr);
        workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
2182

2183
        INTERNET_AsyncCall(&workRequest);
2184

2185
        return ERROR_IO_PENDING;
2186 2187 2188 2189 2190
    }

    res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
            !(flags & IRF_NO_WAIT));

2191
done:
2192 2193 2194 2195 2196 2197 2198 2199 2200
    if (res == ERROR_SUCCESS) {
        DWORD size = buffers->dwBufferLength;
        INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
                &size, sizeof(size));
    }

    return res;
}

2201 2202 2203
static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
2204
    http_request_t *req = (http_request_t*)workRequest->hdr;
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
    INTERNET_ASYNC_RESULT iar;
    DWORD res;

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

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

    iar.dwResult = res == ERROR_SUCCESS;
    iar.dwError = res;

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

2221
static DWORD HTTPREQ_ReadFileExW(object_header_t *hdr, INTERNET_BUFFERSW *buffers,
2222 2223 2224
        DWORD flags, DWORD_PTR context)
{

2225
    http_request_t *req = (http_request_t*)hdr;
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
    DWORD res;

    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);

2236
    if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
2237 2238
    {
        WORKREQUEST workRequest;
2239

2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
        if (TryEnterCriticalSection( &req->read_section ))
        {
            if (get_avail_data(req))
            {
                res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength,
                                   &buffers->dwBufferLength, FALSE);
                LeaveCriticalSection( &req->read_section );
                goto done;
            }
            LeaveCriticalSection( &req->read_section );
        }

2252 2253 2254
        workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
        workRequest.hdr = WININET_AddRef(&req->hdr);
        workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
2255

2256
        INTERNET_AsyncCall(&workRequest);
2257

2258
        return ERROR_IO_PENDING;
2259 2260 2261 2262 2263
    }

    res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
            !(flags & IRF_NO_WAIT));

2264
done:
2265 2266 2267 2268 2269 2270 2271 2272 2273
    if (res == ERROR_SUCCESS) {
        DWORD size = buffers->dwBufferLength;
        INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
                &size, sizeof(size));
    }

    return res;
}

2274
static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
2275
{
2276
    DWORD res;
2277
    http_request_t *lpwhr = (http_request_t*)hdr;
2278

2279 2280
    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);

2281
    *written = 0;
2282 2283
    res = NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
    if (res == ERROR_SUCCESS)
2284 2285
        lpwhr->dwBytesWritten += *written;

2286
    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
2287
    return res;
2288 2289
}

2290 2291
static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
{
2292
    http_request_t *req = (http_request_t*)workRequest->hdr;
2293

2294
    HTTP_ReceiveRequestData(req, FALSE);
2295 2296
}

2297
static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
2298
{
2299
    http_request_t *req = (http_request_t*)hdr;
2300 2301 2302

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

2303
    if (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2304
    {
2305
        WORKREQUEST workRequest;
2306

2307 2308
        /* never wait, if we can't enter the section we queue an async request right away */
        if (TryEnterCriticalSection( &req->read_section ))
2309
        {
2310 2311 2312 2313
            if ((*available = get_avail_data( req ))) goto done;
            if (end_of_read_data( req )) goto done;
            LeaveCriticalSection( &req->read_section );
        }
2314

2315 2316
        workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
        workRequest.hdr = WININET_AddRef( &req->hdr );
2317

2318
        INTERNET_AsyncCall(&workRequest);
2319

2320
        return ERROR_IO_PENDING;
2321
    }
2322

2323 2324 2325 2326 2327 2328 2329 2330 2331
    EnterCriticalSection( &req->read_section );

    if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
    {
        refill_buffer( req );
        *available = get_avail_data( req );
    }

done:
2332
    if (*available == sizeof(req->read_buf) && !req->gzip_stream)  /* check if we have even more pending in the socket */
2333 2334 2335 2336
    {
        DWORD extra;
        if (NETCON_query_data_available(&req->netConnection, &extra))
            *available = min( *available + extra, req->dwContentLength - req->dwContentRead );
2337
    }
2338
    LeaveCriticalSection( &req->read_section );
2339

2340
    TRACE( "returning %u\n", *available );
2341 2342 2343
    return ERROR_SUCCESS;
}

2344
static const object_vtbl_t HTTPREQVtbl = {
2345
    HTTPREQ_Destroy,
2346
    HTTPREQ_CloseConnection,
2347
    HTTPREQ_QueryOption,
2348
    HTTPREQ_SetOption,
2349
    HTTPREQ_ReadFile,
2350
    HTTPREQ_ReadFileExA,
2351
    HTTPREQ_ReadFileExW,
2352
    HTTPREQ_WriteFile,
2353
    HTTPREQ_QueryDataAvailable,
2354
    NULL
2355 2356
};

2357
/***********************************************************************
2358
 *           HTTP_HttpOpenRequestW (internal)
2359 2360 2361 2362 2363 2364 2365 2366
 *
 * Open a HTTP request handle
 *
 * RETURNS
 *    HINTERNET  a HTTP request handle on success
 *    NULL 	 on failure
 *
 */
2367 2368 2369 2370
static DWORD HTTP_HttpOpenRequestW(http_session_t *lpwhs,
        LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
        LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
        DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
2371
{
2372
    appinfo_t *hIC = NULL;
2373
    http_request_t *lpwhr;
2374
    LPWSTR lpszHostName = NULL;
2375
    HINTERNET handle = NULL;
2376
    static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
2377
    DWORD len, res;
2378

2379
    TRACE("-->\n");
2380

2381
    assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
2382
    hIC = lpwhs->lpAppInfo;
2383

2384
    lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(http_request_t));
2385 2386
    if (NULL == lpwhr)
    {
2387
        res = ERROR_OUTOFMEMORY;
2388
        goto lend;
2389
    }
2390
    lpwhr->hdr.htype = WH_HHTTPREQ;
2391
    lpwhr->hdr.vtbl = &HTTPREQVtbl;
2392 2393
    lpwhr->hdr.dwFlags = dwFlags;
    lpwhr->hdr.dwContext = dwContext;
2394
    lpwhr->hdr.refs = 1;
2395
    lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
2396
    lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
2397
    lpwhr->dwContentLength = ~0u;
2398
    InitializeCriticalSection( &lpwhr->read_section );
2399

2400 2401
    WININET_AddRef( &lpwhs->hdr );
    lpwhr->lpHttpSession = lpwhs;
2402
    list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
2403

2404 2405 2406 2407
    lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
            (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
    if (NULL == lpszHostName)
    {
2408
        res = ERROR_OUTOFMEMORY;
2409 2410 2411
        goto lend;
    }

2412 2413 2414
    handle = WININET_AllocHandle( &lpwhr->hdr );
    if (NULL == handle)
    {
2415
        res = ERROR_OUTOFMEMORY;
2416
        goto lend;
2417 2418
    }

2419
    if ((res = NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE)) != ERROR_SUCCESS)
2420 2421 2422 2423 2424
    {
        InternetCloseHandle( handle );
        handle = NULL;
        goto lend;
    }
2425

Jacek Caban's avatar
Jacek Caban committed
2426
    if (lpszObjectName && *lpszObjectName) {
2427
        HRESULT rc;
2428 2429 2430

        len = 0;
        rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
2431
        if (rc != E_POINTER)
2432 2433 2434
            len = strlenW(lpszObjectName)+1;
        lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
        rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
2435
                   URL_ESCAPE_SPACES_ONLY);
2436
        if (rc != S_OK)
2437
        {
2438
            ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2439
            strcpyW(lpwhr->lpszPath,lpszObjectName);
2440
        }
2441 2442 2443
    }else {
        static const WCHAR slashW[] = {'/',0};

2444
        lpwhr->lpszPath = heap_strdupW(slashW);
2445
    }
2446

Jacek Caban's avatar
Jacek Caban committed
2447
    if (lpszReferrer && *lpszReferrer)
2448
        HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2449

2450
    if (lpszAcceptTypes)
2451 2452
    {
        int i;
2453 2454 2455
        for (i = 0; lpszAcceptTypes[i]; i++)
        {
            if (!*lpszAcceptTypes[i]) continue;
2456
            HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2457 2458 2459 2460
                               HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
                               HTTP_ADDHDR_FLAG_REQ |
                               (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
        }
2461
    }
2462

2463 2464
    lpwhr->lpszVerb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
    lpwhr->lpszVersion = heap_strdupW(lpszVersion ? lpszVersion : g_szHttp1_1);
2465

2466 2467 2468 2469 2470
    if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
        lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
        lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
    {
        sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2471
        HTTP_ProcessHeader(lpwhr, hostW, lpszHostName,
2472 2473 2474
                HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
    }
    else
2475
        HTTP_ProcessHeader(lpwhr, hostW, lpwhs->lpszHostName,
2476
                HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2477

2478 2479 2480 2481
    if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
        lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
                        INTERNET_DEFAULT_HTTPS_PORT :
                        INTERNET_DEFAULT_HTTP_PORT);
2482 2483 2484 2485 2486

    if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
        lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
                        INTERNET_DEFAULT_HTTPS_PORT :
                        INTERNET_DEFAULT_HTTP_PORT);
2487

2488 2489
    if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
        HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2490

2491 2492 2493
    INTERNET_SendCallback(&lpwhs->hdr, dwContext,
                          INTERNET_STATUS_HANDLE_CREATED, &handle,
                          sizeof(handle));
2494

2495
lend:
2496
    HeapFree(GetProcessHeap(), 0, lpszHostName);
2497 2498 2499 2500
    if( lpwhr )
        WININET_Release( &lpwhr->hdr );

    TRACE("<-- %p (%p)\n", handle, lpwhr);
2501 2502
    *ret = handle;
    return res;
2503 2504
}

2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
/***********************************************************************
 *           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)
{
    http_session_t *lpwhs;
    HINTERNET handle = NULL;
2522
    DWORD res;
2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537

    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]));
    }

    lpwhs = (http_session_t*) WININET_GetObject( hHttpSession );
    if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
    {
2538 2539
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
2540 2541 2542 2543 2544 2545 2546 2547 2548
    }

    /*
     * 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.
     *
     */
2549 2550 2551
    res = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
                                lpszVersion, lpszReferrer, lpszAcceptTypes,
                                dwFlags, dwContext, &handle);
2552 2553 2554 2555
lend:
    if( lpwhs )
        WININET_Release( &lpwhs->hdr );
    TRACE("returning %p\n", handle);
2556 2557
    if(res != ERROR_SUCCESS)
        SetLastError(res);
2558 2559 2560
    return handle;
}

2561 2562
/* read any content returned by the server so that the connection can be
 * reused */
2563
static void HTTP_DrainContent(http_request_t *req)
2564 2565 2566 2567 2568 2569
{
    DWORD bytes_read;

    if (!NETCON_connected(&req->netConnection)) return;

    if (req->dwContentLength == -1)
2570
    {
2571
        NETCON_close(&req->netConnection);
2572 2573
        return;
    }
2574
    if (!strcmpW(req->lpszVerb, szHEAD)) return;
2575 2576 2577 2578

    do
    {
        char buffer[2048];
2579
        if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2580 2581 2582 2583
            return;
    } while (bytes_read);
}

2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
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 */
    NULL,			/* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
    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 */
2640
    hostW,			/* HTTP_QUERY_HOST = 55 */
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
    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 */
2656 2657
};

2658 2659
#define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))

2660
/***********************************************************************
2661
 *           HTTP_HttpQueryInfoW (internal)
2662
 */
2663 2664
static DWORD HTTP_HttpQueryInfoW(http_request_t *lpwhr, DWORD dwInfoLevel,
        LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2665
{
2666
    LPHTTPHEADERW lphttpHdr = NULL;
2667
    BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2668
    INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2669
    DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2670
    INT index = -1;
2671

2672
    /* Find requested header structure */
2673
    switch (level)
2674
    {
2675
    case HTTP_QUERY_CUSTOM:
2676
        if (!lpBuffer) return ERROR_INVALID_PARAMETER;
2677 2678 2679
        index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
        break;
    case HTTP_QUERY_RAW_HEADERS_CRLF:
2680
        {
2681
            LPWSTR headers;
2682
            DWORD len = 0;
2683
            DWORD res = ERROR_INVALID_PARAMETER;
2684 2685

            if (request_only)
2686
                headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2687 2688 2689
            else
                headers = lpwhr->lpszRawHeaders;

2690 2691 2692
            if (headers)
                len = strlenW(headers) * sizeof(WCHAR);

2693
            if (len + sizeof(WCHAR) > *lpdwBufferLength)
2694
            {
2695
                len += sizeof(WCHAR);
2696
                res = ERROR_INSUFFICIENT_BUFFER;
2697 2698
            }
            else if (lpBuffer)
2699
            {
2700 2701 2702 2703
                if (headers)
                    memcpy(lpBuffer, headers, len + sizeof(WCHAR));
                else
                {
2704 2705
                    len = strlenW(szCrLf) * sizeof(WCHAR);
                    memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2706
                }
2707
                TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2708
                res = ERROR_SUCCESS;
2709
            }
2710
            *lpdwBufferLength = len;
2711

2712 2713
            if (request_only)
                HeapFree(GetProcessHeap(), 0, headers);
2714
            return res;
2715
        }
2716
    case HTTP_QUERY_RAW_HEADERS:
2717 2718
        {
            LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2719
            DWORD i, size = 0;
2720
            LPWSTR pszString = lpBuffer;
2721 2722 2723 2724 2725 2726 2727 2728

            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);
2729
                return ERROR_INSUFFICIENT_BUFFER;
2730
            }
2731
            if (pszString)
2732
            {
2733 2734 2735 2736 2737 2738 2739 2740
                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));
2741
            }
2742
            *lpdwBufferLength = size * sizeof(WCHAR);
2743 2744
            HTTP_FreeTokens(ppszRawHeaderLines);

2745
            return ERROR_SUCCESS;
2746
        }
2747
    case HTTP_QUERY_STATUS_TEXT:
2748
        if (lpwhr->lpszStatusText)
2749 2750 2751 2752 2753
        {
            DWORD len = strlenW(lpwhr->lpszStatusText);
            if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
            {
                *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2754
                return ERROR_INSUFFICIENT_BUFFER;
2755
            }
2756 2757 2758 2759 2760
            if (lpBuffer)
            {
                memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
                TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
            }
2761
            *lpdwBufferLength = len * sizeof(WCHAR);
2762
            return ERROR_SUCCESS;
2763
        }
2764
        break;
2765
    case HTTP_QUERY_VERSION:
2766
        if (lpwhr->lpszVersion)
2767 2768 2769 2770 2771
        {
            DWORD len = strlenW(lpwhr->lpszVersion);
            if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
            {
                *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2772
                return ERROR_INSUFFICIENT_BUFFER;
2773
            }
2774 2775 2776 2777 2778
            if (lpBuffer)
            {
                memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
                TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
            }
2779
            *lpdwBufferLength = len * sizeof(WCHAR);
2780
            return ERROR_SUCCESS;
2781
        }
2782
        break;
2783 2784 2785 2786
    case HTTP_QUERY_CONTENT_ENCODING:
        index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[lpwhr->gzip_stream ? HTTP_QUERY_CONTENT_TYPE : level],
                requested_index,request_only);
        break;
2787
    default:
2788 2789
        assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));

2790
        if (level < LAST_TABLE_HEADER && header_lookup[level])
2791 2792
            index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
                                              requested_index,request_only);
2793 2794
    }

2795 2796 2797
    if (index >= 0)
        lphttpHdr = &lpwhr->pCustHeaders[index];

Austin English's avatar
Austin English committed
2798
    /* Ensure header satisfies requested attributes */
2799 2800 2801
    if (!lphttpHdr ||
        ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
         (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2802
    {
2803
        return ERROR_HTTP_HEADER_NOT_FOUND;
2804
    }
2805

2806
    if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2807

Austin English's avatar
Austin English committed
2808
    /* coalesce value to requested type */
2809
    if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2810
    {
2811 2812
        *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
        TRACE(" returning number: %d\n", *(int *)lpBuffer);
2813
     }
2814
    else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2815 2816 2817 2818
    {
        time_t tmpTime;
        struct tm tmpTM;
        SYSTEMTIME *STHook;
2819

2820 2821 2822
        tmpTime = ConvertTimeString(lphttpHdr->lpszValue);

        tmpTM = *gmtime(&tmpTime);
2823 2824 2825 2826 2827 2828 2829 2830 2831
        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;
2832

2833 2834 2835
        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);
2836
    }
2837
    else if (lphttpHdr->lpszValue)
2838
    {
2839
        DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2840

2841
        if (len > *lpdwBufferLength)
2842
        {
2843
            *lpdwBufferLength = len;
2844
            return ERROR_INSUFFICIENT_BUFFER;
2845
        }
2846 2847 2848
        if (lpBuffer)
        {
            memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2849
            TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
2850
        }
2851
        *lpdwBufferLength = len - sizeof(WCHAR);
2852
    }
2853
    return ERROR_SUCCESS;
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
}

/***********************************************************************
 *           HttpQueryInfoW (WININET.@)
 *
 * Queries for information about an HTTP request
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2867
        LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2868
{
2869
    http_request_t *lpwhr;
2870
    DWORD res;
2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917

    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),
2918 2919
        FE(HTTP_QUERY_SET_COOKIE),
        FE(HTTP_QUERY_COOKIE),
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
	    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;
2954
	DWORD i;
2955

2956
	TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
2957 2958 2959
	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
2960
		TRACE(" %s", query_flags[i].name);
2961 2962 2963 2964
		break;
	    }
	}
	if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2965
	    TRACE(" Unknown (%08x)", info);
2966 2967
	}

Diego Pettenò's avatar
Diego Pettenò committed
2968
	TRACE(" Modifier:");
2969 2970
	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
2971
		TRACE(" %s", modifier_flags[i].name);
2972 2973 2974 2975 2976
		info_mod &= ~ modifier_flags[i].val;
	    }
	}
	
	if (info_mod) {
2977
	    TRACE(" Unknown (%08x)", info_mod);
2978
	}
Diego Pettenò's avatar
Diego Pettenò committed
2979
	TRACE("\n");
2980 2981
    }
    
2982
    lpwhr = (http_request_t*) WININET_GetObject( hHttpRequest );
2983 2984
    if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
    {
2985 2986
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
2987 2988
    }

2989 2990
    if (lpBuffer == NULL)
        *lpdwBufferLength = 0;
2991 2992
    res = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
                               lpBuffer, lpdwBufferLength, lpdwIndex);
2993

2994 2995 2996 2997
lend:
    if( lpwhr )
         WININET_Release( &lpwhr->hdr );

2998 2999 3000 3001
    TRACE("%u <--\n", res);
    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
3002 3003
}

3004
/***********************************************************************
3005
 *           HttpQueryInfoA (WININET.@)
3006 3007 3008 3009 3010 3011 3012 3013
 *
 * Queries for information about an HTTP request
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
3014
BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3015 3016 3017
	LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
{
    BOOL result;
3018 3019 3020
    DWORD len;
    WCHAR* bufferW;

3021 3022 3023
    if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
       (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
    {
3024 3025
        return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
                               lpdwBufferLength, lpdwIndex );
3026
    }
3027

3028 3029
    if (lpBuffer)
    {
3030
        DWORD alloclen;
3031
        len = (*lpdwBufferLength)*sizeof(WCHAR);
3032 3033 3034 3035 3036 3037 3038 3039 3040
        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;
        bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
3041 3042
        /* buffer is in/out because of HTTP_QUERY_CUSTOM */
        if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3043
            MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3044 3045 3046 3047 3048 3049
    } else
    {
        bufferW = NULL;
        len = 0;
    }

3050 3051 3052
    result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
                           &len, lpdwIndex );
    if( result )
3053
    {
3054
        len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3055
                                     lpBuffer, *lpdwBufferLength, NULL, NULL );
3056 3057 3058
        *lpdwBufferLength = len - 1;

        TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3059
    }
3060 3061 3062 3063 3064
    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);
3065

3066 3067
    HeapFree(GetProcessHeap(), 0, bufferW );

3068 3069
    return result;
}
3070 3071

/***********************************************************************
3072
 *           HTTP_GetRedirectURL (internal)
3073
 */
3074
static LPWSTR HTTP_GetRedirectURL(http_request_t *lpwhr, LPCWSTR lpszUrl)
3075
{
3076 3077 3078 3079 3080 3081 3082
    static WCHAR szHttp[] = {'h','t','t','p',0};
    static WCHAR szHttps[] = {'h','t','t','p','s',0};
    http_session_t *lpwhs = lpwhr->lpHttpSession;
    URL_COMPONENTSW urlComponents;
    DWORD url_length = 0;
    LPWSTR orig_url;
    LPWSTR combined_url;
3083

3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
    urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
    urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
    urlComponents.dwSchemeLength = 0;
    urlComponents.lpszHostName = lpwhs->lpszHostName;
    urlComponents.dwHostNameLength = 0;
    urlComponents.nPort = lpwhs->nHostPort;
    urlComponents.lpszUserName = lpwhs->lpszUserName;
    urlComponents.dwUserNameLength = 0;
    urlComponents.lpszPassword = NULL;
    urlComponents.dwPasswordLength = 0;
    urlComponents.lpszUrlPath = lpwhr->lpszPath;
    urlComponents.dwUrlPathLength = 0;
    urlComponents.lpszExtraInfo = NULL;
    urlComponents.dwExtraInfoLength = 0;
3098

3099 3100 3101
    if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
        (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
        return NULL;
3102

3103
    orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
3104

3105 3106 3107 3108 3109 3110 3111
    /* convert from bytes to characters */
    url_length = url_length / sizeof(WCHAR) - 1;
    if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
    {
        HeapFree(GetProcessHeap(), 0, orig_url);
        return NULL;
    }
3112

3113 3114 3115 3116 3117 3118 3119 3120
    url_length = 0;
    if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
        (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
    {
        HeapFree(GetProcessHeap(), 0, orig_url);
        return NULL;
    }
    combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
3121

3122 3123 3124 3125 3126 3127 3128 3129 3130
    if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
    {
        HeapFree(GetProcessHeap(), 0, orig_url);
        HeapFree(GetProcessHeap(), 0, combined_url);
        return NULL;
    }
    HeapFree(GetProcessHeap(), 0, orig_url);
    return combined_url;
}
3131 3132


3133 3134 3135
/***********************************************************************
 *           HTTP_HandleRedirect (internal)
 */
3136
static DWORD HTTP_HandleRedirect(http_request_t *lpwhr, LPCWSTR lpszUrl)
3137 3138 3139 3140 3141 3142
{
    http_session_t *lpwhs = lpwhr->lpHttpSession;
    appinfo_t *hIC = lpwhs->lpAppInfo;
    BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
    WCHAR path[INTERNET_MAX_URL_LENGTH];
    int index;
3143

3144
    if(lpszUrl[0]=='/')
3145
    {
3146 3147
        /* if it's an absolute path, keep the same session info */
        lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
3148
    }
3149 3150 3151 3152 3153 3154
    else
    {
        URL_COMPONENTSW urlComponents;
        WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
        static WCHAR szHttp[] = {'h','t','t','p',0};
        static WCHAR szHttps[] = {'h','t','t','p','s',0};
3155

3156 3157 3158
        userName[0] = 0;
        hostName[0] = 0;
        protocol[0] = 0;
3159

3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173
        urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
        urlComponents.lpszScheme = protocol;
        urlComponents.dwSchemeLength = 32;
        urlComponents.lpszHostName = hostName;
        urlComponents.dwHostNameLength = MAXHOSTNAME;
        urlComponents.lpszUserName = userName;
        urlComponents.dwUserNameLength = 1024;
        urlComponents.lpszPassword = NULL;
        urlComponents.dwPasswordLength = 0;
        urlComponents.lpszUrlPath = path;
        urlComponents.dwUrlPathLength = 2048;
        urlComponents.lpszExtraInfo = NULL;
        urlComponents.dwExtraInfoLength = 0;
        if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
3174
            return INTERNET_GetLastError();
3175

3176 3177
        if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
            (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3178
        {
3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
            TRACE("redirect from secure page to non-secure page\n");
            /* FIXME: warn about from secure redirect to non-secure page */
            lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
        }
        if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
            !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
        {
            TRACE("redirect from non-secure page to secure page\n");
            /* FIXME: notify about redirect to secure page */
            lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
        }
3190

3191 3192 3193 3194 3195 3196 3197
        if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
        {
            if (lstrlenW(protocol)>4) /*https*/
                urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
            else /*http*/
                urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
        }
3198

3199 3200 3201 3202 3203 3204 3205 3206 3207
#if 0
        /*
         * This upsets redirects to binary files on sourceforge.net 
         * and gives an html page instead of the target file
         * Examination of the HTTP request sent by native wininet.dll
         * reveals that it doesn't send a referrer in that case.
         * Maybe there's a flag that enables this, or maybe a referrer
         * shouldn't be added in case of a redirect.
         */
3208

3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225
        /* consider the current host as the referrer */
        if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
            HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
                           HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
                           HTTP_ADDHDR_FLAG_ADD_IF_NEW);
#endif
        
        HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
        if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
            urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
        {
            int len;
            static const WCHAR fmt[] = {'%','s',':','%','i',0};
            len = lstrlenW(hostName);
            len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
            lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
            sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3226
        }
3227
        else
3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
            lpwhs->lpszHostName = heap_strdupW(hostName);

        HTTP_ProcessHeader(lpwhr, hostW, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);

        HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
        lpwhs->lpszUserName = NULL;
        if (userName[0])
            lpwhs->lpszUserName = heap_strdupW(userName);

        if (!using_proxy)
3238
        {
3239 3240 3241
            if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
            {
                DWORD res;
3242

3243 3244 3245
                HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
                lpwhs->lpszServerName = heap_strdupW(hostName);
                lpwhs->nServerPort = urlComponents.nPort;
3246

3247
                NETCON_close(&lpwhr->netConnection);
3248 3249 3250
                if ((res = HTTP_ResolveName(lpwhr)) != ERROR_SUCCESS)
                    return res;

3251
                res = NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE);
3252 3253 3254
                if (res != ERROR_SUCCESS)
                    return res;

3255 3256 3257 3258 3259 3260
                lpwhr->read_pos = lpwhr->read_size = 0;
                lpwhr->read_chunked = FALSE;
            }
        }
        else
            TRACE("Redirect through proxy\n");
3261
    }
3262 3263 3264 3265

    HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
    lpwhr->lpszPath=NULL;
    if (*path)
3266
    {
3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
        DWORD needed = 0;
        HRESULT rc;

        rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
        if (rc != E_POINTER)
            needed = strlenW(path)+1;
        lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
        rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
                        URL_ESCAPE_SPACES_ONLY);
        if (rc != S_OK)
        {
            ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
            strcpyW(lpwhr->lpszPath,path);
        }
3281
    }
3282

3283 3284 3285 3286 3287 3288 3289
    /* Remove custom content-type/length headers on redirects.  */
    index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
    if (0 <= index)
        HTTP_DeleteCustomHeader(lpwhr, index);
    index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
    if (0 <= index)
        HTTP_DeleteCustomHeader(lpwhr, index);
3290

3291
    return ERROR_SUCCESS;
3292 3293
}

3294
/***********************************************************************
3295
 *           HTTP_build_req (internal)
3296
 *
3297
 *  concatenate all the strings in the request together
3298
 */
3299
static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3300
{
3301 3302
    LPCWSTR *t;
    LPWSTR str;
3303

3304 3305 3306
    for( t = list; *t ; t++  )
        len += strlenW( *t );
    len++;
3307

3308 3309
    str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
    *str = 0;
3310

3311 3312
    for( t = list; *t ; t++ )
        strcatW( str, *t );
3313

3314 3315
    return str;
}
3316

3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
static DWORD HTTP_SecureProxyConnect(http_request_t *lpwhr)
{
    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};
    static const WCHAR szFormat[] = {'%','s',':','%','d',0};
    http_session_t *lpwhs = lpwhr->lpHttpSession;
3329

3330
    TRACE("\n");
3331

3332 3333 3334 3335
    lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
    sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
    requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
    HeapFree( GetProcessHeap(), 0, lpszPath );
3336

3337 3338 3339 3340 3341 3342 3343
    len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
                                NULL, 0, NULL, NULL );
    len--; /* the nul terminator isn't needed */
    ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
    WideCharToMultiByte( CP_ACP, 0, requestString, -1,
                            ascii_req, len, NULL, NULL );
    HeapFree( GetProcessHeap(), 0, requestString );
3344

3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
    TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );

    res = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
    HeapFree( GetProcessHeap(), 0, ascii_req );
    if (res != ERROR_SUCCESS)
        return res;

    responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
    if (!responseLen)
        return ERROR_HTTP_INVALID_HEADER;

    return ERROR_SUCCESS;
}

static void HTTP_InsertCookies(http_request_t *lpwhr)
{
    static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
    LPWSTR lpszCookies, lpszUrl = NULL;
    DWORD nCookieSize, size;
    LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr, hostW);

    size = (strlenW(Host->lpszValue) + strlenW(szUrlForm) + strlenW(lpwhr->lpszPath)) * sizeof(WCHAR);
    if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
    sprintfW( lpszUrl, szUrlForm, Host->lpszValue, lpwhr->lpszPath);

    if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3371
    {
3372 3373
        int cnt = 0;
        static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3374

3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386
        size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
        if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
        {
            cnt += sprintfW(lpszCookies, szCookie);
            InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
            strcatW(lpszCookies, szCrLf);

            HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_REPLACE);
            HeapFree(GetProcessHeap(), 0, lpszCookies);
        }
    }
    HeapFree(GetProcessHeap(), 0, lpszUrl);
3387 3388
}

3389
/***********************************************************************
3390
 *           HTTP_HttpSendRequestW (internal)
3391 3392 3393 3394 3395 3396 3397 3398
 *
 * Sends the specified request to the HTTP server
 *
 * RETURNS
 *    TRUE  on success
 *    FALSE on failure
 *
 */
3399
static DWORD HTTP_HttpSendRequestW(http_request_t *lpwhr, LPCWSTR lpszHeaders,
3400 3401
	DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
	DWORD dwContentLength, BOOL bEndRequest)
3402
{
3403
    INT cnt;
3404
    BOOL redirected = FALSE;
3405 3406 3407 3408 3409 3410 3411 3412 3413
    LPWSTR requestString = NULL;
    INT responseLen;
    BOOL loop_next;
    INTERNET_ASYNC_RESULT iar;
    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;
3414

3415
    TRACE("--> %p\n", lpwhr);
3416

3417
    assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3418

3419 3420 3421
    /* if the verb is NULL default to GET */
    if (!lpwhr->lpszVerb)
        lpwhr->lpszVerb = heap_strdupW(szGET);
3422

3423
    if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3424
    {
3425 3426 3427
        sprintfW(contentLengthStr, szContentLength, dwContentLength);
        HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
        lpwhr->dwBytesToWrite = dwContentLength;
3428
    }
3429
    if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3430
    {
3431 3432 3433
        WCHAR *agent_header;
        static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
        int len;
3434

3435 3436 3437 3438 3439 3440 3441 3442
        len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
        agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);

        HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
        HeapFree(GetProcessHeap(), 0, agent_header);
    }
    if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3443
    {
3444 3445
        static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
        HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3446
    }
3447
    if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3448
    {
3449 3450 3451
        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};
        HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3452
    }
3453 3454

    do
3455
    {
3456 3457
        DWORD len;
        char *ascii_req;
3458

3459
        loop_next = FALSE;
3460

3461 3462 3463 3464
        /* like native, just in case the caller forgot to call InternetReadFile
         * for all the data */
        HTTP_DrainContent(lpwhr);
        lpwhr->dwContentRead = 0;
3465 3466 3467 3468
        if(redirected) {
            lpwhr->dwContentLength = ~0u;
            lpwhr->dwBytesToWrite = 0;
        }
3469

3470
        if (TRACE_ON(wininet))
3471
        {
3472 3473
            LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr, hostW);
            TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3474 3475
        }

3476 3477
        HTTP_FixURL(lpwhr);
        if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3478
        {
3479
            HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3480
        }
3481 3482
        HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
        HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3483

3484 3485
        if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
            HTTP_InsertCookies(lpwhr);
3486

3487 3488
        /* add the headers the caller supplied */
        if( lpszHeaders && dwHeaderLength )
3489
        {
3490 3491
            HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
                        HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3492
        }
3493

3494
        if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3495
        {
3496 3497 3498
            WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
            requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
            HeapFree(GetProcessHeap(), 0, url);
3499 3500
        }
        else
3501
            requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3502

3503 3504
 
        TRACE("Request header -> %s\n", debugstr_w(requestString) );
3505

3506
        /* Send the request and store the results */
3507
        if ((res = HTTP_OpenConnection(lpwhr)) != ERROR_SUCCESS)
3508
            goto lend;
3509

3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522
        /* 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 );
        ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
        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) );
3523

3524 3525
        INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                              INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3526

3527
        res = NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3528
        HeapFree( GetProcessHeap(), 0, ascii_req );
3529

3530
        lpwhr->dwBytesWritten = dwOptionalLength;
3531

3532 3533 3534
        INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                              INTERNET_STATUS_REQUEST_SENT,
                              &len, sizeof(DWORD));
3535

3536 3537 3538 3539
        if (bEndRequest)
        {
            DWORD dwBufferSize;
            DWORD dwStatusCode;
3540

3541 3542 3543
            INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                                INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
    
3544
            if (res != ERROR_SUCCESS)
3545 3546 3547 3548 3549 3550 3551
                goto lend;
    
            responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
    
            INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                                INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
                                sizeof(DWORD));
3552

3553
            HTTP_ProcessCookies(lpwhr);
3554

3555
            if (!set_content_length( lpwhr )) HTTP_FinishedReading(lpwhr);
3556

3557
            dwBufferSize = sizeof(dwStatusCode);
3558 3559
            if (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
                                    &dwStatusCode,&dwBufferSize,NULL) != ERROR_SUCCESS)
3560
                dwStatusCode = 0;
3561

3562
            if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
3563
            {
3564
                WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
3565
                dwBufferSize=sizeof(szNewLocation);
3566
                if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3567
                    HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) == ERROR_SUCCESS)
3568
                {
3569 3570 3571 3572 3573
                    if (strcmpW(lpwhr->lpszVerb, szGET) && strcmpW(lpwhr->lpszVerb, szHEAD))
                    {
                        HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
                        lpwhr->lpszVerb = heap_strdupW(szGET);
                    }
3574
                    HTTP_DrainContent(lpwhr);
3575
                    if ((new_url = HTTP_GetRedirectURL( lpwhr, szNewLocation )))
3576
                    {
3577 3578
                        INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REDIRECT,
                                              new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
3579 3580
                        res = HTTP_HandleRedirect(lpwhr, new_url);
                        if (res == ERROR_SUCCESS)
3581 3582 3583 3584 3585
                        {
                            HeapFree(GetProcessHeap(), 0, requestString);
                            loop_next = TRUE;
                        }
                        HeapFree( GetProcessHeap(), 0, new_url );
3586
                    }
3587
                    redirected = TRUE;
3588 3589
                }
            }
3590
            if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
3591 3592 3593
            {
                WCHAR szAuthValue[2048];
                dwBufferSize=2048;
3594
                if (dwStatusCode == HTTP_STATUS_DENIED)
3595
                {
3596
                    LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr, hostW);
3597
                    DWORD dwIndex = 0;
3598
                    while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
3599
                    {
3600 3601 3602
                        if (HTTP_DoAuthorization(lpwhr, szAuthValue,
                                                 &lpwhr->pAuthInfo,
                                                 lpwhr->lpHttpSession->lpszUserName,
3603 3604
                                                 lpwhr->lpHttpSession->lpszPassword,
                                                 Host->lpszValue))
3605
                        {
3606
                            HeapFree(GetProcessHeap(), 0, requestString);
3607 3608 3609 3610 3611 3612 3613 3614
                            loop_next = TRUE;
                            break;
                        }
                    }
                }
                if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
                {
                    DWORD dwIndex = 0;
3615
                    while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
3616 3617 3618 3619
                    {
                        if (HTTP_DoAuthorization(lpwhr, szAuthValue,
                                                 &lpwhr->pProxyAuthInfo,
                                                 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3620 3621
                                                 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword,
                                                 NULL))
3622 3623 3624 3625 3626 3627 3628
                        {
                            loop_next = TRUE;
                            break;
                        }
                    }
                }
            }
3629 3630
        }
        else
3631
            res = ERROR_SUCCESS;
3632 3633
    }
    while (loop_next);
3634

3635
    if(res == ERROR_SUCCESS) {
3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647
        WCHAR url[INTERNET_MAX_URL_LENGTH];
        WCHAR cacheFileName[MAX_PATH+1];
        BOOL b;

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

        b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
        if(b) {
3648 3649 3650
            HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
            CloseHandle(lpwhr->hCacheFile);

3651
            lpwhr->lpszCacheFile = heap_strdupW(cacheFileName);
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
            lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
                      NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
            if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
                WARN("Could not create file: %u\n", GetLastError());
                lpwhr->hCacheFile = NULL;
            }
        }else {
            WARN("Could not create cache entry: %08x\n", GetLastError());
        }
    }

3663 3664
lend:

3665
    HeapFree(GetProcessHeap(), 0, requestString);
3666

3667
    /* TODO: send notification for P3P header */
3668

3669 3670
    if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
3671 3672
        if (res == ERROR_SUCCESS && lpwhr->dwBytesWritten == lpwhr->dwBytesToWrite)
            HTTP_ReceiveRequestData(lpwhr, TRUE);
3673 3674
        else
        {
3675
            iar.dwResult = 0;
3676
            iar.dwError = res;
3677

3678 3679 3680 3681 3682
            INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                                  INTERNET_STATUS_REQUEST_COMPLETE, &iar,
                                  sizeof(INTERNET_ASYNC_RESULT));
        }
    }
3683 3684

    TRACE("<--\n");
3685
    return res;
3686 3687
}

3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
/***********************************************************************
 *
 * Helper functions for the HttpSendRequest(Ex) functions
 *
 */
static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
{
    struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
    http_request_t *lpwhr = (http_request_t*) workRequest->hdr;

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

    HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
            req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
            req->dwContentLength, req->bEndRequest);

    HeapFree(GetProcessHeap(), 0, req->lpszHeader);
}


3708
static DWORD HTTP_HttpEndRequestW(http_request_t *lpwhr, DWORD dwFlags, DWORD_PTR dwContext)
3709 3710 3711 3712
{
    INT responseLen;
    DWORD dwBufferSize;
    INTERNET_ASYNC_RESULT iar;
3713
    DWORD res = ERROR_SUCCESS;
3714 3715 3716 3717 3718

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

    responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3719 3720
    if (!responseLen)
        res = ERROR_HTTP_HEADER_NOT_FOUND;
3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732

    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                  INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));

    /* process cookies here. Is this right? */
    HTTP_ProcessCookies(lpwhr);

    if (!set_content_length( lpwhr )) HTTP_FinishedReading(lpwhr);

    if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
    {
        DWORD dwCode,dwCodeLength = sizeof(DWORD);
3733 3734
        if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE, &dwCode, &dwCodeLength, NULL) == ERROR_SUCCESS
            && (dwCode == 302 || dwCode == 301 || dwCode == 303))
3735 3736 3737
        {
            WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
            dwBufferSize=sizeof(szNewLocation);
3738
            if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) == ERROR_SUCCESS)
3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749
            {
                if (strcmpW(lpwhr->lpszVerb, szGET) && strcmpW(lpwhr->lpszVerb, szHEAD))
                {
                    HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
                    lpwhr->lpszVerb = heap_strdupW(szGET);
                }
                HTTP_DrainContent(lpwhr);
                if ((new_url = HTTP_GetRedirectURL( lpwhr, szNewLocation )))
                {
                    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REDIRECT,
                                          new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
3750 3751
                    res = HTTP_HandleRedirect(lpwhr, new_url);
                    if (res == ERROR_SUCCESS)
3752
                        res = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
3753 3754 3755 3756 3757 3758 3759
                    HeapFree( GetProcessHeap(), 0, new_url );
                }
            }
        }
    }

    iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3760
    iar.dwError = res;
3761 3762 3763 3764

    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                          INTERNET_STATUS_REQUEST_COMPLETE, &iar,
                          sizeof(INTERNET_ASYNC_RESULT));
3765
    return res;
3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784
}

/***********************************************************************
 *           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)
    {
3785
        SetLastError(ERROR_INVALID_PARAMETER);
3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815
        return FALSE;
    }

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

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

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

    HTTP_HttpEndRequestW(lpwhr, req->dwFlags, req->dwContext);
}

/***********************************************************************
 *           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)
{
    http_request_t *lpwhr;
3816
    DWORD res;
3817 3818 3819 3820 3821

    TRACE("-->\n");

    if (lpBuffersOut)
    {
3822
        SetLastError(ERROR_INVALID_PARAMETER);
3823 3824 3825 3826 3827 3828 3829
        return FALSE;
    }

    lpwhr = (http_request_t*) WININET_GetObject( hRequest );

    if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
    {
3830
        SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849
        if (lpwhr)
            WININET_Release( &lpwhr->hdr );
        return FALSE;
    }
    lpwhr->hdr.dwFlags |= dwFlags;

    if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
    {
        WORKREQUEST work;
        struct WORKREQ_HTTPENDREQUESTW *request;

        work.asyncproc = AsyncHttpEndRequestProc;
        work.hdr = WININET_AddRef( &lpwhr->hdr );

        request = &work.u.HttpEndRequestW;
        request->dwFlags = dwFlags;
        request->dwContext = dwContext;

        INTERNET_AsyncCall(&work);
3850
        res = ERROR_IO_PENDING;
3851 3852
    }
    else
3853
        res = HTTP_HttpEndRequestW(lpwhr, dwFlags, dwContext);
3854 3855

    WININET_Release( &lpwhr->hdr );
3856 3857 3858 3859
    TRACE("%u <--\n", res);
    if(res != ERROR_SUCCESS)
        SetLastError(res);
    return res == ERROR_SUCCESS;
3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
}

/***********************************************************************
 *           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);
            header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
            if (!(BuffersInW.lpcszHeader = header))
            {
3895
                SetLastError(ERROR_OUTOFMEMORY);
3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935
                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);

    HeapFree(GetProcessHeap(),0,header);

    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)
{
    http_request_t *lpwhr;
    http_session_t *lpwhs;
    appinfo_t *hIC;
3936
    DWORD res;
3937 3938 3939 3940 3941 3942 3943 3944

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

    lpwhr = (http_request_t*) WININET_GetObject( hRequest );

    if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
    {
3945
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997
        goto lend;
    }

    lpwhs = lpwhr->lpHttpSession;
    assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
    hIC = lpwhs->lpAppInfo;
    assert(hIC->hdr.htype == WH_HINIT);

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

        workRequest.asyncproc = AsyncHttpSendRequestProc;
        workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
        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);

                req->lpszHeader = HeapAlloc( GetProcessHeap(), 0, size );
                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.
         */
3998
        res = ERROR_IO_PENDING;
3999 4000 4001 4002
    }
    else
    {
        if (lpBuffersIn)
4003
            res = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
4004 4005 4006
                                        lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
                                        lpBuffersIn->dwBufferTotal, FALSE);
        else
4007
            res = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
4008 4009 4010 4011 4012 4013 4014
    }

lend:
    if ( lpwhr )
        WININET_Release( &lpwhr->hdr );

    TRACE("<---\n");
4015
    SetLastError(res);
4016
    return res == ERROR_SUCCESS;
4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
}

/***********************************************************************
 *           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)
{
    http_request_t *lpwhr;
    http_session_t *lpwhs = NULL;
    appinfo_t *hIC = NULL;
    DWORD res = ERROR_SUCCESS;

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

    lpwhr = (http_request_t*) WININET_GetObject( hHttpRequest );
    if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
    {
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
    }

    lpwhs = lpwhr->lpHttpSession;
    if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
    {
        res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
        goto lend;
    }

    hIC = lpwhs->lpAppInfo;
    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;
        workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
        req = &workRequest.u.HttpSendRequestW;
        if (lpszHeaders)
        {
            DWORD size;

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

            req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, size);
            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
    {
4095
	res = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
4096 4097 4098 4099 4100 4101 4102
		dwHeaderLength, lpOptional, dwOptionalLength,
		dwOptionalLength, TRUE);
    }
lend:
    if( lpwhr )
        WININET_Release( &lpwhr->hdr );

4103
    SetLastError(res);
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
    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);
        szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
    }
    result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
    HeapFree(GetProcessHeap(),0,szHeaders);
    return result;
}

4134 4135 4136 4137 4138 4139
/***********************************************************************
 *           HTTPSESSION_Destroy (internal)
 *
 * Deallocate session handle
 *
 */
4140
static void HTTPSESSION_Destroy(object_header_t *hdr)
4141
{
4142
    http_session_t *lpwhs = (http_session_t*) hdr;
4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154

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

    WININET_Release(&lpwhs->lpAppInfo->hdr);

    HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
    HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
    HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
    HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
    HeapFree(GetProcessHeap(), 0, lpwhs);
}

4155
static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168
{
    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;
    }

4169
    return INET_QueryOption(hdr, option, buffer, size, unicode);
4170
}
4171

4172
static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
4173
{
4174
    http_session_t *ses = (http_session_t*)hdr;
4175 4176 4177 4178

    switch(option) {
    case INTERNET_OPTION_USERNAME:
    {
4179
        HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
4180
        if (!(ses->lpszUserName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
4181 4182 4183 4184
        return ERROR_SUCCESS;
    }
    case INTERNET_OPTION_PASSWORD:
    {
4185
        HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
4186
        if (!(ses->lpszPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
4187 4188 4189 4190 4191 4192 4193 4194
        return ERROR_SUCCESS;
    }
    default: break;
    }

    return ERROR_INTERNET_INVALID_OPTION;
}

4195
static const object_vtbl_t HTTPSESSIONVtbl = {
4196
    HTTPSESSION_Destroy,
4197
    NULL,
4198
    HTTPSESSION_QueryOption,
4199
    HTTPSESSION_SetOption,
4200
    NULL,
4201
    NULL,
4202
    NULL,
4203
    NULL,
4204
    NULL
4205 4206 4207
};


4208 4209 4210 4211 4212 4213 4214 4215 4216 4217
/***********************************************************************
 *           HTTP_Connect  (internal)
 *
 * Create http session handle
 *
 * RETURNS
 *   HINTERNET a session handle on success
 *   NULL on failure
 *
 */
4218 4219 4220 4221
DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
        INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
        LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
        DWORD dwInternalFlags, HINTERNET *ret)
4222
{
4223
    http_session_t *lpwhs = NULL;
4224
    HINTERNET handle = NULL;
4225
    DWORD res = ERROR_SUCCESS;
4226

4227
    TRACE("-->\n");
4228

4229
    if (!lpszServerName || !lpszServerName[0])
4230
        return ERROR_INVALID_PARAMETER;
4231

4232
    assert( hIC->hdr.htype == WH_HINIT );
4233

4234
    lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(http_session_t));
4235 4236
    if (!lpwhs)
        return ERROR_OUTOFMEMORY;
4237

4238 4239 4240
   /*
    * According to my tests. The name is not resolved until a request is sent
    */
4241 4242

    lpwhs->hdr.htype = WH_HHTTPSESSION;
4243
    lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
4244 4245
    lpwhs->hdr.dwFlags = dwFlags;
    lpwhs->hdr.dwContext = dwContext;
4246
    lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
4247
    lpwhs->hdr.refs = 1;
4248
    lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
4249

4250 4251
    WININET_AddRef( &hIC->hdr );
    lpwhs->lpAppInfo = hIC;
4252
    list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
4253

4254 4255 4256 4257
    handle = WININET_AllocHandle( &lpwhs->hdr );
    if (NULL == handle)
    {
        ERR("Failed to alloc handle\n");
4258 4259
        res = ERROR_OUTOFMEMORY;
        goto lerror;
4260 4261
    }

4262 4263 4264 4265
    if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
        if(hIC->lpszProxyBypass)
            FIXME("Proxy bypass is ignored.\n");
    }
4266 4267
    lpwhs->lpszServerName = heap_strdupW(lpszServerName);
    lpwhs->lpszHostName = heap_strdupW(lpszServerName);
4268
    if (lpszUserName && lpszUserName[0])
4269
        lpwhs->lpszUserName = heap_strdupW(lpszUserName);
4270
    if (lpszPassword && lpszPassword[0])
4271
        lpwhs->lpszPassword = heap_strdupW(lpszPassword);
4272
    lpwhs->nServerPort = nServerPort;
4273
    lpwhs->nHostPort = nServerPort;
4274

4275
    /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
4276
    if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
4277
    {
4278 4279 4280
        INTERNET_SendCallback(&hIC->hdr, dwContext,
                              INTERNET_STATUS_HANDLE_CREATED, &handle,
                              sizeof(handle));
4281 4282 4283
    }

lerror:
4284 4285
    if( lpwhs )
        WININET_Release( &lpwhs->hdr );
4286

4287
/*
4288
 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
4289 4290
 * windows
 */
4291

4292
    TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
4293 4294 4295 4296

    if(res == ERROR_SUCCESS)
        *ret = handle;
    return res;
4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309
}


/***********************************************************************
 *           HTTP_OpenConnection (internal)
 *
 * Connect to a web server
 *
 * RETURNS
 *
 *   TRUE  on success
 *   FALSE on failure
 */
4310
static DWORD HTTP_OpenConnection(http_request_t *lpwhr)
4311
{
4312
    http_session_t *lpwhs;
4313
    appinfo_t *hIC = NULL;
4314
    char szaddr[INET6_ADDRSTRLEN];
4315
    const void *addr;
4316
    DWORD res = ERROR_SUCCESS;
4317 4318

    TRACE("-->\n");
4319 4320


4321
    if (lpwhr->hdr.htype != WH_HHTTPREQ)
4322
    {
4323
        res = ERROR_INVALID_PARAMETER;
4324 4325 4326
        goto lend;
    }

4327 4328
    if (NETCON_connected(&lpwhr->netConnection))
        goto lend;
4329
    if ((res = HTTP_ResolveName(lpwhr)) != ERROR_SUCCESS) goto lend;
4330

4331
    lpwhs = lpwhr->lpHttpSession;
4332

4333
    hIC = lpwhs->lpAppInfo;
4334 4335 4336 4337 4338
    switch (lpwhs->socketAddress.ss_family)
    {
    case AF_INET:
        addr = &((struct sockaddr_in *)&lpwhs->socketAddress)->sin_addr;
        break;
4339 4340 4341
    case AF_INET6:
        addr = &((struct sockaddr_in6 *)&lpwhs->socketAddress)->sin6_addr;
        break;
4342 4343
    default:
        WARN("unsupported family %d\n", lpwhs->socketAddress.ss_family);
4344
        return ERROR_INTERNET_NAME_NOT_RESOLVED;
4345 4346
    }
    inet_ntop(lpwhs->socketAddress.ss_family, addr, szaddr, sizeof(szaddr));
4347 4348
    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
                          INTERNET_STATUS_CONNECTING_TO_SERVER,
4349 4350
                          szaddr,
                          strlen(szaddr)+1);
4351

4352 4353
    res = NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.ss_family, SOCK_STREAM, 0);
    if (res != ERROR_SUCCESS)
4354
    {
4355
        WARN("Socket creation failed: %u\n", res);
4356 4357 4358
        goto lend;
    }

4359 4360 4361
    res = NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
                         lpwhs->sa_len);
    if(res != ERROR_SUCCESS)
4362 4363
       goto lend;

4364 4365 4366 4367
    INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
            INTERNET_STATUS_CONNECTED_TO_SERVER,
            szaddr, strlen(szaddr)+1);

4368 4369
    if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
    {
4370 4371 4372 4373 4374 4375
        /* 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 */
4376 4377
        if (hIC->lpszProxy && (res = HTTP_SecureProxyConnect(lpwhr)) != ERROR_SUCCESS) {
            HTTPREQ_CloseConnection(&lpwhr->hdr);
4378
            goto lend;
4379
        }
4380

4381 4382
        res = NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName);
        if(res != ERROR_SUCCESS)
4383 4384
        {
            WARN("Couldn't connect securely to host\n");
4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395

            if((lpwhr->hdr.ErrorMask&INTERNET_ERROR_MASK_COMBINED_SEC_CERT) && (
                    res == ERROR_INTERNET_SEC_CERT_DATE_INVALID
                    || res == ERROR_INTERNET_INVALID_CA
                    || res == ERROR_INTERNET_SEC_CERT_NO_REV
                    || res == ERROR_INTERNET_SEC_CERT_REV_FAILED
                    || res == ERROR_INTERNET_SEC_CERT_REVOKED
                    || res == ERROR_INTERNET_SEC_INVALID_CERT
                    || res == ERROR_INTERNET_SEC_CERT_CN_INVALID))
                res = ERROR_INTERNET_SEC_CERT_ERRORS;

4396
            HTTPREQ_CloseConnection(&lpwhr->hdr);
4397 4398 4399 4400
            goto lend;
        }
    }

4401

4402
lend:
4403
    lpwhr->read_pos = lpwhr->read_size = 0;
4404 4405
    lpwhr->read_chunked = FALSE;

4406 4407
    TRACE("%d <--\n", res);
    return res;
4408 4409 4410
}


4411 4412 4413 4414 4415
/***********************************************************************
 *           HTTP_clear_response_headers (internal)
 *
 * clear out any old response headers
 */
4416
static void HTTP_clear_response_headers( http_request_t *lpwhr )
4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427
{
    DWORD i;

    for( i=0; i<lpwhr->nCustHeaders; i++)
    {
        if( !lpwhr->pCustHeaders[i].lpszField )
            continue;
        if( !lpwhr->pCustHeaders[i].lpszValue )
            continue;
        if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
            continue;
4428 4429
        HTTP_DeleteCustomHeader( lpwhr, i );
        i--;
4430 4431 4432
    }
}

4433 4434 4435 4436 4437 4438 4439 4440 4441 4442
/***********************************************************************
 *           HTTP_GetResponseHeaders (internal)
 *
 * Read server response
 *
 * RETURNS
 *
 *   TRUE  on success
 *   FALSE on error
 */
4443
static INT HTTP_GetResponseHeaders(http_request_t *lpwhr, BOOL clear)
4444 4445
{
    INT cbreaks = 0;
4446
    WCHAR buffer[MAX_REPLY_LEN];
4447 4448
    DWORD buflen = MAX_REPLY_LEN;
    BOOL bSuccess = FALSE;
4449
    INT  rc = 0;
4450
    char bufferA[MAX_REPLY_LEN];
4451
    LPWSTR status_code = NULL, status_text = NULL;
4452
    DWORD cchMaxRawHeaders = 1024;
4453
    LPWSTR lpszRawHeaders = NULL;
4454
    LPWSTR temp;
4455
    DWORD cchRawHeaders = 0;
4456
    BOOL codeHundred = FALSE;
4457

4458
    TRACE("-->\n");
4459

4460
    /* clear old response headers (eg. from a redirect response) */
4461
    if (clear) HTTP_clear_response_headers( lpwhr );
4462

4463
    if (!NETCON_connected(&lpwhr->netConnection))
4464 4465
        goto lend;

4466
    do {
4467
        static const WCHAR szHundred[] = {'1','0','0',0};
4468 4469 4470
        /*
         * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
         */
4471
        buflen = MAX_REPLY_LEN;
4472
        if (!read_line(lpwhr, bufferA, &buflen))
4473
            goto lend;
4474
        rc += buflen;
4475
        MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
4476 4477 4478 4479 4480 4481 4482 4483
        /* 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;
4484

4485 4486 4487 4488 4489
            /* split the status code from the status text */
            status_text = strchrW( status_code, ' ' );
            if( !status_text )
                goto lend;
            *status_text++=0;
4490

4491 4492
            TRACE("version [%s] status code [%s] status text [%s]\n",
               debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
4493

4494 4495 4496 4497
            codeHundred = (!strcmpW(status_code, szHundred));
        }
        else if (!codeHundred)
        {
4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509
            WARN("No status line at head of response (%s)\n", debugstr_w(buffer));

            HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
            HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);

            lpwhr->lpszVersion = heap_strdupW(g_szHttp1_0);
            lpwhr->lpszStatusText = heap_strdupW(szOK);

            HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
            lpwhr->lpszRawHeaders = heap_strdupW(szDefaultHeader);

            bSuccess = TRUE;
4510
            goto lend;
4511 4512
        }
    } while (codeHundred);
4513

4514 4515 4516 4517 4518 4519 4520
    /* Add status code */
    HTTP_ProcessHeader(lpwhr, szStatus, status_code,
            HTTP_ADDHDR_FLAG_REPLACE);

    HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
    HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);

4521 4522
    lpwhr->lpszVersion = heap_strdupW(buffer);
    lpwhr->lpszStatusText = heap_strdupW(status_text);
4523 4524 4525 4526 4527

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

4528
    /* regenerate raw headers */
4529 4530 4531
    lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders + 1) * sizeof(WCHAR));
    if (!lpszRawHeaders) goto lend;

4532 4533
    while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
        cchMaxRawHeaders *= 2;
4534 4535 4536
    temp = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
    if (temp == NULL) goto lend;
    lpszRawHeaders = temp;
4537 4538 4539 4540 4541 4542
    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';

4543 4544 4545 4546
    /* Parse each response line */
    do
    {
	buflen = MAX_REPLY_LEN;
4547
        if (read_line(lpwhr, bufferA, &buflen))
4548 4549 4550
        {
            LPWSTR * pFieldAndValue;

4551
            TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
4552 4553

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

4556
            pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575
            if (pFieldAndValue)
            {
                while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
                    cchMaxRawHeaders *= 2;
                temp = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
                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';

                HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
                                   HTTP_ADDREQ_FLAG_ADD );

                HTTP_FreeTokens(pFieldAndValue);
            }
        }
4576 4577 4578 4579 4580 4581 4582 4583
	else
	{
	    cbreaks++;
	    if (cbreaks >= 2)
	       break;
	}
    }while(1);

4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596
    /* 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);
        temp = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders + 1) * sizeof(WCHAR));
        if (temp == NULL) goto lend;
        lpszRawHeaders = temp;
    }

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

4597
    HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
4598 4599
    lpwhr->lpszRawHeaders = lpszRawHeaders;
    TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
4600 4601 4602 4603
    bSuccess = TRUE;

lend:

4604 4605 4606 4607
    TRACE("<--\n");
    if (bSuccess)
        return rc;
    else
4608 4609
    {
        HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
4610
        return 0;
4611
    }
4612 4613 4614 4615 4616 4617 4618 4619 4620
}

/***********************************************************************
 *           HTTP_InterpretHttpHeader (internal)
 *
 * Parse server response
 *
 * RETURNS
 *
4621 4622
 *   Pointer to array of field, value, NULL on success.
 *   NULL on error.
4623
 */
Jacek Caban's avatar
Jacek Caban committed
4624
static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
4625
{
4626 4627 4628
    LPWSTR * pTokenPair;
    LPWSTR pszColon;
    INT len;
4629

4630
    pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
4631

4632 4633 4634
    pszColon = strchrW(buffer, ':');
    /* must have two tokens */
    if (!pszColon)
4635
    {
4636
        HTTP_FreeTokens(pTokenPair);
4637 4638
        if (buffer[0])
            TRACE("No ':' in line: %s\n", debugstr_w(buffer));
4639
        return NULL;
4640 4641
    }

4642 4643 4644 4645 4646 4647 4648 4649
    pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
    if (!pTokenPair[0])
    {
        HTTP_FreeTokens(pTokenPair);
        return NULL;
    }
    memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
    pTokenPair[0][pszColon - buffer] = '\0';
4650

4651 4652 4653 4654 4655
    /* skip colon */
    pszColon++;
    len = strlenW(pszColon);
    pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
    if (!pTokenPair[1])
4656
    {
4657 4658
        HTTP_FreeTokens(pTokenPair);
        return NULL;
4659
    }
4660
    memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
4661

4662 4663 4664 4665 4666
    strip_spaces(pTokenPair[0]);
    strip_spaces(pTokenPair[1]);

    TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
    return pTokenPair;
4667 4668 4669 4670 4671 4672 4673 4674 4675
}

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

Juan Lang's avatar
Juan Lang committed
4676
#define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4677

4678
static DWORD HTTP_ProcessHeader(http_request_t *lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4679
{
4680
    LPHTTPHEADERW lphttpHdr = NULL;
4681 4682
    INT index = -1;
    BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4683
    DWORD res = ERROR_HTTP_INVALID_HEADER;
4684

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

4687 4688 4689 4690 4691 4692 4693 4694 4695 4696
    /* 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
        index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);

    if (index >= 0)
4697
    {
4698
        if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4699
            return ERROR_HTTP_INVALID_HEADER;
4700 4701 4702 4703 4704
        lphttpHdr = &lpwhr->pCustHeaders[index];
    }
    else if (value)
    {
        HTTPHEADERW hdr;
4705

4706 4707 4708
        hdr.lpszField = (LPWSTR)field;
        hdr.lpszValue = (LPWSTR)value;
        hdr.wFlags = hdr.wCount = 0;
4709

4710 4711
        if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
            hdr.wFlags |= HDR_ISREQUEST;
4712

4713
        return HTTP_InsertCustomHeader(lpwhr, &hdr);
4714
    }
4715
    /* no value to delete */
4716
    else return ERROR_SUCCESS;
4717

4718
    if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4719
	    lphttpHdr->wFlags |= HDR_ISREQUEST;
4720 4721
    else
        lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4722

4723
    if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4724
    {
4725
        HTTP_DeleteCustomHeader( lpwhr, index );
4726

4727
        if (value)
4728
        {
4729 4730 4731 4732 4733
            HTTPHEADERW hdr;

            hdr.lpszField = (LPWSTR)field;
            hdr.lpszValue = (LPWSTR)value;
            hdr.wFlags = hdr.wCount = 0;
4734 4735

            if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4736 4737 4738
                hdr.wFlags |= HDR_ISREQUEST;

            return HTTP_InsertCustomHeader(lpwhr, &hdr);
4739 4740
        }

4741
        return ERROR_SUCCESS;
4742
    }
Juan Lang's avatar
Juan Lang committed
4743
    else if (dwModifier & COALESCEFLAGS)
4744 4745 4746 4747 4748 4749 4750 4751
    {
        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)
4752
        {
4753 4754
            ch = ',';
            lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4755
        }
4756
        else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4757
        {
4758 4759
            ch = ';';
            lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4760 4761
        }

4762
        len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4763

4764
        lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4765 4766 4767 4768 4769
        if (lpsztmp)
        {
            lphttpHdr->lpszValue = lpsztmp;
    /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
            if (ch > 0)
4770
            {
4771 4772 4773 4774
                lphttpHdr->lpszValue[origlen] = ch;
                origlen++;
                lphttpHdr->lpszValue[origlen] = ' ';
                origlen++;
4775
            }
4776 4777 4778

            memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
            lphttpHdr->lpszValue[len] = '\0';
4779
            res = ERROR_SUCCESS;
4780 4781 4782 4783
        }
        else
        {
            WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4784
            res = ERROR_OUTOFMEMORY;
4785 4786
        }
    }
4787 4788
    TRACE("<-- %d\n", res);
    return res;
4789 4790 4791
}


4792 4793 4794 4795 4796 4797
/***********************************************************************
 *           HTTP_FinishedReading (internal)
 *
 * Called when all content from server has been read by client.
 *
 */
4798
static BOOL HTTP_FinishedReading(http_request_t *lpwhr)
4799
{
4800
    BOOL keepalive = HTTP_KeepAlive(lpwhr);
4801 4802 4803

    TRACE("\n");

4804 4805 4806 4807

    if (!keepalive)
    {
        HTTPREQ_CloseConnection(&lpwhr->hdr);
4808 4809 4810 4811 4812 4813 4814
    }

    /* FIXME: store data in the URL cache here */

    return TRUE;
}

4815 4816 4817 4818 4819 4820 4821

/***********************************************************************
 *           HTTP_GetCustomHeaderIndex (internal)
 *
 * Return index of custom header from header array
 *
 */
4822
static INT HTTP_GetCustomHeaderIndex(http_request_t *lpwhr, LPCWSTR lpszField,
4823
                                     int requested_index, BOOL request_only)
4824
{
4825
    DWORD index;
4826

4827
    TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
4828 4829 4830

    for (index = 0; index < lpwhr->nCustHeaders; index++)
    {
4831 4832 4833 4834 4835 4836 4837
        if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
            continue;

        if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
            continue;

        if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4838
            continue;
4839

4840
        if (requested_index == 0)
4841 4842
            break;
        requested_index --;
4843 4844 4845 4846 4847
    }

    if (index >= lpwhr->nCustHeaders)
	index = -1;

4848
    TRACE("Return: %d\n", index);
4849 4850 4851 4852 4853 4854 4855 4856 4857 4858
    return index;
}


/***********************************************************************
 *           HTTP_InsertCustomHeader (internal)
 *
 * Insert header into array
 *
 */
4859
static DWORD HTTP_InsertCustomHeader(http_request_t *lpwhr, LPHTTPHEADERW lpHdr)
4860 4861
{
    INT count;
4862
    LPHTTPHEADERW lph = NULL;
4863

4864
    TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4865 4866
    count = lpwhr->nCustHeaders + 1;
    if (count > 1)
4867
	lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4868
    else
4869
	lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4870

4871 4872
    if (!lph)
        return ERROR_OUTOFMEMORY;
4873

4874 4875 4876 4877 4878 4879 4880 4881
    lpwhr->pCustHeaders = lph;
    lpwhr->pCustHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
    lpwhr->pCustHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
    lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
    lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
    lpwhr->nCustHeaders++;

    return ERROR_SUCCESS;
4882 4883 4884 4885 4886 4887 4888
}


/***********************************************************************
 *           HTTP_DeleteCustomHeader (internal)
 *
 * Delete header from array
4889
 *  If this function is called, the indexs may change.
4890
 */
4891
static BOOL HTTP_DeleteCustomHeader(http_request_t *lpwhr, DWORD index)
4892
{
4893 4894
    if( lpwhr->nCustHeaders <= 0 )
        return FALSE;
4895
    if( index >= lpwhr->nCustHeaders )
4896 4897 4898
        return FALSE;
    lpwhr->nCustHeaders--;

4899 4900 4901
    HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
    HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);

4902
    memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4903 4904
             (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
    memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4905 4906

    return TRUE;
4907
}
4908

4909 4910 4911 4912 4913 4914 4915

/***********************************************************************
 *           HTTP_VerifyValidHeader (internal)
 *
 * Verify the given header is not invalid for the given http request
 *
 */
4916
static BOOL HTTP_VerifyValidHeader(http_request_t *lpwhr, LPCWSTR field)
4917 4918
{
    /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4919
    if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4920
        return ERROR_HTTP_INVALID_HEADER;
4921

4922
    return ERROR_SUCCESS;
4923 4924
}

4925 4926 4927 4928 4929 4930 4931 4932
/***********************************************************************
 *          IsHostInProxyBypassList (@)
 *
 * Undocumented
 *
 */
BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
{
4933
   FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4934 4935
   return FALSE;
}