wininet: Don't forget the INTERNET_STATUS_REDIRECT callback in HttpEndRequest.
[wine] / dlls / wininet / http.c
1 /*
2  * Wininet - Http Implementation
3  *
4  * Copyright 1999 Corel Corporation
5  * Copyright 2002 CodeWeavers Inc.
6  * Copyright 2002 TransGaming Technologies Inc.
7  * Copyright 2004 Mike McCormack for CodeWeavers
8  * Copyright 2005 Aric Stewart for CodeWeavers
9  * Copyright 2006 Robert Shearman for CodeWeavers
10  *
11  * Ulrich Czekalla
12  * David Hammerton
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27  */
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #include <sys/types.h>
33 #ifdef HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
35 #endif
36 #ifdef HAVE_ARPA_INET_H
37 # include <arpa/inet.h>
38 #endif
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45 #include <time.h>
46 #include <assert.h>
47
48 #include "windef.h"
49 #include "winbase.h"
50 #include "wininet.h"
51 #include "winerror.h"
52 #define NO_SHLWAPI_STREAM
53 #define NO_SHLWAPI_REG
54 #define NO_SHLWAPI_STRFCNS
55 #define NO_SHLWAPI_GDI
56 #include "shlwapi.h"
57 #include "sspi.h"
58 #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',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;
968     INT acceptTypesCount;
969     HINTERNET rc = FALSE;
970     TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
971           debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
972           debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
973           dwFlags, dwContext);
974
975     if (lpszVerb)
976     {
977         len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
978         szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
979         if ( !szVerb )
980             goto end;
981         MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
982     }
983
984     if (lpszObjectName)
985     {
986         len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
987         szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
988         if ( !szObjectName )
989             goto end;
990         MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
991     }
992
993     if (lpszVersion)
994     {
995         len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
996         szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
997         if ( !szVersion )
998             goto end;
999         MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
1000     }
1001
1002     if (lpszReferrer)
1003     {
1004         len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1005         szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1006         if ( !szReferrer )
1007             goto end;
1008         MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1009     }
1010
1011     acceptTypesCount = 0;
1012     if (lpszAcceptTypes)
1013     {
1014         /* find out how many there are */
1015         while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1016             acceptTypesCount++;
1017         szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1018         acceptTypesCount = 0;
1019         while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1020         {
1021             len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1022                                 -1, NULL, 0 );
1023             szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1024             if (!szAcceptTypes[acceptTypesCount] )
1025                 goto end;
1026             MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1027                                 -1, szAcceptTypes[acceptTypesCount], len );
1028             acceptTypesCount++;
1029         }
1030         szAcceptTypes[acceptTypesCount] = NULL;
1031     }
1032     else szAcceptTypes = 0;
1033
1034     rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1035                           szVersion, szReferrer,
1036                           (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1037
1038 end:
1039     if (szAcceptTypes)
1040     {
1041         acceptTypesCount = 0;
1042         while (szAcceptTypes[acceptTypesCount])
1043         {
1044             HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1045             acceptTypesCount++;
1046         }
1047         HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1048     }
1049     HeapFree(GetProcessHeap(), 0, szReferrer);
1050     HeapFree(GetProcessHeap(), 0, szVersion);
1051     HeapFree(GetProcessHeap(), 0, szObjectName);
1052     HeapFree(GetProcessHeap(), 0, szVerb);
1053
1054     return rc;
1055 }
1056
1057 /***********************************************************************
1058  *  HTTP_EncodeBase64
1059  */
1060 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1061 {
1062     UINT n = 0, x;
1063     static const CHAR HTTP_Base64Enc[] =
1064         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1065
1066     while( len > 0 )
1067     {
1068         /* first 6 bits, all from bin[0] */
1069         base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1070         x = (bin[0] & 3) << 4;
1071
1072         /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1073         if( len == 1 )
1074         {
1075             base64[n++] = HTTP_Base64Enc[x];
1076             base64[n++] = '=';
1077             base64[n++] = '=';
1078             break;
1079         }
1080         base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1081         x = ( bin[1] & 0x0f ) << 2;
1082
1083         /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1084         if( len == 2 )
1085         {
1086             base64[n++] = HTTP_Base64Enc[x];
1087             base64[n++] = '=';
1088             break;
1089         }
1090         base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1091
1092         /* last 6 bits, all from bin [2] */
1093         base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1094         bin += 3;
1095         len -= 3;
1096     }
1097     base64[n] = 0;
1098     return n;
1099 }
1100
1101 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1102                ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1103                ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1104                ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1105 static const signed char HTTP_Base64Dec[256] =
1106 {
1107     CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1108     CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1109     CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1110     CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1111     CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1112     CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1113     CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1114     CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1115     CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1116     CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1117     CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1118     CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1119     CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1120     CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1121     CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1122     CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1123     CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1124     CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1125     CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1126     CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1127     CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1128     CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1129     CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1130     CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1131     CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1132     CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1133 };
1134 #undef CH
1135
1136 /***********************************************************************
1137  *  HTTP_DecodeBase64
1138  */
1139 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1140 {
1141     unsigned int n = 0;
1142
1143     while(*base64)
1144     {
1145         signed char in[4];
1146
1147         if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1148             ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1149             base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1150             ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1151         {
1152             WARN("invalid base64: %s\n", debugstr_w(base64));
1153             return 0;
1154         }
1155         if (bin)
1156             bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1157         n++;
1158
1159         if ((base64[2] == '=') && (base64[3] == '='))
1160             break;
1161         if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1162             ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1163         {
1164             WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1165             return 0;
1166         }
1167         if (bin)
1168             bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1169         n++;
1170
1171         if (base64[3] == '=')
1172             break;
1173         if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1174             ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1175         {
1176             WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1177             return 0;
1178         }
1179         if (bin)
1180             bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1181         n++;
1182
1183         base64 += 4;
1184     }
1185
1186     return n;
1187 }
1188
1189 /***********************************************************************
1190  *  HTTP_InsertAuthorizationForHeader
1191  *
1192  *   Insert or delete the authorization field in the request header.
1193  */
1194 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1195 {
1196     if (pAuthInfo)
1197     {
1198         static const WCHAR wszSpace[] = {' ',0};
1199         static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1200         unsigned int len;
1201         WCHAR *authorization = NULL;
1202
1203         if (pAuthInfo->auth_data_len)
1204         {
1205             /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1206             len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1207             authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1208             if (!authorization)
1209                 return FALSE;
1210
1211             strcpyW(authorization, pAuthInfo->scheme);
1212             strcatW(authorization, wszSpace);
1213             HTTP_EncodeBase64(pAuthInfo->auth_data,
1214                               pAuthInfo->auth_data_len,
1215                               authorization+strlenW(authorization));
1216
1217             /* clear the data as it isn't valid now that it has been sent to the
1218              * server, unless it's Basic authentication which doesn't do
1219              * connection tracking */
1220             if (strcmpiW(pAuthInfo->scheme, wszBasic))
1221             {
1222                 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1223                 pAuthInfo->auth_data = NULL;
1224                 pAuthInfo->auth_data_len = 0;
1225             }
1226         }
1227
1228         TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1229
1230         HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1231
1232         HeapFree(GetProcessHeap(), 0, authorization);
1233     }
1234     return TRUE;
1235 }
1236
1237 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1238 {
1239     WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1240     DWORD size;
1241
1242     size = sizeof(new_location);
1243     if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1244     {
1245         if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1246         strcpyW( url, new_location );
1247     }
1248     else
1249     {
1250         static const WCHAR slash[] = { '/',0 };
1251         static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1252         WININETHTTPSESSIONW *session = req->lpHttpSession;
1253
1254         size = 15; /* "http://" + sizeof(port#) + ":/\0" */
1255         size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1256
1257         if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
1258
1259         sprintfW( url, format, session->lpszHostName, session->nHostPort );
1260         if (req->lpszPath[0] != '/') strcatW( url, slash );
1261         strcatW( url, req->lpszPath );
1262     }
1263     TRACE("url=%s\n", debugstr_w(url));
1264     return url;
1265 }
1266
1267 /***********************************************************************
1268  *           HTTP_DealWithProxy
1269  */
1270 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1271     LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1272 {
1273     WCHAR buf[MAXHOSTNAME];
1274     WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1275     static WCHAR szNul[] = { 0 };
1276     URL_COMPONENTSW UrlComponents;
1277     static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1278     static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1279
1280     memset( &UrlComponents, 0, sizeof UrlComponents );
1281     UrlComponents.dwStructSize = sizeof UrlComponents;
1282     UrlComponents.lpszHostName = buf;
1283     UrlComponents.dwHostNameLength = MAXHOSTNAME;
1284
1285     if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1286                                  hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1287         sprintfW(proxy, szFormat, hIC->lpszProxy);
1288     else
1289         strcpyW(proxy, hIC->lpszProxy);
1290     if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1291         return FALSE;
1292     if( UrlComponents.dwHostNameLength == 0 )
1293         return FALSE;
1294
1295     if( !lpwhr->lpszPath )
1296         lpwhr->lpszPath = szNul;
1297
1298     if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1299         UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1300
1301     HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1302     lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1303     lpwhs->nServerPort = UrlComponents.nPort;
1304
1305     TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1306     return TRUE;
1307 }
1308
1309 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1310 {
1311     char szaddr[32];
1312     LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1313
1314     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1315                           INTERNET_STATUS_RESOLVING_NAME,
1316                           lpwhs->lpszServerName,
1317                           strlenW(lpwhs->lpszServerName)+1);
1318
1319     if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1320                     &lpwhs->socketAddress))
1321     {
1322         INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1323         return FALSE;
1324     }
1325
1326     inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1327               szaddr, sizeof(szaddr));
1328     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1329                           INTERNET_STATUS_NAME_RESOLVED,
1330                           szaddr, strlen(szaddr)+1);
1331     return TRUE;
1332 }
1333
1334
1335 /***********************************************************************
1336  *           HTTPREQ_Destroy (internal)
1337  *
1338  * Deallocate request handle
1339  *
1340  */
1341 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1342 {
1343     LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1344     DWORD i;
1345
1346     TRACE("\n");
1347
1348     if(lpwhr->hCacheFile)
1349         CloseHandle(lpwhr->hCacheFile);
1350
1351     if(lpwhr->lpszCacheFile) {
1352         DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1353         HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1354     }
1355
1356     WININET_Release(&lpwhr->lpHttpSession->hdr);
1357
1358     HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1359     HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1360     HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1361     HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1362     HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1363
1364     for (i = 0; i < lpwhr->nCustHeaders; i++)
1365     {
1366         HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1367         HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1368     }
1369
1370     HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1371     HeapFree(GetProcessHeap(), 0, lpwhr);
1372 }
1373
1374 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1375 {
1376     LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1377     LPWININETHTTPSESSIONW lpwhs = NULL;
1378     LPWININETAPPINFOW hIC = NULL;
1379
1380     TRACE("%p\n",lpwhr);
1381
1382     if (!NETCON_connected(&lpwhr->netConnection))
1383         return;
1384
1385     if (lpwhr->pAuthInfo)
1386     {
1387         if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1388             DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1389         if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1390             FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1391
1392         HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1393         HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1394         HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1395         lpwhr->pAuthInfo = NULL;
1396     }
1397     if (lpwhr->pProxyAuthInfo)
1398     {
1399         if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1400             DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1401         if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1402             FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1403
1404         HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1405         HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1406         HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1407         lpwhr->pProxyAuthInfo = NULL;
1408     }
1409
1410     lpwhs = lpwhr->lpHttpSession;
1411     hIC = lpwhs->lpAppInfo;
1412
1413     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1414                           INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1415
1416     NETCON_close(&lpwhr->netConnection);
1417
1418     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1419                           INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1420 }
1421
1422 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1423 {
1424     WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1425
1426     switch(option) {
1427     case INTERNET_OPTION_HANDLE_TYPE:
1428         TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1429
1430         if (*size < sizeof(ULONG))
1431             return ERROR_INSUFFICIENT_BUFFER;
1432
1433         *size = sizeof(DWORD);
1434         *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1435         return ERROR_SUCCESS;
1436
1437     case INTERNET_OPTION_URL: {
1438         WCHAR url[INTERNET_MAX_URL_LENGTH];
1439         HTTPHEADERW *host;
1440         DWORD len;
1441
1442         static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
1443         static const WCHAR hostW[] = {'H','o','s','t',0};
1444
1445         TRACE("INTERNET_OPTION_URL\n");
1446
1447         host = HTTP_GetHeader(req, hostW);
1448         sprintfW(url, formatW, host->lpszValue, req->lpszPath);
1449         TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1450
1451         if(unicode) {
1452             len = (strlenW(url)+1) * sizeof(WCHAR);
1453             if(*size < len)
1454                 return ERROR_INSUFFICIENT_BUFFER;
1455
1456             *size = len;
1457             strcpyW(buffer, url);
1458             return ERROR_SUCCESS;
1459         }else {
1460             len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1461             if(len > *size)
1462                 return ERROR_INSUFFICIENT_BUFFER;
1463
1464             *size = len;
1465             return ERROR_SUCCESS;
1466         }
1467     }
1468
1469     case INTERNET_OPTION_DATAFILE_NAME: {
1470         DWORD req_size;
1471
1472         TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1473
1474         if(!req->lpszCacheFile) {
1475             *size = 0;
1476             return ERROR_INTERNET_ITEM_NOT_FOUND;
1477         }
1478
1479         if(unicode) {
1480             req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1481             if(*size < req_size)
1482                 return ERROR_INSUFFICIENT_BUFFER;
1483
1484             *size = req_size;
1485             memcpy(buffer, req->lpszCacheFile, *size);
1486             return ERROR_SUCCESS;
1487         }else {
1488             req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1489             if (req_size > *size)
1490                 return ERROR_INSUFFICIENT_BUFFER;
1491
1492             *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1493                     -1, buffer, *size, NULL, NULL);
1494             return ERROR_SUCCESS;
1495         }
1496     }
1497
1498     case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1499         PCCERT_CONTEXT context;
1500
1501         if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1502             *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1503             return ERROR_INSUFFICIENT_BUFFER;
1504         }
1505
1506         context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1507         if(context) {
1508             INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1509             DWORD len;
1510
1511             memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1512             info->ftExpiry = context->pCertInfo->NotAfter;
1513             info->ftStart = context->pCertInfo->NotBefore;
1514             if(unicode) {
1515                 len = CertNameToStrW(context->dwCertEncodingType,
1516                         &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1517                 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1518                 if(info->lpszSubjectInfo)
1519                     CertNameToStrW(context->dwCertEncodingType,
1520                              &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1521                              info->lpszSubjectInfo, len);
1522                 len = CertNameToStrW(context->dwCertEncodingType,
1523                          &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1524                 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1525                 if (info->lpszIssuerInfo)
1526                     CertNameToStrW(context->dwCertEncodingType,
1527                              &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1528                              info->lpszIssuerInfo, len);
1529             }else {
1530                 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1531
1532                 len = CertNameToStrA(context->dwCertEncodingType,
1533                          &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1534                 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1535                 if(infoA->lpszSubjectInfo)
1536                     CertNameToStrA(context->dwCertEncodingType,
1537                              &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1538                              infoA->lpszSubjectInfo, len);
1539                 len = CertNameToStrA(context->dwCertEncodingType,
1540                          &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1541                 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1542                 if(infoA->lpszIssuerInfo)
1543                     CertNameToStrA(context->dwCertEncodingType,
1544                              &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1545                              infoA->lpszIssuerInfo, len);
1546             }
1547
1548             /*
1549              * Contrary to MSDN, these do not appear to be set.
1550              * lpszProtocolName
1551              * lpszSignatureAlgName
1552              * lpszEncryptionAlgName
1553              * dwKeySize
1554              */
1555             CertFreeCertificateContext(context);
1556             return ERROR_SUCCESS;
1557         }
1558     }
1559     }
1560
1561     FIXME("Not implemented option %d\n", option);
1562     return ERROR_INTERNET_INVALID_OPTION;
1563 }
1564
1565 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1566 {
1567     WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1568
1569     switch(option) {
1570     case INTERNET_OPTION_SEND_TIMEOUT:
1571     case INTERNET_OPTION_RECEIVE_TIMEOUT:
1572         TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1573
1574         if (size != sizeof(DWORD))
1575             return ERROR_INVALID_PARAMETER;
1576
1577         return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1578                     *(DWORD*)buffer);
1579     }
1580
1581     return ERROR_INTERNET_INVALID_OPTION;
1582 }
1583
1584 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1585 {
1586     int bytes_read;
1587
1588     if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1589                      sync ? MSG_WAITALL : 0, &bytes_read)) {
1590         if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1591             ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1592
1593         /* always return success, even if the network layer returns an error */
1594         *read = 0;
1595         HTTP_FinishedReading(req);
1596         return ERROR_SUCCESS;
1597     }
1598
1599     req->dwContentRead += bytes_read;
1600     *read = bytes_read;
1601
1602     if(req->lpszCacheFile) {
1603         BOOL res;
1604
1605         res = WriteFile(req->hCacheFile, buffer, bytes_read, NULL, NULL);
1606         if(!res)
1607             WARN("WriteFile failed: %u\n", GetLastError());
1608     }
1609
1610     if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1611         HTTP_FinishedReading(req);
1612
1613     return ERROR_SUCCESS;
1614 }
1615
1616 static DWORD get_chunk_size(const char *buffer)
1617 {
1618     const char *p;
1619     DWORD size = 0;
1620
1621     for (p = buffer; *p; p++)
1622     {
1623         if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1624         else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1625         else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1626         else if (*p == ';') break;
1627     }
1628     return size;
1629 }
1630
1631 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1632 {
1633     char reply[MAX_REPLY_LEN], *p = buffer;
1634     DWORD buflen, to_read, to_write = size;
1635     int bytes_read;
1636
1637     *read = 0;
1638     for (;;)
1639     {
1640         if (*read == size) break;
1641
1642         if (req->dwContentLength == ~0UL) /* new chunk */
1643         {
1644             buflen = sizeof(reply);
1645             if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1646
1647             if (!(req->dwContentLength = get_chunk_size(reply)))
1648             {
1649                 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1650                 HTTP_GetResponseHeaders(req, FALSE);
1651                 break;
1652             }
1653         }
1654         to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1655
1656         if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1657         {
1658             if (bytes_read != to_read)
1659                 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1660
1661             /* always return success, even if the network layer returns an error */
1662             *read = 0;
1663             break;
1664         }
1665         if (!bytes_read) break;
1666
1667         req->dwContentRead += bytes_read;
1668         to_write -= bytes_read;
1669         *read += bytes_read;
1670
1671         if (req->lpszCacheFile)
1672         {
1673             if (!WriteFile(req->hCacheFile, p, bytes_read, NULL, NULL))
1674                 WARN("WriteFile failed: %u\n", GetLastError());
1675         }
1676         p += bytes_read;
1677
1678         if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1679         {
1680             req->dwContentRead = 0;
1681             req->dwContentLength = ~0UL;
1682
1683             buflen = sizeof(reply);
1684             if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1685             {
1686                 ERR("Malformed chunk\n");
1687                 *read = 0;
1688                 break;
1689             }
1690         }
1691     }
1692     if (!*read) HTTP_FinishedReading(req);
1693     return ERROR_SUCCESS;
1694 }
1695
1696 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1697 {
1698     WCHAR encoding[20];
1699     DWORD buflen = sizeof(encoding);
1700     static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1701
1702     if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1703         !strcmpiW(encoding, szChunked))
1704     {
1705         return HTTP_ReadChunked(req, buffer, size, read, sync);
1706     }
1707     else
1708         return HTTP_Read(req, buffer, size, read, sync);
1709 }
1710
1711 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1712 {
1713     WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1714     return HTTPREQ_Read(req, buffer, size, read, TRUE);
1715 }
1716
1717 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1718 {
1719     struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1720     WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1721     INTERNET_ASYNC_RESULT iar;
1722     DWORD res;
1723
1724     TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1725
1726     res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1727             data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1728
1729     iar.dwResult = res == ERROR_SUCCESS;
1730     iar.dwError = res;
1731
1732     INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1733                           INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1734                           sizeof(INTERNET_ASYNC_RESULT));
1735 }
1736
1737 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1738         DWORD flags, DWORD_PTR context)
1739 {
1740
1741     WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1742     DWORD res;
1743
1744     if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1745         FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1746
1747     if (buffers->dwStructSize != sizeof(*buffers))
1748         return ERROR_INVALID_PARAMETER;
1749
1750     INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1751
1752     if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1753         DWORD available = 0;
1754
1755         NETCON_query_data_available(&req->netConnection, &available);
1756         if (!available)
1757         {
1758             WORKREQUEST workRequest;
1759
1760             workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1761             workRequest.hdr = WININET_AddRef(&req->hdr);
1762             workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1763
1764             INTERNET_AsyncCall(&workRequest);
1765
1766             return ERROR_IO_PENDING;
1767         }
1768     }
1769
1770     res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1771             !(flags & IRF_NO_WAIT));
1772
1773     if (res == ERROR_SUCCESS) {
1774         DWORD size = buffers->dwBufferLength;
1775         INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1776                 &size, sizeof(size));
1777     }
1778
1779     return res;
1780 }
1781
1782 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1783 {
1784     LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1785
1786     return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1787 }
1788
1789 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1790 {
1791     WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1792     INTERNET_ASYNC_RESULT iar;
1793     char buffer[4048];
1794
1795     TRACE("%p\n", workRequest->hdr);
1796
1797     iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1798                                min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1799                                MSG_PEEK, (int *)&iar.dwError);
1800
1801     INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1802                           sizeof(INTERNET_ASYNC_RESULT));
1803 }
1804
1805 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1806 {
1807     WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1808     BYTE buffer[4048];
1809     BOOL async;
1810
1811     TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1812
1813     if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1814         return ERROR_SUCCESS;
1815
1816     /* Even if we are in async mode, we need to determine whether
1817      * there is actually more data available. We do this by trying
1818      * to peek only a single byte in async mode. */
1819     async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1820
1821     if (NETCON_recv(&req->netConnection, buffer,
1822                     min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1823                     MSG_PEEK, (int *)available) && async && *available)
1824     {
1825         WORKREQUEST workRequest;
1826
1827         *available = 0;
1828         workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1829         workRequest.hdr = WININET_AddRef( &req->hdr );
1830
1831         INTERNET_AsyncCall(&workRequest);
1832
1833         return ERROR_IO_PENDING;
1834     }
1835
1836     return ERROR_SUCCESS;
1837 }
1838
1839 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1840     HTTPREQ_Destroy,
1841     HTTPREQ_CloseConnection,
1842     HTTPREQ_QueryOption,
1843     HTTPREQ_SetOption,
1844     HTTPREQ_ReadFile,
1845     HTTPREQ_ReadFileExA,
1846     HTTPREQ_WriteFile,
1847     HTTPREQ_QueryDataAvailable,
1848     NULL
1849 };
1850
1851 /***********************************************************************
1852  *           HTTP_HttpOpenRequestW (internal)
1853  *
1854  * Open a HTTP request handle
1855  *
1856  * RETURNS
1857  *    HINTERNET  a HTTP request handle on success
1858  *    NULL       on failure
1859  *
1860  */
1861 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1862         LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1863         LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1864         DWORD dwFlags, DWORD_PTR dwContext)
1865 {
1866     LPWININETAPPINFOW hIC = NULL;
1867     LPWININETHTTPREQW lpwhr;
1868     LPWSTR lpszCookies;
1869     LPWSTR lpszUrl = NULL;
1870     DWORD nCookieSize;
1871     HINTERNET handle = NULL;
1872     static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1873     DWORD len;
1874     LPHTTPHEADERW Host;
1875
1876     TRACE("-->\n");
1877
1878     assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1879     hIC = lpwhs->lpAppInfo;
1880
1881     lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1882     if (NULL == lpwhr)
1883     {
1884         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1885         goto lend;
1886     }
1887     lpwhr->hdr.htype = WH_HHTTPREQ;
1888     lpwhr->hdr.vtbl = &HTTPREQVtbl;
1889     lpwhr->hdr.dwFlags = dwFlags;
1890     lpwhr->hdr.dwContext = dwContext;
1891     lpwhr->hdr.refs = 1;
1892     lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1893     lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1894
1895     WININET_AddRef( &lpwhs->hdr );
1896     lpwhr->lpHttpSession = lpwhs;
1897     list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1898
1899     handle = WININET_AllocHandle( &lpwhr->hdr );
1900     if (NULL == handle)
1901     {
1902         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1903         goto lend;
1904     }
1905
1906     if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1907     {
1908         InternetCloseHandle( handle );
1909         handle = NULL;
1910         goto lend;
1911     }
1912
1913     if (lpszObjectName && *lpszObjectName) {
1914         HRESULT rc;
1915
1916         len = 0;
1917         rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1918         if (rc != E_POINTER)
1919             len = strlenW(lpszObjectName)+1;
1920         lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1921         rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1922                    URL_ESCAPE_SPACES_ONLY);
1923         if (rc)
1924         {
1925             ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1926             strcpyW(lpwhr->lpszPath,lpszObjectName);
1927         }
1928     }
1929
1930     if (lpszReferrer && *lpszReferrer)
1931         HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1932
1933     if (lpszAcceptTypes)
1934     {
1935         int i;
1936         for (i = 0; lpszAcceptTypes[i]; i++)
1937         {
1938             if (!*lpszAcceptTypes[i]) continue;
1939             HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1940                                HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1941                                HTTP_ADDHDR_FLAG_REQ |
1942                                (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1943         }
1944     }
1945
1946     lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1947
1948     if (lpszVersion)
1949         lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1950     else
1951         lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1952
1953     HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1954
1955     if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1956         lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1957                         INTERNET_DEFAULT_HTTPS_PORT :
1958                         INTERNET_DEFAULT_HTTP_PORT);
1959
1960     if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
1961         lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
1962                         INTERNET_DEFAULT_HTTPS_PORT :
1963                         INTERNET_DEFAULT_HTTP_PORT);
1964
1965     if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1966         HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1967
1968     if (hIC->lpszAgent)
1969     {
1970         WCHAR *agent_header;
1971         static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1972
1973         len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1974         agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1975         sprintfW(agent_header, user_agent, hIC->lpszAgent );
1976
1977         HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1978                                HTTP_ADDREQ_FLAG_ADD);
1979         HeapFree(GetProcessHeap(), 0, agent_header);
1980     }
1981
1982     Host = HTTP_GetHeader(lpwhr,szHost);
1983
1984     len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1985     lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1986     sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1987
1988     if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1989         InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1990     {
1991         int cnt = 0;
1992         static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1993         static const WCHAR szcrlf[] = {'\r','\n',0};
1994
1995         lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1996
1997         cnt += sprintfW(lpszCookies, szCookie);
1998         InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1999         strcatW(lpszCookies, szcrlf);
2000
2001         HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
2002                                HTTP_ADDREQ_FLAG_ADD);
2003         HeapFree(GetProcessHeap(), 0, lpszCookies);
2004     }
2005     HeapFree(GetProcessHeap(), 0, lpszUrl);
2006
2007
2008     INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2009                           INTERNET_STATUS_HANDLE_CREATED, &handle,
2010                           sizeof(handle));
2011
2012     /*
2013      * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
2014      */
2015
2016     if (!HTTP_ResolveName(lpwhr))
2017     {
2018         InternetCloseHandle( handle );
2019         handle = NULL;
2020     }
2021
2022 lend:
2023     if( lpwhr )
2024         WININET_Release( &lpwhr->hdr );
2025
2026     TRACE("<-- %p (%p)\n", handle, lpwhr);
2027     return handle;
2028 }
2029
2030 /* read any content returned by the server so that the connection can be
2031  * reused */
2032 static void HTTP_DrainContent(WININETHTTPREQW *req)
2033 {
2034     DWORD bytes_read;
2035
2036     if (!NETCON_connected(&req->netConnection)) return;
2037
2038     if (req->dwContentLength == -1)
2039         NETCON_close(&req->netConnection);
2040
2041     do
2042     {
2043         char buffer[2048];
2044         if (HTTP_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2045             return;
2046     } while (bytes_read);
2047 }
2048
2049 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2050 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2051 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2052 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2053 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2054 static const WCHAR szAge[] = { 'A','g','e',0 };
2055 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2056 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2057 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2058 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2059 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2060 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2061 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2062 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2063 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2064 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2065 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2066 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 };
2067 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2068 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2069 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2070 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2071 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2072 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2073 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2074 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2075 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2076 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2077 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2078 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2079 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2080 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2081 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2082 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2083 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2084 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2085 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2086 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2087 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2088 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2089 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2090 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2091 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2092 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2093 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 };
2094 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2095 static const WCHAR szURI[] = { 'U','R','I',0 };
2096 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2097 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2098 static const WCHAR szVia[] = { 'V','i','a',0 };
2099 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2100 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2101
2102 static const LPCWSTR header_lookup[] = {
2103     szMime_Version,             /* HTTP_QUERY_MIME_VERSION = 0 */
2104     szContent_Type,             /* HTTP_QUERY_CONTENT_TYPE = 1 */
2105     szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2106     szContent_ID,               /* HTTP_QUERY_CONTENT_ID = 3 */
2107     NULL,                       /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2108     szContent_Length,           /* HTTP_QUERY_CONTENT_LENGTH =  5 */
2109     szContent_Language,         /* HTTP_QUERY_CONTENT_LANGUAGE =  6 */
2110     szAllow,                    /* HTTP_QUERY_ALLOW = 7 */
2111     szPublic,                   /* HTTP_QUERY_PUBLIC = 8 */
2112     szDate,                     /* HTTP_QUERY_DATE = 9 */
2113     szExpires,                  /* HTTP_QUERY_EXPIRES = 10 */
2114     szLast_Modified,            /* HTTP_QUERY_LAST_MODIFIED = 11 */
2115     NULL,                       /* HTTP_QUERY_MESSAGE_ID = 12 */
2116     szURI,                      /* HTTP_QUERY_URI = 13 */
2117     szFrom,                     /* HTTP_QUERY_DERIVED_FROM = 14 */
2118     NULL,                       /* HTTP_QUERY_COST = 15 */
2119     NULL,                       /* HTTP_QUERY_LINK = 16 */
2120     szPragma,                   /* HTTP_QUERY_PRAGMA = 17 */
2121     NULL,                       /* HTTP_QUERY_VERSION = 18 */
2122     szStatus,                   /* HTTP_QUERY_STATUS_CODE = 19 */
2123     NULL,                       /* HTTP_QUERY_STATUS_TEXT = 20 */
2124     NULL,                       /* HTTP_QUERY_RAW_HEADERS = 21 */
2125     NULL,                       /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2126     szConnection,               /* HTTP_QUERY_CONNECTION = 23 */
2127     szAccept,                   /* HTTP_QUERY_ACCEPT = 24 */
2128     szAccept_Charset,           /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2129     szAccept_Encoding,          /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2130     szAccept_Language,          /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2131     szAuthorization,            /* HTTP_QUERY_AUTHORIZATION = 28 */
2132     szContent_Encoding,         /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2133     NULL,                       /* HTTP_QUERY_FORWARDED = 30 */
2134     NULL,                       /* HTTP_QUERY_FROM = 31 */
2135     szIf_Modified_Since,        /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2136     szLocation,                 /* HTTP_QUERY_LOCATION = 33 */
2137     NULL,                       /* HTTP_QUERY_ORIG_URI = 34 */
2138     szReferer,                  /* HTTP_QUERY_REFERER = 35 */
2139     szRetry_After,              /* HTTP_QUERY_RETRY_AFTER = 36 */
2140     szServer,                   /* HTTP_QUERY_SERVER = 37 */
2141     NULL,                       /* HTTP_TITLE = 38 */
2142     szUser_Agent,               /* HTTP_QUERY_USER_AGENT = 39 */
2143     szWWW_Authenticate,         /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2144     szProxy_Authenticate,       /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2145     szAccept_Ranges,            /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2146     szSet_Cookie,               /* HTTP_QUERY_SET_COOKIE = 43 */
2147     szCookie,                   /* HTTP_QUERY_COOKIE = 44 */
2148     NULL,                       /* HTTP_QUERY_REQUEST_METHOD = 45 */
2149     NULL,                       /* HTTP_QUERY_REFRESH = 46 */
2150     NULL,                       /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2151     szAge,                      /* HTTP_QUERY_AGE = 48 */
2152     szCache_Control,            /* HTTP_QUERY_CACHE_CONTROL = 49 */
2153     szContent_Base,             /* HTTP_QUERY_CONTENT_BASE = 50 */
2154     szContent_Location,         /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2155     szContent_MD5,              /* HTTP_QUERY_CONTENT_MD5 = 52 */
2156     szContent_Range,            /* HTTP_QUERY_CONTENT_RANGE = 53 */
2157     szETag,                     /* HTTP_QUERY_ETAG = 54 */
2158     szHost,                     /* HTTP_QUERY_HOST = 55 */
2159     szIf_Match,                 /* HTTP_QUERY_IF_MATCH = 56 */
2160     szIf_None_Match,            /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2161     szIf_Range,                 /* HTTP_QUERY_IF_RANGE = 58 */
2162     szIf_Unmodified_Since,      /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2163     szMax_Forwards,             /* HTTP_QUERY_MAX_FORWARDS = 60 */
2164     szProxy_Authorization,      /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2165     szRange,                    /* HTTP_QUERY_RANGE = 62 */
2166     szTransfer_Encoding,        /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2167     szUpgrade,                  /* HTTP_QUERY_UPGRADE = 64 */
2168     szVary,                     /* HTTP_QUERY_VARY = 65 */
2169     szVia,                      /* HTTP_QUERY_VIA = 66 */
2170     szWarning,                  /* HTTP_QUERY_WARNING = 67 */
2171     szExpect,                   /* HTTP_QUERY_EXPECT = 68 */
2172     szProxy_Connection,         /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2173     szUnless_Modified_Since,    /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2174 };
2175
2176 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2177
2178 /***********************************************************************
2179  *           HTTP_HttpQueryInfoW (internal)
2180  */
2181 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2182         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2183 {
2184     LPHTTPHEADERW lphttpHdr = NULL;
2185     BOOL bSuccess = FALSE;
2186     BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2187     INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2188     INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2189     INT index = -1;
2190
2191     /* Find requested header structure */
2192     switch (level)
2193     {
2194     case HTTP_QUERY_CUSTOM:
2195         index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2196         break;
2197
2198     case HTTP_QUERY_RAW_HEADERS_CRLF:
2199         {
2200             LPWSTR headers;
2201             DWORD len;
2202             BOOL ret;
2203
2204             if (request_only)
2205                 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2206             else
2207                 headers = lpwhr->lpszRawHeaders;
2208
2209             len = strlenW(headers);
2210             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2211             {
2212                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2213                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2214                 ret = FALSE;
2215             } else
2216             {
2217                 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
2218                 *lpdwBufferLength = len * sizeof(WCHAR);
2219
2220                 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2221                 ret = TRUE;
2222             }
2223
2224             if (request_only)
2225                 HeapFree(GetProcessHeap(), 0, headers);
2226             return ret;
2227         }
2228     case HTTP_QUERY_RAW_HEADERS:
2229         {
2230             static const WCHAR szCrLf[] = {'\r','\n',0};
2231             LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2232             DWORD i, size = 0;
2233             LPWSTR pszString = (WCHAR*)lpBuffer;
2234
2235             for (i = 0; ppszRawHeaderLines[i]; i++)
2236                 size += strlenW(ppszRawHeaderLines[i]) + 1;
2237
2238             if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2239             {
2240                 HTTP_FreeTokens(ppszRawHeaderLines);
2241                 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2242                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2243                 return FALSE;
2244             }
2245
2246             for (i = 0; ppszRawHeaderLines[i]; i++)
2247             {
2248                 DWORD len = strlenW(ppszRawHeaderLines[i]);
2249                 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2250                 pszString += len+1;
2251             }
2252             *pszString = '\0';
2253
2254             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
2255
2256             *lpdwBufferLength = size * sizeof(WCHAR);
2257             HTTP_FreeTokens(ppszRawHeaderLines);
2258
2259             return TRUE;
2260         }
2261     case HTTP_QUERY_STATUS_TEXT:
2262         if (lpwhr->lpszStatusText)
2263         {
2264             DWORD len = strlenW(lpwhr->lpszStatusText);
2265             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2266             {
2267                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2268                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2269                 return FALSE;
2270             }
2271             memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
2272             *lpdwBufferLength = len * sizeof(WCHAR);
2273
2274             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2275
2276             return TRUE;
2277         }
2278         break;
2279     case HTTP_QUERY_VERSION:
2280         if (lpwhr->lpszVersion)
2281         {
2282             DWORD len = strlenW(lpwhr->lpszVersion);
2283             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2284             {
2285                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2286                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2287                 return FALSE;
2288             }
2289             memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
2290             *lpdwBufferLength = len * sizeof(WCHAR);
2291
2292             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2293
2294             return TRUE;
2295         }
2296         break;
2297     default:
2298         assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2299
2300         if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
2301             index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2302                                               requested_index,request_only);
2303     }
2304
2305     if (index >= 0)
2306         lphttpHdr = &lpwhr->pCustHeaders[index];
2307
2308     /* Ensure header satisfies requested attributes */
2309     if (!lphttpHdr ||
2310         ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2311          (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2312     {
2313         INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2314         return bSuccess;
2315     }
2316
2317     if (lpdwIndex)
2318         (*lpdwIndex)++;
2319
2320     /* coalesce value to requested type */
2321     if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
2322     {
2323         *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2324         bSuccess = TRUE;
2325
2326         TRACE(" returning number : %d\n", *(int *)lpBuffer);
2327     }
2328     else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
2329     {
2330         time_t tmpTime;
2331         struct tm tmpTM;
2332         SYSTEMTIME *STHook;
2333
2334         tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2335
2336         tmpTM = *gmtime(&tmpTime);
2337         STHook = (SYSTEMTIME *) lpBuffer;
2338         if(STHook==NULL)
2339             return bSuccess;
2340
2341         STHook->wDay = tmpTM.tm_mday;
2342         STHook->wHour = tmpTM.tm_hour;
2343         STHook->wMilliseconds = 0;
2344         STHook->wMinute = tmpTM.tm_min;
2345         STHook->wDayOfWeek = tmpTM.tm_wday;
2346         STHook->wMonth = tmpTM.tm_mon + 1;
2347         STHook->wSecond = tmpTM.tm_sec;
2348         STHook->wYear = tmpTM.tm_year;
2349         
2350         bSuccess = TRUE;
2351         
2352         TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n", 
2353               STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2354               STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2355     }
2356     else if (lphttpHdr->lpszValue)
2357     {
2358         DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2359
2360         if (len > *lpdwBufferLength)
2361         {
2362             *lpdwBufferLength = len;
2363             INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2364             return bSuccess;
2365         }
2366
2367         memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2368         *lpdwBufferLength = len - sizeof(WCHAR);
2369         bSuccess = TRUE;
2370
2371         TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
2372     }
2373     return bSuccess;
2374 }
2375
2376 /***********************************************************************
2377  *           HttpQueryInfoW (WININET.@)
2378  *
2379  * Queries for information about an HTTP request
2380  *
2381  * RETURNS
2382  *    TRUE  on success
2383  *    FALSE on failure
2384  *
2385  */
2386 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2387         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2388 {
2389     BOOL bSuccess = FALSE;
2390     LPWININETHTTPREQW lpwhr;
2391
2392     if (TRACE_ON(wininet)) {
2393 #define FE(x) { x, #x }
2394         static const wininet_flag_info query_flags[] = {
2395             FE(HTTP_QUERY_MIME_VERSION),
2396             FE(HTTP_QUERY_CONTENT_TYPE),
2397             FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2398             FE(HTTP_QUERY_CONTENT_ID),
2399             FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2400             FE(HTTP_QUERY_CONTENT_LENGTH),
2401             FE(HTTP_QUERY_CONTENT_LANGUAGE),
2402             FE(HTTP_QUERY_ALLOW),
2403             FE(HTTP_QUERY_PUBLIC),
2404             FE(HTTP_QUERY_DATE),
2405             FE(HTTP_QUERY_EXPIRES),
2406             FE(HTTP_QUERY_LAST_MODIFIED),
2407             FE(HTTP_QUERY_MESSAGE_ID),
2408             FE(HTTP_QUERY_URI),
2409             FE(HTTP_QUERY_DERIVED_FROM),
2410             FE(HTTP_QUERY_COST),
2411             FE(HTTP_QUERY_LINK),
2412             FE(HTTP_QUERY_PRAGMA),
2413             FE(HTTP_QUERY_VERSION),
2414             FE(HTTP_QUERY_STATUS_CODE),
2415             FE(HTTP_QUERY_STATUS_TEXT),
2416             FE(HTTP_QUERY_RAW_HEADERS),
2417             FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2418             FE(HTTP_QUERY_CONNECTION),
2419             FE(HTTP_QUERY_ACCEPT),
2420             FE(HTTP_QUERY_ACCEPT_CHARSET),
2421             FE(HTTP_QUERY_ACCEPT_ENCODING),
2422             FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2423             FE(HTTP_QUERY_AUTHORIZATION),
2424             FE(HTTP_QUERY_CONTENT_ENCODING),
2425             FE(HTTP_QUERY_FORWARDED),
2426             FE(HTTP_QUERY_FROM),
2427             FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2428             FE(HTTP_QUERY_LOCATION),
2429             FE(HTTP_QUERY_ORIG_URI),
2430             FE(HTTP_QUERY_REFERER),
2431             FE(HTTP_QUERY_RETRY_AFTER),
2432             FE(HTTP_QUERY_SERVER),
2433             FE(HTTP_QUERY_TITLE),
2434             FE(HTTP_QUERY_USER_AGENT),
2435             FE(HTTP_QUERY_WWW_AUTHENTICATE),
2436             FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2437             FE(HTTP_QUERY_ACCEPT_RANGES),
2438         FE(HTTP_QUERY_SET_COOKIE),
2439         FE(HTTP_QUERY_COOKIE),
2440             FE(HTTP_QUERY_REQUEST_METHOD),
2441             FE(HTTP_QUERY_REFRESH),
2442             FE(HTTP_QUERY_CONTENT_DISPOSITION),
2443             FE(HTTP_QUERY_AGE),
2444             FE(HTTP_QUERY_CACHE_CONTROL),
2445             FE(HTTP_QUERY_CONTENT_BASE),
2446             FE(HTTP_QUERY_CONTENT_LOCATION),
2447             FE(HTTP_QUERY_CONTENT_MD5),
2448             FE(HTTP_QUERY_CONTENT_RANGE),
2449             FE(HTTP_QUERY_ETAG),
2450             FE(HTTP_QUERY_HOST),
2451             FE(HTTP_QUERY_IF_MATCH),
2452             FE(HTTP_QUERY_IF_NONE_MATCH),
2453             FE(HTTP_QUERY_IF_RANGE),
2454             FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2455             FE(HTTP_QUERY_MAX_FORWARDS),
2456             FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2457             FE(HTTP_QUERY_RANGE),
2458             FE(HTTP_QUERY_TRANSFER_ENCODING),
2459             FE(HTTP_QUERY_UPGRADE),
2460             FE(HTTP_QUERY_VARY),
2461             FE(HTTP_QUERY_VIA),
2462             FE(HTTP_QUERY_WARNING),
2463             FE(HTTP_QUERY_CUSTOM)
2464         };
2465         static const wininet_flag_info modifier_flags[] = {
2466             FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2467             FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2468             FE(HTTP_QUERY_FLAG_NUMBER),
2469             FE(HTTP_QUERY_FLAG_COALESCE)
2470         };
2471 #undef FE
2472         DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2473         DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2474         DWORD i;
2475
2476         TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2477         TRACE("  Attribute:");
2478         for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2479             if (query_flags[i].val == info) {
2480                 TRACE(" %s", query_flags[i].name);
2481                 break;
2482             }
2483         }
2484         if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2485             TRACE(" Unknown (%08x)", info);
2486         }
2487
2488         TRACE(" Modifier:");
2489         for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2490             if (modifier_flags[i].val & info_mod) {
2491                 TRACE(" %s", modifier_flags[i].name);
2492                 info_mod &= ~ modifier_flags[i].val;
2493             }
2494         }
2495         
2496         if (info_mod) {
2497             TRACE(" Unknown (%08x)", info_mod);
2498         }
2499         TRACE("\n");
2500     }
2501     
2502     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2503     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
2504     {
2505         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2506         goto lend;
2507     }
2508
2509     if (lpBuffer == NULL)
2510         *lpdwBufferLength = 0;
2511     bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2512                                     lpBuffer, lpdwBufferLength, lpdwIndex);
2513
2514 lend:
2515     if( lpwhr )
2516          WININET_Release( &lpwhr->hdr );
2517
2518     TRACE("%d <--\n", bSuccess);
2519     return bSuccess;
2520 }
2521
2522 /***********************************************************************
2523  *           HttpQueryInfoA (WININET.@)
2524  *
2525  * Queries for information about an HTTP request
2526  *
2527  * RETURNS
2528  *    TRUE  on success
2529  *    FALSE on failure
2530  *
2531  */
2532 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2533         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2534 {
2535     BOOL result;
2536     DWORD len;
2537     WCHAR* bufferW;
2538
2539     if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2540        (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2541     {
2542         return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2543                                lpdwBufferLength, lpdwIndex );
2544     }
2545
2546     if (lpBuffer)
2547     {
2548         DWORD alloclen;
2549         len = (*lpdwBufferLength)*sizeof(WCHAR);
2550         if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2551         {
2552             alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2553             if (alloclen < len)
2554                 alloclen = len;
2555         }
2556         else
2557             alloclen = len;
2558         bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2559         /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2560         if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2561             MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2562     } else
2563     {
2564         bufferW = NULL;
2565         len = 0;
2566     }
2567
2568     result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2569                            &len, lpdwIndex );
2570     if( result )
2571     {
2572         len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2573                                      lpBuffer, *lpdwBufferLength, NULL, NULL );
2574         *lpdwBufferLength = len - 1;
2575
2576         TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2577     }
2578     else
2579         /* since the strings being returned from HttpQueryInfoW should be
2580          * only ASCII characters, it is reasonable to assume that all of
2581          * the Unicode characters can be reduced to a single byte */
2582         *lpdwBufferLength = len / sizeof(WCHAR);
2583
2584     HeapFree(GetProcessHeap(), 0, bufferW );
2585
2586     return result;
2587 }
2588
2589 /***********************************************************************
2590  *           HttpSendRequestExA (WININET.@)
2591  *
2592  * Sends the specified request to the HTTP server and allows chunked
2593  * transfers.
2594  *
2595  * RETURNS
2596  *  Success: TRUE
2597  *  Failure: FALSE, call GetLastError() for more information.
2598  */
2599 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2600                                LPINTERNET_BUFFERSA lpBuffersIn,
2601                                LPINTERNET_BUFFERSA lpBuffersOut,
2602                                DWORD dwFlags, DWORD_PTR dwContext)
2603 {
2604     INTERNET_BUFFERSW BuffersInW;
2605     BOOL rc = FALSE;
2606     DWORD headerlen;
2607     LPWSTR header = NULL;
2608
2609     TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2610             lpBuffersOut, dwFlags, dwContext);
2611
2612     if (lpBuffersIn)
2613     {
2614         BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2615         if (lpBuffersIn->lpcszHeader)
2616         {
2617             headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2618                     lpBuffersIn->dwHeadersLength,0,0);
2619             header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2620             if (!(BuffersInW.lpcszHeader = header))
2621             {
2622                 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2623                 return FALSE;
2624             }
2625             BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2626                     lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2627                     header, headerlen);
2628         }
2629         else
2630             BuffersInW.lpcszHeader = NULL;
2631         BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2632         BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2633         BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2634         BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2635         BuffersInW.Next = NULL;
2636     }
2637
2638     rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2639
2640     HeapFree(GetProcessHeap(),0,header);
2641
2642     return rc;
2643 }
2644
2645 /***********************************************************************
2646  *           HttpSendRequestExW (WININET.@)
2647  *
2648  * Sends the specified request to the HTTP server and allows chunked
2649  * transfers
2650  *
2651  * RETURNS
2652  *  Success: TRUE
2653  *  Failure: FALSE, call GetLastError() for more information.
2654  */
2655 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2656                    LPINTERNET_BUFFERSW lpBuffersIn,
2657                    LPINTERNET_BUFFERSW lpBuffersOut,
2658                    DWORD dwFlags, DWORD_PTR dwContext)
2659 {
2660     BOOL ret = FALSE;
2661     LPWININETHTTPREQW lpwhr;
2662     LPWININETHTTPSESSIONW lpwhs;
2663     LPWININETAPPINFOW hIC;
2664
2665     TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2666             lpBuffersOut, dwFlags, dwContext);
2667
2668     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2669
2670     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2671     {
2672         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2673         goto lend;
2674     }
2675
2676     lpwhs = lpwhr->lpHttpSession;
2677     assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2678     hIC = lpwhs->lpAppInfo;
2679     assert(hIC->hdr.htype == WH_HINIT);
2680
2681     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2682     {
2683         WORKREQUEST workRequest;
2684         struct WORKREQ_HTTPSENDREQUESTW *req;
2685
2686         workRequest.asyncproc = AsyncHttpSendRequestProc;
2687         workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2688         req = &workRequest.u.HttpSendRequestW;
2689         if (lpBuffersIn)
2690         {
2691             if (lpBuffersIn->lpcszHeader)
2692                 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2693                 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2694             else
2695                 req->lpszHeader = NULL;
2696             req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2697             req->lpOptional = lpBuffersIn->lpvBuffer;
2698             req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2699             req->dwContentLength = lpBuffersIn->dwBufferTotal;
2700         }
2701         else
2702         {
2703             req->lpszHeader = NULL;
2704             req->dwHeaderLength = 0;
2705             req->lpOptional = NULL;
2706             req->dwOptionalLength = 0;
2707             req->dwContentLength = 0;
2708         }
2709
2710         req->bEndRequest = FALSE;
2711
2712         INTERNET_AsyncCall(&workRequest);
2713         /*
2714          * This is from windows.
2715          */
2716         INTERNET_SetLastError(ERROR_IO_PENDING);
2717     }
2718     else
2719     {
2720         if (lpBuffersIn)
2721             ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2722                                         lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2723                                         lpBuffersIn->dwBufferTotal, FALSE);
2724         else
2725             ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2726     }
2727
2728 lend:
2729     if ( lpwhr )
2730         WININET_Release( &lpwhr->hdr );
2731
2732     TRACE("<---\n");
2733     return ret;
2734 }
2735
2736 /***********************************************************************
2737  *           HttpSendRequestW (WININET.@)
2738  *
2739  * Sends the specified request to the HTTP server
2740  *
2741  * RETURNS
2742  *    TRUE  on success
2743  *    FALSE on failure
2744  *
2745  */
2746 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2747         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2748 {
2749     LPWININETHTTPREQW lpwhr;
2750     LPWININETHTTPSESSIONW lpwhs = NULL;
2751     LPWININETAPPINFOW hIC = NULL;
2752     BOOL r;
2753
2754     TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2755             debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2756
2757     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2758     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2759     {
2760         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2761         r = FALSE;
2762         goto lend;
2763     }
2764
2765     lpwhs = lpwhr->lpHttpSession;
2766     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
2767     {
2768         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2769         r = FALSE;
2770         goto lend;
2771     }
2772
2773     hIC = lpwhs->lpAppInfo;
2774     if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT)
2775     {
2776         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2777         r = FALSE;
2778         goto lend;
2779     }
2780
2781     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2782     {
2783         WORKREQUEST workRequest;
2784         struct WORKREQ_HTTPSENDREQUESTW *req;
2785
2786         workRequest.asyncproc = AsyncHttpSendRequestProc;
2787         workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2788         req = &workRequest.u.HttpSendRequestW;
2789         if (lpszHeaders)
2790         {
2791             req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2792             memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2793         }
2794         else
2795             req->lpszHeader = 0;
2796         req->dwHeaderLength = dwHeaderLength;
2797         req->lpOptional = lpOptional;
2798         req->dwOptionalLength = dwOptionalLength;
2799         req->dwContentLength = dwOptionalLength;
2800         req->bEndRequest = TRUE;
2801
2802         INTERNET_AsyncCall(&workRequest);
2803         /*
2804          * This is from windows.
2805          */
2806         INTERNET_SetLastError(ERROR_IO_PENDING);
2807         r = FALSE;
2808     }
2809     else
2810     {
2811         r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2812                 dwHeaderLength, lpOptional, dwOptionalLength,
2813                 dwOptionalLength, TRUE);
2814     }
2815 lend:
2816     if( lpwhr )
2817         WININET_Release( &lpwhr->hdr );
2818     return r;
2819 }
2820
2821 /***********************************************************************
2822  *           HttpSendRequestA (WININET.@)
2823  *
2824  * Sends the specified request to the HTTP server
2825  *
2826  * RETURNS
2827  *    TRUE  on success
2828  *    FALSE on failure
2829  *
2830  */
2831 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2832         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2833 {
2834     BOOL result;
2835     LPWSTR szHeaders=NULL;
2836     DWORD nLen=dwHeaderLength;
2837     if(lpszHeaders!=NULL)
2838     {
2839         nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2840         szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2841         MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2842     }
2843     result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2844     HeapFree(GetProcessHeap(),0,szHeaders);
2845     return result;
2846 }
2847
2848 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2849 {
2850     LPHTTPHEADERW host_header;
2851
2852     static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2853
2854     host_header = HTTP_GetHeader(req, szHost);
2855     if(!host_header)
2856         return FALSE;
2857
2858     sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2859     return TRUE;
2860 }
2861
2862 /***********************************************************************
2863  *           HTTP_HandleRedirect (internal)
2864  */
2865 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2866 {
2867     static const WCHAR szContentType[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
2868     static const WCHAR szContentLength[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
2869     LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2870     LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2871     BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2872     WCHAR path[INTERNET_MAX_URL_LENGTH];
2873     int index;
2874
2875     if(lpszUrl[0]=='/')
2876     {
2877         /* if it's an absolute path, keep the same session info */
2878         lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2879     }
2880     else
2881     {
2882         URL_COMPONENTSW urlComponents;
2883         WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2884         static WCHAR szHttp[] = {'h','t','t','p',0};
2885         static WCHAR szHttps[] = {'h','t','t','p','s',0};
2886         DWORD url_length = 0;
2887         LPWSTR orig_url;
2888         LPWSTR combined_url;
2889
2890         urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2891         urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2892         urlComponents.dwSchemeLength = 0;
2893         urlComponents.lpszHostName = lpwhs->lpszHostName;
2894         urlComponents.dwHostNameLength = 0;
2895         urlComponents.nPort = lpwhs->nHostPort;
2896         urlComponents.lpszUserName = lpwhs->lpszUserName;
2897         urlComponents.dwUserNameLength = 0;
2898         urlComponents.lpszPassword = NULL;
2899         urlComponents.dwPasswordLength = 0;
2900         urlComponents.lpszUrlPath = lpwhr->lpszPath;
2901         urlComponents.dwUrlPathLength = 0;
2902         urlComponents.lpszExtraInfo = NULL;
2903         urlComponents.dwExtraInfoLength = 0;
2904
2905         if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2906             (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2907             return FALSE;
2908
2909         orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2910
2911         /* convert from bytes to characters */
2912         url_length = url_length / sizeof(WCHAR) - 1;
2913         if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2914         {
2915             HeapFree(GetProcessHeap(), 0, orig_url);
2916             return FALSE;
2917         }
2918
2919         url_length = 0;
2920         if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2921             (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2922         {
2923             HeapFree(GetProcessHeap(), 0, orig_url);
2924             return FALSE;
2925         }
2926         combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2927
2928         if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2929         {
2930             HeapFree(GetProcessHeap(), 0, orig_url);
2931             HeapFree(GetProcessHeap(), 0, combined_url);
2932             return FALSE;
2933         }
2934         HeapFree(GetProcessHeap(), 0, orig_url);
2935
2936         userName[0] = 0;
2937         hostName[0] = 0;
2938         protocol[0] = 0;
2939
2940         urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2941         urlComponents.lpszScheme = protocol;
2942         urlComponents.dwSchemeLength = 32;
2943         urlComponents.lpszHostName = hostName;
2944         urlComponents.dwHostNameLength = MAXHOSTNAME;
2945         urlComponents.lpszUserName = userName;
2946         urlComponents.dwUserNameLength = 1024;
2947         urlComponents.lpszPassword = NULL;
2948         urlComponents.dwPasswordLength = 0;
2949         urlComponents.lpszUrlPath = path;
2950         urlComponents.dwUrlPathLength = 2048;
2951         urlComponents.lpszExtraInfo = NULL;
2952         urlComponents.dwExtraInfoLength = 0;
2953         if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2954         {
2955             HeapFree(GetProcessHeap(), 0, combined_url);
2956             return FALSE;
2957         }
2958
2959         HeapFree(GetProcessHeap(), 0, combined_url);
2960
2961         if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2962             (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2963         {
2964             TRACE("redirect from secure page to non-secure page\n");
2965             /* FIXME: warn about from secure redirect to non-secure page */
2966             lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2967         }
2968         if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2969             !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2970         {
2971             TRACE("redirect from non-secure page to secure page\n");
2972             /* FIXME: notify about redirect to secure page */
2973             lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2974         }
2975
2976         if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2977         {
2978             if (lstrlenW(protocol)>4) /*https*/
2979                 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2980             else /*http*/
2981                 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2982         }
2983
2984 #if 0
2985         /*
2986          * This upsets redirects to binary files on sourceforge.net 
2987          * and gives an html page instead of the target file
2988          * Examination of the HTTP request sent by native wininet.dll
2989          * reveals that it doesn't send a referrer in that case.
2990          * Maybe there's a flag that enables this, or maybe a referrer
2991          * shouldn't be added in case of a redirect.
2992          */
2993
2994         /* consider the current host as the referrer */
2995         if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2996             HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2997                            HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2998                            HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2999 #endif
3000         
3001         HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3002         if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3003             urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3004         {
3005             int len;
3006             static const WCHAR fmt[] = {'%','s',':','%','i',0};
3007             len = lstrlenW(hostName);
3008             len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3009             lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3010             sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3011         }
3012         else
3013             lpwhs->lpszHostName = WININET_strdupW(hostName);
3014
3015         HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3016
3017         HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3018         lpwhs->lpszUserName = NULL;
3019         if (userName[0])
3020             lpwhs->lpszUserName = WININET_strdupW(userName);
3021
3022         if (!using_proxy)
3023         {
3024             HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3025             lpwhs->lpszServerName = WININET_strdupW(hostName);
3026             lpwhs->nServerPort = urlComponents.nPort;
3027
3028             if (!HTTP_ResolveName(lpwhr))
3029                 return FALSE;
3030
3031             NETCON_close(&lpwhr->netConnection);
3032
3033             if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3034                 return FALSE;
3035         }
3036         else
3037             TRACE("Redirect through proxy\n");
3038     }
3039
3040     HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3041     lpwhr->lpszPath=NULL;
3042     if (*path)
3043     {
3044         DWORD needed = 0;
3045         HRESULT rc;
3046
3047         rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3048         if (rc != E_POINTER)
3049             needed = strlenW(path)+1;
3050         lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3051         rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3052                         URL_ESCAPE_SPACES_ONLY);
3053         if (rc)
3054         {
3055             ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3056             strcpyW(lpwhr->lpszPath,path);
3057         }
3058     }
3059
3060     /* Remove custom content-type/length headers on redirects.  */
3061     index = HTTP_GetCustomHeaderIndex(lpwhr, szContentType, 0, TRUE);
3062     if (0 <= index)
3063         HTTP_DeleteCustomHeader(lpwhr, index);
3064     index = HTTP_GetCustomHeaderIndex(lpwhr, szContentLength, 0, TRUE);
3065     if (0 <= index)
3066         HTTP_DeleteCustomHeader(lpwhr, index);
3067
3068     return TRUE;
3069 }
3070
3071 /***********************************************************************
3072  *           HTTP_build_req (internal)
3073  *
3074  *  concatenate all the strings in the request together
3075  */
3076 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3077 {
3078     LPCWSTR *t;
3079     LPWSTR str;
3080
3081     for( t = list; *t ; t++  )
3082         len += strlenW( *t );
3083     len++;
3084
3085     str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3086     *str = 0;
3087
3088     for( t = list; *t ; t++ )
3089         strcatW( str, *t );
3090
3091     return str;
3092 }
3093
3094 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3095 {
3096     LPWSTR lpszPath;
3097     LPWSTR requestString;
3098     INT len;
3099     INT cnt;
3100     INT responseLen;
3101     char *ascii_req;
3102     BOOL ret;
3103     static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3104     static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3105     LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3106
3107     TRACE("\n");
3108
3109     lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3110     sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3111     requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3112     HeapFree( GetProcessHeap(), 0, lpszPath );
3113
3114     len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3115                                 NULL, 0, NULL, NULL );
3116     len--; /* the nul terminator isn't needed */
3117     ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3118     WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3119                             ascii_req, len, NULL, NULL );
3120     HeapFree( GetProcessHeap(), 0, requestString );
3121
3122     TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3123
3124     ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3125     HeapFree( GetProcessHeap(), 0, ascii_req );
3126     if (!ret || cnt < 0)
3127         return FALSE;
3128
3129     responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3130     if (!responseLen)
3131         return FALSE;
3132
3133     return TRUE;
3134 }
3135
3136 /***********************************************************************
3137  *           HTTP_HttpSendRequestW (internal)
3138  *
3139  * Sends the specified request to the HTTP server
3140  *
3141  * RETURNS
3142  *    TRUE  on success
3143  *    FALSE on failure
3144  *
3145  */
3146 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3147         DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3148         DWORD dwContentLength, BOOL bEndRequest)
3149 {
3150     INT cnt;
3151     BOOL bSuccess = FALSE;
3152     LPWSTR requestString = NULL;
3153     INT responseLen;
3154     BOOL loop_next;
3155     INTERNET_ASYNC_RESULT iar;
3156     static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
3157     static const WCHAR szPost[] = { 'P','O','S','T',0 };
3158     static const WCHAR szContentLength[] =
3159         { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3160     WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3161
3162     TRACE("--> %p\n", lpwhr);
3163
3164     assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3165
3166     /* Clear any error information */
3167     INTERNET_SetLastError(0);
3168
3169     /* if the verb is NULL default to GET */
3170     if (!lpwhr->lpszVerb)
3171         lpwhr->lpszVerb = WININET_strdupW(szGET);
3172
3173     if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
3174     {
3175         sprintfW(contentLengthStr, szContentLength, dwContentLength);
3176         HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3177     }
3178
3179     do
3180     {
3181         DWORD len;
3182         char *ascii_req;
3183
3184         loop_next = FALSE;
3185
3186         /* like native, just in case the caller forgot to call InternetReadFile
3187          * for all the data */
3188         HTTP_DrainContent(lpwhr);
3189         lpwhr->dwContentRead = 0;
3190
3191         if (TRACE_ON(wininet))
3192         {
3193             LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3194             TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3195         }
3196
3197         HTTP_FixURL(lpwhr);
3198         HTTP_ProcessHeader(lpwhr, szConnection,
3199                            lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
3200                            HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3201
3202         HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3203         HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3204
3205         /* add the headers the caller supplied */
3206         if( lpszHeaders && dwHeaderLength )
3207         {
3208             HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3209                         HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3210         }
3211
3212         if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3213         {
3214             WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3215             requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3216             HeapFree(GetProcessHeap(), 0, url);
3217         }
3218         else
3219             requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3220
3221  
3222         TRACE("Request header -> %s\n", debugstr_w(requestString) );
3223
3224         /* Send the request and store the results */
3225         if (!HTTP_OpenConnection(lpwhr))
3226             goto lend;
3227
3228         /* send the request as ASCII, tack on the optional data */
3229         if( !lpOptional )
3230             dwOptionalLength = 0;
3231         len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3232                                    NULL, 0, NULL, NULL );
3233         ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3234         WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3235                              ascii_req, len, NULL, NULL );
3236         if( lpOptional )
3237             memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3238         len = (len + dwOptionalLength - 1);
3239         ascii_req[len] = 0;
3240         TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3241
3242         INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3243                               INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3244
3245         NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3246         HeapFree( GetProcessHeap(), 0, ascii_req );
3247
3248         INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3249                               INTERNET_STATUS_REQUEST_SENT,
3250                               &len, sizeof(DWORD));
3251
3252         if (bEndRequest)
3253         {
3254             DWORD dwBufferSize;
3255             DWORD dwStatusCode;
3256             WCHAR encoding[20];
3257             static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3258
3259             INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3260                                 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3261     
3262             if (cnt < 0)
3263                 goto lend;
3264     
3265             responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3266             if (responseLen)
3267                 bSuccess = TRUE;
3268     
3269             INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3270                                 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3271                                 sizeof(DWORD));
3272
3273             HTTP_ProcessCookies(lpwhr);
3274
3275             dwBufferSize = sizeof(lpwhr->dwContentLength);
3276             if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3277                                      &lpwhr->dwContentLength,&dwBufferSize,NULL))
3278                 lpwhr->dwContentLength = -1;
3279
3280             if (lpwhr->dwContentLength == 0)
3281                 HTTP_FinishedReading(lpwhr);
3282
3283             /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3284
3285             dwBufferSize = sizeof(encoding);
3286             if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3287                 !strcmpiW(encoding, szChunked))
3288             {
3289                 lpwhr->dwContentLength = -1;
3290             }
3291
3292             dwBufferSize = sizeof(dwStatusCode);
3293             if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3294                                      &dwStatusCode,&dwBufferSize,NULL))
3295                 dwStatusCode = 0;
3296
3297             if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3298             {
3299                 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3300                 dwBufferSize=sizeof(szNewLocation);
3301                 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3302                     HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3303                 {
3304                     HTTP_DrainContent(lpwhr);
3305                     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3306                                           INTERNET_STATUS_REDIRECT, szNewLocation,
3307                                           dwBufferSize);
3308                     bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3309                     if (bSuccess)
3310                     {
3311                         HeapFree(GetProcessHeap(), 0, requestString);
3312                         loop_next = TRUE;
3313                     }
3314                 }
3315             }
3316             if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3317             {
3318                 WCHAR szAuthValue[2048];
3319                 dwBufferSize=2048;
3320                 if (dwStatusCode == HTTP_STATUS_DENIED)
3321                 {
3322                     DWORD dwIndex = 0;
3323                     while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3324                     {
3325                         if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3326                                                  &lpwhr->pAuthInfo,
3327                                                  lpwhr->lpHttpSession->lpszUserName,
3328                                                  lpwhr->lpHttpSession->lpszPassword))
3329                         {
3330                             loop_next = TRUE;
3331                             break;
3332                         }
3333                     }
3334                 }
3335                 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3336                 {
3337                     DWORD dwIndex = 0;
3338                     while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3339                     {
3340                         if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3341                                                  &lpwhr->pProxyAuthInfo,
3342                                                  lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3343                                                  lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3344                         {
3345                             loop_next = TRUE;
3346                             break;
3347                         }
3348                     }
3349                 }
3350             }
3351         }
3352         else
3353             bSuccess = TRUE;
3354     }
3355     while (loop_next);
3356
3357     /* FIXME: Better check, when we have to create the cache file */
3358     if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3359         WCHAR url[INTERNET_MAX_URL_LENGTH];
3360         WCHAR cacheFileName[MAX_PATH+1];
3361         BOOL b;
3362
3363         b = HTTP_GetRequestURL(lpwhr, url);
3364         if(!b) {
3365             WARN("Could not get URL\n");
3366             goto lend;
3367         }
3368
3369         b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3370         if(b) {
3371             lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3372             lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3373                       NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3374             if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3375                 WARN("Could not create file: %u\n", GetLastError());
3376                 lpwhr->hCacheFile = NULL;
3377             }
3378         }else {
3379             WARN("Could not create cache entry: %08x\n", GetLastError());
3380         }
3381     }
3382
3383 lend:
3384
3385     HeapFree(GetProcessHeap(), 0, requestString);
3386
3387     /* TODO: send notification for P3P header */
3388
3389     iar.dwResult = (DWORD)bSuccess;
3390     iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
3391
3392     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3393                           INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3394                           sizeof(INTERNET_ASYNC_RESULT));
3395
3396     TRACE("<--\n");
3397     return bSuccess;
3398 }
3399
3400 /***********************************************************************
3401  *           HTTPSESSION_Destroy (internal)
3402  *
3403  * Deallocate session handle
3404  *
3405  */
3406 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3407 {
3408     LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3409
3410     TRACE("%p\n", lpwhs);
3411
3412     WININET_Release(&lpwhs->lpAppInfo->hdr);
3413
3414     HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3415     HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3416     HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3417     HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3418     HeapFree(GetProcessHeap(), 0, lpwhs);
3419 }
3420
3421 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3422 {
3423     switch(option) {
3424     case INTERNET_OPTION_HANDLE_TYPE:
3425         TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3426
3427         if (*size < sizeof(ULONG))
3428             return ERROR_INSUFFICIENT_BUFFER;
3429
3430         *size = sizeof(DWORD);
3431         *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3432         return ERROR_SUCCESS;
3433     }
3434
3435     FIXME("Not implemented option %d\n", option);
3436     return ERROR_INTERNET_INVALID_OPTION;
3437 }
3438
3439 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3440     HTTPSESSION_Destroy,
3441     NULL,
3442     HTTPSESSION_QueryOption,
3443     NULL,
3444     NULL,
3445     NULL,
3446     NULL,
3447     NULL,
3448     NULL
3449 };
3450
3451
3452 /***********************************************************************
3453  *           HTTP_Connect  (internal)
3454  *
3455  * Create http session handle
3456  *
3457  * RETURNS
3458  *   HINTERNET a session handle on success
3459  *   NULL on failure
3460  *
3461  */
3462 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3463         INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3464         LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3465         DWORD dwInternalFlags)
3466 {
3467     BOOL bSuccess = FALSE;
3468     LPWININETHTTPSESSIONW lpwhs = NULL;
3469     HINTERNET handle = NULL;
3470
3471     TRACE("-->\n");
3472
3473     if (!lpszServerName || !lpszServerName[0])
3474     {
3475         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3476         goto lerror;
3477     }
3478
3479     assert( hIC->hdr.htype == WH_HINIT );
3480
3481     lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3482     if (NULL == lpwhs)
3483     {
3484         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3485         goto lerror;
3486     }
3487
3488    /*
3489     * According to my tests. The name is not resolved until a request is sent
3490     */
3491
3492     lpwhs->hdr.htype = WH_HHTTPSESSION;
3493     lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3494     lpwhs->hdr.dwFlags = dwFlags;
3495     lpwhs->hdr.dwContext = dwContext;
3496     lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3497     lpwhs->hdr.refs = 1;
3498     lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3499
3500     WININET_AddRef( &hIC->hdr );
3501     lpwhs->lpAppInfo = hIC;
3502     list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3503
3504     handle = WININET_AllocHandle( &lpwhs->hdr );
3505     if (NULL == handle)
3506     {
3507         ERR("Failed to alloc handle\n");
3508         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3509         goto lerror;
3510     }
3511
3512     if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3513         if(strchrW(hIC->lpszProxy, ' '))
3514             FIXME("Several proxies not implemented.\n");
3515         if(hIC->lpszProxyBypass)
3516             FIXME("Proxy bypass is ignored.\n");
3517     }
3518     if (lpszServerName && lpszServerName[0])
3519     {
3520         lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3521         lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3522     }
3523     if (lpszUserName && lpszUserName[0])
3524         lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3525     if (lpszPassword && lpszPassword[0])
3526         lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3527     lpwhs->nServerPort = nServerPort;
3528     lpwhs->nHostPort = nServerPort;
3529
3530     /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3531     if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3532     {
3533         INTERNET_SendCallback(&hIC->hdr, dwContext,
3534                               INTERNET_STATUS_HANDLE_CREATED, &handle,
3535                               sizeof(handle));
3536     }
3537
3538     bSuccess = TRUE;
3539
3540 lerror:
3541     if( lpwhs )
3542         WININET_Release( &lpwhs->hdr );
3543
3544 /*
3545  * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3546  * windows
3547  */
3548
3549     TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3550     return handle;
3551 }
3552
3553
3554 /***********************************************************************
3555  *           HTTP_OpenConnection (internal)
3556  *
3557  * Connect to a web server
3558  *
3559  * RETURNS
3560  *
3561  *   TRUE  on success
3562  *   FALSE on failure
3563  */
3564 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3565 {
3566     BOOL bSuccess = FALSE;
3567     LPWININETHTTPSESSIONW lpwhs;
3568     LPWININETAPPINFOW hIC = NULL;
3569     char szaddr[32];
3570
3571     TRACE("-->\n");
3572
3573
3574     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
3575     {
3576         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3577         goto lend;
3578     }
3579
3580     if (NETCON_connected(&lpwhr->netConnection))
3581     {
3582         bSuccess = TRUE;
3583         goto lend;
3584     }
3585
3586     lpwhs = lpwhr->lpHttpSession;
3587
3588     hIC = lpwhs->lpAppInfo;
3589     inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3590               szaddr, sizeof(szaddr));
3591     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3592                           INTERNET_STATUS_CONNECTING_TO_SERVER,
3593                           szaddr,
3594                           strlen(szaddr)+1);
3595
3596     if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3597                          SOCK_STREAM, 0))
3598     {
3599         WARN("Socket creation failed\n");
3600         goto lend;
3601     }
3602
3603     if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3604                       sizeof(lpwhs->socketAddress)))
3605        goto lend;
3606
3607     if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3608     {
3609         /* Note: we differ from Microsoft's WinINet here. they seem to have
3610          * a bug that causes no status callbacks to be sent when starting
3611          * a tunnel to a proxy server using the CONNECT verb. i believe our
3612          * behaviour to be more correct and to not cause any incompatibilities
3613          * because using a secure connection through a proxy server is a rare
3614          * case that would be hard for anyone to depend on */
3615         if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3616             goto lend;
3617
3618         if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3619         {
3620             WARN("Couldn't connect securely to host\n");
3621             goto lend;
3622         }
3623     }
3624
3625     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3626                           INTERNET_STATUS_CONNECTED_TO_SERVER,
3627                           szaddr, strlen(szaddr)+1);
3628
3629     bSuccess = TRUE;
3630
3631 lend:
3632     TRACE("%d <--\n", bSuccess);
3633     return bSuccess;
3634 }
3635
3636
3637 /***********************************************************************
3638  *           HTTP_clear_response_headers (internal)
3639  *
3640  * clear out any old response headers
3641  */
3642 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3643 {
3644     DWORD i;
3645
3646     for( i=0; i<lpwhr->nCustHeaders; i++)
3647     {
3648         if( !lpwhr->pCustHeaders[i].lpszField )
3649             continue;
3650         if( !lpwhr->pCustHeaders[i].lpszValue )
3651             continue;
3652         if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3653             continue;
3654         HTTP_DeleteCustomHeader( lpwhr, i );
3655         i--;
3656     }
3657 }
3658
3659 /***********************************************************************
3660  *           HTTP_GetResponseHeaders (internal)
3661  *
3662  * Read server response
3663  *
3664  * RETURNS
3665  *
3666  *   TRUE  on success
3667  *   FALSE on error
3668  */
3669 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3670 {
3671     INT cbreaks = 0;
3672     WCHAR buffer[MAX_REPLY_LEN];
3673     DWORD buflen = MAX_REPLY_LEN;
3674     BOOL bSuccess = FALSE;
3675     INT  rc = 0;
3676     static const WCHAR szCrLf[] = {'\r','\n',0};
3677     static const WCHAR szHundred[] = {'1','0','0',0};
3678     char bufferA[MAX_REPLY_LEN];
3679     LPWSTR status_code, status_text;
3680     DWORD cchMaxRawHeaders = 1024;
3681     LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3682     DWORD cchRawHeaders = 0;
3683
3684     TRACE("-->\n");
3685
3686     /* clear old response headers (eg. from a redirect response) */
3687     if (clear) HTTP_clear_response_headers( lpwhr );
3688
3689     if (!NETCON_connected(&lpwhr->netConnection))
3690         goto lend;
3691
3692     do {
3693         /*
3694          * HACK peek at the buffer
3695          */
3696         buflen = MAX_REPLY_LEN;
3697         NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3698
3699         /*
3700          * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3701          */
3702         memset(buffer, 0, MAX_REPLY_LEN);
3703         if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3704             goto lend;
3705         MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3706
3707         /* split the version from the status code */
3708         status_code = strchrW( buffer, ' ' );
3709         if( !status_code )
3710             goto lend;
3711         *status_code++=0;
3712
3713         /* split the status code from the status text */
3714         status_text = strchrW( status_code, ' ' );
3715         if( !status_text )
3716             goto lend;
3717         *status_text++=0;
3718
3719         TRACE("version [%s] status code [%s] status text [%s]\n",
3720            debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3721
3722     } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3723
3724     /* Add status code */
3725     HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3726             HTTP_ADDHDR_FLAG_REPLACE);
3727
3728     HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3729     HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3730
3731     lpwhr->lpszVersion= WININET_strdupW(buffer);
3732     lpwhr->lpszStatusText = WININET_strdupW(status_text);
3733
3734     /* Restore the spaces */
3735     *(status_code-1) = ' ';
3736     *(status_text-1) = ' ';
3737
3738     /* regenerate raw headers */
3739     while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3740     {
3741         cchMaxRawHeaders *= 2;
3742         lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3743     }
3744     memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3745     cchRawHeaders += (buflen-1);
3746     memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3747     cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3748     lpszRawHeaders[cchRawHeaders] = '\0';
3749
3750     /* Parse each response line */
3751     do
3752     {
3753         buflen = MAX_REPLY_LEN;
3754         if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3755         {
3756             LPWSTR * pFieldAndValue;
3757
3758             TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3759             MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3760
3761             while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3762             {
3763                 cchMaxRawHeaders *= 2;
3764                 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3765             }
3766             memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3767             cchRawHeaders += (buflen-1);
3768             memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3769             cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3770             lpszRawHeaders[cchRawHeaders] = '\0';
3771
3772             pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3773             if (!pFieldAndValue)
3774                 break;
3775
3776             HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1], 
3777                 HTTP_ADDREQ_FLAG_ADD );
3778
3779             HTTP_FreeTokens(pFieldAndValue);
3780         }
3781         else
3782         {
3783             cbreaks++;
3784             if (cbreaks >= 2)
3785                break;
3786         }
3787     }while(1);
3788
3789     HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3790     lpwhr->lpszRawHeaders = lpszRawHeaders;
3791     TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3792     bSuccess = TRUE;
3793
3794 lend:
3795
3796     TRACE("<--\n");
3797     if (bSuccess)
3798         return rc;
3799     else
3800         return 0;
3801 }
3802
3803
3804 static void strip_spaces(LPWSTR start)
3805 {
3806     LPWSTR str = start;
3807     LPWSTR end;
3808
3809     while (*str == ' ' && *str != '\0')
3810         str++;
3811
3812     if (str != start)
3813         memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3814
3815     end = start + strlenW(start) - 1;
3816     while (end >= start && *end == ' ')
3817     {
3818         *end = '\0';
3819         end--;
3820     }
3821 }
3822
3823
3824 /***********************************************************************
3825  *           HTTP_InterpretHttpHeader (internal)
3826  *
3827  * Parse server response
3828  *
3829  * RETURNS
3830  *
3831  *   Pointer to array of field, value, NULL on success.
3832  *   NULL on error.
3833  */
3834 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3835 {
3836     LPWSTR * pTokenPair;
3837     LPWSTR pszColon;
3838     INT len;
3839
3840     pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3841
3842     pszColon = strchrW(buffer, ':');
3843     /* must have two tokens */
3844     if (!pszColon)
3845     {
3846         HTTP_FreeTokens(pTokenPair);
3847         if (buffer[0])
3848             TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3849         return NULL;
3850     }
3851
3852     pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3853     if (!pTokenPair[0])
3854     {
3855         HTTP_FreeTokens(pTokenPair);
3856         return NULL;
3857     }
3858     memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3859     pTokenPair[0][pszColon - buffer] = '\0';
3860
3861     /* skip colon */
3862     pszColon++;
3863     len = strlenW(pszColon);
3864     pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3865     if (!pTokenPair[1])
3866     {
3867         HTTP_FreeTokens(pTokenPair);
3868         return NULL;
3869     }
3870     memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3871
3872     strip_spaces(pTokenPair[0]);
3873     strip_spaces(pTokenPair[1]);
3874
3875     TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3876     return pTokenPair;
3877 }
3878
3879 /***********************************************************************
3880  *           HTTP_ProcessHeader (internal)
3881  *
3882  * Stuff header into header tables according to <dwModifier>
3883  *
3884  */
3885
3886 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3887
3888 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3889 {
3890     LPHTTPHEADERW lphttpHdr = NULL;
3891     BOOL bSuccess = FALSE;
3892     INT index = -1;
3893     BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3894
3895     TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3896
3897     /* REPLACE wins out over ADD */
3898     if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3899         dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3900     
3901     if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3902         index = -1;
3903     else
3904         index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3905
3906     if (index >= 0)
3907     {
3908         if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3909         {
3910             return FALSE;
3911         }
3912         lphttpHdr = &lpwhr->pCustHeaders[index];
3913     }
3914     else if (value)
3915     {
3916         HTTPHEADERW hdr;
3917
3918         hdr.lpszField = (LPWSTR)field;
3919         hdr.lpszValue = (LPWSTR)value;
3920         hdr.wFlags = hdr.wCount = 0;
3921
3922         if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3923             hdr.wFlags |= HDR_ISREQUEST;
3924
3925         return HTTP_InsertCustomHeader(lpwhr, &hdr);
3926     }
3927     /* no value to delete */
3928     else return TRUE;
3929
3930     if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3931             lphttpHdr->wFlags |= HDR_ISREQUEST;
3932     else
3933         lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3934
3935     if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3936     {
3937         HTTP_DeleteCustomHeader( lpwhr, index );
3938
3939         if (value)
3940         {
3941             HTTPHEADERW hdr;
3942
3943             hdr.lpszField = (LPWSTR)field;
3944             hdr.lpszValue = (LPWSTR)value;
3945             hdr.wFlags = hdr.wCount = 0;
3946
3947             if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3948                 hdr.wFlags |= HDR_ISREQUEST;
3949
3950             return HTTP_InsertCustomHeader(lpwhr, &hdr);
3951         }
3952
3953         return TRUE;
3954     }
3955     else if (dwModifier & COALESCEFLAGS)
3956     {
3957         LPWSTR lpsztmp;
3958         WCHAR ch = 0;
3959         INT len = 0;
3960         INT origlen = strlenW(lphttpHdr->lpszValue);
3961         INT valuelen = strlenW(value);
3962
3963         if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3964         {
3965             ch = ',';
3966             lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3967         }
3968         else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3969         {
3970             ch = ';';
3971             lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3972         }
3973
3974         len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3975
3976         lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3977         if (lpsztmp)
3978         {
3979             lphttpHdr->lpszValue = lpsztmp;
3980     /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3981             if (ch > 0)
3982             {
3983                 lphttpHdr->lpszValue[origlen] = ch;
3984                 origlen++;
3985                 lphttpHdr->lpszValue[origlen] = ' ';
3986                 origlen++;
3987             }
3988
3989             memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3990             lphttpHdr->lpszValue[len] = '\0';
3991             bSuccess = TRUE;
3992         }
3993         else
3994         {
3995             WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3996             INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3997         }
3998     }
3999     TRACE("<-- %d\n",bSuccess);
4000     return bSuccess;
4001 }
4002
4003
4004 /***********************************************************************
4005  *           HTTP_FinishedReading (internal)
4006  *
4007  * Called when all content from server has been read by client.
4008  *
4009  */
4010 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4011 {
4012     WCHAR szVersion[10];
4013     DWORD dwBufferSize = sizeof(szVersion);
4014
4015     TRACE("\n");
4016
4017     /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4018      * the connection is keep-alive by default */
4019     if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4020                              &dwBufferSize, NULL) ||
4021         strcmpiW(szVersion, g_szHttp1_1))
4022     {
4023         WCHAR szConnectionResponse[20];
4024         dwBufferSize = sizeof(szConnectionResponse);
4025         if ((!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4026              strcmpiW(szConnectionResponse, szKeepAlive)) &&
4027             (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4028              strcmpiW(szConnectionResponse, szKeepAlive)))
4029         {
4030             HTTPREQ_CloseConnection(&lpwhr->hdr);
4031         }
4032     }
4033
4034     /* FIXME: store data in the URL cache here */
4035
4036     return TRUE;
4037 }
4038
4039
4040 /***********************************************************************
4041  *           HTTP_GetCustomHeaderIndex (internal)
4042  *
4043  * Return index of custom header from header array
4044  *
4045  */
4046 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4047                                      int requested_index, BOOL request_only)
4048 {
4049     DWORD index;
4050
4051     TRACE("%s\n", debugstr_w(lpszField));
4052
4053     for (index = 0; index < lpwhr->nCustHeaders; index++)
4054     {
4055         if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4056             continue;
4057
4058         if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4059             continue;
4060
4061         if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4062             continue;
4063
4064         if (requested_index == 0)
4065             break;
4066         requested_index --;
4067     }
4068
4069     if (index >= lpwhr->nCustHeaders)
4070         index = -1;
4071
4072     TRACE("Return: %d\n", index);
4073     return index;
4074 }
4075
4076
4077 /***********************************************************************
4078  *           HTTP_InsertCustomHeader (internal)
4079  *
4080  * Insert header into array
4081  *
4082  */
4083 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4084 {
4085     INT count;
4086     LPHTTPHEADERW lph = NULL;
4087     BOOL r = FALSE;
4088
4089     TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4090     count = lpwhr->nCustHeaders + 1;
4091     if (count > 1)
4092         lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4093     else
4094         lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4095
4096     if (NULL != lph)
4097     {
4098         lpwhr->pCustHeaders = lph;
4099         lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4100         lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4101         lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4102         lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4103         lpwhr->nCustHeaders++;
4104         r = TRUE;
4105     }
4106     else
4107     {
4108         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4109     }
4110
4111     return r;
4112 }
4113
4114
4115 /***********************************************************************
4116  *           HTTP_DeleteCustomHeader (internal)
4117  *
4118  * Delete header from array
4119  *  If this function is called, the indexs may change.
4120  */
4121 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4122 {
4123     if( lpwhr->nCustHeaders <= 0 )
4124         return FALSE;
4125     if( index >= lpwhr->nCustHeaders )
4126         return FALSE;
4127     lpwhr->nCustHeaders--;
4128
4129     memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4130              (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4131     memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4132
4133     return TRUE;
4134 }
4135
4136
4137 /***********************************************************************
4138  *           HTTP_VerifyValidHeader (internal)
4139  *
4140  * Verify the given header is not invalid for the given http request
4141  *
4142  */
4143 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4144 {
4145     /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4146     if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4147         return FALSE;
4148
4149     return TRUE;
4150 }
4151
4152 /***********************************************************************
4153  *          IsHostInProxyBypassList (@)
4154  *
4155  * Undocumented
4156  *
4157  */
4158 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4159 {
4160    FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4161    return FALSE;
4162 }