wintrust: Use a helper function to get a signer's cert info from a message.
[wine] / dlls / wininet / http.c
1 /*
2  * Wininet - Http Implementation
3  *
4  * Copyright 1999 Corel Corporation
5  * Copyright 2002 CodeWeavers Inc.
6  * Copyright 2002 TransGaming Technologies Inc.
7  * Copyright 2004 Mike McCormack for CodeWeavers
8  * Copyright 2005 Aric Stewart for CodeWeavers
9  * Copyright 2006 Robert Shearman for CodeWeavers
10  *
11  * Ulrich Czekalla
12  * David Hammerton
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * 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
29 #include "config.h"
30 #include "wine/port.h"
31
32 #include <sys/types.h>
33 #ifdef HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
35 #endif
36 #ifdef HAVE_ARPA_INET_H
37 # include <arpa/inet.h>
38 #endif
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45 #include <time.h>
46 #include <assert.h>
47
48 #include "windef.h"
49 #include "winbase.h"
50 #include "wininet.h"
51 #include "winerror.h"
52 #define NO_SHLWAPI_STREAM
53 #define NO_SHLWAPI_REG
54 #define NO_SHLWAPI_STRFCNS
55 #define NO_SHLWAPI_GDI
56 #include "shlwapi.h"
57 #include "sspi.h"
58
59 #include "internet.h"
60 #include "wine/debug.h"
61 #include "wine/unicode.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
64
65 static const WCHAR g_szHttp1_0[] = {' ','H','T','T','P','/','1','.','0',0 };
66 static const WCHAR g_szHttp1_1[] = {' ','H','T','T','P','/','1','.','1',0 };
67 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
68 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
69 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
70 static const WCHAR szHost[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
75
76 #define MAXHOSTNAME 100
77 #define MAX_FIELD_VALUE_LEN 256
78 #define MAX_FIELD_LEN 256
79
80 #define HTTP_REFERER    g_szReferer
81 #define HTTP_ACCEPT     g_szAccept
82 #define HTTP_USERAGENT  g_szUserAgent
83
84 #define HTTP_ADDHDR_FLAG_ADD                            0x20000000
85 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW                     0x10000000
86 #define HTTP_ADDHDR_FLAG_COALESCE                       0x40000000
87 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA            0x40000000
88 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON        0x01000000
89 #define HTTP_ADDHDR_FLAG_REPLACE                        0x80000000
90 #define HTTP_ADDHDR_FLAG_REQ                            0x02000000
91
92 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
93
94 struct HttpAuthInfo
95 {
96     LPWSTR scheme;
97     CredHandle cred;
98     CtxtHandle ctx;
99     TimeStamp exp;
100     ULONG attr;
101     void *auth_data;
102     unsigned int auth_data_len;
103     BOOL finished; /* finished authenticating */
104 };
105
106 static void HTTP_CloseConnection(LPWININETHANDLEHEADER hdr);
107 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr);
108 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr);
109 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
110 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr);
111 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
112 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
113 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
114 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
115 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
116 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
117 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
118         dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
119         lpdwIndex);
120 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
121 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
122 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
123
124
125 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
126 {
127     int HeaderIndex = 0;
128     HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
129     if (HeaderIndex == -1)
130         return NULL;
131     else
132         return &req->pCustHeaders[HeaderIndex];
133 }
134
135 /***********************************************************************
136  *           HTTP_Tokenize (internal)
137  *
138  *  Tokenize a string, allocating memory for the tokens.
139  */
140 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
141 {
142     LPWSTR * token_array;
143     int tokens = 0;
144     int i;
145     LPCWSTR next_token;
146
147     /* empty string has no tokens */
148     if (*string)
149         tokens++;
150     /* count tokens */
151     for (i = 0; string[i]; i++)
152         if (!strncmpW(string+i, token_string, strlenW(token_string)))
153         {
154             DWORD j;
155             tokens++;
156             /* we want to skip over separators, but not the null terminator */
157             for (j = 0; j < strlenW(token_string) - 1; j++)
158                 if (!string[i+j])
159                     break;
160             i += j;
161         }
162
163     /* add 1 for terminating NULL */
164     token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
165     token_array[tokens] = NULL;
166     if (!tokens)
167         return token_array;
168     for (i = 0; i < tokens; i++)
169     {
170         int len;
171         next_token = strstrW(string, token_string);
172         if (!next_token) next_token = string+strlenW(string);
173         len = next_token - string;
174         token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
175         memcpy(token_array[i], string, len*sizeof(WCHAR));
176         token_array[i][len] = '\0';
177         string = next_token+strlenW(token_string);
178     }
179     return token_array;
180 }
181
182 /***********************************************************************
183  *           HTTP_FreeTokens (internal)
184  *
185  *  Frees memory returned from HTTP_Tokenize.
186  */
187 static void HTTP_FreeTokens(LPWSTR * token_array)
188 {
189     int i;
190     for (i = 0; token_array[i]; i++)
191         HeapFree(GetProcessHeap(), 0, token_array[i]);
192     HeapFree(GetProcessHeap(), 0, token_array);
193 }
194
195 /* **********************************************************************
196  * 
197  * Helper functions for the HttpSendRequest(Ex) functions
198  * 
199  */
200 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
201 {
202     struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
203     LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
204
205     TRACE("%p\n", lpwhr);
206
207     HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
208             req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
209             req->dwContentLength, req->bEndRequest);
210
211     HeapFree(GetProcessHeap(), 0, req->lpszHeader);
212 }
213
214 static void HTTP_FixVerb( LPWININETHTTPREQW lpwhr )
215 {
216     /* if the verb is NULL default to GET */
217     if (NULL == lpwhr->lpszVerb)
218     {
219             static const WCHAR szGET[] = { 'G','E','T', 0 };
220             lpwhr->lpszVerb = WININET_strdupW(szGET);
221     }
222 }
223
224 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
225 {
226     static const WCHAR szSlash[] = { '/',0 };
227     static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
228
229     /* If we don't have a path we set it to root */
230     if (NULL == lpwhr->lpszPath)
231         lpwhr->lpszPath = WININET_strdupW(szSlash);
232     else /* remove \r and \n*/
233     {
234         int nLen = strlenW(lpwhr->lpszPath);
235         while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
236         {
237             nLen--;
238             lpwhr->lpszPath[nLen]='\0';
239         }
240         /* Replace '\' with '/' */
241         while (nLen>0) {
242             nLen--;
243             if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
244         }
245     }
246
247     if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
248                        lpwhr->lpszPath, strlenW(szHttp), szHttp, strlenW(szHttp) )
249        && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
250     {
251         WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0, 
252                              (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
253         *fixurl = '/';
254         strcpyW(fixurl + 1, lpwhr->lpszPath);
255         HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
256         lpwhr->lpszPath = fixurl;
257     }
258 }
259
260 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, BOOL http1_1 )
261 {
262     LPWSTR requestString;
263     DWORD len, n;
264     LPCWSTR *req;
265     INT i;
266     LPWSTR p;
267
268     static const WCHAR szSpace[] = { ' ',0 };
269     static const WCHAR szcrlf[] = {'\r','\n', 0};
270     static const WCHAR szColon[] = { ':',' ',0 };
271     static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
272
273     /* allocate space for an array of all the string pointers to be added */
274     len = (lpwhr->nCustHeaders)*4 + 9;
275     req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
276
277     /* add the verb, path and HTTP version string */
278     n = 0;
279     req[n++] = verb;
280     req[n++] = szSpace;
281     req[n++] = path;
282     req[n++] = http1_1 ? g_szHttp1_1 : g_szHttp1_0;
283
284     /* Append custom request heades */
285     for (i = 0; i < lpwhr->nCustHeaders; i++)
286     {
287         if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
288         {
289             req[n++] = szcrlf;
290             req[n++] = lpwhr->pCustHeaders[i].lpszField;
291             req[n++] = szColon;
292             req[n++] = lpwhr->pCustHeaders[i].lpszValue;
293
294             TRACE("Adding custom header %s (%s)\n",
295                    debugstr_w(lpwhr->pCustHeaders[i].lpszField),
296                    debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
297         }
298     }
299
300     if( n >= len )
301         ERR("oops. buffer overrun\n");
302
303     req[n] = NULL;
304     requestString = HTTP_build_req( req, 4 );
305     HeapFree( GetProcessHeap(), 0, req );
306
307     /*
308      * Set (header) termination string for request
309      * Make sure there's exactly two new lines at the end of the request
310      */
311     p = &requestString[strlenW(requestString)-1];
312     while ( (*p == '\n') || (*p == '\r') )
313        p--;
314     strcpyW( p+1, sztwocrlf );
315     
316     return requestString;
317 }
318
319 static void HTTP_ProcessHeaders( LPWININETHTTPREQW lpwhr )
320 {
321     static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
322     int HeaderIndex;
323     LPHTTPHEADERW setCookieHeader;
324
325     HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
326     if (HeaderIndex == -1)
327             return;
328     setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
329
330     if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
331     {
332         int nPosStart = 0, nPosEnd = 0, len;
333         static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
334
335         while (setCookieHeader->lpszValue[nPosEnd] != '\0')
336         {
337             LPWSTR buf_cookie, cookie_name, cookie_data;
338             LPWSTR buf_url;
339             LPWSTR domain = NULL;
340             LPHTTPHEADERW Host;
341
342             int nEqualPos = 0;
343             while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
344                    setCookieHeader->lpszValue[nPosEnd] != '\0')
345             {
346                 nPosEnd++;
347             }
348             if (setCookieHeader->lpszValue[nPosEnd] == ';')
349             {
350                 /* fixme: not case sensitive, strcasestr is gnu only */
351                 int nDomainPosEnd = 0;
352                 int nDomainPosStart = 0, nDomainLength = 0;
353                 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
354                 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
355                 if (lpszDomain)
356                 { /* they have specified their own domain, lets use it */
357                     while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
358                            lpszDomain[nDomainPosEnd] != '\0')
359                     {
360                         nDomainPosEnd++;
361                     }
362                     nDomainPosStart = strlenW(szDomain);
363                     nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
364                     domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
365                     lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
366                 }
367             }
368             if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
369             buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
370             lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
371             TRACE("%s\n", debugstr_w(buf_cookie));
372             while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
373             {
374                 nEqualPos++;
375             }
376             if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
377             {
378                 HeapFree(GetProcessHeap(), 0, buf_cookie);
379                 break;
380             }
381
382             cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
383             lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
384             cookie_data = &buf_cookie[nEqualPos + 1];
385
386             Host = HTTP_GetHeader(lpwhr,szHost);
387             len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) + 
388                 strlenW(lpwhr->lpszPath) + 9;
389             buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
390             sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
391             InternetSetCookieW(buf_url, cookie_name, cookie_data);
392
393             HeapFree(GetProcessHeap(), 0, buf_url);
394             HeapFree(GetProcessHeap(), 0, buf_cookie);
395             HeapFree(GetProcessHeap(), 0, cookie_name);
396             HeapFree(GetProcessHeap(), 0, domain);
397             nPosStart = nPosEnd;
398         }
399     }
400 }
401
402 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
403 {
404     static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
405     return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
406         ((pszAuthValue[ARRAYSIZE(szBasic)] != ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
407 }
408
409 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
410                                   struct HttpAuthInfo **ppAuthInfo,
411                                   LPWSTR domain_and_username, LPWSTR password )
412 {
413     SECURITY_STATUS sec_status;
414     struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
415     BOOL first = FALSE;
416
417     TRACE("%s\n", debugstr_w(pszAuthValue));
418
419     if (!domain_and_username) return FALSE;
420
421     if (!pAuthInfo)
422     {
423         TimeStamp exp;
424
425         first = TRUE;
426         pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
427         if (!pAuthInfo)
428             return FALSE;
429
430         SecInvalidateHandle(&pAuthInfo->cred);
431         SecInvalidateHandle(&pAuthInfo->ctx);
432         memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
433         pAuthInfo->attr = 0;
434         pAuthInfo->auth_data = NULL;
435         pAuthInfo->auth_data_len = 0;
436         pAuthInfo->finished = FALSE;
437
438         if (is_basic_auth_value(pszAuthValue))
439         {
440             static const WCHAR szBasic[] = {'B','a','s','i','c',0};
441             pAuthInfo->scheme = WININET_strdupW(szBasic);
442             if (!pAuthInfo->scheme)
443             {
444                 HeapFree(GetProcessHeap(), 0, pAuthInfo);
445                 return FALSE;
446             }
447         }
448         else
449         {
450             SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
451             WCHAR *user = strchrW(domain_and_username, '\\');
452             WCHAR *domain = domain_and_username;
453
454             pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
455             if (!pAuthInfo->scheme)
456             {
457                 HeapFree(GetProcessHeap(), 0, pAuthInfo);
458                 return FALSE;
459             }
460
461             if (user) user++;
462             else
463             {
464                 user = domain_and_username;
465                 domain = NULL;
466             }
467             nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
468             nt_auth_identity.User = user;
469             nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
470             nt_auth_identity.Domain = domain;
471             nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
472             nt_auth_identity.Password = password;
473             nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
474
475             /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
476
477             sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
478                                                    SECPKG_CRED_OUTBOUND, NULL,
479                                                    &nt_auth_identity, NULL,
480                                                    NULL, &pAuthInfo->cred,
481                                                    &exp);
482             if (sec_status != SEC_E_OK)
483             {
484                 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
485                      debugstr_w(pAuthInfo->scheme), sec_status);
486                 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
487                 HeapFree(GetProcessHeap(), 0, pAuthInfo);
488                 return FALSE;
489             }
490         }
491         *ppAuthInfo = pAuthInfo;
492     }
493     else if (pAuthInfo->finished)
494         return FALSE;
495
496     if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
497         strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
498     {
499         ERR("authentication scheme changed from %s to %s\n",
500             debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
501         return FALSE;
502     }
503
504     if (is_basic_auth_value(pszAuthValue))
505     {
506         int userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
507         int passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
508         char *auth_data;
509
510         TRACE("basic authentication\n");
511
512         /* length includes a nul terminator, which will be re-used for the ':' */
513         auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
514         if (!auth_data)
515             return FALSE;
516
517         WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
518         auth_data[userlen] = ':';
519         WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
520
521         pAuthInfo->auth_data = auth_data;
522         pAuthInfo->auth_data_len = userlen + 1 + passlen;
523         pAuthInfo->finished = TRUE;
524
525         return TRUE;
526     }
527     else
528     {
529         LPCWSTR pszAuthData;
530         SecBufferDesc out_desc, in_desc;
531         SecBuffer out, in;
532         unsigned char *buffer;
533         ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
534             ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
535
536         in.BufferType = SECBUFFER_TOKEN;
537         in.cbBuffer = 0;
538         in.pvBuffer = NULL;
539
540         in_desc.ulVersion = 0;
541         in_desc.cBuffers = 1;
542         in_desc.pBuffers = &in;
543
544         pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
545         if (*pszAuthData == ' ')
546         {
547             pszAuthData++;
548             in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
549             in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
550             HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
551         }
552
553         buffer = HeapAlloc(GetProcessHeap(), 0, 0x100);
554
555         out.BufferType = SECBUFFER_TOKEN;
556         out.cbBuffer = 0x100;
557         out.pvBuffer = buffer;
558
559         out_desc.ulVersion = 0;
560         out_desc.cBuffers = 1;
561         out_desc.pBuffers = &out;
562
563         sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
564                                                 first ? NULL : &pAuthInfo->ctx, NULL,
565                                                 context_req, 0, SECURITY_NETWORK_DREP,
566                                                 in.pvBuffer ? &in_desc : NULL,
567                                                 0, &pAuthInfo->ctx, &out_desc,
568                                                 &pAuthInfo->attr, &pAuthInfo->exp);
569         if (sec_status == SEC_E_OK)
570         {
571             pAuthInfo->finished = TRUE;
572             pAuthInfo->auth_data = out.pvBuffer;
573             pAuthInfo->auth_data_len = out.cbBuffer;
574             TRACE("sending last auth packet\n");
575         }
576         else if (sec_status == SEC_I_CONTINUE_NEEDED)
577         {
578             pAuthInfo->auth_data = out.pvBuffer;
579             pAuthInfo->auth_data_len = out.cbBuffer;
580             TRACE("sending next auth packet\n");
581         }
582         else
583         {
584             ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
585             HeapFree(GetProcessHeap(), 0, out.pvBuffer);
586             return FALSE;
587         }
588     }
589
590     return TRUE;
591 }
592
593 /***********************************************************************
594  *           HTTP_HttpAddRequestHeadersW (internal)
595  */
596 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
597         LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
598 {
599     LPWSTR lpszStart;
600     LPWSTR lpszEnd;
601     LPWSTR buffer;
602     BOOL bSuccess = FALSE;
603     DWORD len;
604
605     TRACE("copying header: %s\n", debugstr_w(lpszHeader));
606
607     if( dwHeaderLength == ~0U )
608         len = strlenW(lpszHeader);
609     else
610         len = dwHeaderLength;
611     buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
612     lstrcpynW( buffer, lpszHeader, len + 1);
613
614     lpszStart = buffer;
615
616     do
617     {
618         LPWSTR * pFieldAndValue;
619
620         lpszEnd = lpszStart;
621
622         while (*lpszEnd != '\0')
623         {
624             if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
625                  break;
626             lpszEnd++;
627         }
628
629         if (*lpszStart == '\0')
630             break;
631
632         if (*lpszEnd == '\r')
633         {
634             *lpszEnd = '\0';
635             lpszEnd += 2; /* Jump over \r\n */
636         }
637         TRACE("interpreting header %s\n", debugstr_w(lpszStart));
638         pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
639         if (pFieldAndValue)
640         {
641             bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
642             if (bSuccess)
643                 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
644                     pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
645             HTTP_FreeTokens(pFieldAndValue);
646         }
647
648         lpszStart = lpszEnd;
649     } while (bSuccess);
650
651     HeapFree(GetProcessHeap(), 0, buffer);
652
653     return bSuccess;
654 }
655
656 /***********************************************************************
657  *           HttpAddRequestHeadersW (WININET.@)
658  *
659  * Adds one or more HTTP header to the request handler
660  *
661  * RETURNS
662  *    TRUE  on success
663  *    FALSE on failure
664  *
665  */
666 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
667         LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
668 {
669     BOOL bSuccess = FALSE;
670     LPWININETHTTPREQW lpwhr;
671
672     TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_w(lpszHeader), dwHeaderLength,
673           dwModifier);
674
675     if (!lpszHeader) 
676       return TRUE;
677
678     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
679     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
680     {
681         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
682         goto lend;
683     }
684     bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
685 lend:
686     if( lpwhr )
687         WININET_Release( &lpwhr->hdr );
688
689     return bSuccess;
690 }
691
692 /***********************************************************************
693  *           HttpAddRequestHeadersA (WININET.@)
694  *
695  * Adds one or more HTTP header to the request handler
696  *
697  * RETURNS
698  *    TRUE  on success
699  *    FALSE on failure
700  *
701  */
702 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
703         LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
704 {
705     DWORD len;
706     LPWSTR hdr;
707     BOOL r;
708
709     TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_a(lpszHeader), dwHeaderLength,
710           dwModifier);
711
712     len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
713     hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
714     MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
715     if( dwHeaderLength != ~0U )
716         dwHeaderLength = len;
717
718     r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
719
720     HeapFree( GetProcessHeap(), 0, hdr );
721
722     return r;
723 }
724
725 /* read any content returned by the server so that the connection can be
726  * resued */
727 static void HTTP_DrainContent(LPWININETHTTPREQW lpwhr)
728 {
729     DWORD bytes_read;
730
731     if (!NETCON_connected(&lpwhr->netConnection)) return;
732
733     if (lpwhr->dwContentLength == -1)
734         NETCON_close(&lpwhr->netConnection);
735
736     do
737     {
738         char buffer[2048];
739         if (!INTERNET_ReadFile(&lpwhr->hdr, buffer, sizeof(buffer), &bytes_read,
740                                TRUE, FALSE))
741             return;
742     } while (bytes_read);
743 }
744
745 /***********************************************************************
746  *           HttpEndRequestA (WININET.@)
747  *
748  * Ends an HTTP request that was started by HttpSendRequestEx
749  *
750  * RETURNS
751  *    TRUE      if successful
752  *    FALSE     on failure
753  *
754  */
755 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest, 
756         LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD dwContext)
757 {
758     LPINTERNET_BUFFERSA ptr;
759     LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
760     BOOL rc = FALSE;
761
762     TRACE("(%p, %p, %08x, %08x): stub\n", hRequest, lpBuffersOut, dwFlags,
763             dwContext);
764
765     ptr = lpBuffersOut;
766     if (ptr)
767         lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
768                 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
769     else
770         lpBuffersOutW = NULL;
771
772     ptrW = lpBuffersOutW;
773     while (ptr)
774     {
775         if (ptr->lpvBuffer && ptr->dwBufferLength)
776             ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
777         ptrW->dwBufferLength = ptr->dwBufferLength;
778         ptrW->dwBufferTotal= ptr->dwBufferTotal;
779
780         if (ptr->Next)
781             ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
782                     sizeof(INTERNET_BUFFERSW));
783
784         ptr = ptr->Next;
785         ptrW = ptrW->Next;
786     }
787
788     rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
789
790     if (lpBuffersOutW)
791     {
792         ptrW = lpBuffersOutW;
793         while (ptrW)
794         {
795             LPINTERNET_BUFFERSW ptrW2;
796
797             FIXME("Do we need to translate info out of these buffer?\n");
798
799             HeapFree(GetProcessHeap(),0,(LPVOID)ptrW->lpvBuffer);
800             ptrW2 = ptrW->Next;
801             HeapFree(GetProcessHeap(),0,ptrW);
802             ptrW = ptrW2;
803         }
804     }
805
806     return rc;
807 }
808
809 /***********************************************************************
810  *           HttpEndRequestW (WININET.@)
811  *
812  * Ends an HTTP request that was started by HttpSendRequestEx
813  *
814  * RETURNS
815  *    TRUE      if successful
816  *    FALSE     on failure
817  *
818  */
819 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest, 
820         LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD dwContext)
821 {
822     BOOL rc = FALSE;
823     LPWININETHTTPREQW lpwhr;
824     INT responseLen;
825     DWORD dwBufferSize;
826
827     TRACE("-->\n");
828     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
829
830     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
831     {
832         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
833         return FALSE;
834     }
835
836     lpwhr->hdr.dwFlags |= dwFlags;
837     lpwhr->hdr.dwContext = dwContext;
838
839     /* We appear to do nothing with lpBuffersOut.. is that correct? */
840
841     SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
842             INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
843
844     responseLen = HTTP_GetResponseHeaders(lpwhr);
845     if (responseLen)
846             rc = TRUE;
847
848     SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
849             INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
850
851     /* process headers here. Is this right? */
852     HTTP_ProcessHeaders(lpwhr);
853
854     dwBufferSize = sizeof(lpwhr->dwContentLength);
855     if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
856                              &lpwhr->dwContentLength,&dwBufferSize,NULL))
857         lpwhr->dwContentLength = -1;
858
859     if (lpwhr->dwContentLength == 0)
860         HTTP_FinishedReading(lpwhr);
861
862     if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
863     {
864         DWORD dwCode,dwCodeLength=sizeof(DWORD);
865         if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
866             (dwCode==302 || dwCode==301))
867         {
868             WCHAR szNewLocation[2048];
869             dwBufferSize=sizeof(szNewLocation);
870             if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
871             {
872                     static const WCHAR szGET[] = { 'G','E','T', 0 };
873                 /* redirects are always GETs */
874                 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
875                     lpwhr->lpszVerb = WININET_strdupW(szGET);
876                 HTTP_DrainContent(lpwhr);
877                 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
878                 if (rc)
879                     rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
880             }
881         }
882     }
883
884     TRACE("%i <--\n",rc);
885     return rc;
886 }
887
888 /***********************************************************************
889  *           HttpOpenRequestW (WININET.@)
890  *
891  * Open a HTTP request handle
892  *
893  * RETURNS
894  *    HINTERNET  a HTTP request handle on success
895  *    NULL       on failure
896  *
897  */
898 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
899         LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
900         LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
901         DWORD dwFlags, DWORD dwContext)
902 {
903     LPWININETHTTPSESSIONW lpwhs;
904     HINTERNET handle = NULL;
905
906     TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08x)\n", hHttpSession,
907           debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
908           debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
909           dwFlags, dwContext);
910     if(lpszAcceptTypes!=NULL)
911     {
912         int i;
913         for(i=0;lpszAcceptTypes[i]!=NULL;i++)
914             TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
915     }    
916
917     lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
918     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
919     {
920         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
921         goto lend;
922     }
923
924     /*
925      * My tests seem to show that the windows version does not
926      * become asynchronous until after this point. And anyhow
927      * if this call was asynchronous then how would you get the
928      * necessary HINTERNET pointer returned by this function.
929      *
930      */
931     handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
932                                    lpszVersion, lpszReferrer, lpszAcceptTypes,
933                                    dwFlags, dwContext);
934 lend:
935     if( lpwhs )
936         WININET_Release( &lpwhs->hdr );
937     TRACE("returning %p\n", handle);
938     return handle;
939 }
940
941
942 /***********************************************************************
943  *           HttpOpenRequestA (WININET.@)
944  *
945  * Open a HTTP request handle
946  *
947  * RETURNS
948  *    HINTERNET  a HTTP request handle on success
949  *    NULL       on failure
950  *
951  */
952 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
953         LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
954         LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
955         DWORD dwFlags, DWORD dwContext)
956 {
957     LPWSTR szVerb = NULL, szObjectName = NULL;
958     LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
959     INT len;
960     INT acceptTypesCount;
961     HINTERNET rc = FALSE;
962     TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08x)\n", hHttpSession,
963           debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
964           debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
965           dwFlags, dwContext);
966
967     if (lpszVerb)
968     {
969         len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
970         szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
971         if ( !szVerb )
972             goto end;
973         MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
974     }
975
976     if (lpszObjectName)
977     {
978         len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
979         szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
980         if ( !szObjectName )
981             goto end;
982         MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
983     }
984
985     if (lpszVersion)
986     {
987         len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
988         szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
989         if ( !szVersion )
990             goto end;
991         MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
992     }
993
994     if (lpszReferrer)
995     {
996         len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
997         szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
998         if ( !szReferrer )
999             goto end;
1000         MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1001     }
1002
1003     acceptTypesCount = 0;
1004     if (lpszAcceptTypes)
1005     {
1006         /* find out how many there are */
1007         while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1008             acceptTypesCount++;
1009         szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1010         acceptTypesCount = 0;
1011         while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1012         {
1013             len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1014                                 -1, NULL, 0 );
1015             szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1016             if (!szAcceptTypes[acceptTypesCount] )
1017                 goto end;
1018             MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1019                                 -1, szAcceptTypes[acceptTypesCount], len );
1020             acceptTypesCount++;
1021         }
1022         szAcceptTypes[acceptTypesCount] = NULL;
1023     }
1024     else szAcceptTypes = 0;
1025
1026     rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1027                           szVersion, szReferrer,
1028                           (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1029
1030 end:
1031     if (szAcceptTypes)
1032     {
1033         acceptTypesCount = 0;
1034         while (szAcceptTypes[acceptTypesCount])
1035         {
1036             HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1037             acceptTypesCount++;
1038         }
1039         HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1040     }
1041     HeapFree(GetProcessHeap(), 0, szReferrer);
1042     HeapFree(GetProcessHeap(), 0, szVersion);
1043     HeapFree(GetProcessHeap(), 0, szObjectName);
1044     HeapFree(GetProcessHeap(), 0, szVerb);
1045
1046     return rc;
1047 }
1048
1049 /***********************************************************************
1050  *  HTTP_EncodeBase64
1051  */
1052 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1053 {
1054     UINT n = 0, x;
1055     static const CHAR HTTP_Base64Enc[] =
1056         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1057
1058     while( len > 0 )
1059     {
1060         /* first 6 bits, all from bin[0] */
1061         base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1062         x = (bin[0] & 3) << 4;
1063
1064         /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1065         if( len == 1 )
1066         {
1067             base64[n++] = HTTP_Base64Enc[x];
1068             base64[n++] = '=';
1069             base64[n++] = '=';
1070             break;
1071         }
1072         base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1073         x = ( bin[1] & 0x0f ) << 2;
1074
1075         /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1076         if( len == 2 )
1077         {
1078             base64[n++] = HTTP_Base64Enc[x];
1079             base64[n++] = '=';
1080             break;
1081         }
1082         base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1083
1084         /* last 6 bits, all from bin [2] */
1085         base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1086         bin += 3;
1087         len -= 3;
1088     }
1089     base64[n] = 0;
1090     return n;
1091 }
1092
1093 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1094                ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1095                ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1096                ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1097 static const signed char HTTP_Base64Dec[256] =
1098 {
1099     CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1100     CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1101     CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1102     CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1103     CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1104     CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1105     CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1106     CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1107     CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1108     CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1109     CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1110     CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1111     CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1112     CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1113     CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1114     CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1115     CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1116     CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1117     CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1118     CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1119     CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1120     CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1121     CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1122     CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1123     CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1124     CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1125 };
1126 #undef CH
1127
1128 /***********************************************************************
1129  *  HTTP_DecodeBase64
1130  */
1131 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1132 {
1133     unsigned int n = 0;
1134
1135     while(*base64)
1136     {
1137         signed char in[4];
1138
1139         if (base64[0] > ARRAYSIZE(HTTP_Base64Dec) ||
1140             ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1141             base64[1] > ARRAYSIZE(HTTP_Base64Dec) ||
1142             ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1143         {
1144             WARN("invalid base64: %s\n", debugstr_w(base64));
1145             return 0;
1146         }
1147         if (bin)
1148             bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1149         n++;
1150
1151         if ((base64[2] == '=') && (base64[3] == '='))
1152             break;
1153         if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1154             ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1155         {
1156             WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1157             return 0;
1158         }
1159         if (bin)
1160             bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1161         n++;
1162
1163         if (base64[3] == '=')
1164             break;
1165         if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1166             ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1167         {
1168             WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1169             return 0;
1170         }
1171         if (bin)
1172             bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1173         n++;
1174
1175         base64 += 4;
1176     }
1177
1178     return n;
1179 }
1180
1181 /***********************************************************************
1182  *  HTTP_InsertAuthorizationForHeader
1183  *
1184  *   Insert or delete the authorization field in the request header.
1185  */
1186 static BOOL HTTP_InsertAuthorizationForHeader( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1187 {
1188     WCHAR *authorization = NULL;
1189
1190     if (pAuthInfo && pAuthInfo->auth_data_len)
1191     {
1192         static const WCHAR wszSpace[] = {' ',0};
1193         unsigned int len;
1194
1195         /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1196         len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1197         authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1198         if (!authorization)
1199             return FALSE;
1200
1201         strcpyW(authorization, pAuthInfo->scheme);
1202         strcatW(authorization, wszSpace);
1203         HTTP_EncodeBase64(pAuthInfo->auth_data,
1204                           pAuthInfo->auth_data_len,
1205                           authorization+strlenW(authorization));
1206
1207         /* clear the data as it isn't valid now that it has been sent to the
1208          * server */
1209         HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1210         pAuthInfo->auth_data = NULL;
1211         pAuthInfo->auth_data_len = 0;
1212     }
1213
1214     TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1215
1216     HTTP_ProcessHeader(lpwhr, header, authorization,
1217                        HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1218
1219     HeapFree(GetProcessHeap(), 0, authorization);
1220
1221     return TRUE;
1222 }
1223
1224 /***********************************************************************
1225  *  HTTP_InsertAuthorization
1226  *
1227  *   Insert the authorization field in the request header
1228  */
1229 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr )
1230 {
1231     return HTTP_InsertAuthorizationForHeader(lpwhr, lpwhr->pAuthInfo, szAuthorization);
1232 }
1233
1234 /***********************************************************************
1235  *  HTTP_InsertProxyAuthorization
1236  *
1237  *   Insert the proxy authorization field in the request header
1238  */
1239 static BOOL HTTP_InsertProxyAuthorization( LPWININETHTTPREQW lpwhr )
1240 {
1241     return HTTP_InsertAuthorizationForHeader(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
1242 }
1243
1244 /***********************************************************************
1245  *           HTTP_DealWithProxy
1246  */
1247 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1248     LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1249 {
1250     WCHAR buf[MAXHOSTNAME];
1251     WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1252     WCHAR* url;
1253     static WCHAR szNul[] = { 0 };
1254     URL_COMPONENTSW UrlComponents;
1255     static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
1256     static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
1257     static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1258     int len;
1259
1260     memset( &UrlComponents, 0, sizeof UrlComponents );
1261     UrlComponents.dwStructSize = sizeof UrlComponents;
1262     UrlComponents.lpszHostName = buf;
1263     UrlComponents.dwHostNameLength = MAXHOSTNAME;
1264
1265     if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1266                                  hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1267         sprintfW(proxy, szFormat1, hIC->lpszProxy);
1268     else
1269         strcpyW(proxy, hIC->lpszProxy);
1270     if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1271         return FALSE;
1272     if( UrlComponents.dwHostNameLength == 0 )
1273         return FALSE;
1274
1275     if( !lpwhr->lpszPath )
1276         lpwhr->lpszPath = szNul;
1277     TRACE("server=%s path=%s\n",
1278           debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
1279     /* for constant 15 see above */
1280     len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
1281     url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1282
1283     if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1284         UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1285
1286     sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
1287
1288     if( lpwhr->lpszPath[0] != '/' )
1289         strcatW( url, szSlash );
1290     strcatW(url, lpwhr->lpszPath);
1291     if(lpwhr->lpszPath != szNul)
1292         HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1293     lpwhr->lpszPath = url;
1294
1295     HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1296     lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1297     lpwhs->nServerPort = UrlComponents.nPort;
1298
1299     return TRUE;
1300 }
1301
1302 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1303 {
1304     char szaddr[32];
1305     LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1306
1307     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1308                           INTERNET_STATUS_RESOLVING_NAME,
1309                           lpwhs->lpszServerName,
1310                           strlenW(lpwhs->lpszServerName)+1);
1311
1312     if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1313                     &lpwhs->socketAddress))
1314     {
1315         INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1316         return FALSE;
1317     }
1318
1319     inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1320               szaddr, sizeof(szaddr));
1321     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1322                           INTERNET_STATUS_NAME_RESOLVED,
1323                           szaddr, strlen(szaddr)+1);
1324     return TRUE;
1325 }
1326
1327 /***********************************************************************
1328  *           HTTP_HttpOpenRequestW (internal)
1329  *
1330  * Open a HTTP request handle
1331  *
1332  * RETURNS
1333  *    HINTERNET  a HTTP request handle on success
1334  *    NULL       on failure
1335  *
1336  */
1337 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1338         LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1339         LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1340         DWORD dwFlags, DWORD dwContext)
1341 {
1342     LPWININETAPPINFOW hIC = NULL;
1343     LPWININETHTTPREQW lpwhr;
1344     LPWSTR lpszCookies;
1345     LPWSTR lpszUrl = NULL;
1346     DWORD nCookieSize;
1347     HINTERNET handle = NULL;
1348     static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1349     DWORD len;
1350     LPHTTPHEADERW Host;
1351
1352     TRACE("-->\n");
1353
1354     assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1355     hIC = lpwhs->lpAppInfo;
1356
1357     lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1358     if (NULL == lpwhr)
1359     {
1360         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1361         goto lend;
1362     }
1363     lpwhr->hdr.htype = WH_HHTTPREQ;
1364     lpwhr->hdr.dwFlags = dwFlags;
1365     lpwhr->hdr.dwContext = dwContext;
1366     lpwhr->hdr.dwRefCount = 1;
1367     lpwhr->hdr.close_connection = HTTP_CloseConnection;
1368     lpwhr->hdr.destroy = HTTP_CloseHTTPRequestHandle;
1369     lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1370     lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1371
1372     WININET_AddRef( &lpwhs->hdr );
1373     lpwhr->lpHttpSession = lpwhs;
1374
1375     handle = WININET_AllocHandle( &lpwhr->hdr );
1376     if (NULL == handle)
1377     {
1378         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1379         goto lend;
1380     }
1381
1382     if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1383     {
1384         InternetCloseHandle( handle );
1385         handle = NULL;
1386         goto lend;
1387     }
1388
1389     if (NULL != lpszObjectName && strlenW(lpszObjectName)) {
1390         HRESULT rc;
1391
1392         len = 0;
1393         rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1394         if (rc != E_POINTER)
1395             len = strlenW(lpszObjectName)+1;
1396         lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1397         rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1398                    URL_ESCAPE_SPACES_ONLY);
1399         if (rc)
1400         {
1401             ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1402             strcpyW(lpwhr->lpszPath,lpszObjectName);
1403         }
1404     }
1405
1406     if (NULL != lpszReferrer && strlenW(lpszReferrer))
1407         HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDHDR_FLAG_COALESCE);
1408
1409     if (lpszAcceptTypes)
1410     {
1411         int i;
1412         for (i = 0; lpszAcceptTypes[i]; i++)
1413         {
1414             if (!*lpszAcceptTypes[i]) continue;
1415             HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1416                                HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1417                                HTTP_ADDHDR_FLAG_REQ |
1418                                (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1419         }
1420     }
1421
1422     if (NULL == lpszVerb)
1423     {
1424         static const WCHAR szGet[] = {'G','E','T',0};
1425         lpwhr->lpszVerb = WININET_strdupW(szGet);
1426     }
1427     else if (strlenW(lpszVerb))
1428         lpwhr->lpszVerb = WININET_strdupW(lpszVerb);
1429
1430     if (NULL != lpszReferrer && strlenW(lpszReferrer))
1431     {
1432         WCHAR buf[MAXHOSTNAME];
1433         URL_COMPONENTSW UrlComponents;
1434
1435         memset( &UrlComponents, 0, sizeof UrlComponents );
1436         UrlComponents.dwStructSize = sizeof UrlComponents;
1437         UrlComponents.lpszHostName = buf;
1438         UrlComponents.dwHostNameLength = MAXHOSTNAME;
1439
1440         InternetCrackUrlW(lpszReferrer, 0, 0, &UrlComponents);
1441         if (strlenW(UrlComponents.lpszHostName))
1442             HTTP_ProcessHeader(lpwhr, szHost, UrlComponents.lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1443     }
1444     else
1445         HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1446
1447     if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1448         lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1449                         INTERNET_DEFAULT_HTTPS_PORT :
1450                         INTERNET_DEFAULT_HTTP_PORT);
1451     lpwhs->nHostPort = lpwhs->nServerPort;
1452
1453     if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1454         HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1455
1456     if (hIC->lpszAgent)
1457     {
1458         WCHAR *agent_header;
1459         static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1460
1461         len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1462         agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1463         sprintfW(agent_header, user_agent, hIC->lpszAgent );
1464
1465         HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1466                                HTTP_ADDREQ_FLAG_ADD);
1467         HeapFree(GetProcessHeap(), 0, agent_header);
1468     }
1469
1470     Host = HTTP_GetHeader(lpwhr,szHost);
1471
1472     len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1473     lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1474     sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1475
1476     if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1477         InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1478     {
1479         int cnt = 0;
1480         static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1481         static const WCHAR szcrlf[] = {'\r','\n',0};
1482
1483         lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1484
1485         cnt += sprintfW(lpszCookies, szCookie);
1486         InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1487         strcatW(lpszCookies, szcrlf);
1488
1489         HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1490                                HTTP_ADDREQ_FLAG_ADD);
1491         HeapFree(GetProcessHeap(), 0, lpszCookies);
1492     }
1493     HeapFree(GetProcessHeap(), 0, lpszUrl);
1494
1495
1496     INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1497                           INTERNET_STATUS_HANDLE_CREATED, &handle,
1498                           sizeof(handle));
1499
1500     /*
1501      * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1502      */
1503
1504     if (!HTTP_ResolveName(lpwhr))
1505     {
1506         InternetCloseHandle( handle );
1507         handle = NULL;
1508     }
1509
1510 lend:
1511     if( lpwhr )
1512         WININET_Release( &lpwhr->hdr );
1513
1514     TRACE("<-- %p (%p)\n", handle, lpwhr);
1515     return handle;
1516 }
1517
1518 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1519 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1520 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1521 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1522 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1523 static const WCHAR szAge[] = { 'A','g','e',0 };
1524 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1525 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1526 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1527 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1528 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1529 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1530 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1531 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1532 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1533 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1534 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1535 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 };
1536 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1537 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1538 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1539 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1540 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1541 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1542 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1543 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1544 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1545 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1546 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1547 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1548 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1549 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1550 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1551 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1552 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1553 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1554 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1555 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1556 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1557 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1558 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1559 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1560 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1561 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1562 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 };
1563 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1564 static const WCHAR szURI[] = { 'U','R','I',0 };
1565 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1566 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1567 static const WCHAR szVia[] = { 'V','i','a',0 };
1568 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1569 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1570
1571 static const LPCWSTR header_lookup[] = {
1572     szMime_Version,             /* HTTP_QUERY_MIME_VERSION = 0 */
1573     szContent_Type,             /* HTTP_QUERY_CONTENT_TYPE = 1 */
1574     szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1575     szContent_ID,               /* HTTP_QUERY_CONTENT_ID = 3 */
1576     NULL,                       /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1577     szContent_Length,           /* HTTP_QUERY_CONTENT_LENGTH =  5 */
1578     szContent_Language,         /* HTTP_QUERY_CONTENT_LANGUAGE =  6 */
1579     szAllow,                    /* HTTP_QUERY_ALLOW = 7 */
1580     szPublic,                   /* HTTP_QUERY_PUBLIC = 8 */
1581     szDate,                     /* HTTP_QUERY_DATE = 9 */
1582     szExpires,                  /* HTTP_QUERY_EXPIRES = 10 */
1583     szLast_Modified,            /* HTTP_QUERY_LAST_MODIFIED = 11 */
1584     NULL,                       /* HTTP_QUERY_MESSAGE_ID = 12 */
1585     szURI,                      /* HTTP_QUERY_URI = 13 */
1586     szFrom,                     /* HTTP_QUERY_DERIVED_FROM = 14 */
1587     NULL,                       /* HTTP_QUERY_COST = 15 */
1588     NULL,                       /* HTTP_QUERY_LINK = 16 */
1589     szPragma,                   /* HTTP_QUERY_PRAGMA = 17 */
1590     NULL,                       /* HTTP_QUERY_VERSION = 18 */
1591     szStatus,                   /* HTTP_QUERY_STATUS_CODE = 19 */
1592     NULL,                       /* HTTP_QUERY_STATUS_TEXT = 20 */
1593     NULL,                       /* HTTP_QUERY_RAW_HEADERS = 21 */
1594     NULL,                       /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
1595     szConnection,               /* HTTP_QUERY_CONNECTION = 23 */
1596     szAccept,                   /* HTTP_QUERY_ACCEPT = 24 */
1597     szAccept_Charset,           /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
1598     szAccept_Encoding,          /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
1599     szAccept_Language,          /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
1600     szAuthorization,            /* HTTP_QUERY_AUTHORIZATION = 28 */
1601     szContent_Encoding,         /* HTTP_QUERY_CONTENT_ENCODING = 29 */
1602     NULL,                       /* HTTP_QUERY_FORWARDED = 30 */
1603     NULL,                       /* HTTP_QUERY_FROM = 31 */
1604     szIf_Modified_Since,        /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
1605     szLocation,                 /* HTTP_QUERY_LOCATION = 33 */
1606     NULL,                       /* HTTP_QUERY_ORIG_URI = 34 */
1607     szReferer,                  /* HTTP_QUERY_REFERER = 35 */
1608     szRetry_After,              /* HTTP_QUERY_RETRY_AFTER = 36 */
1609     szServer,                   /* HTTP_QUERY_SERVER = 37 */
1610     NULL,                       /* HTTP_TITLE = 38 */
1611     szUser_Agent,               /* HTTP_QUERY_USER_AGENT = 39 */
1612     szWWW_Authenticate,         /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
1613     szProxy_Authenticate,       /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
1614     szAccept_Ranges,            /* HTTP_QUERY_ACCEPT_RANGES = 42 */
1615     szSet_Cookie,               /* HTTP_QUERY_SET_COOKIE = 43 */
1616     szCookie,                   /* HTTP_QUERY_COOKIE = 44 */
1617     NULL,                       /* HTTP_QUERY_REQUEST_METHOD = 45 */
1618     NULL,                       /* HTTP_QUERY_REFRESH = 46 */
1619     NULL,                       /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
1620     szAge,                      /* HTTP_QUERY_AGE = 48 */
1621     szCache_Control,            /* HTTP_QUERY_CACHE_CONTROL = 49 */
1622     szContent_Base,             /* HTTP_QUERY_CONTENT_BASE = 50 */
1623     szContent_Location,         /* HTTP_QUERY_CONTENT_LOCATION = 51 */
1624     szContent_MD5,              /* HTTP_QUERY_CONTENT_MD5 = 52 */
1625     szContent_Range,            /* HTTP_QUERY_CONTENT_RANGE = 53 */
1626     szETag,                     /* HTTP_QUERY_ETAG = 54 */
1627     szHost,                     /* HTTP_QUERY_HOST = 55 */
1628     szIf_Match,                 /* HTTP_QUERY_IF_MATCH = 56 */
1629     szIf_None_Match,            /* HTTP_QUERY_IF_NONE_MATCH = 57 */
1630     szIf_Range,                 /* HTTP_QUERY_IF_RANGE = 58 */
1631     szIf_Unmodified_Since,      /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
1632     szMax_Forwards,             /* HTTP_QUERY_MAX_FORWARDS = 60 */
1633     szProxy_Authorization,      /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
1634     szRange,                    /* HTTP_QUERY_RANGE = 62 */
1635     szTransfer_Encoding,        /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
1636     szUpgrade,                  /* HTTP_QUERY_UPGRADE = 64 */
1637     szVary,                     /* HTTP_QUERY_VARY = 65 */
1638     szVia,                      /* HTTP_QUERY_VIA = 66 */
1639     szWarning,                  /* HTTP_QUERY_WARNING = 67 */
1640     szExpect,                   /* HTTP_QUERY_EXPECT = 68 */
1641     szProxy_Connection,         /* HTTP_QUERY_PROXY_CONNECTION = 69 */
1642     szUnless_Modified_Since,    /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
1643 };
1644
1645 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
1646
1647 /***********************************************************************
1648  *           HTTP_HttpQueryInfoW (internal)
1649  */
1650 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1651         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1652 {
1653     LPHTTPHEADERW lphttpHdr = NULL;
1654     BOOL bSuccess = FALSE;
1655     BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1656     INT requested_index = lpdwIndex ? *lpdwIndex : 0;
1657     INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
1658     INT index = -1;
1659
1660     /* Find requested header structure */
1661     switch (level)
1662     {
1663     case HTTP_QUERY_CUSTOM:
1664         index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
1665         break;
1666
1667     case HTTP_QUERY_RAW_HEADERS_CRLF:
1668         {
1669             LPWSTR headers;
1670             DWORD len;
1671             BOOL ret;
1672
1673             if (request_only)
1674                 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, FALSE);
1675             else
1676                 headers = lpwhr->lpszRawHeaders;
1677
1678             len = strlenW(headers);
1679             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1680             {
1681                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1682                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1683                 ret = FALSE;
1684             } else
1685             {
1686                 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
1687                 *lpdwBufferLength = len * sizeof(WCHAR);
1688
1689                 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1690                 ret = TRUE;
1691             }
1692
1693             if (request_only)
1694                 HeapFree(GetProcessHeap(), 0, headers);
1695             return ret;
1696         }
1697     case HTTP_QUERY_RAW_HEADERS:
1698         {
1699             static const WCHAR szCrLf[] = {'\r','\n',0};
1700             LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1701             DWORD i, size = 0;
1702             LPWSTR pszString = (WCHAR*)lpBuffer;
1703
1704             for (i = 0; ppszRawHeaderLines[i]; i++)
1705                 size += strlenW(ppszRawHeaderLines[i]) + 1;
1706
1707             if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1708             {
1709                 HTTP_FreeTokens(ppszRawHeaderLines);
1710                 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1711                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1712                 return FALSE;
1713             }
1714
1715             for (i = 0; ppszRawHeaderLines[i]; i++)
1716             {
1717                 DWORD len = strlenW(ppszRawHeaderLines[i]);
1718                 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1719                 pszString += len+1;
1720             }
1721             *pszString = '\0';
1722
1723             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1724
1725             *lpdwBufferLength = size * sizeof(WCHAR);
1726             HTTP_FreeTokens(ppszRawHeaderLines);
1727
1728             return TRUE;
1729         }
1730     case HTTP_QUERY_STATUS_TEXT:
1731         if (lpwhr->lpszStatusText)
1732         {
1733             DWORD len = strlenW(lpwhr->lpszStatusText);
1734             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1735             {
1736                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1737                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1738                 return FALSE;
1739             }
1740             memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1741             *lpdwBufferLength = len * sizeof(WCHAR);
1742
1743             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1744
1745             return TRUE;
1746         }
1747         break;
1748     case HTTP_QUERY_VERSION:
1749         if (lpwhr->lpszVersion)
1750         {
1751             DWORD len = strlenW(lpwhr->lpszVersion);
1752             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1753             {
1754                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1755                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1756                 return FALSE;
1757             }
1758             memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
1759             *lpdwBufferLength = len * sizeof(WCHAR);
1760
1761             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1762
1763             return TRUE;
1764         }
1765         break;
1766     default:
1767         assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
1768
1769         if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
1770             index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
1771                                               requested_index,request_only);
1772     }
1773
1774     if (index >= 0)
1775         lphttpHdr = &lpwhr->pCustHeaders[index];
1776
1777     /* Ensure header satisifies requested attributes */
1778     if (!lphttpHdr ||
1779         ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
1780          (~lphttpHdr->wFlags & HDR_ISREQUEST)))
1781     {
1782         INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1783         return bSuccess;
1784     }
1785
1786     if (lpdwIndex)
1787         (*lpdwIndex)++;
1788
1789     /* coalesce value to reuqested type */
1790     if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
1791     {
1792         *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
1793         bSuccess = TRUE;
1794
1795         TRACE(" returning number : %d\n", *(int *)lpBuffer);
1796     }
1797     else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
1798     {
1799         time_t tmpTime;
1800         struct tm tmpTM;
1801         SYSTEMTIME *STHook;
1802
1803         tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
1804
1805         tmpTM = *gmtime(&tmpTime);
1806         STHook = (SYSTEMTIME *) lpBuffer;
1807         if(STHook==NULL)
1808             return bSuccess;
1809
1810         STHook->wDay = tmpTM.tm_mday;
1811         STHook->wHour = tmpTM.tm_hour;
1812         STHook->wMilliseconds = 0;
1813         STHook->wMinute = tmpTM.tm_min;
1814         STHook->wDayOfWeek = tmpTM.tm_wday;
1815         STHook->wMonth = tmpTM.tm_mon + 1;
1816         STHook->wSecond = tmpTM.tm_sec;
1817         STHook->wYear = tmpTM.tm_year;
1818         
1819         bSuccess = TRUE;
1820         
1821         TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n", 
1822               STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
1823               STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
1824     }
1825     else if (lphttpHdr->lpszValue)
1826     {
1827         DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
1828
1829         if (len > *lpdwBufferLength)
1830         {
1831             *lpdwBufferLength = len;
1832             INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1833             return bSuccess;
1834         }
1835
1836         memcpy(lpBuffer, lphttpHdr->lpszValue, len);
1837         *lpdwBufferLength = len - sizeof(WCHAR);
1838         bSuccess = TRUE;
1839
1840         TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
1841     }
1842     return bSuccess;
1843 }
1844
1845 /***********************************************************************
1846  *           HttpQueryInfoW (WININET.@)
1847  *
1848  * Queries for information about an HTTP request
1849  *
1850  * RETURNS
1851  *    TRUE  on success
1852  *    FALSE on failure
1853  *
1854  */
1855 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1856         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1857 {
1858     BOOL bSuccess = FALSE;
1859     LPWININETHTTPREQW lpwhr;
1860
1861     if (TRACE_ON(wininet)) {
1862 #define FE(x) { x, #x }
1863         static const wininet_flag_info query_flags[] = {
1864             FE(HTTP_QUERY_MIME_VERSION),
1865             FE(HTTP_QUERY_CONTENT_TYPE),
1866             FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
1867             FE(HTTP_QUERY_CONTENT_ID),
1868             FE(HTTP_QUERY_CONTENT_DESCRIPTION),
1869             FE(HTTP_QUERY_CONTENT_LENGTH),
1870             FE(HTTP_QUERY_CONTENT_LANGUAGE),
1871             FE(HTTP_QUERY_ALLOW),
1872             FE(HTTP_QUERY_PUBLIC),
1873             FE(HTTP_QUERY_DATE),
1874             FE(HTTP_QUERY_EXPIRES),
1875             FE(HTTP_QUERY_LAST_MODIFIED),
1876             FE(HTTP_QUERY_MESSAGE_ID),
1877             FE(HTTP_QUERY_URI),
1878             FE(HTTP_QUERY_DERIVED_FROM),
1879             FE(HTTP_QUERY_COST),
1880             FE(HTTP_QUERY_LINK),
1881             FE(HTTP_QUERY_PRAGMA),
1882             FE(HTTP_QUERY_VERSION),
1883             FE(HTTP_QUERY_STATUS_CODE),
1884             FE(HTTP_QUERY_STATUS_TEXT),
1885             FE(HTTP_QUERY_RAW_HEADERS),
1886             FE(HTTP_QUERY_RAW_HEADERS_CRLF),
1887             FE(HTTP_QUERY_CONNECTION),
1888             FE(HTTP_QUERY_ACCEPT),
1889             FE(HTTP_QUERY_ACCEPT_CHARSET),
1890             FE(HTTP_QUERY_ACCEPT_ENCODING),
1891             FE(HTTP_QUERY_ACCEPT_LANGUAGE),
1892             FE(HTTP_QUERY_AUTHORIZATION),
1893             FE(HTTP_QUERY_CONTENT_ENCODING),
1894             FE(HTTP_QUERY_FORWARDED),
1895             FE(HTTP_QUERY_FROM),
1896             FE(HTTP_QUERY_IF_MODIFIED_SINCE),
1897             FE(HTTP_QUERY_LOCATION),
1898             FE(HTTP_QUERY_ORIG_URI),
1899             FE(HTTP_QUERY_REFERER),
1900             FE(HTTP_QUERY_RETRY_AFTER),
1901             FE(HTTP_QUERY_SERVER),
1902             FE(HTTP_QUERY_TITLE),
1903             FE(HTTP_QUERY_USER_AGENT),
1904             FE(HTTP_QUERY_WWW_AUTHENTICATE),
1905             FE(HTTP_QUERY_PROXY_AUTHENTICATE),
1906             FE(HTTP_QUERY_ACCEPT_RANGES),
1907         FE(HTTP_QUERY_SET_COOKIE),
1908         FE(HTTP_QUERY_COOKIE),
1909             FE(HTTP_QUERY_REQUEST_METHOD),
1910             FE(HTTP_QUERY_REFRESH),
1911             FE(HTTP_QUERY_CONTENT_DISPOSITION),
1912             FE(HTTP_QUERY_AGE),
1913             FE(HTTP_QUERY_CACHE_CONTROL),
1914             FE(HTTP_QUERY_CONTENT_BASE),
1915             FE(HTTP_QUERY_CONTENT_LOCATION),
1916             FE(HTTP_QUERY_CONTENT_MD5),
1917             FE(HTTP_QUERY_CONTENT_RANGE),
1918             FE(HTTP_QUERY_ETAG),
1919             FE(HTTP_QUERY_HOST),
1920             FE(HTTP_QUERY_IF_MATCH),
1921             FE(HTTP_QUERY_IF_NONE_MATCH),
1922             FE(HTTP_QUERY_IF_RANGE),
1923             FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
1924             FE(HTTP_QUERY_MAX_FORWARDS),
1925             FE(HTTP_QUERY_PROXY_AUTHORIZATION),
1926             FE(HTTP_QUERY_RANGE),
1927             FE(HTTP_QUERY_TRANSFER_ENCODING),
1928             FE(HTTP_QUERY_UPGRADE),
1929             FE(HTTP_QUERY_VARY),
1930             FE(HTTP_QUERY_VIA),
1931             FE(HTTP_QUERY_WARNING),
1932             FE(HTTP_QUERY_CUSTOM)
1933         };
1934         static const wininet_flag_info modifier_flags[] = {
1935             FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
1936             FE(HTTP_QUERY_FLAG_SYSTEMTIME),
1937             FE(HTTP_QUERY_FLAG_NUMBER),
1938             FE(HTTP_QUERY_FLAG_COALESCE)
1939         };
1940 #undef FE
1941         DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
1942         DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
1943         DWORD i;
1944
1945         TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
1946         TRACE("  Attribute:");
1947         for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
1948             if (query_flags[i].val == info) {
1949                 TRACE(" %s", query_flags[i].name);
1950                 break;
1951             }
1952         }
1953         if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
1954             TRACE(" Unknown (%08x)", info);
1955         }
1956
1957         TRACE(" Modifier:");
1958         for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
1959             if (modifier_flags[i].val & info_mod) {
1960                 TRACE(" %s", modifier_flags[i].name);
1961                 info_mod &= ~ modifier_flags[i].val;
1962             }
1963         }
1964         
1965         if (info_mod) {
1966             TRACE(" Unknown (%08x)", info_mod);
1967         }
1968         TRACE("\n");
1969     }
1970     
1971     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1972     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
1973     {
1974         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1975         goto lend;
1976     }
1977
1978     if (lpBuffer == NULL)
1979         *lpdwBufferLength = 0;
1980     bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
1981                                     lpBuffer, lpdwBufferLength, lpdwIndex);
1982
1983 lend:
1984     if( lpwhr )
1985          WININET_Release( &lpwhr->hdr );
1986
1987     TRACE("%d <--\n", bSuccess);
1988     return bSuccess;
1989 }
1990
1991 /***********************************************************************
1992  *           HttpQueryInfoA (WININET.@)
1993  *
1994  * Queries for information about an HTTP request
1995  *
1996  * RETURNS
1997  *    TRUE  on success
1998  *    FALSE on failure
1999  *
2000  */
2001 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2002         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2003 {
2004     BOOL result;
2005     DWORD len;
2006     WCHAR* bufferW;
2007
2008     if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2009        (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2010     {
2011         return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2012                                lpdwBufferLength, lpdwIndex );
2013     }
2014
2015     if (lpBuffer)
2016     {
2017         len = (*lpdwBufferLength)*sizeof(WCHAR);
2018         bufferW = HeapAlloc( GetProcessHeap(), 0, len );
2019         /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2020         if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2021             MultiByteToWideChar(CP_ACP,0,lpBuffer,-1,bufferW,len);
2022     } else
2023     {
2024         bufferW = NULL;
2025         len = 0;
2026     }
2027
2028     result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2029                            &len, lpdwIndex );
2030     if( result )
2031     {
2032         len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2033                                      lpBuffer, *lpdwBufferLength, NULL, NULL );
2034         *lpdwBufferLength = len - 1;
2035
2036         TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2037     }
2038     else
2039         /* since the strings being returned from HttpQueryInfoW should be
2040          * only ASCII characters, it is reasonable to assume that all of
2041          * the Unicode characters can be reduced to a single byte */
2042         *lpdwBufferLength = len / sizeof(WCHAR);
2043
2044     HeapFree(GetProcessHeap(), 0, bufferW );
2045
2046     return result;
2047 }
2048
2049 /***********************************************************************
2050  *           HttpSendRequestExA (WININET.@)
2051  *
2052  * Sends the specified request to the HTTP server and allows chunked
2053  * transfers.
2054  *
2055  * RETURNS
2056  *  Success: TRUE
2057  *  Failure: FALSE, call GetLastError() for more information.
2058  */
2059 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2060                                LPINTERNET_BUFFERSA lpBuffersIn,
2061                                LPINTERNET_BUFFERSA lpBuffersOut,
2062                                DWORD dwFlags, DWORD dwContext)
2063 {
2064     INTERNET_BUFFERSW BuffersInW;
2065     BOOL rc = FALSE;
2066     DWORD headerlen;
2067     LPWSTR header = NULL;
2068
2069     TRACE("(%p, %p, %p, %08x, %08x): stub\n", hRequest, lpBuffersIn,
2070             lpBuffersOut, dwFlags, dwContext);
2071
2072     if (lpBuffersIn)
2073     {
2074         BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2075         if (lpBuffersIn->lpcszHeader)
2076         {
2077             headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2078                     lpBuffersIn->dwHeadersLength,0,0);
2079             header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2080             if (!(BuffersInW.lpcszHeader = header))
2081             {
2082                 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2083                 return FALSE;
2084             }
2085             BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2086                     lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2087                     header, headerlen);
2088         }
2089         else
2090             BuffersInW.lpcszHeader = NULL;
2091         BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2092         BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2093         BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2094         BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2095         BuffersInW.Next = NULL;
2096     }
2097
2098     rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2099
2100     HeapFree(GetProcessHeap(),0,header);
2101
2102     return rc;
2103 }
2104
2105 /***********************************************************************
2106  *           HttpSendRequestExW (WININET.@)
2107  *
2108  * Sends the specified request to the HTTP server and allows chunked
2109  * transfers
2110  *
2111  * RETURNS
2112  *  Success: TRUE
2113  *  Failure: FALSE, call GetLastError() for more information.
2114  */
2115 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2116                    LPINTERNET_BUFFERSW lpBuffersIn,
2117                    LPINTERNET_BUFFERSW lpBuffersOut,
2118                    DWORD dwFlags, DWORD dwContext)
2119 {
2120     BOOL ret;
2121     LPWININETHTTPREQW lpwhr;
2122     LPWININETHTTPSESSIONW lpwhs;
2123     LPWININETAPPINFOW hIC;
2124
2125     TRACE("(%p, %p, %p, %08x, %08x)\n", hRequest, lpBuffersIn,
2126             lpBuffersOut, dwFlags, dwContext);
2127
2128     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2129
2130     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2131     {
2132         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2133         return FALSE;
2134     }
2135
2136     lpwhs = lpwhr->lpHttpSession;
2137     assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2138     hIC = lpwhs->lpAppInfo;
2139     assert(hIC->hdr.htype == WH_HINIT);
2140
2141     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2142     {
2143         WORKREQUEST workRequest;
2144         struct WORKREQ_HTTPSENDREQUESTW *req;
2145
2146         workRequest.asyncproc = AsyncHttpSendRequestProc;
2147         workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2148         req = &workRequest.u.HttpSendRequestW;
2149         if (lpBuffersIn)
2150         {
2151             if (lpBuffersIn->lpcszHeader)
2152                 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2153                 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2154             else
2155                 req->lpszHeader = NULL;
2156             req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2157             req->lpOptional = lpBuffersIn->lpvBuffer;
2158             req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2159             req->dwContentLength = lpBuffersIn->dwBufferTotal;
2160         }
2161         else
2162         {
2163             req->lpszHeader = NULL;
2164             req->dwHeaderLength = 0;
2165             req->lpOptional = NULL;
2166             req->dwOptionalLength = 0;
2167             req->dwContentLength = 0;
2168         }
2169
2170         req->bEndRequest = FALSE;
2171
2172         INTERNET_AsyncCall(&workRequest);
2173         /*
2174          * This is from windows.
2175          */
2176         INTERNET_SetLastError(ERROR_IO_PENDING);
2177         ret = FALSE;
2178     }
2179     else
2180     {
2181         ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2182                                     lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2183                                     lpBuffersIn->dwBufferTotal, FALSE);
2184     }
2185  
2186     WININET_Release(&lpwhr->hdr);
2187     TRACE("<---\n");
2188     return ret;
2189 }
2190
2191 /***********************************************************************
2192  *           HttpSendRequestW (WININET.@)
2193  *
2194  * Sends the specified request to the HTTP server
2195  *
2196  * RETURNS
2197  *    TRUE  on success
2198  *    FALSE on failure
2199  *
2200  */
2201 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2202         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2203 {
2204     LPWININETHTTPREQW lpwhr;
2205     LPWININETHTTPSESSIONW lpwhs = NULL;
2206     LPWININETAPPINFOW hIC = NULL;
2207     BOOL r;
2208
2209     TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2210             debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2211
2212     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2213     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2214     {
2215         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2216         r = FALSE;
2217         goto lend;
2218     }
2219
2220     lpwhs = lpwhr->lpHttpSession;
2221     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
2222     {
2223         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2224         r = FALSE;
2225         goto lend;
2226     }
2227
2228     hIC = lpwhs->lpAppInfo;
2229     if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT)
2230     {
2231         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2232         r = FALSE;
2233         goto lend;
2234     }
2235
2236     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2237     {
2238         WORKREQUEST workRequest;
2239         struct WORKREQ_HTTPSENDREQUESTW *req;
2240
2241         workRequest.asyncproc = AsyncHttpSendRequestProc;
2242         workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2243         req = &workRequest.u.HttpSendRequestW;
2244         if (lpszHeaders)
2245         {
2246             req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2247             memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2248         }
2249         else
2250             req->lpszHeader = 0;
2251         req->dwHeaderLength = dwHeaderLength;
2252         req->lpOptional = lpOptional;
2253         req->dwOptionalLength = dwOptionalLength;
2254         req->dwContentLength = dwOptionalLength;
2255         req->bEndRequest = TRUE;
2256
2257         INTERNET_AsyncCall(&workRequest);
2258         /*
2259          * This is from windows.
2260          */
2261         INTERNET_SetLastError(ERROR_IO_PENDING);
2262         r = FALSE;
2263     }
2264     else
2265     {
2266         r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2267                 dwHeaderLength, lpOptional, dwOptionalLength,
2268                 dwOptionalLength, TRUE);
2269     }
2270 lend:
2271     if( lpwhr )
2272         WININET_Release( &lpwhr->hdr );
2273     return r;
2274 }
2275
2276 /***********************************************************************
2277  *           HttpSendRequestA (WININET.@)
2278  *
2279  * Sends the specified request to the HTTP server
2280  *
2281  * RETURNS
2282  *    TRUE  on success
2283  *    FALSE on failure
2284  *
2285  */
2286 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2287         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2288 {
2289     BOOL result;
2290     LPWSTR szHeaders=NULL;
2291     DWORD nLen=dwHeaderLength;
2292     if(lpszHeaders!=NULL)
2293     {
2294         nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2295         szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2296         MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2297     }
2298     result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2299     HeapFree(GetProcessHeap(),0,szHeaders);
2300     return result;
2301 }
2302
2303 /***********************************************************************
2304  *           HTTP_HandleRedirect (internal)
2305  */
2306 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2307 {
2308     LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2309     LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2310     WCHAR path[2048];
2311
2312     if(lpszUrl[0]=='/')
2313     {
2314         /* if it's an absolute path, keep the same session info */
2315         lstrcpynW(path, lpszUrl, 2048);
2316     }
2317     else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2318     {
2319         TRACE("Redirect through proxy\n");
2320         lstrcpynW(path, lpszUrl, 2048);
2321     }
2322     else
2323     {
2324         URL_COMPONENTSW urlComponents;
2325         WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2326         static WCHAR szHttp[] = {'h','t','t','p',0};
2327         static WCHAR szHttps[] = {'h','t','t','p','s',0};
2328         DWORD url_length = 0;
2329         LPWSTR orig_url;
2330         LPWSTR combined_url;
2331
2332         urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2333         urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2334         urlComponents.dwSchemeLength = 0;
2335         urlComponents.lpszHostName = lpwhs->lpszHostName;
2336         urlComponents.dwHostNameLength = 0;
2337         urlComponents.nPort = lpwhs->nHostPort;
2338         urlComponents.lpszUserName = lpwhs->lpszUserName;
2339         urlComponents.dwUserNameLength = 0;
2340         urlComponents.lpszPassword = NULL;
2341         urlComponents.dwPasswordLength = 0;
2342         urlComponents.lpszUrlPath = lpwhr->lpszPath;
2343         urlComponents.dwUrlPathLength = 0;
2344         urlComponents.lpszExtraInfo = NULL;
2345         urlComponents.dwExtraInfoLength = 0;
2346
2347         if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2348             (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2349             return FALSE;
2350
2351         orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2352
2353         /* convert from bytes to characters */
2354         url_length = url_length / sizeof(WCHAR) - 1;
2355         if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2356         {
2357             HeapFree(GetProcessHeap(), 0, orig_url);
2358             return FALSE;
2359         }
2360
2361         url_length = 0;
2362         if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2363             (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2364         {
2365             HeapFree(GetProcessHeap(), 0, orig_url);
2366             return FALSE;
2367         }
2368         combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2369
2370         if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2371         {
2372             HeapFree(GetProcessHeap(), 0, orig_url);
2373             HeapFree(GetProcessHeap(), 0, combined_url);
2374             return FALSE;
2375         }
2376         HeapFree(GetProcessHeap(), 0, orig_url);
2377
2378         userName[0] = 0;
2379         hostName[0] = 0;
2380         protocol[0] = 0;
2381
2382         urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2383         urlComponents.lpszScheme = protocol;
2384         urlComponents.dwSchemeLength = 32;
2385         urlComponents.lpszHostName = hostName;
2386         urlComponents.dwHostNameLength = MAXHOSTNAME;
2387         urlComponents.lpszUserName = userName;
2388         urlComponents.dwUserNameLength = 1024;
2389         urlComponents.lpszPassword = NULL;
2390         urlComponents.dwPasswordLength = 0;
2391         urlComponents.lpszUrlPath = path;
2392         urlComponents.dwUrlPathLength = 2048;
2393         urlComponents.lpszExtraInfo = NULL;
2394         urlComponents.dwExtraInfoLength = 0;
2395         if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2396         {
2397             HeapFree(GetProcessHeap(), 0, combined_url);
2398             return FALSE;
2399         }
2400         HeapFree(GetProcessHeap(), 0, combined_url);
2401
2402         if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2403             (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2404         {
2405             TRACE("redirect from secure page to non-secure page\n");
2406             /* FIXME: warn about from secure redirect to non-secure page */
2407             lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2408         }
2409         if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2410             !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2411         {
2412             TRACE("redirect from non-secure page to secure page\n");
2413             /* FIXME: notify about redirect to secure page */
2414             lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2415         }
2416
2417         if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2418         {
2419             if (lstrlenW(protocol)>4) /*https*/
2420                 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2421             else /*http*/
2422                 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2423         }
2424
2425 #if 0
2426         /*
2427          * This upsets redirects to binary files on sourceforge.net 
2428          * and gives an html page instead of the target file
2429          * Examination of the HTTP request sent by native wininet.dll
2430          * reveals that it doesn't send a referrer in that case.
2431          * Maybe there's a flag that enables this, or maybe a referrer
2432          * shouldn't be added in case of a redirect.
2433          */
2434
2435         /* consider the current host as the referrer */
2436         if (NULL != lpwhs->lpszServerName && strlenW(lpwhs->lpszServerName))
2437             HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2438                            HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2439                            HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2440 #endif
2441         
2442         HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2443         lpwhs->lpszServerName = WININET_strdupW(hostName);
2444         HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2445         if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2446                 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2447         {
2448             int len;
2449             static const WCHAR fmt[] = {'%','s',':','%','i',0};
2450             len = lstrlenW(hostName);
2451             len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2452             lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2453             sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2454         }
2455         else
2456             lpwhs->lpszHostName = WININET_strdupW(hostName);
2457
2458         HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2459
2460         
2461         HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2462         lpwhs->lpszUserName = NULL;
2463         if (userName[0])
2464             lpwhs->lpszUserName = WININET_strdupW(userName);
2465         lpwhs->nServerPort = urlComponents.nPort;
2466
2467         if (!HTTP_ResolveName(lpwhr))
2468             return FALSE;
2469
2470         NETCON_close(&lpwhr->netConnection);
2471
2472         if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2473             return FALSE;
2474     }
2475
2476     HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2477     lpwhr->lpszPath=NULL;
2478     if (strlenW(path))
2479     {
2480         DWORD needed = 0;
2481         HRESULT rc;
2482
2483         rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2484         if (rc != E_POINTER)
2485             needed = strlenW(path)+1;
2486         lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2487         rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2488                         URL_ESCAPE_SPACES_ONLY);
2489         if (rc)
2490         {
2491             ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2492             strcpyW(lpwhr->lpszPath,path);
2493         }
2494     }
2495
2496     return TRUE;
2497 }
2498
2499 /***********************************************************************
2500  *           HTTP_build_req (internal)
2501  *
2502  *  concatenate all the strings in the request together
2503  */
2504 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2505 {
2506     LPCWSTR *t;
2507     LPWSTR str;
2508
2509     for( t = list; *t ; t++  )
2510         len += strlenW( *t );
2511     len++;
2512
2513     str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2514     *str = 0;
2515
2516     for( t = list; *t ; t++ )
2517         strcatW( str, *t );
2518
2519     return str;
2520 }
2521
2522 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2523 {
2524     LPWSTR lpszPath;
2525     LPWSTR requestString;
2526     INT len;
2527     INT cnt;
2528     INT responseLen;
2529     char *ascii_req;
2530     BOOL ret;
2531     static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2532     static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2533     LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2534
2535     TRACE("\n");
2536
2537     lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2538     sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2539     requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, FALSE );
2540     HeapFree( GetProcessHeap(), 0, lpszPath );
2541
2542     len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2543                                 NULL, 0, NULL, NULL );
2544     len--; /* the nul terminator isn't needed */
2545     ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2546     WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2547                             ascii_req, len, NULL, NULL );
2548     HeapFree( GetProcessHeap(), 0, requestString );
2549
2550     TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2551
2552     ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2553     HeapFree( GetProcessHeap(), 0, ascii_req );
2554     if (!ret || cnt < 0)
2555         return FALSE;
2556
2557     responseLen = HTTP_GetResponseHeaders( lpwhr );
2558     if (!responseLen)
2559         return FALSE;
2560
2561     return TRUE;
2562 }
2563
2564 /***********************************************************************
2565  *           HTTP_HttpSendRequestW (internal)
2566  *
2567  * Sends the specified request to the HTTP server
2568  *
2569  * RETURNS
2570  *    TRUE  on success
2571  *    FALSE on failure
2572  *
2573  */
2574 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2575         DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2576         DWORD dwContentLength, BOOL bEndRequest)
2577 {
2578     INT cnt;
2579     BOOL bSuccess = FALSE;
2580     LPWSTR requestString = NULL;
2581     INT responseLen;
2582     BOOL loop_next;
2583     INTERNET_ASYNC_RESULT iar;
2584     static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
2585
2586     TRACE("--> %p\n", lpwhr);
2587
2588     assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2589
2590     /* Clear any error information */
2591     INTERNET_SetLastError(0);
2592
2593     HTTP_FixVerb(lpwhr);
2594     
2595     /* if we are using optional stuff, we must add the fixed header of that option length */
2596     if (dwContentLength > 0)
2597     {
2598         static const WCHAR szContentLength[] = {
2599             'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0};
2600         WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \n\r */ + 20 /* int */ ];
2601         sprintfW(contentLengthStr, szContentLength, dwContentLength);
2602         HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L,
2603                 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2604     }
2605
2606     do
2607     {
2608         DWORD len;
2609         char *ascii_req;
2610
2611         loop_next = FALSE;
2612
2613         /* like native, just in case the caller forgot to call InternetReadFile
2614          * for all the data */
2615         HTTP_DrainContent(lpwhr);
2616         lpwhr->dwContentRead = 0;
2617
2618         if (TRACE_ON(wininet))
2619         {
2620             LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
2621             TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2622         }
2623
2624         HTTP_FixURL(lpwhr);
2625         HTTP_ProcessHeader(lpwhr, szConnection,
2626                            lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
2627                            HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
2628
2629         HTTP_InsertAuthorization(lpwhr);
2630         HTTP_InsertProxyAuthorization(lpwhr);
2631
2632         /* add the headers the caller supplied */
2633         if( lpszHeaders && dwHeaderLength )
2634         {
2635             HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2636                         HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2637         }
2638
2639         requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, FALSE);
2640  
2641         TRACE("Request header -> %s\n", debugstr_w(requestString) );
2642
2643         /* Send the request and store the results */
2644         if (!HTTP_OpenConnection(lpwhr))
2645             goto lend;
2646
2647         /* send the request as ASCII, tack on the optional data */
2648         if( !lpOptional )
2649             dwOptionalLength = 0;
2650         len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2651                                    NULL, 0, NULL, NULL );
2652         ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2653         WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2654                              ascii_req, len, NULL, NULL );
2655         if( lpOptional )
2656             memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2657         len = (len + dwOptionalLength - 1);
2658         ascii_req[len] = 0;
2659         TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2660
2661         INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2662                               INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2663
2664         NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2665         HeapFree( GetProcessHeap(), 0, ascii_req );
2666
2667         INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2668                               INTERNET_STATUS_REQUEST_SENT,
2669                               &len, sizeof(DWORD));
2670
2671         if (bEndRequest)
2672         {
2673             DWORD dwBufferSize;
2674             DWORD dwStatusCode;
2675
2676             INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2677                                 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2678     
2679             if (cnt < 0)
2680                 goto lend;
2681     
2682             responseLen = HTTP_GetResponseHeaders(lpwhr);
2683             if (responseLen)
2684                 bSuccess = TRUE;
2685     
2686             INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2687                                 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2688                                 sizeof(DWORD));
2689
2690             HTTP_ProcessHeaders(lpwhr);
2691
2692             dwBufferSize = sizeof(lpwhr->dwContentLength);
2693             if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2694                                      &lpwhr->dwContentLength,&dwBufferSize,NULL))
2695                 lpwhr->dwContentLength = -1;
2696
2697             if (lpwhr->dwContentLength == 0)
2698                 HTTP_FinishedReading(lpwhr);
2699
2700             dwBufferSize = sizeof(dwStatusCode);
2701             if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
2702                                      &dwStatusCode,&dwBufferSize,NULL))
2703                 dwStatusCode = 0;
2704
2705             if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
2706             {
2707                 WCHAR szNewLocation[2048];
2708                 dwBufferSize=sizeof(szNewLocation);
2709                 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
2710                     HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
2711                 {
2712                     HTTP_DrainContent(lpwhr);
2713                     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2714                                           INTERNET_STATUS_REDIRECT, szNewLocation,
2715                                           dwBufferSize);
2716                     bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
2717                     if (bSuccess)
2718                     {
2719                         HeapFree(GetProcessHeap(), 0, requestString);
2720                         loop_next = TRUE;
2721                     }
2722                 }
2723             }
2724             if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
2725             {
2726                 WCHAR szAuthValue[2048];
2727                 dwBufferSize=2048;
2728                 if (dwStatusCode == HTTP_STATUS_DENIED)
2729                 {
2730                     DWORD dwIndex = 0;
2731                     while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2732                     {
2733                         if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2734                                                  &lpwhr->pAuthInfo,
2735                                                  lpwhr->lpHttpSession->lpszUserName,
2736                                                  lpwhr->lpHttpSession->lpszPassword))
2737                         {
2738                             loop_next = TRUE;
2739                             break;
2740                         }
2741                     }
2742                 }
2743                 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
2744                 {
2745                     DWORD dwIndex = 0;
2746                     while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2747                     {
2748                         if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2749                                                  &lpwhr->pProxyAuthInfo,
2750                                                  lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
2751                                                  lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
2752                         {
2753                             loop_next = TRUE;
2754                             break;
2755                         }
2756                     }
2757                 }
2758             }
2759         }
2760         else
2761             bSuccess = TRUE;
2762     }
2763     while (loop_next);
2764
2765 lend:
2766
2767     HeapFree(GetProcessHeap(), 0, requestString);
2768
2769     /* TODO: send notification for P3P header */
2770
2771     iar.dwResult = (DWORD)bSuccess;
2772     iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2773
2774     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2775                           INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2776                           sizeof(INTERNET_ASYNC_RESULT));
2777
2778     TRACE("<--\n");
2779     return bSuccess;
2780 }
2781
2782 /***********************************************************************
2783  *           HTTP_Connect  (internal)
2784  *
2785  * Create http session handle
2786  *
2787  * RETURNS
2788  *   HINTERNET a session handle on success
2789  *   NULL on failure
2790  *
2791  */
2792 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
2793         INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2794         LPCWSTR lpszPassword, DWORD dwFlags, DWORD dwContext,
2795         DWORD dwInternalFlags)
2796 {
2797     BOOL bSuccess = FALSE;
2798     LPWININETHTTPSESSIONW lpwhs = NULL;
2799     HINTERNET handle = NULL;
2800
2801     TRACE("-->\n");
2802
2803     assert( hIC->hdr.htype == WH_HINIT );
2804
2805     lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
2806     if (NULL == lpwhs)
2807     {
2808         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2809         goto lerror;
2810     }
2811
2812    /*
2813     * According to my tests. The name is not resolved until a request is sent
2814     */
2815
2816     lpwhs->hdr.htype = WH_HHTTPSESSION;
2817     lpwhs->hdr.dwFlags = dwFlags;
2818     lpwhs->hdr.dwContext = dwContext;
2819     lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
2820     lpwhs->hdr.dwRefCount = 1;
2821     lpwhs->hdr.close_connection = NULL;
2822     lpwhs->hdr.destroy = HTTP_CloseHTTPSessionHandle;
2823     lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
2824
2825     WININET_AddRef( &hIC->hdr );
2826     lpwhs->lpAppInfo = hIC;
2827
2828     handle = WININET_AllocHandle( &lpwhs->hdr );
2829     if (NULL == handle)
2830     {
2831         ERR("Failed to alloc handle\n");
2832         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2833         goto lerror;
2834     }
2835
2836     if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
2837         if(strchrW(hIC->lpszProxy, ' '))
2838             FIXME("Several proxies not implemented.\n");
2839         if(hIC->lpszProxyBypass)
2840             FIXME("Proxy bypass is ignored.\n");
2841     }
2842     if (lpszServerName && lpszServerName[0])
2843     {
2844         lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
2845         lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
2846     }
2847     if (lpszUserName && lpszUserName[0])
2848         lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
2849     if (lpszPassword && lpszPassword[0])
2850         lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
2851     lpwhs->nServerPort = nServerPort;
2852     lpwhs->nHostPort = nServerPort;
2853
2854     /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
2855     if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
2856     {
2857         INTERNET_SendCallback(&hIC->hdr, dwContext,
2858                               INTERNET_STATUS_HANDLE_CREATED, &handle,
2859                               sizeof(handle));
2860     }
2861
2862     bSuccess = TRUE;
2863
2864 lerror:
2865     if( lpwhs )
2866         WININET_Release( &lpwhs->hdr );
2867
2868 /*
2869  * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
2870  * windows
2871  */
2872
2873     TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
2874     return handle;
2875 }
2876
2877
2878 /***********************************************************************
2879  *           HTTP_OpenConnection (internal)
2880  *
2881  * Connect to a web server
2882  *
2883  * RETURNS
2884  *
2885  *   TRUE  on success
2886  *   FALSE on failure
2887  */
2888 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
2889 {
2890     BOOL bSuccess = FALSE;
2891     LPWININETHTTPSESSIONW lpwhs;
2892     LPWININETAPPINFOW hIC = NULL;
2893     char szaddr[32];
2894
2895     TRACE("-->\n");
2896
2897
2898     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
2899     {
2900         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2901         goto lend;
2902     }
2903
2904     if (NETCON_connected(&lpwhr->netConnection))
2905     {
2906         bSuccess = TRUE;
2907         goto lend;
2908     }
2909
2910     lpwhs = lpwhr->lpHttpSession;
2911
2912     hIC = lpwhs->lpAppInfo;
2913     inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
2914               szaddr, sizeof(szaddr));
2915     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2916                           INTERNET_STATUS_CONNECTING_TO_SERVER,
2917                           szaddr,
2918                           strlen(szaddr)+1);
2919
2920     if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
2921                          SOCK_STREAM, 0))
2922     {
2923         WARN("Socket creation failed\n");
2924         goto lend;
2925     }
2926
2927     if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
2928                       sizeof(lpwhs->socketAddress)))
2929        goto lend;
2930
2931     if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
2932     {
2933         /* Note: we differ from Microsoft's WinINet here. they seem to have
2934          * a bug that causes no status callbacks to be sent when starting
2935          * a tunnel to a proxy server using the CONNECT verb. i believe our
2936          * behaviour to be more correct and to not cause any incompatibilities
2937          * because using a secure connection through a proxy server is a rare
2938          * case that would be hard for anyone to depend on */
2939         if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
2940             goto lend;
2941
2942         if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
2943         {
2944             WARN("Couldn't connect securely to host\n");
2945             goto lend;
2946         }
2947     }
2948
2949     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2950                           INTERNET_STATUS_CONNECTED_TO_SERVER,
2951                           szaddr, strlen(szaddr)+1);
2952
2953     bSuccess = TRUE;
2954
2955 lend:
2956     TRACE("%d <--\n", bSuccess);
2957     return bSuccess;
2958 }
2959
2960
2961 /***********************************************************************
2962  *           HTTP_clear_response_headers (internal)
2963  *
2964  * clear out any old response headers
2965  */
2966 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
2967 {
2968     DWORD i;
2969
2970     for( i=0; i<lpwhr->nCustHeaders; i++)
2971     {
2972         if( !lpwhr->pCustHeaders[i].lpszField )
2973             continue;
2974         if( !lpwhr->pCustHeaders[i].lpszValue )
2975             continue;
2976         if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
2977             continue;
2978         HTTP_DeleteCustomHeader( lpwhr, i );
2979         i--;
2980     }
2981 }
2982
2983 /***********************************************************************
2984  *           HTTP_GetResponseHeaders (internal)
2985  *
2986  * Read server response
2987  *
2988  * RETURNS
2989  *
2990  *   TRUE  on success
2991  *   FALSE on error
2992  */
2993 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
2994 {
2995     INT cbreaks = 0;
2996     WCHAR buffer[MAX_REPLY_LEN];
2997     DWORD buflen = MAX_REPLY_LEN;
2998     BOOL bSuccess = FALSE;
2999     INT  rc = 0;
3000     static const WCHAR szCrLf[] = {'\r','\n',0};
3001     char bufferA[MAX_REPLY_LEN];
3002     LPWSTR status_code, status_text;
3003     DWORD cchMaxRawHeaders = 1024;
3004     LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3005     DWORD cchRawHeaders = 0;
3006
3007     TRACE("-->\n");
3008
3009     /* clear old response headers (eg. from a redirect response) */
3010     HTTP_clear_response_headers( lpwhr );
3011
3012     if (!NETCON_connected(&lpwhr->netConnection))
3013         goto lend;
3014
3015     /*
3016      * HACK peek at the buffer
3017      */
3018     NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3019
3020     /*
3021      * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3022      */
3023     buflen = MAX_REPLY_LEN;
3024     memset(buffer, 0, MAX_REPLY_LEN);
3025     if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3026         goto lend;
3027     MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3028
3029     /* regenerate raw headers */
3030     while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3031     {
3032         cchMaxRawHeaders *= 2;
3033         lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3034     }
3035     memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3036     cchRawHeaders += (buflen-1);
3037     memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3038     cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3039     lpszRawHeaders[cchRawHeaders] = '\0';
3040
3041     /* split the version from the status code */
3042     status_code = strchrW( buffer, ' ' );
3043     if( !status_code )
3044         goto lend;
3045     *status_code++=0;
3046
3047     /* split the status code from the status text */
3048     status_text = strchrW( status_code, ' ' );
3049     if( !status_text )
3050         goto lend;
3051     *status_text++=0;
3052
3053     TRACE("version [%s] status code [%s] status text [%s]\n",
3054          debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3055
3056     HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3057             HTTP_ADDHDR_FLAG_REPLACE);
3058
3059     HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3060     HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3061
3062     lpwhr->lpszVersion= WININET_strdupW(buffer);
3063     lpwhr->lpszStatusText = WININET_strdupW(status_text);
3064
3065     /* Parse each response line */
3066     do
3067     {
3068         buflen = MAX_REPLY_LEN;
3069         if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3070         {
3071             LPWSTR * pFieldAndValue;
3072
3073             TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3074             MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3075
3076             while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3077             {
3078                 cchMaxRawHeaders *= 2;
3079                 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3080             }
3081             memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3082             cchRawHeaders += (buflen-1);
3083             memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3084             cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3085             lpszRawHeaders[cchRawHeaders] = '\0';
3086
3087             pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3088             if (!pFieldAndValue)
3089                 break;
3090
3091             HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1], 
3092                 HTTP_ADDREQ_FLAG_ADD );
3093
3094             HTTP_FreeTokens(pFieldAndValue);
3095         }
3096         else
3097         {
3098             cbreaks++;
3099             if (cbreaks >= 2)
3100                break;
3101         }
3102     }while(1);
3103
3104     HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3105     lpwhr->lpszRawHeaders = lpszRawHeaders;
3106     TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3107     bSuccess = TRUE;
3108
3109 lend:
3110
3111     TRACE("<--\n");
3112     if (bSuccess)
3113         return rc;
3114     else
3115         return 0;
3116 }
3117
3118
3119 static void strip_spaces(LPWSTR start)
3120 {
3121     LPWSTR str = start;
3122     LPWSTR end;
3123
3124     while (*str == ' ' && *str != '\0')
3125         str++;
3126
3127     if (str != start)
3128         memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3129
3130     end = start + strlenW(start) - 1;
3131     while (end >= start && *end == ' ')
3132     {
3133         *end = '\0';
3134         end--;
3135     }
3136 }
3137
3138
3139 /***********************************************************************
3140  *           HTTP_InterpretHttpHeader (internal)
3141  *
3142  * Parse server response
3143  *
3144  * RETURNS
3145  *
3146  *   Pointer to array of field, value, NULL on success.
3147  *   NULL on error.
3148  */
3149 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3150 {
3151     LPWSTR * pTokenPair;
3152     LPWSTR pszColon;
3153     INT len;
3154
3155     pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3156
3157     pszColon = strchrW(buffer, ':');
3158     /* must have two tokens */
3159     if (!pszColon)
3160     {
3161         HTTP_FreeTokens(pTokenPair);
3162         if (buffer[0])
3163             TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3164         return NULL;
3165     }
3166
3167     pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3168     if (!pTokenPair[0])
3169     {
3170         HTTP_FreeTokens(pTokenPair);
3171         return NULL;
3172     }
3173     memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3174     pTokenPair[0][pszColon - buffer] = '\0';
3175
3176     /* skip colon */
3177     pszColon++;
3178     len = strlenW(pszColon);
3179     pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3180     if (!pTokenPair[1])
3181     {
3182         HTTP_FreeTokens(pTokenPair);
3183         return NULL;
3184     }
3185     memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3186
3187     strip_spaces(pTokenPair[0]);
3188     strip_spaces(pTokenPair[1]);
3189
3190     TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3191     return pTokenPair;
3192 }
3193
3194 /***********************************************************************
3195  *           HTTP_ProcessHeader (internal)
3196  *
3197  * Stuff header into header tables according to <dwModifier>
3198  *
3199  */
3200
3201 #define COALESCEFLASG (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3202
3203 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3204 {
3205     LPHTTPHEADERW lphttpHdr = NULL;
3206     BOOL bSuccess = FALSE;
3207     INT index = -1;
3208     BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3209
3210     TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3211
3212     /* REPLACE wins out over ADD */
3213     if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3214         dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3215     
3216     if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3217         index = -1;
3218     else
3219         index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3220
3221     if (index >= 0)
3222     {
3223         if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3224         {
3225             return FALSE;
3226         }
3227         lphttpHdr = &lpwhr->pCustHeaders[index];
3228     }
3229     else if (value)
3230     {
3231         HTTPHEADERW hdr;
3232
3233         hdr.lpszField = (LPWSTR)field;
3234         hdr.lpszValue = (LPWSTR)value;
3235         hdr.wFlags = hdr.wCount = 0;
3236
3237         if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3238             hdr.wFlags |= HDR_ISREQUEST;
3239
3240         return HTTP_InsertCustomHeader(lpwhr, &hdr);
3241     }
3242     /* no value to delete */
3243     else return TRUE;
3244
3245     if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3246             lphttpHdr->wFlags |= HDR_ISREQUEST;
3247     else
3248         lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3249
3250     if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3251     {
3252         HTTP_DeleteCustomHeader( lpwhr, index );
3253
3254         if (value)
3255         {
3256             HTTPHEADERW hdr;
3257
3258             hdr.lpszField = (LPWSTR)field;
3259             hdr.lpszValue = (LPWSTR)value;
3260             hdr.wFlags = hdr.wCount = 0;
3261
3262             if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3263                 hdr.wFlags |= HDR_ISREQUEST;
3264
3265             return HTTP_InsertCustomHeader(lpwhr, &hdr);
3266         }
3267
3268         return TRUE;
3269     }
3270     else if (dwModifier & COALESCEFLASG)
3271     {
3272         LPWSTR lpsztmp;
3273         WCHAR ch = 0;
3274         INT len = 0;
3275         INT origlen = strlenW(lphttpHdr->lpszValue);
3276         INT valuelen = strlenW(value);
3277
3278         if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3279         {
3280             ch = ',';
3281             lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3282         }
3283         else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3284         {
3285             ch = ';';
3286             lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3287         }
3288
3289         len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3290
3291         lpsztmp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,  lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3292         if (lpsztmp)
3293         {
3294             lphttpHdr->lpszValue = lpsztmp;
3295     /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3296             if (ch > 0)
3297             {
3298                 lphttpHdr->lpszValue[origlen] = ch;
3299                 origlen++;
3300                 lphttpHdr->lpszValue[origlen] = ' ';
3301                 origlen++;
3302             }
3303
3304             memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3305             lphttpHdr->lpszValue[len] = '\0';
3306             bSuccess = TRUE;
3307         }
3308         else
3309         {
3310             WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3311             INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3312         }
3313     }
3314     TRACE("<-- %d\n",bSuccess);
3315     return bSuccess;
3316 }
3317
3318
3319 /***********************************************************************
3320  *           HTTP_CloseConnection (internal)
3321  *
3322  * Close socket connection
3323  *
3324  */
3325 static void HTTP_CloseConnection(LPWININETHANDLEHEADER hdr)
3326 {
3327     LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
3328     LPWININETHTTPSESSIONW lpwhs = NULL;
3329     LPWININETAPPINFOW hIC = NULL;
3330
3331     TRACE("%p\n",lpwhr);
3332
3333     if (!NETCON_connected(&lpwhr->netConnection))
3334         return;
3335
3336     if (lpwhr->pAuthInfo)
3337     {
3338         DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
3339         FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
3340
3341         HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
3342         HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
3343         HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
3344         lpwhr->pAuthInfo = NULL;
3345     }
3346     if (lpwhr->pProxyAuthInfo)
3347     {
3348         DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
3349         FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
3350
3351         HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
3352         HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
3353         HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
3354         lpwhr->pProxyAuthInfo = NULL;
3355     }
3356
3357     lpwhs = lpwhr->lpHttpSession;
3358     hIC = lpwhs->lpAppInfo;
3359
3360     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3361                           INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
3362
3363     NETCON_close(&lpwhr->netConnection);
3364
3365     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3366                           INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
3367 }
3368
3369
3370 /***********************************************************************
3371  *           HTTP_FinishedReading (internal)
3372  *
3373  * Called when all content from server has been read by client.
3374  *
3375  */
3376 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
3377 {
3378     WCHAR szConnectionResponse[20];
3379     DWORD dwBufferSize = sizeof(szConnectionResponse);
3380
3381     TRACE("\n");
3382
3383     if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse,
3384                              &dwBufferSize, NULL) ||
3385         strcmpiW(szConnectionResponse, szKeepAlive))
3386     {
3387         HTTP_CloseConnection(&lpwhr->hdr);
3388     }
3389
3390     /* FIXME: store data in the URL cache here */
3391
3392     return TRUE;
3393 }
3394
3395 /***********************************************************************
3396  *           HTTP_CloseHTTPRequestHandle (internal)
3397  *
3398  * Deallocate request handle
3399  *
3400  */
3401 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr)
3402 {
3403     DWORD i;
3404     LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
3405
3406     TRACE("\n");
3407
3408     WININET_Release(&lpwhr->lpHttpSession->hdr);
3409
3410     HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3411     HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3412     HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3413     HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
3414     HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
3415
3416     for (i = 0; i < lpwhr->nCustHeaders; i++)
3417     {
3418         HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
3419         HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
3420     }
3421
3422     HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
3423     HeapFree(GetProcessHeap(), 0, lpwhr);
3424 }
3425
3426
3427 /***********************************************************************
3428  *           HTTP_CloseHTTPSessionHandle (internal)
3429  *
3430  * Deallocate session handle
3431  *
3432  */
3433 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr)
3434 {
3435     LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3436
3437     TRACE("%p\n", lpwhs);
3438
3439     WININET_Release(&lpwhs->lpAppInfo->hdr);
3440
3441     HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3442     HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3443     HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3444     HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3445     HeapFree(GetProcessHeap(), 0, lpwhs);
3446 }
3447
3448
3449 /***********************************************************************
3450  *           HTTP_GetCustomHeaderIndex (internal)
3451  *
3452  * Return index of custom header from header array
3453  *
3454  */
3455 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
3456                                      int requested_index, BOOL request_only)
3457 {
3458     DWORD index;
3459
3460     TRACE("%s\n", debugstr_w(lpszField));
3461
3462     for (index = 0; index < lpwhr->nCustHeaders; index++)
3463     {
3464         if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3465             continue;
3466
3467         if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3468             continue;
3469
3470         if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3471             continue;
3472
3473         if (requested_index == 0)
3474             break;
3475         requested_index --;
3476     }
3477
3478     if (index >= lpwhr->nCustHeaders)
3479         index = -1;
3480
3481     TRACE("Return: %d\n", index);
3482     return index;
3483 }
3484
3485
3486 /***********************************************************************
3487  *           HTTP_InsertCustomHeader (internal)
3488  *
3489  * Insert header into array
3490  *
3491  */
3492 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3493 {
3494     INT count;
3495     LPHTTPHEADERW lph = NULL;
3496     BOOL r = FALSE;
3497
3498     TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3499     count = lpwhr->nCustHeaders + 1;
3500     if (count > 1)
3501         lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3502     else
3503         lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3504
3505     if (NULL != lph)
3506     {
3507         lpwhr->pCustHeaders = lph;
3508         lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3509         lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3510         lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3511         lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3512         lpwhr->nCustHeaders++;
3513         r = TRUE;
3514     }
3515     else
3516     {
3517         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3518     }
3519
3520     return r;
3521 }
3522
3523
3524 /***********************************************************************
3525  *           HTTP_DeleteCustomHeader (internal)
3526  *
3527  * Delete header from array
3528  *  If this function is called, the indexs may change.
3529  */
3530 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3531 {
3532     if( lpwhr->nCustHeaders <= 0 )
3533         return FALSE;
3534     if( index >= lpwhr->nCustHeaders )
3535         return FALSE;
3536     lpwhr->nCustHeaders--;
3537
3538     memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3539              (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3540     memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3541
3542     return TRUE;
3543 }
3544
3545
3546 /***********************************************************************
3547  *           HTTP_VerifyValidHeader (internal)
3548  *
3549  * Verify the given header is not invalid for the given http request
3550  *
3551  */
3552 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
3553 {
3554     BOOL rc = TRUE;
3555
3556     /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
3557     if (strcmpiW(field,szAccept_Encoding)==0)
3558         return FALSE;
3559
3560     return rc;
3561 }
3562
3563 /***********************************************************************
3564  *          IsHostInProxyBypassList (@)
3565  *
3566  * Undocumented
3567  *
3568  */
3569 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3570 {
3571    FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
3572    return FALSE;
3573 }