wininet: Don't duplicate empty strings.
[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  *
10  * Ulrich Czekalla
11  * David Hammerton
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Lesser General Public
15  * License as published by the Free Software Foundation; either
16  * version 2.1 of the License, or (at your option) any later version.
17  *
18  * This library is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public
24  * License along with this library; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26  */
27
28 #include "config.h"
29 #include "wine/port.h"
30
31 #include <sys/types.h>
32 #ifdef HAVE_SYS_SOCKET_H
33 # include <sys/socket.h>
34 #endif
35 #ifdef HAVE_ARPA_INET_H
36 # include <arpa/inet.h>
37 #endif
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #ifdef HAVE_UNISTD_H
42 # include <unistd.h>
43 #endif
44 #include <time.h>
45 #include <assert.h>
46
47 #include "windef.h"
48 #include "winbase.h"
49 #include "wininet.h"
50 #include "winreg.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
58 #include "internet.h"
59 #include "wine/debug.h"
60 #include "wine/unicode.h"
61
62 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
63
64 static const WCHAR g_szHttp1_0[] = {' ','H','T','T','P','/','1','.','0',0 };
65 static const WCHAR g_szHttp1_1[] = {' ','H','T','T','P','/','1','.','1',0 };
66 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
67 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
68 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
69 static const WCHAR szHost[] = { 'H','o','s','t',0 };
70 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
71 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
72
73 #define MAXHOSTNAME 100
74 #define MAX_FIELD_VALUE_LEN 256
75 #define MAX_FIELD_LEN 256
76
77 #define HTTP_REFERER    g_szReferer
78 #define HTTP_ACCEPT     g_szAccept
79 #define HTTP_USERAGENT  g_szUserAgent
80
81 #define HTTP_ADDHDR_FLAG_ADD                            0x20000000
82 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW                     0x10000000
83 #define HTTP_ADDHDR_FLAG_COALESCE                       0x40000000
84 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA            0x40000000
85 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON        0x01000000
86 #define HTTP_ADDHDR_FLAG_REPLACE                        0x80000000
87 #define HTTP_ADDHDR_FLAG_REQ                            0x02000000
88
89
90 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr);
91 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr);
92 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
93 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr);
94 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
95 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
96 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
97 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
98 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
99 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
100 static BOOL HTTP_InsertProxyAuthorization( LPWININETHTTPREQW lpwhr,
101                        LPCWSTR username, LPCWSTR password );
102 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
103         dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
104         lpdwIndex);
105 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl,
106         LPCWSTR lpszHeaders, DWORD dwHeaderLength, LPVOID lpOptional, DWORD
107         dwOptionalLength, DWORD dwContentLength);
108
109
110 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
111 {
112     int HeaderIndex = 0;
113     HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
114     if (HeaderIndex == -1)
115         return NULL;
116     else
117         return &req->pCustHeaders[HeaderIndex];
118 }
119
120 /***********************************************************************
121  *           HTTP_Tokenize (internal)
122  *
123  *  Tokenize a string, allocating memory for the tokens.
124  */
125 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
126 {
127     LPWSTR * token_array;
128     int tokens = 0;
129     int i;
130     LPCWSTR next_token;
131
132     /* empty string has no tokens */
133     if (*string)
134         tokens++;
135     /* count tokens */
136     for (i = 0; string[i]; i++)
137         if (!strncmpW(string+i, token_string, strlenW(token_string)))
138         {
139             DWORD j;
140             tokens++;
141             /* we want to skip over separators, but not the null terminator */
142             for (j = 0; j < strlenW(token_string) - 1; j++)
143                 if (!string[i+j])
144                     break;
145             i += j;
146         }
147
148     /* add 1 for terminating NULL */
149     token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
150     token_array[tokens] = NULL;
151     if (!tokens)
152         return token_array;
153     for (i = 0; i < tokens; i++)
154     {
155         int len;
156         next_token = strstrW(string, token_string);
157         if (!next_token) next_token = string+strlenW(string);
158         len = next_token - string;
159         token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
160         memcpy(token_array[i], string, len*sizeof(WCHAR));
161         token_array[i][len] = '\0';
162         string = next_token+strlenW(token_string);
163     }
164     return token_array;
165 }
166
167 /***********************************************************************
168  *           HTTP_FreeTokens (internal)
169  *
170  *  Frees memory returned from HTTP_Tokenize.
171  */
172 static void HTTP_FreeTokens(LPWSTR * token_array)
173 {
174     int i;
175     for (i = 0; token_array[i]; i++)
176         HeapFree(GetProcessHeap(), 0, token_array[i]);
177     HeapFree(GetProcessHeap(), 0, token_array);
178 }
179
180 /* **********************************************************************
181  * 
182  * Helper functions for the HttpSendRequest(Ex) functions
183  * 
184  */
185 static void HTTP_FixVerb( LPWININETHTTPREQW lpwhr )
186 {
187     /* if the verb is NULL default to GET */
188     if (NULL == lpwhr->lpszVerb)
189     {
190             static const WCHAR szGET[] = { 'G','E','T', 0 };
191             lpwhr->lpszVerb = WININET_strdupW(szGET);
192     }
193 }
194
195 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
196 {
197     static const WCHAR szSlash[] = { '/',0 };
198     static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
199
200     /* If we don't have a path we set it to root */
201     if (NULL == lpwhr->lpszPath)
202         lpwhr->lpszPath = WININET_strdupW(szSlash);
203     else /* remove \r and \n*/
204     {
205         int nLen = strlenW(lpwhr->lpszPath);
206         while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
207         {
208             nLen--;
209             lpwhr->lpszPath[nLen]='\0';
210         }
211         /* Replace '\' with '/' */
212         while (nLen>0) {
213             nLen--;
214             if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
215         }
216     }
217
218     if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
219                        lpwhr->lpszPath, strlenW(szHttp), szHttp, strlenW(szHttp) )
220        && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
221     {
222         WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0, 
223                              (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
224         *fixurl = '/';
225         strcpyW(fixurl + 1, lpwhr->lpszPath);
226         HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
227         lpwhr->lpszPath = fixurl;
228     }
229 }
230
231 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, BOOL http1_1 )
232 {
233     LPWSTR requestString;
234     DWORD len, n;
235     LPCWSTR *req;
236     INT i;
237     LPWSTR p;
238
239     static const WCHAR szSpace[] = { ' ',0 };
240     static const WCHAR szcrlf[] = {'\r','\n', 0};
241     static const WCHAR szColon[] = { ':',' ',0 };
242     static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
243
244     /* allocate space for an array of all the string pointers to be added */
245     len = (lpwhr->nCustHeaders)*4 + 9;
246     req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
247
248     /* add the verb, path and HTTP version string */
249     n = 0;
250     req[n++] = verb;
251     req[n++] = szSpace;
252     req[n++] = path;
253     req[n++] = http1_1 ? g_szHttp1_1 : g_szHttp1_0;
254
255     /* Append custom request heades */
256     for (i = 0; i < lpwhr->nCustHeaders; i++)
257     {
258         if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
259         {
260             req[n++] = szcrlf;
261             req[n++] = lpwhr->pCustHeaders[i].lpszField;
262             req[n++] = szColon;
263             req[n++] = lpwhr->pCustHeaders[i].lpszValue;
264
265             TRACE("Adding custom header %s (%s)\n",
266                    debugstr_w(lpwhr->pCustHeaders[i].lpszField),
267                    debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
268         }
269     }
270
271     if( n >= len )
272         ERR("oops. buffer overrun\n");
273
274     req[n] = NULL;
275     requestString = HTTP_build_req( req, 4 );
276     HeapFree( GetProcessHeap(), 0, req );
277
278     /*
279      * Set (header) termination string for request
280      * Make sure there's exactly two new lines at the end of the request
281      */
282     p = &requestString[strlenW(requestString)-1];
283     while ( (*p == '\n') || (*p == '\r') )
284        p--;
285     strcpyW( p+1, sztwocrlf );
286     
287     return requestString;
288 }
289
290 static void HTTP_ProcessHeaders( LPWININETHTTPREQW lpwhr )
291 {
292     static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
293     int HeaderIndex;
294     LPHTTPHEADERW setCookieHeader;
295
296     HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
297     if (HeaderIndex == -1)
298             return;
299     setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
300
301     if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
302     {
303         int nPosStart = 0, nPosEnd = 0, len;
304         static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
305
306         while (setCookieHeader->lpszValue[nPosEnd] != '\0')
307         {
308             LPWSTR buf_cookie, cookie_name, cookie_data;
309             LPWSTR buf_url;
310             LPWSTR domain = NULL;
311             LPHTTPHEADERW Host;
312
313             int nEqualPos = 0;
314             while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
315                    setCookieHeader->lpszValue[nPosEnd] != '\0')
316             {
317                 nPosEnd++;
318             }
319             if (setCookieHeader->lpszValue[nPosEnd] == ';')
320             {
321                 /* fixme: not case sensitive, strcasestr is gnu only */
322                 int nDomainPosEnd = 0;
323                 int nDomainPosStart = 0, nDomainLength = 0;
324                 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
325                 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
326                 if (lpszDomain)
327                 { /* they have specified their own domain, lets use it */
328                     while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
329                            lpszDomain[nDomainPosEnd] != '\0')
330                     {
331                         nDomainPosEnd++;
332                     }
333                     nDomainPosStart = strlenW(szDomain);
334                     nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
335                     domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
336                     lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
337                 }
338             }
339             if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
340             buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
341             lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
342             TRACE("%s\n", debugstr_w(buf_cookie));
343             while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
344             {
345                 nEqualPos++;
346             }
347             if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
348             {
349                 HeapFree(GetProcessHeap(), 0, buf_cookie);
350                 break;
351             }
352
353             cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
354             lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
355             cookie_data = &buf_cookie[nEqualPos + 1];
356
357             Host = HTTP_GetHeader(lpwhr,szHost);
358             len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) + 
359                 strlenW(lpwhr->lpszPath) + 9;
360             buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
361             sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
362             InternetSetCookieW(buf_url, cookie_name, cookie_data);
363
364             HeapFree(GetProcessHeap(), 0, buf_url);
365             HeapFree(GetProcessHeap(), 0, buf_cookie);
366             HeapFree(GetProcessHeap(), 0, cookie_name);
367             HeapFree(GetProcessHeap(), 0, domain);
368             nPosStart = nPosEnd;
369         }
370     }
371 }
372
373 static void HTTP_AddProxyInfo( LPWININETHTTPREQW lpwhr )
374 {
375     LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW)lpwhr->hdr.lpwhparent;
376     LPWININETAPPINFOW hIC = (LPWININETAPPINFOW)lpwhs->hdr.lpwhparent;
377
378     assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
379     assert(hIC->hdr.htype == WH_HINIT);
380
381     if (hIC && (hIC->lpszProxyUsername || hIC->lpszProxyPassword ))
382         HTTP_InsertProxyAuthorization(lpwhr, hIC->lpszProxyUsername,
383                 hIC->lpszProxyPassword);
384 }
385
386 /***********************************************************************
387  *           HTTP_HttpAddRequestHeadersW (internal)
388  */
389 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
390         LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
391 {
392     LPWSTR lpszStart;
393     LPWSTR lpszEnd;
394     LPWSTR buffer;
395     BOOL bSuccess = FALSE;
396     DWORD len;
397
398     TRACE("copying header: %s\n", debugstr_w(lpszHeader));
399
400     if( dwHeaderLength == ~0U )
401         len = strlenW(lpszHeader);
402     else
403         len = dwHeaderLength;
404     buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
405     lstrcpynW( buffer, lpszHeader, len + 1);
406
407     lpszStart = buffer;
408
409     do
410     {
411         LPWSTR * pFieldAndValue;
412
413         lpszEnd = lpszStart;
414
415         while (*lpszEnd != '\0')
416         {
417             if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
418                  break;
419             lpszEnd++;
420         }
421
422         if (*lpszStart == '\0')
423             break;
424
425         if (*lpszEnd == '\r')
426         {
427             *lpszEnd = '\0';
428             lpszEnd += 2; /* Jump over \r\n */
429         }
430         TRACE("interpreting header %s\n", debugstr_w(lpszStart));
431         pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
432         if (pFieldAndValue)
433         {
434             bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
435                 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
436             HTTP_FreeTokens(pFieldAndValue);
437         }
438
439         lpszStart = lpszEnd;
440     } while (bSuccess);
441
442     HeapFree(GetProcessHeap(), 0, buffer);
443
444     return bSuccess;
445 }
446
447 /***********************************************************************
448  *           HttpAddRequestHeadersW (WININET.@)
449  *
450  * Adds one or more HTTP header to the request handler
451  *
452  * RETURNS
453  *    TRUE  on success
454  *    FALSE on failure
455  *
456  */
457 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
458         LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
459 {
460     BOOL bSuccess = FALSE;
461     LPWININETHTTPREQW lpwhr;
462
463     TRACE("%p, %s, %li, %li\n", hHttpRequest, debugstr_w(lpszHeader), dwHeaderLength,
464           dwModifier);
465
466     if (!lpszHeader) 
467       return TRUE;
468
469     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
470     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
471     {
472         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
473         goto lend;
474     }
475     bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
476 lend:
477     if( lpwhr )
478         WININET_Release( &lpwhr->hdr );
479
480     return bSuccess;
481 }
482
483 /***********************************************************************
484  *           HttpAddRequestHeadersA (WININET.@)
485  *
486  * Adds one or more HTTP header to the request handler
487  *
488  * RETURNS
489  *    TRUE  on success
490  *    FALSE on failure
491  *
492  */
493 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
494         LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
495 {
496     DWORD len;
497     LPWSTR hdr;
498     BOOL r;
499
500     TRACE("%p, %s, %li, %li\n", hHttpRequest, debugstr_a(lpszHeader), dwHeaderLength,
501           dwModifier);
502
503     len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
504     hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
505     MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
506     if( dwHeaderLength != ~0U )
507         dwHeaderLength = len;
508
509     r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
510
511     HeapFree( GetProcessHeap(), 0, hdr );
512
513     return r;
514 }
515
516 /***********************************************************************
517  *           HttpEndRequestA (WININET.@)
518  *
519  * Ends an HTTP request that was started by HttpSendRequestEx
520  *
521  * RETURNS
522  *    TRUE      if successful
523  *    FALSE     on failure
524  *
525  */
526 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest, 
527         LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD dwContext)
528 {
529     LPINTERNET_BUFFERSA ptr;
530     LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
531     BOOL rc = FALSE;
532
533     TRACE("(%p, %p, %08lx, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
534             dwContext);
535
536     ptr = lpBuffersOut;
537     if (ptr)
538         lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
539                 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
540     else
541         lpBuffersOutW = NULL;
542
543     ptrW = lpBuffersOutW;
544     while (ptr)
545     {
546         if (ptr->lpvBuffer && ptr->dwBufferLength)
547             ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
548         ptrW->dwBufferLength = ptr->dwBufferLength;
549         ptrW->dwBufferTotal= ptr->dwBufferTotal;
550
551         if (ptr->Next)
552             ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
553                     sizeof(INTERNET_BUFFERSW));
554
555         ptr = ptr->Next;
556         ptrW = ptrW->Next;
557     }
558
559     rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
560
561     if (lpBuffersOutW)
562     {
563         ptrW = lpBuffersOutW;
564         while (ptrW)
565         {
566             LPINTERNET_BUFFERSW ptrW2;
567
568             FIXME("Do we need to translate info out of these buffer?\n");
569
570             HeapFree(GetProcessHeap(),0,(LPVOID)ptrW->lpvBuffer);
571             ptrW2 = ptrW->Next;
572             HeapFree(GetProcessHeap(),0,ptrW);
573             ptrW = ptrW2;
574         }
575     }
576
577     return rc;
578 }
579
580 /***********************************************************************
581  *           HttpEndRequestW (WININET.@)
582  *
583  * Ends an HTTP request that was started by HttpSendRequestEx
584  *
585  * RETURNS
586  *    TRUE      if successful
587  *    FALSE     on failure
588  *
589  */
590 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest, 
591         LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD dwContext)
592 {
593     BOOL rc = FALSE;
594     LPWININETHTTPREQW lpwhr;
595     INT responseLen;
596
597     TRACE("-->\n");
598     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
599
600     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
601     {
602         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
603         return FALSE;
604     }
605
606     lpwhr->hdr.dwFlags |= dwFlags;
607     lpwhr->hdr.dwContext = dwContext;
608
609     SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
610             INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
611
612     responseLen = HTTP_GetResponseHeaders(lpwhr);
613     if (responseLen)
614             rc = TRUE;
615
616     SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
617             INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
618
619     /* process headers here. Is this right? */
620     HTTP_ProcessHeaders(lpwhr);
621
622     /* We appear to do nothing with the buffer.. is that correct? */
623
624     if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
625     {
626         DWORD dwCode,dwCodeLength=sizeof(DWORD),dwIndex=0;
627         if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,&dwIndex) &&
628             (dwCode==302 || dwCode==301))
629         {
630             WCHAR szNewLocation[2048];
631             DWORD dwBufferSize=2048;
632             dwIndex=0;
633             if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,&dwIndex))
634             {
635                     static const WCHAR szGET[] = { 'G','E','T', 0 };
636                 /* redirects are always GETs */
637                 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
638                     lpwhr->lpszVerb = WININET_strdupW(szGET);
639                 return HTTP_HandleRedirect(lpwhr, szNewLocation, NULL, 0, NULL, 0, 0);
640             }
641         }
642     }
643
644     TRACE("%i <--\n",rc);
645     return rc;
646 }
647
648 /***********************************************************************
649  *           HttpOpenRequestW (WININET.@)
650  *
651  * Open a HTTP request handle
652  *
653  * RETURNS
654  *    HINTERNET  a HTTP request handle on success
655  *    NULL       on failure
656  *
657  */
658 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
659         LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
660         LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
661         DWORD dwFlags, DWORD dwContext)
662 {
663     LPWININETHTTPSESSIONW lpwhs;
664     HINTERNET handle = NULL;
665
666     TRACE("(%p, %s, %s, %s, %s, %p, %08lx, %08lx)\n", hHttpSession,
667           debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
668           debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
669           dwFlags, dwContext);
670     if(lpszAcceptTypes!=NULL)
671     {
672         int i;
673         for(i=0;lpszAcceptTypes[i]!=NULL;i++)
674             TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
675     }    
676
677     lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
678     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
679     {
680         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
681         goto lend;
682     }
683
684     /*
685      * My tests seem to show that the windows version does not
686      * become asynchronous until after this point. And anyhow
687      * if this call was asynchronous then how would you get the
688      * necessary HINTERNET pointer returned by this function.
689      *
690      */
691     handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
692                                    lpszVersion, lpszReferrer, lpszAcceptTypes,
693                                    dwFlags, dwContext);
694 lend:
695     if( lpwhs )
696         WININET_Release( &lpwhs->hdr );
697     TRACE("returning %p\n", handle);
698     return handle;
699 }
700
701
702 /***********************************************************************
703  *           HttpOpenRequestA (WININET.@)
704  *
705  * Open a HTTP request handle
706  *
707  * RETURNS
708  *    HINTERNET  a HTTP request handle on success
709  *    NULL       on failure
710  *
711  */
712 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
713         LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
714         LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
715         DWORD dwFlags, DWORD dwContext)
716 {
717     LPWSTR szVerb = NULL, szObjectName = NULL;
718     LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
719     INT len;
720     INT acceptTypesCount;
721     HINTERNET rc = FALSE;
722     TRACE("(%p, %s, %s, %s, %s, %p, %08lx, %08lx)\n", hHttpSession,
723           debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
724           debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
725           dwFlags, dwContext);
726
727     if (lpszVerb)
728     {
729         len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
730         szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
731         if ( !szVerb )
732             goto end;
733         MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
734     }
735
736     if (lpszObjectName)
737     {
738         len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
739         szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
740         if ( !szObjectName )
741             goto end;
742         MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
743     }
744
745     if (lpszVersion)
746     {
747         len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
748         szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
749         if ( !szVersion )
750             goto end;
751         MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
752     }
753
754     if (lpszReferrer)
755     {
756         len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
757         szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
758         if ( !szReferrer )
759             goto end;
760         MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
761     }
762
763     acceptTypesCount = 0;
764     if (lpszAcceptTypes)
765     {
766         /* find out how many there are */
767         while (lpszAcceptTypes[acceptTypesCount]) 
768             acceptTypesCount++;
769         szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
770         acceptTypesCount = 0;
771         while (lpszAcceptTypes[acceptTypesCount])
772         {
773             len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
774                                 -1, NULL, 0 );
775             szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
776             if (!szAcceptTypes[acceptTypesCount] )
777                 goto end;
778             MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
779                                 -1, szAcceptTypes[acceptTypesCount], len );
780             acceptTypesCount++;
781         }
782         szAcceptTypes[acceptTypesCount] = NULL;
783     }
784     else szAcceptTypes = 0;
785
786     rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
787                           szVersion, szReferrer,
788                           (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
789
790 end:
791     if (szAcceptTypes)
792     {
793         acceptTypesCount = 0;
794         while (szAcceptTypes[acceptTypesCount])
795         {
796             HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
797             acceptTypesCount++;
798         }
799         HeapFree(GetProcessHeap(), 0, szAcceptTypes);
800     }
801     HeapFree(GetProcessHeap(), 0, szReferrer);
802     HeapFree(GetProcessHeap(), 0, szVersion);
803     HeapFree(GetProcessHeap(), 0, szObjectName);
804     HeapFree(GetProcessHeap(), 0, szVerb);
805
806     return rc;
807 }
808
809 /***********************************************************************
810  *  HTTP_Base64
811  */
812 static UINT HTTP_Base64( LPCWSTR bin, LPWSTR base64 )
813 {
814     UINT n = 0, x;
815     static LPCSTR HTTP_Base64Enc = 
816         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
817
818     while( bin[0] )
819     {
820         /* first 6 bits, all from bin[0] */
821         base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
822         x = (bin[0] & 3) << 4;
823
824         /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
825         if( !bin[1] )
826         {
827             base64[n++] = HTTP_Base64Enc[x];
828             base64[n++] = '=';
829             base64[n++] = '=';
830             break;
831         }
832         base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
833         x = ( bin[1] & 0x0f ) << 2;
834
835         /* next 6 bits 4 from bin[1] and 2 from bin[2] */
836         if( !bin[2] )
837         {
838             base64[n++] = HTTP_Base64Enc[x];
839             base64[n++] = '=';
840             break;
841         }
842         base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
843
844         /* last 6 bits, all from bin [2] */
845         base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
846         bin += 3;
847     }
848     base64[n] = 0;
849     return n;
850 }
851
852 /***********************************************************************
853  *  HTTP_EncodeBasicAuth
854  *
855  *  Encode the basic authentication string for HTTP 1.1
856  */
857 static LPWSTR HTTP_EncodeBasicAuth( LPCWSTR username, LPCWSTR password)
858 {
859     UINT len;
860     LPWSTR in, out;
861     static const WCHAR szBasic[] = {'B','a','s','i','c',' ',0};
862     static const WCHAR szColon[] = {':',0};
863
864     len = lstrlenW( username ) + 1 + lstrlenW ( password ) + 1;
865     in = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
866     if( !in )
867         return NULL;
868
869     len = lstrlenW(szBasic) +
870           (lstrlenW( username ) + 1 + lstrlenW ( password ))*2 + 1 + 1;
871     out = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
872     if( out )
873     {
874         lstrcpyW( in, username );
875         lstrcatW( in, szColon );
876         lstrcatW( in, password );
877         lstrcpyW( out, szBasic );
878         HTTP_Base64( in, &out[strlenW(out)] );
879     }
880     HeapFree( GetProcessHeap(), 0, in );
881
882     return out;
883 }
884
885 /***********************************************************************
886  *  HTTP_InsertProxyAuthorization
887  *
888  *   Insert the basic authorization field in the request header
889  */
890 static BOOL HTTP_InsertProxyAuthorization( LPWININETHTTPREQW lpwhr,
891                        LPCWSTR username, LPCWSTR password )
892 {
893     WCHAR *authorization = HTTP_EncodeBasicAuth( username, password );
894     BOOL ret = TRUE;
895
896     if (!authorization)
897         return FALSE;
898
899     TRACE( "Inserting authorization: %s\n", debugstr_w( authorization ) );
900
901     HTTP_ProcessHeader(lpwhr, szProxy_Authorization, authorization,
902             HTTP_ADDHDR_FLAG_REPLACE);
903
904     HeapFree( GetProcessHeap(), 0, authorization );
905     
906     return ret;
907 }
908
909 /***********************************************************************
910  *           HTTP_DealWithProxy
911  */
912 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
913     LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
914 {
915     WCHAR buf[MAXHOSTNAME];
916     WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
917     WCHAR* url;
918     static const WCHAR szNul[] = { 0 };
919     URL_COMPONENTSW UrlComponents;
920     static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
921     static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
922     static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
923     int len;
924
925     memset( &UrlComponents, 0, sizeof UrlComponents );
926     UrlComponents.dwStructSize = sizeof UrlComponents;
927     UrlComponents.lpszHostName = buf;
928     UrlComponents.dwHostNameLength = MAXHOSTNAME;
929
930     if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
931                                  hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
932         sprintfW(proxy, szFormat1, hIC->lpszProxy);
933     else
934         strcpyW(proxy, hIC->lpszProxy);
935     if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
936         return FALSE;
937     if( UrlComponents.dwHostNameLength == 0 )
938         return FALSE;
939
940     if( !lpwhr->lpszPath )
941         lpwhr->lpszPath = (LPWSTR)szNul;
942     TRACE("server='%s' path='%s'\n",
943           debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
944     /* for constant 15 see above */
945     len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
946     url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
947
948     if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
949         UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
950
951     sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
952
953     if( lpwhr->lpszPath[0] != '/' )
954         strcatW( url, szSlash );
955     strcatW(url, lpwhr->lpszPath);
956     if(lpwhr->lpszPath != szNul)
957         HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
958     lpwhr->lpszPath = url;
959
960     HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
961     lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
962     lpwhs->nServerPort = UrlComponents.nPort;
963
964     return TRUE;
965 }
966
967 /***********************************************************************
968  *           HTTP_HttpOpenRequestW (internal)
969  *
970  * Open a HTTP request handle
971  *
972  * RETURNS
973  *    HINTERNET  a HTTP request handle on success
974  *    NULL       on failure
975  *
976  */
977 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
978         LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
979         LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
980         DWORD dwFlags, DWORD dwContext)
981 {
982     LPWININETAPPINFOW hIC = NULL;
983     LPWININETHTTPREQW lpwhr;
984     LPWSTR lpszCookies;
985     LPWSTR lpszUrl = NULL;
986     DWORD nCookieSize;
987     HINTERNET handle = NULL;
988     static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
989     DWORD len;
990     LPHTTPHEADERW Host;
991     char szaddr[32];
992
993     TRACE("-->\n");
994
995     assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
996     hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
997
998     lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
999     if (NULL == lpwhr)
1000     {
1001         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1002         goto lend;
1003     }
1004     lpwhr->hdr.htype = WH_HHTTPREQ;
1005     lpwhr->hdr.lpwhparent = WININET_AddRef( &lpwhs->hdr );
1006     lpwhr->hdr.dwFlags = dwFlags;
1007     lpwhr->hdr.dwContext = dwContext;
1008     lpwhr->hdr.dwRefCount = 1;
1009     lpwhr->hdr.destroy = HTTP_CloseHTTPRequestHandle;
1010     lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1011
1012     handle = WININET_AllocHandle( &lpwhr->hdr );
1013     if (NULL == handle)
1014     {
1015         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1016         goto lend;
1017     }
1018
1019     if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1020     {
1021         InternetCloseHandle( handle );
1022         handle = NULL;
1023         goto lend;
1024     }
1025
1026     if (NULL != lpszObjectName && strlenW(lpszObjectName)) {
1027         HRESULT rc;
1028
1029         len = 0;
1030         rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1031         if (rc != E_POINTER)
1032             len = strlenW(lpszObjectName)+1;
1033         lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1034         rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1035                    URL_ESCAPE_SPACES_ONLY);
1036         if (rc)
1037         {
1038             ERR("Unable to escape string!(%s) (%ld)\n",debugstr_w(lpszObjectName),rc);
1039             strcpyW(lpwhr->lpszPath,lpszObjectName);
1040         }
1041     }
1042
1043     if (NULL != lpszReferrer && strlenW(lpszReferrer))
1044         HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDHDR_FLAG_COALESCE);
1045
1046     if(lpszAcceptTypes!=NULL)
1047     {
1048         int i;
1049         for(i=0;lpszAcceptTypes[i]!=NULL;i++)
1050             HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i], HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_REQ|HTTP_ADDHDR_FLAG_ADD_IF_NEW);
1051     }
1052
1053     if (NULL == lpszVerb)
1054     {
1055         static const WCHAR szGet[] = {'G','E','T',0};
1056         lpwhr->lpszVerb = WININET_strdupW(szGet);
1057     }
1058     else if (strlenW(lpszVerb))
1059         lpwhr->lpszVerb = WININET_strdupW(lpszVerb);
1060
1061     if (NULL != lpszReferrer && strlenW(lpszReferrer))
1062     {
1063         WCHAR buf[MAXHOSTNAME];
1064         URL_COMPONENTSW UrlComponents;
1065
1066         memset( &UrlComponents, 0, sizeof UrlComponents );
1067         UrlComponents.dwStructSize = sizeof UrlComponents;
1068         UrlComponents.lpszHostName = buf;
1069         UrlComponents.dwHostNameLength = MAXHOSTNAME;
1070
1071         InternetCrackUrlW(lpszReferrer, 0, 0, &UrlComponents);
1072         if (strlenW(UrlComponents.lpszHostName))
1073             HTTP_ProcessHeader(lpwhr, szHost, UrlComponents.lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1074     }
1075     else
1076         HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1077
1078     if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1079         lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1080                         INTERNET_DEFAULT_HTTPS_PORT :
1081                         INTERNET_DEFAULT_HTTP_PORT);
1082     lpwhs->nHostPort = lpwhs->nServerPort;
1083
1084     if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1085         HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1086
1087     if (hIC->lpszAgent)
1088     {
1089         WCHAR *agent_header;
1090         static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1091
1092         len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1093         agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1094         sprintfW(agent_header, user_agent, hIC->lpszAgent );
1095
1096         HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1097                                HTTP_ADDREQ_FLAG_ADD);
1098         HeapFree(GetProcessHeap(), 0, agent_header);
1099     }
1100
1101     Host = HTTP_GetHeader(lpwhr,szHost);
1102
1103     len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1104     lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1105     sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1106
1107     if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1108         InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1109     {
1110         int cnt = 0;
1111         static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1112         static const WCHAR szcrlf[] = {'\r','\n',0};
1113
1114         lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1115
1116         cnt += sprintfW(lpszCookies, szCookie);
1117         InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1118         strcatW(lpszCookies, szcrlf);
1119
1120         HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1121                                HTTP_ADDREQ_FLAG_ADD);
1122         HeapFree(GetProcessHeap(), 0, lpszCookies);
1123     }
1124     HeapFree(GetProcessHeap(), 0, lpszUrl);
1125
1126
1127     INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1128                           INTERNET_STATUS_HANDLE_CREATED, &handle,
1129                           sizeof(handle));
1130
1131     /*
1132      * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1133      */
1134
1135     /*
1136      * According to my tests. The name is not resolved until a request is Opened
1137      */
1138     INTERNET_SendCallback(&lpwhr->hdr, dwContext,
1139                           INTERNET_STATUS_RESOLVING_NAME,
1140                           lpwhs->lpszServerName,
1141                           strlenW(lpwhs->lpszServerName)+1);
1142
1143     if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1144                     &lpwhs->socketAddress))
1145     {
1146         INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1147         InternetCloseHandle( handle );
1148         handle = NULL;
1149         goto lend;
1150     }
1151
1152     inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1153               szaddr, sizeof(szaddr));
1154     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1155                           INTERNET_STATUS_NAME_RESOLVED,
1156                           szaddr, strlen(szaddr)+1);
1157
1158 lend:
1159     if( lpwhr )
1160         WININET_Release( &lpwhr->hdr );
1161
1162     TRACE("<-- %p (%p)\n", handle, lpwhr);
1163     return handle;
1164 }
1165
1166 typedef struct std_hdr_data
1167 {
1168         const WCHAR* hdrStr;
1169         INT hdrIndex;
1170 } std_hdr_data;
1171
1172 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1173 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1174 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1175 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1176 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1177 static const WCHAR szAge[] = { 'A','g','e',0 };
1178 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1179 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
1180 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1181 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1182 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1183 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1184 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1185 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1186 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1187 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1188 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1189 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1190 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 };
1191 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1192 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1193 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1194 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1195 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1196 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1197 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1198 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1199 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1200 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1201 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1202 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1203 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1204 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1205 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1206 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1207 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1208 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1209 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1210 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1211 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1212 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1213 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1214 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1215 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1216 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1217 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 };
1218 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1219 static const WCHAR szURI[] = { 'U','R','I',0 };
1220 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1221 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1222 static const WCHAR szVia[] = { 'V','i','a',0 };
1223 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1224 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1225
1226 static const std_hdr_data SORTED_STANDARD_HEADERS[] = {
1227     {szAccept,                  HTTP_QUERY_ACCEPT,},
1228     {szAccept_Charset,          HTTP_QUERY_ACCEPT_CHARSET,},
1229     {szAccept_Encoding,         HTTP_QUERY_ACCEPT_ENCODING,},
1230     {szAccept_Language,         HTTP_QUERY_ACCEPT_LANGUAGE,},
1231     {szAccept_Ranges,           HTTP_QUERY_ACCEPT_RANGES,},
1232     {szAge,                     HTTP_QUERY_AGE,},
1233     {szAllow,                   HTTP_QUERY_ALLOW,},
1234     {szAuthorization,           HTTP_QUERY_AUTHORIZATION,},
1235     {szCache_Control,           HTTP_QUERY_CACHE_CONTROL,},
1236     {szConnection,              HTTP_QUERY_CONNECTION,},
1237     {szContent_Base,            HTTP_QUERY_CONTENT_BASE,},
1238     {szContent_Encoding,        HTTP_QUERY_CONTENT_ENCODING,},
1239     {szContent_ID,              HTTP_QUERY_CONTENT_ID,},
1240     {szContent_Language,        HTTP_QUERY_CONTENT_LANGUAGE,},
1241     {szContent_Length,          HTTP_QUERY_CONTENT_LENGTH,},
1242     {szContent_Location,        HTTP_QUERY_CONTENT_LOCATION,},
1243     {szContent_MD5,             HTTP_QUERY_CONTENT_MD5,},
1244     {szContent_Range,           HTTP_QUERY_CONTENT_RANGE,},
1245     {szContent_Transfer_Encoding,HTTP_QUERY_CONTENT_TRANSFER_ENCODING,},
1246     {szContent_Type,            HTTP_QUERY_CONTENT_TYPE,},
1247     {szCookie,                  HTTP_QUERY_COOKIE,},
1248     {szDate,                    HTTP_QUERY_DATE,},
1249     {szETag,                    HTTP_QUERY_ETAG,},
1250     {szExpect,                  HTTP_QUERY_EXPECT,},
1251     {szExpires,                 HTTP_QUERY_EXPIRES,},
1252     {szFrom,                    HTTP_QUERY_DERIVED_FROM,},
1253     {szHost,                    HTTP_QUERY_HOST,},
1254     {szIf_Match,                HTTP_QUERY_IF_MATCH,},
1255     {szIf_Modified_Since,       HTTP_QUERY_IF_MODIFIED_SINCE,},
1256     {szIf_None_Match,           HTTP_QUERY_IF_NONE_MATCH,},
1257     {szIf_Range,                HTTP_QUERY_IF_RANGE,},
1258     {szIf_Unmodified_Since,     HTTP_QUERY_IF_UNMODIFIED_SINCE,},
1259     {szLast_Modified,           HTTP_QUERY_LAST_MODIFIED,},
1260     {szLocation,                HTTP_QUERY_LOCATION,},
1261     {szMax_Forwards,            HTTP_QUERY_MAX_FORWARDS,},
1262     {szMime_Version,            HTTP_QUERY_MIME_VERSION,},
1263     {szPragma,                  HTTP_QUERY_PRAGMA,},
1264     {szProxy_Authenticate,      HTTP_QUERY_PROXY_AUTHENTICATE,},
1265     {szProxy_Authorization,     HTTP_QUERY_PROXY_AUTHORIZATION,},
1266     {szProxy_Connection,        HTTP_QUERY_PROXY_CONNECTION,},
1267     {szPublic,                  HTTP_QUERY_PUBLIC,},
1268     {szRange,                   HTTP_QUERY_RANGE,},
1269     {szReferer,                 HTTP_QUERY_REFERER,},
1270     {szRetry_After,             HTTP_QUERY_RETRY_AFTER,},
1271     {szServer,                  HTTP_QUERY_SERVER,},
1272     {szSet_Cookie,              HTTP_QUERY_SET_COOKIE,},
1273     {szStatus,                  HTTP_QUERY_STATUS_CODE,},
1274     {szTransfer_Encoding,       HTTP_QUERY_TRANSFER_ENCODING,},
1275     {szUnless_Modified_Since,   HTTP_QUERY_UNLESS_MODIFIED_SINCE,},
1276     {szUpgrade,                 HTTP_QUERY_UPGRADE,},
1277     {szURI,                     HTTP_QUERY_URI,},
1278     {szUser_Agent,              HTTP_QUERY_USER_AGENT,},
1279     {szVary,                    HTTP_QUERY_VARY,},
1280     {szVia,                     HTTP_QUERY_VIA,},
1281     {szWarning,                 HTTP_QUERY_WARNING,},
1282     {szWWW_Authenticate,        HTTP_QUERY_WWW_AUTHENTICATE,},
1283 };
1284
1285 /***********************************************************************
1286  *           HTTP_HttpQueryInfoW (internal)
1287  */
1288 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1289         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1290 {
1291     LPHTTPHEADERW lphttpHdr = NULL;
1292     BOOL bSuccess = FALSE;
1293     BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1294
1295
1296     /* Find requested header structure */
1297     if ((dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK) == HTTP_QUERY_CUSTOM)
1298     {
1299         INT requested_index = (lpdwIndex)?(*lpdwIndex):0;
1300         INT index = HTTP_GetCustomHeaderIndex(lpwhr, (LPWSTR)lpBuffer, 
1301                 requested_index,request_only);
1302
1303         if (index < 0)
1304             return bSuccess;
1305         else
1306             lphttpHdr = &lpwhr->pCustHeaders[index];
1307
1308         if (lpdwIndex)
1309             (*lpdwIndex)++;
1310     }
1311     else
1312     {
1313         INT index = dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK;
1314
1315         if (index == HTTP_QUERY_RAW_HEADERS_CRLF)
1316         {
1317             DWORD len = strlenW(lpwhr->lpszRawHeaders);
1318             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1319             {
1320                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1321                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1322                 return FALSE;
1323             }
1324             memcpy(lpBuffer, lpwhr->lpszRawHeaders, (len+1)*sizeof(WCHAR));
1325             *lpdwBufferLength = len * sizeof(WCHAR);
1326
1327             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1328
1329             return TRUE;
1330         }
1331         else if (index == HTTP_QUERY_RAW_HEADERS)
1332         {
1333             static const WCHAR szCrLf[] = {'\r','\n',0};
1334             LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1335             DWORD i, size = 0;
1336             LPWSTR pszString = (WCHAR*)lpBuffer;
1337
1338             for (i = 0; ppszRawHeaderLines[i]; i++)
1339                 size += strlenW(ppszRawHeaderLines[i]) + 1;
1340
1341             if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1342             {
1343                 HTTP_FreeTokens(ppszRawHeaderLines);
1344                 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1345                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1346                 return FALSE;
1347             }
1348
1349             for (i = 0; ppszRawHeaderLines[i]; i++)
1350             {
1351                 DWORD len = strlenW(ppszRawHeaderLines[i]);
1352                 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1353                 pszString += len+1;
1354             }
1355             *pszString = '\0';
1356
1357             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1358
1359             *lpdwBufferLength = size * sizeof(WCHAR);
1360             HTTP_FreeTokens(ppszRawHeaderLines);
1361
1362             return TRUE;
1363         }
1364         else if (index == HTTP_QUERY_STATUS_TEXT)
1365         {
1366             DWORD len = strlenW(lpwhr->lpszStatusText);
1367             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1368             {
1369                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1370                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1371                 return FALSE;
1372             }
1373             memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1374             *lpdwBufferLength = len * sizeof(WCHAR);
1375
1376             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1377
1378             return TRUE;
1379         }
1380         else if (index == HTTP_QUERY_VERSION)
1381         {
1382             DWORD len = strlenW(lpwhr->lpszVersion);
1383             if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1384             {
1385                 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1386                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1387                 return FALSE;
1388             }
1389             memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
1390             *lpdwBufferLength = len * sizeof(WCHAR);
1391
1392             TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1393
1394             return TRUE;
1395         }
1396             else if (index >= 0 && index <= HTTP_QUERY_MAX )
1397             {
1398             int i;
1399             for (i = 0; i <  sizeof(SORTED_STANDARD_HEADERS)/sizeof(std_hdr_data) ; i++)
1400             {
1401                 if (SORTED_STANDARD_HEADERS[i].hdrIndex == index)
1402                 {
1403                     INT requested_index = (lpdwIndex)?(*lpdwIndex):0;
1404                     INT index = HTTP_GetCustomHeaderIndex(lpwhr,
1405                             (LPWSTR)SORTED_STANDARD_HEADERS[i].hdrStr,
1406                             requested_index,request_only);
1407
1408                     if (index < 0)
1409                         return bSuccess;
1410                     else
1411                         lphttpHdr = &lpwhr->pCustHeaders[index];
1412
1413                     if (lpdwIndex)
1414                         (*lpdwIndex)++;
1415
1416                     break;
1417                 }
1418             }
1419
1420             if (!lphttpHdr)
1421             {
1422                 SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1423                 return bSuccess;
1424             }
1425             }
1426             else
1427         {
1428             SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1429             return bSuccess;
1430         }
1431     }
1432
1433     /* Ensure header satisifies requested attributes */
1434     if ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
1435             (~lphttpHdr->wFlags & HDR_ISREQUEST))
1436     {
1437         SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1438         return bSuccess;
1439     }
1440
1441     /* coalesce value to reuqested type */
1442     if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
1443     {
1444         *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
1445         bSuccess = TRUE;
1446
1447         TRACE(" returning number : %d\n", *(int *)lpBuffer);
1448     }
1449     else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
1450     {
1451         time_t tmpTime;
1452         struct tm tmpTM;
1453         SYSTEMTIME *STHook;
1454
1455         tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
1456
1457         tmpTM = *gmtime(&tmpTime);
1458         STHook = (SYSTEMTIME *) lpBuffer;
1459         if(STHook==NULL)
1460             return bSuccess;
1461
1462         STHook->wDay = tmpTM.tm_mday;
1463         STHook->wHour = tmpTM.tm_hour;
1464         STHook->wMilliseconds = 0;
1465         STHook->wMinute = tmpTM.tm_min;
1466         STHook->wDayOfWeek = tmpTM.tm_wday;
1467         STHook->wMonth = tmpTM.tm_mon + 1;
1468         STHook->wSecond = tmpTM.tm_sec;
1469         STHook->wYear = tmpTM.tm_year;
1470         
1471         bSuccess = TRUE;
1472         
1473         TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n", 
1474               STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
1475               STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
1476     }
1477     else if (dwInfoLevel & HTTP_QUERY_FLAG_COALESCE)
1478     {
1479             if (*lpdwIndex >= lphttpHdr->wCount)
1480                 {
1481                 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1482                 }
1483             else
1484             {
1485             /* Copy strncpyW(lpBuffer, lphttpHdr[*lpdwIndex], len); */
1486             (*lpdwIndex)++;
1487             }
1488     }
1489     else if (lphttpHdr->lpszValue)
1490     {
1491         DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
1492
1493         if (len > *lpdwBufferLength)
1494         {
1495             *lpdwBufferLength = len;
1496             INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1497             return bSuccess;
1498         }
1499
1500         memcpy(lpBuffer, lphttpHdr->lpszValue, len);
1501         *lpdwBufferLength = len - sizeof(WCHAR);
1502         bSuccess = TRUE;
1503
1504         TRACE(" returning string : '%s'\n", debugstr_w(lpBuffer));
1505     }
1506     return bSuccess;
1507 }
1508
1509 /***********************************************************************
1510  *           HttpQueryInfoW (WININET.@)
1511  *
1512  * Queries for information about an HTTP request
1513  *
1514  * RETURNS
1515  *    TRUE  on success
1516  *    FALSE on failure
1517  *
1518  */
1519 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1520         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1521 {
1522     BOOL bSuccess = FALSE;
1523     LPWININETHTTPREQW lpwhr;
1524
1525     if (TRACE_ON(wininet)) {
1526 #define FE(x) { x, #x }
1527         static const wininet_flag_info query_flags[] = {
1528             FE(HTTP_QUERY_MIME_VERSION),
1529             FE(HTTP_QUERY_CONTENT_TYPE),
1530             FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
1531             FE(HTTP_QUERY_CONTENT_ID),
1532             FE(HTTP_QUERY_CONTENT_DESCRIPTION),
1533             FE(HTTP_QUERY_CONTENT_LENGTH),
1534             FE(HTTP_QUERY_CONTENT_LANGUAGE),
1535             FE(HTTP_QUERY_ALLOW),
1536             FE(HTTP_QUERY_PUBLIC),
1537             FE(HTTP_QUERY_DATE),
1538             FE(HTTP_QUERY_EXPIRES),
1539             FE(HTTP_QUERY_LAST_MODIFIED),
1540             FE(HTTP_QUERY_MESSAGE_ID),
1541             FE(HTTP_QUERY_URI),
1542             FE(HTTP_QUERY_DERIVED_FROM),
1543             FE(HTTP_QUERY_COST),
1544             FE(HTTP_QUERY_LINK),
1545             FE(HTTP_QUERY_PRAGMA),
1546             FE(HTTP_QUERY_VERSION),
1547             FE(HTTP_QUERY_STATUS_CODE),
1548             FE(HTTP_QUERY_STATUS_TEXT),
1549             FE(HTTP_QUERY_RAW_HEADERS),
1550             FE(HTTP_QUERY_RAW_HEADERS_CRLF),
1551             FE(HTTP_QUERY_CONNECTION),
1552             FE(HTTP_QUERY_ACCEPT),
1553             FE(HTTP_QUERY_ACCEPT_CHARSET),
1554             FE(HTTP_QUERY_ACCEPT_ENCODING),
1555             FE(HTTP_QUERY_ACCEPT_LANGUAGE),
1556             FE(HTTP_QUERY_AUTHORIZATION),
1557             FE(HTTP_QUERY_CONTENT_ENCODING),
1558             FE(HTTP_QUERY_FORWARDED),
1559             FE(HTTP_QUERY_FROM),
1560             FE(HTTP_QUERY_IF_MODIFIED_SINCE),
1561             FE(HTTP_QUERY_LOCATION),
1562             FE(HTTP_QUERY_ORIG_URI),
1563             FE(HTTP_QUERY_REFERER),
1564             FE(HTTP_QUERY_RETRY_AFTER),
1565             FE(HTTP_QUERY_SERVER),
1566             FE(HTTP_QUERY_TITLE),
1567             FE(HTTP_QUERY_USER_AGENT),
1568             FE(HTTP_QUERY_WWW_AUTHENTICATE),
1569             FE(HTTP_QUERY_PROXY_AUTHENTICATE),
1570             FE(HTTP_QUERY_ACCEPT_RANGES),
1571         FE(HTTP_QUERY_SET_COOKIE),
1572         FE(HTTP_QUERY_COOKIE),
1573             FE(HTTP_QUERY_REQUEST_METHOD),
1574             FE(HTTP_QUERY_REFRESH),
1575             FE(HTTP_QUERY_CONTENT_DISPOSITION),
1576             FE(HTTP_QUERY_AGE),
1577             FE(HTTP_QUERY_CACHE_CONTROL),
1578             FE(HTTP_QUERY_CONTENT_BASE),
1579             FE(HTTP_QUERY_CONTENT_LOCATION),
1580             FE(HTTP_QUERY_CONTENT_MD5),
1581             FE(HTTP_QUERY_CONTENT_RANGE),
1582             FE(HTTP_QUERY_ETAG),
1583             FE(HTTP_QUERY_HOST),
1584             FE(HTTP_QUERY_IF_MATCH),
1585             FE(HTTP_QUERY_IF_NONE_MATCH),
1586             FE(HTTP_QUERY_IF_RANGE),
1587             FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
1588             FE(HTTP_QUERY_MAX_FORWARDS),
1589             FE(HTTP_QUERY_PROXY_AUTHORIZATION),
1590             FE(HTTP_QUERY_RANGE),
1591             FE(HTTP_QUERY_TRANSFER_ENCODING),
1592             FE(HTTP_QUERY_UPGRADE),
1593             FE(HTTP_QUERY_VARY),
1594             FE(HTTP_QUERY_VIA),
1595             FE(HTTP_QUERY_WARNING),
1596             FE(HTTP_QUERY_CUSTOM)
1597         };
1598         static const wininet_flag_info modifier_flags[] = {
1599             FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
1600             FE(HTTP_QUERY_FLAG_SYSTEMTIME),
1601             FE(HTTP_QUERY_FLAG_NUMBER),
1602             FE(HTTP_QUERY_FLAG_COALESCE)
1603         };
1604 #undef FE
1605         DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
1606         DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
1607         DWORD i;
1608
1609         TRACE("(%p, 0x%08lx)--> %ld\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
1610         TRACE("  Attribute:");
1611         for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
1612             if (query_flags[i].val == info) {
1613                 TRACE(" %s", query_flags[i].name);
1614                 break;
1615             }
1616         }
1617         if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
1618             TRACE(" Unknown (%08lx)", info);
1619         }
1620
1621         TRACE(" Modifier:");
1622         for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
1623             if (modifier_flags[i].val & info_mod) {
1624                 TRACE(" %s", modifier_flags[i].name);
1625                 info_mod &= ~ modifier_flags[i].val;
1626             }
1627         }
1628         
1629         if (info_mod) {
1630             TRACE(" Unknown (%08lx)", info_mod);
1631         }
1632         TRACE("\n");
1633     }
1634     
1635     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1636     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
1637     {
1638         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1639         goto lend;
1640     }
1641
1642     bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
1643                                     lpBuffer, lpdwBufferLength, lpdwIndex);
1644
1645 lend:
1646     if( lpwhr )
1647          WININET_Release( &lpwhr->hdr );
1648
1649     TRACE("%d <--\n", bSuccess);
1650     return bSuccess;
1651 }
1652
1653 /***********************************************************************
1654  *           HttpQueryInfoA (WININET.@)
1655  *
1656  * Queries for information about an HTTP request
1657  *
1658  * RETURNS
1659  *    TRUE  on success
1660  *    FALSE on failure
1661  *
1662  */
1663 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1664         LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1665 {
1666     BOOL result;
1667     DWORD len;
1668     WCHAR* bufferW;
1669
1670     if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
1671        (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
1672     {
1673         return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
1674                                lpdwBufferLength, lpdwIndex );
1675     }
1676
1677     len = (*lpdwBufferLength)*sizeof(WCHAR);
1678     bufferW = HeapAlloc( GetProcessHeap(), 0, len );
1679     /* buffer is in/out because of HTTP_QUERY_CUSTOM */
1680     if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
1681         MultiByteToWideChar(CP_ACP,0,lpBuffer,-1,bufferW,len);
1682     result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
1683                            &len, lpdwIndex );
1684     if( result )
1685     {
1686         len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
1687                                      lpBuffer, *lpdwBufferLength, NULL, NULL );
1688         *lpdwBufferLength = len - 1;
1689
1690         TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
1691     }
1692     else
1693         /* since the strings being returned from HttpQueryInfoW should be
1694          * only ASCII characters, it is reasonable to assume that all of
1695          * the Unicode characters can be reduced to a single byte */
1696         *lpdwBufferLength = len / sizeof(WCHAR);
1697
1698     HeapFree(GetProcessHeap(), 0, bufferW );
1699
1700     return result;
1701 }
1702
1703 /***********************************************************************
1704  *           HttpSendRequestExA (WININET.@)
1705  *
1706  * Sends the specified request to the HTTP server and allows chunked
1707  * transfers.
1708  *
1709  * RETURNS
1710  *  Success: TRUE
1711  *  Failure: FALSE, call GetLastError() for more information.
1712  */
1713 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
1714                                LPINTERNET_BUFFERSA lpBuffersIn,
1715                                LPINTERNET_BUFFERSA lpBuffersOut,
1716                                DWORD dwFlags, DWORD dwContext)
1717 {
1718     INTERNET_BUFFERSW BuffersInW;
1719     BOOL rc = FALSE;
1720     DWORD headerlen;
1721
1722     TRACE("(%p, %p, %p, %08lx, %08lx): stub\n", hRequest, lpBuffersIn,
1723             lpBuffersOut, dwFlags, dwContext);
1724
1725     if (lpBuffersIn)
1726     {
1727         BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
1728         if (lpBuffersIn->lpcszHeader)
1729         {
1730             headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
1731                     lpBuffersIn->dwHeadersLength,0,0);
1732             BuffersInW.lpcszHeader = HeapAlloc(GetProcessHeap(),0,headerlen*
1733                     sizeof(WCHAR));
1734             if (!BuffersInW.lpcszHeader)
1735             {
1736                 SetLastError(ERROR_OUTOFMEMORY);
1737                 return FALSE;
1738             }
1739             BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
1740                     lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
1741                     (LPWSTR)BuffersInW.lpcszHeader, headerlen);
1742         }
1743         else
1744             BuffersInW.lpcszHeader = NULL;
1745         BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
1746         BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
1747         BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
1748         BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
1749         BuffersInW.Next = NULL;
1750     }
1751
1752     rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
1753
1754     if (lpBuffersIn)
1755         HeapFree(GetProcessHeap(),0,(LPVOID)BuffersInW.lpcszHeader);
1756
1757     return rc;
1758 }
1759
1760 /***********************************************************************
1761  *           HttpSendRequestExW (WININET.@)
1762  *
1763  * Sends the specified request to the HTTP server and allows chunked
1764  * transfers
1765  *
1766  * RETURNS
1767  *  Success: TRUE
1768  *  Failure: FALSE, call GetLastError() for more information.
1769  */
1770 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
1771                    LPINTERNET_BUFFERSW lpBuffersIn,
1772                    LPINTERNET_BUFFERSW lpBuffersOut,
1773                    DWORD dwFlags, DWORD dwContext)
1774 {
1775     BOOL ret;
1776     LPWININETHTTPREQW lpwhr;
1777     LPWININETHTTPSESSIONW lpwhs;
1778     LPWININETAPPINFOW hIC;
1779
1780     TRACE("(%p, %p, %p, %08lx, %08lx)\n", hRequest, lpBuffersIn,
1781             lpBuffersOut, dwFlags, dwContext);
1782
1783     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
1784
1785     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1786     {
1787         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1788         return FALSE;
1789     }
1790
1791     lpwhs = (LPWININETHTTPSESSIONW) lpwhr->hdr.lpwhparent;
1792     assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
1793     hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
1794     assert(hIC->hdr.htype == WH_HINIT);
1795
1796     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1797     {
1798         WORKREQUEST workRequest;
1799         struct WORKREQ_HTTPSENDREQUESTW *req;
1800
1801         workRequest.asyncall = HTTPSENDREQUESTW;
1802         workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
1803         req = &workRequest.u.HttpSendRequestW;
1804         if (lpBuffersIn)
1805         {
1806             if (lpBuffersIn->lpcszHeader)
1807                 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
1808                 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
1809             else
1810                 req->lpszHeader = NULL;
1811             req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
1812             req->lpOptional = lpBuffersIn->lpvBuffer;
1813             req->dwOptionalLength = lpBuffersIn->dwBufferLength;
1814             req->dwContentLength = lpBuffersIn->dwBufferTotal;
1815         }
1816         else
1817         {
1818             req->lpszHeader = NULL;
1819             req->dwHeaderLength = 0;
1820             req->lpOptional = NULL;
1821             req->dwOptionalLength = 0;
1822             req->dwContentLength = 0;
1823         }
1824
1825         req->bEndRequest = FALSE;
1826
1827         INTERNET_AsyncCall(&workRequest);
1828         /*
1829          * This is from windows.
1830          */
1831         SetLastError(ERROR_IO_PENDING);
1832         ret = FALSE;
1833     }
1834     else
1835     {
1836         ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
1837                                     lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
1838                                     lpBuffersIn->dwBufferTotal, FALSE);
1839     }
1840  
1841     WININET_Release(&lpwhr->hdr);
1842     TRACE("<---\n");
1843     return ret;
1844 }
1845
1846 /***********************************************************************
1847  *           HttpSendRequestW (WININET.@)
1848  *
1849  * Sends the specified request to the HTTP server
1850  *
1851  * RETURNS
1852  *    TRUE  on success
1853  *    FALSE on failure
1854  *
1855  */
1856 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
1857         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1858 {
1859     LPWININETHTTPREQW lpwhr;
1860     LPWININETHTTPSESSIONW lpwhs = NULL;
1861     LPWININETAPPINFOW hIC = NULL;
1862     BOOL r;
1863
1864     TRACE("%p, %p (%s), %li, %p, %li)\n", hHttpRequest,
1865             lpszHeaders, debugstr_w(lpszHeaders), dwHeaderLength, lpOptional, dwOptionalLength);
1866
1867     lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1868     if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1869     {
1870         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1871         r = FALSE;
1872         goto lend;
1873     }
1874
1875     lpwhs = (LPWININETHTTPSESSIONW) lpwhr->hdr.lpwhparent;
1876     if (NULL == lpwhs ||  lpwhs->hdr.htype != WH_HHTTPSESSION)
1877     {
1878         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1879         r = FALSE;
1880         goto lend;
1881     }
1882
1883     hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
1884     if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT)
1885     {
1886         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1887         r = FALSE;
1888         goto lend;
1889     }
1890
1891     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1892     {
1893         WORKREQUEST workRequest;
1894         struct WORKREQ_HTTPSENDREQUESTW *req;
1895
1896         workRequest.asyncall = HTTPSENDREQUESTW;
1897         workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
1898         req = &workRequest.u.HttpSendRequestW;
1899         if (lpszHeaders)
1900             req->lpszHeader = WININET_strdupW(lpszHeaders);
1901         else
1902             req->lpszHeader = 0;
1903         req->dwHeaderLength = dwHeaderLength;
1904         req->lpOptional = lpOptional;
1905         req->dwOptionalLength = dwOptionalLength;
1906         req->dwContentLength = dwOptionalLength;
1907         req->bEndRequest = TRUE;
1908
1909         INTERNET_AsyncCall(&workRequest);
1910         /*
1911          * This is from windows.
1912          */
1913         SetLastError(ERROR_IO_PENDING);
1914         r = FALSE;
1915     }
1916     else
1917     {
1918         r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
1919                 dwHeaderLength, lpOptional, dwOptionalLength,
1920                 dwOptionalLength, TRUE);
1921     }
1922 lend:
1923     if( lpwhr )
1924         WININET_Release( &lpwhr->hdr );
1925     return r;
1926 }
1927
1928 /***********************************************************************
1929  *           HttpSendRequestA (WININET.@)
1930  *
1931  * Sends the specified request to the HTTP server
1932  *
1933  * RETURNS
1934  *    TRUE  on success
1935  *    FALSE on failure
1936  *
1937  */
1938 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
1939         DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
1940 {
1941     BOOL result;
1942     LPWSTR szHeaders=NULL;
1943     DWORD nLen=dwHeaderLength;
1944     if(lpszHeaders!=NULL)
1945     {
1946         nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
1947         szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
1948         MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
1949     }
1950     result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
1951     HeapFree(GetProcessHeap(),0,szHeaders);
1952     return result;
1953 }
1954
1955 /***********************************************************************
1956  *           HTTP_HandleRedirect (internal)
1957  */
1958 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl, LPCWSTR lpszHeaders,
1959                                 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
1960                                 DWORD dwContentLength)
1961 {
1962     LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) lpwhr->hdr.lpwhparent;
1963     LPWININETAPPINFOW hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
1964     WCHAR path[2048];
1965     char szaddr[32];
1966
1967     if(lpszUrl[0]=='/')
1968     {
1969         /* if it's an absolute path, keep the same session info */
1970         lstrcpynW(path, lpszUrl, 2048);
1971     }
1972     else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1973     {
1974         TRACE("Redirect through proxy\n");
1975         lstrcpynW(path, lpszUrl, 2048);
1976     }
1977     else
1978     {
1979         URL_COMPONENTSW urlComponents;
1980         WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
1981         static const WCHAR szHttp[] = {'h','t','t','p',0};
1982         static const WCHAR szHttps[] = {'h','t','t','p','s',0};
1983         DWORD url_length = 0;
1984         LPWSTR orig_url;
1985         LPWSTR combined_url;
1986
1987         urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
1988         urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? (LPWSTR)szHttps : (LPWSTR)szHttp;
1989         urlComponents.dwSchemeLength = 0;
1990         urlComponents.lpszHostName = lpwhs->lpszHostName;
1991         urlComponents.dwHostNameLength = 0;
1992         urlComponents.nPort = lpwhs->nHostPort;
1993         urlComponents.lpszUserName = lpwhs->lpszUserName;
1994         urlComponents.dwUserNameLength = 0;
1995         urlComponents.lpszPassword = NULL;
1996         urlComponents.dwPasswordLength = 0;
1997         urlComponents.lpszUrlPath = lpwhr->lpszPath;
1998         urlComponents.dwUrlPathLength = 0;
1999         urlComponents.lpszExtraInfo = NULL;
2000         urlComponents.dwExtraInfoLength = 0;
2001
2002         if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2003             (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2004             return FALSE;
2005
2006         url_length++; /* for nul terminating character */
2007         orig_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2008
2009         if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2010         {
2011             HeapFree(GetProcessHeap(), 0, orig_url);
2012             return FALSE;
2013         }
2014
2015         url_length = 0;
2016         if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2017             (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2018         {
2019             HeapFree(GetProcessHeap(), 0, orig_url);
2020             return FALSE;
2021         }
2022         combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2023
2024         if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2025         {
2026             HeapFree(GetProcessHeap(), 0, orig_url);
2027             HeapFree(GetProcessHeap(), 0, combined_url);
2028             return FALSE;
2029         }
2030         HeapFree(GetProcessHeap(), 0, orig_url);
2031
2032         userName[0] = 0;
2033         hostName[0] = 0;
2034         protocol[0] = 0;
2035
2036         urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2037         urlComponents.lpszScheme = protocol;
2038         urlComponents.dwSchemeLength = 32;
2039         urlComponents.lpszHostName = hostName;
2040         urlComponents.dwHostNameLength = MAXHOSTNAME;
2041         urlComponents.lpszUserName = userName;
2042         urlComponents.dwUserNameLength = 1024;
2043         urlComponents.lpszPassword = NULL;
2044         urlComponents.dwPasswordLength = 0;
2045         urlComponents.lpszUrlPath = path;
2046         urlComponents.dwUrlPathLength = 2048;
2047         urlComponents.lpszExtraInfo = NULL;
2048         urlComponents.dwExtraInfoLength = 0;
2049         if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2050         {
2051             HeapFree(GetProcessHeap(), 0, combined_url);
2052             return FALSE;
2053         }
2054         HeapFree(GetProcessHeap(), 0, combined_url);
2055
2056         if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2057             (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2058         {
2059             TRACE("redirect from secure page to non-secure page\n");
2060             /* FIXME: warn about from secure redirect to non-secure page */
2061             lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2062         }
2063         if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2064             !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2065         {
2066             TRACE("redirect from non-secure page to secure page\n");
2067             /* FIXME: notify about redirect to secure page */
2068             lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2069         }
2070
2071         if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2072         {
2073             if (lstrlenW(protocol)>4) /*https*/
2074                 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2075             else /*http*/
2076                 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2077         }
2078
2079 #if 0
2080         /*
2081          * This upsets redirects to binary files on sourceforge.net 
2082          * and gives an html page instead of the target file
2083          * Examination of the HTTP request sent by native wininet.dll
2084          * reveals that it doesn't send a referrer in that case.
2085          * Maybe there's a flag that enables this, or maybe a referrer
2086          * shouldn't be added in case of a redirect.
2087          */
2088
2089         /* consider the current host as the referrer */
2090         if (NULL != lpwhs->lpszServerName && strlenW(lpwhs->lpszServerName))
2091             HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2092                            HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2093                            HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2094 #endif
2095         
2096         HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2097         lpwhs->lpszServerName = WININET_strdupW(hostName);
2098         HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2099         if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2100                 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2101         {
2102             int len;
2103             static WCHAR fmt[] = {'%','s',':','%','i',0};
2104             len = lstrlenW(hostName);
2105             len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2106             lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2107             sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2108         }
2109         else
2110             lpwhs->lpszHostName = WININET_strdupW(hostName);
2111
2112         HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2113
2114         
2115         HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2116         lpwhs->lpszUserName = NULL;
2117         if (userName[0])
2118             lpwhs->lpszUserName = WININET_strdupW(userName);
2119         lpwhs->nServerPort = urlComponents.nPort;
2120
2121         INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2122                               INTERNET_STATUS_RESOLVING_NAME,
2123                               lpwhs->lpszServerName,
2124                               strlenW(lpwhs->lpszServerName)+1);
2125
2126         if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
2127                     &lpwhs->socketAddress))
2128         {
2129             INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
2130             return FALSE;
2131         }
2132
2133         inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
2134               szaddr, sizeof(szaddr));
2135         INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2136                               INTERNET_STATUS_NAME_RESOLVED,
2137                               szaddr, strlen(szaddr)+1);
2138
2139         NETCON_close(&lpwhr->netConnection);
2140
2141         if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2142             return FALSE;
2143     }
2144
2145     HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2146     lpwhr->lpszPath=NULL;
2147     if (strlenW(path))
2148     {
2149         DWORD needed = 0;
2150         HRESULT rc;
2151
2152         rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2153         if (rc != E_POINTER)
2154             needed = strlenW(path)+1;
2155         lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2156         rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2157                         URL_ESCAPE_SPACES_ONLY);
2158         if (rc)
2159         {
2160             ERR("Unable to escape string!(%s) (%ld)\n",debugstr_w(path),rc);
2161             strcpyW(lpwhr->lpszPath,path);
2162         }
2163     }
2164
2165     return HTTP_HttpSendRequestW(lpwhr, lpszHeaders, dwHeaderLength, lpOptional,
2166                                  dwOptionalLength, dwContentLength, TRUE);
2167 }
2168
2169 /***********************************************************************
2170  *           HTTP_build_req (internal)
2171  *
2172  *  concatenate all the strings in the request together
2173  */
2174 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2175 {
2176     LPCWSTR *t;
2177     LPWSTR str;
2178
2179     for( t = list; *t ; t++  )
2180         len += strlenW( *t );
2181     len++;
2182
2183     str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2184     *str = 0;
2185
2186     for( t = list; *t ; t++ )
2187         strcatW( str, *t );
2188
2189     return str;
2190 }
2191
2192 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2193 {
2194     LPWSTR lpszPath;
2195     LPWSTR requestString;
2196     INT len;
2197     INT cnt;
2198     INT responseLen;
2199     char *ascii_req;
2200     BOOL ret;
2201     static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2202     static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2203     LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW)lpwhr->hdr.lpwhparent;
2204
2205     TRACE("\n");
2206
2207     lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2208     sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2209     requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, FALSE );
2210     HeapFree( GetProcessHeap(), 0, lpszPath );
2211
2212     len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2213                                 NULL, 0, NULL, NULL );
2214     len--; /* the nul terminator isn't needed */
2215     ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2216     WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2217                             ascii_req, len, NULL, NULL );
2218     HeapFree( GetProcessHeap(), 0, requestString );
2219
2220     TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2221
2222     ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2223     HeapFree( GetProcessHeap(), 0, ascii_req );
2224     if (!ret || cnt < 0)
2225         return FALSE;
2226
2227     responseLen = HTTP_GetResponseHeaders( lpwhr );
2228     if (!responseLen)
2229         return FALSE;
2230
2231     return TRUE;
2232 }
2233
2234 /***********************************************************************
2235  *           HTTP_HttpSendRequestW (internal)
2236  *
2237  * Sends the specified request to the HTTP server
2238  *
2239  * RETURNS
2240  *    TRUE  on success
2241  *    FALSE on failure
2242  *
2243  */
2244 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2245         DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2246         DWORD dwContentLength, BOOL bEndRequest)
2247 {
2248     INT cnt;
2249     BOOL bSuccess = FALSE;
2250     LPWSTR requestString = NULL;
2251     INT responseLen;
2252     BOOL loop_next = FALSE;
2253     INTERNET_ASYNC_RESULT iar;
2254     LPHTTPHEADERW Host;
2255
2256     TRACE("--> %p\n", lpwhr);
2257
2258     assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2259
2260     /* Clear any error information */
2261     INTERNET_SetLastError(0);
2262
2263     HTTP_FixVerb(lpwhr);
2264     
2265     /* if we are using optional stuff, we must add the fixed header of that option length */
2266     if (dwContentLength > 0)
2267     {
2268         static const WCHAR szContentLength[] = {
2269             'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0};
2270         WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \n\r */ + 20 /* int */ ];
2271         sprintfW(contentLengthStr, szContentLength, dwContentLength);
2272         HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD);
2273     }
2274
2275     Host = HTTP_GetHeader(lpwhr,szHost);
2276     do
2277     {
2278         DWORD len;
2279         char *ascii_req;
2280
2281         TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2282         loop_next = FALSE;
2283
2284         HTTP_FixURL(lpwhr);
2285
2286         /* add the headers the caller supplied */
2287         if( lpszHeaders && dwHeaderLength )
2288         {
2289             HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2290                         HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2291         }
2292
2293         /* if there's a proxy username and password, add it to the headers */
2294         HTTP_AddProxyInfo(lpwhr);
2295
2296         requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, FALSE);
2297  
2298         TRACE("Request header -> %s\n", debugstr_w(requestString) );
2299
2300         /* Send the request and store the results */
2301         if (!HTTP_OpenConnection(lpwhr))
2302             goto lend;
2303
2304         /* send the request as ASCII, tack on the optional data */
2305         if( !lpOptional )
2306             dwOptionalLength = 0;
2307         len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2308                                    NULL, 0, NULL, NULL );
2309         ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2310         WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2311                              ascii_req, len, NULL, NULL );
2312         if( lpOptional )
2313             memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2314         len = (len + dwOptionalLength - 1);
2315         ascii_req[len] = 0;
2316         TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2317
2318         INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2319                               INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2320
2321         NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2322         HeapFree( GetProcessHeap(), 0, ascii_req );
2323
2324         INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2325                               INTERNET_STATUS_REQUEST_SENT,
2326                               &len, sizeof(DWORD));
2327
2328         if (bEndRequest)
2329         {
2330             INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2331                                 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2332     
2333             if (cnt < 0)
2334                 goto lend;
2335     
2336             responseLen = HTTP_GetResponseHeaders(lpwhr);
2337             if (responseLen)
2338                 bSuccess = TRUE;
2339     
2340             INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2341                                 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2342                                 sizeof(DWORD));
2343     
2344             HTTP_ProcessHeaders(lpwhr);
2345         }
2346         else
2347             bSuccess = TRUE;
2348     }
2349     while (loop_next);
2350
2351 lend:
2352
2353     HeapFree(GetProcessHeap(), 0, requestString);
2354
2355     /* TODO: send notification for P3P header */
2356     
2357     if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess && bEndRequest)
2358     {
2359         DWORD dwCode,dwCodeLength=sizeof(DWORD),dwIndex=0;
2360         if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,&dwIndex) &&
2361             (dwCode==302 || dwCode==301))
2362         {
2363             WCHAR szNewLocation[2048];
2364             DWORD dwBufferSize=2048;
2365             dwIndex=0;
2366             if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,&dwIndex))
2367             {
2368                 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2369                                       INTERNET_STATUS_REDIRECT, szNewLocation,
2370                                       dwBufferSize);
2371                 return HTTP_HandleRedirect(lpwhr, szNewLocation, lpszHeaders,
2372                                            dwHeaderLength, lpOptional, dwOptionalLength,
2373                                            dwContentLength);
2374             }
2375         }
2376     }
2377
2378
2379     iar.dwResult = (DWORD)bSuccess;
2380     iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2381
2382     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2383                           INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2384                           sizeof(INTERNET_ASYNC_RESULT));
2385
2386     TRACE("<--\n");
2387     return bSuccess;
2388 }
2389
2390
2391 /***********************************************************************
2392  *           HTTP_Connect  (internal)
2393  *
2394  * Create http session handle
2395  *
2396  * RETURNS
2397  *   HINTERNET a session handle on success
2398  *   NULL on failure
2399  *
2400  */
2401 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
2402         INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2403         LPCWSTR lpszPassword, DWORD dwFlags, DWORD dwContext,
2404         DWORD dwInternalFlags)
2405 {
2406     BOOL bSuccess = FALSE;
2407     LPWININETHTTPSESSIONW lpwhs = NULL;
2408     HINTERNET handle = NULL;
2409
2410     TRACE("-->\n");
2411
2412     assert( hIC->hdr.htype == WH_HINIT );
2413
2414     hIC->hdr.dwContext = dwContext;
2415     
2416     lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
2417     if (NULL == lpwhs)
2418     {
2419         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2420         goto lerror;
2421     }
2422
2423    /*
2424     * According to my tests. The name is not resolved until a request is sent
2425     */
2426
2427     lpwhs->hdr.htype = WH_HHTTPSESSION;
2428     lpwhs->hdr.lpwhparent = WININET_AddRef( &hIC->hdr );
2429     lpwhs->hdr.dwFlags = dwFlags;
2430     lpwhs->hdr.dwContext = dwContext;
2431     lpwhs->hdr.dwInternalFlags = dwInternalFlags;
2432     lpwhs->hdr.dwRefCount = 1;
2433     lpwhs->hdr.destroy = HTTP_CloseHTTPSessionHandle;
2434     lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
2435
2436     handle = WININET_AllocHandle( &lpwhs->hdr );
2437     if (NULL == handle)
2438     {
2439         ERR("Failed to alloc handle\n");
2440         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2441         goto lerror;
2442     }
2443
2444     if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
2445         if(strchrW(hIC->lpszProxy, ' '))
2446             FIXME("Several proxies not implemented.\n");
2447         if(hIC->lpszProxyBypass)
2448             FIXME("Proxy bypass is ignored.\n");
2449     }
2450     if (lpszServerName && lpszServerName[0])
2451     {
2452         lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
2453         lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
2454     }
2455     if (lpszUserName && lpszUserName[0])
2456         lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
2457     lpwhs->nServerPort = nServerPort;
2458     lpwhs->nHostPort = nServerPort;
2459
2460     /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
2461     if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
2462     {
2463         INTERNET_SendCallback(&hIC->hdr, dwContext,
2464                               INTERNET_STATUS_HANDLE_CREATED, &handle,
2465                               sizeof(handle));
2466     }
2467
2468     bSuccess = TRUE;
2469
2470 lerror:
2471     if( lpwhs )
2472         WININET_Release( &lpwhs->hdr );
2473
2474 /*
2475  * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
2476  * windows
2477  */
2478
2479     TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
2480     return handle;
2481 }
2482
2483
2484 /***********************************************************************
2485  *           HTTP_OpenConnection (internal)
2486  *
2487  * Connect to a web server
2488  *
2489  * RETURNS
2490  *
2491  *   TRUE  on success
2492  *   FALSE on failure
2493  */
2494 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
2495 {
2496     BOOL bSuccess = FALSE;
2497     LPWININETHTTPSESSIONW lpwhs;
2498     LPWININETAPPINFOW hIC = NULL;
2499     char szaddr[32];
2500
2501     TRACE("-->\n");
2502
2503
2504     if (NULL == lpwhr ||  lpwhr->hdr.htype != WH_HHTTPREQ)
2505     {
2506         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2507         goto lend;
2508     }
2509
2510     lpwhs = (LPWININETHTTPSESSIONW)lpwhr->hdr.lpwhparent;
2511
2512     hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
2513     inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
2514               szaddr, sizeof(szaddr));
2515     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2516                           INTERNET_STATUS_CONNECTING_TO_SERVER,
2517                           szaddr,
2518                           strlen(szaddr)+1);
2519
2520     if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
2521                          SOCK_STREAM, 0))
2522     {
2523         WARN("Socket creation failed\n");
2524         goto lend;
2525     }
2526
2527     if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
2528                       sizeof(lpwhs->socketAddress)))
2529        goto lend;
2530
2531     if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
2532     {
2533         /* Note: we differ from Microsoft's WinINet here. they seem to have
2534          * a bug that causes no status callbacks to be sent when starting
2535          * a tunnel to a proxy server using the CONNECT verb. i believe our
2536          * behaviour to be more correct and to not cause any incompatibilities
2537          * because using a secure connection through a proxy server is a rare
2538          * case that would be hard for anyone to depend on */
2539         if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
2540             goto lend;
2541
2542         if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
2543         {
2544             WARN("Couldn't connect securely to host\n");
2545             goto lend;
2546         }
2547     }
2548
2549     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2550                           INTERNET_STATUS_CONNECTED_TO_SERVER,
2551                           szaddr, strlen(szaddr)+1);
2552
2553     bSuccess = TRUE;
2554
2555 lend:
2556     TRACE("%d <--\n", bSuccess);
2557     return bSuccess;
2558 }
2559
2560
2561 /***********************************************************************
2562  *           HTTP_clear_response_headers (internal)
2563  *
2564  * clear out any old response headers
2565  */
2566 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
2567 {
2568     DWORD i;
2569
2570     for( i=0; i<lpwhr->nCustHeaders; i++)
2571     {
2572         if( !lpwhr->pCustHeaders[i].lpszField )
2573             continue;
2574         if( !lpwhr->pCustHeaders[i].lpszValue )
2575             continue;
2576         if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
2577             continue;
2578         HTTP_DeleteCustomHeader( lpwhr, i );
2579         i--;
2580     }
2581 }
2582
2583 /***********************************************************************
2584  *           HTTP_GetResponseHeaders (internal)
2585  *
2586  * Read server response
2587  *
2588  * RETURNS
2589  *
2590  *   TRUE  on success
2591  *   FALSE on error
2592  */
2593 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
2594 {
2595     INT cbreaks = 0;
2596     WCHAR buffer[MAX_REPLY_LEN];
2597     DWORD buflen = MAX_REPLY_LEN;
2598     BOOL bSuccess = FALSE;
2599     INT  rc = 0;
2600     static const WCHAR szCrLf[] = {'\r','\n',0};
2601     char bufferA[MAX_REPLY_LEN];
2602     LPWSTR status_code, status_text;
2603     DWORD cchMaxRawHeaders = 1024;
2604     LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2605     DWORD cchRawHeaders = 0;
2606
2607     TRACE("-->\n");
2608
2609     /* clear old response headers (eg. from a redirect response) */
2610     HTTP_clear_response_headers( lpwhr );
2611
2612     if (!NETCON_connected(&lpwhr->netConnection))
2613         goto lend;
2614
2615     /*
2616      * HACK peek at the buffer
2617      */
2618     NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
2619
2620     /*
2621      * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
2622      */
2623     buflen = MAX_REPLY_LEN;
2624     memset(buffer, 0, MAX_REPLY_LEN);
2625     if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
2626         goto lend;
2627     MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
2628
2629     /* regenerate raw headers */
2630     while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
2631     {
2632         cchMaxRawHeaders *= 2;
2633         lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2634     }
2635     memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
2636     cchRawHeaders += (buflen-1);
2637     memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
2638     cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
2639     lpszRawHeaders[cchRawHeaders] = '\0';
2640
2641     /* split the version from the status code */
2642     status_code = strchrW( buffer, ' ' );
2643     if( !status_code )
2644         goto lend;
2645     *status_code++=0;
2646
2647     /* split the status code from the status text */
2648     status_text = strchrW( status_code, ' ' );
2649     if( !status_text )
2650         goto lend;
2651     *status_text++=0;
2652
2653     TRACE("version [%s] status code [%s] status text [%s]\n",
2654          debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
2655
2656     HTTP_ProcessHeader(lpwhr, szStatus, status_code,
2657             HTTP_ADDHDR_FLAG_REPLACE);
2658
2659     HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
2660     HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
2661
2662     lpwhr->lpszVersion= WININET_strdupW(buffer);
2663     lpwhr->lpszStatusText = WININET_strdupW(status_text);
2664
2665     /* Parse each response line */
2666     do
2667     {
2668         buflen = MAX_REPLY_LEN;
2669         if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
2670         {
2671             LPWSTR * pFieldAndValue;
2672
2673             TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
2674             MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
2675
2676             while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
2677             {
2678                 cchMaxRawHeaders *= 2;
2679                 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
2680             }
2681             memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
2682             cchRawHeaders += (buflen-1);
2683             memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
2684             cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
2685             lpszRawHeaders[cchRawHeaders] = '\0';
2686
2687             pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
2688             if (!pFieldAndValue)
2689                 break;
2690
2691             HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1], 
2692                 HTTP_ADDREQ_FLAG_ADD );
2693
2694             HTTP_FreeTokens(pFieldAndValue);
2695         }
2696         else
2697         {
2698             cbreaks++;
2699             if (cbreaks >= 2)
2700                break;
2701         }
2702     }while(1);
2703
2704     HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
2705     lpwhr->lpszRawHeaders = lpszRawHeaders;
2706     TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
2707     bSuccess = TRUE;
2708
2709 lend:
2710
2711     TRACE("<--\n");
2712     if (bSuccess)
2713         return rc;
2714     else
2715         return 0;
2716 }
2717
2718
2719 static void strip_spaces(LPWSTR start)
2720 {
2721     LPWSTR str = start;
2722     LPWSTR end;
2723
2724     while (*str == ' ' && *str != '\0')
2725         str++;
2726
2727     if (str != start)
2728         memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
2729
2730     end = start + strlenW(start) - 1;
2731     while (end >= start && *end == ' ')
2732     {
2733         *end = '\0';
2734         end--;
2735     }
2736 }
2737
2738
2739 /***********************************************************************
2740  *           HTTP_InterpretHttpHeader (internal)
2741  *
2742  * Parse server response
2743  *
2744  * RETURNS
2745  *
2746  *   Pointer to array of field, value, NULL on success.
2747  *   NULL on error.
2748  */
2749 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
2750 {
2751     LPWSTR * pTokenPair;
2752     LPWSTR pszColon;
2753     INT len;
2754
2755     pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
2756
2757     pszColon = strchrW(buffer, ':');
2758     /* must have two tokens */
2759     if (!pszColon)
2760     {
2761         HTTP_FreeTokens(pTokenPair);
2762         if (buffer[0])
2763             TRACE("No ':' in line: %s\n", debugstr_w(buffer));
2764         return NULL;
2765     }
2766
2767     pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
2768     if (!pTokenPair[0])
2769     {
2770         HTTP_FreeTokens(pTokenPair);
2771         return NULL;
2772     }
2773     memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
2774     pTokenPair[0][pszColon - buffer] = '\0';
2775
2776     /* skip colon */
2777     pszColon++;
2778     len = strlenW(pszColon);
2779     pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2780     if (!pTokenPair[1])
2781     {
2782         HTTP_FreeTokens(pTokenPair);
2783         return NULL;
2784     }
2785     memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
2786
2787     strip_spaces(pTokenPair[0]);
2788     strip_spaces(pTokenPair[1]);
2789
2790     TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
2791     return pTokenPair;
2792 }
2793
2794 /***********************************************************************
2795  *           HTTP_ProcessHeader (internal)
2796  *
2797  * Stuff header into header tables according to <dwModifier>
2798  *
2799  */
2800
2801 #define COALESCEFLASG (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
2802
2803 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
2804 {
2805     LPHTTPHEADERW lphttpHdr = NULL;
2806     BOOL bSuccess = FALSE;
2807     INT index = -1;
2808     static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2809     BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
2810
2811     TRACE("--> %s: %s - 0x%08lx\n", debugstr_w(field), debugstr_w(value), dwModifier);
2812
2813     /* Don't let applications add Connection header to request */
2814     if (strcmpW(szConnection,field)==0 && (dwModifier & HTTP_ADDHDR_FLAG_REQ))
2815     {
2816         return FALSE;
2817     }
2818
2819     /* REPLACE wins out over ADD */
2820     if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
2821         dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
2822     
2823     if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
2824         index = -1;
2825     else
2826         index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
2827
2828     if (index >= 0)
2829     {
2830         if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
2831         {
2832             return FALSE;
2833         }
2834         lphttpHdr = &lpwhr->pCustHeaders[index];
2835     }
2836     else if (value)
2837     {
2838         HTTPHEADERW hdr;
2839
2840         hdr.lpszField = (LPWSTR)field;
2841         hdr.lpszValue = (LPWSTR)value;
2842         hdr.wFlags = hdr.wCount = 0;
2843
2844         if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2845             hdr.wFlags |= HDR_ISREQUEST;
2846
2847         return HTTP_InsertCustomHeader(lpwhr, &hdr);
2848     }
2849
2850     if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2851             lphttpHdr->wFlags |= HDR_ISREQUEST;
2852     else
2853         lphttpHdr->wFlags &= ~HDR_ISREQUEST;
2854
2855     if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
2856     {
2857         HTTP_DeleteCustomHeader( lpwhr, index );
2858
2859         if (value)
2860         {
2861             HTTPHEADERW hdr;
2862
2863             hdr.lpszField = (LPWSTR)field;
2864             hdr.lpszValue = (LPWSTR)value;
2865             hdr.wFlags = hdr.wCount = 0;
2866
2867             if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
2868                 hdr.wFlags |= HDR_ISREQUEST;
2869
2870             return HTTP_InsertCustomHeader(lpwhr, &hdr);
2871         }
2872
2873         return TRUE;
2874     }
2875     else if (dwModifier & COALESCEFLASG)
2876     {
2877         LPWSTR lpsztmp;
2878         WCHAR ch = 0;
2879         INT len = 0;
2880         INT origlen = strlenW(lphttpHdr->lpszValue);
2881         INT valuelen = strlenW(value);
2882
2883         if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
2884         {
2885             ch = ',';
2886             lphttpHdr->wFlags |= HDR_COMMADELIMITED;
2887         }
2888         else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
2889         {
2890             ch = ';';
2891             lphttpHdr->wFlags |= HDR_COMMADELIMITED;
2892         }
2893
2894         len = origlen + valuelen + ((ch > 0) ? 2 : 0);
2895
2896         lpsztmp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,  lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
2897         if (lpsztmp)
2898         {
2899             lphttpHdr->lpszValue = lpsztmp;
2900     /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
2901             if (ch > 0)
2902             {
2903                 lphttpHdr->lpszValue[origlen] = ch;
2904                 origlen++;
2905                 lphttpHdr->lpszValue[origlen] = ' ';
2906                 origlen++;
2907             }
2908
2909             memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
2910             lphttpHdr->lpszValue[len] = '\0';
2911             bSuccess = TRUE;
2912         }
2913         else
2914         {
2915             WARN("HeapReAlloc (%d bytes) failed\n",len+1);
2916             INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2917         }
2918     }
2919     TRACE("<-- %d\n",bSuccess);
2920     return bSuccess;
2921 }
2922
2923
2924 /***********************************************************************
2925  *           HTTP_CloseConnection (internal)
2926  *
2927  * Close socket connection
2928  *
2929  */
2930 static VOID HTTP_CloseConnection(LPWININETHTTPREQW lpwhr)
2931 {
2932     LPWININETHTTPSESSIONW lpwhs = NULL;
2933     LPWININETAPPINFOW hIC = NULL;
2934
2935     TRACE("%p\n",lpwhr);
2936
2937     lpwhs = (LPWININETHTTPSESSIONW) lpwhr->hdr.lpwhparent;
2938     hIC = (LPWININETAPPINFOW) lpwhs->hdr.lpwhparent;
2939
2940     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2941                           INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
2942
2943     if (NETCON_connected(&lpwhr->netConnection))
2944     {
2945         NETCON_close(&lpwhr->netConnection);
2946     }
2947
2948     INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2949                           INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
2950 }
2951
2952
2953 /***********************************************************************
2954  *           HTTP_CloseHTTPRequestHandle (internal)
2955  *
2956  * Deallocate request handle
2957  *
2958  */
2959 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr)
2960 {
2961     DWORD i;
2962     LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
2963
2964     TRACE("\n");
2965
2966     if (NETCON_connected(&lpwhr->netConnection))
2967         HTTP_CloseConnection(lpwhr);
2968
2969     HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2970     HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
2971     HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
2972     HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
2973     HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
2974
2975     for (i = 0; i < lpwhr->nCustHeaders; i++)
2976     {
2977         HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
2978         HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
2979     }
2980
2981     HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
2982     HeapFree(GetProcessHeap(), 0, lpwhr);
2983 }
2984
2985
2986 /***********************************************************************
2987  *           HTTP_CloseHTTPSessionHandle (internal)
2988  *
2989  * Deallocate session handle
2990  *
2991  */
2992 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr)
2993 {
2994     LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
2995
2996     TRACE("%p\n", lpwhs);
2997
2998     HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2999     HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3000     HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3001     HeapFree(GetProcessHeap(), 0, lpwhs);
3002 }
3003
3004
3005 /***********************************************************************
3006  *           HTTP_GetCustomHeaderIndex (internal)
3007  *
3008  * Return index of custom header from header array
3009  *
3010  */
3011 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,int requested_index, BOOL request_only)
3012 {
3013     DWORD index;
3014
3015     TRACE("%s\n", debugstr_w(lpszField));
3016
3017     for (index = 0; index < lpwhr->nCustHeaders; index++)
3018     {
3019         if (!strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3020     {
3021         if ((request_only && 
3022                 !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))||
3023             (!request_only &&
3024                 (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST)))
3025             continue;
3026
3027         if (requested_index == 0)
3028             break;
3029         else
3030             requested_index --;
3031     }
3032     }
3033
3034     if (index >= lpwhr->nCustHeaders)
3035         index = -1;
3036
3037     TRACE("Return: %ld\n", index);
3038     return index;
3039 }
3040
3041
3042 /***********************************************************************
3043  *           HTTP_InsertCustomHeader (internal)
3044  *
3045  * Insert header into array
3046  *
3047  */
3048 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3049 {
3050     INT count;
3051     LPHTTPHEADERW lph = NULL;
3052     BOOL r = FALSE;
3053
3054     TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3055     count = lpwhr->nCustHeaders + 1;
3056     if (count > 1)
3057         lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3058     else
3059         lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3060
3061     if (NULL != lph)
3062     {
3063         lpwhr->pCustHeaders = lph;
3064         lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3065         lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3066         lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3067         lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3068         lpwhr->nCustHeaders++;
3069         r = TRUE;
3070     }
3071     else
3072     {
3073         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3074     }
3075
3076     return r;
3077 }
3078
3079
3080 /***********************************************************************
3081  *           HTTP_DeleteCustomHeader (internal)
3082  *
3083  * Delete header from array
3084  *  If this function is called, the indexs may change.
3085  */
3086 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3087 {
3088     if( lpwhr->nCustHeaders <= 0 )
3089         return FALSE;
3090     if( index >= lpwhr->nCustHeaders )
3091         return FALSE;
3092     lpwhr->nCustHeaders--;
3093
3094     memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3095              (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3096     memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3097
3098     return TRUE;
3099 }
3100
3101 /***********************************************************************
3102  *          IsHostInProxyBypassList (@)
3103  *
3104  * Undocumented
3105  *
3106  */
3107 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3108 {
3109    FIXME("STUB: flags=%ld host=%s length=%ld\n",flags,szHost,length);
3110    return FALSE;
3111 }