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