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