wininet: Move InternetReadFile to vtbl.
[wine/hacks.git] / dlls / wininet / http.c
blob40070fbe2af7471b4bfcb7dff583623660a55410
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, TRUE))
733 return;
734 } while (bytes_read);
737 /***********************************************************************
738 * HttpEndRequestA (WININET.@)
740 * Ends an HTTP request that was started by HttpSendRequestEx
742 * RETURNS
743 * TRUE if successful
744 * FALSE on failure
747 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
748 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
750 LPINTERNET_BUFFERSA ptr;
751 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
752 BOOL rc = FALSE;
754 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
755 dwContext);
757 ptr = lpBuffersOut;
758 if (ptr)
759 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
760 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
761 else
762 lpBuffersOutW = NULL;
764 ptrW = lpBuffersOutW;
765 while (ptr)
767 if (ptr->lpvBuffer && ptr->dwBufferLength)
768 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
769 ptrW->dwBufferLength = ptr->dwBufferLength;
770 ptrW->dwBufferTotal= ptr->dwBufferTotal;
772 if (ptr->Next)
773 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
774 sizeof(INTERNET_BUFFERSW));
776 ptr = ptr->Next;
777 ptrW = ptrW->Next;
780 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
782 if (lpBuffersOutW)
784 ptrW = lpBuffersOutW;
785 while (ptrW)
787 LPINTERNET_BUFFERSW ptrW2;
789 FIXME("Do we need to translate info out of these buffer?\n");
791 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
792 ptrW2 = ptrW->Next;
793 HeapFree(GetProcessHeap(),0,ptrW);
794 ptrW = ptrW2;
798 return rc;
801 /***********************************************************************
802 * HttpEndRequestW (WININET.@)
804 * Ends an HTTP request that was started by HttpSendRequestEx
806 * RETURNS
807 * TRUE if successful
808 * FALSE on failure
811 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
812 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
814 BOOL rc = FALSE;
815 LPWININETHTTPREQW lpwhr;
816 INT responseLen;
817 DWORD dwBufferSize;
819 TRACE("-->\n");
820 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
822 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
824 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
825 if (lpwhr)
826 WININET_Release( &lpwhr->hdr );
827 return FALSE;
830 lpwhr->hdr.dwFlags |= dwFlags;
831 lpwhr->hdr.dwContext = dwContext;
833 /* We appear to do nothing with lpBuffersOut.. is that correct? */
835 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
836 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
838 responseLen = HTTP_GetResponseHeaders(lpwhr);
839 if (responseLen)
840 rc = TRUE;
842 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
843 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
845 /* process cookies here. Is this right? */
846 HTTP_ProcessCookies(lpwhr);
848 dwBufferSize = sizeof(lpwhr->dwContentLength);
849 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
850 &lpwhr->dwContentLength,&dwBufferSize,NULL))
851 lpwhr->dwContentLength = -1;
853 if (lpwhr->dwContentLength == 0)
854 HTTP_FinishedReading(lpwhr);
856 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
858 DWORD dwCode,dwCodeLength=sizeof(DWORD);
859 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
860 (dwCode==302 || dwCode==301))
862 WCHAR szNewLocation[2048];
863 dwBufferSize=sizeof(szNewLocation);
864 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
866 /* redirects are always GETs */
867 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
868 lpwhr->lpszVerb = WININET_strdupW(szGET);
869 HTTP_DrainContent(lpwhr);
870 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
871 if (rc)
872 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
877 WININET_Release( &lpwhr->hdr );
878 TRACE("%i <--\n",rc);
879 return rc;
882 /***********************************************************************
883 * HttpOpenRequestW (WININET.@)
885 * Open a HTTP request handle
887 * RETURNS
888 * HINTERNET a HTTP request handle on success
889 * NULL on failure
892 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
893 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
894 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
895 DWORD dwFlags, DWORD_PTR dwContext)
897 LPWININETHTTPSESSIONW lpwhs;
898 HINTERNET handle = NULL;
900 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
901 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
902 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
903 dwFlags, dwContext);
904 if(lpszAcceptTypes!=NULL)
906 int i;
907 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
908 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
911 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
912 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
914 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
915 goto lend;
919 * My tests seem to show that the windows version does not
920 * become asynchronous until after this point. And anyhow
921 * if this call was asynchronous then how would you get the
922 * necessary HINTERNET pointer returned by this function.
925 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
926 lpszVersion, lpszReferrer, lpszAcceptTypes,
927 dwFlags, dwContext);
928 lend:
929 if( lpwhs )
930 WININET_Release( &lpwhs->hdr );
931 TRACE("returning %p\n", handle);
932 return handle;
936 /***********************************************************************
937 * HttpOpenRequestA (WININET.@)
939 * Open a HTTP request handle
941 * RETURNS
942 * HINTERNET a HTTP request handle on success
943 * NULL on failure
946 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
947 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
948 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
949 DWORD dwFlags, DWORD_PTR dwContext)
951 LPWSTR szVerb = NULL, szObjectName = NULL;
952 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
953 INT len;
954 INT acceptTypesCount;
955 HINTERNET rc = FALSE;
956 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
957 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
958 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
959 dwFlags, dwContext);
961 if (lpszVerb)
963 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
964 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
965 if ( !szVerb )
966 goto end;
967 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
970 if (lpszObjectName)
972 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
973 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
974 if ( !szObjectName )
975 goto end;
976 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
979 if (lpszVersion)
981 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
982 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
983 if ( !szVersion )
984 goto end;
985 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
988 if (lpszReferrer)
990 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
991 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
992 if ( !szReferrer )
993 goto end;
994 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
997 acceptTypesCount = 0;
998 if (lpszAcceptTypes)
1000 /* find out how many there are */
1001 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1002 acceptTypesCount++;
1003 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1004 acceptTypesCount = 0;
1005 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1007 len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1008 -1, NULL, 0 );
1009 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1010 if (!szAcceptTypes[acceptTypesCount] )
1011 goto end;
1012 MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1013 -1, szAcceptTypes[acceptTypesCount], len );
1014 acceptTypesCount++;
1016 szAcceptTypes[acceptTypesCount] = NULL;
1018 else szAcceptTypes = 0;
1020 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1021 szVersion, szReferrer,
1022 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1024 end:
1025 if (szAcceptTypes)
1027 acceptTypesCount = 0;
1028 while (szAcceptTypes[acceptTypesCount])
1030 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1031 acceptTypesCount++;
1033 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1035 HeapFree(GetProcessHeap(), 0, szReferrer);
1036 HeapFree(GetProcessHeap(), 0, szVersion);
1037 HeapFree(GetProcessHeap(), 0, szObjectName);
1038 HeapFree(GetProcessHeap(), 0, szVerb);
1040 return rc;
1043 /***********************************************************************
1044 * HTTP_EncodeBase64
1046 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1048 UINT n = 0, x;
1049 static const CHAR HTTP_Base64Enc[] =
1050 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1052 while( len > 0 )
1054 /* first 6 bits, all from bin[0] */
1055 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1056 x = (bin[0] & 3) << 4;
1058 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1059 if( len == 1 )
1061 base64[n++] = HTTP_Base64Enc[x];
1062 base64[n++] = '=';
1063 base64[n++] = '=';
1064 break;
1066 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1067 x = ( bin[1] & 0x0f ) << 2;
1069 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1070 if( len == 2 )
1072 base64[n++] = HTTP_Base64Enc[x];
1073 base64[n++] = '=';
1074 break;
1076 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1078 /* last 6 bits, all from bin [2] */
1079 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1080 bin += 3;
1081 len -= 3;
1083 base64[n] = 0;
1084 return n;
1087 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1088 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1089 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1090 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1091 static const signed char HTTP_Base64Dec[256] =
1093 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1094 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1095 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1096 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1097 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1098 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1099 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1100 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1101 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1102 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1103 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1104 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1105 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1106 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1107 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1108 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1109 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1110 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1111 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1112 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1113 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1114 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1115 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1116 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1117 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1118 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1120 #undef CH
1122 /***********************************************************************
1123 * HTTP_DecodeBase64
1125 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1127 unsigned int n = 0;
1129 while(*base64)
1131 signed char in[4];
1133 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1134 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1135 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1136 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1138 WARN("invalid base64: %s\n", debugstr_w(base64));
1139 return 0;
1141 if (bin)
1142 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1143 n++;
1145 if ((base64[2] == '=') && (base64[3] == '='))
1146 break;
1147 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1148 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1150 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1151 return 0;
1153 if (bin)
1154 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1155 n++;
1157 if (base64[3] == '=')
1158 break;
1159 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1160 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1162 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1163 return 0;
1165 if (bin)
1166 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1167 n++;
1169 base64 += 4;
1172 return n;
1175 /***********************************************************************
1176 * HTTP_InsertAuthorizationForHeader
1178 * Insert or delete the authorization field in the request header.
1180 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR header, BOOL first )
1182 WCHAR *authorization = NULL;
1183 struct HttpAuthInfo *pAuthInfo = lpwhr->pAuthInfo;
1184 DWORD flags;
1186 if (pAuthInfo && pAuthInfo->auth_data_len)
1188 static const WCHAR wszSpace[] = {' ',0};
1189 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1190 unsigned int len;
1192 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1193 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1194 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1195 if (!authorization)
1196 return FALSE;
1198 strcpyW(authorization, pAuthInfo->scheme);
1199 strcatW(authorization, wszSpace);
1200 HTTP_EncodeBase64(pAuthInfo->auth_data,
1201 pAuthInfo->auth_data_len,
1202 authorization+strlenW(authorization));
1204 /* clear the data as it isn't valid now that it has been sent to the
1205 * server, unless it's Basic authentication which doesn't do
1206 * connection tracking */
1207 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1209 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1210 pAuthInfo->auth_data = NULL;
1211 pAuthInfo->auth_data_len = 0;
1215 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1217 /* make sure not to overwrite any caller supplied authorization header */
1218 flags = HTTP_ADDHDR_FLAG_REQ;
1219 flags |= first ? HTTP_ADDHDR_FLAG_ADD_IF_NEW : HTTP_ADDHDR_FLAG_REPLACE;
1221 HTTP_ProcessHeader(lpwhr, header, authorization, flags);
1223 HeapFree(GetProcessHeap(), 0, authorization);
1224 return TRUE;
1227 /***********************************************************************
1228 * HTTP_DealWithProxy
1230 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1231 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1233 WCHAR buf[MAXHOSTNAME];
1234 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1235 WCHAR* url;
1236 static WCHAR szNul[] = { 0 };
1237 URL_COMPONENTSW UrlComponents;
1238 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
1239 static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
1240 static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1241 int len;
1243 memset( &UrlComponents, 0, sizeof UrlComponents );
1244 UrlComponents.dwStructSize = sizeof UrlComponents;
1245 UrlComponents.lpszHostName = buf;
1246 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1248 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1249 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1250 sprintfW(proxy, szFormat1, hIC->lpszProxy);
1251 else
1252 strcpyW(proxy, hIC->lpszProxy);
1253 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1254 return FALSE;
1255 if( UrlComponents.dwHostNameLength == 0 )
1256 return FALSE;
1258 if( !lpwhr->lpszPath )
1259 lpwhr->lpszPath = szNul;
1260 TRACE("server=%s path=%s\n",
1261 debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
1262 /* for constant 15 see above */
1263 len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
1264 url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1266 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1267 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1269 sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
1271 if( lpwhr->lpszPath[0] != '/' )
1272 strcatW( url, szSlash );
1273 strcatW(url, lpwhr->lpszPath);
1274 if(lpwhr->lpszPath != szNul)
1275 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1276 lpwhr->lpszPath = url;
1278 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1279 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1280 lpwhs->nServerPort = UrlComponents.nPort;
1282 return TRUE;
1285 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1287 char szaddr[32];
1288 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1290 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1291 INTERNET_STATUS_RESOLVING_NAME,
1292 lpwhs->lpszServerName,
1293 strlenW(lpwhs->lpszServerName)+1);
1295 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1296 &lpwhs->socketAddress))
1298 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1299 return FALSE;
1302 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1303 szaddr, sizeof(szaddr));
1304 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1305 INTERNET_STATUS_NAME_RESOLVED,
1306 szaddr, strlen(szaddr)+1);
1307 return TRUE;
1311 /***********************************************************************
1312 * HTTPREQ_Destroy (internal)
1314 * Deallocate request handle
1317 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1319 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1320 DWORD i;
1322 TRACE("\n");
1324 if(lpwhr->hCacheFile)
1325 CloseHandle(lpwhr->hCacheFile);
1327 if(lpwhr->lpszCacheFile) {
1328 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1329 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1332 WININET_Release(&lpwhr->lpHttpSession->hdr);
1334 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1335 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1336 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1337 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1338 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1340 for (i = 0; i < lpwhr->nCustHeaders; i++)
1342 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1343 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1346 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1347 HeapFree(GetProcessHeap(), 0, lpwhr);
1350 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1352 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1353 LPWININETHTTPSESSIONW lpwhs = NULL;
1354 LPWININETAPPINFOW hIC = NULL;
1356 TRACE("%p\n",lpwhr);
1358 if (!NETCON_connected(&lpwhr->netConnection))
1359 return;
1361 if (lpwhr->pAuthInfo)
1363 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1364 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1366 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1367 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1368 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1369 lpwhr->pAuthInfo = NULL;
1371 if (lpwhr->pProxyAuthInfo)
1373 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1374 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1376 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1377 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1378 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1379 lpwhr->pProxyAuthInfo = NULL;
1382 lpwhs = lpwhr->lpHttpSession;
1383 hIC = lpwhs->lpAppInfo;
1385 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1386 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1388 NETCON_close(&lpwhr->netConnection);
1390 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1391 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1394 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1396 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1398 switch(option) {
1399 case INTERNET_OPTION_SEND_TIMEOUT:
1400 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1401 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1403 if (size != sizeof(DWORD))
1404 return ERROR_INVALID_PARAMETER;
1406 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1407 *(DWORD*)buffer);
1410 return ERROR_INTERNET_INVALID_OPTION;
1413 DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1415 int bytes_read;
1417 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1418 sync ? MSG_WAITALL : 0, &bytes_read)) {
1419 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1420 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1422 /* always returns TRUE, even if the network layer returns an
1423 * error */
1424 *read = 0;
1425 HTTP_FinishedReading(req);
1426 return ERROR_SUCCESS;
1429 req->dwContentRead += bytes_read;
1430 *read = bytes_read;
1432 if(req->lpszCacheFile) {
1433 BOOL res;
1435 res = WriteFile(req->hCacheFile, buffer, bytes_read, NULL, NULL);
1436 if(!res)
1437 WARN("WriteFile failed: %u\n", GetLastError());
1440 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1441 HTTP_FinishedReading(req);
1443 return ERROR_SUCCESS;
1446 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1448 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1450 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1453 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1455 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1457 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1460 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1462 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1463 INTERNET_ASYNC_RESULT iar;
1464 char buffer[4048];
1466 TRACE("%p\n", workRequest->hdr);
1468 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1469 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1470 MSG_PEEK, (int *)&iar.dwError);
1472 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1473 sizeof(INTERNET_ASYNC_RESULT));
1476 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1478 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1479 BYTE buffer[4048];
1480 BOOL async;
1482 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1484 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1485 return ERROR_SUCCESS;
1487 /* Even if we are in async mode, we need to determine whether
1488 * there is actually more data available. We do this by trying
1489 * to peek only a single byte in async mode. */
1490 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1492 if (NETCON_recv(&req->netConnection, buffer,
1493 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1494 MSG_PEEK, (int *)available) && async && *available)
1496 WORKREQUEST workRequest;
1498 *available = 0;
1499 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1500 workRequest.hdr = WININET_AddRef( &req->hdr );
1502 INTERNET_AsyncCall(&workRequest);
1504 return ERROR_IO_PENDING;
1507 return ERROR_SUCCESS;
1510 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1511 HTTPREQ_Destroy,
1512 HTTPREQ_CloseConnection,
1513 HTTPREQ_SetOption,
1514 HTTPREQ_ReadFile,
1515 HTTPREQ_WriteFile,
1516 HTTPREQ_QueryDataAvailable,
1517 NULL
1520 /***********************************************************************
1521 * HTTP_HttpOpenRequestW (internal)
1523 * Open a HTTP request handle
1525 * RETURNS
1526 * HINTERNET a HTTP request handle on success
1527 * NULL on failure
1530 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1531 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1532 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1533 DWORD dwFlags, DWORD_PTR dwContext)
1535 LPWININETAPPINFOW hIC = NULL;
1536 LPWININETHTTPREQW lpwhr;
1537 LPWSTR lpszCookies;
1538 LPWSTR lpszUrl = NULL;
1539 DWORD nCookieSize;
1540 HINTERNET handle = NULL;
1541 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1542 DWORD len;
1543 LPHTTPHEADERW Host;
1545 TRACE("-->\n");
1547 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1548 hIC = lpwhs->lpAppInfo;
1550 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1551 if (NULL == lpwhr)
1553 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1554 goto lend;
1556 lpwhr->hdr.htype = WH_HHTTPREQ;
1557 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1558 lpwhr->hdr.dwFlags = dwFlags;
1559 lpwhr->hdr.dwContext = dwContext;
1560 lpwhr->hdr.dwRefCount = 1;
1561 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1562 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1564 WININET_AddRef( &lpwhs->hdr );
1565 lpwhr->lpHttpSession = lpwhs;
1566 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1568 handle = WININET_AllocHandle( &lpwhr->hdr );
1569 if (NULL == handle)
1571 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1572 goto lend;
1575 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1577 InternetCloseHandle( handle );
1578 handle = NULL;
1579 goto lend;
1582 if (lpszObjectName && *lpszObjectName) {
1583 HRESULT rc;
1585 len = 0;
1586 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1587 if (rc != E_POINTER)
1588 len = strlenW(lpszObjectName)+1;
1589 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1590 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1591 URL_ESCAPE_SPACES_ONLY);
1592 if (rc)
1594 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1595 strcpyW(lpwhr->lpszPath,lpszObjectName);
1599 if (lpszReferrer && *lpszReferrer)
1600 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1602 if (lpszAcceptTypes)
1604 int i;
1605 for (i = 0; lpszAcceptTypes[i]; i++)
1607 if (!*lpszAcceptTypes[i]) continue;
1608 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1609 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1610 HTTP_ADDHDR_FLAG_REQ |
1611 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1615 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1617 if (lpszVersion)
1618 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1619 else
1620 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1622 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1624 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1625 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1626 INTERNET_DEFAULT_HTTPS_PORT :
1627 INTERNET_DEFAULT_HTTP_PORT);
1628 lpwhs->nHostPort = lpwhs->nServerPort;
1630 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1631 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1633 if (hIC->lpszAgent)
1635 WCHAR *agent_header;
1636 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1638 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1639 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1640 sprintfW(agent_header, user_agent, hIC->lpszAgent );
1642 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1643 HTTP_ADDREQ_FLAG_ADD);
1644 HeapFree(GetProcessHeap(), 0, agent_header);
1647 Host = HTTP_GetHeader(lpwhr,szHost);
1649 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1650 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1651 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1653 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1654 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1656 int cnt = 0;
1657 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1658 static const WCHAR szcrlf[] = {'\r','\n',0};
1660 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1662 cnt += sprintfW(lpszCookies, szCookie);
1663 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1664 strcatW(lpszCookies, szcrlf);
1666 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1667 HTTP_ADDREQ_FLAG_ADD);
1668 HeapFree(GetProcessHeap(), 0, lpszCookies);
1670 HeapFree(GetProcessHeap(), 0, lpszUrl);
1673 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1674 INTERNET_STATUS_HANDLE_CREATED, &handle,
1675 sizeof(handle));
1678 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1681 if (!HTTP_ResolveName(lpwhr))
1683 InternetCloseHandle( handle );
1684 handle = NULL;
1687 lend:
1688 if( lpwhr )
1689 WININET_Release( &lpwhr->hdr );
1691 TRACE("<-- %p (%p)\n", handle, lpwhr);
1692 return handle;
1695 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1696 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1697 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1698 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1699 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1700 static const WCHAR szAge[] = { 'A','g','e',0 };
1701 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1702 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1703 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1704 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1705 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1706 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1707 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1708 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1709 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1710 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1711 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1712 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 };
1713 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1714 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1715 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1716 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1717 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1718 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1719 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1720 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1721 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1722 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1723 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1724 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1725 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1726 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1727 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1728 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1729 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1730 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1731 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1732 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1733 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1734 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1735 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1736 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1737 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1738 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1739 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 };
1740 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1741 static const WCHAR szURI[] = { 'U','R','I',0 };
1742 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1743 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1744 static const WCHAR szVia[] = { 'V','i','a',0 };
1745 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1746 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1748 static const LPCWSTR header_lookup[] = {
1749 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
1750 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
1751 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1752 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
1753 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1754 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
1755 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
1756 szAllow, /* HTTP_QUERY_ALLOW = 7 */
1757 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
1758 szDate, /* HTTP_QUERY_DATE = 9 */
1759 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
1760 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
1761 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
1762 szURI, /* HTTP_QUERY_URI = 13 */
1763 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
1764 NULL, /* HTTP_QUERY_COST = 15 */
1765 NULL, /* HTTP_QUERY_LINK = 16 */
1766 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
1767 NULL, /* HTTP_QUERY_VERSION = 18 */
1768 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
1769 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
1770 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
1771 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
1772 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
1773 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
1774 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
1775 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
1776 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
1777 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
1778 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
1779 NULL, /* HTTP_QUERY_FORWARDED = 30 */
1780 NULL, /* HTTP_QUERY_FROM = 31 */
1781 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
1782 szLocation, /* HTTP_QUERY_LOCATION = 33 */
1783 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
1784 szReferer, /* HTTP_QUERY_REFERER = 35 */
1785 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
1786 szServer, /* HTTP_QUERY_SERVER = 37 */
1787 NULL, /* HTTP_TITLE = 38 */
1788 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
1789 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
1790 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
1791 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
1792 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
1793 szCookie, /* HTTP_QUERY_COOKIE = 44 */
1794 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
1795 NULL, /* HTTP_QUERY_REFRESH = 46 */
1796 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
1797 szAge, /* HTTP_QUERY_AGE = 48 */
1798 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
1799 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
1800 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
1801 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
1802 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
1803 szETag, /* HTTP_QUERY_ETAG = 54 */
1804 szHost, /* HTTP_QUERY_HOST = 55 */
1805 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
1806 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
1807 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
1808 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
1809 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
1810 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
1811 szRange, /* HTTP_QUERY_RANGE = 62 */
1812 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
1813 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
1814 szVary, /* HTTP_QUERY_VARY = 65 */
1815 szVia, /* HTTP_QUERY_VIA = 66 */
1816 szWarning, /* HTTP_QUERY_WARNING = 67 */
1817 szExpect, /* HTTP_QUERY_EXPECT = 68 */
1818 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
1819 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
1822 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
1824 /***********************************************************************
1825 * HTTP_HttpQueryInfoW (internal)
1827 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1828 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1830 LPHTTPHEADERW lphttpHdr = NULL;
1831 BOOL bSuccess = FALSE;
1832 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1833 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
1834 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
1835 INT index = -1;
1837 /* Find requested header structure */
1838 switch (level)
1840 case HTTP_QUERY_CUSTOM:
1841 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
1842 break;
1844 case HTTP_QUERY_RAW_HEADERS_CRLF:
1846 LPWSTR headers;
1847 DWORD len;
1848 BOOL ret;
1850 if (request_only)
1851 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
1852 else
1853 headers = lpwhr->lpszRawHeaders;
1855 len = strlenW(headers);
1856 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1858 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1859 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1860 ret = FALSE;
1861 } else
1863 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
1864 *lpdwBufferLength = len * sizeof(WCHAR);
1866 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1867 ret = TRUE;
1870 if (request_only)
1871 HeapFree(GetProcessHeap(), 0, headers);
1872 return ret;
1874 case HTTP_QUERY_RAW_HEADERS:
1876 static const WCHAR szCrLf[] = {'\r','\n',0};
1877 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1878 DWORD i, size = 0;
1879 LPWSTR pszString = (WCHAR*)lpBuffer;
1881 for (i = 0; ppszRawHeaderLines[i]; i++)
1882 size += strlenW(ppszRawHeaderLines[i]) + 1;
1884 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1886 HTTP_FreeTokens(ppszRawHeaderLines);
1887 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1888 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1889 return FALSE;
1892 for (i = 0; ppszRawHeaderLines[i]; i++)
1894 DWORD len = strlenW(ppszRawHeaderLines[i]);
1895 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1896 pszString += len+1;
1898 *pszString = '\0';
1900 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1902 *lpdwBufferLength = size * sizeof(WCHAR);
1903 HTTP_FreeTokens(ppszRawHeaderLines);
1905 return TRUE;
1907 case HTTP_QUERY_STATUS_TEXT:
1908 if (lpwhr->lpszStatusText)
1910 DWORD len = strlenW(lpwhr->lpszStatusText);
1911 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1913 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1914 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1915 return FALSE;
1917 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1918 *lpdwBufferLength = len * sizeof(WCHAR);
1920 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1922 return TRUE;
1924 break;
1925 case HTTP_QUERY_VERSION:
1926 if (lpwhr->lpszVersion)
1928 DWORD len = strlenW(lpwhr->lpszVersion);
1929 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1931 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1932 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1933 return FALSE;
1935 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
1936 *lpdwBufferLength = len * sizeof(WCHAR);
1938 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1940 return TRUE;
1942 break;
1943 default:
1944 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
1946 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
1947 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
1948 requested_index,request_only);
1951 if (index >= 0)
1952 lphttpHdr = &lpwhr->pCustHeaders[index];
1954 /* Ensure header satisfies requested attributes */
1955 if (!lphttpHdr ||
1956 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
1957 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
1959 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1960 return bSuccess;
1963 if (lpdwIndex)
1964 (*lpdwIndex)++;
1966 /* coalesce value to requested type */
1967 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
1969 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
1970 bSuccess = TRUE;
1972 TRACE(" returning number : %d\n", *(int *)lpBuffer);
1974 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
1976 time_t tmpTime;
1977 struct tm tmpTM;
1978 SYSTEMTIME *STHook;
1980 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
1982 tmpTM = *gmtime(&tmpTime);
1983 STHook = (SYSTEMTIME *) lpBuffer;
1984 if(STHook==NULL)
1985 return bSuccess;
1987 STHook->wDay = tmpTM.tm_mday;
1988 STHook->wHour = tmpTM.tm_hour;
1989 STHook->wMilliseconds = 0;
1990 STHook->wMinute = tmpTM.tm_min;
1991 STHook->wDayOfWeek = tmpTM.tm_wday;
1992 STHook->wMonth = tmpTM.tm_mon + 1;
1993 STHook->wSecond = tmpTM.tm_sec;
1994 STHook->wYear = tmpTM.tm_year;
1996 bSuccess = TRUE;
1998 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
1999 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2000 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2002 else if (lphttpHdr->lpszValue)
2004 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2006 if (len > *lpdwBufferLength)
2008 *lpdwBufferLength = len;
2009 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2010 return bSuccess;
2013 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2014 *lpdwBufferLength = len - sizeof(WCHAR);
2015 bSuccess = TRUE;
2017 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
2019 return bSuccess;
2022 /***********************************************************************
2023 * HttpQueryInfoW (WININET.@)
2025 * Queries for information about an HTTP request
2027 * RETURNS
2028 * TRUE on success
2029 * FALSE on failure
2032 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2033 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2035 BOOL bSuccess = FALSE;
2036 LPWININETHTTPREQW lpwhr;
2038 if (TRACE_ON(wininet)) {
2039 #define FE(x) { x, #x }
2040 static const wininet_flag_info query_flags[] = {
2041 FE(HTTP_QUERY_MIME_VERSION),
2042 FE(HTTP_QUERY_CONTENT_TYPE),
2043 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2044 FE(HTTP_QUERY_CONTENT_ID),
2045 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2046 FE(HTTP_QUERY_CONTENT_LENGTH),
2047 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2048 FE(HTTP_QUERY_ALLOW),
2049 FE(HTTP_QUERY_PUBLIC),
2050 FE(HTTP_QUERY_DATE),
2051 FE(HTTP_QUERY_EXPIRES),
2052 FE(HTTP_QUERY_LAST_MODIFIED),
2053 FE(HTTP_QUERY_MESSAGE_ID),
2054 FE(HTTP_QUERY_URI),
2055 FE(HTTP_QUERY_DERIVED_FROM),
2056 FE(HTTP_QUERY_COST),
2057 FE(HTTP_QUERY_LINK),
2058 FE(HTTP_QUERY_PRAGMA),
2059 FE(HTTP_QUERY_VERSION),
2060 FE(HTTP_QUERY_STATUS_CODE),
2061 FE(HTTP_QUERY_STATUS_TEXT),
2062 FE(HTTP_QUERY_RAW_HEADERS),
2063 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2064 FE(HTTP_QUERY_CONNECTION),
2065 FE(HTTP_QUERY_ACCEPT),
2066 FE(HTTP_QUERY_ACCEPT_CHARSET),
2067 FE(HTTP_QUERY_ACCEPT_ENCODING),
2068 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2069 FE(HTTP_QUERY_AUTHORIZATION),
2070 FE(HTTP_QUERY_CONTENT_ENCODING),
2071 FE(HTTP_QUERY_FORWARDED),
2072 FE(HTTP_QUERY_FROM),
2073 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2074 FE(HTTP_QUERY_LOCATION),
2075 FE(HTTP_QUERY_ORIG_URI),
2076 FE(HTTP_QUERY_REFERER),
2077 FE(HTTP_QUERY_RETRY_AFTER),
2078 FE(HTTP_QUERY_SERVER),
2079 FE(HTTP_QUERY_TITLE),
2080 FE(HTTP_QUERY_USER_AGENT),
2081 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2082 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2083 FE(HTTP_QUERY_ACCEPT_RANGES),
2084 FE(HTTP_QUERY_SET_COOKIE),
2085 FE(HTTP_QUERY_COOKIE),
2086 FE(HTTP_QUERY_REQUEST_METHOD),
2087 FE(HTTP_QUERY_REFRESH),
2088 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2089 FE(HTTP_QUERY_AGE),
2090 FE(HTTP_QUERY_CACHE_CONTROL),
2091 FE(HTTP_QUERY_CONTENT_BASE),
2092 FE(HTTP_QUERY_CONTENT_LOCATION),
2093 FE(HTTP_QUERY_CONTENT_MD5),
2094 FE(HTTP_QUERY_CONTENT_RANGE),
2095 FE(HTTP_QUERY_ETAG),
2096 FE(HTTP_QUERY_HOST),
2097 FE(HTTP_QUERY_IF_MATCH),
2098 FE(HTTP_QUERY_IF_NONE_MATCH),
2099 FE(HTTP_QUERY_IF_RANGE),
2100 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2101 FE(HTTP_QUERY_MAX_FORWARDS),
2102 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2103 FE(HTTP_QUERY_RANGE),
2104 FE(HTTP_QUERY_TRANSFER_ENCODING),
2105 FE(HTTP_QUERY_UPGRADE),
2106 FE(HTTP_QUERY_VARY),
2107 FE(HTTP_QUERY_VIA),
2108 FE(HTTP_QUERY_WARNING),
2109 FE(HTTP_QUERY_CUSTOM)
2111 static const wininet_flag_info modifier_flags[] = {
2112 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2113 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2114 FE(HTTP_QUERY_FLAG_NUMBER),
2115 FE(HTTP_QUERY_FLAG_COALESCE)
2117 #undef FE
2118 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2119 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2120 DWORD i;
2122 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2123 TRACE(" Attribute:");
2124 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2125 if (query_flags[i].val == info) {
2126 TRACE(" %s", query_flags[i].name);
2127 break;
2130 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2131 TRACE(" Unknown (%08x)", info);
2134 TRACE(" Modifier:");
2135 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2136 if (modifier_flags[i].val & info_mod) {
2137 TRACE(" %s", modifier_flags[i].name);
2138 info_mod &= ~ modifier_flags[i].val;
2142 if (info_mod) {
2143 TRACE(" Unknown (%08x)", info_mod);
2145 TRACE("\n");
2148 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2149 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2151 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2152 goto lend;
2155 if (lpBuffer == NULL)
2156 *lpdwBufferLength = 0;
2157 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2158 lpBuffer, lpdwBufferLength, lpdwIndex);
2160 lend:
2161 if( lpwhr )
2162 WININET_Release( &lpwhr->hdr );
2164 TRACE("%d <--\n", bSuccess);
2165 return bSuccess;
2168 /***********************************************************************
2169 * HttpQueryInfoA (WININET.@)
2171 * Queries for information about an HTTP request
2173 * RETURNS
2174 * TRUE on success
2175 * FALSE on failure
2178 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2179 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2181 BOOL result;
2182 DWORD len;
2183 WCHAR* bufferW;
2185 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2186 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2188 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2189 lpdwBufferLength, lpdwIndex );
2192 if (lpBuffer)
2194 DWORD alloclen;
2195 len = (*lpdwBufferLength)*sizeof(WCHAR);
2196 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2198 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2199 if (alloclen < len)
2200 alloclen = len;
2202 else
2203 alloclen = len;
2204 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2205 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2206 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2207 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2208 } else
2210 bufferW = NULL;
2211 len = 0;
2214 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2215 &len, lpdwIndex );
2216 if( result )
2218 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2219 lpBuffer, *lpdwBufferLength, NULL, NULL );
2220 *lpdwBufferLength = len - 1;
2222 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2224 else
2225 /* since the strings being returned from HttpQueryInfoW should be
2226 * only ASCII characters, it is reasonable to assume that all of
2227 * the Unicode characters can be reduced to a single byte */
2228 *lpdwBufferLength = len / sizeof(WCHAR);
2230 HeapFree(GetProcessHeap(), 0, bufferW );
2232 return result;
2235 /***********************************************************************
2236 * HttpSendRequestExA (WININET.@)
2238 * Sends the specified request to the HTTP server and allows chunked
2239 * transfers.
2241 * RETURNS
2242 * Success: TRUE
2243 * Failure: FALSE, call GetLastError() for more information.
2245 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2246 LPINTERNET_BUFFERSA lpBuffersIn,
2247 LPINTERNET_BUFFERSA lpBuffersOut,
2248 DWORD dwFlags, DWORD_PTR dwContext)
2250 INTERNET_BUFFERSW BuffersInW;
2251 BOOL rc = FALSE;
2252 DWORD headerlen;
2253 LPWSTR header = NULL;
2255 TRACE("(%p, %p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersIn,
2256 lpBuffersOut, dwFlags, dwContext);
2258 if (lpBuffersIn)
2260 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2261 if (lpBuffersIn->lpcszHeader)
2263 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2264 lpBuffersIn->dwHeadersLength,0,0);
2265 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2266 if (!(BuffersInW.lpcszHeader = header))
2268 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2269 return FALSE;
2271 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2272 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2273 header, headerlen);
2275 else
2276 BuffersInW.lpcszHeader = NULL;
2277 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2278 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2279 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2280 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2281 BuffersInW.Next = NULL;
2284 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2286 HeapFree(GetProcessHeap(),0,header);
2288 return rc;
2291 /***********************************************************************
2292 * HttpSendRequestExW (WININET.@)
2294 * Sends the specified request to the HTTP server and allows chunked
2295 * transfers
2297 * RETURNS
2298 * Success: TRUE
2299 * Failure: FALSE, call GetLastError() for more information.
2301 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2302 LPINTERNET_BUFFERSW lpBuffersIn,
2303 LPINTERNET_BUFFERSW lpBuffersOut,
2304 DWORD dwFlags, DWORD_PTR dwContext)
2306 BOOL ret = FALSE;
2307 LPWININETHTTPREQW lpwhr;
2308 LPWININETHTTPSESSIONW lpwhs;
2309 LPWININETAPPINFOW hIC;
2311 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2312 lpBuffersOut, dwFlags, dwContext);
2314 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2316 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2318 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2319 goto lend;
2322 lpwhs = lpwhr->lpHttpSession;
2323 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2324 hIC = lpwhs->lpAppInfo;
2325 assert(hIC->hdr.htype == WH_HINIT);
2327 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2329 WORKREQUEST workRequest;
2330 struct WORKREQ_HTTPSENDREQUESTW *req;
2332 workRequest.asyncproc = AsyncHttpSendRequestProc;
2333 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2334 req = &workRequest.u.HttpSendRequestW;
2335 if (lpBuffersIn)
2337 if (lpBuffersIn->lpcszHeader)
2338 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2339 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2340 else
2341 req->lpszHeader = NULL;
2342 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2343 req->lpOptional = lpBuffersIn->lpvBuffer;
2344 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2345 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2347 else
2349 req->lpszHeader = NULL;
2350 req->dwHeaderLength = 0;
2351 req->lpOptional = NULL;
2352 req->dwOptionalLength = 0;
2353 req->dwContentLength = 0;
2356 req->bEndRequest = FALSE;
2358 INTERNET_AsyncCall(&workRequest);
2360 * This is from windows.
2362 INTERNET_SetLastError(ERROR_IO_PENDING);
2364 else
2366 if (lpBuffersIn)
2367 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2368 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2369 lpBuffersIn->dwBufferTotal, FALSE);
2370 else
2371 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2374 lend:
2375 if ( lpwhr )
2376 WININET_Release( &lpwhr->hdr );
2378 TRACE("<---\n");
2379 return ret;
2382 /***********************************************************************
2383 * HttpSendRequestW (WININET.@)
2385 * Sends the specified request to the HTTP server
2387 * RETURNS
2388 * TRUE on success
2389 * FALSE on failure
2392 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2393 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2395 LPWININETHTTPREQW lpwhr;
2396 LPWININETHTTPSESSIONW lpwhs = NULL;
2397 LPWININETAPPINFOW hIC = NULL;
2398 BOOL r;
2400 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2401 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2403 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2404 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2406 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2407 r = FALSE;
2408 goto lend;
2411 lpwhs = lpwhr->lpHttpSession;
2412 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2414 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2415 r = FALSE;
2416 goto lend;
2419 hIC = lpwhs->lpAppInfo;
2420 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2422 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2423 r = FALSE;
2424 goto lend;
2427 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2429 WORKREQUEST workRequest;
2430 struct WORKREQ_HTTPSENDREQUESTW *req;
2432 workRequest.asyncproc = AsyncHttpSendRequestProc;
2433 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2434 req = &workRequest.u.HttpSendRequestW;
2435 if (lpszHeaders)
2437 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2438 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2440 else
2441 req->lpszHeader = 0;
2442 req->dwHeaderLength = dwHeaderLength;
2443 req->lpOptional = lpOptional;
2444 req->dwOptionalLength = dwOptionalLength;
2445 req->dwContentLength = dwOptionalLength;
2446 req->bEndRequest = TRUE;
2448 INTERNET_AsyncCall(&workRequest);
2450 * This is from windows.
2452 INTERNET_SetLastError(ERROR_IO_PENDING);
2453 r = FALSE;
2455 else
2457 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2458 dwHeaderLength, lpOptional, dwOptionalLength,
2459 dwOptionalLength, TRUE);
2461 lend:
2462 if( lpwhr )
2463 WININET_Release( &lpwhr->hdr );
2464 return r;
2467 /***********************************************************************
2468 * HttpSendRequestA (WININET.@)
2470 * Sends the specified request to the HTTP server
2472 * RETURNS
2473 * TRUE on success
2474 * FALSE on failure
2477 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2478 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2480 BOOL result;
2481 LPWSTR szHeaders=NULL;
2482 DWORD nLen=dwHeaderLength;
2483 if(lpszHeaders!=NULL)
2485 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2486 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2487 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2489 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2490 HeapFree(GetProcessHeap(),0,szHeaders);
2491 return result;
2494 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2496 LPHTTPHEADERW host_header;
2498 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2500 host_header = HTTP_GetHeader(req, szHost);
2501 if(!host_header)
2502 return FALSE;
2504 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2505 return TRUE;
2508 /***********************************************************************
2509 * HTTP_HandleRedirect (internal)
2511 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2513 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2514 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2515 WCHAR path[2048];
2517 if(lpszUrl[0]=='/')
2519 /* if it's an absolute path, keep the same session info */
2520 lstrcpynW(path, lpszUrl, 2048);
2522 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2524 TRACE("Redirect through proxy\n");
2525 lstrcpynW(path, lpszUrl, 2048);
2527 else
2529 URL_COMPONENTSW urlComponents;
2530 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2531 static WCHAR szHttp[] = {'h','t','t','p',0};
2532 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2533 DWORD url_length = 0;
2534 LPWSTR orig_url;
2535 LPWSTR combined_url;
2537 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2538 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2539 urlComponents.dwSchemeLength = 0;
2540 urlComponents.lpszHostName = lpwhs->lpszHostName;
2541 urlComponents.dwHostNameLength = 0;
2542 urlComponents.nPort = lpwhs->nHostPort;
2543 urlComponents.lpszUserName = lpwhs->lpszUserName;
2544 urlComponents.dwUserNameLength = 0;
2545 urlComponents.lpszPassword = NULL;
2546 urlComponents.dwPasswordLength = 0;
2547 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2548 urlComponents.dwUrlPathLength = 0;
2549 urlComponents.lpszExtraInfo = NULL;
2550 urlComponents.dwExtraInfoLength = 0;
2552 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2553 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2554 return FALSE;
2556 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2558 /* convert from bytes to characters */
2559 url_length = url_length / sizeof(WCHAR) - 1;
2560 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2562 HeapFree(GetProcessHeap(), 0, orig_url);
2563 return FALSE;
2566 url_length = 0;
2567 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2568 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2570 HeapFree(GetProcessHeap(), 0, orig_url);
2571 return FALSE;
2573 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2575 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2577 HeapFree(GetProcessHeap(), 0, orig_url);
2578 HeapFree(GetProcessHeap(), 0, combined_url);
2579 return FALSE;
2581 HeapFree(GetProcessHeap(), 0, orig_url);
2583 userName[0] = 0;
2584 hostName[0] = 0;
2585 protocol[0] = 0;
2587 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2588 urlComponents.lpszScheme = protocol;
2589 urlComponents.dwSchemeLength = 32;
2590 urlComponents.lpszHostName = hostName;
2591 urlComponents.dwHostNameLength = MAXHOSTNAME;
2592 urlComponents.lpszUserName = userName;
2593 urlComponents.dwUserNameLength = 1024;
2594 urlComponents.lpszPassword = NULL;
2595 urlComponents.dwPasswordLength = 0;
2596 urlComponents.lpszUrlPath = path;
2597 urlComponents.dwUrlPathLength = 2048;
2598 urlComponents.lpszExtraInfo = NULL;
2599 urlComponents.dwExtraInfoLength = 0;
2600 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2602 HeapFree(GetProcessHeap(), 0, combined_url);
2603 return FALSE;
2606 HeapFree(GetProcessHeap(), 0, combined_url);
2608 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2609 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2611 TRACE("redirect from secure page to non-secure page\n");
2612 /* FIXME: warn about from secure redirect to non-secure page */
2613 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2615 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2616 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2618 TRACE("redirect from non-secure page to secure page\n");
2619 /* FIXME: notify about redirect to secure page */
2620 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2623 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2625 if (lstrlenW(protocol)>4) /*https*/
2626 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2627 else /*http*/
2628 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2631 #if 0
2633 * This upsets redirects to binary files on sourceforge.net
2634 * and gives an html page instead of the target file
2635 * Examination of the HTTP request sent by native wininet.dll
2636 * reveals that it doesn't send a referrer in that case.
2637 * Maybe there's a flag that enables this, or maybe a referrer
2638 * shouldn't be added in case of a redirect.
2641 /* consider the current host as the referrer */
2642 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2643 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2644 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2645 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2646 #endif
2648 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2649 lpwhs->lpszServerName = WININET_strdupW(hostName);
2650 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2651 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2652 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2654 int len;
2655 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2656 len = lstrlenW(hostName);
2657 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2658 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2659 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2661 else
2662 lpwhs->lpszHostName = WININET_strdupW(hostName);
2664 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2667 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2668 lpwhs->lpszUserName = NULL;
2669 if (userName[0])
2670 lpwhs->lpszUserName = WININET_strdupW(userName);
2671 lpwhs->nServerPort = urlComponents.nPort;
2673 if (!HTTP_ResolveName(lpwhr))
2674 return FALSE;
2676 NETCON_close(&lpwhr->netConnection);
2678 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2679 return FALSE;
2682 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2683 lpwhr->lpszPath=NULL;
2684 if (*path)
2686 DWORD needed = 0;
2687 HRESULT rc;
2689 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2690 if (rc != E_POINTER)
2691 needed = strlenW(path)+1;
2692 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2693 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2694 URL_ESCAPE_SPACES_ONLY);
2695 if (rc)
2697 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2698 strcpyW(lpwhr->lpszPath,path);
2702 return TRUE;
2705 /***********************************************************************
2706 * HTTP_build_req (internal)
2708 * concatenate all the strings in the request together
2710 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2712 LPCWSTR *t;
2713 LPWSTR str;
2715 for( t = list; *t ; t++ )
2716 len += strlenW( *t );
2717 len++;
2719 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2720 *str = 0;
2722 for( t = list; *t ; t++ )
2723 strcatW( str, *t );
2725 return str;
2728 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2730 LPWSTR lpszPath;
2731 LPWSTR requestString;
2732 INT len;
2733 INT cnt;
2734 INT responseLen;
2735 char *ascii_req;
2736 BOOL ret;
2737 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2738 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2739 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2741 TRACE("\n");
2743 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2744 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2745 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
2746 HeapFree( GetProcessHeap(), 0, lpszPath );
2748 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2749 NULL, 0, NULL, NULL );
2750 len--; /* the nul terminator isn't needed */
2751 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2752 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2753 ascii_req, len, NULL, NULL );
2754 HeapFree( GetProcessHeap(), 0, requestString );
2756 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2758 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2759 HeapFree( GetProcessHeap(), 0, ascii_req );
2760 if (!ret || cnt < 0)
2761 return FALSE;
2763 responseLen = HTTP_GetResponseHeaders( lpwhr );
2764 if (!responseLen)
2765 return FALSE;
2767 return TRUE;
2770 /***********************************************************************
2771 * HTTP_HttpSendRequestW (internal)
2773 * Sends the specified request to the HTTP server
2775 * RETURNS
2776 * TRUE on success
2777 * FALSE on failure
2780 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2781 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2782 DWORD dwContentLength, BOOL bEndRequest)
2784 INT cnt;
2785 BOOL bSuccess = FALSE;
2786 LPWSTR requestString = NULL;
2787 INT responseLen;
2788 BOOL loop_next;
2789 INTERNET_ASYNC_RESULT iar;
2790 static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
2791 static const WCHAR szPost[] = { 'P','O','S','T',0 };
2792 static const WCHAR szContentLength[] =
2793 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
2794 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
2796 TRACE("--> %p\n", lpwhr);
2798 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2800 /* Clear any error information */
2801 INTERNET_SetLastError(0);
2803 /* if the verb is NULL default to GET */
2804 if (!lpwhr->lpszVerb)
2805 lpwhr->lpszVerb = WININET_strdupW(szGET);
2807 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
2809 sprintfW(contentLengthStr, szContentLength, dwContentLength);
2810 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2815 DWORD len;
2816 char *ascii_req;
2818 loop_next = FALSE;
2820 /* like native, just in case the caller forgot to call InternetReadFile
2821 * for all the data */
2822 HTTP_DrainContent(lpwhr);
2823 lpwhr->dwContentRead = 0;
2825 if (TRACE_ON(wininet))
2827 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
2828 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2831 HTTP_FixURL(lpwhr);
2832 HTTP_ProcessHeader(lpwhr, szConnection,
2833 lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
2834 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
2836 HTTP_InsertAuthorization(lpwhr, szAuthorization, !loop_next);
2837 HTTP_InsertAuthorization(lpwhr, szProxy_Authorization, !loop_next);
2839 /* add the headers the caller supplied */
2840 if( lpszHeaders && dwHeaderLength )
2842 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2843 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2846 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2848 TRACE("Request header -> %s\n", debugstr_w(requestString) );
2850 /* Send the request and store the results */
2851 if (!HTTP_OpenConnection(lpwhr))
2852 goto lend;
2854 /* send the request as ASCII, tack on the optional data */
2855 if( !lpOptional )
2856 dwOptionalLength = 0;
2857 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2858 NULL, 0, NULL, NULL );
2859 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2860 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2861 ascii_req, len, NULL, NULL );
2862 if( lpOptional )
2863 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2864 len = (len + dwOptionalLength - 1);
2865 ascii_req[len] = 0;
2866 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2868 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2869 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2871 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2872 HeapFree( GetProcessHeap(), 0, ascii_req );
2874 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2875 INTERNET_STATUS_REQUEST_SENT,
2876 &len, sizeof(DWORD));
2878 if (bEndRequest)
2880 DWORD dwBufferSize;
2881 DWORD dwStatusCode;
2883 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2884 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2886 if (cnt < 0)
2887 goto lend;
2889 responseLen = HTTP_GetResponseHeaders(lpwhr);
2890 if (responseLen)
2891 bSuccess = TRUE;
2893 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2894 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2895 sizeof(DWORD));
2897 HTTP_ProcessCookies(lpwhr);
2899 dwBufferSize = sizeof(lpwhr->dwContentLength);
2900 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2901 &lpwhr->dwContentLength,&dwBufferSize,NULL))
2902 lpwhr->dwContentLength = -1;
2904 if (lpwhr->dwContentLength == 0)
2905 HTTP_FinishedReading(lpwhr);
2907 dwBufferSize = sizeof(dwStatusCode);
2908 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
2909 &dwStatusCode,&dwBufferSize,NULL))
2910 dwStatusCode = 0;
2912 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
2914 WCHAR szNewLocation[2048];
2915 dwBufferSize=sizeof(szNewLocation);
2916 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
2917 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
2919 HTTP_DrainContent(lpwhr);
2920 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2921 INTERNET_STATUS_REDIRECT, szNewLocation,
2922 dwBufferSize);
2923 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
2924 if (bSuccess)
2926 HeapFree(GetProcessHeap(), 0, requestString);
2927 loop_next = TRUE;
2931 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
2933 WCHAR szAuthValue[2048];
2934 dwBufferSize=2048;
2935 if (dwStatusCode == HTTP_STATUS_DENIED)
2937 DWORD dwIndex = 0;
2938 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2940 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2941 &lpwhr->pAuthInfo,
2942 lpwhr->lpHttpSession->lpszUserName,
2943 lpwhr->lpHttpSession->lpszPassword))
2945 loop_next = TRUE;
2946 break;
2950 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
2952 DWORD dwIndex = 0;
2953 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2955 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2956 &lpwhr->pProxyAuthInfo,
2957 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
2958 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
2960 loop_next = TRUE;
2961 break;
2967 else
2968 bSuccess = TRUE;
2970 while (loop_next);
2972 /* FIXME: Better check, when we have to create the cache file */
2973 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
2974 WCHAR url[INTERNET_MAX_URL_LENGTH];
2975 WCHAR cacheFileName[MAX_PATH+1];
2976 BOOL b;
2978 b = HTTP_GetRequestURL(lpwhr, url);
2979 if(!b) {
2980 WARN("Could not get URL\n");
2981 goto lend;
2984 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
2985 if(b) {
2986 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
2987 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2988 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2989 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
2990 WARN("Could not create file: %u\n", GetLastError());
2991 lpwhr->hCacheFile = NULL;
2993 }else {
2994 WARN("Could not create cache entry: %08x\n", GetLastError());
2998 lend:
3000 HeapFree(GetProcessHeap(), 0, requestString);
3002 /* TODO: send notification for P3P header */
3004 iar.dwResult = (DWORD)bSuccess;
3005 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
3007 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3008 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3009 sizeof(INTERNET_ASYNC_RESULT));
3011 TRACE("<--\n");
3012 return bSuccess;
3015 /***********************************************************************
3016 * HTTPSESSION_Destroy (internal)
3018 * Deallocate session handle
3021 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3023 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3025 TRACE("%p\n", lpwhs);
3027 WININET_Release(&lpwhs->lpAppInfo->hdr);
3029 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3030 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3031 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3032 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3033 HeapFree(GetProcessHeap(), 0, lpwhs);
3037 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3038 HTTPSESSION_Destroy,
3039 NULL,
3040 NULL,
3041 NULL,
3042 NULL,
3043 NULL,
3044 NULL
3048 /***********************************************************************
3049 * HTTP_Connect (internal)
3051 * Create http session handle
3053 * RETURNS
3054 * HINTERNET a session handle on success
3055 * NULL on failure
3058 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3059 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3060 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3061 DWORD dwInternalFlags)
3063 BOOL bSuccess = FALSE;
3064 LPWININETHTTPSESSIONW lpwhs = NULL;
3065 HINTERNET handle = NULL;
3067 TRACE("-->\n");
3069 if (!lpszServerName || !lpszServerName[0])
3071 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3072 goto lerror;
3075 assert( hIC->hdr.htype == WH_HINIT );
3077 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3078 if (NULL == lpwhs)
3080 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3081 goto lerror;
3085 * According to my tests. The name is not resolved until a request is sent
3088 lpwhs->hdr.htype = WH_HHTTPSESSION;
3089 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3090 lpwhs->hdr.dwFlags = dwFlags;
3091 lpwhs->hdr.dwContext = dwContext;
3092 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3093 lpwhs->hdr.dwRefCount = 1;
3094 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3096 WININET_AddRef( &hIC->hdr );
3097 lpwhs->lpAppInfo = hIC;
3098 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3100 handle = WININET_AllocHandle( &lpwhs->hdr );
3101 if (NULL == handle)
3103 ERR("Failed to alloc handle\n");
3104 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3105 goto lerror;
3108 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3109 if(strchrW(hIC->lpszProxy, ' '))
3110 FIXME("Several proxies not implemented.\n");
3111 if(hIC->lpszProxyBypass)
3112 FIXME("Proxy bypass is ignored.\n");
3114 if (lpszServerName && lpszServerName[0])
3116 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3117 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3119 if (lpszUserName && lpszUserName[0])
3120 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3121 if (lpszPassword && lpszPassword[0])
3122 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3123 lpwhs->nServerPort = nServerPort;
3124 lpwhs->nHostPort = nServerPort;
3126 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3127 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3129 INTERNET_SendCallback(&hIC->hdr, dwContext,
3130 INTERNET_STATUS_HANDLE_CREATED, &handle,
3131 sizeof(handle));
3134 bSuccess = TRUE;
3136 lerror:
3137 if( lpwhs )
3138 WININET_Release( &lpwhs->hdr );
3141 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3142 * windows
3145 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3146 return handle;
3150 /***********************************************************************
3151 * HTTP_OpenConnection (internal)
3153 * Connect to a web server
3155 * RETURNS
3157 * TRUE on success
3158 * FALSE on failure
3160 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3162 BOOL bSuccess = FALSE;
3163 LPWININETHTTPSESSIONW lpwhs;
3164 LPWININETAPPINFOW hIC = NULL;
3165 char szaddr[32];
3167 TRACE("-->\n");
3170 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3172 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3173 goto lend;
3176 if (NETCON_connected(&lpwhr->netConnection))
3178 bSuccess = TRUE;
3179 goto lend;
3182 lpwhs = lpwhr->lpHttpSession;
3184 hIC = lpwhs->lpAppInfo;
3185 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3186 szaddr, sizeof(szaddr));
3187 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3188 INTERNET_STATUS_CONNECTING_TO_SERVER,
3189 szaddr,
3190 strlen(szaddr)+1);
3192 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3193 SOCK_STREAM, 0))
3195 WARN("Socket creation failed\n");
3196 goto lend;
3199 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3200 sizeof(lpwhs->socketAddress)))
3201 goto lend;
3203 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3205 /* Note: we differ from Microsoft's WinINet here. they seem to have
3206 * a bug that causes no status callbacks to be sent when starting
3207 * a tunnel to a proxy server using the CONNECT verb. i believe our
3208 * behaviour to be more correct and to not cause any incompatibilities
3209 * because using a secure connection through a proxy server is a rare
3210 * case that would be hard for anyone to depend on */
3211 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3212 goto lend;
3214 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3216 WARN("Couldn't connect securely to host\n");
3217 goto lend;
3221 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3222 INTERNET_STATUS_CONNECTED_TO_SERVER,
3223 szaddr, strlen(szaddr)+1);
3225 bSuccess = TRUE;
3227 lend:
3228 TRACE("%d <--\n", bSuccess);
3229 return bSuccess;
3233 /***********************************************************************
3234 * HTTP_clear_response_headers (internal)
3236 * clear out any old response headers
3238 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3240 DWORD i;
3242 for( i=0; i<lpwhr->nCustHeaders; i++)
3244 if( !lpwhr->pCustHeaders[i].lpszField )
3245 continue;
3246 if( !lpwhr->pCustHeaders[i].lpszValue )
3247 continue;
3248 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3249 continue;
3250 HTTP_DeleteCustomHeader( lpwhr, i );
3251 i--;
3255 /***********************************************************************
3256 * HTTP_GetResponseHeaders (internal)
3258 * Read server response
3260 * RETURNS
3262 * TRUE on success
3263 * FALSE on error
3265 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
3267 INT cbreaks = 0;
3268 WCHAR buffer[MAX_REPLY_LEN];
3269 DWORD buflen = MAX_REPLY_LEN;
3270 BOOL bSuccess = FALSE;
3271 INT rc = 0;
3272 static const WCHAR szCrLf[] = {'\r','\n',0};
3273 static const WCHAR szHundred[] = {'1','0','0',0};
3274 char bufferA[MAX_REPLY_LEN];
3275 LPWSTR status_code, status_text;
3276 DWORD cchMaxRawHeaders = 1024;
3277 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3278 DWORD cchRawHeaders = 0;
3280 TRACE("-->\n");
3282 /* clear old response headers (eg. from a redirect response) */
3283 HTTP_clear_response_headers( lpwhr );
3285 if (!NETCON_connected(&lpwhr->netConnection))
3286 goto lend;
3288 do {
3290 * HACK peek at the buffer
3292 buflen = MAX_REPLY_LEN;
3293 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3296 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3298 memset(buffer, 0, MAX_REPLY_LEN);
3299 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3300 goto lend;
3301 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3303 /* split the version from the status code */
3304 status_code = strchrW( buffer, ' ' );
3305 if( !status_code )
3306 goto lend;
3307 *status_code++=0;
3309 /* split the status code from the status text */
3310 status_text = strchrW( status_code, ' ' );
3311 if( !status_text )
3312 goto lend;
3313 *status_text++=0;
3315 TRACE("version [%s] status code [%s] status text [%s]\n",
3316 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3318 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3320 /* Add status code */
3321 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3322 HTTP_ADDHDR_FLAG_REPLACE);
3324 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3325 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3327 lpwhr->lpszVersion= WININET_strdupW(buffer);
3328 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3330 /* Restore the spaces */
3331 *(status_code-1) = ' ';
3332 *(status_text-1) = ' ';
3334 /* regenerate raw headers */
3335 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3337 cchMaxRawHeaders *= 2;
3338 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3340 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3341 cchRawHeaders += (buflen-1);
3342 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3343 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3344 lpszRawHeaders[cchRawHeaders] = '\0';
3346 /* Parse each response line */
3349 buflen = MAX_REPLY_LEN;
3350 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3352 LPWSTR * pFieldAndValue;
3354 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3355 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3357 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3359 cchMaxRawHeaders *= 2;
3360 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3362 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3363 cchRawHeaders += (buflen-1);
3364 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3365 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3366 lpszRawHeaders[cchRawHeaders] = '\0';
3368 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3369 if (!pFieldAndValue)
3370 break;
3372 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3373 HTTP_ADDREQ_FLAG_ADD );
3375 HTTP_FreeTokens(pFieldAndValue);
3377 else
3379 cbreaks++;
3380 if (cbreaks >= 2)
3381 break;
3383 }while(1);
3385 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3386 lpwhr->lpszRawHeaders = lpszRawHeaders;
3387 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3388 bSuccess = TRUE;
3390 lend:
3392 TRACE("<--\n");
3393 if (bSuccess)
3394 return rc;
3395 else
3396 return 0;
3400 static void strip_spaces(LPWSTR start)
3402 LPWSTR str = start;
3403 LPWSTR end;
3405 while (*str == ' ' && *str != '\0')
3406 str++;
3408 if (str != start)
3409 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3411 end = start + strlenW(start) - 1;
3412 while (end >= start && *end == ' ')
3414 *end = '\0';
3415 end--;
3420 /***********************************************************************
3421 * HTTP_InterpretHttpHeader (internal)
3423 * Parse server response
3425 * RETURNS
3427 * Pointer to array of field, value, NULL on success.
3428 * NULL on error.
3430 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3432 LPWSTR * pTokenPair;
3433 LPWSTR pszColon;
3434 INT len;
3436 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3438 pszColon = strchrW(buffer, ':');
3439 /* must have two tokens */
3440 if (!pszColon)
3442 HTTP_FreeTokens(pTokenPair);
3443 if (buffer[0])
3444 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3445 return NULL;
3448 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3449 if (!pTokenPair[0])
3451 HTTP_FreeTokens(pTokenPair);
3452 return NULL;
3454 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3455 pTokenPair[0][pszColon - buffer] = '\0';
3457 /* skip colon */
3458 pszColon++;
3459 len = strlenW(pszColon);
3460 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3461 if (!pTokenPair[1])
3463 HTTP_FreeTokens(pTokenPair);
3464 return NULL;
3466 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3468 strip_spaces(pTokenPair[0]);
3469 strip_spaces(pTokenPair[1]);
3471 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3472 return pTokenPair;
3475 /***********************************************************************
3476 * HTTP_ProcessHeader (internal)
3478 * Stuff header into header tables according to <dwModifier>
3482 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3484 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3486 LPHTTPHEADERW lphttpHdr = NULL;
3487 BOOL bSuccess = FALSE;
3488 INT index = -1;
3489 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3491 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3493 /* REPLACE wins out over ADD */
3494 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3495 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3497 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3498 index = -1;
3499 else
3500 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3502 if (index >= 0)
3504 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3506 return FALSE;
3508 lphttpHdr = &lpwhr->pCustHeaders[index];
3510 else if (value)
3512 HTTPHEADERW hdr;
3514 hdr.lpszField = (LPWSTR)field;
3515 hdr.lpszValue = (LPWSTR)value;
3516 hdr.wFlags = hdr.wCount = 0;
3518 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3519 hdr.wFlags |= HDR_ISREQUEST;
3521 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3523 /* no value to delete */
3524 else return TRUE;
3526 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3527 lphttpHdr->wFlags |= HDR_ISREQUEST;
3528 else
3529 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3531 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3533 HTTP_DeleteCustomHeader( lpwhr, index );
3535 if (value)
3537 HTTPHEADERW hdr;
3539 hdr.lpszField = (LPWSTR)field;
3540 hdr.lpszValue = (LPWSTR)value;
3541 hdr.wFlags = hdr.wCount = 0;
3543 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3544 hdr.wFlags |= HDR_ISREQUEST;
3546 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3549 return TRUE;
3551 else if (dwModifier & COALESCEFLAGS)
3553 LPWSTR lpsztmp;
3554 WCHAR ch = 0;
3555 INT len = 0;
3556 INT origlen = strlenW(lphttpHdr->lpszValue);
3557 INT valuelen = strlenW(value);
3559 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3561 ch = ',';
3562 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3564 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3566 ch = ';';
3567 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3570 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3572 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3573 if (lpsztmp)
3575 lphttpHdr->lpszValue = lpsztmp;
3576 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3577 if (ch > 0)
3579 lphttpHdr->lpszValue[origlen] = ch;
3580 origlen++;
3581 lphttpHdr->lpszValue[origlen] = ' ';
3582 origlen++;
3585 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3586 lphttpHdr->lpszValue[len] = '\0';
3587 bSuccess = TRUE;
3589 else
3591 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3592 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3595 TRACE("<-- %d\n",bSuccess);
3596 return bSuccess;
3600 /***********************************************************************
3601 * HTTP_FinishedReading (internal)
3603 * Called when all content from server has been read by client.
3606 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
3608 WCHAR szConnectionResponse[20];
3609 DWORD dwBufferSize = sizeof(szConnectionResponse);
3611 TRACE("\n");
3613 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse,
3614 &dwBufferSize, NULL) ||
3615 strcmpiW(szConnectionResponse, szKeepAlive))
3617 HTTPREQ_CloseConnection(&lpwhr->hdr);
3620 /* FIXME: store data in the URL cache here */
3622 return TRUE;
3626 /***********************************************************************
3627 * HTTP_GetCustomHeaderIndex (internal)
3629 * Return index of custom header from header array
3632 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
3633 int requested_index, BOOL request_only)
3635 DWORD index;
3637 TRACE("%s\n", debugstr_w(lpszField));
3639 for (index = 0; index < lpwhr->nCustHeaders; index++)
3641 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3642 continue;
3644 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3645 continue;
3647 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3648 continue;
3650 if (requested_index == 0)
3651 break;
3652 requested_index --;
3655 if (index >= lpwhr->nCustHeaders)
3656 index = -1;
3658 TRACE("Return: %d\n", index);
3659 return index;
3663 /***********************************************************************
3664 * HTTP_InsertCustomHeader (internal)
3666 * Insert header into array
3669 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3671 INT count;
3672 LPHTTPHEADERW lph = NULL;
3673 BOOL r = FALSE;
3675 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3676 count = lpwhr->nCustHeaders + 1;
3677 if (count > 1)
3678 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3679 else
3680 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3682 if (NULL != lph)
3684 lpwhr->pCustHeaders = lph;
3685 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3686 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3687 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3688 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3689 lpwhr->nCustHeaders++;
3690 r = TRUE;
3692 else
3694 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3697 return r;
3701 /***********************************************************************
3702 * HTTP_DeleteCustomHeader (internal)
3704 * Delete header from array
3705 * If this function is called, the indexs may change.
3707 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3709 if( lpwhr->nCustHeaders <= 0 )
3710 return FALSE;
3711 if( index >= lpwhr->nCustHeaders )
3712 return FALSE;
3713 lpwhr->nCustHeaders--;
3715 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3716 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3717 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3719 return TRUE;
3723 /***********************************************************************
3724 * HTTP_VerifyValidHeader (internal)
3726 * Verify the given header is not invalid for the given http request
3729 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
3731 BOOL rc = TRUE;
3733 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
3734 if (strcmpiW(field,szAccept_Encoding)==0)
3735 return FALSE;
3737 return rc;
3740 /***********************************************************************
3741 * IsHostInProxyBypassList (@)
3743 * Undocumented
3746 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3748 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
3749 return FALSE;