wininet: Only clear authentication header if the connection has authentication inform...
[wine/gsoc_dplay.git] / dlls / wininet / http.c
blobda5d2da62b906540721df2ecd3fb9681a9c2c929
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"
58 #include "wincrypt.h"
60 #include "internet.h"
61 #include "wine/debug.h"
62 #include "wine/unicode.h"
64 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
66 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
67 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
68 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
69 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
70 static const WCHAR szHost[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
75 static const WCHAR szGET[] = { 'G','E','T', 0 };
77 #define MAXHOSTNAME 100
78 #define MAX_FIELD_VALUE_LEN 256
79 #define MAX_FIELD_LEN 256
81 #define HTTP_REFERER g_szReferer
82 #define HTTP_ACCEPT g_szAccept
83 #define HTTP_USERAGENT g_szUserAgent
85 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
86 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
87 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
88 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
89 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
90 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
91 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
93 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
95 struct HttpAuthInfo
97 LPWSTR scheme;
98 CredHandle cred;
99 CtxtHandle ctx;
100 TimeStamp exp;
101 ULONG attr;
102 ULONG max_token;
103 void *auth_data;
104 unsigned int auth_data_len;
105 BOOL finished; /* finished authenticating */
108 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
109 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr);
110 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
111 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
112 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
113 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
114 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
115 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
116 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
117 dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
118 lpdwIndex);
119 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
120 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
121 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
122 static void HTTP_DrainContent(WININETHTTPREQW *req);
124 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
126 int HeaderIndex = 0;
127 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
128 if (HeaderIndex == -1)
129 return NULL;
130 else
131 return &req->pCustHeaders[HeaderIndex];
134 /***********************************************************************
135 * HTTP_Tokenize (internal)
137 * Tokenize a string, allocating memory for the tokens.
139 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
141 LPWSTR * token_array;
142 int tokens = 0;
143 int i;
144 LPCWSTR next_token;
146 /* empty string has no tokens */
147 if (*string)
148 tokens++;
149 /* count tokens */
150 for (i = 0; string[i]; i++)
151 if (!strncmpW(string+i, token_string, strlenW(token_string)))
153 DWORD j;
154 tokens++;
155 /* we want to skip over separators, but not the null terminator */
156 for (j = 0; j < strlenW(token_string) - 1; j++)
157 if (!string[i+j])
158 break;
159 i += j;
162 /* add 1 for terminating NULL */
163 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
164 token_array[tokens] = NULL;
165 if (!tokens)
166 return token_array;
167 for (i = 0; i < tokens; i++)
169 int len;
170 next_token = strstrW(string, token_string);
171 if (!next_token) next_token = string+strlenW(string);
172 len = next_token - string;
173 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
174 memcpy(token_array[i], string, len*sizeof(WCHAR));
175 token_array[i][len] = '\0';
176 string = next_token+strlenW(token_string);
178 return token_array;
181 /***********************************************************************
182 * HTTP_FreeTokens (internal)
184 * Frees memory returned from HTTP_Tokenize.
186 static void HTTP_FreeTokens(LPWSTR * token_array)
188 int i;
189 for (i = 0; token_array[i]; i++)
190 HeapFree(GetProcessHeap(), 0, token_array[i]);
191 HeapFree(GetProcessHeap(), 0, token_array);
194 /* **********************************************************************
196 * Helper functions for the HttpSendRequest(Ex) functions
199 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
201 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
202 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
204 TRACE("%p\n", lpwhr);
206 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
207 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
208 req->dwContentLength, req->bEndRequest);
210 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
213 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
215 static const WCHAR szSlash[] = { '/',0 };
216 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
218 /* If we don't have a path we set it to root */
219 if (NULL == lpwhr->lpszPath)
220 lpwhr->lpszPath = WININET_strdupW(szSlash);
221 else /* remove \r and \n*/
223 int nLen = strlenW(lpwhr->lpszPath);
224 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
226 nLen--;
227 lpwhr->lpszPath[nLen]='\0';
229 /* Replace '\' with '/' */
230 while (nLen>0) {
231 nLen--;
232 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
236 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
237 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
238 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
240 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
241 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
242 *fixurl = '/';
243 strcpyW(fixurl + 1, lpwhr->lpszPath);
244 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
245 lpwhr->lpszPath = fixurl;
249 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
251 LPWSTR requestString;
252 DWORD len, n;
253 LPCWSTR *req;
254 UINT i;
255 LPWSTR p;
257 static const WCHAR szSpace[] = { ' ',0 };
258 static const WCHAR szcrlf[] = {'\r','\n', 0};
259 static const WCHAR szColon[] = { ':',' ',0 };
260 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
262 /* allocate space for an array of all the string pointers to be added */
263 len = (lpwhr->nCustHeaders)*4 + 10;
264 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
266 /* add the verb, path and HTTP version string */
267 n = 0;
268 req[n++] = verb;
269 req[n++] = szSpace;
270 req[n++] = path;
271 req[n++] = szSpace;
272 req[n++] = version;
274 /* Append custom request headers */
275 for (i = 0; i < lpwhr->nCustHeaders; i++)
277 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
279 req[n++] = szcrlf;
280 req[n++] = lpwhr->pCustHeaders[i].lpszField;
281 req[n++] = szColon;
282 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
284 TRACE("Adding custom header %s (%s)\n",
285 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
286 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
290 if( n >= len )
291 ERR("oops. buffer overrun\n");
293 req[n] = NULL;
294 requestString = HTTP_build_req( req, 4 );
295 HeapFree( GetProcessHeap(), 0, req );
298 * Set (header) termination string for request
299 * Make sure there's exactly two new lines at the end of the request
301 p = &requestString[strlenW(requestString)-1];
302 while ( (*p == '\n') || (*p == '\r') )
303 p--;
304 strcpyW( p+1, sztwocrlf );
306 return requestString;
309 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
311 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
312 int HeaderIndex;
313 LPHTTPHEADERW setCookieHeader;
315 HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
316 if (HeaderIndex == -1)
317 return;
318 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
320 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
322 int nPosStart = 0, nPosEnd = 0, len;
323 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
325 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
327 LPWSTR buf_cookie, cookie_name, cookie_data;
328 LPWSTR buf_url;
329 LPWSTR domain = NULL;
330 LPHTTPHEADERW Host;
332 int nEqualPos = 0;
333 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
334 setCookieHeader->lpszValue[nPosEnd] != '\0')
336 nPosEnd++;
338 if (setCookieHeader->lpszValue[nPosEnd] == ';')
340 /* fixme: not case sensitive, strcasestr is gnu only */
341 int nDomainPosEnd = 0;
342 int nDomainPosStart = 0, nDomainLength = 0;
343 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
344 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
345 if (lpszDomain)
346 { /* they have specified their own domain, lets use it */
347 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
348 lpszDomain[nDomainPosEnd] != '\0')
350 nDomainPosEnd++;
352 nDomainPosStart = strlenW(szDomain);
353 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
354 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
355 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
358 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
359 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
360 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
361 TRACE("%s\n", debugstr_w(buf_cookie));
362 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
364 nEqualPos++;
366 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
368 HeapFree(GetProcessHeap(), 0, buf_cookie);
369 break;
372 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
373 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
374 cookie_data = &buf_cookie[nEqualPos + 1];
376 Host = HTTP_GetHeader(lpwhr,szHost);
377 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
378 strlenW(lpwhr->lpszPath) + 9;
379 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
380 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
381 InternetSetCookieW(buf_url, cookie_name, cookie_data);
383 HeapFree(GetProcessHeap(), 0, buf_url);
384 HeapFree(GetProcessHeap(), 0, buf_cookie);
385 HeapFree(GetProcessHeap(), 0, cookie_name);
386 HeapFree(GetProcessHeap(), 0, domain);
387 nPosStart = nPosEnd;
392 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
394 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
395 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
396 ((pszAuthValue[ARRAYSIZE(szBasic)] != ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
399 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
400 struct HttpAuthInfo **ppAuthInfo,
401 LPWSTR domain_and_username, LPWSTR password )
403 SECURITY_STATUS sec_status;
404 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
405 BOOL first = FALSE;
407 TRACE("%s\n", debugstr_w(pszAuthValue));
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 PVOID pAuthData;
439 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
441 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
442 if (!pAuthInfo->scheme)
444 HeapFree(GetProcessHeap(), 0, pAuthInfo);
445 return FALSE;
448 if (domain_and_username)
450 WCHAR *user = strchrW(domain_and_username, '\\');
451 WCHAR *domain = domain_and_username;
453 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
455 pAuthData = &nt_auth_identity;
457 if (user) user++;
458 else
460 user = domain_and_username;
461 domain = NULL;
464 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
465 nt_auth_identity.User = user;
466 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
467 nt_auth_identity.Domain = domain;
468 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
469 nt_auth_identity.Password = password;
470 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
472 else
473 /* use default credentials */
474 pAuthData = NULL;
476 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
477 SECPKG_CRED_OUTBOUND, NULL,
478 pAuthData, NULL,
479 NULL, &pAuthInfo->cred,
480 &exp);
481 if (sec_status == SEC_E_OK)
483 PSecPkgInfoW sec_pkg_info;
484 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
485 if (sec_status == SEC_E_OK)
487 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
488 FreeContextBuffer(sec_pkg_info);
491 if (sec_status != SEC_E_OK)
493 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
494 debugstr_w(pAuthInfo->scheme), sec_status);
495 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
496 HeapFree(GetProcessHeap(), 0, pAuthInfo);
497 return FALSE;
500 *ppAuthInfo = pAuthInfo;
502 else if (pAuthInfo->finished)
503 return FALSE;
505 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
506 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
508 ERR("authentication scheme changed from %s to %s\n",
509 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
510 return FALSE;
513 if (is_basic_auth_value(pszAuthValue))
515 int userlen;
516 int passlen;
517 char *auth_data;
519 TRACE("basic authentication\n");
521 /* we don't cache credentials for basic authentication, so we can't
522 * retrieve them if the application didn't pass us any credentials */
523 if (!domain_and_username) return FALSE;
525 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
526 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
528 /* length includes a nul terminator, which will be re-used for the ':' */
529 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
530 if (!auth_data)
531 return FALSE;
533 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
534 auth_data[userlen] = ':';
535 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
537 pAuthInfo->auth_data = auth_data;
538 pAuthInfo->auth_data_len = userlen + 1 + passlen;
539 pAuthInfo->finished = TRUE;
541 return TRUE;
543 else
545 LPCWSTR pszAuthData;
546 SecBufferDesc out_desc, in_desc;
547 SecBuffer out, in;
548 unsigned char *buffer;
549 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
550 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
552 in.BufferType = SECBUFFER_TOKEN;
553 in.cbBuffer = 0;
554 in.pvBuffer = NULL;
556 in_desc.ulVersion = 0;
557 in_desc.cBuffers = 1;
558 in_desc.pBuffers = &in;
560 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
561 if (*pszAuthData == ' ')
563 pszAuthData++;
564 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
565 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
566 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
569 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
571 out.BufferType = SECBUFFER_TOKEN;
572 out.cbBuffer = pAuthInfo->max_token;
573 out.pvBuffer = buffer;
575 out_desc.ulVersion = 0;
576 out_desc.cBuffers = 1;
577 out_desc.pBuffers = &out;
579 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
580 first ? NULL : &pAuthInfo->ctx,
581 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
582 context_req, 0, SECURITY_NETWORK_DREP,
583 in.pvBuffer ? &in_desc : NULL,
584 0, &pAuthInfo->ctx, &out_desc,
585 &pAuthInfo->attr, &pAuthInfo->exp);
586 if (sec_status == SEC_E_OK)
588 pAuthInfo->finished = TRUE;
589 pAuthInfo->auth_data = out.pvBuffer;
590 pAuthInfo->auth_data_len = out.cbBuffer;
591 TRACE("sending last auth packet\n");
593 else if (sec_status == SEC_I_CONTINUE_NEEDED)
595 pAuthInfo->auth_data = out.pvBuffer;
596 pAuthInfo->auth_data_len = out.cbBuffer;
597 TRACE("sending next auth packet\n");
599 else
601 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
602 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
603 return FALSE;
607 return TRUE;
610 /***********************************************************************
611 * HTTP_HttpAddRequestHeadersW (internal)
613 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
614 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
616 LPWSTR lpszStart;
617 LPWSTR lpszEnd;
618 LPWSTR buffer;
619 BOOL bSuccess = FALSE;
620 DWORD len;
622 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
624 if( dwHeaderLength == ~0U )
625 len = strlenW(lpszHeader);
626 else
627 len = dwHeaderLength;
628 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
629 lstrcpynW( buffer, lpszHeader, len + 1);
631 lpszStart = buffer;
635 LPWSTR * pFieldAndValue;
637 lpszEnd = lpszStart;
639 while (*lpszEnd != '\0')
641 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
642 break;
643 lpszEnd++;
646 if (*lpszStart == '\0')
647 break;
649 if (*lpszEnd == '\r')
651 *lpszEnd = '\0';
652 lpszEnd += 2; /* Jump over \r\n */
654 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
655 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
656 if (pFieldAndValue)
658 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
659 if (bSuccess)
660 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
661 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
662 HTTP_FreeTokens(pFieldAndValue);
665 lpszStart = lpszEnd;
666 } while (bSuccess);
668 HeapFree(GetProcessHeap(), 0, buffer);
670 return bSuccess;
673 /***********************************************************************
674 * HttpAddRequestHeadersW (WININET.@)
676 * Adds one or more HTTP header to the request handler
678 * NOTE
679 * On Windows if dwHeaderLength includes the trailing '\0', then
680 * HttpAddRequestHeadersW() adds it too. However this results in an
681 * invalid Http header which is rejected by some servers so we probably
682 * don't need to match Windows on that point.
684 * RETURNS
685 * TRUE on success
686 * FALSE on failure
689 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
690 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
692 BOOL bSuccess = FALSE;
693 LPWININETHTTPREQW lpwhr;
695 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
697 if (!lpszHeader)
698 return TRUE;
700 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
701 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
703 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
704 goto lend;
706 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
707 lend:
708 if( lpwhr )
709 WININET_Release( &lpwhr->hdr );
711 return bSuccess;
714 /***********************************************************************
715 * HttpAddRequestHeadersA (WININET.@)
717 * Adds one or more HTTP header to the request handler
719 * RETURNS
720 * TRUE on success
721 * FALSE on failure
724 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
725 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
727 DWORD len;
728 LPWSTR hdr;
729 BOOL r;
731 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
733 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
734 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
735 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
736 if( dwHeaderLength != ~0U )
737 dwHeaderLength = len;
739 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
741 HeapFree( GetProcessHeap(), 0, hdr );
743 return r;
746 /***********************************************************************
747 * HttpEndRequestA (WININET.@)
749 * Ends an HTTP request that was started by HttpSendRequestEx
751 * RETURNS
752 * TRUE if successful
753 * FALSE on failure
756 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
757 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
759 LPINTERNET_BUFFERSA ptr;
760 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
761 BOOL rc = FALSE;
763 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
764 dwContext);
766 ptr = lpBuffersOut;
767 if (ptr)
768 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
769 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
770 else
771 lpBuffersOutW = NULL;
773 ptrW = lpBuffersOutW;
774 while (ptr)
776 if (ptr->lpvBuffer && ptr->dwBufferLength)
777 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
778 ptrW->dwBufferLength = ptr->dwBufferLength;
779 ptrW->dwBufferTotal= ptr->dwBufferTotal;
781 if (ptr->Next)
782 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
783 sizeof(INTERNET_BUFFERSW));
785 ptr = ptr->Next;
786 ptrW = ptrW->Next;
789 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
791 if (lpBuffersOutW)
793 ptrW = lpBuffersOutW;
794 while (ptrW)
796 LPINTERNET_BUFFERSW ptrW2;
798 FIXME("Do we need to translate info out of these buffer?\n");
800 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
801 ptrW2 = ptrW->Next;
802 HeapFree(GetProcessHeap(),0,ptrW);
803 ptrW = ptrW2;
807 return rc;
810 /***********************************************************************
811 * HttpEndRequestW (WININET.@)
813 * Ends an HTTP request that was started by HttpSendRequestEx
815 * RETURNS
816 * TRUE if successful
817 * FALSE on failure
820 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
821 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
823 BOOL rc = FALSE;
824 LPWININETHTTPREQW lpwhr;
825 INT responseLen;
826 DWORD dwBufferSize;
828 TRACE("-->\n");
829 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
831 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
833 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
834 if (lpwhr)
835 WININET_Release( &lpwhr->hdr );
836 return FALSE;
839 lpwhr->hdr.dwFlags |= dwFlags;
840 lpwhr->hdr.dwContext = dwContext;
842 /* We appear to do nothing with lpBuffersOut.. is that correct? */
844 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
845 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
847 responseLen = HTTP_GetResponseHeaders(lpwhr);
848 if (responseLen)
849 rc = TRUE;
851 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
852 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
854 /* process cookies here. Is this right? */
855 HTTP_ProcessCookies(lpwhr);
857 dwBufferSize = sizeof(lpwhr->dwContentLength);
858 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
859 &lpwhr->dwContentLength,&dwBufferSize,NULL))
860 lpwhr->dwContentLength = -1;
862 if (lpwhr->dwContentLength == 0)
863 HTTP_FinishedReading(lpwhr);
865 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
867 DWORD dwCode,dwCodeLength=sizeof(DWORD);
868 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
869 (dwCode==302 || dwCode==301))
871 WCHAR szNewLocation[2048];
872 dwBufferSize=sizeof(szNewLocation);
873 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
875 /* redirects are always GETs */
876 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
877 lpwhr->lpszVerb = WININET_strdupW(szGET);
878 HTTP_DrainContent(lpwhr);
879 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
880 if (rc)
881 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
886 WININET_Release( &lpwhr->hdr );
887 TRACE("%i <--\n",rc);
888 return rc;
891 /***********************************************************************
892 * HttpOpenRequestW (WININET.@)
894 * Open a HTTP request handle
896 * RETURNS
897 * HINTERNET a HTTP request handle on success
898 * NULL on failure
901 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
902 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
903 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
904 DWORD dwFlags, DWORD_PTR dwContext)
906 LPWININETHTTPSESSIONW lpwhs;
907 HINTERNET handle = NULL;
909 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
910 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
911 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
912 dwFlags, dwContext);
913 if(lpszAcceptTypes!=NULL)
915 int i;
916 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
917 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
920 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
921 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
923 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
924 goto lend;
928 * My tests seem to show that the windows version does not
929 * become asynchronous until after this point. And anyhow
930 * if this call was asynchronous then how would you get the
931 * necessary HINTERNET pointer returned by this function.
934 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
935 lpszVersion, lpszReferrer, lpszAcceptTypes,
936 dwFlags, dwContext);
937 lend:
938 if( lpwhs )
939 WININET_Release( &lpwhs->hdr );
940 TRACE("returning %p\n", handle);
941 return handle;
945 /***********************************************************************
946 * HttpOpenRequestA (WININET.@)
948 * Open a HTTP request handle
950 * RETURNS
951 * HINTERNET a HTTP request handle on success
952 * NULL on failure
955 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
956 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
957 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
958 DWORD dwFlags, DWORD_PTR dwContext)
960 LPWSTR szVerb = NULL, szObjectName = NULL;
961 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
962 INT len;
963 INT acceptTypesCount;
964 HINTERNET rc = FALSE;
965 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
966 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
967 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
968 dwFlags, dwContext);
970 if (lpszVerb)
972 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
973 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
974 if ( !szVerb )
975 goto end;
976 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
979 if (lpszObjectName)
981 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
982 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
983 if ( !szObjectName )
984 goto end;
985 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
988 if (lpszVersion)
990 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
991 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
992 if ( !szVersion )
993 goto end;
994 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
997 if (lpszReferrer)
999 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1000 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1001 if ( !szReferrer )
1002 goto end;
1003 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1006 acceptTypesCount = 0;
1007 if (lpszAcceptTypes)
1009 /* find out how many there are */
1010 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1011 acceptTypesCount++;
1012 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1013 acceptTypesCount = 0;
1014 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1016 len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1017 -1, NULL, 0 );
1018 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1019 if (!szAcceptTypes[acceptTypesCount] )
1020 goto end;
1021 MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1022 -1, szAcceptTypes[acceptTypesCount], len );
1023 acceptTypesCount++;
1025 szAcceptTypes[acceptTypesCount] = NULL;
1027 else szAcceptTypes = 0;
1029 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1030 szVersion, szReferrer,
1031 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1033 end:
1034 if (szAcceptTypes)
1036 acceptTypesCount = 0;
1037 while (szAcceptTypes[acceptTypesCount])
1039 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1040 acceptTypesCount++;
1042 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1044 HeapFree(GetProcessHeap(), 0, szReferrer);
1045 HeapFree(GetProcessHeap(), 0, szVersion);
1046 HeapFree(GetProcessHeap(), 0, szObjectName);
1047 HeapFree(GetProcessHeap(), 0, szVerb);
1049 return rc;
1052 /***********************************************************************
1053 * HTTP_EncodeBase64
1055 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1057 UINT n = 0, x;
1058 static const CHAR HTTP_Base64Enc[] =
1059 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1061 while( len > 0 )
1063 /* first 6 bits, all from bin[0] */
1064 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1065 x = (bin[0] & 3) << 4;
1067 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1068 if( len == 1 )
1070 base64[n++] = HTTP_Base64Enc[x];
1071 base64[n++] = '=';
1072 base64[n++] = '=';
1073 break;
1075 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1076 x = ( bin[1] & 0x0f ) << 2;
1078 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1079 if( len == 2 )
1081 base64[n++] = HTTP_Base64Enc[x];
1082 base64[n++] = '=';
1083 break;
1085 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1087 /* last 6 bits, all from bin [2] */
1088 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1089 bin += 3;
1090 len -= 3;
1092 base64[n] = 0;
1093 return n;
1096 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1097 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1098 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1099 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1100 static const signed char HTTP_Base64Dec[256] =
1102 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1103 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1104 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1105 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1106 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1107 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1108 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1109 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1110 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1111 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1112 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1113 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1114 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1115 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1116 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1117 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1118 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1119 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1120 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1121 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1122 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1123 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1124 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1125 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1126 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1127 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1129 #undef CH
1131 /***********************************************************************
1132 * HTTP_DecodeBase64
1134 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1136 unsigned int n = 0;
1138 while(*base64)
1140 signed char in[4];
1142 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1143 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1144 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1145 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1147 WARN("invalid base64: %s\n", debugstr_w(base64));
1148 return 0;
1150 if (bin)
1151 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1152 n++;
1154 if ((base64[2] == '=') && (base64[3] == '='))
1155 break;
1156 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1157 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1159 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1160 return 0;
1162 if (bin)
1163 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1164 n++;
1166 if (base64[3] == '=')
1167 break;
1168 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1169 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1171 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1172 return 0;
1174 if (bin)
1175 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1176 n++;
1178 base64 += 4;
1181 return n;
1184 /***********************************************************************
1185 * HTTP_InsertAuthorizationForHeader
1187 * Insert or delete the authorization field in the request header.
1189 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1191 if (pAuthInfo)
1193 static const WCHAR wszSpace[] = {' ',0};
1194 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1195 unsigned int len;
1196 WCHAR *authorization = NULL;
1198 if (pAuthInfo->auth_data_len)
1200 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1201 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1202 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1203 if (!authorization)
1204 return FALSE;
1206 strcpyW(authorization, pAuthInfo->scheme);
1207 strcatW(authorization, wszSpace);
1208 HTTP_EncodeBase64(pAuthInfo->auth_data,
1209 pAuthInfo->auth_data_len,
1210 authorization+strlenW(authorization));
1212 /* clear the data as it isn't valid now that it has been sent to the
1213 * server, unless it's Basic authentication which doesn't do
1214 * connection tracking */
1215 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1217 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1218 pAuthInfo->auth_data = NULL;
1219 pAuthInfo->auth_data_len = 0;
1223 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1225 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1227 HeapFree(GetProcessHeap(), 0, authorization);
1229 return TRUE;
1232 /***********************************************************************
1233 * HTTP_DealWithProxy
1235 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1236 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1238 WCHAR buf[MAXHOSTNAME];
1239 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1240 WCHAR* url;
1241 static WCHAR szNul[] = { 0 };
1242 URL_COMPONENTSW UrlComponents;
1243 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
1244 static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
1245 static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1246 int len;
1248 memset( &UrlComponents, 0, sizeof UrlComponents );
1249 UrlComponents.dwStructSize = sizeof UrlComponents;
1250 UrlComponents.lpszHostName = buf;
1251 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1253 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1254 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1255 sprintfW(proxy, szFormat1, hIC->lpszProxy);
1256 else
1257 strcpyW(proxy, hIC->lpszProxy);
1258 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1259 return FALSE;
1260 if( UrlComponents.dwHostNameLength == 0 )
1261 return FALSE;
1263 if( !lpwhr->lpszPath )
1264 lpwhr->lpszPath = szNul;
1265 TRACE("server=%s path=%s\n",
1266 debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
1267 /* for constant 15 see above */
1268 len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
1269 url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1271 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1272 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1274 sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
1276 if( lpwhr->lpszPath[0] != '/' )
1277 strcatW( url, szSlash );
1278 strcatW(url, lpwhr->lpszPath);
1279 if(lpwhr->lpszPath != szNul)
1280 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1281 lpwhr->lpszPath = url;
1283 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1284 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1285 lpwhs->nServerPort = UrlComponents.nPort;
1287 return TRUE;
1290 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1292 char szaddr[32];
1293 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1295 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1296 INTERNET_STATUS_RESOLVING_NAME,
1297 lpwhs->lpszServerName,
1298 strlenW(lpwhs->lpszServerName)+1);
1300 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1301 &lpwhs->socketAddress))
1303 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1304 return FALSE;
1307 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1308 szaddr, sizeof(szaddr));
1309 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1310 INTERNET_STATUS_NAME_RESOLVED,
1311 szaddr, strlen(szaddr)+1);
1312 return TRUE;
1316 /***********************************************************************
1317 * HTTPREQ_Destroy (internal)
1319 * Deallocate request handle
1322 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1324 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1325 DWORD i;
1327 TRACE("\n");
1329 if(lpwhr->hCacheFile)
1330 CloseHandle(lpwhr->hCacheFile);
1332 if(lpwhr->lpszCacheFile) {
1333 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1334 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1337 WININET_Release(&lpwhr->lpHttpSession->hdr);
1339 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1340 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1341 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1342 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1343 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1345 for (i = 0; i < lpwhr->nCustHeaders; i++)
1347 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1348 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1351 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1352 HeapFree(GetProcessHeap(), 0, lpwhr);
1355 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1357 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1358 LPWININETHTTPSESSIONW lpwhs = NULL;
1359 LPWININETAPPINFOW hIC = NULL;
1361 TRACE("%p\n",lpwhr);
1363 if (!NETCON_connected(&lpwhr->netConnection))
1364 return;
1366 if (lpwhr->pAuthInfo)
1368 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1369 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1370 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1371 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1373 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1374 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1375 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1376 lpwhr->pAuthInfo = NULL;
1378 if (lpwhr->pProxyAuthInfo)
1380 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1381 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1382 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1383 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1385 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1386 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1387 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1388 lpwhr->pProxyAuthInfo = NULL;
1391 lpwhs = lpwhr->lpHttpSession;
1392 hIC = lpwhs->lpAppInfo;
1394 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1395 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1397 NETCON_close(&lpwhr->netConnection);
1399 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1400 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1403 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1405 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1407 switch(option) {
1408 case INTERNET_OPTION_HANDLE_TYPE:
1409 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1411 if (*size < sizeof(ULONG))
1412 return ERROR_INSUFFICIENT_BUFFER;
1414 *size = sizeof(DWORD);
1415 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1416 return ERROR_SUCCESS;
1418 case INTERNET_OPTION_URL: {
1419 WCHAR url[INTERNET_MAX_URL_LENGTH];
1420 HTTPHEADERW *host;
1421 DWORD len;
1423 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
1424 static const WCHAR hostW[] = {'H','o','s','t',0};
1426 TRACE("INTERNET_OPTION_URL\n");
1428 host = HTTP_GetHeader(req, hostW);
1429 sprintfW(url, formatW, host->lpszValue, req->lpszPath);
1430 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1432 if(unicode) {
1433 len = (strlenW(url)+1) * sizeof(WCHAR);
1434 if(*size < len)
1435 return ERROR_INSUFFICIENT_BUFFER;
1437 *size = len;
1438 strcpyW(buffer, url);
1439 return ERROR_SUCCESS;
1440 }else {
1441 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1442 if(len > *size)
1443 return ERROR_INSUFFICIENT_BUFFER;
1445 *size = len;
1446 return ERROR_SUCCESS;
1450 case INTERNET_OPTION_DATAFILE_NAME: {
1451 DWORD req_size;
1453 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1455 if(!req->lpszCacheFile) {
1456 *size = 0;
1457 return ERROR_INTERNET_ITEM_NOT_FOUND;
1460 if(unicode) {
1461 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1462 if(*size < req_size)
1463 return ERROR_INSUFFICIENT_BUFFER;
1465 *size = req_size;
1466 memcpy(buffer, req->lpszCacheFile, *size);
1467 return ERROR_SUCCESS;
1468 }else {
1469 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1470 if (req_size > *size)
1471 return ERROR_INSUFFICIENT_BUFFER;
1473 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1474 -1, buffer, *size, NULL, NULL);
1475 return ERROR_SUCCESS;
1479 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1480 PCCERT_CONTEXT context;
1482 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1483 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1484 return ERROR_INSUFFICIENT_BUFFER;
1487 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1488 if(context) {
1489 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1490 DWORD len;
1492 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1493 info->ftExpiry = context->pCertInfo->NotAfter;
1494 info->ftStart = context->pCertInfo->NotBefore;
1495 if(unicode) {
1496 len = CertNameToStrW(context->dwCertEncodingType,
1497 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1498 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1499 if(info->lpszSubjectInfo)
1500 CertNameToStrW(context->dwCertEncodingType,
1501 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1502 info->lpszSubjectInfo, len);
1503 len = CertNameToStrW(context->dwCertEncodingType,
1504 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1505 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1506 if (info->lpszIssuerInfo)
1507 CertNameToStrW(context->dwCertEncodingType,
1508 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1509 info->lpszIssuerInfo, len);
1510 }else {
1511 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1513 len = CertNameToStrA(context->dwCertEncodingType,
1514 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1515 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1516 if(infoA->lpszSubjectInfo)
1517 CertNameToStrA(context->dwCertEncodingType,
1518 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1519 infoA->lpszSubjectInfo, len);
1520 len = CertNameToStrA(context->dwCertEncodingType,
1521 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1522 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1523 if(infoA->lpszIssuerInfo)
1524 CertNameToStrA(context->dwCertEncodingType,
1525 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1526 infoA->lpszIssuerInfo, len);
1530 * Contrary to MSDN, these do not appear to be set.
1531 * lpszProtocolName
1532 * lpszSignatureAlgName
1533 * lpszEncryptionAlgName
1534 * dwKeySize
1536 CertFreeCertificateContext(context);
1537 return ERROR_SUCCESS;
1542 FIXME("Not implemented option %d\n", option);
1543 return ERROR_INTERNET_INVALID_OPTION;
1546 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1548 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1550 switch(option) {
1551 case INTERNET_OPTION_SEND_TIMEOUT:
1552 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1553 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1555 if (size != sizeof(DWORD))
1556 return ERROR_INVALID_PARAMETER;
1558 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1559 *(DWORD*)buffer);
1562 return ERROR_INTERNET_INVALID_OPTION;
1565 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1567 int bytes_read;
1569 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1570 sync ? MSG_WAITALL : 0, &bytes_read)) {
1571 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1572 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1574 /* always returns TRUE, even if the network layer returns an
1575 * error */
1576 *read = 0;
1577 HTTP_FinishedReading(req);
1578 return ERROR_SUCCESS;
1581 req->dwContentRead += bytes_read;
1582 *read = bytes_read;
1584 if(req->lpszCacheFile) {
1585 BOOL res;
1587 res = WriteFile(req->hCacheFile, buffer, bytes_read, NULL, NULL);
1588 if(!res)
1589 WARN("WriteFile failed: %u\n", GetLastError());
1592 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1593 HTTP_FinishedReading(req);
1595 return ERROR_SUCCESS;
1598 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1600 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1602 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1605 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1607 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1608 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1609 INTERNET_ASYNC_RESULT iar;
1610 DWORD res;
1612 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1614 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1615 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1617 iar.dwResult = res == ERROR_SUCCESS;
1618 iar.dwError = res;
1620 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1621 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1622 sizeof(INTERNET_ASYNC_RESULT));
1625 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1626 DWORD flags, DWORD_PTR context)
1629 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1630 DWORD res;
1632 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1633 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1635 if (buffers->dwStructSize != sizeof(*buffers))
1636 return ERROR_INVALID_PARAMETER;
1638 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1640 /* FIXME: IRF_ASYNC may not be the right thing to test here;
1641 * hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC is probably better */
1642 if (flags & IRF_ASYNC) {
1643 DWORD available = 0;
1645 NETCON_query_data_available(&req->netConnection, &available);
1646 if (!available)
1648 WORKREQUEST workRequest;
1650 workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1651 workRequest.hdr = WININET_AddRef(&req->hdr);
1652 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1654 INTERNET_AsyncCall(&workRequest);
1656 return ERROR_IO_PENDING;
1660 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1661 !(flags & IRF_NO_WAIT));
1663 if (res == ERROR_SUCCESS) {
1664 DWORD size = buffers->dwBufferLength;
1665 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1666 &size, sizeof(size));
1669 return res;
1672 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1674 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1676 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1679 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1681 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1682 INTERNET_ASYNC_RESULT iar;
1683 char buffer[4048];
1685 TRACE("%p\n", workRequest->hdr);
1687 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1688 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1689 MSG_PEEK, (int *)&iar.dwError);
1691 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1692 sizeof(INTERNET_ASYNC_RESULT));
1695 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1697 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1698 BYTE buffer[4048];
1699 BOOL async;
1701 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1703 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1704 return ERROR_SUCCESS;
1706 /* Even if we are in async mode, we need to determine whether
1707 * there is actually more data available. We do this by trying
1708 * to peek only a single byte in async mode. */
1709 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1711 if (NETCON_recv(&req->netConnection, buffer,
1712 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1713 MSG_PEEK, (int *)available) && async && *available)
1715 WORKREQUEST workRequest;
1717 *available = 0;
1718 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1719 workRequest.hdr = WININET_AddRef( &req->hdr );
1721 INTERNET_AsyncCall(&workRequest);
1723 return ERROR_IO_PENDING;
1726 return ERROR_SUCCESS;
1729 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1730 HTTPREQ_Destroy,
1731 HTTPREQ_CloseConnection,
1732 HTTPREQ_QueryOption,
1733 HTTPREQ_SetOption,
1734 HTTPREQ_ReadFile,
1735 HTTPREQ_ReadFileExA,
1736 HTTPREQ_WriteFile,
1737 HTTPREQ_QueryDataAvailable,
1738 NULL
1741 /***********************************************************************
1742 * HTTP_HttpOpenRequestW (internal)
1744 * Open a HTTP request handle
1746 * RETURNS
1747 * HINTERNET a HTTP request handle on success
1748 * NULL on failure
1751 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1752 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1753 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1754 DWORD dwFlags, DWORD_PTR dwContext)
1756 LPWININETAPPINFOW hIC = NULL;
1757 LPWININETHTTPREQW lpwhr;
1758 LPWSTR lpszCookies;
1759 LPWSTR lpszUrl = NULL;
1760 DWORD nCookieSize;
1761 HINTERNET handle = NULL;
1762 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1763 DWORD len;
1764 LPHTTPHEADERW Host;
1766 TRACE("-->\n");
1768 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1769 hIC = lpwhs->lpAppInfo;
1771 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1772 if (NULL == lpwhr)
1774 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1775 goto lend;
1777 lpwhr->hdr.htype = WH_HHTTPREQ;
1778 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1779 lpwhr->hdr.dwFlags = dwFlags;
1780 lpwhr->hdr.dwContext = dwContext;
1781 lpwhr->hdr.refs = 1;
1782 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1783 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1785 WININET_AddRef( &lpwhs->hdr );
1786 lpwhr->lpHttpSession = lpwhs;
1787 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1789 handle = WININET_AllocHandle( &lpwhr->hdr );
1790 if (NULL == handle)
1792 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1793 goto lend;
1796 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1798 InternetCloseHandle( handle );
1799 handle = NULL;
1800 goto lend;
1803 if (lpszObjectName && *lpszObjectName) {
1804 HRESULT rc;
1806 len = 0;
1807 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1808 if (rc != E_POINTER)
1809 len = strlenW(lpszObjectName)+1;
1810 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1811 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1812 URL_ESCAPE_SPACES_ONLY);
1813 if (rc)
1815 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1816 strcpyW(lpwhr->lpszPath,lpszObjectName);
1820 if (lpszReferrer && *lpszReferrer)
1821 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1823 if (lpszAcceptTypes)
1825 int i;
1826 for (i = 0; lpszAcceptTypes[i]; i++)
1828 if (!*lpszAcceptTypes[i]) continue;
1829 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1830 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1831 HTTP_ADDHDR_FLAG_REQ |
1832 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1836 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1838 if (lpszVersion)
1839 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1840 else
1841 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1843 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1845 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1846 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1847 INTERNET_DEFAULT_HTTPS_PORT :
1848 INTERNET_DEFAULT_HTTP_PORT);
1849 lpwhs->nHostPort = lpwhs->nServerPort;
1851 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1852 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1854 if (hIC->lpszAgent)
1856 WCHAR *agent_header;
1857 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1859 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1860 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1861 sprintfW(agent_header, user_agent, hIC->lpszAgent );
1863 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1864 HTTP_ADDREQ_FLAG_ADD);
1865 HeapFree(GetProcessHeap(), 0, agent_header);
1868 Host = HTTP_GetHeader(lpwhr,szHost);
1870 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1871 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1872 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1874 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1875 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1877 int cnt = 0;
1878 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1879 static const WCHAR szcrlf[] = {'\r','\n',0};
1881 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1883 cnt += sprintfW(lpszCookies, szCookie);
1884 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1885 strcatW(lpszCookies, szcrlf);
1887 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1888 HTTP_ADDREQ_FLAG_ADD);
1889 HeapFree(GetProcessHeap(), 0, lpszCookies);
1891 HeapFree(GetProcessHeap(), 0, lpszUrl);
1894 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1895 INTERNET_STATUS_HANDLE_CREATED, &handle,
1896 sizeof(handle));
1899 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1902 if (!HTTP_ResolveName(lpwhr))
1904 InternetCloseHandle( handle );
1905 handle = NULL;
1908 lend:
1909 if( lpwhr )
1910 WININET_Release( &lpwhr->hdr );
1912 TRACE("<-- %p (%p)\n", handle, lpwhr);
1913 return handle;
1916 /* read any content returned by the server so that the connection can be
1917 * reused */
1918 static void HTTP_DrainContent(WININETHTTPREQW *req)
1920 DWORD bytes_read;
1922 if (!NETCON_connected(&req->netConnection)) return;
1924 if (req->dwContentLength == -1)
1925 NETCON_close(&req->netConnection);
1929 char buffer[2048];
1930 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
1931 return;
1932 } while (bytes_read);
1935 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1936 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1937 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1938 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1939 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1940 static const WCHAR szAge[] = { 'A','g','e',0 };
1941 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1942 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1943 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1944 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1945 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1946 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1947 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1948 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1949 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1950 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1951 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1952 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 };
1953 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1954 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1955 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1956 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1957 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1958 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1959 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1960 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1961 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1962 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1963 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1964 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1965 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1966 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1967 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1968 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1969 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1970 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1971 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1972 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1973 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1974 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1975 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1976 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1977 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1978 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1979 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 };
1980 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1981 static const WCHAR szURI[] = { 'U','R','I',0 };
1982 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1983 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1984 static const WCHAR szVia[] = { 'V','i','a',0 };
1985 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1986 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1988 static const LPCWSTR header_lookup[] = {
1989 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
1990 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
1991 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1992 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
1993 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1994 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
1995 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
1996 szAllow, /* HTTP_QUERY_ALLOW = 7 */
1997 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
1998 szDate, /* HTTP_QUERY_DATE = 9 */
1999 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2000 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2001 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2002 szURI, /* HTTP_QUERY_URI = 13 */
2003 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2004 NULL, /* HTTP_QUERY_COST = 15 */
2005 NULL, /* HTTP_QUERY_LINK = 16 */
2006 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2007 NULL, /* HTTP_QUERY_VERSION = 18 */
2008 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2009 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2010 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2011 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2012 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2013 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2014 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2015 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2016 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2017 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2018 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2019 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2020 NULL, /* HTTP_QUERY_FROM = 31 */
2021 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2022 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2023 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2024 szReferer, /* HTTP_QUERY_REFERER = 35 */
2025 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2026 szServer, /* HTTP_QUERY_SERVER = 37 */
2027 NULL, /* HTTP_TITLE = 38 */
2028 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2029 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2030 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2031 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2032 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2033 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2034 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2035 NULL, /* HTTP_QUERY_REFRESH = 46 */
2036 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2037 szAge, /* HTTP_QUERY_AGE = 48 */
2038 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2039 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2040 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2041 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2042 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2043 szETag, /* HTTP_QUERY_ETAG = 54 */
2044 szHost, /* HTTP_QUERY_HOST = 55 */
2045 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2046 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2047 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2048 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2049 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2050 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2051 szRange, /* HTTP_QUERY_RANGE = 62 */
2052 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2053 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2054 szVary, /* HTTP_QUERY_VARY = 65 */
2055 szVia, /* HTTP_QUERY_VIA = 66 */
2056 szWarning, /* HTTP_QUERY_WARNING = 67 */
2057 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2058 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2059 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2062 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2064 /***********************************************************************
2065 * HTTP_HttpQueryInfoW (internal)
2067 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2068 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2070 LPHTTPHEADERW lphttpHdr = NULL;
2071 BOOL bSuccess = FALSE;
2072 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2073 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2074 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2075 INT index = -1;
2077 /* Find requested header structure */
2078 switch (level)
2080 case HTTP_QUERY_CUSTOM:
2081 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2082 break;
2084 case HTTP_QUERY_RAW_HEADERS_CRLF:
2086 LPWSTR headers;
2087 DWORD len;
2088 BOOL ret;
2090 if (request_only)
2091 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2092 else
2093 headers = lpwhr->lpszRawHeaders;
2095 len = strlenW(headers);
2096 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2098 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2099 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2100 ret = FALSE;
2101 } else
2103 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
2104 *lpdwBufferLength = len * sizeof(WCHAR);
2106 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2107 ret = TRUE;
2110 if (request_only)
2111 HeapFree(GetProcessHeap(), 0, headers);
2112 return ret;
2114 case HTTP_QUERY_RAW_HEADERS:
2116 static const WCHAR szCrLf[] = {'\r','\n',0};
2117 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2118 DWORD i, size = 0;
2119 LPWSTR pszString = (WCHAR*)lpBuffer;
2121 for (i = 0; ppszRawHeaderLines[i]; i++)
2122 size += strlenW(ppszRawHeaderLines[i]) + 1;
2124 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2126 HTTP_FreeTokens(ppszRawHeaderLines);
2127 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2128 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2129 return FALSE;
2132 for (i = 0; ppszRawHeaderLines[i]; i++)
2134 DWORD len = strlenW(ppszRawHeaderLines[i]);
2135 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2136 pszString += len+1;
2138 *pszString = '\0';
2140 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
2142 *lpdwBufferLength = size * sizeof(WCHAR);
2143 HTTP_FreeTokens(ppszRawHeaderLines);
2145 return TRUE;
2147 case HTTP_QUERY_STATUS_TEXT:
2148 if (lpwhr->lpszStatusText)
2150 DWORD len = strlenW(lpwhr->lpszStatusText);
2151 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2153 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2154 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2155 return FALSE;
2157 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
2158 *lpdwBufferLength = len * sizeof(WCHAR);
2160 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2162 return TRUE;
2164 break;
2165 case HTTP_QUERY_VERSION:
2166 if (lpwhr->lpszVersion)
2168 DWORD len = strlenW(lpwhr->lpszVersion);
2169 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2171 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2172 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2173 return FALSE;
2175 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
2176 *lpdwBufferLength = len * sizeof(WCHAR);
2178 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2180 return TRUE;
2182 break;
2183 default:
2184 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2186 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
2187 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2188 requested_index,request_only);
2191 if (index >= 0)
2192 lphttpHdr = &lpwhr->pCustHeaders[index];
2194 /* Ensure header satisfies requested attributes */
2195 if (!lphttpHdr ||
2196 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2197 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2199 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2200 return bSuccess;
2203 if (lpdwIndex)
2204 (*lpdwIndex)++;
2206 /* coalesce value to requested type */
2207 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
2209 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2210 bSuccess = TRUE;
2212 TRACE(" returning number : %d\n", *(int *)lpBuffer);
2214 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
2216 time_t tmpTime;
2217 struct tm tmpTM;
2218 SYSTEMTIME *STHook;
2220 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2222 tmpTM = *gmtime(&tmpTime);
2223 STHook = (SYSTEMTIME *) lpBuffer;
2224 if(STHook==NULL)
2225 return bSuccess;
2227 STHook->wDay = tmpTM.tm_mday;
2228 STHook->wHour = tmpTM.tm_hour;
2229 STHook->wMilliseconds = 0;
2230 STHook->wMinute = tmpTM.tm_min;
2231 STHook->wDayOfWeek = tmpTM.tm_wday;
2232 STHook->wMonth = tmpTM.tm_mon + 1;
2233 STHook->wSecond = tmpTM.tm_sec;
2234 STHook->wYear = tmpTM.tm_year;
2236 bSuccess = TRUE;
2238 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2239 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2240 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2242 else if (lphttpHdr->lpszValue)
2244 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2246 if (len > *lpdwBufferLength)
2248 *lpdwBufferLength = len;
2249 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2250 return bSuccess;
2253 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2254 *lpdwBufferLength = len - sizeof(WCHAR);
2255 bSuccess = TRUE;
2257 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
2259 return bSuccess;
2262 /***********************************************************************
2263 * HttpQueryInfoW (WININET.@)
2265 * Queries for information about an HTTP request
2267 * RETURNS
2268 * TRUE on success
2269 * FALSE on failure
2272 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2273 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2275 BOOL bSuccess = FALSE;
2276 LPWININETHTTPREQW lpwhr;
2278 if (TRACE_ON(wininet)) {
2279 #define FE(x) { x, #x }
2280 static const wininet_flag_info query_flags[] = {
2281 FE(HTTP_QUERY_MIME_VERSION),
2282 FE(HTTP_QUERY_CONTENT_TYPE),
2283 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2284 FE(HTTP_QUERY_CONTENT_ID),
2285 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2286 FE(HTTP_QUERY_CONTENT_LENGTH),
2287 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2288 FE(HTTP_QUERY_ALLOW),
2289 FE(HTTP_QUERY_PUBLIC),
2290 FE(HTTP_QUERY_DATE),
2291 FE(HTTP_QUERY_EXPIRES),
2292 FE(HTTP_QUERY_LAST_MODIFIED),
2293 FE(HTTP_QUERY_MESSAGE_ID),
2294 FE(HTTP_QUERY_URI),
2295 FE(HTTP_QUERY_DERIVED_FROM),
2296 FE(HTTP_QUERY_COST),
2297 FE(HTTP_QUERY_LINK),
2298 FE(HTTP_QUERY_PRAGMA),
2299 FE(HTTP_QUERY_VERSION),
2300 FE(HTTP_QUERY_STATUS_CODE),
2301 FE(HTTP_QUERY_STATUS_TEXT),
2302 FE(HTTP_QUERY_RAW_HEADERS),
2303 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2304 FE(HTTP_QUERY_CONNECTION),
2305 FE(HTTP_QUERY_ACCEPT),
2306 FE(HTTP_QUERY_ACCEPT_CHARSET),
2307 FE(HTTP_QUERY_ACCEPT_ENCODING),
2308 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2309 FE(HTTP_QUERY_AUTHORIZATION),
2310 FE(HTTP_QUERY_CONTENT_ENCODING),
2311 FE(HTTP_QUERY_FORWARDED),
2312 FE(HTTP_QUERY_FROM),
2313 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2314 FE(HTTP_QUERY_LOCATION),
2315 FE(HTTP_QUERY_ORIG_URI),
2316 FE(HTTP_QUERY_REFERER),
2317 FE(HTTP_QUERY_RETRY_AFTER),
2318 FE(HTTP_QUERY_SERVER),
2319 FE(HTTP_QUERY_TITLE),
2320 FE(HTTP_QUERY_USER_AGENT),
2321 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2322 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2323 FE(HTTP_QUERY_ACCEPT_RANGES),
2324 FE(HTTP_QUERY_SET_COOKIE),
2325 FE(HTTP_QUERY_COOKIE),
2326 FE(HTTP_QUERY_REQUEST_METHOD),
2327 FE(HTTP_QUERY_REFRESH),
2328 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2329 FE(HTTP_QUERY_AGE),
2330 FE(HTTP_QUERY_CACHE_CONTROL),
2331 FE(HTTP_QUERY_CONTENT_BASE),
2332 FE(HTTP_QUERY_CONTENT_LOCATION),
2333 FE(HTTP_QUERY_CONTENT_MD5),
2334 FE(HTTP_QUERY_CONTENT_RANGE),
2335 FE(HTTP_QUERY_ETAG),
2336 FE(HTTP_QUERY_HOST),
2337 FE(HTTP_QUERY_IF_MATCH),
2338 FE(HTTP_QUERY_IF_NONE_MATCH),
2339 FE(HTTP_QUERY_IF_RANGE),
2340 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2341 FE(HTTP_QUERY_MAX_FORWARDS),
2342 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2343 FE(HTTP_QUERY_RANGE),
2344 FE(HTTP_QUERY_TRANSFER_ENCODING),
2345 FE(HTTP_QUERY_UPGRADE),
2346 FE(HTTP_QUERY_VARY),
2347 FE(HTTP_QUERY_VIA),
2348 FE(HTTP_QUERY_WARNING),
2349 FE(HTTP_QUERY_CUSTOM)
2351 static const wininet_flag_info modifier_flags[] = {
2352 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2353 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2354 FE(HTTP_QUERY_FLAG_NUMBER),
2355 FE(HTTP_QUERY_FLAG_COALESCE)
2357 #undef FE
2358 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2359 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2360 DWORD i;
2362 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2363 TRACE(" Attribute:");
2364 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2365 if (query_flags[i].val == info) {
2366 TRACE(" %s", query_flags[i].name);
2367 break;
2370 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2371 TRACE(" Unknown (%08x)", info);
2374 TRACE(" Modifier:");
2375 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2376 if (modifier_flags[i].val & info_mod) {
2377 TRACE(" %s", modifier_flags[i].name);
2378 info_mod &= ~ modifier_flags[i].val;
2382 if (info_mod) {
2383 TRACE(" Unknown (%08x)", info_mod);
2385 TRACE("\n");
2388 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2389 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2391 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2392 goto lend;
2395 if (lpBuffer == NULL)
2396 *lpdwBufferLength = 0;
2397 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2398 lpBuffer, lpdwBufferLength, lpdwIndex);
2400 lend:
2401 if( lpwhr )
2402 WININET_Release( &lpwhr->hdr );
2404 TRACE("%d <--\n", bSuccess);
2405 return bSuccess;
2408 /***********************************************************************
2409 * HttpQueryInfoA (WININET.@)
2411 * Queries for information about an HTTP request
2413 * RETURNS
2414 * TRUE on success
2415 * FALSE on failure
2418 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2419 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2421 BOOL result;
2422 DWORD len;
2423 WCHAR* bufferW;
2425 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2426 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2428 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2429 lpdwBufferLength, lpdwIndex );
2432 if (lpBuffer)
2434 DWORD alloclen;
2435 len = (*lpdwBufferLength)*sizeof(WCHAR);
2436 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2438 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2439 if (alloclen < len)
2440 alloclen = len;
2442 else
2443 alloclen = len;
2444 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2445 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2446 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2447 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2448 } else
2450 bufferW = NULL;
2451 len = 0;
2454 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2455 &len, lpdwIndex );
2456 if( result )
2458 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2459 lpBuffer, *lpdwBufferLength, NULL, NULL );
2460 *lpdwBufferLength = len - 1;
2462 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2464 else
2465 /* since the strings being returned from HttpQueryInfoW should be
2466 * only ASCII characters, it is reasonable to assume that all of
2467 * the Unicode characters can be reduced to a single byte */
2468 *lpdwBufferLength = len / sizeof(WCHAR);
2470 HeapFree(GetProcessHeap(), 0, bufferW );
2472 return result;
2475 /***********************************************************************
2476 * HttpSendRequestExA (WININET.@)
2478 * Sends the specified request to the HTTP server and allows chunked
2479 * transfers.
2481 * RETURNS
2482 * Success: TRUE
2483 * Failure: FALSE, call GetLastError() for more information.
2485 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2486 LPINTERNET_BUFFERSA lpBuffersIn,
2487 LPINTERNET_BUFFERSA lpBuffersOut,
2488 DWORD dwFlags, DWORD_PTR dwContext)
2490 INTERNET_BUFFERSW BuffersInW;
2491 BOOL rc = FALSE;
2492 DWORD headerlen;
2493 LPWSTR header = NULL;
2495 TRACE("(%p, %p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersIn,
2496 lpBuffersOut, dwFlags, dwContext);
2498 if (lpBuffersIn)
2500 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2501 if (lpBuffersIn->lpcszHeader)
2503 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2504 lpBuffersIn->dwHeadersLength,0,0);
2505 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2506 if (!(BuffersInW.lpcszHeader = header))
2508 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2509 return FALSE;
2511 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2512 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2513 header, headerlen);
2515 else
2516 BuffersInW.lpcszHeader = NULL;
2517 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2518 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2519 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2520 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2521 BuffersInW.Next = NULL;
2524 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2526 HeapFree(GetProcessHeap(),0,header);
2528 return rc;
2531 /***********************************************************************
2532 * HttpSendRequestExW (WININET.@)
2534 * Sends the specified request to the HTTP server and allows chunked
2535 * transfers
2537 * RETURNS
2538 * Success: TRUE
2539 * Failure: FALSE, call GetLastError() for more information.
2541 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2542 LPINTERNET_BUFFERSW lpBuffersIn,
2543 LPINTERNET_BUFFERSW lpBuffersOut,
2544 DWORD dwFlags, DWORD_PTR dwContext)
2546 BOOL ret = FALSE;
2547 LPWININETHTTPREQW lpwhr;
2548 LPWININETHTTPSESSIONW lpwhs;
2549 LPWININETAPPINFOW hIC;
2551 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2552 lpBuffersOut, dwFlags, dwContext);
2554 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2556 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2558 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2559 goto lend;
2562 lpwhs = lpwhr->lpHttpSession;
2563 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2564 hIC = lpwhs->lpAppInfo;
2565 assert(hIC->hdr.htype == WH_HINIT);
2567 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2569 WORKREQUEST workRequest;
2570 struct WORKREQ_HTTPSENDREQUESTW *req;
2572 workRequest.asyncproc = AsyncHttpSendRequestProc;
2573 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2574 req = &workRequest.u.HttpSendRequestW;
2575 if (lpBuffersIn)
2577 if (lpBuffersIn->lpcszHeader)
2578 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2579 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2580 else
2581 req->lpszHeader = NULL;
2582 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2583 req->lpOptional = lpBuffersIn->lpvBuffer;
2584 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2585 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2587 else
2589 req->lpszHeader = NULL;
2590 req->dwHeaderLength = 0;
2591 req->lpOptional = NULL;
2592 req->dwOptionalLength = 0;
2593 req->dwContentLength = 0;
2596 req->bEndRequest = FALSE;
2598 INTERNET_AsyncCall(&workRequest);
2600 * This is from windows.
2602 INTERNET_SetLastError(ERROR_IO_PENDING);
2604 else
2606 if (lpBuffersIn)
2607 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2608 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2609 lpBuffersIn->dwBufferTotal, FALSE);
2610 else
2611 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2614 lend:
2615 if ( lpwhr )
2616 WININET_Release( &lpwhr->hdr );
2618 TRACE("<---\n");
2619 return ret;
2622 /***********************************************************************
2623 * HttpSendRequestW (WININET.@)
2625 * Sends the specified request to the HTTP server
2627 * RETURNS
2628 * TRUE on success
2629 * FALSE on failure
2632 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2633 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2635 LPWININETHTTPREQW lpwhr;
2636 LPWININETHTTPSESSIONW lpwhs = NULL;
2637 LPWININETAPPINFOW hIC = NULL;
2638 BOOL r;
2640 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2641 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2643 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2644 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2646 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2647 r = FALSE;
2648 goto lend;
2651 lpwhs = lpwhr->lpHttpSession;
2652 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2654 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2655 r = FALSE;
2656 goto lend;
2659 hIC = lpwhs->lpAppInfo;
2660 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2662 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2663 r = FALSE;
2664 goto lend;
2667 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2669 WORKREQUEST workRequest;
2670 struct WORKREQ_HTTPSENDREQUESTW *req;
2672 workRequest.asyncproc = AsyncHttpSendRequestProc;
2673 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2674 req = &workRequest.u.HttpSendRequestW;
2675 if (lpszHeaders)
2677 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2678 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2680 else
2681 req->lpszHeader = 0;
2682 req->dwHeaderLength = dwHeaderLength;
2683 req->lpOptional = lpOptional;
2684 req->dwOptionalLength = dwOptionalLength;
2685 req->dwContentLength = dwOptionalLength;
2686 req->bEndRequest = TRUE;
2688 INTERNET_AsyncCall(&workRequest);
2690 * This is from windows.
2692 INTERNET_SetLastError(ERROR_IO_PENDING);
2693 r = FALSE;
2695 else
2697 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2698 dwHeaderLength, lpOptional, dwOptionalLength,
2699 dwOptionalLength, TRUE);
2701 lend:
2702 if( lpwhr )
2703 WININET_Release( &lpwhr->hdr );
2704 return r;
2707 /***********************************************************************
2708 * HttpSendRequestA (WININET.@)
2710 * Sends the specified request to the HTTP server
2712 * RETURNS
2713 * TRUE on success
2714 * FALSE on failure
2717 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2718 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2720 BOOL result;
2721 LPWSTR szHeaders=NULL;
2722 DWORD nLen=dwHeaderLength;
2723 if(lpszHeaders!=NULL)
2725 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2726 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2727 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2729 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2730 HeapFree(GetProcessHeap(),0,szHeaders);
2731 return result;
2734 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2736 LPHTTPHEADERW host_header;
2738 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2740 host_header = HTTP_GetHeader(req, szHost);
2741 if(!host_header)
2742 return FALSE;
2744 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2745 return TRUE;
2748 /***********************************************************************
2749 * HTTP_HandleRedirect (internal)
2751 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2753 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2754 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2755 WCHAR path[2048];
2757 if(lpszUrl[0]=='/')
2759 /* if it's an absolute path, keep the same session info */
2760 lstrcpynW(path, lpszUrl, 2048);
2762 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2764 TRACE("Redirect through proxy\n");
2765 lstrcpynW(path, lpszUrl, 2048);
2767 else
2769 URL_COMPONENTSW urlComponents;
2770 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2771 static WCHAR szHttp[] = {'h','t','t','p',0};
2772 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2773 DWORD url_length = 0;
2774 LPWSTR orig_url;
2775 LPWSTR combined_url;
2777 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2778 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2779 urlComponents.dwSchemeLength = 0;
2780 urlComponents.lpszHostName = lpwhs->lpszHostName;
2781 urlComponents.dwHostNameLength = 0;
2782 urlComponents.nPort = lpwhs->nHostPort;
2783 urlComponents.lpszUserName = lpwhs->lpszUserName;
2784 urlComponents.dwUserNameLength = 0;
2785 urlComponents.lpszPassword = NULL;
2786 urlComponents.dwPasswordLength = 0;
2787 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2788 urlComponents.dwUrlPathLength = 0;
2789 urlComponents.lpszExtraInfo = NULL;
2790 urlComponents.dwExtraInfoLength = 0;
2792 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2793 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2794 return FALSE;
2796 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2798 /* convert from bytes to characters */
2799 url_length = url_length / sizeof(WCHAR) - 1;
2800 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2802 HeapFree(GetProcessHeap(), 0, orig_url);
2803 return FALSE;
2806 url_length = 0;
2807 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2808 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2810 HeapFree(GetProcessHeap(), 0, orig_url);
2811 return FALSE;
2813 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2815 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2817 HeapFree(GetProcessHeap(), 0, orig_url);
2818 HeapFree(GetProcessHeap(), 0, combined_url);
2819 return FALSE;
2821 HeapFree(GetProcessHeap(), 0, orig_url);
2823 userName[0] = 0;
2824 hostName[0] = 0;
2825 protocol[0] = 0;
2827 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2828 urlComponents.lpszScheme = protocol;
2829 urlComponents.dwSchemeLength = 32;
2830 urlComponents.lpszHostName = hostName;
2831 urlComponents.dwHostNameLength = MAXHOSTNAME;
2832 urlComponents.lpszUserName = userName;
2833 urlComponents.dwUserNameLength = 1024;
2834 urlComponents.lpszPassword = NULL;
2835 urlComponents.dwPasswordLength = 0;
2836 urlComponents.lpszUrlPath = path;
2837 urlComponents.dwUrlPathLength = 2048;
2838 urlComponents.lpszExtraInfo = NULL;
2839 urlComponents.dwExtraInfoLength = 0;
2840 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2842 HeapFree(GetProcessHeap(), 0, combined_url);
2843 return FALSE;
2846 HeapFree(GetProcessHeap(), 0, combined_url);
2848 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2849 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2851 TRACE("redirect from secure page to non-secure page\n");
2852 /* FIXME: warn about from secure redirect to non-secure page */
2853 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2855 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2856 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2858 TRACE("redirect from non-secure page to secure page\n");
2859 /* FIXME: notify about redirect to secure page */
2860 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2863 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2865 if (lstrlenW(protocol)>4) /*https*/
2866 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2867 else /*http*/
2868 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2871 #if 0
2873 * This upsets redirects to binary files on sourceforge.net
2874 * and gives an html page instead of the target file
2875 * Examination of the HTTP request sent by native wininet.dll
2876 * reveals that it doesn't send a referrer in that case.
2877 * Maybe there's a flag that enables this, or maybe a referrer
2878 * shouldn't be added in case of a redirect.
2881 /* consider the current host as the referrer */
2882 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2883 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2884 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2885 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2886 #endif
2888 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2889 lpwhs->lpszServerName = WININET_strdupW(hostName);
2890 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2891 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2892 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2894 int len;
2895 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2896 len = lstrlenW(hostName);
2897 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2898 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2899 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2901 else
2902 lpwhs->lpszHostName = WININET_strdupW(hostName);
2904 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2907 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2908 lpwhs->lpszUserName = NULL;
2909 if (userName[0])
2910 lpwhs->lpszUserName = WININET_strdupW(userName);
2911 lpwhs->nServerPort = urlComponents.nPort;
2913 if (!HTTP_ResolveName(lpwhr))
2914 return FALSE;
2916 NETCON_close(&lpwhr->netConnection);
2918 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2919 return FALSE;
2922 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2923 lpwhr->lpszPath=NULL;
2924 if (*path)
2926 DWORD needed = 0;
2927 HRESULT rc;
2929 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2930 if (rc != E_POINTER)
2931 needed = strlenW(path)+1;
2932 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2933 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2934 URL_ESCAPE_SPACES_ONLY);
2935 if (rc)
2937 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2938 strcpyW(lpwhr->lpszPath,path);
2942 return TRUE;
2945 /***********************************************************************
2946 * HTTP_build_req (internal)
2948 * concatenate all the strings in the request together
2950 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2952 LPCWSTR *t;
2953 LPWSTR str;
2955 for( t = list; *t ; t++ )
2956 len += strlenW( *t );
2957 len++;
2959 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2960 *str = 0;
2962 for( t = list; *t ; t++ )
2963 strcatW( str, *t );
2965 return str;
2968 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2970 LPWSTR lpszPath;
2971 LPWSTR requestString;
2972 INT len;
2973 INT cnt;
2974 INT responseLen;
2975 char *ascii_req;
2976 BOOL ret;
2977 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2978 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2979 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2981 TRACE("\n");
2983 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2984 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2985 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
2986 HeapFree( GetProcessHeap(), 0, lpszPath );
2988 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2989 NULL, 0, NULL, NULL );
2990 len--; /* the nul terminator isn't needed */
2991 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2992 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2993 ascii_req, len, NULL, NULL );
2994 HeapFree( GetProcessHeap(), 0, requestString );
2996 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2998 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2999 HeapFree( GetProcessHeap(), 0, ascii_req );
3000 if (!ret || cnt < 0)
3001 return FALSE;
3003 responseLen = HTTP_GetResponseHeaders( lpwhr );
3004 if (!responseLen)
3005 return FALSE;
3007 return TRUE;
3010 /***********************************************************************
3011 * HTTP_HttpSendRequestW (internal)
3013 * Sends the specified request to the HTTP server
3015 * RETURNS
3016 * TRUE on success
3017 * FALSE on failure
3020 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3021 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3022 DWORD dwContentLength, BOOL bEndRequest)
3024 INT cnt;
3025 BOOL bSuccess = FALSE;
3026 LPWSTR requestString = NULL;
3027 INT responseLen;
3028 BOOL loop_next;
3029 INTERNET_ASYNC_RESULT iar;
3030 static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
3031 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3032 static const WCHAR szContentLength[] =
3033 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3034 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3036 TRACE("--> %p\n", lpwhr);
3038 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3040 /* Clear any error information */
3041 INTERNET_SetLastError(0);
3043 /* if the verb is NULL default to GET */
3044 if (!lpwhr->lpszVerb)
3045 lpwhr->lpszVerb = WININET_strdupW(szGET);
3047 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
3049 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3050 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3055 DWORD len;
3056 char *ascii_req;
3058 loop_next = FALSE;
3060 /* like native, just in case the caller forgot to call InternetReadFile
3061 * for all the data */
3062 HTTP_DrainContent(lpwhr);
3063 lpwhr->dwContentRead = 0;
3065 if (TRACE_ON(wininet))
3067 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3068 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3071 HTTP_FixURL(lpwhr);
3072 HTTP_ProcessHeader(lpwhr, szConnection,
3073 lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
3074 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3076 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3077 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3079 /* add the headers the caller supplied */
3080 if( lpszHeaders && dwHeaderLength )
3082 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3083 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3086 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3088 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3090 /* Send the request and store the results */
3091 if (!HTTP_OpenConnection(lpwhr))
3092 goto lend;
3094 /* send the request as ASCII, tack on the optional data */
3095 if( !lpOptional )
3096 dwOptionalLength = 0;
3097 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3098 NULL, 0, NULL, NULL );
3099 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3100 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3101 ascii_req, len, NULL, NULL );
3102 if( lpOptional )
3103 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3104 len = (len + dwOptionalLength - 1);
3105 ascii_req[len] = 0;
3106 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3108 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3109 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3111 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3112 HeapFree( GetProcessHeap(), 0, ascii_req );
3114 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3115 INTERNET_STATUS_REQUEST_SENT,
3116 &len, sizeof(DWORD));
3118 if (bEndRequest)
3120 DWORD dwBufferSize;
3121 DWORD dwStatusCode;
3123 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3124 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3126 if (cnt < 0)
3127 goto lend;
3129 responseLen = HTTP_GetResponseHeaders(lpwhr);
3130 if (responseLen)
3131 bSuccess = TRUE;
3133 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3134 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3135 sizeof(DWORD));
3137 HTTP_ProcessCookies(lpwhr);
3139 dwBufferSize = sizeof(lpwhr->dwContentLength);
3140 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3141 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3142 lpwhr->dwContentLength = -1;
3144 if (lpwhr->dwContentLength == 0)
3145 HTTP_FinishedReading(lpwhr);
3147 dwBufferSize = sizeof(dwStatusCode);
3148 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3149 &dwStatusCode,&dwBufferSize,NULL))
3150 dwStatusCode = 0;
3152 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3154 WCHAR szNewLocation[2048];
3155 dwBufferSize=sizeof(szNewLocation);
3156 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3157 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3159 HTTP_DrainContent(lpwhr);
3160 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3161 INTERNET_STATUS_REDIRECT, szNewLocation,
3162 dwBufferSize);
3163 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3164 if (bSuccess)
3166 HeapFree(GetProcessHeap(), 0, requestString);
3167 loop_next = TRUE;
3171 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3173 WCHAR szAuthValue[2048];
3174 dwBufferSize=2048;
3175 if (dwStatusCode == HTTP_STATUS_DENIED)
3177 DWORD dwIndex = 0;
3178 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3180 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3181 &lpwhr->pAuthInfo,
3182 lpwhr->lpHttpSession->lpszUserName,
3183 lpwhr->lpHttpSession->lpszPassword))
3185 loop_next = TRUE;
3186 break;
3190 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3192 DWORD dwIndex = 0;
3193 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3195 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3196 &lpwhr->pProxyAuthInfo,
3197 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3198 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3200 loop_next = TRUE;
3201 break;
3207 else
3208 bSuccess = TRUE;
3210 while (loop_next);
3212 /* FIXME: Better check, when we have to create the cache file */
3213 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3214 WCHAR url[INTERNET_MAX_URL_LENGTH];
3215 WCHAR cacheFileName[MAX_PATH+1];
3216 BOOL b;
3218 b = HTTP_GetRequestURL(lpwhr, url);
3219 if(!b) {
3220 WARN("Could not get URL\n");
3221 goto lend;
3224 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3225 if(b) {
3226 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3227 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3228 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3229 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3230 WARN("Could not create file: %u\n", GetLastError());
3231 lpwhr->hCacheFile = NULL;
3233 }else {
3234 WARN("Could not create cache entry: %08x\n", GetLastError());
3238 lend:
3240 HeapFree(GetProcessHeap(), 0, requestString);
3242 /* TODO: send notification for P3P header */
3244 iar.dwResult = (DWORD)bSuccess;
3245 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
3247 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3248 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3249 sizeof(INTERNET_ASYNC_RESULT));
3251 TRACE("<--\n");
3252 return bSuccess;
3255 /***********************************************************************
3256 * HTTPSESSION_Destroy (internal)
3258 * Deallocate session handle
3261 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3263 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3265 TRACE("%p\n", lpwhs);
3267 WININET_Release(&lpwhs->lpAppInfo->hdr);
3269 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3270 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3271 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3272 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3273 HeapFree(GetProcessHeap(), 0, lpwhs);
3276 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3278 switch(option) {
3279 case INTERNET_OPTION_HANDLE_TYPE:
3280 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3282 if (*size < sizeof(ULONG))
3283 return ERROR_INSUFFICIENT_BUFFER;
3285 *size = sizeof(DWORD);
3286 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3287 return ERROR_SUCCESS;
3290 FIXME("Not implemented option %d\n", option);
3291 return ERROR_INTERNET_INVALID_OPTION;
3294 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3295 HTTPSESSION_Destroy,
3296 NULL,
3297 HTTPSESSION_QueryOption,
3298 NULL,
3299 NULL,
3300 NULL,
3301 NULL,
3302 NULL,
3303 NULL
3307 /***********************************************************************
3308 * HTTP_Connect (internal)
3310 * Create http session handle
3312 * RETURNS
3313 * HINTERNET a session handle on success
3314 * NULL on failure
3317 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3318 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3319 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3320 DWORD dwInternalFlags)
3322 BOOL bSuccess = FALSE;
3323 LPWININETHTTPSESSIONW lpwhs = NULL;
3324 HINTERNET handle = NULL;
3326 TRACE("-->\n");
3328 if (!lpszServerName || !lpszServerName[0])
3330 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3331 goto lerror;
3334 assert( hIC->hdr.htype == WH_HINIT );
3336 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3337 if (NULL == lpwhs)
3339 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3340 goto lerror;
3344 * According to my tests. The name is not resolved until a request is sent
3347 lpwhs->hdr.htype = WH_HHTTPSESSION;
3348 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3349 lpwhs->hdr.dwFlags = dwFlags;
3350 lpwhs->hdr.dwContext = dwContext;
3351 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3352 lpwhs->hdr.refs = 1;
3353 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3355 WININET_AddRef( &hIC->hdr );
3356 lpwhs->lpAppInfo = hIC;
3357 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3359 handle = WININET_AllocHandle( &lpwhs->hdr );
3360 if (NULL == handle)
3362 ERR("Failed to alloc handle\n");
3363 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3364 goto lerror;
3367 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3368 if(strchrW(hIC->lpszProxy, ' '))
3369 FIXME("Several proxies not implemented.\n");
3370 if(hIC->lpszProxyBypass)
3371 FIXME("Proxy bypass is ignored.\n");
3373 if (lpszServerName && lpszServerName[0])
3375 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3376 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3378 if (lpszUserName && lpszUserName[0])
3379 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3380 if (lpszPassword && lpszPassword[0])
3381 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3382 lpwhs->nServerPort = nServerPort;
3383 lpwhs->nHostPort = nServerPort;
3385 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3386 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3388 INTERNET_SendCallback(&hIC->hdr, dwContext,
3389 INTERNET_STATUS_HANDLE_CREATED, &handle,
3390 sizeof(handle));
3393 bSuccess = TRUE;
3395 lerror:
3396 if( lpwhs )
3397 WININET_Release( &lpwhs->hdr );
3400 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3401 * windows
3404 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3405 return handle;
3409 /***********************************************************************
3410 * HTTP_OpenConnection (internal)
3412 * Connect to a web server
3414 * RETURNS
3416 * TRUE on success
3417 * FALSE on failure
3419 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3421 BOOL bSuccess = FALSE;
3422 LPWININETHTTPSESSIONW lpwhs;
3423 LPWININETAPPINFOW hIC = NULL;
3424 char szaddr[32];
3426 TRACE("-->\n");
3429 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3431 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3432 goto lend;
3435 if (NETCON_connected(&lpwhr->netConnection))
3437 bSuccess = TRUE;
3438 goto lend;
3441 lpwhs = lpwhr->lpHttpSession;
3443 hIC = lpwhs->lpAppInfo;
3444 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3445 szaddr, sizeof(szaddr));
3446 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3447 INTERNET_STATUS_CONNECTING_TO_SERVER,
3448 szaddr,
3449 strlen(szaddr)+1);
3451 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3452 SOCK_STREAM, 0))
3454 WARN("Socket creation failed\n");
3455 goto lend;
3458 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3459 sizeof(lpwhs->socketAddress)))
3460 goto lend;
3462 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3464 /* Note: we differ from Microsoft's WinINet here. they seem to have
3465 * a bug that causes no status callbacks to be sent when starting
3466 * a tunnel to a proxy server using the CONNECT verb. i believe our
3467 * behaviour to be more correct and to not cause any incompatibilities
3468 * because using a secure connection through a proxy server is a rare
3469 * case that would be hard for anyone to depend on */
3470 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3471 goto lend;
3473 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3475 WARN("Couldn't connect securely to host\n");
3476 goto lend;
3480 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3481 INTERNET_STATUS_CONNECTED_TO_SERVER,
3482 szaddr, strlen(szaddr)+1);
3484 bSuccess = TRUE;
3486 lend:
3487 TRACE("%d <--\n", bSuccess);
3488 return bSuccess;
3492 /***********************************************************************
3493 * HTTP_clear_response_headers (internal)
3495 * clear out any old response headers
3497 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3499 DWORD i;
3501 for( i=0; i<lpwhr->nCustHeaders; i++)
3503 if( !lpwhr->pCustHeaders[i].lpszField )
3504 continue;
3505 if( !lpwhr->pCustHeaders[i].lpszValue )
3506 continue;
3507 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3508 continue;
3509 HTTP_DeleteCustomHeader( lpwhr, i );
3510 i--;
3514 /***********************************************************************
3515 * HTTP_GetResponseHeaders (internal)
3517 * Read server response
3519 * RETURNS
3521 * TRUE on success
3522 * FALSE on error
3524 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
3526 INT cbreaks = 0;
3527 WCHAR buffer[MAX_REPLY_LEN];
3528 DWORD buflen = MAX_REPLY_LEN;
3529 BOOL bSuccess = FALSE;
3530 INT rc = 0;
3531 static const WCHAR szCrLf[] = {'\r','\n',0};
3532 static const WCHAR szHundred[] = {'1','0','0',0};
3533 char bufferA[MAX_REPLY_LEN];
3534 LPWSTR status_code, status_text;
3535 DWORD cchMaxRawHeaders = 1024;
3536 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3537 DWORD cchRawHeaders = 0;
3539 TRACE("-->\n");
3541 /* clear old response headers (eg. from a redirect response) */
3542 HTTP_clear_response_headers( lpwhr );
3544 if (!NETCON_connected(&lpwhr->netConnection))
3545 goto lend;
3547 do {
3549 * HACK peek at the buffer
3551 buflen = MAX_REPLY_LEN;
3552 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3555 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3557 memset(buffer, 0, MAX_REPLY_LEN);
3558 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3559 goto lend;
3560 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3562 /* split the version from the status code */
3563 status_code = strchrW( buffer, ' ' );
3564 if( !status_code )
3565 goto lend;
3566 *status_code++=0;
3568 /* split the status code from the status text */
3569 status_text = strchrW( status_code, ' ' );
3570 if( !status_text )
3571 goto lend;
3572 *status_text++=0;
3574 TRACE("version [%s] status code [%s] status text [%s]\n",
3575 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3577 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3579 /* Add status code */
3580 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3581 HTTP_ADDHDR_FLAG_REPLACE);
3583 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3584 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3586 lpwhr->lpszVersion= WININET_strdupW(buffer);
3587 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3589 /* Restore the spaces */
3590 *(status_code-1) = ' ';
3591 *(status_text-1) = ' ';
3593 /* regenerate raw headers */
3594 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3596 cchMaxRawHeaders *= 2;
3597 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3599 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3600 cchRawHeaders += (buflen-1);
3601 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3602 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3603 lpszRawHeaders[cchRawHeaders] = '\0';
3605 /* Parse each response line */
3608 buflen = MAX_REPLY_LEN;
3609 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3611 LPWSTR * pFieldAndValue;
3613 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3614 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3616 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3618 cchMaxRawHeaders *= 2;
3619 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3621 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3622 cchRawHeaders += (buflen-1);
3623 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3624 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3625 lpszRawHeaders[cchRawHeaders] = '\0';
3627 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3628 if (!pFieldAndValue)
3629 break;
3631 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3632 HTTP_ADDREQ_FLAG_ADD );
3634 HTTP_FreeTokens(pFieldAndValue);
3636 else
3638 cbreaks++;
3639 if (cbreaks >= 2)
3640 break;
3642 }while(1);
3644 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3645 lpwhr->lpszRawHeaders = lpszRawHeaders;
3646 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3647 bSuccess = TRUE;
3649 lend:
3651 TRACE("<--\n");
3652 if (bSuccess)
3653 return rc;
3654 else
3655 return 0;
3659 static void strip_spaces(LPWSTR start)
3661 LPWSTR str = start;
3662 LPWSTR end;
3664 while (*str == ' ' && *str != '\0')
3665 str++;
3667 if (str != start)
3668 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3670 end = start + strlenW(start) - 1;
3671 while (end >= start && *end == ' ')
3673 *end = '\0';
3674 end--;
3679 /***********************************************************************
3680 * HTTP_InterpretHttpHeader (internal)
3682 * Parse server response
3684 * RETURNS
3686 * Pointer to array of field, value, NULL on success.
3687 * NULL on error.
3689 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3691 LPWSTR * pTokenPair;
3692 LPWSTR pszColon;
3693 INT len;
3695 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3697 pszColon = strchrW(buffer, ':');
3698 /* must have two tokens */
3699 if (!pszColon)
3701 HTTP_FreeTokens(pTokenPair);
3702 if (buffer[0])
3703 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3704 return NULL;
3707 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3708 if (!pTokenPair[0])
3710 HTTP_FreeTokens(pTokenPair);
3711 return NULL;
3713 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3714 pTokenPair[0][pszColon - buffer] = '\0';
3716 /* skip colon */
3717 pszColon++;
3718 len = strlenW(pszColon);
3719 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3720 if (!pTokenPair[1])
3722 HTTP_FreeTokens(pTokenPair);
3723 return NULL;
3725 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3727 strip_spaces(pTokenPair[0]);
3728 strip_spaces(pTokenPair[1]);
3730 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3731 return pTokenPair;
3734 /***********************************************************************
3735 * HTTP_ProcessHeader (internal)
3737 * Stuff header into header tables according to <dwModifier>
3741 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3743 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3745 LPHTTPHEADERW lphttpHdr = NULL;
3746 BOOL bSuccess = FALSE;
3747 INT index = -1;
3748 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3750 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3752 /* REPLACE wins out over ADD */
3753 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3754 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3756 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3757 index = -1;
3758 else
3759 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3761 if (index >= 0)
3763 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3765 return FALSE;
3767 lphttpHdr = &lpwhr->pCustHeaders[index];
3769 else if (value)
3771 HTTPHEADERW hdr;
3773 hdr.lpszField = (LPWSTR)field;
3774 hdr.lpszValue = (LPWSTR)value;
3775 hdr.wFlags = hdr.wCount = 0;
3777 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3778 hdr.wFlags |= HDR_ISREQUEST;
3780 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3782 /* no value to delete */
3783 else return TRUE;
3785 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3786 lphttpHdr->wFlags |= HDR_ISREQUEST;
3787 else
3788 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3790 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3792 HTTP_DeleteCustomHeader( lpwhr, index );
3794 if (value)
3796 HTTPHEADERW hdr;
3798 hdr.lpszField = (LPWSTR)field;
3799 hdr.lpszValue = (LPWSTR)value;
3800 hdr.wFlags = hdr.wCount = 0;
3802 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3803 hdr.wFlags |= HDR_ISREQUEST;
3805 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3808 return TRUE;
3810 else if (dwModifier & COALESCEFLAGS)
3812 LPWSTR lpsztmp;
3813 WCHAR ch = 0;
3814 INT len = 0;
3815 INT origlen = strlenW(lphttpHdr->lpszValue);
3816 INT valuelen = strlenW(value);
3818 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3820 ch = ',';
3821 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3823 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3825 ch = ';';
3826 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3829 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3831 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3832 if (lpsztmp)
3834 lphttpHdr->lpszValue = lpsztmp;
3835 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3836 if (ch > 0)
3838 lphttpHdr->lpszValue[origlen] = ch;
3839 origlen++;
3840 lphttpHdr->lpszValue[origlen] = ' ';
3841 origlen++;
3844 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3845 lphttpHdr->lpszValue[len] = '\0';
3846 bSuccess = TRUE;
3848 else
3850 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3851 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3854 TRACE("<-- %d\n",bSuccess);
3855 return bSuccess;
3859 /***********************************************************************
3860 * HTTP_FinishedReading (internal)
3862 * Called when all content from server has been read by client.
3865 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
3867 WCHAR szConnectionResponse[20];
3868 DWORD dwBufferSize = sizeof(szConnectionResponse);
3870 TRACE("\n");
3872 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse,
3873 &dwBufferSize, NULL) ||
3874 strcmpiW(szConnectionResponse, szKeepAlive))
3876 HTTPREQ_CloseConnection(&lpwhr->hdr);
3879 /* FIXME: store data in the URL cache here */
3881 return TRUE;
3885 /***********************************************************************
3886 * HTTP_GetCustomHeaderIndex (internal)
3888 * Return index of custom header from header array
3891 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
3892 int requested_index, BOOL request_only)
3894 DWORD index;
3896 TRACE("%s\n", debugstr_w(lpszField));
3898 for (index = 0; index < lpwhr->nCustHeaders; index++)
3900 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3901 continue;
3903 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3904 continue;
3906 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3907 continue;
3909 if (requested_index == 0)
3910 break;
3911 requested_index --;
3914 if (index >= lpwhr->nCustHeaders)
3915 index = -1;
3917 TRACE("Return: %d\n", index);
3918 return index;
3922 /***********************************************************************
3923 * HTTP_InsertCustomHeader (internal)
3925 * Insert header into array
3928 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3930 INT count;
3931 LPHTTPHEADERW lph = NULL;
3932 BOOL r = FALSE;
3934 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3935 count = lpwhr->nCustHeaders + 1;
3936 if (count > 1)
3937 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3938 else
3939 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3941 if (NULL != lph)
3943 lpwhr->pCustHeaders = lph;
3944 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3945 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3946 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3947 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3948 lpwhr->nCustHeaders++;
3949 r = TRUE;
3951 else
3953 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3956 return r;
3960 /***********************************************************************
3961 * HTTP_DeleteCustomHeader (internal)
3963 * Delete header from array
3964 * If this function is called, the indexs may change.
3966 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3968 if( lpwhr->nCustHeaders <= 0 )
3969 return FALSE;
3970 if( index >= lpwhr->nCustHeaders )
3971 return FALSE;
3972 lpwhr->nCustHeaders--;
3974 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3975 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3976 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3978 return TRUE;
3982 /***********************************************************************
3983 * HTTP_VerifyValidHeader (internal)
3985 * Verify the given header is not invalid for the given http request
3988 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
3990 BOOL rc = TRUE;
3992 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
3993 if (strcmpiW(field,szAccept_Encoding)==0)
3994 return FALSE;
3996 return rc;
3999 /***********************************************************************
4000 * IsHostInProxyBypassList (@)
4002 * Undocumented
4005 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4007 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4008 return FALSE;