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
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
30 #include "wine/port.h"
32 #include <sys/types.h>
33 #ifdef HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
36 #ifdef HAVE_ARPA_INET_H
37 # include <arpa/inet.h>
52 #define NO_SHLWAPI_STREAM
53 #define NO_SHLWAPI_REG
54 #define NO_SHLWAPI_STRFCNS
55 #define NO_SHLWAPI_GDI
61 #include "wine/debug.h"
62 #include "wine/unicode.h"
64 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
66 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
67 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
68 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
69 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
70 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
71 static const WCHAR szHost[] = { 'H','o','s','t',0 };
72 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
74 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
75 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
76 static const WCHAR szGET[] = { 'G','E','T', 0 };
77 static const WCHAR szCrLf[] = {'\r','\n', 0};
79 #define MAXHOSTNAME 100
80 #define MAX_FIELD_VALUE_LEN 256
81 #define MAX_FIELD_LEN 256
83 #define HTTP_REFERER g_szReferer
84 #define HTTP_ACCEPT g_szAccept
85 #define HTTP_USERAGENT g_szUserAgent
87 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
88 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
89 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
90 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
91 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
92 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
93 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
95 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
106 unsigned int auth_data_len;
107 BOOL finished; /* finished authenticating */
110 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
111 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
112 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
113 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
114 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
115 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
116 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
117 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
118 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
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)
127 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
128 if (HeaderIndex == -1)
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;
146 /* empty string has no tokens */
150 for (i = 0; string[i]; i++)
151 if (!strncmpW(string+i, token_string, strlenW(token_string)))
155 /* we want to skip over separators, but not the null terminator */
156 for (j = 0; j < strlenW(token_string) - 1; j++)
162 /* add 1 for terminating NULL */
163 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
164 token_array[tokens] = NULL;
167 for (i = 0; i < tokens; i++)
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);
181 /***********************************************************************
182 * HTTP_FreeTokens (internal)
184 * Frees memory returned from HTTP_Tokenize.
186 static void HTTP_FreeTokens(LPWSTR * token_array)
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')))
227 lpwhr->lpszPath[nLen]='\0';
229 /* Replace '\' with '/' */
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));
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;
257 static const WCHAR szSpace[] = { ' ',0 };
258 static const WCHAR szColon[] = { ':',' ',0 };
259 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
261 /* allocate space for an array of all the string pointers to be added */
262 len = (lpwhr->nCustHeaders)*4 + 10;
263 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
265 /* add the verb, path and HTTP version string */
273 /* Append custom request headers */
274 for (i = 0; i < lpwhr->nCustHeaders; i++)
276 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
279 req[n++] = lpwhr->pCustHeaders[i].lpszField;
281 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
283 TRACE("Adding custom header %s (%s)\n",
284 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
285 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
290 ERR("oops. buffer overrun\n");
293 requestString = HTTP_build_req( req, 4 );
294 HeapFree( GetProcessHeap(), 0, req );
297 * Set (header) termination string for request
298 * Make sure there's exactly two new lines at the end of the request
300 p = &requestString[strlenW(requestString)-1];
301 while ( (*p == '\n') || (*p == '\r') )
303 strcpyW( p+1, sztwocrlf );
305 return requestString;
308 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
310 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
312 LPHTTPHEADERW setCookieHeader;
314 HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
315 if (HeaderIndex == -1)
317 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
319 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
321 int nPosStart = 0, nPosEnd = 0, len;
322 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
324 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
326 LPWSTR buf_cookie, cookie_name, cookie_data;
328 LPWSTR domain = NULL;
332 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
333 setCookieHeader->lpszValue[nPosEnd] != '\0')
337 if (setCookieHeader->lpszValue[nPosEnd] == ';')
339 /* fixme: not case sensitive, strcasestr is gnu only */
340 int nDomainPosEnd = 0;
341 int nDomainPosStart = 0, nDomainLength = 0;
342 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
343 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
345 { /* they have specified their own domain, lets use it */
346 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
347 lpszDomain[nDomainPosEnd] != '\0')
351 nDomainPosStart = strlenW(szDomain);
352 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
353 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
354 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
357 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
358 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
359 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
360 TRACE("%s\n", debugstr_w(buf_cookie));
361 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
365 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
367 HeapFree(GetProcessHeap(), 0, buf_cookie);
371 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
372 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
373 cookie_data = &buf_cookie[nEqualPos + 1];
375 Host = HTTP_GetHeader(lpwhr,szHost);
376 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
377 strlenW(lpwhr->lpszPath) + 9;
378 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
379 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
380 InternetSetCookieW(buf_url, cookie_name, cookie_data);
382 HeapFree(GetProcessHeap(), 0, buf_url);
383 HeapFree(GetProcessHeap(), 0, buf_cookie);
384 HeapFree(GetProcessHeap(), 0, cookie_name);
385 HeapFree(GetProcessHeap(), 0, domain);
391 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
393 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
394 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
395 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
398 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
399 struct HttpAuthInfo **ppAuthInfo,
400 LPWSTR domain_and_username, LPWSTR password )
402 SECURITY_STATUS sec_status;
403 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
406 TRACE("%s\n", debugstr_w(pszAuthValue));
413 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
417 SecInvalidateHandle(&pAuthInfo->cred);
418 SecInvalidateHandle(&pAuthInfo->ctx);
419 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
421 pAuthInfo->auth_data = NULL;
422 pAuthInfo->auth_data_len = 0;
423 pAuthInfo->finished = FALSE;
425 if (is_basic_auth_value(pszAuthValue))
427 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
428 pAuthInfo->scheme = WININET_strdupW(szBasic);
429 if (!pAuthInfo->scheme)
431 HeapFree(GetProcessHeap(), 0, pAuthInfo);
438 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
440 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
441 if (!pAuthInfo->scheme)
443 HeapFree(GetProcessHeap(), 0, pAuthInfo);
447 if (domain_and_username)
449 WCHAR *user = strchrW(domain_and_username, '\\');
450 WCHAR *domain = domain_and_username;
452 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
454 pAuthData = &nt_auth_identity;
459 user = domain_and_username;
463 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
464 nt_auth_identity.User = user;
465 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
466 nt_auth_identity.Domain = domain;
467 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
468 nt_auth_identity.Password = password;
469 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
472 /* use default credentials */
475 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
476 SECPKG_CRED_OUTBOUND, NULL,
478 NULL, &pAuthInfo->cred,
480 if (sec_status == SEC_E_OK)
482 PSecPkgInfoW sec_pkg_info;
483 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
484 if (sec_status == SEC_E_OK)
486 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
487 FreeContextBuffer(sec_pkg_info);
490 if (sec_status != SEC_E_OK)
492 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
493 debugstr_w(pAuthInfo->scheme), sec_status);
494 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
495 HeapFree(GetProcessHeap(), 0, pAuthInfo);
499 *ppAuthInfo = pAuthInfo;
501 else if (pAuthInfo->finished)
504 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
505 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
507 ERR("authentication scheme changed from %s to %s\n",
508 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
512 if (is_basic_auth_value(pszAuthValue))
518 TRACE("basic authentication\n");
520 /* we don't cache credentials for basic authentication, so we can't
521 * retrieve them if the application didn't pass us any credentials */
522 if (!domain_and_username) return FALSE;
524 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
525 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
527 /* length includes a nul terminator, which will be re-used for the ':' */
528 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
532 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
533 auth_data[userlen] = ':';
534 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
536 pAuthInfo->auth_data = auth_data;
537 pAuthInfo->auth_data_len = userlen + 1 + passlen;
538 pAuthInfo->finished = TRUE;
545 SecBufferDesc out_desc, in_desc;
547 unsigned char *buffer;
548 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
549 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
551 in.BufferType = SECBUFFER_TOKEN;
555 in_desc.ulVersion = 0;
556 in_desc.cBuffers = 1;
557 in_desc.pBuffers = ∈
559 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
560 if (*pszAuthData == ' ')
563 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
564 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
565 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
568 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
570 out.BufferType = SECBUFFER_TOKEN;
571 out.cbBuffer = pAuthInfo->max_token;
572 out.pvBuffer = buffer;
574 out_desc.ulVersion = 0;
575 out_desc.cBuffers = 1;
576 out_desc.pBuffers = &out;
578 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
579 first ? NULL : &pAuthInfo->ctx,
580 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
581 context_req, 0, SECURITY_NETWORK_DREP,
582 in.pvBuffer ? &in_desc : NULL,
583 0, &pAuthInfo->ctx, &out_desc,
584 &pAuthInfo->attr, &pAuthInfo->exp);
585 if (sec_status == SEC_E_OK)
587 pAuthInfo->finished = TRUE;
588 pAuthInfo->auth_data = out.pvBuffer;
589 pAuthInfo->auth_data_len = out.cbBuffer;
590 TRACE("sending last auth packet\n");
592 else if (sec_status == SEC_I_CONTINUE_NEEDED)
594 pAuthInfo->auth_data = out.pvBuffer;
595 pAuthInfo->auth_data_len = out.cbBuffer;
596 TRACE("sending next auth packet\n");
600 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
601 pAuthInfo->finished = TRUE;
602 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
610 /***********************************************************************
611 * HTTP_HttpAddRequestHeadersW (internal)
613 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
614 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
619 BOOL bSuccess = FALSE;
622 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
624 if( dwHeaderLength == ~0U )
625 len = strlenW(lpszHeader);
627 len = dwHeaderLength;
628 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
629 lstrcpynW( buffer, lpszHeader, len + 1);
635 LPWSTR * pFieldAndValue;
639 while (*lpszEnd != '\0')
641 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
646 if (*lpszStart == '\0')
649 if (*lpszEnd == '\r')
652 lpszEnd += 2; /* Jump over \r\n */
654 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
655 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
658 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
660 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
661 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
662 HTTP_FreeTokens(pFieldAndValue);
668 HeapFree(GetProcessHeap(), 0, buffer);
673 /***********************************************************************
674 * HttpAddRequestHeadersW (WININET.@)
676 * Adds one or more HTTP header to the request handler
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.
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);
700 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
701 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
703 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
706 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
709 WININET_Release( &lpwhr->hdr );
714 /***********************************************************************
715 * HttpAddRequestHeadersA (WININET.@)
717 * Adds one or more HTTP header to the request handler
724 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
725 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
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 );
746 /***********************************************************************
747 * HttpEndRequestA (WININET.@)
749 * Ends an HTTP request that was started by HttpSendRequestEx
756 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
757 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
759 LPINTERNET_BUFFERSA ptr;
760 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
763 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
768 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
769 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
771 lpBuffersOutW = NULL;
773 ptrW = lpBuffersOutW;
776 if (ptr->lpvBuffer && ptr->dwBufferLength)
777 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
778 ptrW->dwBufferLength = ptr->dwBufferLength;
779 ptrW->dwBufferTotal= ptr->dwBufferTotal;
782 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
783 sizeof(INTERNET_BUFFERSW));
789 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
793 ptrW = lpBuffersOutW;
796 LPINTERNET_BUFFERSW ptrW2;
798 FIXME("Do we need to translate info out of these buffer?\n");
800 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
802 HeapFree(GetProcessHeap(),0,ptrW);
810 /***********************************************************************
811 * HttpEndRequestW (WININET.@)
813 * Ends an HTTP request that was started by HttpSendRequestEx
820 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
821 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
824 LPWININETHTTPREQW lpwhr;
829 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
831 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
833 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
835 WININET_Release( &lpwhr->hdr );
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, 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[INTERNET_MAX_URL_LENGTH];
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 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
880 INTERNET_STATUS_REDIRECT, szNewLocation,
882 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
884 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
889 WININET_Release( &lpwhr->hdr );
890 TRACE("%i <--\n",rc);
894 /***********************************************************************
895 * HttpOpenRequestW (WININET.@)
897 * Open a HTTP request handle
900 * HINTERNET a HTTP request handle on success
904 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
905 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
906 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
907 DWORD dwFlags, DWORD_PTR dwContext)
909 LPWININETHTTPSESSIONW lpwhs;
910 HINTERNET handle = NULL;
912 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
913 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
914 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
916 if(lpszAcceptTypes!=NULL)
919 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
920 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
923 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
924 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
926 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
931 * My tests seem to show that the windows version does not
932 * become asynchronous until after this point. And anyhow
933 * if this call was asynchronous then how would you get the
934 * necessary HINTERNET pointer returned by this function.
937 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
938 lpszVersion, lpszReferrer, lpszAcceptTypes,
942 WININET_Release( &lpwhs->hdr );
943 TRACE("returning %p\n", handle);
948 /***********************************************************************
949 * HttpOpenRequestA (WININET.@)
951 * Open a HTTP request handle
954 * HINTERNET a HTTP request handle on success
958 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
959 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
960 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
961 DWORD dwFlags, DWORD_PTR dwContext)
963 LPWSTR szVerb = NULL, szObjectName = NULL;
964 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
965 INT len, acceptTypesCount;
966 HINTERNET rc = FALSE;
969 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
970 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
971 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
976 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
977 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
980 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
985 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
986 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
989 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
994 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
995 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
998 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
1003 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1004 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1007 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1010 if (lpszAcceptTypes)
1012 acceptTypesCount = 0;
1013 types = lpszAcceptTypes;
1016 /* find out how many there are */
1017 if (((ULONG_PTR)*types >> 16) && **types)
1019 TRACE("accept type: %s\n", debugstr_a(*types));
1024 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1025 if (!szAcceptTypes) goto end;
1027 acceptTypesCount = 0;
1028 types = lpszAcceptTypes;
1031 if (((ULONG_PTR)*types >> 16) && **types)
1033 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1034 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1035 if (!szAcceptTypes[acceptTypesCount]) goto end;
1037 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1042 szAcceptTypes[acceptTypesCount] = NULL;
1044 else szAcceptTypes = 0;
1046 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1047 szVersion, szReferrer,
1048 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1053 acceptTypesCount = 0;
1054 while (szAcceptTypes[acceptTypesCount])
1056 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1059 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1061 HeapFree(GetProcessHeap(), 0, szReferrer);
1062 HeapFree(GetProcessHeap(), 0, szVersion);
1063 HeapFree(GetProcessHeap(), 0, szObjectName);
1064 HeapFree(GetProcessHeap(), 0, szVerb);
1069 /***********************************************************************
1072 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1075 static const CHAR HTTP_Base64Enc[] =
1076 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1080 /* first 6 bits, all from bin[0] */
1081 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1082 x = (bin[0] & 3) << 4;
1084 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1087 base64[n++] = HTTP_Base64Enc[x];
1092 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1093 x = ( bin[1] & 0x0f ) << 2;
1095 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1098 base64[n++] = HTTP_Base64Enc[x];
1102 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1104 /* last 6 bits, all from bin [2] */
1105 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1113 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1114 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1115 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1116 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1117 static const signed char HTTP_Base64Dec[256] =
1119 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1120 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1121 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1122 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1123 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1124 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1125 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1126 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1127 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1128 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1129 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1130 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1131 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1132 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1133 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1134 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1135 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1136 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1137 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1138 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1139 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1140 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1141 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1142 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1143 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1144 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1148 /***********************************************************************
1151 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1159 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1160 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1161 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1162 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1164 WARN("invalid base64: %s\n", debugstr_w(base64));
1168 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1171 if ((base64[2] == '=') && (base64[3] == '='))
1173 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1174 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1176 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1180 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1183 if (base64[3] == '=')
1185 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1186 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1188 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1192 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1201 /***********************************************************************
1202 * HTTP_InsertAuthorization
1204 * Insert or delete the authorization field in the request header.
1206 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1210 static const WCHAR wszSpace[] = {' ',0};
1211 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1213 WCHAR *authorization = NULL;
1215 if (pAuthInfo->auth_data_len)
1217 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1218 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1219 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1223 strcpyW(authorization, pAuthInfo->scheme);
1224 strcatW(authorization, wszSpace);
1225 HTTP_EncodeBase64(pAuthInfo->auth_data,
1226 pAuthInfo->auth_data_len,
1227 authorization+strlenW(authorization));
1229 /* clear the data as it isn't valid now that it has been sent to the
1230 * server, unless it's Basic authentication which doesn't do
1231 * connection tracking */
1232 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1234 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1235 pAuthInfo->auth_data = NULL;
1236 pAuthInfo->auth_data_len = 0;
1240 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1242 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1244 HeapFree(GetProcessHeap(), 0, authorization);
1249 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1251 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1254 size = sizeof(new_location);
1255 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1257 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1258 strcpyW( url, new_location );
1262 static const WCHAR slash[] = { '/',0 };
1263 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1264 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1265 WININETHTTPSESSIONW *session = req->lpHttpSession;
1267 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1268 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1270 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1272 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1273 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1275 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1276 if (req->lpszPath[0] != '/') strcatW( url, slash );
1277 strcatW( url, req->lpszPath );
1279 TRACE("url=%s\n", debugstr_w(url));
1283 /***********************************************************************
1284 * HTTP_DealWithProxy
1286 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1287 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1289 WCHAR buf[MAXHOSTNAME];
1290 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1291 static WCHAR szNul[] = { 0 };
1292 URL_COMPONENTSW UrlComponents;
1293 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1294 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1296 memset( &UrlComponents, 0, sizeof UrlComponents );
1297 UrlComponents.dwStructSize = sizeof UrlComponents;
1298 UrlComponents.lpszHostName = buf;
1299 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1301 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1302 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1303 sprintfW(proxy, szFormat, hIC->lpszProxy);
1305 strcpyW(proxy, hIC->lpszProxy);
1306 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1308 if( UrlComponents.dwHostNameLength == 0 )
1311 if( !lpwhr->lpszPath )
1312 lpwhr->lpszPath = szNul;
1314 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1315 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1317 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1318 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1319 lpwhs->nServerPort = UrlComponents.nPort;
1321 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1325 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1328 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1330 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1331 INTERNET_STATUS_RESOLVING_NAME,
1332 lpwhs->lpszServerName,
1333 strlenW(lpwhs->lpszServerName)+1);
1335 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1336 &lpwhs->socketAddress))
1338 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1342 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1343 szaddr, sizeof(szaddr));
1344 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1345 INTERNET_STATUS_NAME_RESOLVED,
1346 szaddr, strlen(szaddr)+1);
1348 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1353 /***********************************************************************
1354 * HTTPREQ_Destroy (internal)
1356 * Deallocate request handle
1359 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1361 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1366 if(lpwhr->hCacheFile)
1367 CloseHandle(lpwhr->hCacheFile);
1369 if(lpwhr->lpszCacheFile) {
1370 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1371 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1374 WININET_Release(&lpwhr->lpHttpSession->hdr);
1376 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1377 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1378 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1379 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1380 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1382 for (i = 0; i < lpwhr->nCustHeaders; i++)
1384 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1385 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1388 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1389 HeapFree(GetProcessHeap(), 0, lpwhr);
1392 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1394 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1396 TRACE("%p\n",lpwhr);
1398 if (!NETCON_connected(&lpwhr->netConnection))
1401 if (lpwhr->pAuthInfo)
1403 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1404 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1405 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1406 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1408 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1409 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1410 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1411 lpwhr->pAuthInfo = NULL;
1413 if (lpwhr->pProxyAuthInfo)
1415 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1416 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1417 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1418 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1420 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1421 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1422 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1423 lpwhr->pProxyAuthInfo = NULL;
1426 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1427 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1429 NETCON_close(&lpwhr->netConnection);
1431 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1432 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1435 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1437 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1440 case INTERNET_OPTION_HANDLE_TYPE:
1441 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1443 if (*size < sizeof(ULONG))
1444 return ERROR_INSUFFICIENT_BUFFER;
1446 *size = sizeof(DWORD);
1447 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1448 return ERROR_SUCCESS;
1450 case INTERNET_OPTION_URL: {
1451 WCHAR url[INTERNET_MAX_URL_LENGTH];
1456 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1457 static const WCHAR hostW[] = {'H','o','s','t',0};
1459 TRACE("INTERNET_OPTION_URL\n");
1461 host = HTTP_GetHeader(req, hostW);
1462 strcpyW(url, httpW);
1463 strcatW(url, host->lpszValue);
1464 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1466 strcatW(url, req->lpszPath);
1468 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1471 len = (strlenW(url)+1) * sizeof(WCHAR);
1473 return ERROR_INSUFFICIENT_BUFFER;
1476 strcpyW(buffer, url);
1477 return ERROR_SUCCESS;
1479 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1481 return ERROR_INSUFFICIENT_BUFFER;
1484 return ERROR_SUCCESS;
1488 case INTERNET_OPTION_DATAFILE_NAME: {
1491 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1493 if(!req->lpszCacheFile) {
1495 return ERROR_INTERNET_ITEM_NOT_FOUND;
1499 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1500 if(*size < req_size)
1501 return ERROR_INSUFFICIENT_BUFFER;
1504 memcpy(buffer, req->lpszCacheFile, *size);
1505 return ERROR_SUCCESS;
1507 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1508 if (req_size > *size)
1509 return ERROR_INSUFFICIENT_BUFFER;
1511 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1512 -1, buffer, *size, NULL, NULL);
1513 return ERROR_SUCCESS;
1517 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1518 PCCERT_CONTEXT context;
1520 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1521 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1522 return ERROR_INSUFFICIENT_BUFFER;
1525 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1527 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1530 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1531 info->ftExpiry = context->pCertInfo->NotAfter;
1532 info->ftStart = context->pCertInfo->NotBefore;
1534 len = CertNameToStrW(context->dwCertEncodingType,
1535 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1536 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1537 if(info->lpszSubjectInfo)
1538 CertNameToStrW(context->dwCertEncodingType,
1539 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1540 info->lpszSubjectInfo, len);
1541 len = CertNameToStrW(context->dwCertEncodingType,
1542 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1543 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1544 if (info->lpszIssuerInfo)
1545 CertNameToStrW(context->dwCertEncodingType,
1546 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1547 info->lpszIssuerInfo, len);
1549 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1551 len = CertNameToStrA(context->dwCertEncodingType,
1552 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1553 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1554 if(infoA->lpszSubjectInfo)
1555 CertNameToStrA(context->dwCertEncodingType,
1556 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1557 infoA->lpszSubjectInfo, len);
1558 len = CertNameToStrA(context->dwCertEncodingType,
1559 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1560 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1561 if(infoA->lpszIssuerInfo)
1562 CertNameToStrA(context->dwCertEncodingType,
1563 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1564 infoA->lpszIssuerInfo, len);
1568 * Contrary to MSDN, these do not appear to be set.
1570 * lpszSignatureAlgName
1571 * lpszEncryptionAlgName
1574 CertFreeCertificateContext(context);
1575 return ERROR_SUCCESS;
1580 return INET_QueryOption(option, buffer, size, unicode);
1583 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1585 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1588 case INTERNET_OPTION_SEND_TIMEOUT:
1589 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1590 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1592 if (size != sizeof(DWORD))
1593 return ERROR_INVALID_PARAMETER;
1595 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1599 return ERROR_INTERNET_INVALID_OPTION;
1602 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1606 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1607 sync ? MSG_WAITALL : 0, &bytes_read)) {
1608 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1609 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1611 /* always return success, even if the network layer returns an error */
1613 HTTP_FinishedReading(req);
1614 return ERROR_SUCCESS;
1617 req->dwContentRead += bytes_read;
1620 if(req->lpszCacheFile) {
1622 DWORD dwBytesWritten;
1624 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1626 WARN("WriteFile failed: %u\n", GetLastError());
1629 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1630 HTTP_FinishedReading(req);
1632 return ERROR_SUCCESS;
1635 static DWORD get_chunk_size(const char *buffer)
1640 for (p = buffer; *p; p++)
1642 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1643 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1644 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1645 else if (*p == ';') break;
1650 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1652 char reply[MAX_REPLY_LEN], *p = buffer;
1653 DWORD buflen, to_read, to_write = size;
1659 if (*read == size) break;
1661 if (req->dwContentLength == ~0UL) /* new chunk */
1663 buflen = sizeof(reply);
1664 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1666 if (!(req->dwContentLength = get_chunk_size(reply)))
1668 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1669 HTTP_GetResponseHeaders(req, FALSE);
1673 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1675 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1677 if (bytes_read != to_read)
1678 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1680 /* always return success, even if the network layer returns an error */
1684 if (!bytes_read) break;
1686 req->dwContentRead += bytes_read;
1687 to_write -= bytes_read;
1688 *read += bytes_read;
1690 if (req->lpszCacheFile)
1692 DWORD dwBytesWritten;
1694 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1695 WARN("WriteFile failed: %u\n", GetLastError());
1699 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1701 req->dwContentRead = 0;
1702 req->dwContentLength = ~0UL;
1704 buflen = sizeof(reply);
1705 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1707 ERR("Malformed chunk\n");
1713 if (!*read) HTTP_FinishedReading(req);
1714 return ERROR_SUCCESS;
1717 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1720 DWORD buflen = sizeof(encoding);
1721 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1723 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1724 !strcmpiW(encoding, szChunked))
1726 return HTTP_ReadChunked(req, buffer, size, read, sync);
1729 return HTTP_Read(req, buffer, size, read, sync);
1732 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1734 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1735 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1738 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1740 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1741 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1742 INTERNET_ASYNC_RESULT iar;
1745 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1747 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1748 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1750 iar.dwResult = res == ERROR_SUCCESS;
1753 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1754 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1755 sizeof(INTERNET_ASYNC_RESULT));
1758 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1759 DWORD flags, DWORD_PTR context)
1762 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1765 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1766 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1768 if (buffers->dwStructSize != sizeof(*buffers))
1769 return ERROR_INVALID_PARAMETER;
1771 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1773 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1774 DWORD available = 0;
1776 NETCON_query_data_available(&req->netConnection, &available);
1779 WORKREQUEST workRequest;
1781 workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1782 workRequest.hdr = WININET_AddRef(&req->hdr);
1783 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1785 INTERNET_AsyncCall(&workRequest);
1787 return ERROR_IO_PENDING;
1791 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1792 !(flags & IRF_NO_WAIT));
1794 if (res == ERROR_SUCCESS) {
1795 DWORD size = buffers->dwBufferLength;
1796 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1797 &size, sizeof(size));
1803 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1805 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1807 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1810 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1812 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1813 INTERNET_ASYNC_RESULT iar;
1816 TRACE("%p\n", workRequest->hdr);
1818 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1819 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1820 MSG_PEEK, (int *)&iar.dwError);
1822 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1823 sizeof(INTERNET_ASYNC_RESULT));
1826 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1828 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1832 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1834 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1835 return ERROR_SUCCESS;
1837 /* Even if we are in async mode, we need to determine whether
1838 * there is actually more data available. We do this by trying
1839 * to peek only a single byte in async mode. */
1840 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1842 if (NETCON_recv(&req->netConnection, buffer,
1843 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1844 MSG_PEEK, (int *)available) && async && *available)
1846 WORKREQUEST workRequest;
1849 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1850 workRequest.hdr = WININET_AddRef( &req->hdr );
1852 INTERNET_AsyncCall(&workRequest);
1854 return ERROR_IO_PENDING;
1857 return ERROR_SUCCESS;
1860 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1862 HTTPREQ_CloseConnection,
1863 HTTPREQ_QueryOption,
1866 HTTPREQ_ReadFileExA,
1868 HTTPREQ_QueryDataAvailable,
1872 /***********************************************************************
1873 * HTTP_HttpOpenRequestW (internal)
1875 * Open a HTTP request handle
1878 * HINTERNET a HTTP request handle on success
1882 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1883 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1884 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1885 DWORD dwFlags, DWORD_PTR dwContext)
1887 LPWININETAPPINFOW hIC = NULL;
1888 LPWININETHTTPREQW lpwhr;
1889 LPWSTR lpszHostName = NULL;
1890 HINTERNET handle = NULL;
1891 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1896 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1897 hIC = lpwhs->lpAppInfo;
1899 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1902 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1905 lpwhr->hdr.htype = WH_HHTTPREQ;
1906 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1907 lpwhr->hdr.dwFlags = dwFlags;
1908 lpwhr->hdr.dwContext = dwContext;
1909 lpwhr->hdr.refs = 1;
1910 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1911 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1913 WININET_AddRef( &lpwhs->hdr );
1914 lpwhr->lpHttpSession = lpwhs;
1915 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1917 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
1918 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
1919 if (NULL == lpszHostName)
1921 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1925 handle = WININET_AllocHandle( &lpwhr->hdr );
1928 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1932 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1934 InternetCloseHandle( handle );
1939 if (lpszObjectName && *lpszObjectName) {
1943 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1944 if (rc != E_POINTER)
1945 len = strlenW(lpszObjectName)+1;
1946 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1947 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1948 URL_ESCAPE_SPACES_ONLY);
1951 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1952 strcpyW(lpwhr->lpszPath,lpszObjectName);
1956 if (lpszReferrer && *lpszReferrer)
1957 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1959 if (lpszAcceptTypes)
1962 for (i = 0; lpszAcceptTypes[i]; i++)
1964 if (!*lpszAcceptTypes[i]) continue;
1965 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1966 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1967 HTTP_ADDHDR_FLAG_REQ |
1968 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1972 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1975 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1977 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1979 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
1980 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
1981 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
1983 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
1984 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
1985 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1988 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
1989 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1991 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1992 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1993 INTERNET_DEFAULT_HTTPS_PORT :
1994 INTERNET_DEFAULT_HTTP_PORT);
1996 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
1997 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
1998 INTERNET_DEFAULT_HTTPS_PORT :
1999 INTERNET_DEFAULT_HTTP_PORT);
2001 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2002 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2004 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2005 INTERNET_STATUS_HANDLE_CREATED, &handle,
2009 HeapFree(GetProcessHeap(), 0, lpszHostName);
2011 WININET_Release( &lpwhr->hdr );
2013 TRACE("<-- %p (%p)\n", handle, lpwhr);
2017 /* read any content returned by the server so that the connection can be
2019 static void HTTP_DrainContent(WININETHTTPREQW *req)
2023 if (!NETCON_connected(&req->netConnection)) return;
2025 if (req->dwContentLength == -1)
2026 NETCON_close(&req->netConnection);
2031 if (HTTP_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2033 } while (bytes_read);
2036 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2037 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2038 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2039 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2040 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2041 static const WCHAR szAge[] = { 'A','g','e',0 };
2042 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2043 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2044 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2045 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2046 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2047 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2048 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2049 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2050 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2051 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2052 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2053 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 };
2054 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2055 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2056 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2057 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2058 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2059 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2060 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2061 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2062 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2063 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2064 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2065 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2066 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2067 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2068 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2069 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2070 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2071 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2072 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2073 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2074 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2075 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2076 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2077 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2078 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2079 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2080 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 };
2081 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2082 static const WCHAR szURI[] = { 'U','R','I',0 };
2083 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2084 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2085 static const WCHAR szVia[] = { 'V','i','a',0 };
2086 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2087 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2089 static const LPCWSTR header_lookup[] = {
2090 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2091 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2092 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2093 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2094 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2095 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2096 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2097 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2098 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2099 szDate, /* HTTP_QUERY_DATE = 9 */
2100 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2101 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2102 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2103 szURI, /* HTTP_QUERY_URI = 13 */
2104 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2105 NULL, /* HTTP_QUERY_COST = 15 */
2106 NULL, /* HTTP_QUERY_LINK = 16 */
2107 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2108 NULL, /* HTTP_QUERY_VERSION = 18 */
2109 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2110 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2111 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2112 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2113 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2114 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2115 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2116 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2117 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2118 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2119 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2120 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2121 NULL, /* HTTP_QUERY_FROM = 31 */
2122 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2123 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2124 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2125 szReferer, /* HTTP_QUERY_REFERER = 35 */
2126 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2127 szServer, /* HTTP_QUERY_SERVER = 37 */
2128 NULL, /* HTTP_TITLE = 38 */
2129 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2130 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2131 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2132 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2133 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2134 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2135 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2136 NULL, /* HTTP_QUERY_REFRESH = 46 */
2137 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2138 szAge, /* HTTP_QUERY_AGE = 48 */
2139 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2140 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2141 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2142 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2143 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2144 szETag, /* HTTP_QUERY_ETAG = 54 */
2145 szHost, /* HTTP_QUERY_HOST = 55 */
2146 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2147 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2148 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2149 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2150 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2151 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2152 szRange, /* HTTP_QUERY_RANGE = 62 */
2153 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2154 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2155 szVary, /* HTTP_QUERY_VARY = 65 */
2156 szVia, /* HTTP_QUERY_VIA = 66 */
2157 szWarning, /* HTTP_QUERY_WARNING = 67 */
2158 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2159 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2160 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2163 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2165 /***********************************************************************
2166 * HTTP_HttpQueryInfoW (internal)
2168 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2169 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2171 LPHTTPHEADERW lphttpHdr = NULL;
2172 BOOL bSuccess = FALSE;
2173 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2174 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2175 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2178 /* Find requested header structure */
2181 case HTTP_QUERY_CUSTOM:
2182 if (!lpBuffer) return FALSE;
2183 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2186 case HTTP_QUERY_RAW_HEADERS_CRLF:
2193 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2195 headers = lpwhr->lpszRawHeaders;
2198 len = strlenW(headers) * sizeof(WCHAR);
2200 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2202 len += sizeof(WCHAR);
2203 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2209 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2212 len = strlenW(szCrLf) * sizeof(WCHAR);
2213 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2215 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2218 *lpdwBufferLength = len;
2221 HeapFree(GetProcessHeap(), 0, headers);
2224 case HTTP_QUERY_RAW_HEADERS:
2226 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2228 LPWSTR pszString = lpBuffer;
2230 for (i = 0; ppszRawHeaderLines[i]; i++)
2231 size += strlenW(ppszRawHeaderLines[i]) + 1;
2233 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2235 HTTP_FreeTokens(ppszRawHeaderLines);
2236 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2237 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2242 for (i = 0; ppszRawHeaderLines[i]; i++)
2244 DWORD len = strlenW(ppszRawHeaderLines[i]);
2245 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2249 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2251 *lpdwBufferLength = size * sizeof(WCHAR);
2252 HTTP_FreeTokens(ppszRawHeaderLines);
2256 case HTTP_QUERY_STATUS_TEXT:
2257 if (lpwhr->lpszStatusText)
2259 DWORD len = strlenW(lpwhr->lpszStatusText);
2260 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2262 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2263 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2268 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2269 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2271 *lpdwBufferLength = len * sizeof(WCHAR);
2275 case HTTP_QUERY_VERSION:
2276 if (lpwhr->lpszVersion)
2278 DWORD len = strlenW(lpwhr->lpszVersion);
2279 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2281 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2282 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2287 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2288 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2290 *lpdwBufferLength = len * sizeof(WCHAR);
2295 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2297 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
2298 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2299 requested_index,request_only);
2303 lphttpHdr = &lpwhr->pCustHeaders[index];
2305 /* Ensure header satisfies requested attributes */
2307 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2308 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2310 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2317 /* coalesce value to requested type */
2318 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2320 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2321 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2324 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2330 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2332 tmpTM = *gmtime(&tmpTime);
2333 STHook = (SYSTEMTIME *)lpBuffer;
2334 if (!STHook) return bSuccess;
2336 STHook->wDay = tmpTM.tm_mday;
2337 STHook->wHour = tmpTM.tm_hour;
2338 STHook->wMilliseconds = 0;
2339 STHook->wMinute = tmpTM.tm_min;
2340 STHook->wDayOfWeek = tmpTM.tm_wday;
2341 STHook->wMonth = tmpTM.tm_mon + 1;
2342 STHook->wSecond = tmpTM.tm_sec;
2343 STHook->wYear = tmpTM.tm_year;
2346 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2347 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2348 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2350 else if (lphttpHdr->lpszValue)
2352 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2354 if (len > *lpdwBufferLength)
2356 *lpdwBufferLength = len;
2357 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2362 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2363 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2365 *lpdwBufferLength = len - sizeof(WCHAR);
2371 /***********************************************************************
2372 * HttpQueryInfoW (WININET.@)
2374 * Queries for information about an HTTP request
2381 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2382 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2384 BOOL bSuccess = FALSE;
2385 LPWININETHTTPREQW lpwhr;
2387 if (TRACE_ON(wininet)) {
2388 #define FE(x) { x, #x }
2389 static const wininet_flag_info query_flags[] = {
2390 FE(HTTP_QUERY_MIME_VERSION),
2391 FE(HTTP_QUERY_CONTENT_TYPE),
2392 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2393 FE(HTTP_QUERY_CONTENT_ID),
2394 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2395 FE(HTTP_QUERY_CONTENT_LENGTH),
2396 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2397 FE(HTTP_QUERY_ALLOW),
2398 FE(HTTP_QUERY_PUBLIC),
2399 FE(HTTP_QUERY_DATE),
2400 FE(HTTP_QUERY_EXPIRES),
2401 FE(HTTP_QUERY_LAST_MODIFIED),
2402 FE(HTTP_QUERY_MESSAGE_ID),
2404 FE(HTTP_QUERY_DERIVED_FROM),
2405 FE(HTTP_QUERY_COST),
2406 FE(HTTP_QUERY_LINK),
2407 FE(HTTP_QUERY_PRAGMA),
2408 FE(HTTP_QUERY_VERSION),
2409 FE(HTTP_QUERY_STATUS_CODE),
2410 FE(HTTP_QUERY_STATUS_TEXT),
2411 FE(HTTP_QUERY_RAW_HEADERS),
2412 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2413 FE(HTTP_QUERY_CONNECTION),
2414 FE(HTTP_QUERY_ACCEPT),
2415 FE(HTTP_QUERY_ACCEPT_CHARSET),
2416 FE(HTTP_QUERY_ACCEPT_ENCODING),
2417 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2418 FE(HTTP_QUERY_AUTHORIZATION),
2419 FE(HTTP_QUERY_CONTENT_ENCODING),
2420 FE(HTTP_QUERY_FORWARDED),
2421 FE(HTTP_QUERY_FROM),
2422 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2423 FE(HTTP_QUERY_LOCATION),
2424 FE(HTTP_QUERY_ORIG_URI),
2425 FE(HTTP_QUERY_REFERER),
2426 FE(HTTP_QUERY_RETRY_AFTER),
2427 FE(HTTP_QUERY_SERVER),
2428 FE(HTTP_QUERY_TITLE),
2429 FE(HTTP_QUERY_USER_AGENT),
2430 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2431 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2432 FE(HTTP_QUERY_ACCEPT_RANGES),
2433 FE(HTTP_QUERY_SET_COOKIE),
2434 FE(HTTP_QUERY_COOKIE),
2435 FE(HTTP_QUERY_REQUEST_METHOD),
2436 FE(HTTP_QUERY_REFRESH),
2437 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2439 FE(HTTP_QUERY_CACHE_CONTROL),
2440 FE(HTTP_QUERY_CONTENT_BASE),
2441 FE(HTTP_QUERY_CONTENT_LOCATION),
2442 FE(HTTP_QUERY_CONTENT_MD5),
2443 FE(HTTP_QUERY_CONTENT_RANGE),
2444 FE(HTTP_QUERY_ETAG),
2445 FE(HTTP_QUERY_HOST),
2446 FE(HTTP_QUERY_IF_MATCH),
2447 FE(HTTP_QUERY_IF_NONE_MATCH),
2448 FE(HTTP_QUERY_IF_RANGE),
2449 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2450 FE(HTTP_QUERY_MAX_FORWARDS),
2451 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2452 FE(HTTP_QUERY_RANGE),
2453 FE(HTTP_QUERY_TRANSFER_ENCODING),
2454 FE(HTTP_QUERY_UPGRADE),
2455 FE(HTTP_QUERY_VARY),
2457 FE(HTTP_QUERY_WARNING),
2458 FE(HTTP_QUERY_CUSTOM)
2460 static const wininet_flag_info modifier_flags[] = {
2461 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2462 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2463 FE(HTTP_QUERY_FLAG_NUMBER),
2464 FE(HTTP_QUERY_FLAG_COALESCE)
2467 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2468 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2471 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2472 TRACE(" Attribute:");
2473 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2474 if (query_flags[i].val == info) {
2475 TRACE(" %s", query_flags[i].name);
2479 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2480 TRACE(" Unknown (%08x)", info);
2483 TRACE(" Modifier:");
2484 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2485 if (modifier_flags[i].val & info_mod) {
2486 TRACE(" %s", modifier_flags[i].name);
2487 info_mod &= ~ modifier_flags[i].val;
2492 TRACE(" Unknown (%08x)", info_mod);
2497 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2498 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2500 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2504 if (lpBuffer == NULL)
2505 *lpdwBufferLength = 0;
2506 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2507 lpBuffer, lpdwBufferLength, lpdwIndex);
2511 WININET_Release( &lpwhr->hdr );
2513 TRACE("%d <--\n", bSuccess);
2517 /***********************************************************************
2518 * HttpQueryInfoA (WININET.@)
2520 * Queries for information about an HTTP request
2527 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2528 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2534 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2535 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2537 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2538 lpdwBufferLength, lpdwIndex );
2544 len = (*lpdwBufferLength)*sizeof(WCHAR);
2545 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2547 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2553 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2554 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2555 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2556 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2563 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2567 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2568 lpBuffer, *lpdwBufferLength, NULL, NULL );
2569 *lpdwBufferLength = len - 1;
2571 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2574 /* since the strings being returned from HttpQueryInfoW should be
2575 * only ASCII characters, it is reasonable to assume that all of
2576 * the Unicode characters can be reduced to a single byte */
2577 *lpdwBufferLength = len / sizeof(WCHAR);
2579 HeapFree(GetProcessHeap(), 0, bufferW );
2584 /***********************************************************************
2585 * HttpSendRequestExA (WININET.@)
2587 * Sends the specified request to the HTTP server and allows chunked
2592 * Failure: FALSE, call GetLastError() for more information.
2594 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2595 LPINTERNET_BUFFERSA lpBuffersIn,
2596 LPINTERNET_BUFFERSA lpBuffersOut,
2597 DWORD dwFlags, DWORD_PTR dwContext)
2599 INTERNET_BUFFERSW BuffersInW;
2602 LPWSTR header = NULL;
2604 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2605 lpBuffersOut, dwFlags, dwContext);
2609 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2610 if (lpBuffersIn->lpcszHeader)
2612 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2613 lpBuffersIn->dwHeadersLength,0,0);
2614 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2615 if (!(BuffersInW.lpcszHeader = header))
2617 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2620 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2621 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2625 BuffersInW.lpcszHeader = NULL;
2626 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2627 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2628 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2629 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2630 BuffersInW.Next = NULL;
2633 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2635 HeapFree(GetProcessHeap(),0,header);
2640 /***********************************************************************
2641 * HttpSendRequestExW (WININET.@)
2643 * Sends the specified request to the HTTP server and allows chunked
2648 * Failure: FALSE, call GetLastError() for more information.
2650 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2651 LPINTERNET_BUFFERSW lpBuffersIn,
2652 LPINTERNET_BUFFERSW lpBuffersOut,
2653 DWORD dwFlags, DWORD_PTR dwContext)
2656 LPWININETHTTPREQW lpwhr;
2657 LPWININETHTTPSESSIONW lpwhs;
2658 LPWININETAPPINFOW hIC;
2660 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2661 lpBuffersOut, dwFlags, dwContext);
2663 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2665 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2667 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2671 lpwhs = lpwhr->lpHttpSession;
2672 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2673 hIC = lpwhs->lpAppInfo;
2674 assert(hIC->hdr.htype == WH_HINIT);
2676 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2678 WORKREQUEST workRequest;
2679 struct WORKREQ_HTTPSENDREQUESTW *req;
2681 workRequest.asyncproc = AsyncHttpSendRequestProc;
2682 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2683 req = &workRequest.u.HttpSendRequestW;
2686 if (lpBuffersIn->lpcszHeader)
2687 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2688 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2690 req->lpszHeader = NULL;
2691 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2692 req->lpOptional = lpBuffersIn->lpvBuffer;
2693 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2694 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2698 req->lpszHeader = NULL;
2699 req->dwHeaderLength = 0;
2700 req->lpOptional = NULL;
2701 req->dwOptionalLength = 0;
2702 req->dwContentLength = 0;
2705 req->bEndRequest = FALSE;
2707 INTERNET_AsyncCall(&workRequest);
2709 * This is from windows.
2711 INTERNET_SetLastError(ERROR_IO_PENDING);
2716 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2717 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2718 lpBuffersIn->dwBufferTotal, FALSE);
2720 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2725 WININET_Release( &lpwhr->hdr );
2731 /***********************************************************************
2732 * HttpSendRequestW (WININET.@)
2734 * Sends the specified request to the HTTP server
2741 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2742 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2744 LPWININETHTTPREQW lpwhr;
2745 LPWININETHTTPSESSIONW lpwhs = NULL;
2746 LPWININETAPPINFOW hIC = NULL;
2749 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2750 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2752 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2753 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2755 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2760 lpwhs = lpwhr->lpHttpSession;
2761 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2763 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2768 hIC = lpwhs->lpAppInfo;
2769 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2771 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2776 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2778 WORKREQUEST workRequest;
2779 struct WORKREQ_HTTPSENDREQUESTW *req;
2781 workRequest.asyncproc = AsyncHttpSendRequestProc;
2782 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2783 req = &workRequest.u.HttpSendRequestW;
2786 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2787 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2790 req->lpszHeader = 0;
2791 req->dwHeaderLength = dwHeaderLength;
2792 req->lpOptional = lpOptional;
2793 req->dwOptionalLength = dwOptionalLength;
2794 req->dwContentLength = dwOptionalLength;
2795 req->bEndRequest = TRUE;
2797 INTERNET_AsyncCall(&workRequest);
2799 * This is from windows.
2801 INTERNET_SetLastError(ERROR_IO_PENDING);
2806 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2807 dwHeaderLength, lpOptional, dwOptionalLength,
2808 dwOptionalLength, TRUE);
2812 WININET_Release( &lpwhr->hdr );
2816 /***********************************************************************
2817 * HttpSendRequestA (WININET.@)
2819 * Sends the specified request to the HTTP server
2826 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2827 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2830 LPWSTR szHeaders=NULL;
2831 DWORD nLen=dwHeaderLength;
2832 if(lpszHeaders!=NULL)
2834 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2835 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2836 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2838 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2839 HeapFree(GetProcessHeap(),0,szHeaders);
2843 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2845 LPHTTPHEADERW host_header;
2847 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2849 host_header = HTTP_GetHeader(req, szHost);
2853 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2857 /***********************************************************************
2858 * HTTP_HandleRedirect (internal)
2860 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2862 static const WCHAR szContentType[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
2863 static const WCHAR szContentLength[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
2864 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2865 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2866 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2867 WCHAR path[INTERNET_MAX_URL_LENGTH];
2872 /* if it's an absolute path, keep the same session info */
2873 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2877 URL_COMPONENTSW urlComponents;
2878 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2879 static WCHAR szHttp[] = {'h','t','t','p',0};
2880 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2881 DWORD url_length = 0;
2883 LPWSTR combined_url;
2885 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2886 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2887 urlComponents.dwSchemeLength = 0;
2888 urlComponents.lpszHostName = lpwhs->lpszHostName;
2889 urlComponents.dwHostNameLength = 0;
2890 urlComponents.nPort = lpwhs->nHostPort;
2891 urlComponents.lpszUserName = lpwhs->lpszUserName;
2892 urlComponents.dwUserNameLength = 0;
2893 urlComponents.lpszPassword = NULL;
2894 urlComponents.dwPasswordLength = 0;
2895 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2896 urlComponents.dwUrlPathLength = 0;
2897 urlComponents.lpszExtraInfo = NULL;
2898 urlComponents.dwExtraInfoLength = 0;
2900 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2901 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2904 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2906 /* convert from bytes to characters */
2907 url_length = url_length / sizeof(WCHAR) - 1;
2908 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2910 HeapFree(GetProcessHeap(), 0, orig_url);
2915 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2916 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2918 HeapFree(GetProcessHeap(), 0, orig_url);
2921 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2923 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2925 HeapFree(GetProcessHeap(), 0, orig_url);
2926 HeapFree(GetProcessHeap(), 0, combined_url);
2929 HeapFree(GetProcessHeap(), 0, orig_url);
2935 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2936 urlComponents.lpszScheme = protocol;
2937 urlComponents.dwSchemeLength = 32;
2938 urlComponents.lpszHostName = hostName;
2939 urlComponents.dwHostNameLength = MAXHOSTNAME;
2940 urlComponents.lpszUserName = userName;
2941 urlComponents.dwUserNameLength = 1024;
2942 urlComponents.lpszPassword = NULL;
2943 urlComponents.dwPasswordLength = 0;
2944 urlComponents.lpszUrlPath = path;
2945 urlComponents.dwUrlPathLength = 2048;
2946 urlComponents.lpszExtraInfo = NULL;
2947 urlComponents.dwExtraInfoLength = 0;
2948 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2950 HeapFree(GetProcessHeap(), 0, combined_url);
2954 HeapFree(GetProcessHeap(), 0, combined_url);
2956 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2957 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2959 TRACE("redirect from secure page to non-secure page\n");
2960 /* FIXME: warn about from secure redirect to non-secure page */
2961 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2963 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2964 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2966 TRACE("redirect from non-secure page to secure page\n");
2967 /* FIXME: notify about redirect to secure page */
2968 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2971 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2973 if (lstrlenW(protocol)>4) /*https*/
2974 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2976 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2981 * This upsets redirects to binary files on sourceforge.net
2982 * and gives an html page instead of the target file
2983 * Examination of the HTTP request sent by native wininet.dll
2984 * reveals that it doesn't send a referrer in that case.
2985 * Maybe there's a flag that enables this, or maybe a referrer
2986 * shouldn't be added in case of a redirect.
2989 /* consider the current host as the referrer */
2990 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2991 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2992 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2993 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2996 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2997 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2998 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3001 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3002 len = lstrlenW(hostName);
3003 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3004 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3005 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3008 lpwhs->lpszHostName = WININET_strdupW(hostName);
3010 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3012 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3013 lpwhs->lpszUserName = NULL;
3015 lpwhs->lpszUserName = WININET_strdupW(userName);
3019 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3021 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3022 lpwhs->lpszServerName = WININET_strdupW(hostName);
3023 lpwhs->nServerPort = urlComponents.nPort;
3025 NETCON_close(&lpwhr->netConnection);
3026 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3027 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3031 TRACE("Redirect through proxy\n");
3034 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3035 lpwhr->lpszPath=NULL;
3041 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3042 if (rc != E_POINTER)
3043 needed = strlenW(path)+1;
3044 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3045 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3046 URL_ESCAPE_SPACES_ONLY);
3049 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3050 strcpyW(lpwhr->lpszPath,path);
3054 /* Remove custom content-type/length headers on redirects. */
3055 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentType, 0, TRUE);
3057 HTTP_DeleteCustomHeader(lpwhr, index);
3058 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentLength, 0, TRUE);
3060 HTTP_DeleteCustomHeader(lpwhr, index);
3065 /***********************************************************************
3066 * HTTP_build_req (internal)
3068 * concatenate all the strings in the request together
3070 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3075 for( t = list; *t ; t++ )
3076 len += strlenW( *t );
3079 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3082 for( t = list; *t ; t++ )
3088 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3091 LPWSTR requestString;
3097 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3098 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3099 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3103 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3104 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3105 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3106 HeapFree( GetProcessHeap(), 0, lpszPath );
3108 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3109 NULL, 0, NULL, NULL );
3110 len--; /* the nul terminator isn't needed */
3111 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3112 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3113 ascii_req, len, NULL, NULL );
3114 HeapFree( GetProcessHeap(), 0, requestString );
3116 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3118 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3119 HeapFree( GetProcessHeap(), 0, ascii_req );
3120 if (!ret || cnt < 0)
3123 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3130 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3132 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
3133 LPWSTR lpszCookies, lpszUrl = NULL;
3134 DWORD nCookieSize, size;
3135 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3137 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm)) * sizeof(WCHAR);
3138 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3139 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
3141 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3144 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3146 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3147 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3149 cnt += sprintfW(lpszCookies, szCookie);
3150 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3151 strcatW(lpszCookies, szCrLf);
3153 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_ADD);
3154 HeapFree(GetProcessHeap(), 0, lpszCookies);
3157 HeapFree(GetProcessHeap(), 0, lpszUrl);
3160 /***********************************************************************
3161 * HTTP_HttpSendRequestW (internal)
3163 * Sends the specified request to the HTTP server
3170 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3171 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3172 DWORD dwContentLength, BOOL bEndRequest)
3175 BOOL bSuccess = FALSE;
3176 LPWSTR requestString = NULL;
3179 INTERNET_ASYNC_RESULT iar;
3180 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3181 static const WCHAR szContentLength[] =
3182 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3183 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3185 TRACE("--> %p\n", lpwhr);
3187 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3189 /* if the verb is NULL default to GET */
3190 if (!lpwhr->lpszVerb)
3191 lpwhr->lpszVerb = WININET_strdupW(szGET);
3193 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
3195 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3196 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3198 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3200 WCHAR *agent_header;
3201 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3204 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3205 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3206 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3208 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3209 HeapFree(GetProcessHeap(), 0, agent_header);
3211 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3213 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3214 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3216 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3218 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3219 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3220 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3230 /* like native, just in case the caller forgot to call InternetReadFile
3231 * for all the data */
3232 HTTP_DrainContent(lpwhr);
3233 lpwhr->dwContentRead = 0;
3235 if (TRACE_ON(wininet))
3237 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3238 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3242 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3244 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3246 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3247 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3249 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3250 HTTP_InsertCookies(lpwhr);
3252 /* add the headers the caller supplied */
3253 if( lpszHeaders && dwHeaderLength )
3255 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3256 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3259 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3261 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3262 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3263 HeapFree(GetProcessHeap(), 0, url);
3266 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3269 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3271 /* Send the request and store the results */
3272 if (!HTTP_OpenConnection(lpwhr))
3275 /* send the request as ASCII, tack on the optional data */
3277 dwOptionalLength = 0;
3278 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3279 NULL, 0, NULL, NULL );
3280 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3281 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3282 ascii_req, len, NULL, NULL );
3284 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3285 len = (len + dwOptionalLength - 1);
3287 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3289 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3290 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3292 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3293 HeapFree( GetProcessHeap(), 0, ascii_req );
3295 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3296 INTERNET_STATUS_REQUEST_SENT,
3297 &len, sizeof(DWORD));
3304 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3306 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3307 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3312 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3316 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3317 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3320 HTTP_ProcessCookies(lpwhr);
3322 dwBufferSize = sizeof(lpwhr->dwContentLength);
3323 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3324 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3325 lpwhr->dwContentLength = -1;
3327 if (lpwhr->dwContentLength == 0)
3328 HTTP_FinishedReading(lpwhr);
3330 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3332 dwBufferSize = sizeof(encoding);
3333 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3334 !strcmpiW(encoding, szChunked))
3336 lpwhr->dwContentLength = -1;
3339 dwBufferSize = sizeof(dwStatusCode);
3340 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3341 &dwStatusCode,&dwBufferSize,NULL))
3344 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3346 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3347 dwBufferSize=sizeof(szNewLocation);
3348 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3349 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3351 HTTP_DrainContent(lpwhr);
3352 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3353 INTERNET_STATUS_REDIRECT, szNewLocation,
3355 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3358 HeapFree(GetProcessHeap(), 0, requestString);
3363 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3365 WCHAR szAuthValue[2048];
3367 if (dwStatusCode == HTTP_STATUS_DENIED)
3370 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3372 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3374 lpwhr->lpHttpSession->lpszUserName,
3375 lpwhr->lpHttpSession->lpszPassword))
3382 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3385 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3387 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3388 &lpwhr->pProxyAuthInfo,
3389 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3390 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3404 /* FIXME: Better check, when we have to create the cache file */
3405 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3406 WCHAR url[INTERNET_MAX_URL_LENGTH];
3407 WCHAR cacheFileName[MAX_PATH+1];
3410 b = HTTP_GetRequestURL(lpwhr, url);
3412 WARN("Could not get URL\n");
3416 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3418 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3419 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3420 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3421 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3422 WARN("Could not create file: %u\n", GetLastError());
3423 lpwhr->hCacheFile = NULL;
3426 WARN("Could not create cache entry: %08x\n", GetLastError());
3432 HeapFree(GetProcessHeap(), 0, requestString);
3434 /* TODO: send notification for P3P header */
3436 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3437 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
3439 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3440 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3441 sizeof(INTERNET_ASYNC_RESULT));
3444 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3448 /***********************************************************************
3449 * HTTPSESSION_Destroy (internal)
3451 * Deallocate session handle
3454 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3456 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3458 TRACE("%p\n", lpwhs);
3460 WININET_Release(&lpwhs->lpAppInfo->hdr);
3462 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3463 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3464 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3465 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3466 HeapFree(GetProcessHeap(), 0, lpwhs);
3469 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3472 case INTERNET_OPTION_HANDLE_TYPE:
3473 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3475 if (*size < sizeof(ULONG))
3476 return ERROR_INSUFFICIENT_BUFFER;
3478 *size = sizeof(DWORD);
3479 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3480 return ERROR_SUCCESS;
3483 return INET_QueryOption(option, buffer, size, unicode);
3486 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3488 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3491 case INTERNET_OPTION_USERNAME:
3493 if (!(ses->lpszUserName = WININET_strdupW(buffer))) break;
3494 return ERROR_SUCCESS;
3496 case INTERNET_OPTION_PASSWORD:
3498 if (!(ses->lpszPassword = WININET_strdupW(buffer))) break;
3499 return ERROR_SUCCESS;
3504 return ERROR_INTERNET_INVALID_OPTION;
3507 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3508 HTTPSESSION_Destroy,
3510 HTTPSESSION_QueryOption,
3511 HTTPSESSION_SetOption,
3520 /***********************************************************************
3521 * HTTP_Connect (internal)
3523 * Create http session handle
3526 * HINTERNET a session handle on success
3530 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3531 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3532 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3533 DWORD dwInternalFlags)
3535 LPWININETHTTPSESSIONW lpwhs = NULL;
3536 HINTERNET handle = NULL;
3540 if (!lpszServerName || !lpszServerName[0])
3542 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3546 assert( hIC->hdr.htype == WH_HINIT );
3548 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3551 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3556 * According to my tests. The name is not resolved until a request is sent
3559 lpwhs->hdr.htype = WH_HHTTPSESSION;
3560 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3561 lpwhs->hdr.dwFlags = dwFlags;
3562 lpwhs->hdr.dwContext = dwContext;
3563 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3564 lpwhs->hdr.refs = 1;
3565 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3567 WININET_AddRef( &hIC->hdr );
3568 lpwhs->lpAppInfo = hIC;
3569 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3571 handle = WININET_AllocHandle( &lpwhs->hdr );
3574 ERR("Failed to alloc handle\n");
3575 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3579 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3580 if(strchrW(hIC->lpszProxy, ' '))
3581 FIXME("Several proxies not implemented.\n");
3582 if(hIC->lpszProxyBypass)
3583 FIXME("Proxy bypass is ignored.\n");
3585 if (lpszServerName && lpszServerName[0])
3587 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3588 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3590 if (lpszUserName && lpszUserName[0])
3591 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3592 if (lpszPassword && lpszPassword[0])
3593 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3594 lpwhs->nServerPort = nServerPort;
3595 lpwhs->nHostPort = nServerPort;
3597 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3598 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3600 INTERNET_SendCallback(&hIC->hdr, dwContext,
3601 INTERNET_STATUS_HANDLE_CREATED, &handle,
3607 WININET_Release( &lpwhs->hdr );
3610 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3614 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3619 /***********************************************************************
3620 * HTTP_OpenConnection (internal)
3622 * Connect to a web server
3629 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3631 BOOL bSuccess = FALSE;
3632 LPWININETHTTPSESSIONW lpwhs;
3633 LPWININETAPPINFOW hIC = NULL;
3639 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3641 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3645 if (NETCON_connected(&lpwhr->netConnection))
3650 if (!HTTP_ResolveName(lpwhr)) goto lend;
3652 lpwhs = lpwhr->lpHttpSession;
3654 hIC = lpwhs->lpAppInfo;
3655 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3656 szaddr, sizeof(szaddr));
3657 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3658 INTERNET_STATUS_CONNECTING_TO_SERVER,
3662 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3665 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3669 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3670 sizeof(lpwhs->socketAddress)))
3673 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3675 /* Note: we differ from Microsoft's WinINet here. they seem to have
3676 * a bug that causes no status callbacks to be sent when starting
3677 * a tunnel to a proxy server using the CONNECT verb. i believe our
3678 * behaviour to be more correct and to not cause any incompatibilities
3679 * because using a secure connection through a proxy server is a rare
3680 * case that would be hard for anyone to depend on */
3681 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3684 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3686 WARN("Couldn't connect securely to host\n");
3691 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3692 INTERNET_STATUS_CONNECTED_TO_SERVER,
3693 szaddr, strlen(szaddr)+1);
3698 TRACE("%d <--\n", bSuccess);
3703 /***********************************************************************
3704 * HTTP_clear_response_headers (internal)
3706 * clear out any old response headers
3708 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3712 for( i=0; i<lpwhr->nCustHeaders; i++)
3714 if( !lpwhr->pCustHeaders[i].lpszField )
3716 if( !lpwhr->pCustHeaders[i].lpszValue )
3718 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3720 HTTP_DeleteCustomHeader( lpwhr, i );
3725 /***********************************************************************
3726 * HTTP_GetResponseHeaders (internal)
3728 * Read server response
3735 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3738 WCHAR buffer[MAX_REPLY_LEN];
3739 DWORD buflen = MAX_REPLY_LEN;
3740 BOOL bSuccess = FALSE;
3742 static const WCHAR szHundred[] = {'1','0','0',0};
3743 char bufferA[MAX_REPLY_LEN];
3744 LPWSTR status_code, status_text;
3745 DWORD cchMaxRawHeaders = 1024;
3746 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3747 DWORD cchRawHeaders = 0;
3751 /* clear old response headers (eg. from a redirect response) */
3752 if (clear) HTTP_clear_response_headers( lpwhr );
3754 if (!NETCON_connected(&lpwhr->netConnection))
3759 * HACK peek at the buffer
3761 buflen = MAX_REPLY_LEN;
3762 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3765 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3767 memset(buffer, 0, MAX_REPLY_LEN);
3768 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3770 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3772 /* split the version from the status code */
3773 status_code = strchrW( buffer, ' ' );
3778 /* split the status code from the status text */
3779 status_text = strchrW( status_code, ' ' );
3784 TRACE("version [%s] status code [%s] status text [%s]\n",
3785 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3787 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3789 /* Add status code */
3790 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3791 HTTP_ADDHDR_FLAG_REPLACE);
3793 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3794 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3796 lpwhr->lpszVersion= WININET_strdupW(buffer);
3797 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3799 /* Restore the spaces */
3800 *(status_code-1) = ' ';
3801 *(status_text-1) = ' ';
3803 /* regenerate raw headers */
3804 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3806 cchMaxRawHeaders *= 2;
3807 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3809 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3810 cchRawHeaders += (buflen-1);
3811 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3812 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3813 lpszRawHeaders[cchRawHeaders] = '\0';
3815 /* Parse each response line */
3818 buflen = MAX_REPLY_LEN;
3819 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3821 LPWSTR * pFieldAndValue;
3823 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3824 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3826 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3828 cchMaxRawHeaders *= 2;
3829 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3831 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3832 cchRawHeaders += (buflen-1);
3833 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3834 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3835 lpszRawHeaders[cchRawHeaders] = '\0';
3837 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3838 if (!pFieldAndValue)
3841 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3842 HTTP_ADDREQ_FLAG_ADD );
3844 HTTP_FreeTokens(pFieldAndValue);
3854 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3855 lpwhr->lpszRawHeaders = lpszRawHeaders;
3856 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3866 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
3872 static void strip_spaces(LPWSTR start)
3877 while (*str == ' ' && *str != '\0')
3881 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3883 end = start + strlenW(start) - 1;
3884 while (end >= start && *end == ' ')
3892 /***********************************************************************
3893 * HTTP_InterpretHttpHeader (internal)
3895 * Parse server response
3899 * Pointer to array of field, value, NULL on success.
3902 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3904 LPWSTR * pTokenPair;
3908 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3910 pszColon = strchrW(buffer, ':');
3911 /* must have two tokens */
3914 HTTP_FreeTokens(pTokenPair);
3916 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3920 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3923 HTTP_FreeTokens(pTokenPair);
3926 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3927 pTokenPair[0][pszColon - buffer] = '\0';
3931 len = strlenW(pszColon);
3932 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3935 HTTP_FreeTokens(pTokenPair);
3938 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3940 strip_spaces(pTokenPair[0]);
3941 strip_spaces(pTokenPair[1]);
3943 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3947 /***********************************************************************
3948 * HTTP_ProcessHeader (internal)
3950 * Stuff header into header tables according to <dwModifier>
3954 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3956 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3958 LPHTTPHEADERW lphttpHdr = NULL;
3959 BOOL bSuccess = FALSE;
3961 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3963 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3965 /* REPLACE wins out over ADD */
3966 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3967 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3969 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3972 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3976 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3980 lphttpHdr = &lpwhr->pCustHeaders[index];
3986 hdr.lpszField = (LPWSTR)field;
3987 hdr.lpszValue = (LPWSTR)value;
3988 hdr.wFlags = hdr.wCount = 0;
3990 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3991 hdr.wFlags |= HDR_ISREQUEST;
3993 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3995 /* no value to delete */
3998 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3999 lphttpHdr->wFlags |= HDR_ISREQUEST;
4001 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4003 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4005 HTTP_DeleteCustomHeader( lpwhr, index );
4011 hdr.lpszField = (LPWSTR)field;
4012 hdr.lpszValue = (LPWSTR)value;
4013 hdr.wFlags = hdr.wCount = 0;
4015 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4016 hdr.wFlags |= HDR_ISREQUEST;
4018 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4023 else if (dwModifier & COALESCEFLAGS)
4028 INT origlen = strlenW(lphttpHdr->lpszValue);
4029 INT valuelen = strlenW(value);
4031 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4034 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4036 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4039 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4042 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4044 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4047 lphttpHdr->lpszValue = lpsztmp;
4048 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4051 lphttpHdr->lpszValue[origlen] = ch;
4053 lphttpHdr->lpszValue[origlen] = ' ';
4057 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4058 lphttpHdr->lpszValue[len] = '\0';
4063 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4064 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4067 TRACE("<-- %d\n",bSuccess);
4072 /***********************************************************************
4073 * HTTP_FinishedReading (internal)
4075 * Called when all content from server has been read by client.
4078 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4080 WCHAR szVersion[10];
4081 WCHAR szConnectionResponse[20];
4082 DWORD dwBufferSize = sizeof(szVersion);
4083 BOOL keepalive = FALSE;
4087 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4088 * the connection is keep-alive by default */
4089 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4090 &dwBufferSize, NULL) &&
4091 !strcmpiW(szVersion, g_szHttp1_1))
4096 dwBufferSize = sizeof(szConnectionResponse);
4097 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4098 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4100 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4105 HTTPREQ_CloseConnection(&lpwhr->hdr);
4108 /* FIXME: store data in the URL cache here */
4114 /***********************************************************************
4115 * HTTP_GetCustomHeaderIndex (internal)
4117 * Return index of custom header from header array
4120 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4121 int requested_index, BOOL request_only)
4125 TRACE("%s\n", debugstr_w(lpszField));
4127 for (index = 0; index < lpwhr->nCustHeaders; index++)
4129 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4132 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4135 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4138 if (requested_index == 0)
4143 if (index >= lpwhr->nCustHeaders)
4146 TRACE("Return: %d\n", index);
4151 /***********************************************************************
4152 * HTTP_InsertCustomHeader (internal)
4154 * Insert header into array
4157 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4160 LPHTTPHEADERW lph = NULL;
4163 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4164 count = lpwhr->nCustHeaders + 1;
4166 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4168 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4172 lpwhr->pCustHeaders = lph;
4173 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4174 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4175 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4176 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4177 lpwhr->nCustHeaders++;
4182 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4189 /***********************************************************************
4190 * HTTP_DeleteCustomHeader (internal)
4192 * Delete header from array
4193 * If this function is called, the indexs may change.
4195 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4197 if( lpwhr->nCustHeaders <= 0 )
4199 if( index >= lpwhr->nCustHeaders )
4201 lpwhr->nCustHeaders--;
4203 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4204 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4206 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4207 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4208 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4214 /***********************************************************************
4215 * HTTP_VerifyValidHeader (internal)
4217 * Verify the given header is not invalid for the given http request
4220 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4222 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4223 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4229 /***********************************************************************
4230 * IsHostInProxyBypassList (@)
4235 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4237 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);