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 #if defined(__MINGW32__) || defined (_MSC_VER)
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
40 #ifdef HAVE_ARPA_INET_H
41 # include <arpa/inet.h>
56 #define NO_SHLWAPI_STREAM
57 #define NO_SHLWAPI_REG
58 #define NO_SHLWAPI_STRFCNS
59 #define NO_SHLWAPI_GDI
65 #include "wine/debug.h"
66 #include "wine/exception.h"
67 #include "wine/unicode.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
71 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
72 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
73 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
74 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
75 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
76 static const WCHAR szHost[] = { 'H','o','s','t',0 };
77 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
78 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
79 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
80 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
81 static const WCHAR szGET[] = { 'G','E','T', 0 };
82 static const WCHAR szCrLf[] = {'\r','\n', 0};
84 #define MAXHOSTNAME 100
85 #define MAX_FIELD_VALUE_LEN 256
86 #define MAX_FIELD_LEN 256
88 #define HTTP_REFERER g_szReferer
89 #define HTTP_ACCEPT g_szAccept
90 #define HTTP_USERAGENT g_szUserAgent
92 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
93 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
94 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
95 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
96 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
97 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
98 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
100 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
111 unsigned int auth_data_len;
112 BOOL finished; /* finished authenticating */
115 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
116 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
117 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
118 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
119 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
120 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
121 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
122 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
123 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
124 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
125 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
126 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
127 static void HTTP_DrainContent(WININETHTTPREQW *req);
128 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr);
130 static LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
133 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
134 if (HeaderIndex == -1)
137 return &req->pCustHeaders[HeaderIndex];
140 /***********************************************************************
141 * HTTP_Tokenize (internal)
143 * Tokenize a string, allocating memory for the tokens.
145 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
147 LPWSTR * token_array;
154 /* empty string has no tokens */
158 for (i = 0; string[i]; i++)
160 if (!strncmpW(string+i, token_string, strlenW(token_string)))
164 /* we want to skip over separators, but not the null terminator */
165 for (j = 0; j < strlenW(token_string) - 1; j++)
173 /* add 1 for terminating NULL */
174 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
175 token_array[tokens] = NULL;
178 for (i = 0; i < tokens; i++)
181 next_token = strstrW(string, token_string);
182 if (!next_token) next_token = string+strlenW(string);
183 len = next_token - string;
184 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
185 memcpy(token_array[i], string, len*sizeof(WCHAR));
186 token_array[i][len] = '\0';
187 string = next_token+strlenW(token_string);
192 /***********************************************************************
193 * HTTP_FreeTokens (internal)
195 * Frees memory returned from HTTP_Tokenize.
197 static void HTTP_FreeTokens(LPWSTR * token_array)
200 for (i = 0; token_array[i]; i++)
201 HeapFree(GetProcessHeap(), 0, token_array[i]);
202 HeapFree(GetProcessHeap(), 0, token_array);
205 /* **********************************************************************
207 * Helper functions for the HttpSendRequest(Ex) functions
210 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
212 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
213 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
215 TRACE("%p\n", lpwhr);
217 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
218 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
219 req->dwContentLength, req->bEndRequest);
221 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
224 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
226 static const WCHAR szSlash[] = { '/',0 };
227 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
229 /* If we don't have a path we set it to root */
230 if (NULL == lpwhr->lpszPath)
231 lpwhr->lpszPath = WININET_strdupW(szSlash);
232 else /* remove \r and \n*/
234 int nLen = strlenW(lpwhr->lpszPath);
235 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
238 lpwhr->lpszPath[nLen]='\0';
240 /* Replace '\' with '/' */
243 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
247 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
248 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
249 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
251 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
252 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
254 strcpyW(fixurl + 1, lpwhr->lpszPath);
255 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
256 lpwhr->lpszPath = fixurl;
260 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
262 LPWSTR requestString;
268 static const WCHAR szSpace[] = { ' ',0 };
269 static const WCHAR szColon[] = { ':',' ',0 };
270 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
272 /* allocate space for an array of all the string pointers to be added */
273 len = (lpwhr->nCustHeaders)*4 + 10;
274 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
276 /* add the verb, path and HTTP version string */
284 /* Append custom request headers */
285 for (i = 0; i < lpwhr->nCustHeaders; i++)
287 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
290 req[n++] = lpwhr->pCustHeaders[i].lpszField;
292 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
294 TRACE("Adding custom header %s (%s)\n",
295 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
296 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
301 ERR("oops. buffer overrun\n");
304 requestString = HTTP_build_req( req, 4 );
305 HeapFree( GetProcessHeap(), 0, req );
308 * Set (header) termination string for request
309 * Make sure there's exactly two new lines at the end of the request
311 p = &requestString[strlenW(requestString)-1];
312 while ( (*p == '\n') || (*p == '\r') )
314 strcpyW( p+1, sztwocrlf );
316 return requestString;
319 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
321 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
324 LPHTTPHEADERW setCookieHeader;
326 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
328 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
330 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
333 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','%','s',0};
337 Host = HTTP_GetHeader(lpwhr,szHost);
338 len = lstrlenW(Host->lpszValue) + 9 + lstrlenW(lpwhr->lpszPath);
339 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
340 sprintfW(buf_url, szFmt, Host->lpszValue, lpwhr->lpszPath);
341 InternetSetCookieW(buf_url, NULL, setCookieHeader->lpszValue);
343 HeapFree(GetProcessHeap(), 0, buf_url);
349 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
351 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
352 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
353 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
356 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
357 struct HttpAuthInfo **ppAuthInfo,
358 LPWSTR domain_and_username, LPWSTR password )
360 SECURITY_STATUS sec_status;
361 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
364 TRACE("%s\n", debugstr_w(pszAuthValue));
371 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
375 SecInvalidateHandle(&pAuthInfo->cred);
376 SecInvalidateHandle(&pAuthInfo->ctx);
377 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
379 pAuthInfo->auth_data = NULL;
380 pAuthInfo->auth_data_len = 0;
381 pAuthInfo->finished = FALSE;
383 if (is_basic_auth_value(pszAuthValue))
385 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
386 pAuthInfo->scheme = WININET_strdupW(szBasic);
387 if (!pAuthInfo->scheme)
389 HeapFree(GetProcessHeap(), 0, pAuthInfo);
396 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
398 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
399 if (!pAuthInfo->scheme)
401 HeapFree(GetProcessHeap(), 0, pAuthInfo);
405 if (domain_and_username)
407 WCHAR *user = strchrW(domain_and_username, '\\');
408 WCHAR *domain = domain_and_username;
410 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
412 pAuthData = &nt_auth_identity;
417 user = domain_and_username;
421 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
422 nt_auth_identity.User = user;
423 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
424 nt_auth_identity.Domain = domain;
425 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
426 nt_auth_identity.Password = password;
427 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
430 /* use default credentials */
433 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
434 SECPKG_CRED_OUTBOUND, NULL,
436 NULL, &pAuthInfo->cred,
438 if (sec_status == SEC_E_OK)
440 PSecPkgInfoW sec_pkg_info;
441 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
442 if (sec_status == SEC_E_OK)
444 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
445 FreeContextBuffer(sec_pkg_info);
448 if (sec_status != SEC_E_OK)
450 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
451 debugstr_w(pAuthInfo->scheme), sec_status);
452 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
453 HeapFree(GetProcessHeap(), 0, pAuthInfo);
457 *ppAuthInfo = pAuthInfo;
459 else if (pAuthInfo->finished)
462 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
463 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
465 ERR("authentication scheme changed from %s to %s\n",
466 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
470 if (is_basic_auth_value(pszAuthValue))
476 TRACE("basic authentication\n");
478 /* we don't cache credentials for basic authentication, so we can't
479 * retrieve them if the application didn't pass us any credentials */
480 if (!domain_and_username) return FALSE;
482 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
483 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
485 /* length includes a nul terminator, which will be re-used for the ':' */
486 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
490 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
491 auth_data[userlen] = ':';
492 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
494 pAuthInfo->auth_data = auth_data;
495 pAuthInfo->auth_data_len = userlen + 1 + passlen;
496 pAuthInfo->finished = TRUE;
503 SecBufferDesc out_desc, in_desc;
505 unsigned char *buffer;
506 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
507 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
509 in.BufferType = SECBUFFER_TOKEN;
513 in_desc.ulVersion = 0;
514 in_desc.cBuffers = 1;
515 in_desc.pBuffers = ∈
517 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
518 if (*pszAuthData == ' ')
521 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
522 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
523 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
526 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
528 out.BufferType = SECBUFFER_TOKEN;
529 out.cbBuffer = pAuthInfo->max_token;
530 out.pvBuffer = buffer;
532 out_desc.ulVersion = 0;
533 out_desc.cBuffers = 1;
534 out_desc.pBuffers = &out;
536 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
537 first ? NULL : &pAuthInfo->ctx,
538 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
539 context_req, 0, SECURITY_NETWORK_DREP,
540 in.pvBuffer ? &in_desc : NULL,
541 0, &pAuthInfo->ctx, &out_desc,
542 &pAuthInfo->attr, &pAuthInfo->exp);
543 if (sec_status == SEC_E_OK)
545 pAuthInfo->finished = TRUE;
546 pAuthInfo->auth_data = out.pvBuffer;
547 pAuthInfo->auth_data_len = out.cbBuffer;
548 TRACE("sending last auth packet\n");
550 else if (sec_status == SEC_I_CONTINUE_NEEDED)
552 pAuthInfo->auth_data = out.pvBuffer;
553 pAuthInfo->auth_data_len = out.cbBuffer;
554 TRACE("sending next auth packet\n");
558 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
559 pAuthInfo->finished = TRUE;
560 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
568 /***********************************************************************
569 * HTTP_HttpAddRequestHeadersW (internal)
571 static BOOL HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
572 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
577 BOOL bSuccess = FALSE;
580 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
582 if( dwHeaderLength == ~0U )
583 len = strlenW(lpszHeader);
585 len = dwHeaderLength;
586 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
587 lstrcpynW( buffer, lpszHeader, len + 1);
593 LPWSTR * pFieldAndValue;
597 while (*lpszEnd != '\0')
599 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
604 if (*lpszStart == '\0')
607 if (*lpszEnd == '\r')
610 lpszEnd += 2; /* Jump over \r\n */
612 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
613 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
616 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
618 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
619 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
620 HTTP_FreeTokens(pFieldAndValue);
626 HeapFree(GetProcessHeap(), 0, buffer);
631 /***********************************************************************
632 * HttpAddRequestHeadersW (WININET.@)
634 * Adds one or more HTTP header to the request handler
637 * On Windows if dwHeaderLength includes the trailing '\0', then
638 * HttpAddRequestHeadersW() adds it too. However this results in an
639 * invalid Http header which is rejected by some servers so we probably
640 * don't need to match Windows on that point.
647 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
648 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
650 BOOL bSuccess = FALSE;
651 LPWININETHTTPREQW lpwhr;
653 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
658 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
659 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
661 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
664 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
667 WININET_Release( &lpwhr->hdr );
672 /***********************************************************************
673 * HttpAddRequestHeadersA (WININET.@)
675 * Adds one or more HTTP header to the request handler
682 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
683 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
689 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
691 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
692 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
693 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
694 if( dwHeaderLength != ~0U )
695 dwHeaderLength = len;
697 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
699 HeapFree( GetProcessHeap(), 0, hdr );
704 /***********************************************************************
705 * HttpEndRequestA (WININET.@)
707 * Ends an HTTP request that was started by HttpSendRequestEx
714 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
715 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
717 LPINTERNET_BUFFERSA ptr;
718 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
721 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
726 lpBuffersOutW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
727 sizeof(INTERNET_BUFFERSW));
729 lpBuffersOutW = NULL;
731 ptrW = lpBuffersOutW;
734 if (ptr->lpvBuffer && ptr->dwBufferLength)
735 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
736 ptrW->dwBufferLength = ptr->dwBufferLength;
737 ptrW->dwBufferTotal= ptr->dwBufferTotal;
740 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
741 sizeof(INTERNET_BUFFERSW));
747 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
751 ptrW = lpBuffersOutW;
754 LPINTERNET_BUFFERSW ptrW2;
756 FIXME("Do we need to translate info out of these buffer?\n");
758 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
760 HeapFree(GetProcessHeap(),0,ptrW);
768 /***********************************************************************
769 * HttpEndRequestW (WININET.@)
771 * Ends an HTTP request that was started by HttpSendRequestEx
778 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
779 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
782 LPWININETHTTPREQW lpwhr;
787 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
789 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
791 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
793 WININET_Release( &lpwhr->hdr );
797 lpwhr->hdr.dwFlags |= dwFlags;
798 lpwhr->hdr.dwContext = dwContext;
800 /* We appear to do nothing with lpBuffersOut.. is that correct? */
802 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
803 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
805 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
809 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
810 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
812 /* process cookies here. Is this right? */
813 HTTP_ProcessCookies(lpwhr);
815 dwBufferSize = sizeof(lpwhr->dwContentLength);
816 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
817 &lpwhr->dwContentLength,&dwBufferSize,NULL))
818 lpwhr->dwContentLength = -1;
820 if (lpwhr->dwContentLength == 0)
821 HTTP_FinishedReading(lpwhr);
823 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
825 DWORD dwCode,dwCodeLength=sizeof(DWORD);
826 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
827 (dwCode==302 || dwCode==301 || dwCode==303))
829 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
830 dwBufferSize=sizeof(szNewLocation);
831 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
833 /* redirects are always GETs */
834 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
835 lpwhr->lpszVerb = WININET_strdupW(szGET);
836 HTTP_DrainContent(lpwhr);
837 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
838 INTERNET_STATUS_REDIRECT, szNewLocation,
840 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
842 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
847 WININET_Release( &lpwhr->hdr );
848 TRACE("%i <--\n",rc);
852 /***********************************************************************
853 * HttpOpenRequestW (WININET.@)
855 * Open a HTTP request handle
858 * HINTERNET a HTTP request handle on success
862 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
863 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
864 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
865 DWORD dwFlags, DWORD_PTR dwContext)
867 LPWININETHTTPSESSIONW lpwhs;
868 HINTERNET handle = NULL;
870 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
871 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
872 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
874 if(lpszAcceptTypes!=NULL)
877 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
878 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
881 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
882 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
884 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
889 * My tests seem to show that the windows version does not
890 * become asynchronous until after this point. And anyhow
891 * if this call was asynchronous then how would you get the
892 * necessary HINTERNET pointer returned by this function.
895 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
896 lpszVersion, lpszReferrer, lpszAcceptTypes,
900 WININET_Release( &lpwhs->hdr );
901 TRACE("returning %p\n", handle);
906 /***********************************************************************
907 * HttpOpenRequestA (WININET.@)
909 * Open a HTTP request handle
912 * HINTERNET a HTTP request handle on success
916 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
917 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
918 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
919 DWORD dwFlags, DWORD_PTR dwContext)
921 LPWSTR szVerb = NULL, szObjectName = NULL;
922 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
923 INT len, acceptTypesCount;
924 HINTERNET rc = FALSE;
927 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
928 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
929 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
934 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
935 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
938 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
943 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
944 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
947 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
952 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
953 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
956 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
961 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
962 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
965 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
970 acceptTypesCount = 0;
971 types = lpszAcceptTypes;
976 /* find out how many there are */
977 if (*types && **types)
979 TRACE("accept type: %s\n", debugstr_a(*types));
985 WARN("invalid accept type pointer\n");
990 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
991 if (!szAcceptTypes) goto end;
993 acceptTypesCount = 0;
994 types = lpszAcceptTypes;
999 if (*types && **types)
1001 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1002 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1004 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1010 /* ignore invalid pointer */
1015 szAcceptTypes[acceptTypesCount] = NULL;
1018 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1019 szVersion, szReferrer,
1020 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1025 acceptTypesCount = 0;
1026 while (szAcceptTypes[acceptTypesCount])
1028 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1031 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1033 HeapFree(GetProcessHeap(), 0, szReferrer);
1034 HeapFree(GetProcessHeap(), 0, szVersion);
1035 HeapFree(GetProcessHeap(), 0, szObjectName);
1036 HeapFree(GetProcessHeap(), 0, szVerb);
1041 /***********************************************************************
1044 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1047 static const CHAR HTTP_Base64Enc[] =
1048 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1052 /* first 6 bits, all from bin[0] */
1053 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1054 x = (bin[0] & 3) << 4;
1056 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1059 base64[n++] = HTTP_Base64Enc[x];
1064 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1065 x = ( bin[1] & 0x0f ) << 2;
1067 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1070 base64[n++] = HTTP_Base64Enc[x];
1074 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1076 /* last 6 bits, all from bin [2] */
1077 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1085 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1086 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1087 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1088 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1089 static const signed char HTTP_Base64Dec[256] =
1091 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1092 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1093 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1094 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1095 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1096 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1097 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1098 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1099 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1100 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1101 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1102 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1103 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1104 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1105 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1106 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1107 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1108 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1109 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1110 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1111 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1112 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1113 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1114 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1115 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1116 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1120 /***********************************************************************
1123 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1131 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1132 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1133 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1134 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1136 WARN("invalid base64: %s\n", debugstr_w(base64));
1140 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1143 if ((base64[2] == '=') && (base64[3] == '='))
1145 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1146 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1148 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1152 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1155 if (base64[3] == '=')
1157 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1158 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1160 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1164 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1173 /***********************************************************************
1174 * HTTP_InsertAuthorization
1176 * Insert or delete the authorization field in the request header.
1178 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1182 static const WCHAR wszSpace[] = {' ',0};
1183 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1185 WCHAR *authorization = NULL;
1187 if (pAuthInfo->auth_data_len)
1189 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1190 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1191 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1195 strcpyW(authorization, pAuthInfo->scheme);
1196 strcatW(authorization, wszSpace);
1197 HTTP_EncodeBase64(pAuthInfo->auth_data,
1198 pAuthInfo->auth_data_len,
1199 authorization+strlenW(authorization));
1201 /* clear the data as it isn't valid now that it has been sent to the
1202 * server, unless it's Basic authentication which doesn't do
1203 * connection tracking */
1204 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1206 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1207 pAuthInfo->auth_data = NULL;
1208 pAuthInfo->auth_data_len = 0;
1212 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1214 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1216 HeapFree(GetProcessHeap(), 0, authorization);
1221 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1223 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1226 size = sizeof(new_location);
1227 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1229 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1230 strcpyW( url, new_location );
1234 static const WCHAR slash[] = { '/',0 };
1235 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1236 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1237 WININETHTTPSESSIONW *session = req->lpHttpSession;
1239 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1240 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1242 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1244 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1245 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1247 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1248 if (req->lpszPath[0] != '/') strcatW( url, slash );
1249 strcatW( url, req->lpszPath );
1251 TRACE("url=%s\n", debugstr_w(url));
1255 /***********************************************************************
1256 * HTTP_DealWithProxy
1258 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1259 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1261 WCHAR buf[MAXHOSTNAME];
1262 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1263 static WCHAR szNul[] = { 0 };
1264 URL_COMPONENTSW UrlComponents;
1265 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1266 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1268 memset( &UrlComponents, 0, sizeof UrlComponents );
1269 UrlComponents.dwStructSize = sizeof UrlComponents;
1270 UrlComponents.lpszHostName = buf;
1271 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1273 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1274 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1275 sprintfW(proxy, szFormat, hIC->lpszProxy);
1277 strcpyW(proxy, hIC->lpszProxy);
1278 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1280 if( UrlComponents.dwHostNameLength == 0 )
1283 if( !lpwhr->lpszPath )
1284 lpwhr->lpszPath = szNul;
1286 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1287 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1289 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1290 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1291 lpwhs->nServerPort = UrlComponents.nPort;
1293 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1297 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1300 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1302 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1303 INTERNET_STATUS_RESOLVING_NAME,
1304 lpwhs->lpszServerName,
1305 strlenW(lpwhs->lpszServerName)+1);
1307 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1308 &lpwhs->socketAddress))
1310 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1314 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1315 szaddr, sizeof(szaddr));
1316 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1317 INTERNET_STATUS_NAME_RESOLVED,
1318 szaddr, strlen(szaddr)+1);
1320 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1325 /***********************************************************************
1326 * HTTPREQ_Destroy (internal)
1328 * Deallocate request handle
1331 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1333 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1338 if(lpwhr->hCacheFile)
1339 CloseHandle(lpwhr->hCacheFile);
1341 if(lpwhr->lpszCacheFile) {
1342 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1343 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1346 WININET_Release(&lpwhr->lpHttpSession->hdr);
1348 if (lpwhr->pAuthInfo)
1350 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1351 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1352 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1353 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1355 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1356 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1357 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1358 lpwhr->pAuthInfo = NULL;
1361 if (lpwhr->pProxyAuthInfo)
1363 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1364 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1365 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1366 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1368 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1369 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1370 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1371 lpwhr->pProxyAuthInfo = NULL;
1374 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1375 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1376 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1377 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1378 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1380 for (i = 0; i < lpwhr->nCustHeaders; i++)
1382 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1383 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1386 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1387 HeapFree(GetProcessHeap(), 0, lpwhr);
1390 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1392 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1394 TRACE("%p\n",lpwhr);
1396 if (!NETCON_connected(&lpwhr->netConnection))
1399 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1400 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1402 NETCON_close(&lpwhr->netConnection);
1404 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1405 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1408 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1410 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1413 case INTERNET_OPTION_HANDLE_TYPE:
1414 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1416 if (*size < sizeof(ULONG))
1417 return ERROR_INSUFFICIENT_BUFFER;
1419 *size = sizeof(DWORD);
1420 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1421 return ERROR_SUCCESS;
1423 case INTERNET_OPTION_URL: {
1424 WCHAR url[INTERNET_MAX_URL_LENGTH];
1429 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1430 static const WCHAR hostW[] = {'H','o','s','t',0};
1432 TRACE("INTERNET_OPTION_URL\n");
1434 host = HTTP_GetHeader(req, hostW);
1435 strcpyW(url, httpW);
1436 strcatW(url, host->lpszValue);
1437 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1439 strcatW(url, req->lpszPath);
1441 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1444 len = (strlenW(url)+1) * sizeof(WCHAR);
1446 return ERROR_INSUFFICIENT_BUFFER;
1449 strcpyW(buffer, url);
1450 return ERROR_SUCCESS;
1452 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1454 return ERROR_INSUFFICIENT_BUFFER;
1457 return ERROR_SUCCESS;
1461 case INTERNET_OPTION_DATAFILE_NAME: {
1464 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1466 if(!req->lpszCacheFile) {
1468 return ERROR_INTERNET_ITEM_NOT_FOUND;
1472 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1473 if(*size < req_size)
1474 return ERROR_INSUFFICIENT_BUFFER;
1477 memcpy(buffer, req->lpszCacheFile, *size);
1478 return ERROR_SUCCESS;
1480 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1481 if (req_size > *size)
1482 return ERROR_INSUFFICIENT_BUFFER;
1484 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1485 -1, buffer, *size, NULL, NULL);
1486 return ERROR_SUCCESS;
1490 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1491 PCCERT_CONTEXT context;
1493 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1494 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1495 return ERROR_INSUFFICIENT_BUFFER;
1498 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1500 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1503 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1504 info->ftExpiry = context->pCertInfo->NotAfter;
1505 info->ftStart = context->pCertInfo->NotBefore;
1507 len = CertNameToStrW(context->dwCertEncodingType,
1508 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1509 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1510 if(info->lpszSubjectInfo)
1511 CertNameToStrW(context->dwCertEncodingType,
1512 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1513 info->lpszSubjectInfo, len);
1514 len = CertNameToStrW(context->dwCertEncodingType,
1515 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1516 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1517 if (info->lpszIssuerInfo)
1518 CertNameToStrW(context->dwCertEncodingType,
1519 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1520 info->lpszIssuerInfo, len);
1522 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1524 len = CertNameToStrA(context->dwCertEncodingType,
1525 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1526 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1527 if(infoA->lpszSubjectInfo)
1528 CertNameToStrA(context->dwCertEncodingType,
1529 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1530 infoA->lpszSubjectInfo, len);
1531 len = CertNameToStrA(context->dwCertEncodingType,
1532 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1533 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1534 if(infoA->lpszIssuerInfo)
1535 CertNameToStrA(context->dwCertEncodingType,
1536 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1537 infoA->lpszIssuerInfo, len);
1541 * Contrary to MSDN, these do not appear to be set.
1543 * lpszSignatureAlgName
1544 * lpszEncryptionAlgName
1547 CertFreeCertificateContext(context);
1548 return ERROR_SUCCESS;
1553 return INET_QueryOption(option, buffer, size, unicode);
1556 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1558 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1561 case INTERNET_OPTION_SEND_TIMEOUT:
1562 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1563 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1565 if (size != sizeof(DWORD))
1566 return ERROR_INVALID_PARAMETER;
1568 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1571 case INTERNET_OPTION_USERNAME:
1572 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1573 if (!(req->lpHttpSession->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1574 return ERROR_SUCCESS;
1576 case INTERNET_OPTION_PASSWORD:
1577 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1578 if (!(req->lpHttpSession->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1579 return ERROR_SUCCESS;
1582 return ERROR_INTERNET_INVALID_OPTION;
1585 static void HTTP_ReceiveRequestData(WININETHTTPREQW *req, BOOL first_notif)
1587 INTERNET_ASYNC_RESULT iar;
1594 res = NETCON_recv(&req->netConnection, buffer,
1595 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1596 MSG_PEEK, &available);
1599 iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
1600 iar.dwError = first_notif ? 0 : available;
1603 iar.dwError = INTERNET_GetLastError();
1606 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1607 sizeof(INTERNET_ASYNC_RESULT));
1610 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1614 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1615 sync ? MSG_WAITALL : 0, &bytes_read)) {
1616 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1617 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1619 /* always return success, even if the network layer returns an error */
1621 HTTP_FinishedReading(req);
1622 return ERROR_SUCCESS;
1625 req->dwContentRead += bytes_read;
1628 if(req->lpszCacheFile) {
1630 DWORD dwBytesWritten;
1632 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1634 WARN("WriteFile failed: %u\n", GetLastError());
1637 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1638 HTTP_FinishedReading(req);
1640 return ERROR_SUCCESS;
1643 static DWORD get_chunk_size(const char *buffer)
1648 for (p = buffer; *p; p++)
1650 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1651 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1652 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1653 else if (*p == ';') break;
1658 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1660 char reply[MAX_REPLY_LEN], *p = buffer;
1661 DWORD buflen, to_read, to_write = size;
1667 if (*read == size) break;
1669 if (req->dwContentLength == ~0u) /* new chunk */
1671 buflen = sizeof(reply);
1672 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1674 if (!(req->dwContentLength = get_chunk_size(reply)))
1676 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1677 HTTP_GetResponseHeaders(req, FALSE);
1681 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1683 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1685 if (bytes_read != to_read)
1686 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1688 /* always return success, even if the network layer returns an error */
1692 if (!bytes_read) break;
1694 req->dwContentRead += bytes_read;
1695 to_write -= bytes_read;
1696 *read += bytes_read;
1698 if (req->lpszCacheFile)
1700 DWORD dwBytesWritten;
1702 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1703 WARN("WriteFile failed: %u\n", GetLastError());
1707 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1709 req->dwContentRead = 0;
1710 req->dwContentLength = ~0u;
1712 buflen = sizeof(reply);
1713 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1715 ERR("Malformed chunk\n");
1721 if (!*read) HTTP_FinishedReading(req);
1722 return ERROR_SUCCESS;
1725 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1728 DWORD buflen = sizeof(encoding);
1729 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1731 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1732 !strcmpiW(encoding, szChunked))
1734 return HTTP_ReadChunked(req, buffer, size, read, sync);
1737 return HTTP_Read(req, buffer, size, read, sync);
1740 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1742 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1743 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1746 static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
1748 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1749 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1750 INTERNET_ASYNC_RESULT iar;
1753 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1755 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1756 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1758 iar.dwResult = res == ERROR_SUCCESS;
1761 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1762 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1763 sizeof(INTERNET_ASYNC_RESULT));
1766 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1767 DWORD flags, DWORD_PTR context)
1770 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1773 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1774 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1776 if (buffers->dwStructSize != sizeof(*buffers))
1777 return ERROR_INVALID_PARAMETER;
1779 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1781 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1782 DWORD available = 0;
1784 NETCON_query_data_available(&req->netConnection, &available);
1787 WORKREQUEST workRequest;
1789 workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
1790 workRequest.hdr = WININET_AddRef(&req->hdr);
1791 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1793 INTERNET_AsyncCall(&workRequest);
1795 return ERROR_IO_PENDING;
1799 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1800 !(flags & IRF_NO_WAIT));
1802 if (res == ERROR_SUCCESS) {
1803 DWORD size = buffers->dwBufferLength;
1804 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1805 &size, sizeof(size));
1811 static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
1813 struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
1814 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1815 INTERNET_ASYNC_RESULT iar;
1818 TRACE("INTERNETREADFILEEXW %p\n", workRequest->hdr);
1820 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1821 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1823 iar.dwResult = res == ERROR_SUCCESS;
1826 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1827 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1828 sizeof(INTERNET_ASYNC_RESULT));
1831 static DWORD HTTPREQ_ReadFileExW(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSW *buffers,
1832 DWORD flags, DWORD_PTR context)
1835 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1838 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1839 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1841 if (buffers->dwStructSize != sizeof(*buffers))
1842 return ERROR_INVALID_PARAMETER;
1844 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1846 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1847 DWORD available = 0;
1849 NETCON_query_data_available(&req->netConnection, &available);
1852 WORKREQUEST workRequest;
1854 workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
1855 workRequest.hdr = WININET_AddRef(&req->hdr);
1856 workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
1858 INTERNET_AsyncCall(&workRequest);
1860 return ERROR_IO_PENDING;
1864 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1865 !(flags & IRF_NO_WAIT));
1867 if (res == ERROR_SUCCESS) {
1868 DWORD size = buffers->dwBufferLength;
1869 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1870 &size, sizeof(size));
1876 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1879 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1881 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
1884 if ((ret = NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written)))
1885 lpwhr->dwBytesWritten += *written;
1887 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
1891 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1893 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1895 HTTP_ReceiveRequestData(req, FALSE);
1898 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1900 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1904 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1906 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1907 return ERROR_SUCCESS;
1909 /* Even if we are in async mode, we need to determine whether
1910 * there is actually more data available. We do this by trying
1911 * to peek only a single byte in async mode. */
1912 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1914 if (NETCON_recv(&req->netConnection, buffer,
1915 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1916 MSG_PEEK, (int *)available) && async && *available)
1918 WORKREQUEST workRequest;
1921 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1922 workRequest.hdr = WININET_AddRef( &req->hdr );
1924 INTERNET_AsyncCall(&workRequest);
1926 return ERROR_IO_PENDING;
1929 return ERROR_SUCCESS;
1932 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1934 HTTPREQ_CloseConnection,
1935 HTTPREQ_QueryOption,
1938 HTTPREQ_ReadFileExA,
1939 HTTPREQ_ReadFileExW,
1941 HTTPREQ_QueryDataAvailable,
1945 /***********************************************************************
1946 * HTTP_HttpOpenRequestW (internal)
1948 * Open a HTTP request handle
1951 * HINTERNET a HTTP request handle on success
1955 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1956 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1957 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1958 DWORD dwFlags, DWORD_PTR dwContext)
1960 LPWININETAPPINFOW hIC = NULL;
1961 LPWININETHTTPREQW lpwhr;
1962 LPWSTR lpszHostName = NULL;
1963 HINTERNET handle = NULL;
1964 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1969 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1970 hIC = lpwhs->lpAppInfo;
1972 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1975 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1978 lpwhr->hdr.htype = WH_HHTTPREQ;
1979 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1980 lpwhr->hdr.dwFlags = dwFlags;
1981 lpwhr->hdr.dwContext = dwContext;
1982 lpwhr->hdr.refs = 1;
1983 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1984 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1986 WININET_AddRef( &lpwhs->hdr );
1987 lpwhr->lpHttpSession = lpwhs;
1988 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1990 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
1991 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
1992 if (NULL == lpszHostName)
1994 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1998 handle = WININET_AllocHandle( &lpwhr->hdr );
2001 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2005 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
2007 InternetCloseHandle( handle );
2012 if (lpszObjectName && *lpszObjectName) {
2016 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
2017 if (rc != E_POINTER)
2018 len = strlenW(lpszObjectName)+1;
2019 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2020 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
2021 URL_ESCAPE_SPACES_ONLY);
2024 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2025 strcpyW(lpwhr->lpszPath,lpszObjectName);
2029 if (lpszReferrer && *lpszReferrer)
2030 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2032 if (lpszAcceptTypes)
2035 for (i = 0; lpszAcceptTypes[i]; i++)
2037 if (!*lpszAcceptTypes[i]) continue;
2038 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2039 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
2040 HTTP_ADDHDR_FLAG_REQ |
2041 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
2045 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
2048 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
2050 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
2052 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
2053 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
2054 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
2056 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2057 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
2058 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2061 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
2062 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2064 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2065 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2066 INTERNET_DEFAULT_HTTPS_PORT :
2067 INTERNET_DEFAULT_HTTP_PORT);
2069 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2070 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2071 INTERNET_DEFAULT_HTTPS_PORT :
2072 INTERNET_DEFAULT_HTTP_PORT);
2074 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2075 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2077 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2078 INTERNET_STATUS_HANDLE_CREATED, &handle,
2082 HeapFree(GetProcessHeap(), 0, lpszHostName);
2084 WININET_Release( &lpwhr->hdr );
2086 TRACE("<-- %p (%p)\n", handle, lpwhr);
2090 /* read any content returned by the server so that the connection can be
2092 static void HTTP_DrainContent(WININETHTTPREQW *req)
2096 if (!NETCON_connected(&req->netConnection)) return;
2098 if (req->dwContentLength == -1)
2099 NETCON_close(&req->netConnection);
2104 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2106 } while (bytes_read);
2109 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2110 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2111 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2112 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2113 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2114 static const WCHAR szAge[] = { 'A','g','e',0 };
2115 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2116 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2117 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2118 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2119 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2120 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2121 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2122 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2123 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2124 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2125 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2126 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 };
2127 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2128 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2129 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2130 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2131 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2132 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2133 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2134 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2135 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2136 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2137 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2138 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2139 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2140 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2141 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2142 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2143 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2144 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2145 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2146 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2147 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2148 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2149 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2150 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2151 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2152 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2153 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 };
2154 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2155 static const WCHAR szURI[] = { 'U','R','I',0 };
2156 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2157 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2158 static const WCHAR szVia[] = { 'V','i','a',0 };
2159 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2160 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2162 static const LPCWSTR header_lookup[] = {
2163 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2164 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2165 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2166 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2167 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2168 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2169 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2170 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2171 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2172 szDate, /* HTTP_QUERY_DATE = 9 */
2173 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2174 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2175 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2176 szURI, /* HTTP_QUERY_URI = 13 */
2177 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2178 NULL, /* HTTP_QUERY_COST = 15 */
2179 NULL, /* HTTP_QUERY_LINK = 16 */
2180 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2181 NULL, /* HTTP_QUERY_VERSION = 18 */
2182 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2183 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2184 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2185 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2186 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2187 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2188 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2189 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2190 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2191 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2192 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2193 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2194 NULL, /* HTTP_QUERY_FROM = 31 */
2195 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2196 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2197 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2198 szReferer, /* HTTP_QUERY_REFERER = 35 */
2199 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2200 szServer, /* HTTP_QUERY_SERVER = 37 */
2201 NULL, /* HTTP_TITLE = 38 */
2202 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2203 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2204 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2205 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2206 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2207 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2208 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2209 NULL, /* HTTP_QUERY_REFRESH = 46 */
2210 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2211 szAge, /* HTTP_QUERY_AGE = 48 */
2212 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2213 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2214 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2215 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2216 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2217 szETag, /* HTTP_QUERY_ETAG = 54 */
2218 szHost, /* HTTP_QUERY_HOST = 55 */
2219 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2220 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2221 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2222 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2223 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2224 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2225 szRange, /* HTTP_QUERY_RANGE = 62 */
2226 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2227 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2228 szVary, /* HTTP_QUERY_VARY = 65 */
2229 szVia, /* HTTP_QUERY_VIA = 66 */
2230 szWarning, /* HTTP_QUERY_WARNING = 67 */
2231 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2232 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2233 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2236 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2238 /***********************************************************************
2239 * HTTP_HttpQueryInfoW (internal)
2241 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2242 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2244 LPHTTPHEADERW lphttpHdr = NULL;
2245 BOOL bSuccess = FALSE;
2246 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2247 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2248 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2251 /* Find requested header structure */
2254 case HTTP_QUERY_CUSTOM:
2255 if (!lpBuffer) return FALSE;
2256 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2259 case HTTP_QUERY_RAW_HEADERS_CRLF:
2266 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2268 headers = lpwhr->lpszRawHeaders;
2271 len = strlenW(headers) * sizeof(WCHAR);
2273 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2275 len += sizeof(WCHAR);
2276 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2282 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2285 len = strlenW(szCrLf) * sizeof(WCHAR);
2286 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2288 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2291 *lpdwBufferLength = len;
2294 HeapFree(GetProcessHeap(), 0, headers);
2297 case HTTP_QUERY_RAW_HEADERS:
2299 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2301 LPWSTR pszString = lpBuffer;
2303 for (i = 0; ppszRawHeaderLines[i]; i++)
2304 size += strlenW(ppszRawHeaderLines[i]) + 1;
2306 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2308 HTTP_FreeTokens(ppszRawHeaderLines);
2309 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2310 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2315 for (i = 0; ppszRawHeaderLines[i]; i++)
2317 DWORD len = strlenW(ppszRawHeaderLines[i]);
2318 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2322 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2324 *lpdwBufferLength = size * sizeof(WCHAR);
2325 HTTP_FreeTokens(ppszRawHeaderLines);
2329 case HTTP_QUERY_STATUS_TEXT:
2330 if (lpwhr->lpszStatusText)
2332 DWORD len = strlenW(lpwhr->lpszStatusText);
2333 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2335 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2336 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2341 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2342 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2344 *lpdwBufferLength = len * sizeof(WCHAR);
2348 case HTTP_QUERY_VERSION:
2349 if (lpwhr->lpszVersion)
2351 DWORD len = strlenW(lpwhr->lpszVersion);
2352 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2354 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2355 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2360 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2361 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2363 *lpdwBufferLength = len * sizeof(WCHAR);
2368 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2370 if (level < LAST_TABLE_HEADER && header_lookup[level])
2371 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2372 requested_index,request_only);
2376 lphttpHdr = &lpwhr->pCustHeaders[index];
2378 /* Ensure header satisfies requested attributes */
2380 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2381 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2383 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2387 if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2389 /* coalesce value to requested type */
2390 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2392 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2393 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2396 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2402 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2404 tmpTM = *gmtime(&tmpTime);
2405 STHook = (SYSTEMTIME *)lpBuffer;
2406 STHook->wDay = tmpTM.tm_mday;
2407 STHook->wHour = tmpTM.tm_hour;
2408 STHook->wMilliseconds = 0;
2409 STHook->wMinute = tmpTM.tm_min;
2410 STHook->wDayOfWeek = tmpTM.tm_wday;
2411 STHook->wMonth = tmpTM.tm_mon + 1;
2412 STHook->wSecond = tmpTM.tm_sec;
2413 STHook->wYear = tmpTM.tm_year;
2416 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2417 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2418 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2420 else if (lphttpHdr->lpszValue)
2422 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2424 if (len > *lpdwBufferLength)
2426 *lpdwBufferLength = len;
2427 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2432 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2433 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2435 *lpdwBufferLength = len - sizeof(WCHAR);
2441 /***********************************************************************
2442 * HttpQueryInfoW (WININET.@)
2444 * Queries for information about an HTTP request
2451 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2452 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2454 BOOL bSuccess = FALSE;
2455 LPWININETHTTPREQW lpwhr;
2457 if (TRACE_ON(wininet)) {
2458 #define FE(x) { x, #x }
2459 static const wininet_flag_info query_flags[] = {
2460 FE(HTTP_QUERY_MIME_VERSION),
2461 FE(HTTP_QUERY_CONTENT_TYPE),
2462 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2463 FE(HTTP_QUERY_CONTENT_ID),
2464 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2465 FE(HTTP_QUERY_CONTENT_LENGTH),
2466 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2467 FE(HTTP_QUERY_ALLOW),
2468 FE(HTTP_QUERY_PUBLIC),
2469 FE(HTTP_QUERY_DATE),
2470 FE(HTTP_QUERY_EXPIRES),
2471 FE(HTTP_QUERY_LAST_MODIFIED),
2472 FE(HTTP_QUERY_MESSAGE_ID),
2474 FE(HTTP_QUERY_DERIVED_FROM),
2475 FE(HTTP_QUERY_COST),
2476 FE(HTTP_QUERY_LINK),
2477 FE(HTTP_QUERY_PRAGMA),
2478 FE(HTTP_QUERY_VERSION),
2479 FE(HTTP_QUERY_STATUS_CODE),
2480 FE(HTTP_QUERY_STATUS_TEXT),
2481 FE(HTTP_QUERY_RAW_HEADERS),
2482 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2483 FE(HTTP_QUERY_CONNECTION),
2484 FE(HTTP_QUERY_ACCEPT),
2485 FE(HTTP_QUERY_ACCEPT_CHARSET),
2486 FE(HTTP_QUERY_ACCEPT_ENCODING),
2487 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2488 FE(HTTP_QUERY_AUTHORIZATION),
2489 FE(HTTP_QUERY_CONTENT_ENCODING),
2490 FE(HTTP_QUERY_FORWARDED),
2491 FE(HTTP_QUERY_FROM),
2492 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2493 FE(HTTP_QUERY_LOCATION),
2494 FE(HTTP_QUERY_ORIG_URI),
2495 FE(HTTP_QUERY_REFERER),
2496 FE(HTTP_QUERY_RETRY_AFTER),
2497 FE(HTTP_QUERY_SERVER),
2498 FE(HTTP_QUERY_TITLE),
2499 FE(HTTP_QUERY_USER_AGENT),
2500 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2501 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2502 FE(HTTP_QUERY_ACCEPT_RANGES),
2503 FE(HTTP_QUERY_SET_COOKIE),
2504 FE(HTTP_QUERY_COOKIE),
2505 FE(HTTP_QUERY_REQUEST_METHOD),
2506 FE(HTTP_QUERY_REFRESH),
2507 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2509 FE(HTTP_QUERY_CACHE_CONTROL),
2510 FE(HTTP_QUERY_CONTENT_BASE),
2511 FE(HTTP_QUERY_CONTENT_LOCATION),
2512 FE(HTTP_QUERY_CONTENT_MD5),
2513 FE(HTTP_QUERY_CONTENT_RANGE),
2514 FE(HTTP_QUERY_ETAG),
2515 FE(HTTP_QUERY_HOST),
2516 FE(HTTP_QUERY_IF_MATCH),
2517 FE(HTTP_QUERY_IF_NONE_MATCH),
2518 FE(HTTP_QUERY_IF_RANGE),
2519 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2520 FE(HTTP_QUERY_MAX_FORWARDS),
2521 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2522 FE(HTTP_QUERY_RANGE),
2523 FE(HTTP_QUERY_TRANSFER_ENCODING),
2524 FE(HTTP_QUERY_UPGRADE),
2525 FE(HTTP_QUERY_VARY),
2527 FE(HTTP_QUERY_WARNING),
2528 FE(HTTP_QUERY_CUSTOM)
2530 static const wininet_flag_info modifier_flags[] = {
2531 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2532 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2533 FE(HTTP_QUERY_FLAG_NUMBER),
2534 FE(HTTP_QUERY_FLAG_COALESCE)
2537 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2538 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2541 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2542 TRACE(" Attribute:");
2543 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2544 if (query_flags[i].val == info) {
2545 TRACE(" %s", query_flags[i].name);
2549 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2550 TRACE(" Unknown (%08x)", info);
2553 TRACE(" Modifier:");
2554 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2555 if (modifier_flags[i].val & info_mod) {
2556 TRACE(" %s", modifier_flags[i].name);
2557 info_mod &= ~ modifier_flags[i].val;
2562 TRACE(" Unknown (%08x)", info_mod);
2567 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2568 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2570 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2574 if (lpBuffer == NULL)
2575 *lpdwBufferLength = 0;
2576 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2577 lpBuffer, lpdwBufferLength, lpdwIndex);
2581 WININET_Release( &lpwhr->hdr );
2583 TRACE("%d <--\n", bSuccess);
2587 /***********************************************************************
2588 * HttpQueryInfoA (WININET.@)
2590 * Queries for information about an HTTP request
2597 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2598 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2604 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2605 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2607 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2608 lpdwBufferLength, lpdwIndex );
2614 len = (*lpdwBufferLength)*sizeof(WCHAR);
2615 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2617 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2623 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2624 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2625 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2626 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2633 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2637 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2638 lpBuffer, *lpdwBufferLength, NULL, NULL );
2639 *lpdwBufferLength = len - 1;
2641 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2644 /* since the strings being returned from HttpQueryInfoW should be
2645 * only ASCII characters, it is reasonable to assume that all of
2646 * the Unicode characters can be reduced to a single byte */
2647 *lpdwBufferLength = len / sizeof(WCHAR);
2649 HeapFree(GetProcessHeap(), 0, bufferW );
2654 /***********************************************************************
2655 * HttpSendRequestExA (WININET.@)
2657 * Sends the specified request to the HTTP server and allows chunked
2662 * Failure: FALSE, call GetLastError() for more information.
2664 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2665 LPINTERNET_BUFFERSA lpBuffersIn,
2666 LPINTERNET_BUFFERSA lpBuffersOut,
2667 DWORD dwFlags, DWORD_PTR dwContext)
2669 INTERNET_BUFFERSW BuffersInW;
2672 LPWSTR header = NULL;
2674 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2675 lpBuffersOut, dwFlags, dwContext);
2679 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2680 if (lpBuffersIn->lpcszHeader)
2682 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2683 lpBuffersIn->dwHeadersLength,0,0);
2684 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2685 if (!(BuffersInW.lpcszHeader = header))
2687 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2690 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2691 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2695 BuffersInW.lpcszHeader = NULL;
2696 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2697 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2698 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2699 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2700 BuffersInW.Next = NULL;
2703 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2705 HeapFree(GetProcessHeap(),0,header);
2710 /***********************************************************************
2711 * HttpSendRequestExW (WININET.@)
2713 * Sends the specified request to the HTTP server and allows chunked
2718 * Failure: FALSE, call GetLastError() for more information.
2720 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2721 LPINTERNET_BUFFERSW lpBuffersIn,
2722 LPINTERNET_BUFFERSW lpBuffersOut,
2723 DWORD dwFlags, DWORD_PTR dwContext)
2726 LPWININETHTTPREQW lpwhr;
2727 LPWININETHTTPSESSIONW lpwhs;
2728 LPWININETAPPINFOW hIC;
2730 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2731 lpBuffersOut, dwFlags, dwContext);
2733 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2735 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2737 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2741 lpwhs = lpwhr->lpHttpSession;
2742 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2743 hIC = lpwhs->lpAppInfo;
2744 assert(hIC->hdr.htype == WH_HINIT);
2746 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2748 WORKREQUEST workRequest;
2749 struct WORKREQ_HTTPSENDREQUESTW *req;
2751 workRequest.asyncproc = AsyncHttpSendRequestProc;
2752 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2753 req = &workRequest.u.HttpSendRequestW;
2756 if (lpBuffersIn->lpcszHeader)
2757 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2758 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2760 req->lpszHeader = NULL;
2761 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2762 req->lpOptional = lpBuffersIn->lpvBuffer;
2763 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2764 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2768 req->lpszHeader = NULL;
2769 req->dwHeaderLength = 0;
2770 req->lpOptional = NULL;
2771 req->dwOptionalLength = 0;
2772 req->dwContentLength = 0;
2775 req->bEndRequest = FALSE;
2777 INTERNET_AsyncCall(&workRequest);
2779 * This is from windows.
2781 INTERNET_SetLastError(ERROR_IO_PENDING);
2786 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2787 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2788 lpBuffersIn->dwBufferTotal, FALSE);
2790 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2795 WININET_Release( &lpwhr->hdr );
2801 /***********************************************************************
2802 * HttpSendRequestW (WININET.@)
2804 * Sends the specified request to the HTTP server
2811 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2812 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2814 LPWININETHTTPREQW lpwhr;
2815 LPWININETHTTPSESSIONW lpwhs = NULL;
2816 LPWININETAPPINFOW hIC = NULL;
2819 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2820 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2822 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2823 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2825 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2830 lpwhs = lpwhr->lpHttpSession;
2831 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2833 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2838 hIC = lpwhs->lpAppInfo;
2839 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2841 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2846 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2848 WORKREQUEST workRequest;
2849 struct WORKREQ_HTTPSENDREQUESTW *req;
2851 workRequest.asyncproc = AsyncHttpSendRequestProc;
2852 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2853 req = &workRequest.u.HttpSendRequestW;
2858 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
2859 else size = dwHeaderLength * sizeof(WCHAR);
2861 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, size);
2862 memcpy(req->lpszHeader, lpszHeaders, size);
2865 req->lpszHeader = 0;
2866 req->dwHeaderLength = dwHeaderLength;
2867 req->lpOptional = lpOptional;
2868 req->dwOptionalLength = dwOptionalLength;
2869 req->dwContentLength = dwOptionalLength;
2870 req->bEndRequest = TRUE;
2872 INTERNET_AsyncCall(&workRequest);
2874 * This is from windows.
2876 INTERNET_SetLastError(ERROR_IO_PENDING);
2881 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2882 dwHeaderLength, lpOptional, dwOptionalLength,
2883 dwOptionalLength, TRUE);
2887 WININET_Release( &lpwhr->hdr );
2891 /***********************************************************************
2892 * HttpSendRequestA (WININET.@)
2894 * Sends the specified request to the HTTP server
2901 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2902 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2905 LPWSTR szHeaders=NULL;
2906 DWORD nLen=dwHeaderLength;
2907 if(lpszHeaders!=NULL)
2909 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2910 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2911 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2913 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2914 HeapFree(GetProcessHeap(),0,szHeaders);
2918 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2920 LPHTTPHEADERW host_header;
2922 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2924 host_header = HTTP_GetHeader(req, szHost);
2928 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2932 /***********************************************************************
2933 * HTTP_HandleRedirect (internal)
2935 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2937 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2938 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2939 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2940 WCHAR path[INTERNET_MAX_URL_LENGTH];
2945 /* if it's an absolute path, keep the same session info */
2946 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2950 URL_COMPONENTSW urlComponents;
2951 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2952 static WCHAR szHttp[] = {'h','t','t','p',0};
2953 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2954 DWORD url_length = 0;
2956 LPWSTR combined_url;
2958 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2959 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2960 urlComponents.dwSchemeLength = 0;
2961 urlComponents.lpszHostName = lpwhs->lpszHostName;
2962 urlComponents.dwHostNameLength = 0;
2963 urlComponents.nPort = lpwhs->nHostPort;
2964 urlComponents.lpszUserName = lpwhs->lpszUserName;
2965 urlComponents.dwUserNameLength = 0;
2966 urlComponents.lpszPassword = NULL;
2967 urlComponents.dwPasswordLength = 0;
2968 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2969 urlComponents.dwUrlPathLength = 0;
2970 urlComponents.lpszExtraInfo = NULL;
2971 urlComponents.dwExtraInfoLength = 0;
2973 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2974 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2977 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2979 /* convert from bytes to characters */
2980 url_length = url_length / sizeof(WCHAR) - 1;
2981 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2983 HeapFree(GetProcessHeap(), 0, orig_url);
2988 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2989 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2991 HeapFree(GetProcessHeap(), 0, orig_url);
2994 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2996 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2998 HeapFree(GetProcessHeap(), 0, orig_url);
2999 HeapFree(GetProcessHeap(), 0, combined_url);
3002 HeapFree(GetProcessHeap(), 0, orig_url);
3008 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3009 urlComponents.lpszScheme = protocol;
3010 urlComponents.dwSchemeLength = 32;
3011 urlComponents.lpszHostName = hostName;
3012 urlComponents.dwHostNameLength = MAXHOSTNAME;
3013 urlComponents.lpszUserName = userName;
3014 urlComponents.dwUserNameLength = 1024;
3015 urlComponents.lpszPassword = NULL;
3016 urlComponents.dwPasswordLength = 0;
3017 urlComponents.lpszUrlPath = path;
3018 urlComponents.dwUrlPathLength = 2048;
3019 urlComponents.lpszExtraInfo = NULL;
3020 urlComponents.dwExtraInfoLength = 0;
3021 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
3023 HeapFree(GetProcessHeap(), 0, combined_url);
3027 HeapFree(GetProcessHeap(), 0, combined_url);
3029 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
3030 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3032 TRACE("redirect from secure page to non-secure page\n");
3033 /* FIXME: warn about from secure redirect to non-secure page */
3034 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
3036 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
3037 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3039 TRACE("redirect from non-secure page to secure page\n");
3040 /* FIXME: notify about redirect to secure page */
3041 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
3044 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3046 if (lstrlenW(protocol)>4) /*https*/
3047 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3049 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3054 * This upsets redirects to binary files on sourceforge.net
3055 * and gives an html page instead of the target file
3056 * Examination of the HTTP request sent by native wininet.dll
3057 * reveals that it doesn't send a referrer in that case.
3058 * Maybe there's a flag that enables this, or maybe a referrer
3059 * shouldn't be added in case of a redirect.
3062 /* consider the current host as the referrer */
3063 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3064 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3065 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3066 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3069 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3070 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3071 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3074 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3075 len = lstrlenW(hostName);
3076 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3077 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3078 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3081 lpwhs->lpszHostName = WININET_strdupW(hostName);
3083 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3085 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3086 lpwhs->lpszUserName = NULL;
3088 lpwhs->lpszUserName = WININET_strdupW(userName);
3092 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3094 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3095 lpwhs->lpszServerName = WININET_strdupW(hostName);
3096 lpwhs->nServerPort = urlComponents.nPort;
3098 NETCON_close(&lpwhr->netConnection);
3099 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3100 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3104 TRACE("Redirect through proxy\n");
3107 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3108 lpwhr->lpszPath=NULL;
3114 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3115 if (rc != E_POINTER)
3116 needed = strlenW(path)+1;
3117 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3118 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3119 URL_ESCAPE_SPACES_ONLY);
3122 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3123 strcpyW(lpwhr->lpszPath,path);
3127 /* Remove custom content-type/length headers on redirects. */
3128 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
3130 HTTP_DeleteCustomHeader(lpwhr, index);
3131 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
3133 HTTP_DeleteCustomHeader(lpwhr, index);
3138 /***********************************************************************
3139 * HTTP_build_req (internal)
3141 * concatenate all the strings in the request together
3143 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3148 for( t = list; *t ; t++ )
3149 len += strlenW( *t );
3152 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3155 for( t = list; *t ; t++ )
3161 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3164 LPWSTR requestString;
3170 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3171 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3172 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3176 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3177 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3178 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3179 HeapFree( GetProcessHeap(), 0, lpszPath );
3181 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3182 NULL, 0, NULL, NULL );
3183 len--; /* the nul terminator isn't needed */
3184 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3185 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3186 ascii_req, len, NULL, NULL );
3187 HeapFree( GetProcessHeap(), 0, requestString );
3189 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3191 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3192 HeapFree( GetProcessHeap(), 0, ascii_req );
3193 if (!ret || cnt < 0)
3196 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3203 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3205 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3206 LPWSTR lpszCookies, lpszUrl = NULL;
3207 DWORD nCookieSize, size;
3208 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3210 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm) + strlenW(lpwhr->lpszPath)) * sizeof(WCHAR);
3211 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3212 sprintfW( lpszUrl, szUrlForm, Host->lpszValue, lpwhr->lpszPath);
3214 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3217 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3219 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3220 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3222 cnt += sprintfW(lpszCookies, szCookie);
3223 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3224 strcatW(lpszCookies, szCrLf);
3226 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_ADD);
3227 HeapFree(GetProcessHeap(), 0, lpszCookies);
3230 HeapFree(GetProcessHeap(), 0, lpszUrl);
3233 /***********************************************************************
3234 * HTTP_HttpSendRequestW (internal)
3236 * Sends the specified request to the HTTP server
3243 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3244 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3245 DWORD dwContentLength, BOOL bEndRequest)
3248 BOOL bSuccess = FALSE;
3249 LPWSTR requestString = NULL;
3252 INTERNET_ASYNC_RESULT iar;
3253 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3254 static const WCHAR szContentLength[] =
3255 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3256 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3258 TRACE("--> %p\n", lpwhr);
3260 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3262 /* if the verb is NULL default to GET */
3263 if (!lpwhr->lpszVerb)
3264 lpwhr->lpszVerb = WININET_strdupW(szGET);
3266 if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3268 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3269 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3270 lpwhr->dwBytesToWrite = dwContentLength;
3272 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3274 WCHAR *agent_header;
3275 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3278 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3279 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3280 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3282 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3283 HeapFree(GetProcessHeap(), 0, agent_header);
3285 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3287 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3288 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3290 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3292 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3293 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3294 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3304 /* like native, just in case the caller forgot to call InternetReadFile
3305 * for all the data */
3306 HTTP_DrainContent(lpwhr);
3307 lpwhr->dwContentRead = 0;
3309 if (TRACE_ON(wininet))
3311 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3312 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3316 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3318 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3320 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3321 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3323 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3324 HTTP_InsertCookies(lpwhr);
3326 /* add the headers the caller supplied */
3327 if( lpszHeaders && dwHeaderLength )
3329 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3330 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3333 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3335 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3336 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3337 HeapFree(GetProcessHeap(), 0, url);
3340 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3343 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3345 /* Send the request and store the results */
3346 if (!HTTP_OpenConnection(lpwhr))
3349 /* send the request as ASCII, tack on the optional data */
3351 dwOptionalLength = 0;
3352 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3353 NULL, 0, NULL, NULL );
3354 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3355 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3356 ascii_req, len, NULL, NULL );
3358 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3359 len = (len + dwOptionalLength - 1);
3361 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3363 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3364 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3366 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3367 HeapFree( GetProcessHeap(), 0, ascii_req );
3369 lpwhr->dwBytesWritten = dwOptionalLength;
3371 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3372 INTERNET_STATUS_REQUEST_SENT,
3373 &len, sizeof(DWORD));
3380 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3382 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3383 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3388 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3392 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3393 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3396 HTTP_ProcessCookies(lpwhr);
3398 dwBufferSize = sizeof(lpwhr->dwContentLength);
3399 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3400 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3401 lpwhr->dwContentLength = -1;
3403 if (lpwhr->dwContentLength == 0)
3404 HTTP_FinishedReading(lpwhr);
3406 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3408 dwBufferSize = sizeof(encoding);
3409 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3410 !strcmpiW(encoding, szChunked))
3412 lpwhr->dwContentLength = -1;
3415 dwBufferSize = sizeof(dwStatusCode);
3416 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3417 &dwStatusCode,&dwBufferSize,NULL))
3420 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3422 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3423 dwBufferSize=sizeof(szNewLocation);
3424 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3425 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3427 /* redirects are always GETs */
3428 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3429 lpwhr->lpszVerb = WININET_strdupW(szGET);
3431 HTTP_DrainContent(lpwhr);
3432 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3433 INTERNET_STATUS_REDIRECT, szNewLocation,
3435 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3438 HeapFree(GetProcessHeap(), 0, requestString);
3443 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3445 WCHAR szAuthValue[2048];
3447 if (dwStatusCode == HTTP_STATUS_DENIED)
3450 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3452 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3454 lpwhr->lpHttpSession->lpszUserName,
3455 lpwhr->lpHttpSession->lpszPassword))
3462 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3465 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3467 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3468 &lpwhr->pProxyAuthInfo,
3469 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3470 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3484 /* FIXME: Better check, when we have to create the cache file */
3485 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3486 WCHAR url[INTERNET_MAX_URL_LENGTH];
3487 WCHAR cacheFileName[MAX_PATH+1];
3490 b = HTTP_GetRequestURL(lpwhr, url);
3492 WARN("Could not get URL\n");
3496 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3498 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3499 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3500 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3501 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3502 WARN("Could not create file: %u\n", GetLastError());
3503 lpwhr->hCacheFile = NULL;
3506 WARN("Could not create cache entry: %08x\n", GetLastError());
3512 HeapFree(GetProcessHeap(), 0, requestString);
3514 /* TODO: send notification for P3P header */
3516 if(lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) {
3518 HTTP_ReceiveRequestData(lpwhr, TRUE);
3520 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3521 iar.dwError = INTERNET_GetLastError();
3523 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3524 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3525 sizeof(INTERNET_ASYNC_RESULT));
3530 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3534 /***********************************************************************
3535 * HTTPSESSION_Destroy (internal)
3537 * Deallocate session handle
3540 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3542 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3544 TRACE("%p\n", lpwhs);
3546 WININET_Release(&lpwhs->lpAppInfo->hdr);
3548 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3549 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3550 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3551 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3552 HeapFree(GetProcessHeap(), 0, lpwhs);
3555 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3558 case INTERNET_OPTION_HANDLE_TYPE:
3559 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3561 if (*size < sizeof(ULONG))
3562 return ERROR_INSUFFICIENT_BUFFER;
3564 *size = sizeof(DWORD);
3565 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3566 return ERROR_SUCCESS;
3569 return INET_QueryOption(option, buffer, size, unicode);
3572 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3574 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3577 case INTERNET_OPTION_USERNAME:
3579 HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
3580 if (!(ses->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3581 return ERROR_SUCCESS;
3583 case INTERNET_OPTION_PASSWORD:
3585 HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
3586 if (!(ses->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3587 return ERROR_SUCCESS;
3592 return ERROR_INTERNET_INVALID_OPTION;
3595 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3596 HTTPSESSION_Destroy,
3598 HTTPSESSION_QueryOption,
3599 HTTPSESSION_SetOption,
3608 /***********************************************************************
3609 * HTTP_Connect (internal)
3611 * Create http session handle
3614 * HINTERNET a session handle on success
3618 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3619 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3620 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3621 DWORD dwInternalFlags)
3623 LPWININETHTTPSESSIONW lpwhs = NULL;
3624 HINTERNET handle = NULL;
3628 if (!lpszServerName || !lpszServerName[0])
3630 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3634 assert( hIC->hdr.htype == WH_HINIT );
3636 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3639 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3644 * According to my tests. The name is not resolved until a request is sent
3647 lpwhs->hdr.htype = WH_HHTTPSESSION;
3648 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3649 lpwhs->hdr.dwFlags = dwFlags;
3650 lpwhs->hdr.dwContext = dwContext;
3651 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3652 lpwhs->hdr.refs = 1;
3653 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3655 WININET_AddRef( &hIC->hdr );
3656 lpwhs->lpAppInfo = hIC;
3657 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3659 handle = WININET_AllocHandle( &lpwhs->hdr );
3662 ERR("Failed to alloc handle\n");
3663 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3667 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3668 if(strchrW(hIC->lpszProxy, ' '))
3669 FIXME("Several proxies not implemented.\n");
3670 if(hIC->lpszProxyBypass)
3671 FIXME("Proxy bypass is ignored.\n");
3673 if (lpszServerName && lpszServerName[0])
3675 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3676 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3678 if (lpszUserName && lpszUserName[0])
3679 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3680 if (lpszPassword && lpszPassword[0])
3681 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3682 lpwhs->nServerPort = nServerPort;
3683 lpwhs->nHostPort = nServerPort;
3685 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3686 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3688 INTERNET_SendCallback(&hIC->hdr, dwContext,
3689 INTERNET_STATUS_HANDLE_CREATED, &handle,
3695 WININET_Release( &lpwhs->hdr );
3698 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3702 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3707 /***********************************************************************
3708 * HTTP_OpenConnection (internal)
3710 * Connect to a web server
3717 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3719 BOOL bSuccess = FALSE;
3720 LPWININETHTTPSESSIONW lpwhs;
3721 LPWININETAPPINFOW hIC = NULL;
3727 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3729 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3733 if (NETCON_connected(&lpwhr->netConnection))
3738 if (!HTTP_ResolveName(lpwhr)) goto lend;
3740 lpwhs = lpwhr->lpHttpSession;
3742 hIC = lpwhs->lpAppInfo;
3743 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3744 szaddr, sizeof(szaddr));
3745 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3746 INTERNET_STATUS_CONNECTING_TO_SERVER,
3750 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3753 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3757 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3758 sizeof(lpwhs->socketAddress)))
3761 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3763 /* Note: we differ from Microsoft's WinINet here. they seem to have
3764 * a bug that causes no status callbacks to be sent when starting
3765 * a tunnel to a proxy server using the CONNECT verb. i believe our
3766 * behaviour to be more correct and to not cause any incompatibilities
3767 * because using a secure connection through a proxy server is a rare
3768 * case that would be hard for anyone to depend on */
3769 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3772 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3774 WARN("Couldn't connect securely to host\n");
3779 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3780 INTERNET_STATUS_CONNECTED_TO_SERVER,
3781 szaddr, strlen(szaddr)+1);
3786 TRACE("%d <--\n", bSuccess);
3791 /***********************************************************************
3792 * HTTP_clear_response_headers (internal)
3794 * clear out any old response headers
3796 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3800 for( i=0; i<lpwhr->nCustHeaders; i++)
3802 if( !lpwhr->pCustHeaders[i].lpszField )
3804 if( !lpwhr->pCustHeaders[i].lpszValue )
3806 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3808 HTTP_DeleteCustomHeader( lpwhr, i );
3813 /***********************************************************************
3814 * HTTP_GetResponseHeaders (internal)
3816 * Read server response
3823 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3826 WCHAR buffer[MAX_REPLY_LEN];
3827 DWORD buflen = MAX_REPLY_LEN;
3828 BOOL bSuccess = FALSE;
3830 static const WCHAR szHundred[] = {'1','0','0',0};
3831 char bufferA[MAX_REPLY_LEN];
3832 LPWSTR status_code, status_text;
3833 DWORD cchMaxRawHeaders = 1024;
3834 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3835 DWORD cchRawHeaders = 0;
3839 /* clear old response headers (eg. from a redirect response) */
3840 if (clear) HTTP_clear_response_headers( lpwhr );
3842 if (!NETCON_connected(&lpwhr->netConnection))
3847 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3849 buflen = MAX_REPLY_LEN;
3850 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3853 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3855 /* split the version from the status code */
3856 status_code = strchrW( buffer, ' ' );
3861 /* split the status code from the status text */
3862 status_text = strchrW( status_code, ' ' );
3867 TRACE("version [%s] status code [%s] status text [%s]\n",
3868 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3870 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3872 /* Add status code */
3873 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3874 HTTP_ADDHDR_FLAG_REPLACE);
3876 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3877 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3879 lpwhr->lpszVersion= WININET_strdupW(buffer);
3880 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3882 /* Restore the spaces */
3883 *(status_code-1) = ' ';
3884 *(status_text-1) = ' ';
3886 /* regenerate raw headers */
3887 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3889 cchMaxRawHeaders *= 2;
3890 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3892 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3893 cchRawHeaders += (buflen-1);
3894 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3895 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3896 lpszRawHeaders[cchRawHeaders] = '\0';
3898 /* Parse each response line */
3901 buflen = MAX_REPLY_LEN;
3902 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3904 LPWSTR * pFieldAndValue;
3906 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3908 if (!bufferA[0]) break;
3909 if (!strchr(bufferA, ':'))
3911 WARN("invalid header\n");
3914 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3916 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3918 cchMaxRawHeaders *= 2;
3919 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3921 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3922 cchRawHeaders += (buflen-1);
3923 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3924 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3925 lpszRawHeaders[cchRawHeaders] = '\0';
3927 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3928 if (!pFieldAndValue)
3931 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3932 HTTP_ADDREQ_FLAG_ADD );
3934 HTTP_FreeTokens(pFieldAndValue);
3944 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3945 lpwhr->lpszRawHeaders = lpszRawHeaders;
3946 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3956 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
3962 static void strip_spaces(LPWSTR start)
3967 while (*str == ' ' && *str != '\0')
3971 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3973 end = start + strlenW(start) - 1;
3974 while (end >= start && *end == ' ')
3982 /***********************************************************************
3983 * HTTP_InterpretHttpHeader (internal)
3985 * Parse server response
3989 * Pointer to array of field, value, NULL on success.
3992 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3994 LPWSTR * pTokenPair;
3998 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
4000 pszColon = strchrW(buffer, ':');
4001 /* must have two tokens */
4004 HTTP_FreeTokens(pTokenPair);
4006 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
4010 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
4013 HTTP_FreeTokens(pTokenPair);
4016 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
4017 pTokenPair[0][pszColon - buffer] = '\0';
4021 len = strlenW(pszColon);
4022 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
4025 HTTP_FreeTokens(pTokenPair);
4028 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
4030 strip_spaces(pTokenPair[0]);
4031 strip_spaces(pTokenPair[1]);
4033 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
4037 /***********************************************************************
4038 * HTTP_ProcessHeader (internal)
4040 * Stuff header into header tables according to <dwModifier>
4044 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4046 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4048 LPHTTPHEADERW lphttpHdr = NULL;
4049 BOOL bSuccess = FALSE;
4051 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4053 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
4055 /* REPLACE wins out over ADD */
4056 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4057 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
4059 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
4062 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
4066 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4070 lphttpHdr = &lpwhr->pCustHeaders[index];
4076 hdr.lpszField = (LPWSTR)field;
4077 hdr.lpszValue = (LPWSTR)value;
4078 hdr.wFlags = hdr.wCount = 0;
4080 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4081 hdr.wFlags |= HDR_ISREQUEST;
4083 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4085 /* no value to delete */
4088 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4089 lphttpHdr->wFlags |= HDR_ISREQUEST;
4091 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4093 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4095 HTTP_DeleteCustomHeader( lpwhr, index );
4101 hdr.lpszField = (LPWSTR)field;
4102 hdr.lpszValue = (LPWSTR)value;
4103 hdr.wFlags = hdr.wCount = 0;
4105 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4106 hdr.wFlags |= HDR_ISREQUEST;
4108 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4113 else if (dwModifier & COALESCEFLAGS)
4118 INT origlen = strlenW(lphttpHdr->lpszValue);
4119 INT valuelen = strlenW(value);
4121 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4124 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4126 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4129 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4132 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4134 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4137 lphttpHdr->lpszValue = lpsztmp;
4138 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4141 lphttpHdr->lpszValue[origlen] = ch;
4143 lphttpHdr->lpszValue[origlen] = ' ';
4147 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4148 lphttpHdr->lpszValue[len] = '\0';
4153 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4154 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4157 TRACE("<-- %d\n",bSuccess);
4162 /***********************************************************************
4163 * HTTP_FinishedReading (internal)
4165 * Called when all content from server has been read by client.
4168 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4170 WCHAR szVersion[10];
4171 WCHAR szConnectionResponse[20];
4172 DWORD dwBufferSize = sizeof(szVersion);
4173 BOOL keepalive = FALSE;
4177 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4178 * the connection is keep-alive by default */
4179 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4180 &dwBufferSize, NULL) &&
4181 !strcmpiW(szVersion, g_szHttp1_1))
4186 dwBufferSize = sizeof(szConnectionResponse);
4187 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4188 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4190 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4195 HTTPREQ_CloseConnection(&lpwhr->hdr);
4198 /* FIXME: store data in the URL cache here */
4204 /***********************************************************************
4205 * HTTP_GetCustomHeaderIndex (internal)
4207 * Return index of custom header from header array
4210 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4211 int requested_index, BOOL request_only)
4215 TRACE("%s\n", debugstr_w(lpszField));
4217 for (index = 0; index < lpwhr->nCustHeaders; index++)
4219 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4222 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4225 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4228 if (requested_index == 0)
4233 if (index >= lpwhr->nCustHeaders)
4236 TRACE("Return: %d\n", index);
4241 /***********************************************************************
4242 * HTTP_InsertCustomHeader (internal)
4244 * Insert header into array
4247 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4250 LPHTTPHEADERW lph = NULL;
4253 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4254 count = lpwhr->nCustHeaders + 1;
4256 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4258 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4262 lpwhr->pCustHeaders = lph;
4263 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4264 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4265 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4266 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4267 lpwhr->nCustHeaders++;
4272 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4279 /***********************************************************************
4280 * HTTP_DeleteCustomHeader (internal)
4282 * Delete header from array
4283 * If this function is called, the indexs may change.
4285 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4287 if( lpwhr->nCustHeaders <= 0 )
4289 if( index >= lpwhr->nCustHeaders )
4291 lpwhr->nCustHeaders--;
4293 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4294 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4296 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4297 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4298 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4304 /***********************************************************************
4305 * HTTP_VerifyValidHeader (internal)
4307 * Verify the given header is not invalid for the given http request
4310 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4312 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4313 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4319 /***********************************************************************
4320 * IsHostInProxyBypassList (@)
4325 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4327 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);