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