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