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