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