wininet: Moved InternetFindNextFileW implementation to vtbl.
[wine/hacks.git] / dlls / wininet / http.c
blob432b142d85fa4e181f1ec5e36f5055001cf9a4a4
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 const HANDLEHEADERVtbl HTTPREQVtbl = {
1422 HTTPREQ_Destroy,
1423 HTTPREQ_CloseConnection,
1424 HTTPREQ_SetOption,
1425 HTTPREQ_WriteFile,
1426 NULL
1429 /***********************************************************************
1430 * HTTP_HttpOpenRequestW (internal)
1432 * Open a HTTP request handle
1434 * RETURNS
1435 * HINTERNET a HTTP request handle on success
1436 * NULL on failure
1439 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1440 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1441 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1442 DWORD dwFlags, DWORD_PTR dwContext)
1444 LPWININETAPPINFOW hIC = NULL;
1445 LPWININETHTTPREQW lpwhr;
1446 LPWSTR lpszCookies;
1447 LPWSTR lpszUrl = NULL;
1448 DWORD nCookieSize;
1449 HINTERNET handle = NULL;
1450 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1451 DWORD len;
1452 LPHTTPHEADERW Host;
1454 TRACE("-->\n");
1456 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1457 hIC = lpwhs->lpAppInfo;
1459 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1460 if (NULL == lpwhr)
1462 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1463 goto lend;
1465 lpwhr->hdr.htype = WH_HHTTPREQ;
1466 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1467 lpwhr->hdr.dwFlags = dwFlags;
1468 lpwhr->hdr.dwContext = dwContext;
1469 lpwhr->hdr.dwRefCount = 1;
1470 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1471 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1473 WININET_AddRef( &lpwhs->hdr );
1474 lpwhr->lpHttpSession = lpwhs;
1475 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1477 handle = WININET_AllocHandle( &lpwhr->hdr );
1478 if (NULL == handle)
1480 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1481 goto lend;
1484 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1486 InternetCloseHandle( handle );
1487 handle = NULL;
1488 goto lend;
1491 if (lpszObjectName && *lpszObjectName) {
1492 HRESULT rc;
1494 len = 0;
1495 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1496 if (rc != E_POINTER)
1497 len = strlenW(lpszObjectName)+1;
1498 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1499 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1500 URL_ESCAPE_SPACES_ONLY);
1501 if (rc)
1503 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1504 strcpyW(lpwhr->lpszPath,lpszObjectName);
1508 if (lpszReferrer && *lpszReferrer)
1509 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1511 if (lpszAcceptTypes)
1513 int i;
1514 for (i = 0; lpszAcceptTypes[i]; i++)
1516 if (!*lpszAcceptTypes[i]) continue;
1517 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1518 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1519 HTTP_ADDHDR_FLAG_REQ |
1520 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1524 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1526 if (lpszVersion)
1527 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1528 else
1529 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1531 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1533 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1534 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1535 INTERNET_DEFAULT_HTTPS_PORT :
1536 INTERNET_DEFAULT_HTTP_PORT);
1537 lpwhs->nHostPort = lpwhs->nServerPort;
1539 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1540 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1542 if (hIC->lpszAgent)
1544 WCHAR *agent_header;
1545 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1547 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1548 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1549 sprintfW(agent_header, user_agent, hIC->lpszAgent );
1551 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1552 HTTP_ADDREQ_FLAG_ADD);
1553 HeapFree(GetProcessHeap(), 0, agent_header);
1556 Host = HTTP_GetHeader(lpwhr,szHost);
1558 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1559 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1560 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1562 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1563 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1565 int cnt = 0;
1566 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1567 static const WCHAR szcrlf[] = {'\r','\n',0};
1569 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1571 cnt += sprintfW(lpszCookies, szCookie);
1572 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1573 strcatW(lpszCookies, szcrlf);
1575 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1576 HTTP_ADDREQ_FLAG_ADD);
1577 HeapFree(GetProcessHeap(), 0, lpszCookies);
1579 HeapFree(GetProcessHeap(), 0, lpszUrl);
1582 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1583 INTERNET_STATUS_HANDLE_CREATED, &handle,
1584 sizeof(handle));
1587 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1590 if (!HTTP_ResolveName(lpwhr))
1592 InternetCloseHandle( handle );
1593 handle = NULL;
1596 lend:
1597 if( lpwhr )
1598 WININET_Release( &lpwhr->hdr );
1600 TRACE("<-- %p (%p)\n", handle, lpwhr);
1601 return handle;
1604 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1605 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1606 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1607 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1608 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1609 static const WCHAR szAge[] = { 'A','g','e',0 };
1610 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1611 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1612 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1613 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1614 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1615 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1616 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1617 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1618 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1619 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1620 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1621 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 };
1622 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1623 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1624 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1625 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1626 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1627 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1628 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1629 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1630 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1631 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1632 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1633 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1634 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1635 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1636 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1637 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1638 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1639 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1640 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1641 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1642 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1643 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1644 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1645 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1646 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1647 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1648 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 };
1649 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1650 static const WCHAR szURI[] = { 'U','R','I',0 };
1651 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1652 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1653 static const WCHAR szVia[] = { 'V','i','a',0 };
1654 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1655 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1657 static const LPCWSTR header_lookup[] = {
1658 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
1659 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
1660 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1661 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
1662 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1663 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
1664 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
1665 szAllow, /* HTTP_QUERY_ALLOW = 7 */
1666 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
1667 szDate, /* HTTP_QUERY_DATE = 9 */
1668 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
1669 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
1670 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
1671 szURI, /* HTTP_QUERY_URI = 13 */
1672 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
1673 NULL, /* HTTP_QUERY_COST = 15 */
1674 NULL, /* HTTP_QUERY_LINK = 16 */
1675 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
1676 NULL, /* HTTP_QUERY_VERSION = 18 */
1677 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
1678 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
1679 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
1680 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
1681 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
1682 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
1683 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
1684 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
1685 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
1686 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
1687 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
1688 NULL, /* HTTP_QUERY_FORWARDED = 30 */
1689 NULL, /* HTTP_QUERY_FROM = 31 */
1690 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
1691 szLocation, /* HTTP_QUERY_LOCATION = 33 */
1692 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
1693 szReferer, /* HTTP_QUERY_REFERER = 35 */
1694 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
1695 szServer, /* HTTP_QUERY_SERVER = 37 */
1696 NULL, /* HTTP_TITLE = 38 */
1697 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
1698 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
1699 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
1700 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
1701 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
1702 szCookie, /* HTTP_QUERY_COOKIE = 44 */
1703 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
1704 NULL, /* HTTP_QUERY_REFRESH = 46 */
1705 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
1706 szAge, /* HTTP_QUERY_AGE = 48 */
1707 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
1708 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
1709 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
1710 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
1711 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
1712 szETag, /* HTTP_QUERY_ETAG = 54 */
1713 szHost, /* HTTP_QUERY_HOST = 55 */
1714 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
1715 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
1716 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
1717 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
1718 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
1719 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
1720 szRange, /* HTTP_QUERY_RANGE = 62 */
1721 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
1722 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
1723 szVary, /* HTTP_QUERY_VARY = 65 */
1724 szVia, /* HTTP_QUERY_VIA = 66 */
1725 szWarning, /* HTTP_QUERY_WARNING = 67 */
1726 szExpect, /* HTTP_QUERY_EXPECT = 68 */
1727 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
1728 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
1731 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
1733 /***********************************************************************
1734 * HTTP_HttpQueryInfoW (internal)
1736 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1737 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1739 LPHTTPHEADERW lphttpHdr = NULL;
1740 BOOL bSuccess = FALSE;
1741 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1742 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
1743 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
1744 INT index = -1;
1746 /* Find requested header structure */
1747 switch (level)
1749 case HTTP_QUERY_CUSTOM:
1750 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
1751 break;
1753 case HTTP_QUERY_RAW_HEADERS_CRLF:
1755 LPWSTR headers;
1756 DWORD len;
1757 BOOL ret;
1759 if (request_only)
1760 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
1761 else
1762 headers = lpwhr->lpszRawHeaders;
1764 len = strlenW(headers);
1765 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1767 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1768 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1769 ret = FALSE;
1770 } else
1772 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
1773 *lpdwBufferLength = len * sizeof(WCHAR);
1775 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1776 ret = TRUE;
1779 if (request_only)
1780 HeapFree(GetProcessHeap(), 0, headers);
1781 return ret;
1783 case HTTP_QUERY_RAW_HEADERS:
1785 static const WCHAR szCrLf[] = {'\r','\n',0};
1786 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1787 DWORD i, size = 0;
1788 LPWSTR pszString = (WCHAR*)lpBuffer;
1790 for (i = 0; ppszRawHeaderLines[i]; i++)
1791 size += strlenW(ppszRawHeaderLines[i]) + 1;
1793 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1795 HTTP_FreeTokens(ppszRawHeaderLines);
1796 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1797 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1798 return FALSE;
1801 for (i = 0; ppszRawHeaderLines[i]; i++)
1803 DWORD len = strlenW(ppszRawHeaderLines[i]);
1804 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1805 pszString += len+1;
1807 *pszString = '\0';
1809 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1811 *lpdwBufferLength = size * sizeof(WCHAR);
1812 HTTP_FreeTokens(ppszRawHeaderLines);
1814 return TRUE;
1816 case HTTP_QUERY_STATUS_TEXT:
1817 if (lpwhr->lpszStatusText)
1819 DWORD len = strlenW(lpwhr->lpszStatusText);
1820 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1822 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1823 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1824 return FALSE;
1826 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1827 *lpdwBufferLength = len * sizeof(WCHAR);
1829 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1831 return TRUE;
1833 break;
1834 case HTTP_QUERY_VERSION:
1835 if (lpwhr->lpszVersion)
1837 DWORD len = strlenW(lpwhr->lpszVersion);
1838 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1840 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1841 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1842 return FALSE;
1844 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
1845 *lpdwBufferLength = len * sizeof(WCHAR);
1847 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1849 return TRUE;
1851 break;
1852 default:
1853 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
1855 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
1856 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
1857 requested_index,request_only);
1860 if (index >= 0)
1861 lphttpHdr = &lpwhr->pCustHeaders[index];
1863 /* Ensure header satisfies requested attributes */
1864 if (!lphttpHdr ||
1865 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
1866 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
1868 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1869 return bSuccess;
1872 if (lpdwIndex)
1873 (*lpdwIndex)++;
1875 /* coalesce value to requested type */
1876 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
1878 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
1879 bSuccess = TRUE;
1881 TRACE(" returning number : %d\n", *(int *)lpBuffer);
1883 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
1885 time_t tmpTime;
1886 struct tm tmpTM;
1887 SYSTEMTIME *STHook;
1889 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
1891 tmpTM = *gmtime(&tmpTime);
1892 STHook = (SYSTEMTIME *) lpBuffer;
1893 if(STHook==NULL)
1894 return bSuccess;
1896 STHook->wDay = tmpTM.tm_mday;
1897 STHook->wHour = tmpTM.tm_hour;
1898 STHook->wMilliseconds = 0;
1899 STHook->wMinute = tmpTM.tm_min;
1900 STHook->wDayOfWeek = tmpTM.tm_wday;
1901 STHook->wMonth = tmpTM.tm_mon + 1;
1902 STHook->wSecond = tmpTM.tm_sec;
1903 STHook->wYear = tmpTM.tm_year;
1905 bSuccess = TRUE;
1907 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
1908 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
1909 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
1911 else if (lphttpHdr->lpszValue)
1913 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
1915 if (len > *lpdwBufferLength)
1917 *lpdwBufferLength = len;
1918 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1919 return bSuccess;
1922 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
1923 *lpdwBufferLength = len - sizeof(WCHAR);
1924 bSuccess = TRUE;
1926 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
1928 return bSuccess;
1931 /***********************************************************************
1932 * HttpQueryInfoW (WININET.@)
1934 * Queries for information about an HTTP request
1936 * RETURNS
1937 * TRUE on success
1938 * FALSE on failure
1941 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1942 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1944 BOOL bSuccess = FALSE;
1945 LPWININETHTTPREQW lpwhr;
1947 if (TRACE_ON(wininet)) {
1948 #define FE(x) { x, #x }
1949 static const wininet_flag_info query_flags[] = {
1950 FE(HTTP_QUERY_MIME_VERSION),
1951 FE(HTTP_QUERY_CONTENT_TYPE),
1952 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
1953 FE(HTTP_QUERY_CONTENT_ID),
1954 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
1955 FE(HTTP_QUERY_CONTENT_LENGTH),
1956 FE(HTTP_QUERY_CONTENT_LANGUAGE),
1957 FE(HTTP_QUERY_ALLOW),
1958 FE(HTTP_QUERY_PUBLIC),
1959 FE(HTTP_QUERY_DATE),
1960 FE(HTTP_QUERY_EXPIRES),
1961 FE(HTTP_QUERY_LAST_MODIFIED),
1962 FE(HTTP_QUERY_MESSAGE_ID),
1963 FE(HTTP_QUERY_URI),
1964 FE(HTTP_QUERY_DERIVED_FROM),
1965 FE(HTTP_QUERY_COST),
1966 FE(HTTP_QUERY_LINK),
1967 FE(HTTP_QUERY_PRAGMA),
1968 FE(HTTP_QUERY_VERSION),
1969 FE(HTTP_QUERY_STATUS_CODE),
1970 FE(HTTP_QUERY_STATUS_TEXT),
1971 FE(HTTP_QUERY_RAW_HEADERS),
1972 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
1973 FE(HTTP_QUERY_CONNECTION),
1974 FE(HTTP_QUERY_ACCEPT),
1975 FE(HTTP_QUERY_ACCEPT_CHARSET),
1976 FE(HTTP_QUERY_ACCEPT_ENCODING),
1977 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
1978 FE(HTTP_QUERY_AUTHORIZATION),
1979 FE(HTTP_QUERY_CONTENT_ENCODING),
1980 FE(HTTP_QUERY_FORWARDED),
1981 FE(HTTP_QUERY_FROM),
1982 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
1983 FE(HTTP_QUERY_LOCATION),
1984 FE(HTTP_QUERY_ORIG_URI),
1985 FE(HTTP_QUERY_REFERER),
1986 FE(HTTP_QUERY_RETRY_AFTER),
1987 FE(HTTP_QUERY_SERVER),
1988 FE(HTTP_QUERY_TITLE),
1989 FE(HTTP_QUERY_USER_AGENT),
1990 FE(HTTP_QUERY_WWW_AUTHENTICATE),
1991 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
1992 FE(HTTP_QUERY_ACCEPT_RANGES),
1993 FE(HTTP_QUERY_SET_COOKIE),
1994 FE(HTTP_QUERY_COOKIE),
1995 FE(HTTP_QUERY_REQUEST_METHOD),
1996 FE(HTTP_QUERY_REFRESH),
1997 FE(HTTP_QUERY_CONTENT_DISPOSITION),
1998 FE(HTTP_QUERY_AGE),
1999 FE(HTTP_QUERY_CACHE_CONTROL),
2000 FE(HTTP_QUERY_CONTENT_BASE),
2001 FE(HTTP_QUERY_CONTENT_LOCATION),
2002 FE(HTTP_QUERY_CONTENT_MD5),
2003 FE(HTTP_QUERY_CONTENT_RANGE),
2004 FE(HTTP_QUERY_ETAG),
2005 FE(HTTP_QUERY_HOST),
2006 FE(HTTP_QUERY_IF_MATCH),
2007 FE(HTTP_QUERY_IF_NONE_MATCH),
2008 FE(HTTP_QUERY_IF_RANGE),
2009 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2010 FE(HTTP_QUERY_MAX_FORWARDS),
2011 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2012 FE(HTTP_QUERY_RANGE),
2013 FE(HTTP_QUERY_TRANSFER_ENCODING),
2014 FE(HTTP_QUERY_UPGRADE),
2015 FE(HTTP_QUERY_VARY),
2016 FE(HTTP_QUERY_VIA),
2017 FE(HTTP_QUERY_WARNING),
2018 FE(HTTP_QUERY_CUSTOM)
2020 static const wininet_flag_info modifier_flags[] = {
2021 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2022 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2023 FE(HTTP_QUERY_FLAG_NUMBER),
2024 FE(HTTP_QUERY_FLAG_COALESCE)
2026 #undef FE
2027 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2028 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2029 DWORD i;
2031 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2032 TRACE(" Attribute:");
2033 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2034 if (query_flags[i].val == info) {
2035 TRACE(" %s", query_flags[i].name);
2036 break;
2039 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2040 TRACE(" Unknown (%08x)", info);
2043 TRACE(" Modifier:");
2044 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2045 if (modifier_flags[i].val & info_mod) {
2046 TRACE(" %s", modifier_flags[i].name);
2047 info_mod &= ~ modifier_flags[i].val;
2051 if (info_mod) {
2052 TRACE(" Unknown (%08x)", info_mod);
2054 TRACE("\n");
2057 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2058 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2060 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2061 goto lend;
2064 if (lpBuffer == NULL)
2065 *lpdwBufferLength = 0;
2066 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2067 lpBuffer, lpdwBufferLength, lpdwIndex);
2069 lend:
2070 if( lpwhr )
2071 WININET_Release( &lpwhr->hdr );
2073 TRACE("%d <--\n", bSuccess);
2074 return bSuccess;
2077 /***********************************************************************
2078 * HttpQueryInfoA (WININET.@)
2080 * Queries for information about an HTTP request
2082 * RETURNS
2083 * TRUE on success
2084 * FALSE on failure
2087 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2088 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2090 BOOL result;
2091 DWORD len;
2092 WCHAR* bufferW;
2094 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2095 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2097 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2098 lpdwBufferLength, lpdwIndex );
2101 if (lpBuffer)
2103 DWORD alloclen;
2104 len = (*lpdwBufferLength)*sizeof(WCHAR);
2105 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2107 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2108 if (alloclen < len)
2109 alloclen = len;
2111 else
2112 alloclen = len;
2113 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2114 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2115 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2116 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2117 } else
2119 bufferW = NULL;
2120 len = 0;
2123 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2124 &len, lpdwIndex );
2125 if( result )
2127 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2128 lpBuffer, *lpdwBufferLength, NULL, NULL );
2129 *lpdwBufferLength = len - 1;
2131 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2133 else
2134 /* since the strings being returned from HttpQueryInfoW should be
2135 * only ASCII characters, it is reasonable to assume that all of
2136 * the Unicode characters can be reduced to a single byte */
2137 *lpdwBufferLength = len / sizeof(WCHAR);
2139 HeapFree(GetProcessHeap(), 0, bufferW );
2141 return result;
2144 /***********************************************************************
2145 * HttpSendRequestExA (WININET.@)
2147 * Sends the specified request to the HTTP server and allows chunked
2148 * transfers.
2150 * RETURNS
2151 * Success: TRUE
2152 * Failure: FALSE, call GetLastError() for more information.
2154 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2155 LPINTERNET_BUFFERSA lpBuffersIn,
2156 LPINTERNET_BUFFERSA lpBuffersOut,
2157 DWORD dwFlags, DWORD_PTR dwContext)
2159 INTERNET_BUFFERSW BuffersInW;
2160 BOOL rc = FALSE;
2161 DWORD headerlen;
2162 LPWSTR header = NULL;
2164 TRACE("(%p, %p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersIn,
2165 lpBuffersOut, dwFlags, dwContext);
2167 if (lpBuffersIn)
2169 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2170 if (lpBuffersIn->lpcszHeader)
2172 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2173 lpBuffersIn->dwHeadersLength,0,0);
2174 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2175 if (!(BuffersInW.lpcszHeader = header))
2177 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2178 return FALSE;
2180 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2181 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2182 header, headerlen);
2184 else
2185 BuffersInW.lpcszHeader = NULL;
2186 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2187 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2188 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2189 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2190 BuffersInW.Next = NULL;
2193 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2195 HeapFree(GetProcessHeap(),0,header);
2197 return rc;
2200 /***********************************************************************
2201 * HttpSendRequestExW (WININET.@)
2203 * Sends the specified request to the HTTP server and allows chunked
2204 * transfers
2206 * RETURNS
2207 * Success: TRUE
2208 * Failure: FALSE, call GetLastError() for more information.
2210 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2211 LPINTERNET_BUFFERSW lpBuffersIn,
2212 LPINTERNET_BUFFERSW lpBuffersOut,
2213 DWORD dwFlags, DWORD_PTR dwContext)
2215 BOOL ret = FALSE;
2216 LPWININETHTTPREQW lpwhr;
2217 LPWININETHTTPSESSIONW lpwhs;
2218 LPWININETAPPINFOW hIC;
2220 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2221 lpBuffersOut, dwFlags, dwContext);
2223 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2225 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2227 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2228 goto lend;
2231 lpwhs = lpwhr->lpHttpSession;
2232 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2233 hIC = lpwhs->lpAppInfo;
2234 assert(hIC->hdr.htype == WH_HINIT);
2236 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2238 WORKREQUEST workRequest;
2239 struct WORKREQ_HTTPSENDREQUESTW *req;
2241 workRequest.asyncproc = AsyncHttpSendRequestProc;
2242 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2243 req = &workRequest.u.HttpSendRequestW;
2244 if (lpBuffersIn)
2246 if (lpBuffersIn->lpcszHeader)
2247 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2248 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2249 else
2250 req->lpszHeader = NULL;
2251 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2252 req->lpOptional = lpBuffersIn->lpvBuffer;
2253 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2254 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2256 else
2258 req->lpszHeader = NULL;
2259 req->dwHeaderLength = 0;
2260 req->lpOptional = NULL;
2261 req->dwOptionalLength = 0;
2262 req->dwContentLength = 0;
2265 req->bEndRequest = FALSE;
2267 INTERNET_AsyncCall(&workRequest);
2269 * This is from windows.
2271 INTERNET_SetLastError(ERROR_IO_PENDING);
2273 else
2275 if (lpBuffersIn)
2276 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2277 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2278 lpBuffersIn->dwBufferTotal, FALSE);
2279 else
2280 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2283 lend:
2284 if ( lpwhr )
2285 WININET_Release( &lpwhr->hdr );
2287 TRACE("<---\n");
2288 return ret;
2291 /***********************************************************************
2292 * HttpSendRequestW (WININET.@)
2294 * Sends the specified request to the HTTP server
2296 * RETURNS
2297 * TRUE on success
2298 * FALSE on failure
2301 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2302 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2304 LPWININETHTTPREQW lpwhr;
2305 LPWININETHTTPSESSIONW lpwhs = NULL;
2306 LPWININETAPPINFOW hIC = NULL;
2307 BOOL r;
2309 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2310 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2312 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2313 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2315 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2316 r = FALSE;
2317 goto lend;
2320 lpwhs = lpwhr->lpHttpSession;
2321 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2323 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2324 r = FALSE;
2325 goto lend;
2328 hIC = lpwhs->lpAppInfo;
2329 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2331 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2332 r = FALSE;
2333 goto lend;
2336 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2338 WORKREQUEST workRequest;
2339 struct WORKREQ_HTTPSENDREQUESTW *req;
2341 workRequest.asyncproc = AsyncHttpSendRequestProc;
2342 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2343 req = &workRequest.u.HttpSendRequestW;
2344 if (lpszHeaders)
2346 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2347 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2349 else
2350 req->lpszHeader = 0;
2351 req->dwHeaderLength = dwHeaderLength;
2352 req->lpOptional = lpOptional;
2353 req->dwOptionalLength = dwOptionalLength;
2354 req->dwContentLength = dwOptionalLength;
2355 req->bEndRequest = TRUE;
2357 INTERNET_AsyncCall(&workRequest);
2359 * This is from windows.
2361 INTERNET_SetLastError(ERROR_IO_PENDING);
2362 r = FALSE;
2364 else
2366 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2367 dwHeaderLength, lpOptional, dwOptionalLength,
2368 dwOptionalLength, TRUE);
2370 lend:
2371 if( lpwhr )
2372 WININET_Release( &lpwhr->hdr );
2373 return r;
2376 /***********************************************************************
2377 * HttpSendRequestA (WININET.@)
2379 * Sends the specified request to the HTTP server
2381 * RETURNS
2382 * TRUE on success
2383 * FALSE on failure
2386 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2387 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2389 BOOL result;
2390 LPWSTR szHeaders=NULL;
2391 DWORD nLen=dwHeaderLength;
2392 if(lpszHeaders!=NULL)
2394 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2395 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2396 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2398 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2399 HeapFree(GetProcessHeap(),0,szHeaders);
2400 return result;
2403 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2405 LPHTTPHEADERW host_header;
2407 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2409 host_header = HTTP_GetHeader(req, szHost);
2410 if(!host_header)
2411 return FALSE;
2413 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2414 return TRUE;
2417 /***********************************************************************
2418 * HTTP_HandleRedirect (internal)
2420 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2422 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2423 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2424 WCHAR path[2048];
2426 if(lpszUrl[0]=='/')
2428 /* if it's an absolute path, keep the same session info */
2429 lstrcpynW(path, lpszUrl, 2048);
2431 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2433 TRACE("Redirect through proxy\n");
2434 lstrcpynW(path, lpszUrl, 2048);
2436 else
2438 URL_COMPONENTSW urlComponents;
2439 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2440 static WCHAR szHttp[] = {'h','t','t','p',0};
2441 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2442 DWORD url_length = 0;
2443 LPWSTR orig_url;
2444 LPWSTR combined_url;
2446 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2447 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2448 urlComponents.dwSchemeLength = 0;
2449 urlComponents.lpszHostName = lpwhs->lpszHostName;
2450 urlComponents.dwHostNameLength = 0;
2451 urlComponents.nPort = lpwhs->nHostPort;
2452 urlComponents.lpszUserName = lpwhs->lpszUserName;
2453 urlComponents.dwUserNameLength = 0;
2454 urlComponents.lpszPassword = NULL;
2455 urlComponents.dwPasswordLength = 0;
2456 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2457 urlComponents.dwUrlPathLength = 0;
2458 urlComponents.lpszExtraInfo = NULL;
2459 urlComponents.dwExtraInfoLength = 0;
2461 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2462 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2463 return FALSE;
2465 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2467 /* convert from bytes to characters */
2468 url_length = url_length / sizeof(WCHAR) - 1;
2469 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2471 HeapFree(GetProcessHeap(), 0, orig_url);
2472 return FALSE;
2475 url_length = 0;
2476 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2477 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2479 HeapFree(GetProcessHeap(), 0, orig_url);
2480 return FALSE;
2482 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2484 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2486 HeapFree(GetProcessHeap(), 0, orig_url);
2487 HeapFree(GetProcessHeap(), 0, combined_url);
2488 return FALSE;
2490 HeapFree(GetProcessHeap(), 0, orig_url);
2492 userName[0] = 0;
2493 hostName[0] = 0;
2494 protocol[0] = 0;
2496 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2497 urlComponents.lpszScheme = protocol;
2498 urlComponents.dwSchemeLength = 32;
2499 urlComponents.lpszHostName = hostName;
2500 urlComponents.dwHostNameLength = MAXHOSTNAME;
2501 urlComponents.lpszUserName = userName;
2502 urlComponents.dwUserNameLength = 1024;
2503 urlComponents.lpszPassword = NULL;
2504 urlComponents.dwPasswordLength = 0;
2505 urlComponents.lpszUrlPath = path;
2506 urlComponents.dwUrlPathLength = 2048;
2507 urlComponents.lpszExtraInfo = NULL;
2508 urlComponents.dwExtraInfoLength = 0;
2509 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2511 HeapFree(GetProcessHeap(), 0, combined_url);
2512 return FALSE;
2515 HeapFree(GetProcessHeap(), 0, combined_url);
2517 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2518 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2520 TRACE("redirect from secure page to non-secure page\n");
2521 /* FIXME: warn about from secure redirect to non-secure page */
2522 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2524 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2525 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2527 TRACE("redirect from non-secure page to secure page\n");
2528 /* FIXME: notify about redirect to secure page */
2529 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2532 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2534 if (lstrlenW(protocol)>4) /*https*/
2535 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2536 else /*http*/
2537 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2540 #if 0
2542 * This upsets redirects to binary files on sourceforge.net
2543 * and gives an html page instead of the target file
2544 * Examination of the HTTP request sent by native wininet.dll
2545 * reveals that it doesn't send a referrer in that case.
2546 * Maybe there's a flag that enables this, or maybe a referrer
2547 * shouldn't be added in case of a redirect.
2550 /* consider the current host as the referrer */
2551 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2552 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2553 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2554 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2555 #endif
2557 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2558 lpwhs->lpszServerName = WININET_strdupW(hostName);
2559 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2560 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2561 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2563 int len;
2564 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2565 len = lstrlenW(hostName);
2566 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2567 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2568 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2570 else
2571 lpwhs->lpszHostName = WININET_strdupW(hostName);
2573 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2576 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2577 lpwhs->lpszUserName = NULL;
2578 if (userName[0])
2579 lpwhs->lpszUserName = WININET_strdupW(userName);
2580 lpwhs->nServerPort = urlComponents.nPort;
2582 if (!HTTP_ResolveName(lpwhr))
2583 return FALSE;
2585 NETCON_close(&lpwhr->netConnection);
2587 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2588 return FALSE;
2591 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2592 lpwhr->lpszPath=NULL;
2593 if (*path)
2595 DWORD needed = 0;
2596 HRESULT rc;
2598 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2599 if (rc != E_POINTER)
2600 needed = strlenW(path)+1;
2601 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2602 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2603 URL_ESCAPE_SPACES_ONLY);
2604 if (rc)
2606 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2607 strcpyW(lpwhr->lpszPath,path);
2611 return TRUE;
2614 /***********************************************************************
2615 * HTTP_build_req (internal)
2617 * concatenate all the strings in the request together
2619 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2621 LPCWSTR *t;
2622 LPWSTR str;
2624 for( t = list; *t ; t++ )
2625 len += strlenW( *t );
2626 len++;
2628 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2629 *str = 0;
2631 for( t = list; *t ; t++ )
2632 strcatW( str, *t );
2634 return str;
2637 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2639 LPWSTR lpszPath;
2640 LPWSTR requestString;
2641 INT len;
2642 INT cnt;
2643 INT responseLen;
2644 char *ascii_req;
2645 BOOL ret;
2646 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2647 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2648 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2650 TRACE("\n");
2652 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2653 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2654 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
2655 HeapFree( GetProcessHeap(), 0, lpszPath );
2657 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2658 NULL, 0, NULL, NULL );
2659 len--; /* the nul terminator isn't needed */
2660 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2661 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2662 ascii_req, len, NULL, NULL );
2663 HeapFree( GetProcessHeap(), 0, requestString );
2665 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2667 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2668 HeapFree( GetProcessHeap(), 0, ascii_req );
2669 if (!ret || cnt < 0)
2670 return FALSE;
2672 responseLen = HTTP_GetResponseHeaders( lpwhr );
2673 if (!responseLen)
2674 return FALSE;
2676 return TRUE;
2679 /***********************************************************************
2680 * HTTP_HttpSendRequestW (internal)
2682 * Sends the specified request to the HTTP server
2684 * RETURNS
2685 * TRUE on success
2686 * FALSE on failure
2689 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2690 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2691 DWORD dwContentLength, BOOL bEndRequest)
2693 INT cnt;
2694 BOOL bSuccess = FALSE;
2695 LPWSTR requestString = NULL;
2696 INT responseLen;
2697 BOOL loop_next;
2698 INTERNET_ASYNC_RESULT iar;
2699 static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
2700 static const WCHAR szPost[] = { 'P','O','S','T',0 };
2701 static const WCHAR szContentLength[] =
2702 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
2703 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
2705 TRACE("--> %p\n", lpwhr);
2707 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2709 /* Clear any error information */
2710 INTERNET_SetLastError(0);
2712 /* if the verb is NULL default to GET */
2713 if (!lpwhr->lpszVerb)
2714 lpwhr->lpszVerb = WININET_strdupW(szGET);
2716 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
2718 sprintfW(contentLengthStr, szContentLength, dwContentLength);
2719 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2724 DWORD len;
2725 char *ascii_req;
2727 loop_next = FALSE;
2729 /* like native, just in case the caller forgot to call InternetReadFile
2730 * for all the data */
2731 HTTP_DrainContent(lpwhr);
2732 lpwhr->dwContentRead = 0;
2734 if (TRACE_ON(wininet))
2736 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
2737 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2740 HTTP_FixURL(lpwhr);
2741 HTTP_ProcessHeader(lpwhr, szConnection,
2742 lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
2743 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
2745 HTTP_InsertAuthorization(lpwhr, szAuthorization, !loop_next);
2746 HTTP_InsertAuthorization(lpwhr, szProxy_Authorization, !loop_next);
2748 /* add the headers the caller supplied */
2749 if( lpszHeaders && dwHeaderLength )
2751 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2752 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2755 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2757 TRACE("Request header -> %s\n", debugstr_w(requestString) );
2759 /* Send the request and store the results */
2760 if (!HTTP_OpenConnection(lpwhr))
2761 goto lend;
2763 /* send the request as ASCII, tack on the optional data */
2764 if( !lpOptional )
2765 dwOptionalLength = 0;
2766 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2767 NULL, 0, NULL, NULL );
2768 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2769 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2770 ascii_req, len, NULL, NULL );
2771 if( lpOptional )
2772 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2773 len = (len + dwOptionalLength - 1);
2774 ascii_req[len] = 0;
2775 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2777 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2778 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2780 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2781 HeapFree( GetProcessHeap(), 0, ascii_req );
2783 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2784 INTERNET_STATUS_REQUEST_SENT,
2785 &len, sizeof(DWORD));
2787 if (bEndRequest)
2789 DWORD dwBufferSize;
2790 DWORD dwStatusCode;
2792 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2793 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2795 if (cnt < 0)
2796 goto lend;
2798 responseLen = HTTP_GetResponseHeaders(lpwhr);
2799 if (responseLen)
2800 bSuccess = TRUE;
2802 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2803 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2804 sizeof(DWORD));
2806 HTTP_ProcessCookies(lpwhr);
2808 dwBufferSize = sizeof(lpwhr->dwContentLength);
2809 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2810 &lpwhr->dwContentLength,&dwBufferSize,NULL))
2811 lpwhr->dwContentLength = -1;
2813 if (lpwhr->dwContentLength == 0)
2814 HTTP_FinishedReading(lpwhr);
2816 dwBufferSize = sizeof(dwStatusCode);
2817 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
2818 &dwStatusCode,&dwBufferSize,NULL))
2819 dwStatusCode = 0;
2821 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
2823 WCHAR szNewLocation[2048];
2824 dwBufferSize=sizeof(szNewLocation);
2825 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
2826 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
2828 HTTP_DrainContent(lpwhr);
2829 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2830 INTERNET_STATUS_REDIRECT, szNewLocation,
2831 dwBufferSize);
2832 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
2833 if (bSuccess)
2835 HeapFree(GetProcessHeap(), 0, requestString);
2836 loop_next = TRUE;
2840 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
2842 WCHAR szAuthValue[2048];
2843 dwBufferSize=2048;
2844 if (dwStatusCode == HTTP_STATUS_DENIED)
2846 DWORD dwIndex = 0;
2847 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2849 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2850 &lpwhr->pAuthInfo,
2851 lpwhr->lpHttpSession->lpszUserName,
2852 lpwhr->lpHttpSession->lpszPassword))
2854 loop_next = TRUE;
2855 break;
2859 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
2861 DWORD dwIndex = 0;
2862 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2864 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2865 &lpwhr->pProxyAuthInfo,
2866 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
2867 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
2869 loop_next = TRUE;
2870 break;
2876 else
2877 bSuccess = TRUE;
2879 while (loop_next);
2881 /* FIXME: Better check, when we have to create the cache file */
2882 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
2883 WCHAR url[INTERNET_MAX_URL_LENGTH];
2884 WCHAR cacheFileName[MAX_PATH+1];
2885 BOOL b;
2887 b = HTTP_GetRequestURL(lpwhr, url);
2888 if(!b) {
2889 WARN("Could not get URL\n");
2890 goto lend;
2893 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
2894 if(b) {
2895 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
2896 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2897 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2898 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
2899 WARN("Could not create file: %u\n", GetLastError());
2900 lpwhr->hCacheFile = NULL;
2902 }else {
2903 WARN("Could not create cache entry: %08x\n", GetLastError());
2907 lend:
2909 HeapFree(GetProcessHeap(), 0, requestString);
2911 /* TODO: send notification for P3P header */
2913 iar.dwResult = (DWORD)bSuccess;
2914 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2916 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2917 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2918 sizeof(INTERNET_ASYNC_RESULT));
2920 TRACE("<--\n");
2921 return bSuccess;
2924 /***********************************************************************
2925 * HTTPSESSION_Destroy (internal)
2927 * Deallocate session handle
2930 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
2932 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
2934 TRACE("%p\n", lpwhs);
2936 WININET_Release(&lpwhs->lpAppInfo->hdr);
2938 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2939 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2940 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
2941 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2942 HeapFree(GetProcessHeap(), 0, lpwhs);
2946 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
2947 HTTPSESSION_Destroy,
2948 NULL,
2949 NULL,
2950 NULL,
2951 NULL
2955 /***********************************************************************
2956 * HTTP_Connect (internal)
2958 * Create http session handle
2960 * RETURNS
2961 * HINTERNET a session handle on success
2962 * NULL on failure
2965 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
2966 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2967 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
2968 DWORD dwInternalFlags)
2970 BOOL bSuccess = FALSE;
2971 LPWININETHTTPSESSIONW lpwhs = NULL;
2972 HINTERNET handle = NULL;
2974 TRACE("-->\n");
2976 if (!lpszServerName || !lpszServerName[0])
2978 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2979 goto lerror;
2982 assert( hIC->hdr.htype == WH_HINIT );
2984 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
2985 if (NULL == lpwhs)
2987 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2988 goto lerror;
2992 * According to my tests. The name is not resolved until a request is sent
2995 lpwhs->hdr.htype = WH_HHTTPSESSION;
2996 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
2997 lpwhs->hdr.dwFlags = dwFlags;
2998 lpwhs->hdr.dwContext = dwContext;
2999 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3000 lpwhs->hdr.dwRefCount = 1;
3001 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3003 WININET_AddRef( &hIC->hdr );
3004 lpwhs->lpAppInfo = hIC;
3005 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3007 handle = WININET_AllocHandle( &lpwhs->hdr );
3008 if (NULL == handle)
3010 ERR("Failed to alloc handle\n");
3011 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3012 goto lerror;
3015 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3016 if(strchrW(hIC->lpszProxy, ' '))
3017 FIXME("Several proxies not implemented.\n");
3018 if(hIC->lpszProxyBypass)
3019 FIXME("Proxy bypass is ignored.\n");
3021 if (lpszServerName && lpszServerName[0])
3023 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3024 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3026 if (lpszUserName && lpszUserName[0])
3027 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3028 if (lpszPassword && lpszPassword[0])
3029 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3030 lpwhs->nServerPort = nServerPort;
3031 lpwhs->nHostPort = nServerPort;
3033 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3034 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3036 INTERNET_SendCallback(&hIC->hdr, dwContext,
3037 INTERNET_STATUS_HANDLE_CREATED, &handle,
3038 sizeof(handle));
3041 bSuccess = TRUE;
3043 lerror:
3044 if( lpwhs )
3045 WININET_Release( &lpwhs->hdr );
3048 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3049 * windows
3052 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3053 return handle;
3057 /***********************************************************************
3058 * HTTP_OpenConnection (internal)
3060 * Connect to a web server
3062 * RETURNS
3064 * TRUE on success
3065 * FALSE on failure
3067 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3069 BOOL bSuccess = FALSE;
3070 LPWININETHTTPSESSIONW lpwhs;
3071 LPWININETAPPINFOW hIC = NULL;
3072 char szaddr[32];
3074 TRACE("-->\n");
3077 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3079 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3080 goto lend;
3083 if (NETCON_connected(&lpwhr->netConnection))
3085 bSuccess = TRUE;
3086 goto lend;
3089 lpwhs = lpwhr->lpHttpSession;
3091 hIC = lpwhs->lpAppInfo;
3092 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3093 szaddr, sizeof(szaddr));
3094 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3095 INTERNET_STATUS_CONNECTING_TO_SERVER,
3096 szaddr,
3097 strlen(szaddr)+1);
3099 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3100 SOCK_STREAM, 0))
3102 WARN("Socket creation failed\n");
3103 goto lend;
3106 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3107 sizeof(lpwhs->socketAddress)))
3108 goto lend;
3110 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3112 /* Note: we differ from Microsoft's WinINet here. they seem to have
3113 * a bug that causes no status callbacks to be sent when starting
3114 * a tunnel to a proxy server using the CONNECT verb. i believe our
3115 * behaviour to be more correct and to not cause any incompatibilities
3116 * because using a secure connection through a proxy server is a rare
3117 * case that would be hard for anyone to depend on */
3118 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3119 goto lend;
3121 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3123 WARN("Couldn't connect securely to host\n");
3124 goto lend;
3128 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3129 INTERNET_STATUS_CONNECTED_TO_SERVER,
3130 szaddr, strlen(szaddr)+1);
3132 bSuccess = TRUE;
3134 lend:
3135 TRACE("%d <--\n", bSuccess);
3136 return bSuccess;
3140 /***********************************************************************
3141 * HTTP_clear_response_headers (internal)
3143 * clear out any old response headers
3145 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3147 DWORD i;
3149 for( i=0; i<lpwhr->nCustHeaders; i++)
3151 if( !lpwhr->pCustHeaders[i].lpszField )
3152 continue;
3153 if( !lpwhr->pCustHeaders[i].lpszValue )
3154 continue;
3155 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3156 continue;
3157 HTTP_DeleteCustomHeader( lpwhr, i );
3158 i--;
3162 /***********************************************************************
3163 * HTTP_GetResponseHeaders (internal)
3165 * Read server response
3167 * RETURNS
3169 * TRUE on success
3170 * FALSE on error
3172 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
3174 INT cbreaks = 0;
3175 WCHAR buffer[MAX_REPLY_LEN];
3176 DWORD buflen = MAX_REPLY_LEN;
3177 BOOL bSuccess = FALSE;
3178 INT rc = 0;
3179 static const WCHAR szCrLf[] = {'\r','\n',0};
3180 static const WCHAR szHundred[] = {'1','0','0',0};
3181 char bufferA[MAX_REPLY_LEN];
3182 LPWSTR status_code, status_text;
3183 DWORD cchMaxRawHeaders = 1024;
3184 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3185 DWORD cchRawHeaders = 0;
3187 TRACE("-->\n");
3189 /* clear old response headers (eg. from a redirect response) */
3190 HTTP_clear_response_headers( lpwhr );
3192 if (!NETCON_connected(&lpwhr->netConnection))
3193 goto lend;
3195 do {
3197 * HACK peek at the buffer
3199 buflen = MAX_REPLY_LEN;
3200 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3203 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3205 memset(buffer, 0, MAX_REPLY_LEN);
3206 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3207 goto lend;
3208 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3210 /* split the version from the status code */
3211 status_code = strchrW( buffer, ' ' );
3212 if( !status_code )
3213 goto lend;
3214 *status_code++=0;
3216 /* split the status code from the status text */
3217 status_text = strchrW( status_code, ' ' );
3218 if( !status_text )
3219 goto lend;
3220 *status_text++=0;
3222 TRACE("version [%s] status code [%s] status text [%s]\n",
3223 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3225 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3227 /* Add status code */
3228 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3229 HTTP_ADDHDR_FLAG_REPLACE);
3231 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3232 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3234 lpwhr->lpszVersion= WININET_strdupW(buffer);
3235 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3237 /* Restore the spaces */
3238 *(status_code-1) = ' ';
3239 *(status_text-1) = ' ';
3241 /* regenerate raw headers */
3242 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3244 cchMaxRawHeaders *= 2;
3245 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3247 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3248 cchRawHeaders += (buflen-1);
3249 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3250 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3251 lpszRawHeaders[cchRawHeaders] = '\0';
3253 /* Parse each response line */
3256 buflen = MAX_REPLY_LEN;
3257 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3259 LPWSTR * pFieldAndValue;
3261 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3262 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3264 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3266 cchMaxRawHeaders *= 2;
3267 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3269 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3270 cchRawHeaders += (buflen-1);
3271 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3272 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3273 lpszRawHeaders[cchRawHeaders] = '\0';
3275 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3276 if (!pFieldAndValue)
3277 break;
3279 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3280 HTTP_ADDREQ_FLAG_ADD );
3282 HTTP_FreeTokens(pFieldAndValue);
3284 else
3286 cbreaks++;
3287 if (cbreaks >= 2)
3288 break;
3290 }while(1);
3292 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3293 lpwhr->lpszRawHeaders = lpszRawHeaders;
3294 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3295 bSuccess = TRUE;
3297 lend:
3299 TRACE("<--\n");
3300 if (bSuccess)
3301 return rc;
3302 else
3303 return 0;
3307 static void strip_spaces(LPWSTR start)
3309 LPWSTR str = start;
3310 LPWSTR end;
3312 while (*str == ' ' && *str != '\0')
3313 str++;
3315 if (str != start)
3316 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3318 end = start + strlenW(start) - 1;
3319 while (end >= start && *end == ' ')
3321 *end = '\0';
3322 end--;
3327 /***********************************************************************
3328 * HTTP_InterpretHttpHeader (internal)
3330 * Parse server response
3332 * RETURNS
3334 * Pointer to array of field, value, NULL on success.
3335 * NULL on error.
3337 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3339 LPWSTR * pTokenPair;
3340 LPWSTR pszColon;
3341 INT len;
3343 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3345 pszColon = strchrW(buffer, ':');
3346 /* must have two tokens */
3347 if (!pszColon)
3349 HTTP_FreeTokens(pTokenPair);
3350 if (buffer[0])
3351 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3352 return NULL;
3355 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3356 if (!pTokenPair[0])
3358 HTTP_FreeTokens(pTokenPair);
3359 return NULL;
3361 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3362 pTokenPair[0][pszColon - buffer] = '\0';
3364 /* skip colon */
3365 pszColon++;
3366 len = strlenW(pszColon);
3367 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3368 if (!pTokenPair[1])
3370 HTTP_FreeTokens(pTokenPair);
3371 return NULL;
3373 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3375 strip_spaces(pTokenPair[0]);
3376 strip_spaces(pTokenPair[1]);
3378 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3379 return pTokenPair;
3382 /***********************************************************************
3383 * HTTP_ProcessHeader (internal)
3385 * Stuff header into header tables according to <dwModifier>
3389 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3391 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3393 LPHTTPHEADERW lphttpHdr = NULL;
3394 BOOL bSuccess = FALSE;
3395 INT index = -1;
3396 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3398 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3400 /* REPLACE wins out over ADD */
3401 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3402 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3404 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3405 index = -1;
3406 else
3407 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3409 if (index >= 0)
3411 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3413 return FALSE;
3415 lphttpHdr = &lpwhr->pCustHeaders[index];
3417 else if (value)
3419 HTTPHEADERW hdr;
3421 hdr.lpszField = (LPWSTR)field;
3422 hdr.lpszValue = (LPWSTR)value;
3423 hdr.wFlags = hdr.wCount = 0;
3425 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3426 hdr.wFlags |= HDR_ISREQUEST;
3428 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3430 /* no value to delete */
3431 else return TRUE;
3433 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3434 lphttpHdr->wFlags |= HDR_ISREQUEST;
3435 else
3436 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3438 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3440 HTTP_DeleteCustomHeader( lpwhr, index );
3442 if (value)
3444 HTTPHEADERW hdr;
3446 hdr.lpszField = (LPWSTR)field;
3447 hdr.lpszValue = (LPWSTR)value;
3448 hdr.wFlags = hdr.wCount = 0;
3450 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3451 hdr.wFlags |= HDR_ISREQUEST;
3453 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3456 return TRUE;
3458 else if (dwModifier & COALESCEFLAGS)
3460 LPWSTR lpsztmp;
3461 WCHAR ch = 0;
3462 INT len = 0;
3463 INT origlen = strlenW(lphttpHdr->lpszValue);
3464 INT valuelen = strlenW(value);
3466 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3468 ch = ',';
3469 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3471 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3473 ch = ';';
3474 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3477 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3479 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3480 if (lpsztmp)
3482 lphttpHdr->lpszValue = lpsztmp;
3483 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3484 if (ch > 0)
3486 lphttpHdr->lpszValue[origlen] = ch;
3487 origlen++;
3488 lphttpHdr->lpszValue[origlen] = ' ';
3489 origlen++;
3492 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3493 lphttpHdr->lpszValue[len] = '\0';
3494 bSuccess = TRUE;
3496 else
3498 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3499 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3502 TRACE("<-- %d\n",bSuccess);
3503 return bSuccess;
3507 /***********************************************************************
3508 * HTTP_FinishedReading (internal)
3510 * Called when all content from server has been read by client.
3513 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
3515 WCHAR szConnectionResponse[20];
3516 DWORD dwBufferSize = sizeof(szConnectionResponse);
3518 TRACE("\n");
3520 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse,
3521 &dwBufferSize, NULL) ||
3522 strcmpiW(szConnectionResponse, szKeepAlive))
3524 HTTPREQ_CloseConnection(&lpwhr->hdr);
3527 /* FIXME: store data in the URL cache here */
3529 return TRUE;
3533 /***********************************************************************
3534 * HTTP_GetCustomHeaderIndex (internal)
3536 * Return index of custom header from header array
3539 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
3540 int requested_index, BOOL request_only)
3542 DWORD index;
3544 TRACE("%s\n", debugstr_w(lpszField));
3546 for (index = 0; index < lpwhr->nCustHeaders; index++)
3548 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3549 continue;
3551 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3552 continue;
3554 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3555 continue;
3557 if (requested_index == 0)
3558 break;
3559 requested_index --;
3562 if (index >= lpwhr->nCustHeaders)
3563 index = -1;
3565 TRACE("Return: %d\n", index);
3566 return index;
3570 /***********************************************************************
3571 * HTTP_InsertCustomHeader (internal)
3573 * Insert header into array
3576 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3578 INT count;
3579 LPHTTPHEADERW lph = NULL;
3580 BOOL r = FALSE;
3582 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3583 count = lpwhr->nCustHeaders + 1;
3584 if (count > 1)
3585 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3586 else
3587 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3589 if (NULL != lph)
3591 lpwhr->pCustHeaders = lph;
3592 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3593 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3594 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3595 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3596 lpwhr->nCustHeaders++;
3597 r = TRUE;
3599 else
3601 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3604 return r;
3608 /***********************************************************************
3609 * HTTP_DeleteCustomHeader (internal)
3611 * Delete header from array
3612 * If this function is called, the indexs may change.
3614 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3616 if( lpwhr->nCustHeaders <= 0 )
3617 return FALSE;
3618 if( index >= lpwhr->nCustHeaders )
3619 return FALSE;
3620 lpwhr->nCustHeaders--;
3622 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3623 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3624 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3626 return TRUE;
3630 /***********************************************************************
3631 * HTTP_VerifyValidHeader (internal)
3633 * Verify the given header is not invalid for the given http request
3636 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
3638 BOOL rc = TRUE;
3640 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
3641 if (strcmpiW(field,szAccept_Encoding)==0)
3642 return FALSE;
3644 return rc;
3647 /***********************************************************************
3648 * IsHostInProxyBypassList (@)
3650 * Undocumented
3653 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3655 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
3656 return FALSE;