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