~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/wininet/http.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

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