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