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