wininet: Move InternetQueryDataAvailable to vtbl.
[wine.git] / dlls / wininet / http.c
blobb1a181d8392e6a6ae247048d4a4b19f5dd1ced34
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);
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 /* read any content returned by the server so that the connection can be
719 * reused */
720 static void HTTP_DrainContent(LPWININETHTTPREQW lpwhr)
722 DWORD bytes_read;
724 if (!NETCON_connected(&lpwhr->netConnection)) return;
726 if (lpwhr->dwContentLength == -1)
727 NETCON_close(&lpwhr->netConnection);
731 char buffer[2048];
732 if (!INTERNET_ReadFile(&lpwhr->hdr, buffer, sizeof(buffer), &bytes_read,
733 TRUE, FALSE))
734 return;
735 } while (bytes_read);
738 /***********************************************************************
739 * HttpEndRequestA (WININET.@)
741 * Ends an HTTP request that was started by HttpSendRequestEx
743 * RETURNS
744 * TRUE if successful
745 * FALSE on failure
748 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
749 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
751 LPINTERNET_BUFFERSA ptr;
752 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
753 BOOL rc = FALSE;
755 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
756 dwContext);
758 ptr = lpBuffersOut;
759 if (ptr)
760 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
761 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
762 else
763 lpBuffersOutW = NULL;
765 ptrW = lpBuffersOutW;
766 while (ptr)
768 if (ptr->lpvBuffer && ptr->dwBufferLength)
769 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
770 ptrW->dwBufferLength = ptr->dwBufferLength;
771 ptrW->dwBufferTotal= ptr->dwBufferTotal;
773 if (ptr->Next)
774 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
775 sizeof(INTERNET_BUFFERSW));
777 ptr = ptr->Next;
778 ptrW = ptrW->Next;
781 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
783 if (lpBuffersOutW)
785 ptrW = lpBuffersOutW;
786 while (ptrW)
788 LPINTERNET_BUFFERSW ptrW2;
790 FIXME("Do we need to translate info out of these buffer?\n");
792 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
793 ptrW2 = ptrW->Next;
794 HeapFree(GetProcessHeap(),0,ptrW);
795 ptrW = ptrW2;
799 return rc;
802 /***********************************************************************
803 * HttpEndRequestW (WININET.@)
805 * Ends an HTTP request that was started by HttpSendRequestEx
807 * RETURNS
808 * TRUE if successful
809 * FALSE on failure
812 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
813 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
815 BOOL rc = FALSE;
816 LPWININETHTTPREQW lpwhr;
817 INT responseLen;
818 DWORD dwBufferSize;
820 TRACE("-->\n");
821 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
823 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
825 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
826 if (lpwhr)
827 WININET_Release( &lpwhr->hdr );
828 return FALSE;
831 lpwhr->hdr.dwFlags |= dwFlags;
832 lpwhr->hdr.dwContext = dwContext;
834 /* We appear to do nothing with lpBuffersOut.. is that correct? */
836 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
837 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
839 responseLen = HTTP_GetResponseHeaders(lpwhr);
840 if (responseLen)
841 rc = TRUE;
843 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
844 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
846 /* process cookies here. Is this right? */
847 HTTP_ProcessCookies(lpwhr);
849 dwBufferSize = sizeof(lpwhr->dwContentLength);
850 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
851 &lpwhr->dwContentLength,&dwBufferSize,NULL))
852 lpwhr->dwContentLength = -1;
854 if (lpwhr->dwContentLength == 0)
855 HTTP_FinishedReading(lpwhr);
857 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
859 DWORD dwCode,dwCodeLength=sizeof(DWORD);
860 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
861 (dwCode==302 || dwCode==301))
863 WCHAR szNewLocation[2048];
864 dwBufferSize=sizeof(szNewLocation);
865 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
867 /* redirects are always GETs */
868 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
869 lpwhr->lpszVerb = WININET_strdupW(szGET);
870 HTTP_DrainContent(lpwhr);
871 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
872 if (rc)
873 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
878 WININET_Release( &lpwhr->hdr );
879 TRACE("%i <--\n",rc);
880 return rc;
883 /***********************************************************************
884 * HttpOpenRequestW (WININET.@)
886 * Open a HTTP request handle
888 * RETURNS
889 * HINTERNET a HTTP request handle on success
890 * NULL on failure
893 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
894 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
895 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
896 DWORD dwFlags, DWORD_PTR dwContext)
898 LPWININETHTTPSESSIONW lpwhs;
899 HINTERNET handle = NULL;
901 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
902 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
903 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
904 dwFlags, dwContext);
905 if(lpszAcceptTypes!=NULL)
907 int i;
908 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
909 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
912 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
913 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
915 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
916 goto lend;
920 * My tests seem to show that the windows version does not
921 * become asynchronous until after this point. And anyhow
922 * if this call was asynchronous then how would you get the
923 * necessary HINTERNET pointer returned by this function.
926 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
927 lpszVersion, lpszReferrer, lpszAcceptTypes,
928 dwFlags, dwContext);
929 lend:
930 if( lpwhs )
931 WININET_Release( &lpwhs->hdr );
932 TRACE("returning %p\n", handle);
933 return handle;
937 /***********************************************************************
938 * HttpOpenRequestA (WININET.@)
940 * Open a HTTP request handle
942 * RETURNS
943 * HINTERNET a HTTP request handle on success
944 * NULL on failure
947 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
948 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
949 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
950 DWORD dwFlags, DWORD_PTR dwContext)
952 LPWSTR szVerb = NULL, szObjectName = NULL;
953 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
954 INT len;
955 INT acceptTypesCount;
956 HINTERNET rc = FALSE;
957 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
958 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
959 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
960 dwFlags, dwContext);
962 if (lpszVerb)
964 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
965 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
966 if ( !szVerb )
967 goto end;
968 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
971 if (lpszObjectName)
973 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
974 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
975 if ( !szObjectName )
976 goto end;
977 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
980 if (lpszVersion)
982 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
983 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
984 if ( !szVersion )
985 goto end;
986 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
989 if (lpszReferrer)
991 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
992 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
993 if ( !szReferrer )
994 goto end;
995 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
998 acceptTypesCount = 0;
999 if (lpszAcceptTypes)
1001 /* find out how many there are */
1002 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1003 acceptTypesCount++;
1004 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1005 acceptTypesCount = 0;
1006 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1008 len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1009 -1, NULL, 0 );
1010 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1011 if (!szAcceptTypes[acceptTypesCount] )
1012 goto end;
1013 MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1014 -1, szAcceptTypes[acceptTypesCount], len );
1015 acceptTypesCount++;
1017 szAcceptTypes[acceptTypesCount] = NULL;
1019 else szAcceptTypes = 0;
1021 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1022 szVersion, szReferrer,
1023 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1025 end:
1026 if (szAcceptTypes)
1028 acceptTypesCount = 0;
1029 while (szAcceptTypes[acceptTypesCount])
1031 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1032 acceptTypesCount++;
1034 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1036 HeapFree(GetProcessHeap(), 0, szReferrer);
1037 HeapFree(GetProcessHeap(), 0, szVersion);
1038 HeapFree(GetProcessHeap(), 0, szObjectName);
1039 HeapFree(GetProcessHeap(), 0, szVerb);
1041 return rc;
1044 /***********************************************************************
1045 * HTTP_EncodeBase64
1047 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1049 UINT n = 0, x;
1050 static const CHAR HTTP_Base64Enc[] =
1051 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1053 while( len > 0 )
1055 /* first 6 bits, all from bin[0] */
1056 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1057 x = (bin[0] & 3) << 4;
1059 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1060 if( len == 1 )
1062 base64[n++] = HTTP_Base64Enc[x];
1063 base64[n++] = '=';
1064 base64[n++] = '=';
1065 break;
1067 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1068 x = ( bin[1] & 0x0f ) << 2;
1070 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1071 if( len == 2 )
1073 base64[n++] = HTTP_Base64Enc[x];
1074 base64[n++] = '=';
1075 break;
1077 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1079 /* last 6 bits, all from bin [2] */
1080 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1081 bin += 3;
1082 len -= 3;
1084 base64[n] = 0;
1085 return n;
1088 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1089 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1090 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1091 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1092 static const signed char HTTP_Base64Dec[256] =
1094 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1095 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1096 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1097 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1098 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1099 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1100 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1101 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1102 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1103 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1104 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1105 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1106 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1107 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1108 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1109 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1110 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1111 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1112 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1113 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1114 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1115 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1116 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1117 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1118 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1119 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1121 #undef CH
1123 /***********************************************************************
1124 * HTTP_DecodeBase64
1126 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1128 unsigned int n = 0;
1130 while(*base64)
1132 signed char in[4];
1134 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1135 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1136 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1137 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1139 WARN("invalid base64: %s\n", debugstr_w(base64));
1140 return 0;
1142 if (bin)
1143 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1144 n++;
1146 if ((base64[2] == '=') && (base64[3] == '='))
1147 break;
1148 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1149 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1151 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1152 return 0;
1154 if (bin)
1155 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1156 n++;
1158 if (base64[3] == '=')
1159 break;
1160 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1161 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1163 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1164 return 0;
1166 if (bin)
1167 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1168 n++;
1170 base64 += 4;
1173 return n;
1176 /***********************************************************************
1177 * HTTP_InsertAuthorizationForHeader
1179 * Insert or delete the authorization field in the request header.
1181 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR header, BOOL first )
1183 WCHAR *authorization = NULL;
1184 struct HttpAuthInfo *pAuthInfo = lpwhr->pAuthInfo;
1185 DWORD flags;
1187 if (pAuthInfo && pAuthInfo->auth_data_len)
1189 static const WCHAR wszSpace[] = {' ',0};
1190 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1191 unsigned int len;
1193 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1194 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1195 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1196 if (!authorization)
1197 return FALSE;
1199 strcpyW(authorization, pAuthInfo->scheme);
1200 strcatW(authorization, wszSpace);
1201 HTTP_EncodeBase64(pAuthInfo->auth_data,
1202 pAuthInfo->auth_data_len,
1203 authorization+strlenW(authorization));
1205 /* clear the data as it isn't valid now that it has been sent to the
1206 * server, unless it's Basic authentication which doesn't do
1207 * connection tracking */
1208 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1210 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1211 pAuthInfo->auth_data = NULL;
1212 pAuthInfo->auth_data_len = 0;
1216 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1218 /* make sure not to overwrite any caller supplied authorization header */
1219 flags = HTTP_ADDHDR_FLAG_REQ;
1220 flags |= first ? HTTP_ADDHDR_FLAG_ADD_IF_NEW : HTTP_ADDHDR_FLAG_REPLACE;
1222 HTTP_ProcessHeader(lpwhr, header, authorization, flags);
1224 HeapFree(GetProcessHeap(), 0, authorization);
1225 return TRUE;
1228 /***********************************************************************
1229 * HTTP_DealWithProxy
1231 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1232 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1234 WCHAR buf[MAXHOSTNAME];
1235 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1236 WCHAR* url;
1237 static WCHAR szNul[] = { 0 };
1238 URL_COMPONENTSW UrlComponents;
1239 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
1240 static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
1241 static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1242 int len;
1244 memset( &UrlComponents, 0, sizeof UrlComponents );
1245 UrlComponents.dwStructSize = sizeof UrlComponents;
1246 UrlComponents.lpszHostName = buf;
1247 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1249 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1250 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1251 sprintfW(proxy, szFormat1, hIC->lpszProxy);
1252 else
1253 strcpyW(proxy, hIC->lpszProxy);
1254 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1255 return FALSE;
1256 if( UrlComponents.dwHostNameLength == 0 )
1257 return FALSE;
1259 if( !lpwhr->lpszPath )
1260 lpwhr->lpszPath = szNul;
1261 TRACE("server=%s path=%s\n",
1262 debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
1263 /* for constant 15 see above */
1264 len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
1265 url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1267 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1268 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1270 sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
1272 if( lpwhr->lpszPath[0] != '/' )
1273 strcatW( url, szSlash );
1274 strcatW(url, lpwhr->lpszPath);
1275 if(lpwhr->lpszPath != szNul)
1276 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1277 lpwhr->lpszPath = url;
1279 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1280 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1281 lpwhs->nServerPort = UrlComponents.nPort;
1283 return TRUE;
1286 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1288 char szaddr[32];
1289 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1291 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1292 INTERNET_STATUS_RESOLVING_NAME,
1293 lpwhs->lpszServerName,
1294 strlenW(lpwhs->lpszServerName)+1);
1296 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1297 &lpwhs->socketAddress))
1299 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1300 return FALSE;
1303 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1304 szaddr, sizeof(szaddr));
1305 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1306 INTERNET_STATUS_NAME_RESOLVED,
1307 szaddr, strlen(szaddr)+1);
1308 return TRUE;
1312 /***********************************************************************
1313 * HTTPREQ_Destroy (internal)
1315 * Deallocate request handle
1318 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1320 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1321 DWORD i;
1323 TRACE("\n");
1325 if(lpwhr->hCacheFile)
1326 CloseHandle(lpwhr->hCacheFile);
1328 if(lpwhr->lpszCacheFile) {
1329 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1330 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1333 WININET_Release(&lpwhr->lpHttpSession->hdr);
1335 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1336 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1337 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1338 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1339 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1341 for (i = 0; i < lpwhr->nCustHeaders; i++)
1343 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1344 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1347 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1348 HeapFree(GetProcessHeap(), 0, lpwhr);
1351 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1353 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1354 LPWININETHTTPSESSIONW lpwhs = NULL;
1355 LPWININETAPPINFOW hIC = NULL;
1357 TRACE("%p\n",lpwhr);
1359 if (!NETCON_connected(&lpwhr->netConnection))
1360 return;
1362 if (lpwhr->pAuthInfo)
1364 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1365 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1367 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1368 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1369 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1370 lpwhr->pAuthInfo = NULL;
1372 if (lpwhr->pProxyAuthInfo)
1374 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1375 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1377 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1378 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1379 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1380 lpwhr->pProxyAuthInfo = NULL;
1383 lpwhs = lpwhr->lpHttpSession;
1384 hIC = lpwhs->lpAppInfo;
1386 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1387 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1389 NETCON_close(&lpwhr->netConnection);
1391 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1392 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1395 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1397 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1399 switch(option) {
1400 case INTERNET_OPTION_SEND_TIMEOUT:
1401 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1402 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1404 if (size != sizeof(DWORD))
1405 return ERROR_INVALID_PARAMETER;
1407 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1408 *(DWORD*)buffer);
1411 return ERROR_INTERNET_INVALID_OPTION;
1414 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1416 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1418 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1421 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1423 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1424 INTERNET_ASYNC_RESULT iar;
1425 char buffer[4048];
1427 TRACE("%p\n", workRequest->hdr);
1429 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1430 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1431 MSG_PEEK, (int *)&iar.dwError);
1433 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1434 sizeof(INTERNET_ASYNC_RESULT));
1437 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1439 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1440 BYTE buffer[4048];
1441 BOOL async;
1443 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1445 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1446 return ERROR_SUCCESS;
1448 /* Even if we are in async mode, we need to determine whether
1449 * there is actually more data available. We do this by trying
1450 * to peek only a single byte in async mode. */
1451 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1453 if (NETCON_recv(&req->netConnection, buffer,
1454 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1455 MSG_PEEK, (int *)available) && async && *available)
1457 WORKREQUEST workRequest;
1459 *available = 0;
1460 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1461 workRequest.hdr = WININET_AddRef( &req->hdr );
1463 INTERNET_AsyncCall(&workRequest);
1465 return ERROR_IO_PENDING;
1468 return ERROR_SUCCESS;
1471 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1472 HTTPREQ_Destroy,
1473 HTTPREQ_CloseConnection,
1474 HTTPREQ_SetOption,
1475 HTTPREQ_WriteFile,
1476 HTTPREQ_QueryDataAvailable,
1477 NULL
1480 /***********************************************************************
1481 * HTTP_HttpOpenRequestW (internal)
1483 * Open a HTTP request handle
1485 * RETURNS
1486 * HINTERNET a HTTP request handle on success
1487 * NULL on failure
1490 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1491 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1492 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1493 DWORD dwFlags, DWORD_PTR dwContext)
1495 LPWININETAPPINFOW hIC = NULL;
1496 LPWININETHTTPREQW lpwhr;
1497 LPWSTR lpszCookies;
1498 LPWSTR lpszUrl = NULL;
1499 DWORD nCookieSize;
1500 HINTERNET handle = NULL;
1501 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1502 DWORD len;
1503 LPHTTPHEADERW Host;
1505 TRACE("-->\n");
1507 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1508 hIC = lpwhs->lpAppInfo;
1510 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1511 if (NULL == lpwhr)
1513 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1514 goto lend;
1516 lpwhr->hdr.htype = WH_HHTTPREQ;
1517 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1518 lpwhr->hdr.dwFlags = dwFlags;
1519 lpwhr->hdr.dwContext = dwContext;
1520 lpwhr->hdr.dwRefCount = 1;
1521 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1522 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1524 WININET_AddRef( &lpwhs->hdr );
1525 lpwhr->lpHttpSession = lpwhs;
1526 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1528 handle = WININET_AllocHandle( &lpwhr->hdr );
1529 if (NULL == handle)
1531 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1532 goto lend;
1535 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1537 InternetCloseHandle( handle );
1538 handle = NULL;
1539 goto lend;
1542 if (lpszObjectName && *lpszObjectName) {
1543 HRESULT rc;
1545 len = 0;
1546 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1547 if (rc != E_POINTER)
1548 len = strlenW(lpszObjectName)+1;
1549 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1550 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1551 URL_ESCAPE_SPACES_ONLY);
1552 if (rc)
1554 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1555 strcpyW(lpwhr->lpszPath,lpszObjectName);
1559 if (lpszReferrer && *lpszReferrer)
1560 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1562 if (lpszAcceptTypes)
1564 int i;
1565 for (i = 0; lpszAcceptTypes[i]; i++)
1567 if (!*lpszAcceptTypes[i]) continue;
1568 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1569 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1570 HTTP_ADDHDR_FLAG_REQ |
1571 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1575 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1577 if (lpszVersion)
1578 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1579 else
1580 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1582 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1584 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1585 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1586 INTERNET_DEFAULT_HTTPS_PORT :
1587 INTERNET_DEFAULT_HTTP_PORT);
1588 lpwhs->nHostPort = lpwhs->nServerPort;
1590 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1591 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1593 if (hIC->lpszAgent)
1595 WCHAR *agent_header;
1596 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1598 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1599 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1600 sprintfW(agent_header, user_agent, hIC->lpszAgent );
1602 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1603 HTTP_ADDREQ_FLAG_ADD);
1604 HeapFree(GetProcessHeap(), 0, agent_header);
1607 Host = HTTP_GetHeader(lpwhr,szHost);
1609 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1610 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1611 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1613 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1614 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1616 int cnt = 0;
1617 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1618 static const WCHAR szcrlf[] = {'\r','\n',0};
1620 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1622 cnt += sprintfW(lpszCookies, szCookie);
1623 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1624 strcatW(lpszCookies, szcrlf);
1626 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1627 HTTP_ADDREQ_FLAG_ADD);
1628 HeapFree(GetProcessHeap(), 0, lpszCookies);
1630 HeapFree(GetProcessHeap(), 0, lpszUrl);
1633 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1634 INTERNET_STATUS_HANDLE_CREATED, &handle,
1635 sizeof(handle));
1638 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1641 if (!HTTP_ResolveName(lpwhr))
1643 InternetCloseHandle( handle );
1644 handle = NULL;
1647 lend:
1648 if( lpwhr )
1649 WININET_Release( &lpwhr->hdr );
1651 TRACE("<-- %p (%p)\n", handle, lpwhr);
1652 return handle;
1655 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1656 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1657 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1658 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1659 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1660 static const WCHAR szAge[] = { 'A','g','e',0 };
1661 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1662 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1663 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1664 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1665 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1666 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1667 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1668 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1669 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1670 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1671 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1672 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 };
1673 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1674 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1675 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1676 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1677 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1678 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1679 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1680 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1681 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1682 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1683 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1684 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1685 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1686 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1687 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1688 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1689 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1690 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1691 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1692 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1693 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1694 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1695 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1696 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1697 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1698 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1699 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 };
1700 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1701 static const WCHAR szURI[] = { 'U','R','I',0 };
1702 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1703 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1704 static const WCHAR szVia[] = { 'V','i','a',0 };
1705 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1706 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1708 static const LPCWSTR header_lookup[] = {
1709 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
1710 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
1711 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1712 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
1713 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1714 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
1715 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
1716 szAllow, /* HTTP_QUERY_ALLOW = 7 */
1717 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
1718 szDate, /* HTTP_QUERY_DATE = 9 */
1719 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
1720 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
1721 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
1722 szURI, /* HTTP_QUERY_URI = 13 */
1723 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
1724 NULL, /* HTTP_QUERY_COST = 15 */
1725 NULL, /* HTTP_QUERY_LINK = 16 */
1726 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
1727 NULL, /* HTTP_QUERY_VERSION = 18 */
1728 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
1729 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
1730 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
1731 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
1732 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
1733 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
1734 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
1735 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
1736 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
1737 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
1738 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
1739 NULL, /* HTTP_QUERY_FORWARDED = 30 */
1740 NULL, /* HTTP_QUERY_FROM = 31 */
1741 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
1742 szLocation, /* HTTP_QUERY_LOCATION = 33 */
1743 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
1744 szReferer, /* HTTP_QUERY_REFERER = 35 */
1745 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
1746 szServer, /* HTTP_QUERY_SERVER = 37 */
1747 NULL, /* HTTP_TITLE = 38 */
1748 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
1749 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
1750 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
1751 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
1752 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
1753 szCookie, /* HTTP_QUERY_COOKIE = 44 */
1754 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
1755 NULL, /* HTTP_QUERY_REFRESH = 46 */
1756 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
1757 szAge, /* HTTP_QUERY_AGE = 48 */
1758 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
1759 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
1760 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
1761 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
1762 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
1763 szETag, /* HTTP_QUERY_ETAG = 54 */
1764 szHost, /* HTTP_QUERY_HOST = 55 */
1765 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
1766 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
1767 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
1768 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
1769 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
1770 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
1771 szRange, /* HTTP_QUERY_RANGE = 62 */
1772 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
1773 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
1774 szVary, /* HTTP_QUERY_VARY = 65 */
1775 szVia, /* HTTP_QUERY_VIA = 66 */
1776 szWarning, /* HTTP_QUERY_WARNING = 67 */
1777 szExpect, /* HTTP_QUERY_EXPECT = 68 */
1778 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
1779 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
1782 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
1784 /***********************************************************************
1785 * HTTP_HttpQueryInfoW (internal)
1787 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1788 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1790 LPHTTPHEADERW lphttpHdr = NULL;
1791 BOOL bSuccess = FALSE;
1792 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1793 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
1794 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
1795 INT index = -1;
1797 /* Find requested header structure */
1798 switch (level)
1800 case HTTP_QUERY_CUSTOM:
1801 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
1802 break;
1804 case HTTP_QUERY_RAW_HEADERS_CRLF:
1806 LPWSTR headers;
1807 DWORD len;
1808 BOOL ret;
1810 if (request_only)
1811 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
1812 else
1813 headers = lpwhr->lpszRawHeaders;
1815 len = strlenW(headers);
1816 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1818 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1819 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1820 ret = FALSE;
1821 } else
1823 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
1824 *lpdwBufferLength = len * sizeof(WCHAR);
1826 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1827 ret = TRUE;
1830 if (request_only)
1831 HeapFree(GetProcessHeap(), 0, headers);
1832 return ret;
1834 case HTTP_QUERY_RAW_HEADERS:
1836 static const WCHAR szCrLf[] = {'\r','\n',0};
1837 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1838 DWORD i, size = 0;
1839 LPWSTR pszString = (WCHAR*)lpBuffer;
1841 for (i = 0; ppszRawHeaderLines[i]; i++)
1842 size += strlenW(ppszRawHeaderLines[i]) + 1;
1844 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1846 HTTP_FreeTokens(ppszRawHeaderLines);
1847 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1848 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1849 return FALSE;
1852 for (i = 0; ppszRawHeaderLines[i]; i++)
1854 DWORD len = strlenW(ppszRawHeaderLines[i]);
1855 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1856 pszString += len+1;
1858 *pszString = '\0';
1860 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1862 *lpdwBufferLength = size * sizeof(WCHAR);
1863 HTTP_FreeTokens(ppszRawHeaderLines);
1865 return TRUE;
1867 case HTTP_QUERY_STATUS_TEXT:
1868 if (lpwhr->lpszStatusText)
1870 DWORD len = strlenW(lpwhr->lpszStatusText);
1871 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1873 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1874 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1875 return FALSE;
1877 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1878 *lpdwBufferLength = len * sizeof(WCHAR);
1880 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1882 return TRUE;
1884 break;
1885 case HTTP_QUERY_VERSION:
1886 if (lpwhr->lpszVersion)
1888 DWORD len = strlenW(lpwhr->lpszVersion);
1889 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1891 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1892 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1893 return FALSE;
1895 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
1896 *lpdwBufferLength = len * sizeof(WCHAR);
1898 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1900 return TRUE;
1902 break;
1903 default:
1904 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
1906 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
1907 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
1908 requested_index,request_only);
1911 if (index >= 0)
1912 lphttpHdr = &lpwhr->pCustHeaders[index];
1914 /* Ensure header satisfies requested attributes */
1915 if (!lphttpHdr ||
1916 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
1917 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
1919 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1920 return bSuccess;
1923 if (lpdwIndex)
1924 (*lpdwIndex)++;
1926 /* coalesce value to requested type */
1927 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
1929 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
1930 bSuccess = TRUE;
1932 TRACE(" returning number : %d\n", *(int *)lpBuffer);
1934 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
1936 time_t tmpTime;
1937 struct tm tmpTM;
1938 SYSTEMTIME *STHook;
1940 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
1942 tmpTM = *gmtime(&tmpTime);
1943 STHook = (SYSTEMTIME *) lpBuffer;
1944 if(STHook==NULL)
1945 return bSuccess;
1947 STHook->wDay = tmpTM.tm_mday;
1948 STHook->wHour = tmpTM.tm_hour;
1949 STHook->wMilliseconds = 0;
1950 STHook->wMinute = tmpTM.tm_min;
1951 STHook->wDayOfWeek = tmpTM.tm_wday;
1952 STHook->wMonth = tmpTM.tm_mon + 1;
1953 STHook->wSecond = tmpTM.tm_sec;
1954 STHook->wYear = tmpTM.tm_year;
1956 bSuccess = TRUE;
1958 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
1959 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
1960 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
1962 else if (lphttpHdr->lpszValue)
1964 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
1966 if (len > *lpdwBufferLength)
1968 *lpdwBufferLength = len;
1969 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1970 return bSuccess;
1973 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
1974 *lpdwBufferLength = len - sizeof(WCHAR);
1975 bSuccess = TRUE;
1977 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
1979 return bSuccess;
1982 /***********************************************************************
1983 * HttpQueryInfoW (WININET.@)
1985 * Queries for information about an HTTP request
1987 * RETURNS
1988 * TRUE on success
1989 * FALSE on failure
1992 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1993 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1995 BOOL bSuccess = FALSE;
1996 LPWININETHTTPREQW lpwhr;
1998 if (TRACE_ON(wininet)) {
1999 #define FE(x) { x, #x }
2000 static const wininet_flag_info query_flags[] = {
2001 FE(HTTP_QUERY_MIME_VERSION),
2002 FE(HTTP_QUERY_CONTENT_TYPE),
2003 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2004 FE(HTTP_QUERY_CONTENT_ID),
2005 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2006 FE(HTTP_QUERY_CONTENT_LENGTH),
2007 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2008 FE(HTTP_QUERY_ALLOW),
2009 FE(HTTP_QUERY_PUBLIC),
2010 FE(HTTP_QUERY_DATE),
2011 FE(HTTP_QUERY_EXPIRES),
2012 FE(HTTP_QUERY_LAST_MODIFIED),
2013 FE(HTTP_QUERY_MESSAGE_ID),
2014 FE(HTTP_QUERY_URI),
2015 FE(HTTP_QUERY_DERIVED_FROM),
2016 FE(HTTP_QUERY_COST),
2017 FE(HTTP_QUERY_LINK),
2018 FE(HTTP_QUERY_PRAGMA),
2019 FE(HTTP_QUERY_VERSION),
2020 FE(HTTP_QUERY_STATUS_CODE),
2021 FE(HTTP_QUERY_STATUS_TEXT),
2022 FE(HTTP_QUERY_RAW_HEADERS),
2023 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2024 FE(HTTP_QUERY_CONNECTION),
2025 FE(HTTP_QUERY_ACCEPT),
2026 FE(HTTP_QUERY_ACCEPT_CHARSET),
2027 FE(HTTP_QUERY_ACCEPT_ENCODING),
2028 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2029 FE(HTTP_QUERY_AUTHORIZATION),
2030 FE(HTTP_QUERY_CONTENT_ENCODING),
2031 FE(HTTP_QUERY_FORWARDED),
2032 FE(HTTP_QUERY_FROM),
2033 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2034 FE(HTTP_QUERY_LOCATION),
2035 FE(HTTP_QUERY_ORIG_URI),
2036 FE(HTTP_QUERY_REFERER),
2037 FE(HTTP_QUERY_RETRY_AFTER),
2038 FE(HTTP_QUERY_SERVER),
2039 FE(HTTP_QUERY_TITLE),
2040 FE(HTTP_QUERY_USER_AGENT),
2041 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2042 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2043 FE(HTTP_QUERY_ACCEPT_RANGES),
2044 FE(HTTP_QUERY_SET_COOKIE),
2045 FE(HTTP_QUERY_COOKIE),
2046 FE(HTTP_QUERY_REQUEST_METHOD),
2047 FE(HTTP_QUERY_REFRESH),
2048 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2049 FE(HTTP_QUERY_AGE),
2050 FE(HTTP_QUERY_CACHE_CONTROL),
2051 FE(HTTP_QUERY_CONTENT_BASE),
2052 FE(HTTP_QUERY_CONTENT_LOCATION),
2053 FE(HTTP_QUERY_CONTENT_MD5),
2054 FE(HTTP_QUERY_CONTENT_RANGE),
2055 FE(HTTP_QUERY_ETAG),
2056 FE(HTTP_QUERY_HOST),
2057 FE(HTTP_QUERY_IF_MATCH),
2058 FE(HTTP_QUERY_IF_NONE_MATCH),
2059 FE(HTTP_QUERY_IF_RANGE),
2060 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2061 FE(HTTP_QUERY_MAX_FORWARDS),
2062 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2063 FE(HTTP_QUERY_RANGE),
2064 FE(HTTP_QUERY_TRANSFER_ENCODING),
2065 FE(HTTP_QUERY_UPGRADE),
2066 FE(HTTP_QUERY_VARY),
2067 FE(HTTP_QUERY_VIA),
2068 FE(HTTP_QUERY_WARNING),
2069 FE(HTTP_QUERY_CUSTOM)
2071 static const wininet_flag_info modifier_flags[] = {
2072 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2073 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2074 FE(HTTP_QUERY_FLAG_NUMBER),
2075 FE(HTTP_QUERY_FLAG_COALESCE)
2077 #undef FE
2078 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2079 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2080 DWORD i;
2082 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2083 TRACE(" Attribute:");
2084 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2085 if (query_flags[i].val == info) {
2086 TRACE(" %s", query_flags[i].name);
2087 break;
2090 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2091 TRACE(" Unknown (%08x)", info);
2094 TRACE(" Modifier:");
2095 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2096 if (modifier_flags[i].val & info_mod) {
2097 TRACE(" %s", modifier_flags[i].name);
2098 info_mod &= ~ modifier_flags[i].val;
2102 if (info_mod) {
2103 TRACE(" Unknown (%08x)", info_mod);
2105 TRACE("\n");
2108 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2109 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2111 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2112 goto lend;
2115 if (lpBuffer == NULL)
2116 *lpdwBufferLength = 0;
2117 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2118 lpBuffer, lpdwBufferLength, lpdwIndex);
2120 lend:
2121 if( lpwhr )
2122 WININET_Release( &lpwhr->hdr );
2124 TRACE("%d <--\n", bSuccess);
2125 return bSuccess;
2128 /***********************************************************************
2129 * HttpQueryInfoA (WININET.@)
2131 * Queries for information about an HTTP request
2133 * RETURNS
2134 * TRUE on success
2135 * FALSE on failure
2138 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2139 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2141 BOOL result;
2142 DWORD len;
2143 WCHAR* bufferW;
2145 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2146 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2148 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2149 lpdwBufferLength, lpdwIndex );
2152 if (lpBuffer)
2154 DWORD alloclen;
2155 len = (*lpdwBufferLength)*sizeof(WCHAR);
2156 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2158 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2159 if (alloclen < len)
2160 alloclen = len;
2162 else
2163 alloclen = len;
2164 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2165 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2166 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2167 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2168 } else
2170 bufferW = NULL;
2171 len = 0;
2174 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2175 &len, lpdwIndex );
2176 if( result )
2178 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2179 lpBuffer, *lpdwBufferLength, NULL, NULL );
2180 *lpdwBufferLength = len - 1;
2182 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2184 else
2185 /* since the strings being returned from HttpQueryInfoW should be
2186 * only ASCII characters, it is reasonable to assume that all of
2187 * the Unicode characters can be reduced to a single byte */
2188 *lpdwBufferLength = len / sizeof(WCHAR);
2190 HeapFree(GetProcessHeap(), 0, bufferW );
2192 return result;
2195 /***********************************************************************
2196 * HttpSendRequestExA (WININET.@)
2198 * Sends the specified request to the HTTP server and allows chunked
2199 * transfers.
2201 * RETURNS
2202 * Success: TRUE
2203 * Failure: FALSE, call GetLastError() for more information.
2205 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2206 LPINTERNET_BUFFERSA lpBuffersIn,
2207 LPINTERNET_BUFFERSA lpBuffersOut,
2208 DWORD dwFlags, DWORD_PTR dwContext)
2210 INTERNET_BUFFERSW BuffersInW;
2211 BOOL rc = FALSE;
2212 DWORD headerlen;
2213 LPWSTR header = NULL;
2215 TRACE("(%p, %p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersIn,
2216 lpBuffersOut, dwFlags, dwContext);
2218 if (lpBuffersIn)
2220 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2221 if (lpBuffersIn->lpcszHeader)
2223 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2224 lpBuffersIn->dwHeadersLength,0,0);
2225 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2226 if (!(BuffersInW.lpcszHeader = header))
2228 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2229 return FALSE;
2231 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2232 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2233 header, headerlen);
2235 else
2236 BuffersInW.lpcszHeader = NULL;
2237 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2238 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2239 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2240 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2241 BuffersInW.Next = NULL;
2244 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2246 HeapFree(GetProcessHeap(),0,header);
2248 return rc;
2251 /***********************************************************************
2252 * HttpSendRequestExW (WININET.@)
2254 * Sends the specified request to the HTTP server and allows chunked
2255 * transfers
2257 * RETURNS
2258 * Success: TRUE
2259 * Failure: FALSE, call GetLastError() for more information.
2261 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2262 LPINTERNET_BUFFERSW lpBuffersIn,
2263 LPINTERNET_BUFFERSW lpBuffersOut,
2264 DWORD dwFlags, DWORD_PTR dwContext)
2266 BOOL ret = FALSE;
2267 LPWININETHTTPREQW lpwhr;
2268 LPWININETHTTPSESSIONW lpwhs;
2269 LPWININETAPPINFOW hIC;
2271 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2272 lpBuffersOut, dwFlags, dwContext);
2274 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2276 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2278 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2279 goto lend;
2282 lpwhs = lpwhr->lpHttpSession;
2283 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2284 hIC = lpwhs->lpAppInfo;
2285 assert(hIC->hdr.htype == WH_HINIT);
2287 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2289 WORKREQUEST workRequest;
2290 struct WORKREQ_HTTPSENDREQUESTW *req;
2292 workRequest.asyncproc = AsyncHttpSendRequestProc;
2293 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2294 req = &workRequest.u.HttpSendRequestW;
2295 if (lpBuffersIn)
2297 if (lpBuffersIn->lpcszHeader)
2298 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2299 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2300 else
2301 req->lpszHeader = NULL;
2302 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2303 req->lpOptional = lpBuffersIn->lpvBuffer;
2304 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2305 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2307 else
2309 req->lpszHeader = NULL;
2310 req->dwHeaderLength = 0;
2311 req->lpOptional = NULL;
2312 req->dwOptionalLength = 0;
2313 req->dwContentLength = 0;
2316 req->bEndRequest = FALSE;
2318 INTERNET_AsyncCall(&workRequest);
2320 * This is from windows.
2322 INTERNET_SetLastError(ERROR_IO_PENDING);
2324 else
2326 if (lpBuffersIn)
2327 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2328 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2329 lpBuffersIn->dwBufferTotal, FALSE);
2330 else
2331 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2334 lend:
2335 if ( lpwhr )
2336 WININET_Release( &lpwhr->hdr );
2338 TRACE("<---\n");
2339 return ret;
2342 /***********************************************************************
2343 * HttpSendRequestW (WININET.@)
2345 * Sends the specified request to the HTTP server
2347 * RETURNS
2348 * TRUE on success
2349 * FALSE on failure
2352 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2353 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2355 LPWININETHTTPREQW lpwhr;
2356 LPWININETHTTPSESSIONW lpwhs = NULL;
2357 LPWININETAPPINFOW hIC = NULL;
2358 BOOL r;
2360 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2361 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2363 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2364 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2366 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2367 r = FALSE;
2368 goto lend;
2371 lpwhs = lpwhr->lpHttpSession;
2372 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2374 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2375 r = FALSE;
2376 goto lend;
2379 hIC = lpwhs->lpAppInfo;
2380 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2382 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2383 r = FALSE;
2384 goto lend;
2387 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2389 WORKREQUEST workRequest;
2390 struct WORKREQ_HTTPSENDREQUESTW *req;
2392 workRequest.asyncproc = AsyncHttpSendRequestProc;
2393 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2394 req = &workRequest.u.HttpSendRequestW;
2395 if (lpszHeaders)
2397 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2398 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2400 else
2401 req->lpszHeader = 0;
2402 req->dwHeaderLength = dwHeaderLength;
2403 req->lpOptional = lpOptional;
2404 req->dwOptionalLength = dwOptionalLength;
2405 req->dwContentLength = dwOptionalLength;
2406 req->bEndRequest = TRUE;
2408 INTERNET_AsyncCall(&workRequest);
2410 * This is from windows.
2412 INTERNET_SetLastError(ERROR_IO_PENDING);
2413 r = FALSE;
2415 else
2417 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2418 dwHeaderLength, lpOptional, dwOptionalLength,
2419 dwOptionalLength, TRUE);
2421 lend:
2422 if( lpwhr )
2423 WININET_Release( &lpwhr->hdr );
2424 return r;
2427 /***********************************************************************
2428 * HttpSendRequestA (WININET.@)
2430 * Sends the specified request to the HTTP server
2432 * RETURNS
2433 * TRUE on success
2434 * FALSE on failure
2437 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2438 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2440 BOOL result;
2441 LPWSTR szHeaders=NULL;
2442 DWORD nLen=dwHeaderLength;
2443 if(lpszHeaders!=NULL)
2445 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2446 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2447 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2449 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2450 HeapFree(GetProcessHeap(),0,szHeaders);
2451 return result;
2454 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2456 LPHTTPHEADERW host_header;
2458 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2460 host_header = HTTP_GetHeader(req, szHost);
2461 if(!host_header)
2462 return FALSE;
2464 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2465 return TRUE;
2468 /***********************************************************************
2469 * HTTP_HandleRedirect (internal)
2471 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2473 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2474 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2475 WCHAR path[2048];
2477 if(lpszUrl[0]=='/')
2479 /* if it's an absolute path, keep the same session info */
2480 lstrcpynW(path, lpszUrl, 2048);
2482 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2484 TRACE("Redirect through proxy\n");
2485 lstrcpynW(path, lpszUrl, 2048);
2487 else
2489 URL_COMPONENTSW urlComponents;
2490 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2491 static WCHAR szHttp[] = {'h','t','t','p',0};
2492 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2493 DWORD url_length = 0;
2494 LPWSTR orig_url;
2495 LPWSTR combined_url;
2497 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2498 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2499 urlComponents.dwSchemeLength = 0;
2500 urlComponents.lpszHostName = lpwhs->lpszHostName;
2501 urlComponents.dwHostNameLength = 0;
2502 urlComponents.nPort = lpwhs->nHostPort;
2503 urlComponents.lpszUserName = lpwhs->lpszUserName;
2504 urlComponents.dwUserNameLength = 0;
2505 urlComponents.lpszPassword = NULL;
2506 urlComponents.dwPasswordLength = 0;
2507 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2508 urlComponents.dwUrlPathLength = 0;
2509 urlComponents.lpszExtraInfo = NULL;
2510 urlComponents.dwExtraInfoLength = 0;
2512 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2513 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2514 return FALSE;
2516 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2518 /* convert from bytes to characters */
2519 url_length = url_length / sizeof(WCHAR) - 1;
2520 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2522 HeapFree(GetProcessHeap(), 0, orig_url);
2523 return FALSE;
2526 url_length = 0;
2527 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2528 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2530 HeapFree(GetProcessHeap(), 0, orig_url);
2531 return FALSE;
2533 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2535 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2537 HeapFree(GetProcessHeap(), 0, orig_url);
2538 HeapFree(GetProcessHeap(), 0, combined_url);
2539 return FALSE;
2541 HeapFree(GetProcessHeap(), 0, orig_url);
2543 userName[0] = 0;
2544 hostName[0] = 0;
2545 protocol[0] = 0;
2547 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2548 urlComponents.lpszScheme = protocol;
2549 urlComponents.dwSchemeLength = 32;
2550 urlComponents.lpszHostName = hostName;
2551 urlComponents.dwHostNameLength = MAXHOSTNAME;
2552 urlComponents.lpszUserName = userName;
2553 urlComponents.dwUserNameLength = 1024;
2554 urlComponents.lpszPassword = NULL;
2555 urlComponents.dwPasswordLength = 0;
2556 urlComponents.lpszUrlPath = path;
2557 urlComponents.dwUrlPathLength = 2048;
2558 urlComponents.lpszExtraInfo = NULL;
2559 urlComponents.dwExtraInfoLength = 0;
2560 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2562 HeapFree(GetProcessHeap(), 0, combined_url);
2563 return FALSE;
2566 HeapFree(GetProcessHeap(), 0, combined_url);
2568 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2569 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2571 TRACE("redirect from secure page to non-secure page\n");
2572 /* FIXME: warn about from secure redirect to non-secure page */
2573 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2575 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2576 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2578 TRACE("redirect from non-secure page to secure page\n");
2579 /* FIXME: notify about redirect to secure page */
2580 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2583 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2585 if (lstrlenW(protocol)>4) /*https*/
2586 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2587 else /*http*/
2588 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2591 #if 0
2593 * This upsets redirects to binary files on sourceforge.net
2594 * and gives an html page instead of the target file
2595 * Examination of the HTTP request sent by native wininet.dll
2596 * reveals that it doesn't send a referrer in that case.
2597 * Maybe there's a flag that enables this, or maybe a referrer
2598 * shouldn't be added in case of a redirect.
2601 /* consider the current host as the referrer */
2602 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2603 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2604 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2605 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2606 #endif
2608 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2609 lpwhs->lpszServerName = WININET_strdupW(hostName);
2610 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2611 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2612 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2614 int len;
2615 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2616 len = lstrlenW(hostName);
2617 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2618 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2619 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2621 else
2622 lpwhs->lpszHostName = WININET_strdupW(hostName);
2624 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2627 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2628 lpwhs->lpszUserName = NULL;
2629 if (userName[0])
2630 lpwhs->lpszUserName = WININET_strdupW(userName);
2631 lpwhs->nServerPort = urlComponents.nPort;
2633 if (!HTTP_ResolveName(lpwhr))
2634 return FALSE;
2636 NETCON_close(&lpwhr->netConnection);
2638 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2639 return FALSE;
2642 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2643 lpwhr->lpszPath=NULL;
2644 if (*path)
2646 DWORD needed = 0;
2647 HRESULT rc;
2649 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2650 if (rc != E_POINTER)
2651 needed = strlenW(path)+1;
2652 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2653 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2654 URL_ESCAPE_SPACES_ONLY);
2655 if (rc)
2657 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2658 strcpyW(lpwhr->lpszPath,path);
2662 return TRUE;
2665 /***********************************************************************
2666 * HTTP_build_req (internal)
2668 * concatenate all the strings in the request together
2670 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2672 LPCWSTR *t;
2673 LPWSTR str;
2675 for( t = list; *t ; t++ )
2676 len += strlenW( *t );
2677 len++;
2679 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2680 *str = 0;
2682 for( t = list; *t ; t++ )
2683 strcatW( str, *t );
2685 return str;
2688 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2690 LPWSTR lpszPath;
2691 LPWSTR requestString;
2692 INT len;
2693 INT cnt;
2694 INT responseLen;
2695 char *ascii_req;
2696 BOOL ret;
2697 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2698 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2699 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2701 TRACE("\n");
2703 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2704 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2705 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
2706 HeapFree( GetProcessHeap(), 0, lpszPath );
2708 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2709 NULL, 0, NULL, NULL );
2710 len--; /* the nul terminator isn't needed */
2711 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2712 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2713 ascii_req, len, NULL, NULL );
2714 HeapFree( GetProcessHeap(), 0, requestString );
2716 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2718 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2719 HeapFree( GetProcessHeap(), 0, ascii_req );
2720 if (!ret || cnt < 0)
2721 return FALSE;
2723 responseLen = HTTP_GetResponseHeaders( lpwhr );
2724 if (!responseLen)
2725 return FALSE;
2727 return TRUE;
2730 /***********************************************************************
2731 * HTTP_HttpSendRequestW (internal)
2733 * Sends the specified request to the HTTP server
2735 * RETURNS
2736 * TRUE on success
2737 * FALSE on failure
2740 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2741 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2742 DWORD dwContentLength, BOOL bEndRequest)
2744 INT cnt;
2745 BOOL bSuccess = FALSE;
2746 LPWSTR requestString = NULL;
2747 INT responseLen;
2748 BOOL loop_next;
2749 INTERNET_ASYNC_RESULT iar;
2750 static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
2751 static const WCHAR szPost[] = { 'P','O','S','T',0 };
2752 static const WCHAR szContentLength[] =
2753 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
2754 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
2756 TRACE("--> %p\n", lpwhr);
2758 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2760 /* Clear any error information */
2761 INTERNET_SetLastError(0);
2763 /* if the verb is NULL default to GET */
2764 if (!lpwhr->lpszVerb)
2765 lpwhr->lpszVerb = WININET_strdupW(szGET);
2767 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
2769 sprintfW(contentLengthStr, szContentLength, dwContentLength);
2770 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2775 DWORD len;
2776 char *ascii_req;
2778 loop_next = FALSE;
2780 /* like native, just in case the caller forgot to call InternetReadFile
2781 * for all the data */
2782 HTTP_DrainContent(lpwhr);
2783 lpwhr->dwContentRead = 0;
2785 if (TRACE_ON(wininet))
2787 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
2788 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2791 HTTP_FixURL(lpwhr);
2792 HTTP_ProcessHeader(lpwhr, szConnection,
2793 lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
2794 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
2796 HTTP_InsertAuthorization(lpwhr, szAuthorization, !loop_next);
2797 HTTP_InsertAuthorization(lpwhr, szProxy_Authorization, !loop_next);
2799 /* add the headers the caller supplied */
2800 if( lpszHeaders && dwHeaderLength )
2802 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2803 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2806 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2808 TRACE("Request header -> %s\n", debugstr_w(requestString) );
2810 /* Send the request and store the results */
2811 if (!HTTP_OpenConnection(lpwhr))
2812 goto lend;
2814 /* send the request as ASCII, tack on the optional data */
2815 if( !lpOptional )
2816 dwOptionalLength = 0;
2817 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2818 NULL, 0, NULL, NULL );
2819 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2820 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2821 ascii_req, len, NULL, NULL );
2822 if( lpOptional )
2823 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2824 len = (len + dwOptionalLength - 1);
2825 ascii_req[len] = 0;
2826 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2828 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2829 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2831 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2832 HeapFree( GetProcessHeap(), 0, ascii_req );
2834 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2835 INTERNET_STATUS_REQUEST_SENT,
2836 &len, sizeof(DWORD));
2838 if (bEndRequest)
2840 DWORD dwBufferSize;
2841 DWORD dwStatusCode;
2843 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2844 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2846 if (cnt < 0)
2847 goto lend;
2849 responseLen = HTTP_GetResponseHeaders(lpwhr);
2850 if (responseLen)
2851 bSuccess = TRUE;
2853 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2854 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2855 sizeof(DWORD));
2857 HTTP_ProcessCookies(lpwhr);
2859 dwBufferSize = sizeof(lpwhr->dwContentLength);
2860 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2861 &lpwhr->dwContentLength,&dwBufferSize,NULL))
2862 lpwhr->dwContentLength = -1;
2864 if (lpwhr->dwContentLength == 0)
2865 HTTP_FinishedReading(lpwhr);
2867 dwBufferSize = sizeof(dwStatusCode);
2868 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
2869 &dwStatusCode,&dwBufferSize,NULL))
2870 dwStatusCode = 0;
2872 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
2874 WCHAR szNewLocation[2048];
2875 dwBufferSize=sizeof(szNewLocation);
2876 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
2877 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
2879 HTTP_DrainContent(lpwhr);
2880 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2881 INTERNET_STATUS_REDIRECT, szNewLocation,
2882 dwBufferSize);
2883 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
2884 if (bSuccess)
2886 HeapFree(GetProcessHeap(), 0, requestString);
2887 loop_next = TRUE;
2891 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
2893 WCHAR szAuthValue[2048];
2894 dwBufferSize=2048;
2895 if (dwStatusCode == HTTP_STATUS_DENIED)
2897 DWORD dwIndex = 0;
2898 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2900 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2901 &lpwhr->pAuthInfo,
2902 lpwhr->lpHttpSession->lpszUserName,
2903 lpwhr->lpHttpSession->lpszPassword))
2905 loop_next = TRUE;
2906 break;
2910 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
2912 DWORD dwIndex = 0;
2913 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2915 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2916 &lpwhr->pProxyAuthInfo,
2917 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
2918 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
2920 loop_next = TRUE;
2921 break;
2927 else
2928 bSuccess = TRUE;
2930 while (loop_next);
2932 /* FIXME: Better check, when we have to create the cache file */
2933 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
2934 WCHAR url[INTERNET_MAX_URL_LENGTH];
2935 WCHAR cacheFileName[MAX_PATH+1];
2936 BOOL b;
2938 b = HTTP_GetRequestURL(lpwhr, url);
2939 if(!b) {
2940 WARN("Could not get URL\n");
2941 goto lend;
2944 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
2945 if(b) {
2946 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
2947 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2948 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2949 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
2950 WARN("Could not create file: %u\n", GetLastError());
2951 lpwhr->hCacheFile = NULL;
2953 }else {
2954 WARN("Could not create cache entry: %08x\n", GetLastError());
2958 lend:
2960 HeapFree(GetProcessHeap(), 0, requestString);
2962 /* TODO: send notification for P3P header */
2964 iar.dwResult = (DWORD)bSuccess;
2965 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2967 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2968 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2969 sizeof(INTERNET_ASYNC_RESULT));
2971 TRACE("<--\n");
2972 return bSuccess;
2975 /***********************************************************************
2976 * HTTPSESSION_Destroy (internal)
2978 * Deallocate session handle
2981 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
2983 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
2985 TRACE("%p\n", lpwhs);
2987 WININET_Release(&lpwhs->lpAppInfo->hdr);
2989 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2990 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2991 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
2992 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2993 HeapFree(GetProcessHeap(), 0, lpwhs);
2997 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
2998 HTTPSESSION_Destroy,
2999 NULL,
3000 NULL,
3001 NULL,
3002 NULL,
3003 NULL
3007 /***********************************************************************
3008 * HTTP_Connect (internal)
3010 * Create http session handle
3012 * RETURNS
3013 * HINTERNET a session handle on success
3014 * NULL on failure
3017 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3018 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3019 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3020 DWORD dwInternalFlags)
3022 BOOL bSuccess = FALSE;
3023 LPWININETHTTPSESSIONW lpwhs = NULL;
3024 HINTERNET handle = NULL;
3026 TRACE("-->\n");
3028 if (!lpszServerName || !lpszServerName[0])
3030 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3031 goto lerror;
3034 assert( hIC->hdr.htype == WH_HINIT );
3036 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3037 if (NULL == lpwhs)
3039 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3040 goto lerror;
3044 * According to my tests. The name is not resolved until a request is sent
3047 lpwhs->hdr.htype = WH_HHTTPSESSION;
3048 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3049 lpwhs->hdr.dwFlags = dwFlags;
3050 lpwhs->hdr.dwContext = dwContext;
3051 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3052 lpwhs->hdr.dwRefCount = 1;
3053 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3055 WININET_AddRef( &hIC->hdr );
3056 lpwhs->lpAppInfo = hIC;
3057 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3059 handle = WININET_AllocHandle( &lpwhs->hdr );
3060 if (NULL == handle)
3062 ERR("Failed to alloc handle\n");
3063 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3064 goto lerror;
3067 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3068 if(strchrW(hIC->lpszProxy, ' '))
3069 FIXME("Several proxies not implemented.\n");
3070 if(hIC->lpszProxyBypass)
3071 FIXME("Proxy bypass is ignored.\n");
3073 if (lpszServerName && lpszServerName[0])
3075 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3076 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3078 if (lpszUserName && lpszUserName[0])
3079 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3080 if (lpszPassword && lpszPassword[0])
3081 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3082 lpwhs->nServerPort = nServerPort;
3083 lpwhs->nHostPort = nServerPort;
3085 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3086 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3088 INTERNET_SendCallback(&hIC->hdr, dwContext,
3089 INTERNET_STATUS_HANDLE_CREATED, &handle,
3090 sizeof(handle));
3093 bSuccess = TRUE;
3095 lerror:
3096 if( lpwhs )
3097 WININET_Release( &lpwhs->hdr );
3100 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3101 * windows
3104 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3105 return handle;
3109 /***********************************************************************
3110 * HTTP_OpenConnection (internal)
3112 * Connect to a web server
3114 * RETURNS
3116 * TRUE on success
3117 * FALSE on failure
3119 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3121 BOOL bSuccess = FALSE;
3122 LPWININETHTTPSESSIONW lpwhs;
3123 LPWININETAPPINFOW hIC = NULL;
3124 char szaddr[32];
3126 TRACE("-->\n");
3129 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3131 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3132 goto lend;
3135 if (NETCON_connected(&lpwhr->netConnection))
3137 bSuccess = TRUE;
3138 goto lend;
3141 lpwhs = lpwhr->lpHttpSession;
3143 hIC = lpwhs->lpAppInfo;
3144 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3145 szaddr, sizeof(szaddr));
3146 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3147 INTERNET_STATUS_CONNECTING_TO_SERVER,
3148 szaddr,
3149 strlen(szaddr)+1);
3151 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3152 SOCK_STREAM, 0))
3154 WARN("Socket creation failed\n");
3155 goto lend;
3158 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3159 sizeof(lpwhs->socketAddress)))
3160 goto lend;
3162 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3164 /* Note: we differ from Microsoft's WinINet here. they seem to have
3165 * a bug that causes no status callbacks to be sent when starting
3166 * a tunnel to a proxy server using the CONNECT verb. i believe our
3167 * behaviour to be more correct and to not cause any incompatibilities
3168 * because using a secure connection through a proxy server is a rare
3169 * case that would be hard for anyone to depend on */
3170 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3171 goto lend;
3173 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3175 WARN("Couldn't connect securely to host\n");
3176 goto lend;
3180 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3181 INTERNET_STATUS_CONNECTED_TO_SERVER,
3182 szaddr, strlen(szaddr)+1);
3184 bSuccess = TRUE;
3186 lend:
3187 TRACE("%d <--\n", bSuccess);
3188 return bSuccess;
3192 /***********************************************************************
3193 * HTTP_clear_response_headers (internal)
3195 * clear out any old response headers
3197 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3199 DWORD i;
3201 for( i=0; i<lpwhr->nCustHeaders; i++)
3203 if( !lpwhr->pCustHeaders[i].lpszField )
3204 continue;
3205 if( !lpwhr->pCustHeaders[i].lpszValue )
3206 continue;
3207 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3208 continue;
3209 HTTP_DeleteCustomHeader( lpwhr, i );
3210 i--;
3214 /***********************************************************************
3215 * HTTP_GetResponseHeaders (internal)
3217 * Read server response
3219 * RETURNS
3221 * TRUE on success
3222 * FALSE on error
3224 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
3226 INT cbreaks = 0;
3227 WCHAR buffer[MAX_REPLY_LEN];
3228 DWORD buflen = MAX_REPLY_LEN;
3229 BOOL bSuccess = FALSE;
3230 INT rc = 0;
3231 static const WCHAR szCrLf[] = {'\r','\n',0};
3232 static const WCHAR szHundred[] = {'1','0','0',0};
3233 char bufferA[MAX_REPLY_LEN];
3234 LPWSTR status_code, status_text;
3235 DWORD cchMaxRawHeaders = 1024;
3236 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3237 DWORD cchRawHeaders = 0;
3239 TRACE("-->\n");
3241 /* clear old response headers (eg. from a redirect response) */
3242 HTTP_clear_response_headers( lpwhr );
3244 if (!NETCON_connected(&lpwhr->netConnection))
3245 goto lend;
3247 do {
3249 * HACK peek at the buffer
3251 buflen = MAX_REPLY_LEN;
3252 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3255 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3257 memset(buffer, 0, MAX_REPLY_LEN);
3258 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3259 goto lend;
3260 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3262 /* split the version from the status code */
3263 status_code = strchrW( buffer, ' ' );
3264 if( !status_code )
3265 goto lend;
3266 *status_code++=0;
3268 /* split the status code from the status text */
3269 status_text = strchrW( status_code, ' ' );
3270 if( !status_text )
3271 goto lend;
3272 *status_text++=0;
3274 TRACE("version [%s] status code [%s] status text [%s]\n",
3275 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3277 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3279 /* Add status code */
3280 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3281 HTTP_ADDHDR_FLAG_REPLACE);
3283 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3284 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3286 lpwhr->lpszVersion= WININET_strdupW(buffer);
3287 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3289 /* Restore the spaces */
3290 *(status_code-1) = ' ';
3291 *(status_text-1) = ' ';
3293 /* regenerate raw headers */
3294 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3296 cchMaxRawHeaders *= 2;
3297 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3299 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3300 cchRawHeaders += (buflen-1);
3301 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3302 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3303 lpszRawHeaders[cchRawHeaders] = '\0';
3305 /* Parse each response line */
3308 buflen = MAX_REPLY_LEN;
3309 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3311 LPWSTR * pFieldAndValue;
3313 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3314 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3316 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3318 cchMaxRawHeaders *= 2;
3319 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3321 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3322 cchRawHeaders += (buflen-1);
3323 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3324 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3325 lpszRawHeaders[cchRawHeaders] = '\0';
3327 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3328 if (!pFieldAndValue)
3329 break;
3331 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3332 HTTP_ADDREQ_FLAG_ADD );
3334 HTTP_FreeTokens(pFieldAndValue);
3336 else
3338 cbreaks++;
3339 if (cbreaks >= 2)
3340 break;
3342 }while(1);
3344 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3345 lpwhr->lpszRawHeaders = lpszRawHeaders;
3346 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3347 bSuccess = TRUE;
3349 lend:
3351 TRACE("<--\n");
3352 if (bSuccess)
3353 return rc;
3354 else
3355 return 0;
3359 static void strip_spaces(LPWSTR start)
3361 LPWSTR str = start;
3362 LPWSTR end;
3364 while (*str == ' ' && *str != '\0')
3365 str++;
3367 if (str != start)
3368 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3370 end = start + strlenW(start) - 1;
3371 while (end >= start && *end == ' ')
3373 *end = '\0';
3374 end--;
3379 /***********************************************************************
3380 * HTTP_InterpretHttpHeader (internal)
3382 * Parse server response
3384 * RETURNS
3386 * Pointer to array of field, value, NULL on success.
3387 * NULL on error.
3389 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3391 LPWSTR * pTokenPair;
3392 LPWSTR pszColon;
3393 INT len;
3395 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3397 pszColon = strchrW(buffer, ':');
3398 /* must have two tokens */
3399 if (!pszColon)
3401 HTTP_FreeTokens(pTokenPair);
3402 if (buffer[0])
3403 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3404 return NULL;
3407 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3408 if (!pTokenPair[0])
3410 HTTP_FreeTokens(pTokenPair);
3411 return NULL;
3413 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3414 pTokenPair[0][pszColon - buffer] = '\0';
3416 /* skip colon */
3417 pszColon++;
3418 len = strlenW(pszColon);
3419 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3420 if (!pTokenPair[1])
3422 HTTP_FreeTokens(pTokenPair);
3423 return NULL;
3425 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3427 strip_spaces(pTokenPair[0]);
3428 strip_spaces(pTokenPair[1]);
3430 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3431 return pTokenPair;
3434 /***********************************************************************
3435 * HTTP_ProcessHeader (internal)
3437 * Stuff header into header tables according to <dwModifier>
3441 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3443 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3445 LPHTTPHEADERW lphttpHdr = NULL;
3446 BOOL bSuccess = FALSE;
3447 INT index = -1;
3448 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3450 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3452 /* REPLACE wins out over ADD */
3453 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3454 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3456 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3457 index = -1;
3458 else
3459 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3461 if (index >= 0)
3463 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3465 return FALSE;
3467 lphttpHdr = &lpwhr->pCustHeaders[index];
3469 else if (value)
3471 HTTPHEADERW hdr;
3473 hdr.lpszField = (LPWSTR)field;
3474 hdr.lpszValue = (LPWSTR)value;
3475 hdr.wFlags = hdr.wCount = 0;
3477 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3478 hdr.wFlags |= HDR_ISREQUEST;
3480 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3482 /* no value to delete */
3483 else return TRUE;
3485 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3486 lphttpHdr->wFlags |= HDR_ISREQUEST;
3487 else
3488 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3490 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3492 HTTP_DeleteCustomHeader( lpwhr, index );
3494 if (value)
3496 HTTPHEADERW hdr;
3498 hdr.lpszField = (LPWSTR)field;
3499 hdr.lpszValue = (LPWSTR)value;
3500 hdr.wFlags = hdr.wCount = 0;
3502 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3503 hdr.wFlags |= HDR_ISREQUEST;
3505 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3508 return TRUE;
3510 else if (dwModifier & COALESCEFLAGS)
3512 LPWSTR lpsztmp;
3513 WCHAR ch = 0;
3514 INT len = 0;
3515 INT origlen = strlenW(lphttpHdr->lpszValue);
3516 INT valuelen = strlenW(value);
3518 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3520 ch = ',';
3521 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3523 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3525 ch = ';';
3526 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3529 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3531 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3532 if (lpsztmp)
3534 lphttpHdr->lpszValue = lpsztmp;
3535 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3536 if (ch > 0)
3538 lphttpHdr->lpszValue[origlen] = ch;
3539 origlen++;
3540 lphttpHdr->lpszValue[origlen] = ' ';
3541 origlen++;
3544 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3545 lphttpHdr->lpszValue[len] = '\0';
3546 bSuccess = TRUE;
3548 else
3550 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3551 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3554 TRACE("<-- %d\n",bSuccess);
3555 return bSuccess;
3559 /***********************************************************************
3560 * HTTP_FinishedReading (internal)
3562 * Called when all content from server has been read by client.
3565 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
3567 WCHAR szConnectionResponse[20];
3568 DWORD dwBufferSize = sizeof(szConnectionResponse);
3570 TRACE("\n");
3572 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse,
3573 &dwBufferSize, NULL) ||
3574 strcmpiW(szConnectionResponse, szKeepAlive))
3576 HTTPREQ_CloseConnection(&lpwhr->hdr);
3579 /* FIXME: store data in the URL cache here */
3581 return TRUE;
3585 /***********************************************************************
3586 * HTTP_GetCustomHeaderIndex (internal)
3588 * Return index of custom header from header array
3591 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
3592 int requested_index, BOOL request_only)
3594 DWORD index;
3596 TRACE("%s\n", debugstr_w(lpszField));
3598 for (index = 0; index < lpwhr->nCustHeaders; index++)
3600 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3601 continue;
3603 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3604 continue;
3606 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3607 continue;
3609 if (requested_index == 0)
3610 break;
3611 requested_index --;
3614 if (index >= lpwhr->nCustHeaders)
3615 index = -1;
3617 TRACE("Return: %d\n", index);
3618 return index;
3622 /***********************************************************************
3623 * HTTP_InsertCustomHeader (internal)
3625 * Insert header into array
3628 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3630 INT count;
3631 LPHTTPHEADERW lph = NULL;
3632 BOOL r = FALSE;
3634 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3635 count = lpwhr->nCustHeaders + 1;
3636 if (count > 1)
3637 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3638 else
3639 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3641 if (NULL != lph)
3643 lpwhr->pCustHeaders = lph;
3644 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3645 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3646 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3647 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3648 lpwhr->nCustHeaders++;
3649 r = TRUE;
3651 else
3653 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3656 return r;
3660 /***********************************************************************
3661 * HTTP_DeleteCustomHeader (internal)
3663 * Delete header from array
3664 * If this function is called, the indexs may change.
3666 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3668 if( lpwhr->nCustHeaders <= 0 )
3669 return FALSE;
3670 if( index >= lpwhr->nCustHeaders )
3671 return FALSE;
3672 lpwhr->nCustHeaders--;
3674 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3675 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3676 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3678 return TRUE;
3682 /***********************************************************************
3683 * HTTP_VerifyValidHeader (internal)
3685 * Verify the given header is not invalid for the given http request
3688 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
3690 BOOL rc = TRUE;
3692 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
3693 if (strcmpiW(field,szAccept_Encoding)==0)
3694 return FALSE;
3696 return rc;
3699 /***********************************************************************
3700 * IsHostInProxyBypassList (@)
3702 * Undocumented
3705 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3707 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
3708 return FALSE;