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