push 85658af99ba4b451a6dbced878cbc531dca1cf66
[wine/hacks.git] / dlls / wininet / http.c
blobe88ef951b0eae3987460e0762693e2f81fe99ca2
1 /*
2 * Wininet - Http Implementation
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
11 * Ulrich Czekalla
12 * David Hammerton
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.
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.
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
29 #include "config.h"
30 #include "wine/port.h"
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>
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"
59 #include "internet.h"
60 #include "wine/debug.h"
61 #include "wine/unicode.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
65 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
66 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
67 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
68 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
69 static const WCHAR szHost[] = { 'H','o','s','t',0 };
70 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
71 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
73 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
74 static const WCHAR szGET[] = { 'G','E','T', 0 };
76 #define MAXHOSTNAME 100
77 #define MAX_FIELD_VALUE_LEN 256
78 #define MAX_FIELD_LEN 256
80 #define HTTP_REFERER g_szReferer
81 #define HTTP_ACCEPT g_szAccept
82 #define HTTP_USERAGENT g_szUserAgent
84 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
85 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
86 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
87 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
88 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
89 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
90 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
92 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
94 struct HttpAuthInfo
96 LPWSTR scheme;
97 CredHandle cred;
98 CtxtHandle ctx;
99 TimeStamp exp;
100 ULONG attr;
101 void *auth_data;
102 unsigned int auth_data_len;
103 BOOL finished; /* finished authenticating */
106 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
107 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr);
108 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
109 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
110 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
111 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
112 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
113 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
114 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
115 dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
116 lpdwIndex);
117 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
118 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
119 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
120 static void HTTP_DrainContent(WININETHTTPREQW *req);
122 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
124 int HeaderIndex = 0;
125 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
126 if (HeaderIndex == -1)
127 return NULL;
128 else
129 return &req->pCustHeaders[HeaderIndex];
132 /***********************************************************************
133 * HTTP_Tokenize (internal)
135 * Tokenize a string, allocating memory for the tokens.
137 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
139 LPWSTR * token_array;
140 int tokens = 0;
141 int i;
142 LPCWSTR next_token;
144 /* empty string has no tokens */
145 if (*string)
146 tokens++;
147 /* count tokens */
148 for (i = 0; string[i]; i++)
149 if (!strncmpW(string+i, token_string, strlenW(token_string)))
151 DWORD j;
152 tokens++;
153 /* we want to skip over separators, but not the null terminator */
154 for (j = 0; j < strlenW(token_string) - 1; j++)
155 if (!string[i+j])
156 break;
157 i += j;
160 /* add 1 for terminating NULL */
161 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
162 token_array[tokens] = NULL;
163 if (!tokens)
164 return token_array;
165 for (i = 0; i < tokens; i++)
167 int len;
168 next_token = strstrW(string, token_string);
169 if (!next_token) next_token = string+strlenW(string);
170 len = next_token - string;
171 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
172 memcpy(token_array[i], string, len*sizeof(WCHAR));
173 token_array[i][len] = '\0';
174 string = next_token+strlenW(token_string);
176 return token_array;
179 /***********************************************************************
180 * HTTP_FreeTokens (internal)
182 * Frees memory returned from HTTP_Tokenize.
184 static void HTTP_FreeTokens(LPWSTR * token_array)
186 int i;
187 for (i = 0; token_array[i]; i++)
188 HeapFree(GetProcessHeap(), 0, token_array[i]);
189 HeapFree(GetProcessHeap(), 0, token_array);
192 /* **********************************************************************
194 * Helper functions for the HttpSendRequest(Ex) functions
197 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
199 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
200 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
202 TRACE("%p\n", lpwhr);
204 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
205 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
206 req->dwContentLength, req->bEndRequest);
208 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
211 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
213 static const WCHAR szSlash[] = { '/',0 };
214 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
216 /* If we don't have a path we set it to root */
217 if (NULL == lpwhr->lpszPath)
218 lpwhr->lpszPath = WININET_strdupW(szSlash);
219 else /* remove \r and \n*/
221 int nLen = strlenW(lpwhr->lpszPath);
222 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
224 nLen--;
225 lpwhr->lpszPath[nLen]='\0';
227 /* Replace '\' with '/' */
228 while (nLen>0) {
229 nLen--;
230 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
234 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
235 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
236 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
238 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
239 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
240 *fixurl = '/';
241 strcpyW(fixurl + 1, lpwhr->lpszPath);
242 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
243 lpwhr->lpszPath = fixurl;
247 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
249 LPWSTR requestString;
250 DWORD len, n;
251 LPCWSTR *req;
252 UINT i;
253 LPWSTR p;
255 static const WCHAR szSpace[] = { ' ',0 };
256 static const WCHAR szcrlf[] = {'\r','\n', 0};
257 static const WCHAR szColon[] = { ':',' ',0 };
258 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
260 /* allocate space for an array of all the string pointers to be added */
261 len = (lpwhr->nCustHeaders)*4 + 10;
262 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
264 /* add the verb, path and HTTP version string */
265 n = 0;
266 req[n++] = verb;
267 req[n++] = szSpace;
268 req[n++] = path;
269 req[n++] = szSpace;
270 req[n++] = version;
272 /* Append custom request headers */
273 for (i = 0; i < lpwhr->nCustHeaders; i++)
275 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
277 req[n++] = szcrlf;
278 req[n++] = lpwhr->pCustHeaders[i].lpszField;
279 req[n++] = szColon;
280 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
282 TRACE("Adding custom header %s (%s)\n",
283 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
284 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
288 if( n >= len )
289 ERR("oops. buffer overrun\n");
291 req[n] = NULL;
292 requestString = HTTP_build_req( req, 4 );
293 HeapFree( GetProcessHeap(), 0, req );
296 * Set (header) termination string for request
297 * Make sure there's exactly two new lines at the end of the request
299 p = &requestString[strlenW(requestString)-1];
300 while ( (*p == '\n') || (*p == '\r') )
301 p--;
302 strcpyW( p+1, sztwocrlf );
304 return requestString;
307 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
309 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
310 int HeaderIndex;
311 LPHTTPHEADERW setCookieHeader;
313 HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
314 if (HeaderIndex == -1)
315 return;
316 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
318 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
320 int nPosStart = 0, nPosEnd = 0, len;
321 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
323 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
325 LPWSTR buf_cookie, cookie_name, cookie_data;
326 LPWSTR buf_url;
327 LPWSTR domain = NULL;
328 LPHTTPHEADERW Host;
330 int nEqualPos = 0;
331 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
332 setCookieHeader->lpszValue[nPosEnd] != '\0')
334 nPosEnd++;
336 if (setCookieHeader->lpszValue[nPosEnd] == ';')
338 /* fixme: not case sensitive, strcasestr is gnu only */
339 int nDomainPosEnd = 0;
340 int nDomainPosStart = 0, nDomainLength = 0;
341 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
342 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
343 if (lpszDomain)
344 { /* they have specified their own domain, lets use it */
345 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
346 lpszDomain[nDomainPosEnd] != '\0')
348 nDomainPosEnd++;
350 nDomainPosStart = strlenW(szDomain);
351 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
352 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
353 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
356 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
357 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
358 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
359 TRACE("%s\n", debugstr_w(buf_cookie));
360 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
362 nEqualPos++;
364 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
366 HeapFree(GetProcessHeap(), 0, buf_cookie);
367 break;
370 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
371 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
372 cookie_data = &buf_cookie[nEqualPos + 1];
374 Host = HTTP_GetHeader(lpwhr,szHost);
375 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
376 strlenW(lpwhr->lpszPath) + 9;
377 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
378 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
379 InternetSetCookieW(buf_url, cookie_name, cookie_data);
381 HeapFree(GetProcessHeap(), 0, buf_url);
382 HeapFree(GetProcessHeap(), 0, buf_cookie);
383 HeapFree(GetProcessHeap(), 0, cookie_name);
384 HeapFree(GetProcessHeap(), 0, domain);
385 nPosStart = nPosEnd;
390 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
392 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
393 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
394 ((pszAuthValue[ARRAYSIZE(szBasic)] != ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
397 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
398 struct HttpAuthInfo **ppAuthInfo,
399 LPWSTR domain_and_username, LPWSTR password )
401 SECURITY_STATUS sec_status;
402 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
403 BOOL first = FALSE;
405 TRACE("%s\n", debugstr_w(pszAuthValue));
407 if (!domain_and_username) return FALSE;
409 if (!pAuthInfo)
411 TimeStamp exp;
413 first = TRUE;
414 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
415 if (!pAuthInfo)
416 return FALSE;
418 SecInvalidateHandle(&pAuthInfo->cred);
419 SecInvalidateHandle(&pAuthInfo->ctx);
420 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
421 pAuthInfo->attr = 0;
422 pAuthInfo->auth_data = NULL;
423 pAuthInfo->auth_data_len = 0;
424 pAuthInfo->finished = FALSE;
426 if (is_basic_auth_value(pszAuthValue))
428 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
429 pAuthInfo->scheme = WININET_strdupW(szBasic);
430 if (!pAuthInfo->scheme)
432 HeapFree(GetProcessHeap(), 0, pAuthInfo);
433 return FALSE;
436 else
438 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
439 WCHAR *user = strchrW(domain_and_username, '\\');
440 WCHAR *domain = domain_and_username;
442 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
443 if (!pAuthInfo->scheme)
445 HeapFree(GetProcessHeap(), 0, pAuthInfo);
446 return FALSE;
449 if (user) user++;
450 else
452 user = domain_and_username;
453 domain = NULL;
455 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
456 nt_auth_identity.User = user;
457 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
458 nt_auth_identity.Domain = domain;
459 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
460 nt_auth_identity.Password = password;
461 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
463 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
465 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
466 SECPKG_CRED_OUTBOUND, NULL,
467 &nt_auth_identity, NULL,
468 NULL, &pAuthInfo->cred,
469 &exp);
470 if (sec_status != SEC_E_OK)
472 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
473 debugstr_w(pAuthInfo->scheme), sec_status);
474 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
475 HeapFree(GetProcessHeap(), 0, pAuthInfo);
476 return FALSE;
479 *ppAuthInfo = pAuthInfo;
481 else if (pAuthInfo->finished)
482 return FALSE;
484 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
485 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
487 ERR("authentication scheme changed from %s to %s\n",
488 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
489 return FALSE;
492 if (is_basic_auth_value(pszAuthValue))
494 int userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
495 int passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
496 char *auth_data;
498 TRACE("basic authentication\n");
500 /* length includes a nul terminator, which will be re-used for the ':' */
501 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
502 if (!auth_data)
503 return FALSE;
505 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
506 auth_data[userlen] = ':';
507 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
509 pAuthInfo->auth_data = auth_data;
510 pAuthInfo->auth_data_len = userlen + 1 + passlen;
511 pAuthInfo->finished = TRUE;
513 return TRUE;
515 else
517 LPCWSTR pszAuthData;
518 SecBufferDesc out_desc, in_desc;
519 SecBuffer out, in;
520 unsigned char *buffer;
521 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
522 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
524 in.BufferType = SECBUFFER_TOKEN;
525 in.cbBuffer = 0;
526 in.pvBuffer = NULL;
528 in_desc.ulVersion = 0;
529 in_desc.cBuffers = 1;
530 in_desc.pBuffers = &in;
532 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
533 if (*pszAuthData == ' ')
535 pszAuthData++;
536 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
537 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
538 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
541 buffer = HeapAlloc(GetProcessHeap(), 0, 0x100);
543 out.BufferType = SECBUFFER_TOKEN;
544 out.cbBuffer = 0x100;
545 out.pvBuffer = buffer;
547 out_desc.ulVersion = 0;
548 out_desc.cBuffers = 1;
549 out_desc.pBuffers = &out;
551 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
552 first ? NULL : &pAuthInfo->ctx,
553 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
554 context_req, 0, SECURITY_NETWORK_DREP,
555 in.pvBuffer ? &in_desc : NULL,
556 0, &pAuthInfo->ctx, &out_desc,
557 &pAuthInfo->attr, &pAuthInfo->exp);
558 if (sec_status == SEC_E_OK)
560 pAuthInfo->finished = TRUE;
561 pAuthInfo->auth_data = out.pvBuffer;
562 pAuthInfo->auth_data_len = out.cbBuffer;
563 TRACE("sending last auth packet\n");
565 else if (sec_status == SEC_I_CONTINUE_NEEDED)
567 pAuthInfo->auth_data = out.pvBuffer;
568 pAuthInfo->auth_data_len = out.cbBuffer;
569 TRACE("sending next auth packet\n");
571 else
573 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
574 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
575 return FALSE;
579 return TRUE;
582 /***********************************************************************
583 * HTTP_HttpAddRequestHeadersW (internal)
585 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
586 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
588 LPWSTR lpszStart;
589 LPWSTR lpszEnd;
590 LPWSTR buffer;
591 BOOL bSuccess = FALSE;
592 DWORD len;
594 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
596 if( dwHeaderLength == ~0U )
597 len = strlenW(lpszHeader);
598 else
599 len = dwHeaderLength;
600 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
601 lstrcpynW( buffer, lpszHeader, len + 1);
603 lpszStart = buffer;
607 LPWSTR * pFieldAndValue;
609 lpszEnd = lpszStart;
611 while (*lpszEnd != '\0')
613 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
614 break;
615 lpszEnd++;
618 if (*lpszStart == '\0')
619 break;
621 if (*lpszEnd == '\r')
623 *lpszEnd = '\0';
624 lpszEnd += 2; /* Jump over \r\n */
626 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
627 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
628 if (pFieldAndValue)
630 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
631 if (bSuccess)
632 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
633 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
634 HTTP_FreeTokens(pFieldAndValue);
637 lpszStart = lpszEnd;
638 } while (bSuccess);
640 HeapFree(GetProcessHeap(), 0, buffer);
642 return bSuccess;
645 /***********************************************************************
646 * HttpAddRequestHeadersW (WININET.@)
648 * Adds one or more HTTP header to the request handler
650 * NOTE
651 * On Windows if dwHeaderLength includes the trailing '\0', then
652 * HttpAddRequestHeadersW() adds it too. However this results in an
653 * invalid Http header which is rejected by some servers so we probably
654 * don't need to match Windows on that point.
656 * RETURNS
657 * TRUE on success
658 * FALSE on failure
661 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
662 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
664 BOOL bSuccess = FALSE;
665 LPWININETHTTPREQW lpwhr;
667 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
669 if (!lpszHeader)
670 return TRUE;
672 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
673 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
675 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
676 goto lend;
678 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
679 lend:
680 if( lpwhr )
681 WININET_Release( &lpwhr->hdr );
683 return bSuccess;
686 /***********************************************************************
687 * HttpAddRequestHeadersA (WININET.@)
689 * Adds one or more HTTP header to the request handler
691 * RETURNS
692 * TRUE on success
693 * FALSE on failure
696 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
697 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
699 DWORD len;
700 LPWSTR hdr;
701 BOOL r;
703 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
705 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
706 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
707 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
708 if( dwHeaderLength != ~0U )
709 dwHeaderLength = len;
711 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
713 HeapFree( GetProcessHeap(), 0, hdr );
715 return r;
718 /***********************************************************************
719 * HttpEndRequestA (WININET.@)
721 * Ends an HTTP request that was started by HttpSendRequestEx
723 * RETURNS
724 * TRUE if successful
725 * FALSE on failure
728 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
729 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
731 LPINTERNET_BUFFERSA ptr;
732 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
733 BOOL rc = FALSE;
735 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
736 dwContext);
738 ptr = lpBuffersOut;
739 if (ptr)
740 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
741 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
742 else
743 lpBuffersOutW = NULL;
745 ptrW = lpBuffersOutW;
746 while (ptr)
748 if (ptr->lpvBuffer && ptr->dwBufferLength)
749 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
750 ptrW->dwBufferLength = ptr->dwBufferLength;
751 ptrW->dwBufferTotal= ptr->dwBufferTotal;
753 if (ptr->Next)
754 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
755 sizeof(INTERNET_BUFFERSW));
757 ptr = ptr->Next;
758 ptrW = ptrW->Next;
761 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
763 if (lpBuffersOutW)
765 ptrW = lpBuffersOutW;
766 while (ptrW)
768 LPINTERNET_BUFFERSW ptrW2;
770 FIXME("Do we need to translate info out of these buffer?\n");
772 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
773 ptrW2 = ptrW->Next;
774 HeapFree(GetProcessHeap(),0,ptrW);
775 ptrW = ptrW2;
779 return rc;
782 /***********************************************************************
783 * HttpEndRequestW (WININET.@)
785 * Ends an HTTP request that was started by HttpSendRequestEx
787 * RETURNS
788 * TRUE if successful
789 * FALSE on failure
792 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
793 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
795 BOOL rc = FALSE;
796 LPWININETHTTPREQW lpwhr;
797 INT responseLen;
798 DWORD dwBufferSize;
800 TRACE("-->\n");
801 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
803 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
805 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
806 if (lpwhr)
807 WININET_Release( &lpwhr->hdr );
808 return FALSE;
811 lpwhr->hdr.dwFlags |= dwFlags;
812 lpwhr->hdr.dwContext = dwContext;
814 /* We appear to do nothing with lpBuffersOut.. is that correct? */
816 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
817 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
819 responseLen = HTTP_GetResponseHeaders(lpwhr);
820 if (responseLen)
821 rc = TRUE;
823 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
824 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
826 /* process cookies here. Is this right? */
827 HTTP_ProcessCookies(lpwhr);
829 dwBufferSize = sizeof(lpwhr->dwContentLength);
830 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
831 &lpwhr->dwContentLength,&dwBufferSize,NULL))
832 lpwhr->dwContentLength = -1;
834 if (lpwhr->dwContentLength == 0)
835 HTTP_FinishedReading(lpwhr);
837 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
839 DWORD dwCode,dwCodeLength=sizeof(DWORD);
840 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
841 (dwCode==302 || dwCode==301))
843 WCHAR szNewLocation[2048];
844 dwBufferSize=sizeof(szNewLocation);
845 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
847 /* redirects are always GETs */
848 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
849 lpwhr->lpszVerb = WININET_strdupW(szGET);
850 HTTP_DrainContent(lpwhr);
851 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
852 if (rc)
853 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
858 WININET_Release( &lpwhr->hdr );
859 TRACE("%i <--\n",rc);
860 return rc;
863 /***********************************************************************
864 * HttpOpenRequestW (WININET.@)
866 * Open a HTTP request handle
868 * RETURNS
869 * HINTERNET a HTTP request handle on success
870 * NULL on failure
873 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
874 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
875 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
876 DWORD dwFlags, DWORD_PTR dwContext)
878 LPWININETHTTPSESSIONW lpwhs;
879 HINTERNET handle = NULL;
881 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
882 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
883 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
884 dwFlags, dwContext);
885 if(lpszAcceptTypes!=NULL)
887 int i;
888 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
889 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
892 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
893 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
895 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
896 goto lend;
900 * My tests seem to show that the windows version does not
901 * become asynchronous until after this point. And anyhow
902 * if this call was asynchronous then how would you get the
903 * necessary HINTERNET pointer returned by this function.
906 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
907 lpszVersion, lpszReferrer, lpszAcceptTypes,
908 dwFlags, dwContext);
909 lend:
910 if( lpwhs )
911 WININET_Release( &lpwhs->hdr );
912 TRACE("returning %p\n", handle);
913 return handle;
917 /***********************************************************************
918 * HttpOpenRequestA (WININET.@)
920 * Open a HTTP request handle
922 * RETURNS
923 * HINTERNET a HTTP request handle on success
924 * NULL on failure
927 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
928 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
929 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
930 DWORD dwFlags, DWORD_PTR dwContext)
932 LPWSTR szVerb = NULL, szObjectName = NULL;
933 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
934 INT len;
935 INT acceptTypesCount;
936 HINTERNET rc = FALSE;
937 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
938 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
939 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
940 dwFlags, dwContext);
942 if (lpszVerb)
944 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
945 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
946 if ( !szVerb )
947 goto end;
948 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
951 if (lpszObjectName)
953 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
954 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
955 if ( !szObjectName )
956 goto end;
957 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
960 if (lpszVersion)
962 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
963 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
964 if ( !szVersion )
965 goto end;
966 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
969 if (lpszReferrer)
971 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
972 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
973 if ( !szReferrer )
974 goto end;
975 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
978 acceptTypesCount = 0;
979 if (lpszAcceptTypes)
981 /* find out how many there are */
982 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
983 acceptTypesCount++;
984 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
985 acceptTypesCount = 0;
986 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
988 len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
989 -1, NULL, 0 );
990 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
991 if (!szAcceptTypes[acceptTypesCount] )
992 goto end;
993 MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
994 -1, szAcceptTypes[acceptTypesCount], len );
995 acceptTypesCount++;
997 szAcceptTypes[acceptTypesCount] = NULL;
999 else szAcceptTypes = 0;
1001 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1002 szVersion, szReferrer,
1003 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1005 end:
1006 if (szAcceptTypes)
1008 acceptTypesCount = 0;
1009 while (szAcceptTypes[acceptTypesCount])
1011 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1012 acceptTypesCount++;
1014 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1016 HeapFree(GetProcessHeap(), 0, szReferrer);
1017 HeapFree(GetProcessHeap(), 0, szVersion);
1018 HeapFree(GetProcessHeap(), 0, szObjectName);
1019 HeapFree(GetProcessHeap(), 0, szVerb);
1021 return rc;
1024 /***********************************************************************
1025 * HTTP_EncodeBase64
1027 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1029 UINT n = 0, x;
1030 static const CHAR HTTP_Base64Enc[] =
1031 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1033 while( len > 0 )
1035 /* first 6 bits, all from bin[0] */
1036 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1037 x = (bin[0] & 3) << 4;
1039 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1040 if( len == 1 )
1042 base64[n++] = HTTP_Base64Enc[x];
1043 base64[n++] = '=';
1044 base64[n++] = '=';
1045 break;
1047 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1048 x = ( bin[1] & 0x0f ) << 2;
1050 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1051 if( len == 2 )
1053 base64[n++] = HTTP_Base64Enc[x];
1054 base64[n++] = '=';
1055 break;
1057 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1059 /* last 6 bits, all from bin [2] */
1060 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1061 bin += 3;
1062 len -= 3;
1064 base64[n] = 0;
1065 return n;
1068 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1069 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1070 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1071 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1072 static const signed char HTTP_Base64Dec[256] =
1074 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1075 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1076 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1077 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1078 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1079 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1080 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1081 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1082 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1083 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1084 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1085 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1086 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1087 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1088 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1089 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1090 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1091 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1092 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1093 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1094 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1095 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1096 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1097 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1098 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1099 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1101 #undef CH
1103 /***********************************************************************
1104 * HTTP_DecodeBase64
1106 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1108 unsigned int n = 0;
1110 while(*base64)
1112 signed char in[4];
1114 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1115 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1116 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1117 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1119 WARN("invalid base64: %s\n", debugstr_w(base64));
1120 return 0;
1122 if (bin)
1123 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1124 n++;
1126 if ((base64[2] == '=') && (base64[3] == '='))
1127 break;
1128 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1129 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1131 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1132 return 0;
1134 if (bin)
1135 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1136 n++;
1138 if (base64[3] == '=')
1139 break;
1140 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1141 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1143 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1144 return 0;
1146 if (bin)
1147 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1148 n++;
1150 base64 += 4;
1153 return n;
1156 /***********************************************************************
1157 * HTTP_InsertAuthorizationForHeader
1159 * Insert or delete the authorization field in the request header.
1161 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR header, BOOL first )
1163 WCHAR *authorization = NULL;
1164 struct HttpAuthInfo *pAuthInfo = lpwhr->pAuthInfo;
1165 DWORD flags;
1167 if (pAuthInfo && pAuthInfo->auth_data_len)
1169 static const WCHAR wszSpace[] = {' ',0};
1170 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1171 unsigned int len;
1173 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1174 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1175 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1176 if (!authorization)
1177 return FALSE;
1179 strcpyW(authorization, pAuthInfo->scheme);
1180 strcatW(authorization, wszSpace);
1181 HTTP_EncodeBase64(pAuthInfo->auth_data,
1182 pAuthInfo->auth_data_len,
1183 authorization+strlenW(authorization));
1185 /* clear the data as it isn't valid now that it has been sent to the
1186 * server, unless it's Basic authentication which doesn't do
1187 * connection tracking */
1188 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1190 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1191 pAuthInfo->auth_data = NULL;
1192 pAuthInfo->auth_data_len = 0;
1196 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1198 /* make sure not to overwrite any caller supplied authorization header */
1199 flags = HTTP_ADDHDR_FLAG_REQ;
1200 flags |= first ? HTTP_ADDHDR_FLAG_ADD_IF_NEW : HTTP_ADDHDR_FLAG_REPLACE;
1202 HTTP_ProcessHeader(lpwhr, header, authorization, flags);
1204 HeapFree(GetProcessHeap(), 0, authorization);
1205 return TRUE;
1208 /***********************************************************************
1209 * HTTP_DealWithProxy
1211 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1212 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1214 WCHAR buf[MAXHOSTNAME];
1215 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1216 WCHAR* url;
1217 static WCHAR szNul[] = { 0 };
1218 URL_COMPONENTSW UrlComponents;
1219 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
1220 static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
1221 static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1222 int len;
1224 memset( &UrlComponents, 0, sizeof UrlComponents );
1225 UrlComponents.dwStructSize = sizeof UrlComponents;
1226 UrlComponents.lpszHostName = buf;
1227 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1229 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1230 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1231 sprintfW(proxy, szFormat1, hIC->lpszProxy);
1232 else
1233 strcpyW(proxy, hIC->lpszProxy);
1234 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1235 return FALSE;
1236 if( UrlComponents.dwHostNameLength == 0 )
1237 return FALSE;
1239 if( !lpwhr->lpszPath )
1240 lpwhr->lpszPath = szNul;
1241 TRACE("server=%s path=%s\n",
1242 debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
1243 /* for constant 15 see above */
1244 len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
1245 url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1247 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1248 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1250 sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
1252 if( lpwhr->lpszPath[0] != '/' )
1253 strcatW( url, szSlash );
1254 strcatW(url, lpwhr->lpszPath);
1255 if(lpwhr->lpszPath != szNul)
1256 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1257 lpwhr->lpszPath = url;
1259 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1260 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1261 lpwhs->nServerPort = UrlComponents.nPort;
1263 return TRUE;
1266 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1268 char szaddr[32];
1269 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1271 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1272 INTERNET_STATUS_RESOLVING_NAME,
1273 lpwhs->lpszServerName,
1274 strlenW(lpwhs->lpszServerName)+1);
1276 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1277 &lpwhs->socketAddress))
1279 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1280 return FALSE;
1283 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1284 szaddr, sizeof(szaddr));
1285 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1286 INTERNET_STATUS_NAME_RESOLVED,
1287 szaddr, strlen(szaddr)+1);
1288 return TRUE;
1292 /***********************************************************************
1293 * HTTPREQ_Destroy (internal)
1295 * Deallocate request handle
1298 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1300 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1301 DWORD i;
1303 TRACE("\n");
1305 if(lpwhr->hCacheFile)
1306 CloseHandle(lpwhr->hCacheFile);
1308 if(lpwhr->lpszCacheFile) {
1309 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1310 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1313 WININET_Release(&lpwhr->lpHttpSession->hdr);
1315 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1316 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1317 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1318 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1319 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1321 for (i = 0; i < lpwhr->nCustHeaders; i++)
1323 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1324 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1327 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1328 HeapFree(GetProcessHeap(), 0, lpwhr);
1331 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1333 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1334 LPWININETHTTPSESSIONW lpwhs = NULL;
1335 LPWININETAPPINFOW hIC = NULL;
1337 TRACE("%p\n",lpwhr);
1339 if (!NETCON_connected(&lpwhr->netConnection))
1340 return;
1342 if (lpwhr->pAuthInfo)
1344 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1345 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1347 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1348 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1349 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1350 lpwhr->pAuthInfo = NULL;
1352 if (lpwhr->pProxyAuthInfo)
1354 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1355 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1357 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1358 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1359 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1360 lpwhr->pProxyAuthInfo = NULL;
1363 lpwhs = lpwhr->lpHttpSession;
1364 hIC = lpwhs->lpAppInfo;
1366 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1367 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1369 NETCON_close(&lpwhr->netConnection);
1371 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1372 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1375 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1377 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1379 switch(option) {
1380 case INTERNET_OPTION_SEND_TIMEOUT:
1381 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1382 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1384 if (size != sizeof(DWORD))
1385 return ERROR_INVALID_PARAMETER;
1387 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1388 *(DWORD*)buffer);
1391 return ERROR_INTERNET_INVALID_OPTION;
1394 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1396 int bytes_read;
1398 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1399 sync ? MSG_WAITALL : 0, &bytes_read)) {
1400 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1401 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1403 /* always returns TRUE, even if the network layer returns an
1404 * error */
1405 *read = 0;
1406 HTTP_FinishedReading(req);
1407 return ERROR_SUCCESS;
1410 req->dwContentRead += bytes_read;
1411 *read = bytes_read;
1413 if(req->lpszCacheFile) {
1414 BOOL res;
1416 res = WriteFile(req->hCacheFile, buffer, bytes_read, NULL, NULL);
1417 if(!res)
1418 WARN("WriteFile failed: %u\n", GetLastError());
1421 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1422 HTTP_FinishedReading(req);
1424 return ERROR_SUCCESS;
1427 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1429 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1431 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1434 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1436 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1437 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1438 INTERNET_ASYNC_RESULT iar;
1439 DWORD res;
1441 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1443 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1444 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1446 iar.dwResult = res == ERROR_SUCCESS;
1447 iar.dwError = res;
1449 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1450 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1451 sizeof(INTERNET_ASYNC_RESULT));
1454 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1455 DWORD flags, DWORD_PTR context)
1458 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1459 DWORD res;
1461 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1462 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1464 if (buffers->dwStructSize != sizeof(*buffers))
1465 return ERROR_INVALID_PARAMETER;
1467 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1469 /* FIXME: IRF_ASYNC may not be the right thing to test here;
1470 * hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC is probably better */
1471 if (flags & IRF_ASYNC) {
1472 DWORD available = 0;
1474 NETCON_query_data_available(&req->netConnection, &available);
1475 if (!available)
1477 WORKREQUEST workRequest;
1479 workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1480 workRequest.hdr = WININET_AddRef(&req->hdr);
1481 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1483 INTERNET_AsyncCall(&workRequest);
1485 return ERROR_IO_PENDING;
1489 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1490 !(flags & IRF_NO_WAIT));
1492 if (res == ERROR_SUCCESS) {
1493 DWORD size = buffers->dwBufferLength;
1494 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1495 &size, sizeof(size));
1498 return res;
1501 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1503 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1505 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1508 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1510 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1511 INTERNET_ASYNC_RESULT iar;
1512 char buffer[4048];
1514 TRACE("%p\n", workRequest->hdr);
1516 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1517 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1518 MSG_PEEK, (int *)&iar.dwError);
1520 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1521 sizeof(INTERNET_ASYNC_RESULT));
1524 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1526 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1527 BYTE buffer[4048];
1528 BOOL async;
1530 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1532 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1533 return ERROR_SUCCESS;
1535 /* Even if we are in async mode, we need to determine whether
1536 * there is actually more data available. We do this by trying
1537 * to peek only a single byte in async mode. */
1538 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1540 if (NETCON_recv(&req->netConnection, buffer,
1541 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1542 MSG_PEEK, (int *)available) && async && *available)
1544 WORKREQUEST workRequest;
1546 *available = 0;
1547 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1548 workRequest.hdr = WININET_AddRef( &req->hdr );
1550 INTERNET_AsyncCall(&workRequest);
1552 return ERROR_IO_PENDING;
1555 return ERROR_SUCCESS;
1558 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1559 HTTPREQ_Destroy,
1560 HTTPREQ_CloseConnection,
1561 HTTPREQ_SetOption,
1562 HTTPREQ_ReadFile,
1563 HTTPREQ_ReadFileExA,
1564 HTTPREQ_WriteFile,
1565 HTTPREQ_QueryDataAvailable,
1566 NULL
1569 /***********************************************************************
1570 * HTTP_HttpOpenRequestW (internal)
1572 * Open a HTTP request handle
1574 * RETURNS
1575 * HINTERNET a HTTP request handle on success
1576 * NULL on failure
1579 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1580 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1581 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1582 DWORD dwFlags, DWORD_PTR dwContext)
1584 LPWININETAPPINFOW hIC = NULL;
1585 LPWININETHTTPREQW lpwhr;
1586 LPWSTR lpszCookies;
1587 LPWSTR lpszUrl = NULL;
1588 DWORD nCookieSize;
1589 HINTERNET handle = NULL;
1590 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1591 DWORD len;
1592 LPHTTPHEADERW Host;
1594 TRACE("-->\n");
1596 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1597 hIC = lpwhs->lpAppInfo;
1599 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1600 if (NULL == lpwhr)
1602 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1603 goto lend;
1605 lpwhr->hdr.htype = WH_HHTTPREQ;
1606 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1607 lpwhr->hdr.dwFlags = dwFlags;
1608 lpwhr->hdr.dwContext = dwContext;
1609 lpwhr->hdr.dwRefCount = 1;
1610 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1611 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1613 WININET_AddRef( &lpwhs->hdr );
1614 lpwhr->lpHttpSession = lpwhs;
1615 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1617 handle = WININET_AllocHandle( &lpwhr->hdr );
1618 if (NULL == handle)
1620 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1621 goto lend;
1624 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1626 InternetCloseHandle( handle );
1627 handle = NULL;
1628 goto lend;
1631 if (lpszObjectName && *lpszObjectName) {
1632 HRESULT rc;
1634 len = 0;
1635 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1636 if (rc != E_POINTER)
1637 len = strlenW(lpszObjectName)+1;
1638 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1639 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1640 URL_ESCAPE_SPACES_ONLY);
1641 if (rc)
1643 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1644 strcpyW(lpwhr->lpszPath,lpszObjectName);
1648 if (lpszReferrer && *lpszReferrer)
1649 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1651 if (lpszAcceptTypes)
1653 int i;
1654 for (i = 0; lpszAcceptTypes[i]; i++)
1656 if (!*lpszAcceptTypes[i]) continue;
1657 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1658 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1659 HTTP_ADDHDR_FLAG_REQ |
1660 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1664 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1666 if (lpszVersion)
1667 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1668 else
1669 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1671 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1673 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1674 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1675 INTERNET_DEFAULT_HTTPS_PORT :
1676 INTERNET_DEFAULT_HTTP_PORT);
1677 lpwhs->nHostPort = lpwhs->nServerPort;
1679 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1680 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1682 if (hIC->lpszAgent)
1684 WCHAR *agent_header;
1685 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1687 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1688 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1689 sprintfW(agent_header, user_agent, hIC->lpszAgent );
1691 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1692 HTTP_ADDREQ_FLAG_ADD);
1693 HeapFree(GetProcessHeap(), 0, agent_header);
1696 Host = HTTP_GetHeader(lpwhr,szHost);
1698 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1699 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1700 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1702 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1703 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1705 int cnt = 0;
1706 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1707 static const WCHAR szcrlf[] = {'\r','\n',0};
1709 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1711 cnt += sprintfW(lpszCookies, szCookie);
1712 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1713 strcatW(lpszCookies, szcrlf);
1715 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1716 HTTP_ADDREQ_FLAG_ADD);
1717 HeapFree(GetProcessHeap(), 0, lpszCookies);
1719 HeapFree(GetProcessHeap(), 0, lpszUrl);
1722 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1723 INTERNET_STATUS_HANDLE_CREATED, &handle,
1724 sizeof(handle));
1727 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1730 if (!HTTP_ResolveName(lpwhr))
1732 InternetCloseHandle( handle );
1733 handle = NULL;
1736 lend:
1737 if( lpwhr )
1738 WININET_Release( &lpwhr->hdr );
1740 TRACE("<-- %p (%p)\n", handle, lpwhr);
1741 return handle;
1744 /* read any content returned by the server so that the connection can be
1745 * reused */
1746 static void HTTP_DrainContent(WININETHTTPREQW *req)
1748 DWORD bytes_read;
1750 if (!NETCON_connected(&req->netConnection)) return;
1752 if (req->dwContentLength == -1)
1753 NETCON_close(&req->netConnection);
1757 char buffer[2048];
1758 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
1759 return;
1760 } while (bytes_read);
1763 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1764 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1765 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1766 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1767 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1768 static const WCHAR szAge[] = { 'A','g','e',0 };
1769 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1770 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1771 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1772 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1773 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1774 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1775 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1776 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1777 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1778 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1779 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1780 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 };
1781 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1782 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1783 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1784 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1785 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1786 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1787 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1788 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1789 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1790 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1791 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1792 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1793 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1794 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1795 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1796 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1797 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1798 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1799 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1800 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1801 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1802 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1803 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1804 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1805 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1806 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1807 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 };
1808 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1809 static const WCHAR szURI[] = { 'U','R','I',0 };
1810 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1811 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1812 static const WCHAR szVia[] = { 'V','i','a',0 };
1813 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1814 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1816 static const LPCWSTR header_lookup[] = {
1817 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
1818 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
1819 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1820 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
1821 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1822 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
1823 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
1824 szAllow, /* HTTP_QUERY_ALLOW = 7 */
1825 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
1826 szDate, /* HTTP_QUERY_DATE = 9 */
1827 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
1828 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
1829 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
1830 szURI, /* HTTP_QUERY_URI = 13 */
1831 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
1832 NULL, /* HTTP_QUERY_COST = 15 */
1833 NULL, /* HTTP_QUERY_LINK = 16 */
1834 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
1835 NULL, /* HTTP_QUERY_VERSION = 18 */
1836 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
1837 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
1838 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
1839 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
1840 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
1841 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
1842 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
1843 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
1844 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
1845 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
1846 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
1847 NULL, /* HTTP_QUERY_FORWARDED = 30 */
1848 NULL, /* HTTP_QUERY_FROM = 31 */
1849 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
1850 szLocation, /* HTTP_QUERY_LOCATION = 33 */
1851 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
1852 szReferer, /* HTTP_QUERY_REFERER = 35 */
1853 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
1854 szServer, /* HTTP_QUERY_SERVER = 37 */
1855 NULL, /* HTTP_TITLE = 38 */
1856 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
1857 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
1858 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
1859 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
1860 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
1861 szCookie, /* HTTP_QUERY_COOKIE = 44 */
1862 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
1863 NULL, /* HTTP_QUERY_REFRESH = 46 */
1864 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
1865 szAge, /* HTTP_QUERY_AGE = 48 */
1866 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
1867 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
1868 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
1869 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
1870 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
1871 szETag, /* HTTP_QUERY_ETAG = 54 */
1872 szHost, /* HTTP_QUERY_HOST = 55 */
1873 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
1874 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
1875 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
1876 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
1877 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
1878 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
1879 szRange, /* HTTP_QUERY_RANGE = 62 */
1880 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
1881 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
1882 szVary, /* HTTP_QUERY_VARY = 65 */
1883 szVia, /* HTTP_QUERY_VIA = 66 */
1884 szWarning, /* HTTP_QUERY_WARNING = 67 */
1885 szExpect, /* HTTP_QUERY_EXPECT = 68 */
1886 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
1887 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
1890 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
1892 /***********************************************************************
1893 * HTTP_HttpQueryInfoW (internal)
1895 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1896 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1898 LPHTTPHEADERW lphttpHdr = NULL;
1899 BOOL bSuccess = FALSE;
1900 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1901 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
1902 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
1903 INT index = -1;
1905 /* Find requested header structure */
1906 switch (level)
1908 case HTTP_QUERY_CUSTOM:
1909 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
1910 break;
1912 case HTTP_QUERY_RAW_HEADERS_CRLF:
1914 LPWSTR headers;
1915 DWORD len;
1916 BOOL ret;
1918 if (request_only)
1919 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
1920 else
1921 headers = lpwhr->lpszRawHeaders;
1923 len = strlenW(headers);
1924 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1926 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1927 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1928 ret = FALSE;
1929 } else
1931 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
1932 *lpdwBufferLength = len * sizeof(WCHAR);
1934 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1935 ret = TRUE;
1938 if (request_only)
1939 HeapFree(GetProcessHeap(), 0, headers);
1940 return ret;
1942 case HTTP_QUERY_RAW_HEADERS:
1944 static const WCHAR szCrLf[] = {'\r','\n',0};
1945 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1946 DWORD i, size = 0;
1947 LPWSTR pszString = (WCHAR*)lpBuffer;
1949 for (i = 0; ppszRawHeaderLines[i]; i++)
1950 size += strlenW(ppszRawHeaderLines[i]) + 1;
1952 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1954 HTTP_FreeTokens(ppszRawHeaderLines);
1955 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1956 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1957 return FALSE;
1960 for (i = 0; ppszRawHeaderLines[i]; i++)
1962 DWORD len = strlenW(ppszRawHeaderLines[i]);
1963 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1964 pszString += len+1;
1966 *pszString = '\0';
1968 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1970 *lpdwBufferLength = size * sizeof(WCHAR);
1971 HTTP_FreeTokens(ppszRawHeaderLines);
1973 return TRUE;
1975 case HTTP_QUERY_STATUS_TEXT:
1976 if (lpwhr->lpszStatusText)
1978 DWORD len = strlenW(lpwhr->lpszStatusText);
1979 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1981 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1982 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1983 return FALSE;
1985 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1986 *lpdwBufferLength = len * sizeof(WCHAR);
1988 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1990 return TRUE;
1992 break;
1993 case HTTP_QUERY_VERSION:
1994 if (lpwhr->lpszVersion)
1996 DWORD len = strlenW(lpwhr->lpszVersion);
1997 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1999 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2000 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2001 return FALSE;
2003 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
2004 *lpdwBufferLength = len * sizeof(WCHAR);
2006 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2008 return TRUE;
2010 break;
2011 default:
2012 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2014 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
2015 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2016 requested_index,request_only);
2019 if (index >= 0)
2020 lphttpHdr = &lpwhr->pCustHeaders[index];
2022 /* Ensure header satisfies requested attributes */
2023 if (!lphttpHdr ||
2024 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2025 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2027 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2028 return bSuccess;
2031 if (lpdwIndex)
2032 (*lpdwIndex)++;
2034 /* coalesce value to requested type */
2035 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
2037 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2038 bSuccess = TRUE;
2040 TRACE(" returning number : %d\n", *(int *)lpBuffer);
2042 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
2044 time_t tmpTime;
2045 struct tm tmpTM;
2046 SYSTEMTIME *STHook;
2048 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2050 tmpTM = *gmtime(&tmpTime);
2051 STHook = (SYSTEMTIME *) lpBuffer;
2052 if(STHook==NULL)
2053 return bSuccess;
2055 STHook->wDay = tmpTM.tm_mday;
2056 STHook->wHour = tmpTM.tm_hour;
2057 STHook->wMilliseconds = 0;
2058 STHook->wMinute = tmpTM.tm_min;
2059 STHook->wDayOfWeek = tmpTM.tm_wday;
2060 STHook->wMonth = tmpTM.tm_mon + 1;
2061 STHook->wSecond = tmpTM.tm_sec;
2062 STHook->wYear = tmpTM.tm_year;
2064 bSuccess = TRUE;
2066 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2067 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2068 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2070 else if (lphttpHdr->lpszValue)
2072 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2074 if (len > *lpdwBufferLength)
2076 *lpdwBufferLength = len;
2077 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2078 return bSuccess;
2081 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2082 *lpdwBufferLength = len - sizeof(WCHAR);
2083 bSuccess = TRUE;
2085 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
2087 return bSuccess;
2090 /***********************************************************************
2091 * HttpQueryInfoW (WININET.@)
2093 * Queries for information about an HTTP request
2095 * RETURNS
2096 * TRUE on success
2097 * FALSE on failure
2100 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2101 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2103 BOOL bSuccess = FALSE;
2104 LPWININETHTTPREQW lpwhr;
2106 if (TRACE_ON(wininet)) {
2107 #define FE(x) { x, #x }
2108 static const wininet_flag_info query_flags[] = {
2109 FE(HTTP_QUERY_MIME_VERSION),
2110 FE(HTTP_QUERY_CONTENT_TYPE),
2111 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2112 FE(HTTP_QUERY_CONTENT_ID),
2113 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2114 FE(HTTP_QUERY_CONTENT_LENGTH),
2115 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2116 FE(HTTP_QUERY_ALLOW),
2117 FE(HTTP_QUERY_PUBLIC),
2118 FE(HTTP_QUERY_DATE),
2119 FE(HTTP_QUERY_EXPIRES),
2120 FE(HTTP_QUERY_LAST_MODIFIED),
2121 FE(HTTP_QUERY_MESSAGE_ID),
2122 FE(HTTP_QUERY_URI),
2123 FE(HTTP_QUERY_DERIVED_FROM),
2124 FE(HTTP_QUERY_COST),
2125 FE(HTTP_QUERY_LINK),
2126 FE(HTTP_QUERY_PRAGMA),
2127 FE(HTTP_QUERY_VERSION),
2128 FE(HTTP_QUERY_STATUS_CODE),
2129 FE(HTTP_QUERY_STATUS_TEXT),
2130 FE(HTTP_QUERY_RAW_HEADERS),
2131 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2132 FE(HTTP_QUERY_CONNECTION),
2133 FE(HTTP_QUERY_ACCEPT),
2134 FE(HTTP_QUERY_ACCEPT_CHARSET),
2135 FE(HTTP_QUERY_ACCEPT_ENCODING),
2136 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2137 FE(HTTP_QUERY_AUTHORIZATION),
2138 FE(HTTP_QUERY_CONTENT_ENCODING),
2139 FE(HTTP_QUERY_FORWARDED),
2140 FE(HTTP_QUERY_FROM),
2141 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2142 FE(HTTP_QUERY_LOCATION),
2143 FE(HTTP_QUERY_ORIG_URI),
2144 FE(HTTP_QUERY_REFERER),
2145 FE(HTTP_QUERY_RETRY_AFTER),
2146 FE(HTTP_QUERY_SERVER),
2147 FE(HTTP_QUERY_TITLE),
2148 FE(HTTP_QUERY_USER_AGENT),
2149 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2150 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2151 FE(HTTP_QUERY_ACCEPT_RANGES),
2152 FE(HTTP_QUERY_SET_COOKIE),
2153 FE(HTTP_QUERY_COOKIE),
2154 FE(HTTP_QUERY_REQUEST_METHOD),
2155 FE(HTTP_QUERY_REFRESH),
2156 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2157 FE(HTTP_QUERY_AGE),
2158 FE(HTTP_QUERY_CACHE_CONTROL),
2159 FE(HTTP_QUERY_CONTENT_BASE),
2160 FE(HTTP_QUERY_CONTENT_LOCATION),
2161 FE(HTTP_QUERY_CONTENT_MD5),
2162 FE(HTTP_QUERY_CONTENT_RANGE),
2163 FE(HTTP_QUERY_ETAG),
2164 FE(HTTP_QUERY_HOST),
2165 FE(HTTP_QUERY_IF_MATCH),
2166 FE(HTTP_QUERY_IF_NONE_MATCH),
2167 FE(HTTP_QUERY_IF_RANGE),
2168 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2169 FE(HTTP_QUERY_MAX_FORWARDS),
2170 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2171 FE(HTTP_QUERY_RANGE),
2172 FE(HTTP_QUERY_TRANSFER_ENCODING),
2173 FE(HTTP_QUERY_UPGRADE),
2174 FE(HTTP_QUERY_VARY),
2175 FE(HTTP_QUERY_VIA),
2176 FE(HTTP_QUERY_WARNING),
2177 FE(HTTP_QUERY_CUSTOM)
2179 static const wininet_flag_info modifier_flags[] = {
2180 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2181 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2182 FE(HTTP_QUERY_FLAG_NUMBER),
2183 FE(HTTP_QUERY_FLAG_COALESCE)
2185 #undef FE
2186 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2187 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2188 DWORD i;
2190 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2191 TRACE(" Attribute:");
2192 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2193 if (query_flags[i].val == info) {
2194 TRACE(" %s", query_flags[i].name);
2195 break;
2198 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2199 TRACE(" Unknown (%08x)", info);
2202 TRACE(" Modifier:");
2203 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2204 if (modifier_flags[i].val & info_mod) {
2205 TRACE(" %s", modifier_flags[i].name);
2206 info_mod &= ~ modifier_flags[i].val;
2210 if (info_mod) {
2211 TRACE(" Unknown (%08x)", info_mod);
2213 TRACE("\n");
2216 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2217 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2219 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2220 goto lend;
2223 if (lpBuffer == NULL)
2224 *lpdwBufferLength = 0;
2225 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2226 lpBuffer, lpdwBufferLength, lpdwIndex);
2228 lend:
2229 if( lpwhr )
2230 WININET_Release( &lpwhr->hdr );
2232 TRACE("%d <--\n", bSuccess);
2233 return bSuccess;
2236 /***********************************************************************
2237 * HttpQueryInfoA (WININET.@)
2239 * Queries for information about an HTTP request
2241 * RETURNS
2242 * TRUE on success
2243 * FALSE on failure
2246 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2247 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2249 BOOL result;
2250 DWORD len;
2251 WCHAR* bufferW;
2253 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2254 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2256 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2257 lpdwBufferLength, lpdwIndex );
2260 if (lpBuffer)
2262 DWORD alloclen;
2263 len = (*lpdwBufferLength)*sizeof(WCHAR);
2264 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2266 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2267 if (alloclen < len)
2268 alloclen = len;
2270 else
2271 alloclen = len;
2272 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2273 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2274 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2275 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2276 } else
2278 bufferW = NULL;
2279 len = 0;
2282 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2283 &len, lpdwIndex );
2284 if( result )
2286 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2287 lpBuffer, *lpdwBufferLength, NULL, NULL );
2288 *lpdwBufferLength = len - 1;
2290 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2292 else
2293 /* since the strings being returned from HttpQueryInfoW should be
2294 * only ASCII characters, it is reasonable to assume that all of
2295 * the Unicode characters can be reduced to a single byte */
2296 *lpdwBufferLength = len / sizeof(WCHAR);
2298 HeapFree(GetProcessHeap(), 0, bufferW );
2300 return result;
2303 /***********************************************************************
2304 * HttpSendRequestExA (WININET.@)
2306 * Sends the specified request to the HTTP server and allows chunked
2307 * transfers.
2309 * RETURNS
2310 * Success: TRUE
2311 * Failure: FALSE, call GetLastError() for more information.
2313 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2314 LPINTERNET_BUFFERSA lpBuffersIn,
2315 LPINTERNET_BUFFERSA lpBuffersOut,
2316 DWORD dwFlags, DWORD_PTR dwContext)
2318 INTERNET_BUFFERSW BuffersInW;
2319 BOOL rc = FALSE;
2320 DWORD headerlen;
2321 LPWSTR header = NULL;
2323 TRACE("(%p, %p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersIn,
2324 lpBuffersOut, dwFlags, dwContext);
2326 if (lpBuffersIn)
2328 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2329 if (lpBuffersIn->lpcszHeader)
2331 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2332 lpBuffersIn->dwHeadersLength,0,0);
2333 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2334 if (!(BuffersInW.lpcszHeader = header))
2336 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2337 return FALSE;
2339 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2340 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2341 header, headerlen);
2343 else
2344 BuffersInW.lpcszHeader = NULL;
2345 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2346 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2347 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2348 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2349 BuffersInW.Next = NULL;
2352 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2354 HeapFree(GetProcessHeap(),0,header);
2356 return rc;
2359 /***********************************************************************
2360 * HttpSendRequestExW (WININET.@)
2362 * Sends the specified request to the HTTP server and allows chunked
2363 * transfers
2365 * RETURNS
2366 * Success: TRUE
2367 * Failure: FALSE, call GetLastError() for more information.
2369 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2370 LPINTERNET_BUFFERSW lpBuffersIn,
2371 LPINTERNET_BUFFERSW lpBuffersOut,
2372 DWORD dwFlags, DWORD_PTR dwContext)
2374 BOOL ret = FALSE;
2375 LPWININETHTTPREQW lpwhr;
2376 LPWININETHTTPSESSIONW lpwhs;
2377 LPWININETAPPINFOW hIC;
2379 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2380 lpBuffersOut, dwFlags, dwContext);
2382 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2384 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2386 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2387 goto lend;
2390 lpwhs = lpwhr->lpHttpSession;
2391 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2392 hIC = lpwhs->lpAppInfo;
2393 assert(hIC->hdr.htype == WH_HINIT);
2395 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2397 WORKREQUEST workRequest;
2398 struct WORKREQ_HTTPSENDREQUESTW *req;
2400 workRequest.asyncproc = AsyncHttpSendRequestProc;
2401 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2402 req = &workRequest.u.HttpSendRequestW;
2403 if (lpBuffersIn)
2405 if (lpBuffersIn->lpcszHeader)
2406 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2407 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2408 else
2409 req->lpszHeader = NULL;
2410 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2411 req->lpOptional = lpBuffersIn->lpvBuffer;
2412 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2413 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2415 else
2417 req->lpszHeader = NULL;
2418 req->dwHeaderLength = 0;
2419 req->lpOptional = NULL;
2420 req->dwOptionalLength = 0;
2421 req->dwContentLength = 0;
2424 req->bEndRequest = FALSE;
2426 INTERNET_AsyncCall(&workRequest);
2428 * This is from windows.
2430 INTERNET_SetLastError(ERROR_IO_PENDING);
2432 else
2434 if (lpBuffersIn)
2435 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2436 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2437 lpBuffersIn->dwBufferTotal, FALSE);
2438 else
2439 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2442 lend:
2443 if ( lpwhr )
2444 WININET_Release( &lpwhr->hdr );
2446 TRACE("<---\n");
2447 return ret;
2450 /***********************************************************************
2451 * HttpSendRequestW (WININET.@)
2453 * Sends the specified request to the HTTP server
2455 * RETURNS
2456 * TRUE on success
2457 * FALSE on failure
2460 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2461 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2463 LPWININETHTTPREQW lpwhr;
2464 LPWININETHTTPSESSIONW lpwhs = NULL;
2465 LPWININETAPPINFOW hIC = NULL;
2466 BOOL r;
2468 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2469 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2471 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2472 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2474 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2475 r = FALSE;
2476 goto lend;
2479 lpwhs = lpwhr->lpHttpSession;
2480 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2482 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2483 r = FALSE;
2484 goto lend;
2487 hIC = lpwhs->lpAppInfo;
2488 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2490 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2491 r = FALSE;
2492 goto lend;
2495 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2497 WORKREQUEST workRequest;
2498 struct WORKREQ_HTTPSENDREQUESTW *req;
2500 workRequest.asyncproc = AsyncHttpSendRequestProc;
2501 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2502 req = &workRequest.u.HttpSendRequestW;
2503 if (lpszHeaders)
2505 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2506 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2508 else
2509 req->lpszHeader = 0;
2510 req->dwHeaderLength = dwHeaderLength;
2511 req->lpOptional = lpOptional;
2512 req->dwOptionalLength = dwOptionalLength;
2513 req->dwContentLength = dwOptionalLength;
2514 req->bEndRequest = TRUE;
2516 INTERNET_AsyncCall(&workRequest);
2518 * This is from windows.
2520 INTERNET_SetLastError(ERROR_IO_PENDING);
2521 r = FALSE;
2523 else
2525 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2526 dwHeaderLength, lpOptional, dwOptionalLength,
2527 dwOptionalLength, TRUE);
2529 lend:
2530 if( lpwhr )
2531 WININET_Release( &lpwhr->hdr );
2532 return r;
2535 /***********************************************************************
2536 * HttpSendRequestA (WININET.@)
2538 * Sends the specified request to the HTTP server
2540 * RETURNS
2541 * TRUE on success
2542 * FALSE on failure
2545 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2546 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2548 BOOL result;
2549 LPWSTR szHeaders=NULL;
2550 DWORD nLen=dwHeaderLength;
2551 if(lpszHeaders!=NULL)
2553 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2554 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2555 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2557 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2558 HeapFree(GetProcessHeap(),0,szHeaders);
2559 return result;
2562 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2564 LPHTTPHEADERW host_header;
2566 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2568 host_header = HTTP_GetHeader(req, szHost);
2569 if(!host_header)
2570 return FALSE;
2572 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2573 return TRUE;
2576 /***********************************************************************
2577 * HTTP_HandleRedirect (internal)
2579 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2581 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2582 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2583 WCHAR path[2048];
2585 if(lpszUrl[0]=='/')
2587 /* if it's an absolute path, keep the same session info */
2588 lstrcpynW(path, lpszUrl, 2048);
2590 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2592 TRACE("Redirect through proxy\n");
2593 lstrcpynW(path, lpszUrl, 2048);
2595 else
2597 URL_COMPONENTSW urlComponents;
2598 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2599 static WCHAR szHttp[] = {'h','t','t','p',0};
2600 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2601 DWORD url_length = 0;
2602 LPWSTR orig_url;
2603 LPWSTR combined_url;
2605 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2606 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2607 urlComponents.dwSchemeLength = 0;
2608 urlComponents.lpszHostName = lpwhs->lpszHostName;
2609 urlComponents.dwHostNameLength = 0;
2610 urlComponents.nPort = lpwhs->nHostPort;
2611 urlComponents.lpszUserName = lpwhs->lpszUserName;
2612 urlComponents.dwUserNameLength = 0;
2613 urlComponents.lpszPassword = NULL;
2614 urlComponents.dwPasswordLength = 0;
2615 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2616 urlComponents.dwUrlPathLength = 0;
2617 urlComponents.lpszExtraInfo = NULL;
2618 urlComponents.dwExtraInfoLength = 0;
2620 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2621 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2622 return FALSE;
2624 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2626 /* convert from bytes to characters */
2627 url_length = url_length / sizeof(WCHAR) - 1;
2628 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2630 HeapFree(GetProcessHeap(), 0, orig_url);
2631 return FALSE;
2634 url_length = 0;
2635 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2636 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2638 HeapFree(GetProcessHeap(), 0, orig_url);
2639 return FALSE;
2641 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2643 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2645 HeapFree(GetProcessHeap(), 0, orig_url);
2646 HeapFree(GetProcessHeap(), 0, combined_url);
2647 return FALSE;
2649 HeapFree(GetProcessHeap(), 0, orig_url);
2651 userName[0] = 0;
2652 hostName[0] = 0;
2653 protocol[0] = 0;
2655 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2656 urlComponents.lpszScheme = protocol;
2657 urlComponents.dwSchemeLength = 32;
2658 urlComponents.lpszHostName = hostName;
2659 urlComponents.dwHostNameLength = MAXHOSTNAME;
2660 urlComponents.lpszUserName = userName;
2661 urlComponents.dwUserNameLength = 1024;
2662 urlComponents.lpszPassword = NULL;
2663 urlComponents.dwPasswordLength = 0;
2664 urlComponents.lpszUrlPath = path;
2665 urlComponents.dwUrlPathLength = 2048;
2666 urlComponents.lpszExtraInfo = NULL;
2667 urlComponents.dwExtraInfoLength = 0;
2668 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2670 HeapFree(GetProcessHeap(), 0, combined_url);
2671 return FALSE;
2674 HeapFree(GetProcessHeap(), 0, combined_url);
2676 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2677 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2679 TRACE("redirect from secure page to non-secure page\n");
2680 /* FIXME: warn about from secure redirect to non-secure page */
2681 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2683 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2684 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2686 TRACE("redirect from non-secure page to secure page\n");
2687 /* FIXME: notify about redirect to secure page */
2688 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2691 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2693 if (lstrlenW(protocol)>4) /*https*/
2694 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2695 else /*http*/
2696 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2699 #if 0
2701 * This upsets redirects to binary files on sourceforge.net
2702 * and gives an html page instead of the target file
2703 * Examination of the HTTP request sent by native wininet.dll
2704 * reveals that it doesn't send a referrer in that case.
2705 * Maybe there's a flag that enables this, or maybe a referrer
2706 * shouldn't be added in case of a redirect.
2709 /* consider the current host as the referrer */
2710 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2711 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2712 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2713 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2714 #endif
2716 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2717 lpwhs->lpszServerName = WININET_strdupW(hostName);
2718 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2719 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2720 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2722 int len;
2723 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2724 len = lstrlenW(hostName);
2725 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2726 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2727 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2729 else
2730 lpwhs->lpszHostName = WININET_strdupW(hostName);
2732 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2735 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2736 lpwhs->lpszUserName = NULL;
2737 if (userName[0])
2738 lpwhs->lpszUserName = WININET_strdupW(userName);
2739 lpwhs->nServerPort = urlComponents.nPort;
2741 if (!HTTP_ResolveName(lpwhr))
2742 return FALSE;
2744 NETCON_close(&lpwhr->netConnection);
2746 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2747 return FALSE;
2750 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2751 lpwhr->lpszPath=NULL;
2752 if (*path)
2754 DWORD needed = 0;
2755 HRESULT rc;
2757 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2758 if (rc != E_POINTER)
2759 needed = strlenW(path)+1;
2760 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2761 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2762 URL_ESCAPE_SPACES_ONLY);
2763 if (rc)
2765 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2766 strcpyW(lpwhr->lpszPath,path);
2770 return TRUE;
2773 /***********************************************************************
2774 * HTTP_build_req (internal)
2776 * concatenate all the strings in the request together
2778 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2780 LPCWSTR *t;
2781 LPWSTR str;
2783 for( t = list; *t ; t++ )
2784 len += strlenW( *t );
2785 len++;
2787 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2788 *str = 0;
2790 for( t = list; *t ; t++ )
2791 strcatW( str, *t );
2793 return str;
2796 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2798 LPWSTR lpszPath;
2799 LPWSTR requestString;
2800 INT len;
2801 INT cnt;
2802 INT responseLen;
2803 char *ascii_req;
2804 BOOL ret;
2805 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2806 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2807 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2809 TRACE("\n");
2811 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2812 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2813 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
2814 HeapFree( GetProcessHeap(), 0, lpszPath );
2816 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2817 NULL, 0, NULL, NULL );
2818 len--; /* the nul terminator isn't needed */
2819 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2820 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2821 ascii_req, len, NULL, NULL );
2822 HeapFree( GetProcessHeap(), 0, requestString );
2824 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2826 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2827 HeapFree( GetProcessHeap(), 0, ascii_req );
2828 if (!ret || cnt < 0)
2829 return FALSE;
2831 responseLen = HTTP_GetResponseHeaders( lpwhr );
2832 if (!responseLen)
2833 return FALSE;
2835 return TRUE;
2838 /***********************************************************************
2839 * HTTP_HttpSendRequestW (internal)
2841 * Sends the specified request to the HTTP server
2843 * RETURNS
2844 * TRUE on success
2845 * FALSE on failure
2848 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2849 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2850 DWORD dwContentLength, BOOL bEndRequest)
2852 INT cnt;
2853 BOOL bSuccess = FALSE;
2854 LPWSTR requestString = NULL;
2855 INT responseLen;
2856 BOOL loop_next;
2857 INTERNET_ASYNC_RESULT iar;
2858 static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
2859 static const WCHAR szPost[] = { 'P','O','S','T',0 };
2860 static const WCHAR szContentLength[] =
2861 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
2862 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
2864 TRACE("--> %p\n", lpwhr);
2866 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2868 /* Clear any error information */
2869 INTERNET_SetLastError(0);
2871 /* if the verb is NULL default to GET */
2872 if (!lpwhr->lpszVerb)
2873 lpwhr->lpszVerb = WININET_strdupW(szGET);
2875 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
2877 sprintfW(contentLengthStr, szContentLength, dwContentLength);
2878 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2883 DWORD len;
2884 char *ascii_req;
2886 loop_next = FALSE;
2888 /* like native, just in case the caller forgot to call InternetReadFile
2889 * for all the data */
2890 HTTP_DrainContent(lpwhr);
2891 lpwhr->dwContentRead = 0;
2893 if (TRACE_ON(wininet))
2895 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
2896 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2899 HTTP_FixURL(lpwhr);
2900 HTTP_ProcessHeader(lpwhr, szConnection,
2901 lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
2902 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
2904 HTTP_InsertAuthorization(lpwhr, szAuthorization, !loop_next);
2905 HTTP_InsertAuthorization(lpwhr, szProxy_Authorization, !loop_next);
2907 /* add the headers the caller supplied */
2908 if( lpszHeaders && dwHeaderLength )
2910 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2911 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2914 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2916 TRACE("Request header -> %s\n", debugstr_w(requestString) );
2918 /* Send the request and store the results */
2919 if (!HTTP_OpenConnection(lpwhr))
2920 goto lend;
2922 /* send the request as ASCII, tack on the optional data */
2923 if( !lpOptional )
2924 dwOptionalLength = 0;
2925 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2926 NULL, 0, NULL, NULL );
2927 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2928 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2929 ascii_req, len, NULL, NULL );
2930 if( lpOptional )
2931 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2932 len = (len + dwOptionalLength - 1);
2933 ascii_req[len] = 0;
2934 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2936 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2937 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2939 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2940 HeapFree( GetProcessHeap(), 0, ascii_req );
2942 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2943 INTERNET_STATUS_REQUEST_SENT,
2944 &len, sizeof(DWORD));
2946 if (bEndRequest)
2948 DWORD dwBufferSize;
2949 DWORD dwStatusCode;
2951 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2952 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2954 if (cnt < 0)
2955 goto lend;
2957 responseLen = HTTP_GetResponseHeaders(lpwhr);
2958 if (responseLen)
2959 bSuccess = TRUE;
2961 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2962 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2963 sizeof(DWORD));
2965 HTTP_ProcessCookies(lpwhr);
2967 dwBufferSize = sizeof(lpwhr->dwContentLength);
2968 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2969 &lpwhr->dwContentLength,&dwBufferSize,NULL))
2970 lpwhr->dwContentLength = -1;
2972 if (lpwhr->dwContentLength == 0)
2973 HTTP_FinishedReading(lpwhr);
2975 dwBufferSize = sizeof(dwStatusCode);
2976 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
2977 &dwStatusCode,&dwBufferSize,NULL))
2978 dwStatusCode = 0;
2980 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
2982 WCHAR szNewLocation[2048];
2983 dwBufferSize=sizeof(szNewLocation);
2984 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
2985 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
2987 HTTP_DrainContent(lpwhr);
2988 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2989 INTERNET_STATUS_REDIRECT, szNewLocation,
2990 dwBufferSize);
2991 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
2992 if (bSuccess)
2994 HeapFree(GetProcessHeap(), 0, requestString);
2995 loop_next = TRUE;
2999 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3001 WCHAR szAuthValue[2048];
3002 dwBufferSize=2048;
3003 if (dwStatusCode == HTTP_STATUS_DENIED)
3005 DWORD dwIndex = 0;
3006 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3008 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3009 &lpwhr->pAuthInfo,
3010 lpwhr->lpHttpSession->lpszUserName,
3011 lpwhr->lpHttpSession->lpszPassword))
3013 loop_next = TRUE;
3014 break;
3018 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3020 DWORD dwIndex = 0;
3021 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3023 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3024 &lpwhr->pProxyAuthInfo,
3025 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3026 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3028 loop_next = TRUE;
3029 break;
3035 else
3036 bSuccess = TRUE;
3038 while (loop_next);
3040 /* FIXME: Better check, when we have to create the cache file */
3041 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3042 WCHAR url[INTERNET_MAX_URL_LENGTH];
3043 WCHAR cacheFileName[MAX_PATH+1];
3044 BOOL b;
3046 b = HTTP_GetRequestURL(lpwhr, url);
3047 if(!b) {
3048 WARN("Could not get URL\n");
3049 goto lend;
3052 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3053 if(b) {
3054 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3055 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3056 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3057 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3058 WARN("Could not create file: %u\n", GetLastError());
3059 lpwhr->hCacheFile = NULL;
3061 }else {
3062 WARN("Could not create cache entry: %08x\n", GetLastError());
3066 lend:
3068 HeapFree(GetProcessHeap(), 0, requestString);
3070 /* TODO: send notification for P3P header */
3072 iar.dwResult = (DWORD)bSuccess;
3073 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
3075 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3076 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3077 sizeof(INTERNET_ASYNC_RESULT));
3079 TRACE("<--\n");
3080 return bSuccess;
3083 /***********************************************************************
3084 * HTTPSESSION_Destroy (internal)
3086 * Deallocate session handle
3089 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3091 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3093 TRACE("%p\n", lpwhs);
3095 WININET_Release(&lpwhs->lpAppInfo->hdr);
3097 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3098 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3099 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3100 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3101 HeapFree(GetProcessHeap(), 0, lpwhs);
3105 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3106 HTTPSESSION_Destroy,
3107 NULL,
3108 NULL,
3109 NULL,
3110 NULL,
3111 NULL,
3112 NULL,
3113 NULL
3117 /***********************************************************************
3118 * HTTP_Connect (internal)
3120 * Create http session handle
3122 * RETURNS
3123 * HINTERNET a session handle on success
3124 * NULL on failure
3127 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3128 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3129 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3130 DWORD dwInternalFlags)
3132 BOOL bSuccess = FALSE;
3133 LPWININETHTTPSESSIONW lpwhs = NULL;
3134 HINTERNET handle = NULL;
3136 TRACE("-->\n");
3138 if (!lpszServerName || !lpszServerName[0])
3140 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3141 goto lerror;
3144 assert( hIC->hdr.htype == WH_HINIT );
3146 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3147 if (NULL == lpwhs)
3149 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3150 goto lerror;
3154 * According to my tests. The name is not resolved until a request is sent
3157 lpwhs->hdr.htype = WH_HHTTPSESSION;
3158 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3159 lpwhs->hdr.dwFlags = dwFlags;
3160 lpwhs->hdr.dwContext = dwContext;
3161 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3162 lpwhs->hdr.dwRefCount = 1;
3163 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3165 WININET_AddRef( &hIC->hdr );
3166 lpwhs->lpAppInfo = hIC;
3167 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3169 handle = WININET_AllocHandle( &lpwhs->hdr );
3170 if (NULL == handle)
3172 ERR("Failed to alloc handle\n");
3173 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3174 goto lerror;
3177 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3178 if(strchrW(hIC->lpszProxy, ' '))
3179 FIXME("Several proxies not implemented.\n");
3180 if(hIC->lpszProxyBypass)
3181 FIXME("Proxy bypass is ignored.\n");
3183 if (lpszServerName && lpszServerName[0])
3185 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3186 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3188 if (lpszUserName && lpszUserName[0])
3189 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3190 if (lpszPassword && lpszPassword[0])
3191 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3192 lpwhs->nServerPort = nServerPort;
3193 lpwhs->nHostPort = nServerPort;
3195 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3196 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3198 INTERNET_SendCallback(&hIC->hdr, dwContext,
3199 INTERNET_STATUS_HANDLE_CREATED, &handle,
3200 sizeof(handle));
3203 bSuccess = TRUE;
3205 lerror:
3206 if( lpwhs )
3207 WININET_Release( &lpwhs->hdr );
3210 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3211 * windows
3214 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3215 return handle;
3219 /***********************************************************************
3220 * HTTP_OpenConnection (internal)
3222 * Connect to a web server
3224 * RETURNS
3226 * TRUE on success
3227 * FALSE on failure
3229 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3231 BOOL bSuccess = FALSE;
3232 LPWININETHTTPSESSIONW lpwhs;
3233 LPWININETAPPINFOW hIC = NULL;
3234 char szaddr[32];
3236 TRACE("-->\n");
3239 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3241 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3242 goto lend;
3245 if (NETCON_connected(&lpwhr->netConnection))
3247 bSuccess = TRUE;
3248 goto lend;
3251 lpwhs = lpwhr->lpHttpSession;
3253 hIC = lpwhs->lpAppInfo;
3254 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3255 szaddr, sizeof(szaddr));
3256 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3257 INTERNET_STATUS_CONNECTING_TO_SERVER,
3258 szaddr,
3259 strlen(szaddr)+1);
3261 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3262 SOCK_STREAM, 0))
3264 WARN("Socket creation failed\n");
3265 goto lend;
3268 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3269 sizeof(lpwhs->socketAddress)))
3270 goto lend;
3272 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3274 /* Note: we differ from Microsoft's WinINet here. they seem to have
3275 * a bug that causes no status callbacks to be sent when starting
3276 * a tunnel to a proxy server using the CONNECT verb. i believe our
3277 * behaviour to be more correct and to not cause any incompatibilities
3278 * because using a secure connection through a proxy server is a rare
3279 * case that would be hard for anyone to depend on */
3280 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3281 goto lend;
3283 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3285 WARN("Couldn't connect securely to host\n");
3286 goto lend;
3290 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3291 INTERNET_STATUS_CONNECTED_TO_SERVER,
3292 szaddr, strlen(szaddr)+1);
3294 bSuccess = TRUE;
3296 lend:
3297 TRACE("%d <--\n", bSuccess);
3298 return bSuccess;
3302 /***********************************************************************
3303 * HTTP_clear_response_headers (internal)
3305 * clear out any old response headers
3307 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3309 DWORD i;
3311 for( i=0; i<lpwhr->nCustHeaders; i++)
3313 if( !lpwhr->pCustHeaders[i].lpszField )
3314 continue;
3315 if( !lpwhr->pCustHeaders[i].lpszValue )
3316 continue;
3317 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3318 continue;
3319 HTTP_DeleteCustomHeader( lpwhr, i );
3320 i--;
3324 /***********************************************************************
3325 * HTTP_GetResponseHeaders (internal)
3327 * Read server response
3329 * RETURNS
3331 * TRUE on success
3332 * FALSE on error
3334 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
3336 INT cbreaks = 0;
3337 WCHAR buffer[MAX_REPLY_LEN];
3338 DWORD buflen = MAX_REPLY_LEN;
3339 BOOL bSuccess = FALSE;
3340 INT rc = 0;
3341 static const WCHAR szCrLf[] = {'\r','\n',0};
3342 static const WCHAR szHundred[] = {'1','0','0',0};
3343 char bufferA[MAX_REPLY_LEN];
3344 LPWSTR status_code, status_text;
3345 DWORD cchMaxRawHeaders = 1024;
3346 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3347 DWORD cchRawHeaders = 0;
3349 TRACE("-->\n");
3351 /* clear old response headers (eg. from a redirect response) */
3352 HTTP_clear_response_headers( lpwhr );
3354 if (!NETCON_connected(&lpwhr->netConnection))
3355 goto lend;
3357 do {
3359 * HACK peek at the buffer
3361 buflen = MAX_REPLY_LEN;
3362 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3365 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3367 memset(buffer, 0, MAX_REPLY_LEN);
3368 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3369 goto lend;
3370 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3372 /* split the version from the status code */
3373 status_code = strchrW( buffer, ' ' );
3374 if( !status_code )
3375 goto lend;
3376 *status_code++=0;
3378 /* split the status code from the status text */
3379 status_text = strchrW( status_code, ' ' );
3380 if( !status_text )
3381 goto lend;
3382 *status_text++=0;
3384 TRACE("version [%s] status code [%s] status text [%s]\n",
3385 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3387 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3389 /* Add status code */
3390 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3391 HTTP_ADDHDR_FLAG_REPLACE);
3393 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3394 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3396 lpwhr->lpszVersion= WININET_strdupW(buffer);
3397 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3399 /* Restore the spaces */
3400 *(status_code-1) = ' ';
3401 *(status_text-1) = ' ';
3403 /* regenerate raw headers */
3404 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3406 cchMaxRawHeaders *= 2;
3407 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3409 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3410 cchRawHeaders += (buflen-1);
3411 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3412 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3413 lpszRawHeaders[cchRawHeaders] = '\0';
3415 /* Parse each response line */
3418 buflen = MAX_REPLY_LEN;
3419 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3421 LPWSTR * pFieldAndValue;
3423 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3424 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3426 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3428 cchMaxRawHeaders *= 2;
3429 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3431 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3432 cchRawHeaders += (buflen-1);
3433 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3434 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3435 lpszRawHeaders[cchRawHeaders] = '\0';
3437 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3438 if (!pFieldAndValue)
3439 break;
3441 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3442 HTTP_ADDREQ_FLAG_ADD );
3444 HTTP_FreeTokens(pFieldAndValue);
3446 else
3448 cbreaks++;
3449 if (cbreaks >= 2)
3450 break;
3452 }while(1);
3454 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3455 lpwhr->lpszRawHeaders = lpszRawHeaders;
3456 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3457 bSuccess = TRUE;
3459 lend:
3461 TRACE("<--\n");
3462 if (bSuccess)
3463 return rc;
3464 else
3465 return 0;
3469 static void strip_spaces(LPWSTR start)
3471 LPWSTR str = start;
3472 LPWSTR end;
3474 while (*str == ' ' && *str != '\0')
3475 str++;
3477 if (str != start)
3478 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3480 end = start + strlenW(start) - 1;
3481 while (end >= start && *end == ' ')
3483 *end = '\0';
3484 end--;
3489 /***********************************************************************
3490 * HTTP_InterpretHttpHeader (internal)
3492 * Parse server response
3494 * RETURNS
3496 * Pointer to array of field, value, NULL on success.
3497 * NULL on error.
3499 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3501 LPWSTR * pTokenPair;
3502 LPWSTR pszColon;
3503 INT len;
3505 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3507 pszColon = strchrW(buffer, ':');
3508 /* must have two tokens */
3509 if (!pszColon)
3511 HTTP_FreeTokens(pTokenPair);
3512 if (buffer[0])
3513 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3514 return NULL;
3517 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3518 if (!pTokenPair[0])
3520 HTTP_FreeTokens(pTokenPair);
3521 return NULL;
3523 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3524 pTokenPair[0][pszColon - buffer] = '\0';
3526 /* skip colon */
3527 pszColon++;
3528 len = strlenW(pszColon);
3529 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3530 if (!pTokenPair[1])
3532 HTTP_FreeTokens(pTokenPair);
3533 return NULL;
3535 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3537 strip_spaces(pTokenPair[0]);
3538 strip_spaces(pTokenPair[1]);
3540 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3541 return pTokenPair;
3544 /***********************************************************************
3545 * HTTP_ProcessHeader (internal)
3547 * Stuff header into header tables according to <dwModifier>
3551 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3553 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3555 LPHTTPHEADERW lphttpHdr = NULL;
3556 BOOL bSuccess = FALSE;
3557 INT index = -1;
3558 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3560 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3562 /* REPLACE wins out over ADD */
3563 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3564 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3566 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3567 index = -1;
3568 else
3569 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3571 if (index >= 0)
3573 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3575 return FALSE;
3577 lphttpHdr = &lpwhr->pCustHeaders[index];
3579 else if (value)
3581 HTTPHEADERW hdr;
3583 hdr.lpszField = (LPWSTR)field;
3584 hdr.lpszValue = (LPWSTR)value;
3585 hdr.wFlags = hdr.wCount = 0;
3587 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3588 hdr.wFlags |= HDR_ISREQUEST;
3590 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3592 /* no value to delete */
3593 else return TRUE;
3595 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3596 lphttpHdr->wFlags |= HDR_ISREQUEST;
3597 else
3598 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3600 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3602 HTTP_DeleteCustomHeader( lpwhr, index );
3604 if (value)
3606 HTTPHEADERW hdr;
3608 hdr.lpszField = (LPWSTR)field;
3609 hdr.lpszValue = (LPWSTR)value;
3610 hdr.wFlags = hdr.wCount = 0;
3612 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3613 hdr.wFlags |= HDR_ISREQUEST;
3615 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3618 return TRUE;
3620 else if (dwModifier & COALESCEFLAGS)
3622 LPWSTR lpsztmp;
3623 WCHAR ch = 0;
3624 INT len = 0;
3625 INT origlen = strlenW(lphttpHdr->lpszValue);
3626 INT valuelen = strlenW(value);
3628 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3630 ch = ',';
3631 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3633 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3635 ch = ';';
3636 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3639 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3641 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3642 if (lpsztmp)
3644 lphttpHdr->lpszValue = lpsztmp;
3645 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3646 if (ch > 0)
3648 lphttpHdr->lpszValue[origlen] = ch;
3649 origlen++;
3650 lphttpHdr->lpszValue[origlen] = ' ';
3651 origlen++;
3654 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3655 lphttpHdr->lpszValue[len] = '\0';
3656 bSuccess = TRUE;
3658 else
3660 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3661 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3664 TRACE("<-- %d\n",bSuccess);
3665 return bSuccess;
3669 /***********************************************************************
3670 * HTTP_FinishedReading (internal)
3672 * Called when all content from server has been read by client.
3675 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
3677 WCHAR szConnectionResponse[20];
3678 DWORD dwBufferSize = sizeof(szConnectionResponse);
3680 TRACE("\n");
3682 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse,
3683 &dwBufferSize, NULL) ||
3684 strcmpiW(szConnectionResponse, szKeepAlive))
3686 HTTPREQ_CloseConnection(&lpwhr->hdr);
3689 /* FIXME: store data in the URL cache here */
3691 return TRUE;
3695 /***********************************************************************
3696 * HTTP_GetCustomHeaderIndex (internal)
3698 * Return index of custom header from header array
3701 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
3702 int requested_index, BOOL request_only)
3704 DWORD index;
3706 TRACE("%s\n", debugstr_w(lpszField));
3708 for (index = 0; index < lpwhr->nCustHeaders; index++)
3710 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3711 continue;
3713 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3714 continue;
3716 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3717 continue;
3719 if (requested_index == 0)
3720 break;
3721 requested_index --;
3724 if (index >= lpwhr->nCustHeaders)
3725 index = -1;
3727 TRACE("Return: %d\n", index);
3728 return index;
3732 /***********************************************************************
3733 * HTTP_InsertCustomHeader (internal)
3735 * Insert header into array
3738 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3740 INT count;
3741 LPHTTPHEADERW lph = NULL;
3742 BOOL r = FALSE;
3744 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3745 count = lpwhr->nCustHeaders + 1;
3746 if (count > 1)
3747 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3748 else
3749 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3751 if (NULL != lph)
3753 lpwhr->pCustHeaders = lph;
3754 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3755 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3756 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3757 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3758 lpwhr->nCustHeaders++;
3759 r = TRUE;
3761 else
3763 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3766 return r;
3770 /***********************************************************************
3771 * HTTP_DeleteCustomHeader (internal)
3773 * Delete header from array
3774 * If this function is called, the indexs may change.
3776 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3778 if( lpwhr->nCustHeaders <= 0 )
3779 return FALSE;
3780 if( index >= lpwhr->nCustHeaders )
3781 return FALSE;
3782 lpwhr->nCustHeaders--;
3784 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3785 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3786 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3788 return TRUE;
3792 /***********************************************************************
3793 * HTTP_VerifyValidHeader (internal)
3795 * Verify the given header is not invalid for the given http request
3798 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
3800 BOOL rc = TRUE;
3802 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
3803 if (strcmpiW(field,szAccept_Encoding)==0)
3804 return FALSE;
3806 return rc;
3809 /***********************************************************************
3810 * IsHostInProxyBypassList (@)
3812 * Undocumented
3815 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3817 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
3818 return FALSE;