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 LPWSTR HTTP_GetRedirectURL(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
125 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
126 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
127 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
128 static void HTTP_DrainContent(WININETHTTPREQW *req);
129 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr);
131 static LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
134 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
135 if (HeaderIndex == -1)
138 return &req->pCustHeaders[HeaderIndex];
141 /***********************************************************************
142 * HTTP_Tokenize (internal)
144 * Tokenize a string, allocating memory for the tokens.
146 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
148 LPWSTR * token_array;
155 /* empty string has no tokens */
159 for (i = 0; string[i]; i++)
161 if (!strncmpW(string+i, token_string, strlenW(token_string)))
165 /* we want to skip over separators, but not the null terminator */
166 for (j = 0; j < strlenW(token_string) - 1; j++)
174 /* add 1 for terminating NULL */
175 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
176 token_array[tokens] = NULL;
179 for (i = 0; i < tokens; i++)
182 next_token = strstrW(string, token_string);
183 if (!next_token) next_token = string+strlenW(string);
184 len = next_token - string;
185 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
186 memcpy(token_array[i], string, len*sizeof(WCHAR));
187 token_array[i][len] = '\0';
188 string = next_token+strlenW(token_string);
193 /***********************************************************************
194 * HTTP_FreeTokens (internal)
196 * Frees memory returned from HTTP_Tokenize.
198 static void HTTP_FreeTokens(LPWSTR * token_array)
201 for (i = 0; token_array[i]; i++)
202 HeapFree(GetProcessHeap(), 0, token_array[i]);
203 HeapFree(GetProcessHeap(), 0, token_array);
206 /* **********************************************************************
208 * Helper functions for the HttpSendRequest(Ex) functions
211 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
213 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
214 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
216 TRACE("%p\n", lpwhr);
218 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
219 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
220 req->dwContentLength, req->bEndRequest);
222 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
225 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
227 static const WCHAR szSlash[] = { '/',0 };
228 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
230 /* If we don't have a path we set it to root */
231 if (NULL == lpwhr->lpszPath)
232 lpwhr->lpszPath = WININET_strdupW(szSlash);
233 else /* remove \r and \n*/
235 int nLen = strlenW(lpwhr->lpszPath);
236 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
239 lpwhr->lpszPath[nLen]='\0';
241 /* Replace '\' with '/' */
244 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
248 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
249 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
250 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
252 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
253 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
255 strcpyW(fixurl + 1, lpwhr->lpszPath);
256 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
257 lpwhr->lpszPath = fixurl;
261 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
263 LPWSTR requestString;
269 static const WCHAR szSpace[] = { ' ',0 };
270 static const WCHAR szColon[] = { ':',' ',0 };
271 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
273 /* allocate space for an array of all the string pointers to be added */
274 len = (lpwhr->nCustHeaders)*4 + 10;
275 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
277 /* add the verb, path and HTTP version string */
285 /* Append custom request headers */
286 for (i = 0; i < lpwhr->nCustHeaders; i++)
288 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
291 req[n++] = lpwhr->pCustHeaders[i].lpszField;
293 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
295 TRACE("Adding custom header %s (%s)\n",
296 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
297 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
302 ERR("oops. buffer overrun\n");
305 requestString = HTTP_build_req( req, 4 );
306 HeapFree( GetProcessHeap(), 0, req );
309 * Set (header) termination string for request
310 * Make sure there's exactly two new lines at the end of the request
312 p = &requestString[strlenW(requestString)-1];
313 while ( (*p == '\n') || (*p == '\r') )
315 strcpyW( p+1, sztwocrlf );
317 return requestString;
320 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
322 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
325 LPHTTPHEADERW setCookieHeader;
327 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
329 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
331 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
334 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','%','s',0};
338 Host = HTTP_GetHeader(lpwhr,szHost);
339 len = lstrlenW(Host->lpszValue) + 9 + lstrlenW(lpwhr->lpszPath);
340 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
341 sprintfW(buf_url, szFmt, Host->lpszValue, lpwhr->lpszPath);
342 InternetSetCookieW(buf_url, NULL, setCookieHeader->lpszValue);
344 HeapFree(GetProcessHeap(), 0, buf_url);
350 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
352 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
353 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
354 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
357 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
358 struct HttpAuthInfo **ppAuthInfo,
359 LPWSTR domain_and_username, LPWSTR password )
361 SECURITY_STATUS sec_status;
362 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
365 TRACE("%s\n", debugstr_w(pszAuthValue));
372 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
376 SecInvalidateHandle(&pAuthInfo->cred);
377 SecInvalidateHandle(&pAuthInfo->ctx);
378 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
380 pAuthInfo->auth_data = NULL;
381 pAuthInfo->auth_data_len = 0;
382 pAuthInfo->finished = FALSE;
384 if (is_basic_auth_value(pszAuthValue))
386 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
387 pAuthInfo->scheme = WININET_strdupW(szBasic);
388 if (!pAuthInfo->scheme)
390 HeapFree(GetProcessHeap(), 0, pAuthInfo);
397 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
399 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
400 if (!pAuthInfo->scheme)
402 HeapFree(GetProcessHeap(), 0, pAuthInfo);
406 if (domain_and_username)
408 WCHAR *user = strchrW(domain_and_username, '\\');
409 WCHAR *domain = domain_and_username;
411 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
413 pAuthData = &nt_auth_identity;
418 user = domain_and_username;
422 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
423 nt_auth_identity.User = user;
424 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
425 nt_auth_identity.Domain = domain;
426 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
427 nt_auth_identity.Password = password;
428 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
431 /* use default credentials */
434 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
435 SECPKG_CRED_OUTBOUND, NULL,
437 NULL, &pAuthInfo->cred,
439 if (sec_status == SEC_E_OK)
441 PSecPkgInfoW sec_pkg_info;
442 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
443 if (sec_status == SEC_E_OK)
445 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
446 FreeContextBuffer(sec_pkg_info);
449 if (sec_status != SEC_E_OK)
451 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
452 debugstr_w(pAuthInfo->scheme), sec_status);
453 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
454 HeapFree(GetProcessHeap(), 0, pAuthInfo);
458 *ppAuthInfo = pAuthInfo;
460 else if (pAuthInfo->finished)
463 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
464 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
466 ERR("authentication scheme changed from %s to %s\n",
467 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
471 if (is_basic_auth_value(pszAuthValue))
477 TRACE("basic authentication\n");
479 /* we don't cache credentials for basic authentication, so we can't
480 * retrieve them if the application didn't pass us any credentials */
481 if (!domain_and_username) return FALSE;
483 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
484 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
486 /* length includes a nul terminator, which will be re-used for the ':' */
487 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
491 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
492 auth_data[userlen] = ':';
493 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
495 pAuthInfo->auth_data = auth_data;
496 pAuthInfo->auth_data_len = userlen + 1 + passlen;
497 pAuthInfo->finished = TRUE;
504 SecBufferDesc out_desc, in_desc;
506 unsigned char *buffer;
507 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
508 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
510 in.BufferType = SECBUFFER_TOKEN;
514 in_desc.ulVersion = 0;
515 in_desc.cBuffers = 1;
516 in_desc.pBuffers = ∈
518 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
519 if (*pszAuthData == ' ')
522 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
523 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
524 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
527 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
529 out.BufferType = SECBUFFER_TOKEN;
530 out.cbBuffer = pAuthInfo->max_token;
531 out.pvBuffer = buffer;
533 out_desc.ulVersion = 0;
534 out_desc.cBuffers = 1;
535 out_desc.pBuffers = &out;
537 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
538 first ? NULL : &pAuthInfo->ctx,
539 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
540 context_req, 0, SECURITY_NETWORK_DREP,
541 in.pvBuffer ? &in_desc : NULL,
542 0, &pAuthInfo->ctx, &out_desc,
543 &pAuthInfo->attr, &pAuthInfo->exp);
544 if (sec_status == SEC_E_OK)
546 pAuthInfo->finished = TRUE;
547 pAuthInfo->auth_data = out.pvBuffer;
548 pAuthInfo->auth_data_len = out.cbBuffer;
549 TRACE("sending last auth packet\n");
551 else if (sec_status == SEC_I_CONTINUE_NEEDED)
553 pAuthInfo->auth_data = out.pvBuffer;
554 pAuthInfo->auth_data_len = out.cbBuffer;
555 TRACE("sending next auth packet\n");
559 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
560 pAuthInfo->finished = TRUE;
561 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
569 /***********************************************************************
570 * HTTP_HttpAddRequestHeadersW (internal)
572 static BOOL HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
573 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
578 BOOL bSuccess = FALSE;
581 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
583 if( dwHeaderLength == ~0U )
584 len = strlenW(lpszHeader);
586 len = dwHeaderLength;
587 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
588 lstrcpynW( buffer, lpszHeader, len + 1);
594 LPWSTR * pFieldAndValue;
598 while (*lpszEnd != '\0')
600 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
605 if (*lpszStart == '\0')
608 if (*lpszEnd == '\r')
611 lpszEnd += 2; /* Jump over \r\n */
613 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
614 if (*lpszStart == '\0')
616 /* Skip 0-length headers */
621 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
624 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
626 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
627 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
628 HTTP_FreeTokens(pFieldAndValue);
634 HeapFree(GetProcessHeap(), 0, buffer);
639 /***********************************************************************
640 * HttpAddRequestHeadersW (WININET.@)
642 * Adds one or more HTTP header to the request handler
645 * On Windows if dwHeaderLength includes the trailing '\0', then
646 * HttpAddRequestHeadersW() adds it too. However this results in an
647 * invalid Http header which is rejected by some servers so we probably
648 * don't need to match Windows on that point.
655 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
656 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
658 BOOL bSuccess = FALSE;
659 LPWININETHTTPREQW lpwhr;
661 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
666 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
667 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
669 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
672 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
675 WININET_Release( &lpwhr->hdr );
680 /***********************************************************************
681 * HttpAddRequestHeadersA (WININET.@)
683 * Adds one or more HTTP header to the request handler
690 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
691 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
697 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
699 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
700 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
701 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
702 if( dwHeaderLength != ~0U )
703 dwHeaderLength = len;
705 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
707 HeapFree( GetProcessHeap(), 0, hdr );
712 /***********************************************************************
713 * HttpEndRequestA (WININET.@)
715 * Ends an HTTP request that was started by HttpSendRequestEx
722 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
723 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
725 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
729 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
733 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
736 static BOOL HTTP_HttpEndRequestW(LPWININETHTTPREQW lpwhr, DWORD dwFlags, DWORD_PTR dwContext)
741 INTERNET_ASYNC_RESULT iar;
743 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
744 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
746 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
750 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
751 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
753 /* process cookies here. Is this right? */
754 HTTP_ProcessCookies(lpwhr);
756 dwBufferSize = sizeof(lpwhr->dwContentLength);
757 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
758 &lpwhr->dwContentLength, &dwBufferSize, NULL))
759 lpwhr->dwContentLength = -1;
761 if (lpwhr->dwContentLength == 0)
762 HTTP_FinishedReading(lpwhr);
764 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
766 DWORD dwCode,dwCodeLength = sizeof(DWORD);
767 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE, &dwCode, &dwCodeLength, NULL) &&
768 (dwCode == 302 || dwCode == 301 || dwCode == 303))
770 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
771 dwBufferSize=sizeof(szNewLocation);
772 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL))
774 /* redirects are always GETs */
775 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
776 lpwhr->lpszVerb = WININET_strdupW(szGET);
777 HTTP_DrainContent(lpwhr);
778 if ((new_url = HTTP_GetRedirectURL( lpwhr, szNewLocation )))
780 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REDIRECT,
781 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
782 rc = HTTP_HandleRedirect(lpwhr, new_url);
784 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
785 HeapFree( GetProcessHeap(), 0, new_url );
791 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
792 iar.dwError = rc ? 0 : INTERNET_GetLastError();
794 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
795 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
796 sizeof(INTERNET_ASYNC_RESULT));
800 static void AsyncHttpEndRequestProc(WORKREQUEST *work)
802 struct WORKREQ_HTTPENDREQUESTW const *req = &work->u.HttpEndRequestW;
803 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)work->hdr;
805 TRACE("%p\n", lpwhr);
807 HTTP_HttpEndRequestW(lpwhr, req->dwFlags, req->dwContext);
810 /***********************************************************************
811 * HttpEndRequestW (WININET.@)
813 * Ends an HTTP request that was started by HttpSendRequestEx
820 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
821 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
824 LPWININETHTTPREQW lpwhr;
830 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
834 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
836 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
838 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
840 WININET_Release( &lpwhr->hdr );
843 lpwhr->hdr.dwFlags |= dwFlags;
845 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
848 struct WORKREQ_HTTPENDREQUESTW *request;
850 work.asyncproc = AsyncHttpEndRequestProc;
851 work.hdr = WININET_AddRef( &lpwhr->hdr );
853 request = &work.u.HttpEndRequestW;
854 request->dwFlags = dwFlags;
855 request->dwContext = dwContext;
857 INTERNET_AsyncCall(&work);
858 INTERNET_SetLastError(ERROR_IO_PENDING);
861 rc = HTTP_HttpEndRequestW(lpwhr, dwFlags, dwContext);
863 WININET_Release( &lpwhr->hdr );
864 TRACE("%i <--\n",rc);
868 /***********************************************************************
869 * HttpOpenRequestW (WININET.@)
871 * Open a HTTP request handle
874 * HINTERNET a HTTP request handle on success
878 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
879 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
880 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
881 DWORD dwFlags, DWORD_PTR dwContext)
883 LPWININETHTTPSESSIONW lpwhs;
884 HINTERNET handle = NULL;
886 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
887 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
888 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
890 if(lpszAcceptTypes!=NULL)
893 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
894 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
897 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
898 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
900 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
905 * My tests seem to show that the windows version does not
906 * become asynchronous until after this point. And anyhow
907 * if this call was asynchronous then how would you get the
908 * necessary HINTERNET pointer returned by this function.
911 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
912 lpszVersion, lpszReferrer, lpszAcceptTypes,
916 WININET_Release( &lpwhs->hdr );
917 TRACE("returning %p\n", handle);
922 /***********************************************************************
923 * HttpOpenRequestA (WININET.@)
925 * Open a HTTP request handle
928 * HINTERNET a HTTP request handle on success
932 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
933 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
934 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
935 DWORD dwFlags, DWORD_PTR dwContext)
937 LPWSTR szVerb = NULL, szObjectName = NULL;
938 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
939 INT len, acceptTypesCount;
940 HINTERNET rc = FALSE;
943 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
944 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
945 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
950 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
951 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
954 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
959 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
960 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
963 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
968 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
969 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
972 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
977 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
978 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
981 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
986 acceptTypesCount = 0;
987 types = lpszAcceptTypes;
992 /* find out how many there are */
993 if (*types && **types)
995 TRACE("accept type: %s\n", debugstr_a(*types));
1001 WARN("invalid accept type pointer\n");
1006 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1007 if (!szAcceptTypes) goto end;
1009 acceptTypesCount = 0;
1010 types = lpszAcceptTypes;
1015 if (*types && **types)
1017 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1018 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1020 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1026 /* ignore invalid pointer */
1031 szAcceptTypes[acceptTypesCount] = NULL;
1034 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1035 szVersion, szReferrer,
1036 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1041 acceptTypesCount = 0;
1042 while (szAcceptTypes[acceptTypesCount])
1044 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1047 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1049 HeapFree(GetProcessHeap(), 0, szReferrer);
1050 HeapFree(GetProcessHeap(), 0, szVersion);
1051 HeapFree(GetProcessHeap(), 0, szObjectName);
1052 HeapFree(GetProcessHeap(), 0, szVerb);
1057 /***********************************************************************
1060 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1063 static const CHAR HTTP_Base64Enc[] =
1064 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1068 /* first 6 bits, all from bin[0] */
1069 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1070 x = (bin[0] & 3) << 4;
1072 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1075 base64[n++] = HTTP_Base64Enc[x];
1080 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1081 x = ( bin[1] & 0x0f ) << 2;
1083 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1086 base64[n++] = HTTP_Base64Enc[x];
1090 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1092 /* last 6 bits, all from bin [2] */
1093 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1101 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1102 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1103 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1104 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1105 static const signed char HTTP_Base64Dec[256] =
1107 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1108 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1109 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1110 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1111 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1112 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1113 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1114 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1115 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1116 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1117 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1118 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1119 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1120 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1121 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1122 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1123 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1124 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1125 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1126 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1127 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1128 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1129 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1130 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1131 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1132 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1136 /***********************************************************************
1139 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1147 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1148 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1149 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1150 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1152 WARN("invalid base64: %s\n", debugstr_w(base64));
1156 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1159 if ((base64[2] == '=') && (base64[3] == '='))
1161 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1162 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1164 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1168 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1171 if (base64[3] == '=')
1173 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1174 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1176 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1180 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1189 /***********************************************************************
1190 * HTTP_InsertAuthorization
1192 * Insert or delete the authorization field in the request header.
1194 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1198 static const WCHAR wszSpace[] = {' ',0};
1199 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1201 WCHAR *authorization = NULL;
1203 if (pAuthInfo->auth_data_len)
1205 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1206 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1207 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1211 strcpyW(authorization, pAuthInfo->scheme);
1212 strcatW(authorization, wszSpace);
1213 HTTP_EncodeBase64(pAuthInfo->auth_data,
1214 pAuthInfo->auth_data_len,
1215 authorization+strlenW(authorization));
1217 /* clear the data as it isn't valid now that it has been sent to the
1218 * server, unless it's Basic authentication which doesn't do
1219 * connection tracking */
1220 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1222 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1223 pAuthInfo->auth_data = NULL;
1224 pAuthInfo->auth_data_len = 0;
1228 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1230 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1232 HeapFree(GetProcessHeap(), 0, authorization);
1237 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1239 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1242 size = sizeof(new_location);
1243 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1245 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1246 strcpyW( url, new_location );
1250 static const WCHAR slash[] = { '/',0 };
1251 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1252 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1253 WININETHTTPSESSIONW *session = req->lpHttpSession;
1255 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1256 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1258 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1260 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1261 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1263 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1264 if (req->lpszPath[0] != '/') strcatW( url, slash );
1265 strcatW( url, req->lpszPath );
1267 TRACE("url=%s\n", debugstr_w(url));
1271 /***********************************************************************
1272 * HTTP_DealWithProxy
1274 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1275 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1277 WCHAR buf[MAXHOSTNAME];
1278 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1279 static WCHAR szNul[] = { 0 };
1280 URL_COMPONENTSW UrlComponents;
1281 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1282 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1284 memset( &UrlComponents, 0, sizeof UrlComponents );
1285 UrlComponents.dwStructSize = sizeof UrlComponents;
1286 UrlComponents.lpszHostName = buf;
1287 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1289 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1290 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1291 sprintfW(proxy, szFormat, hIC->lpszProxy);
1293 strcpyW(proxy, hIC->lpszProxy);
1294 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1296 if( UrlComponents.dwHostNameLength == 0 )
1299 if( !lpwhr->lpszPath )
1300 lpwhr->lpszPath = szNul;
1302 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1303 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1305 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1306 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1307 lpwhs->nServerPort = UrlComponents.nPort;
1309 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1313 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1316 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1318 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1319 INTERNET_STATUS_RESOLVING_NAME,
1320 lpwhs->lpszServerName,
1321 strlenW(lpwhs->lpszServerName)+1);
1323 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1324 &lpwhs->socketAddress))
1326 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1330 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1331 szaddr, sizeof(szaddr));
1332 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1333 INTERNET_STATUS_NAME_RESOLVED,
1334 szaddr, strlen(szaddr)+1);
1336 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1341 /***********************************************************************
1342 * HTTPREQ_Destroy (internal)
1344 * Deallocate request handle
1347 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1349 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1354 if(lpwhr->hCacheFile)
1355 CloseHandle(lpwhr->hCacheFile);
1357 if(lpwhr->lpszCacheFile) {
1358 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1359 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1362 WININET_Release(&lpwhr->lpHttpSession->hdr);
1364 if (lpwhr->pAuthInfo)
1366 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1367 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1368 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1369 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1371 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1372 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1373 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1374 lpwhr->pAuthInfo = NULL;
1377 if (lpwhr->pProxyAuthInfo)
1379 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1380 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1381 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1382 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1384 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1385 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1386 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1387 lpwhr->pProxyAuthInfo = NULL;
1390 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1391 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1392 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1393 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1394 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1396 for (i = 0; i < lpwhr->nCustHeaders; i++)
1398 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1399 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1402 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1403 HeapFree(GetProcessHeap(), 0, lpwhr);
1406 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1408 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1410 TRACE("%p\n",lpwhr);
1412 if (!NETCON_connected(&lpwhr->netConnection))
1415 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1416 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1418 NETCON_close(&lpwhr->netConnection);
1420 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1421 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1424 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1426 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1429 case INTERNET_OPTION_HANDLE_TYPE:
1430 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1432 if (*size < sizeof(ULONG))
1433 return ERROR_INSUFFICIENT_BUFFER;
1435 *size = sizeof(DWORD);
1436 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1437 return ERROR_SUCCESS;
1439 case INTERNET_OPTION_URL: {
1440 WCHAR url[INTERNET_MAX_URL_LENGTH];
1445 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1446 static const WCHAR hostW[] = {'H','o','s','t',0};
1448 TRACE("INTERNET_OPTION_URL\n");
1450 host = HTTP_GetHeader(req, hostW);
1451 strcpyW(url, httpW);
1452 strcatW(url, host->lpszValue);
1453 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1455 strcatW(url, req->lpszPath);
1457 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1460 len = (strlenW(url)+1) * sizeof(WCHAR);
1462 return ERROR_INSUFFICIENT_BUFFER;
1465 strcpyW(buffer, url);
1466 return ERROR_SUCCESS;
1468 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1470 return ERROR_INSUFFICIENT_BUFFER;
1473 return ERROR_SUCCESS;
1477 case INTERNET_OPTION_DATAFILE_NAME: {
1480 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1482 if(!req->lpszCacheFile) {
1484 return ERROR_INTERNET_ITEM_NOT_FOUND;
1488 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1489 if(*size < req_size)
1490 return ERROR_INSUFFICIENT_BUFFER;
1493 memcpy(buffer, req->lpszCacheFile, *size);
1494 return ERROR_SUCCESS;
1496 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1497 if (req_size > *size)
1498 return ERROR_INSUFFICIENT_BUFFER;
1500 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1501 -1, buffer, *size, NULL, NULL);
1502 return ERROR_SUCCESS;
1506 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1507 PCCERT_CONTEXT context;
1509 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1510 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1511 return ERROR_INSUFFICIENT_BUFFER;
1514 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1516 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1519 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1520 info->ftExpiry = context->pCertInfo->NotAfter;
1521 info->ftStart = context->pCertInfo->NotBefore;
1523 len = CertNameToStrW(context->dwCertEncodingType,
1524 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1525 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1526 if(info->lpszSubjectInfo)
1527 CertNameToStrW(context->dwCertEncodingType,
1528 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1529 info->lpszSubjectInfo, len);
1530 len = CertNameToStrW(context->dwCertEncodingType,
1531 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1532 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1533 if (info->lpszIssuerInfo)
1534 CertNameToStrW(context->dwCertEncodingType,
1535 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1536 info->lpszIssuerInfo, len);
1538 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1540 len = CertNameToStrA(context->dwCertEncodingType,
1541 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1542 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1543 if(infoA->lpszSubjectInfo)
1544 CertNameToStrA(context->dwCertEncodingType,
1545 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1546 infoA->lpszSubjectInfo, len);
1547 len = CertNameToStrA(context->dwCertEncodingType,
1548 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1549 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1550 if(infoA->lpszIssuerInfo)
1551 CertNameToStrA(context->dwCertEncodingType,
1552 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1553 infoA->lpszIssuerInfo, len);
1557 * Contrary to MSDN, these do not appear to be set.
1559 * lpszSignatureAlgName
1560 * lpszEncryptionAlgName
1563 CertFreeCertificateContext(context);
1564 return ERROR_SUCCESS;
1569 return INET_QueryOption(option, buffer, size, unicode);
1572 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1574 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1577 case INTERNET_OPTION_SEND_TIMEOUT:
1578 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1579 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1581 if (size != sizeof(DWORD))
1582 return ERROR_INVALID_PARAMETER;
1584 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1587 case INTERNET_OPTION_USERNAME:
1588 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1589 if (!(req->lpHttpSession->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1590 return ERROR_SUCCESS;
1592 case INTERNET_OPTION_PASSWORD:
1593 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1594 if (!(req->lpHttpSession->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1595 return ERROR_SUCCESS;
1598 return ERROR_INTERNET_INVALID_OPTION;
1601 static void HTTP_ReceiveRequestData(WININETHTTPREQW *req, BOOL first_notif)
1603 INTERNET_ASYNC_RESULT iar;
1610 res = NETCON_recv(&req->netConnection, buffer,
1611 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1612 MSG_PEEK, &available);
1615 iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
1616 iar.dwError = first_notif ? 0 : available;
1619 iar.dwError = INTERNET_GetLastError();
1622 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1623 sizeof(INTERNET_ASYNC_RESULT));
1626 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1630 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1631 sync ? MSG_WAITALL : 0, &bytes_read)) {
1632 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1633 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1635 /* always return success, even if the network layer returns an error */
1637 HTTP_FinishedReading(req);
1638 return ERROR_SUCCESS;
1641 req->dwContentRead += bytes_read;
1644 if(req->lpszCacheFile) {
1646 DWORD dwBytesWritten;
1648 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1650 WARN("WriteFile failed: %u\n", GetLastError());
1653 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1654 HTTP_FinishedReading(req);
1656 return ERROR_SUCCESS;
1659 static DWORD get_chunk_size(const char *buffer)
1664 for (p = buffer; *p; p++)
1666 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1667 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1668 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1669 else if (*p == ';') break;
1674 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1676 char reply[MAX_REPLY_LEN], *p = buffer;
1677 DWORD buflen, to_read, to_write = size;
1683 if (*read == size) break;
1685 if (req->dwContentLength == ~0u) /* new chunk */
1687 buflen = sizeof(reply);
1688 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1690 if (!(req->dwContentLength = get_chunk_size(reply)))
1692 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1693 HTTP_GetResponseHeaders(req, FALSE);
1697 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1699 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1701 if (bytes_read != to_read)
1702 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1704 /* always return success, even if the network layer returns an error */
1708 if (!bytes_read) break;
1710 req->dwContentRead += bytes_read;
1711 to_write -= bytes_read;
1712 *read += bytes_read;
1714 if (req->lpszCacheFile)
1716 DWORD dwBytesWritten;
1718 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1719 WARN("WriteFile failed: %u\n", GetLastError());
1723 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1725 req->dwContentRead = 0;
1726 req->dwContentLength = ~0u;
1728 buflen = sizeof(reply);
1729 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1731 ERR("Malformed chunk\n");
1737 if (!*read) HTTP_FinishedReading(req);
1738 return ERROR_SUCCESS;
1741 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1744 DWORD buflen = sizeof(encoding);
1745 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1747 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1748 !strcmpiW(encoding, szChunked))
1750 return HTTP_ReadChunked(req, buffer, size, read, sync);
1753 return HTTP_Read(req, buffer, size, read, sync);
1756 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1758 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1759 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1762 static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
1764 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1765 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1766 INTERNET_ASYNC_RESULT iar;
1769 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1771 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1772 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1774 iar.dwResult = res == ERROR_SUCCESS;
1777 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1778 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1779 sizeof(INTERNET_ASYNC_RESULT));
1782 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1783 DWORD flags, DWORD_PTR context)
1786 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1789 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1790 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1792 if (buffers->dwStructSize != sizeof(*buffers))
1793 return ERROR_INVALID_PARAMETER;
1795 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1797 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1798 DWORD available = 0;
1800 NETCON_query_data_available(&req->netConnection, &available);
1803 WORKREQUEST workRequest;
1805 workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
1806 workRequest.hdr = WININET_AddRef(&req->hdr);
1807 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1809 INTERNET_AsyncCall(&workRequest);
1811 return ERROR_IO_PENDING;
1815 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1816 !(flags & IRF_NO_WAIT));
1818 if (res == ERROR_SUCCESS) {
1819 DWORD size = buffers->dwBufferLength;
1820 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1821 &size, sizeof(size));
1827 static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
1829 struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
1830 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1831 INTERNET_ASYNC_RESULT iar;
1834 TRACE("INTERNETREADFILEEXW %p\n", workRequest->hdr);
1836 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1837 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1839 iar.dwResult = res == ERROR_SUCCESS;
1842 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1843 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1844 sizeof(INTERNET_ASYNC_RESULT));
1847 static DWORD HTTPREQ_ReadFileExW(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSW *buffers,
1848 DWORD flags, DWORD_PTR context)
1851 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1854 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1855 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1857 if (buffers->dwStructSize != sizeof(*buffers))
1858 return ERROR_INVALID_PARAMETER;
1860 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1862 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1863 DWORD available = 0;
1865 NETCON_query_data_available(&req->netConnection, &available);
1868 WORKREQUEST workRequest;
1870 workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
1871 workRequest.hdr = WININET_AddRef(&req->hdr);
1872 workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
1874 INTERNET_AsyncCall(&workRequest);
1876 return ERROR_IO_PENDING;
1880 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1881 !(flags & IRF_NO_WAIT));
1883 if (res == ERROR_SUCCESS) {
1884 DWORD size = buffers->dwBufferLength;
1885 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1886 &size, sizeof(size));
1892 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1895 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1897 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
1900 if ((ret = NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written)))
1901 lpwhr->dwBytesWritten += *written;
1903 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
1907 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1909 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1911 HTTP_ReceiveRequestData(req, FALSE);
1914 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1916 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1920 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1922 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1923 return ERROR_SUCCESS;
1925 /* Even if we are in async mode, we need to determine whether
1926 * there is actually more data available. We do this by trying
1927 * to peek only a single byte in async mode. */
1928 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1930 if (NETCON_recv(&req->netConnection, buffer,
1931 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1932 MSG_PEEK, (int *)available) && async && *available)
1934 WORKREQUEST workRequest;
1937 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1938 workRequest.hdr = WININET_AddRef( &req->hdr );
1940 INTERNET_AsyncCall(&workRequest);
1942 return ERROR_IO_PENDING;
1945 return ERROR_SUCCESS;
1948 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1950 HTTPREQ_CloseConnection,
1951 HTTPREQ_QueryOption,
1954 HTTPREQ_ReadFileExA,
1955 HTTPREQ_ReadFileExW,
1957 HTTPREQ_QueryDataAvailable,
1961 /***********************************************************************
1962 * HTTP_HttpOpenRequestW (internal)
1964 * Open a HTTP request handle
1967 * HINTERNET a HTTP request handle on success
1971 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1972 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1973 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1974 DWORD dwFlags, DWORD_PTR dwContext)
1976 LPWININETAPPINFOW hIC = NULL;
1977 LPWININETHTTPREQW lpwhr;
1978 LPWSTR lpszHostName = NULL;
1979 HINTERNET handle = NULL;
1980 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1985 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1986 hIC = lpwhs->lpAppInfo;
1988 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1991 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1994 lpwhr->hdr.htype = WH_HHTTPREQ;
1995 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1996 lpwhr->hdr.dwFlags = dwFlags;
1997 lpwhr->hdr.dwContext = dwContext;
1998 lpwhr->hdr.refs = 1;
1999 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
2000 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
2002 WININET_AddRef( &lpwhs->hdr );
2003 lpwhr->lpHttpSession = lpwhs;
2004 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
2006 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
2007 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
2008 if (NULL == lpszHostName)
2010 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2014 handle = WININET_AllocHandle( &lpwhr->hdr );
2017 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2021 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
2023 InternetCloseHandle( handle );
2028 if (lpszObjectName && *lpszObjectName) {
2032 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
2033 if (rc != E_POINTER)
2034 len = strlenW(lpszObjectName)+1;
2035 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2036 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
2037 URL_ESCAPE_SPACES_ONLY);
2040 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2041 strcpyW(lpwhr->lpszPath,lpszObjectName);
2045 if (lpszReferrer && *lpszReferrer)
2046 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2048 if (lpszAcceptTypes)
2051 for (i = 0; lpszAcceptTypes[i]; i++)
2053 if (!*lpszAcceptTypes[i]) continue;
2054 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2055 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
2056 HTTP_ADDHDR_FLAG_REQ |
2057 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
2061 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
2064 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
2066 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
2068 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
2069 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
2070 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
2072 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2073 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
2074 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2077 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
2078 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2080 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2081 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2082 INTERNET_DEFAULT_HTTPS_PORT :
2083 INTERNET_DEFAULT_HTTP_PORT);
2085 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2086 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2087 INTERNET_DEFAULT_HTTPS_PORT :
2088 INTERNET_DEFAULT_HTTP_PORT);
2090 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2091 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2093 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2094 INTERNET_STATUS_HANDLE_CREATED, &handle,
2098 HeapFree(GetProcessHeap(), 0, lpszHostName);
2100 WININET_Release( &lpwhr->hdr );
2102 TRACE("<-- %p (%p)\n", handle, lpwhr);
2106 /* read any content returned by the server so that the connection can be
2108 static void HTTP_DrainContent(WININETHTTPREQW *req)
2112 if (!NETCON_connected(&req->netConnection)) return;
2114 if (req->dwContentLength == -1)
2115 NETCON_close(&req->netConnection);
2120 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2122 } while (bytes_read);
2125 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2126 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2127 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2128 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2129 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2130 static const WCHAR szAge[] = { 'A','g','e',0 };
2131 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2132 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2133 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2134 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2135 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2136 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2137 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2138 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2139 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2140 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2141 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2142 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 };
2143 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2144 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2145 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2146 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2147 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2148 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2149 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2150 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2151 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2152 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2153 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2154 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2155 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2156 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2157 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2158 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2159 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2160 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2161 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2162 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2163 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2164 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2165 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2166 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2167 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2168 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2169 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 };
2170 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2171 static const WCHAR szURI[] = { 'U','R','I',0 };
2172 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2173 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2174 static const WCHAR szVia[] = { 'V','i','a',0 };
2175 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2176 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2178 static const LPCWSTR header_lookup[] = {
2179 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2180 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2181 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2182 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2183 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2184 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2185 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2186 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2187 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2188 szDate, /* HTTP_QUERY_DATE = 9 */
2189 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2190 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2191 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2192 szURI, /* HTTP_QUERY_URI = 13 */
2193 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2194 NULL, /* HTTP_QUERY_COST = 15 */
2195 NULL, /* HTTP_QUERY_LINK = 16 */
2196 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2197 NULL, /* HTTP_QUERY_VERSION = 18 */
2198 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2199 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2200 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2201 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2202 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2203 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2204 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2205 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2206 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2207 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2208 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2209 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2210 NULL, /* HTTP_QUERY_FROM = 31 */
2211 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2212 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2213 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2214 szReferer, /* HTTP_QUERY_REFERER = 35 */
2215 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2216 szServer, /* HTTP_QUERY_SERVER = 37 */
2217 NULL, /* HTTP_TITLE = 38 */
2218 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2219 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2220 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2221 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2222 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2223 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2224 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2225 NULL, /* HTTP_QUERY_REFRESH = 46 */
2226 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2227 szAge, /* HTTP_QUERY_AGE = 48 */
2228 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2229 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2230 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2231 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2232 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2233 szETag, /* HTTP_QUERY_ETAG = 54 */
2234 szHost, /* HTTP_QUERY_HOST = 55 */
2235 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2236 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2237 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2238 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2239 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2240 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2241 szRange, /* HTTP_QUERY_RANGE = 62 */
2242 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2243 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2244 szVary, /* HTTP_QUERY_VARY = 65 */
2245 szVia, /* HTTP_QUERY_VIA = 66 */
2246 szWarning, /* HTTP_QUERY_WARNING = 67 */
2247 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2248 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2249 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2252 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2254 /***********************************************************************
2255 * HTTP_HttpQueryInfoW (internal)
2257 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2258 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2260 LPHTTPHEADERW lphttpHdr = NULL;
2261 BOOL bSuccess = FALSE;
2262 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2263 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2264 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2267 /* Find requested header structure */
2270 case HTTP_QUERY_CUSTOM:
2271 if (!lpBuffer) return FALSE;
2272 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2275 case HTTP_QUERY_RAW_HEADERS_CRLF:
2282 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2284 headers = lpwhr->lpszRawHeaders;
2287 len = strlenW(headers) * sizeof(WCHAR);
2289 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2291 len += sizeof(WCHAR);
2292 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2298 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2301 len = strlenW(szCrLf) * sizeof(WCHAR);
2302 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2304 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2307 *lpdwBufferLength = len;
2310 HeapFree(GetProcessHeap(), 0, headers);
2313 case HTTP_QUERY_RAW_HEADERS:
2315 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2317 LPWSTR pszString = lpBuffer;
2319 for (i = 0; ppszRawHeaderLines[i]; i++)
2320 size += strlenW(ppszRawHeaderLines[i]) + 1;
2322 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2324 HTTP_FreeTokens(ppszRawHeaderLines);
2325 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2326 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2331 for (i = 0; ppszRawHeaderLines[i]; i++)
2333 DWORD len = strlenW(ppszRawHeaderLines[i]);
2334 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2338 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2340 *lpdwBufferLength = size * sizeof(WCHAR);
2341 HTTP_FreeTokens(ppszRawHeaderLines);
2345 case HTTP_QUERY_STATUS_TEXT:
2346 if (lpwhr->lpszStatusText)
2348 DWORD len = strlenW(lpwhr->lpszStatusText);
2349 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2351 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2352 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2357 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2358 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2360 *lpdwBufferLength = len * sizeof(WCHAR);
2364 case HTTP_QUERY_VERSION:
2365 if (lpwhr->lpszVersion)
2367 DWORD len = strlenW(lpwhr->lpszVersion);
2368 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2370 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2371 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2376 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2377 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2379 *lpdwBufferLength = len * sizeof(WCHAR);
2384 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2386 if (level < LAST_TABLE_HEADER && header_lookup[level])
2387 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2388 requested_index,request_only);
2392 lphttpHdr = &lpwhr->pCustHeaders[index];
2394 /* Ensure header satisfies requested attributes */
2396 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2397 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2399 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2403 if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2405 /* coalesce value to requested type */
2406 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2408 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2409 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2412 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2418 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2420 tmpTM = *gmtime(&tmpTime);
2421 STHook = (SYSTEMTIME *)lpBuffer;
2422 STHook->wDay = tmpTM.tm_mday;
2423 STHook->wHour = tmpTM.tm_hour;
2424 STHook->wMilliseconds = 0;
2425 STHook->wMinute = tmpTM.tm_min;
2426 STHook->wDayOfWeek = tmpTM.tm_wday;
2427 STHook->wMonth = tmpTM.tm_mon + 1;
2428 STHook->wSecond = tmpTM.tm_sec;
2429 STHook->wYear = tmpTM.tm_year;
2432 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2433 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2434 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2436 else if (lphttpHdr->lpszValue)
2438 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2440 if (len > *lpdwBufferLength)
2442 *lpdwBufferLength = len;
2443 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2448 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2449 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2451 *lpdwBufferLength = len - sizeof(WCHAR);
2457 /***********************************************************************
2458 * HttpQueryInfoW (WININET.@)
2460 * Queries for information about an HTTP request
2467 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2468 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2470 BOOL bSuccess = FALSE;
2471 LPWININETHTTPREQW lpwhr;
2473 if (TRACE_ON(wininet)) {
2474 #define FE(x) { x, #x }
2475 static const wininet_flag_info query_flags[] = {
2476 FE(HTTP_QUERY_MIME_VERSION),
2477 FE(HTTP_QUERY_CONTENT_TYPE),
2478 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2479 FE(HTTP_QUERY_CONTENT_ID),
2480 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2481 FE(HTTP_QUERY_CONTENT_LENGTH),
2482 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2483 FE(HTTP_QUERY_ALLOW),
2484 FE(HTTP_QUERY_PUBLIC),
2485 FE(HTTP_QUERY_DATE),
2486 FE(HTTP_QUERY_EXPIRES),
2487 FE(HTTP_QUERY_LAST_MODIFIED),
2488 FE(HTTP_QUERY_MESSAGE_ID),
2490 FE(HTTP_QUERY_DERIVED_FROM),
2491 FE(HTTP_QUERY_COST),
2492 FE(HTTP_QUERY_LINK),
2493 FE(HTTP_QUERY_PRAGMA),
2494 FE(HTTP_QUERY_VERSION),
2495 FE(HTTP_QUERY_STATUS_CODE),
2496 FE(HTTP_QUERY_STATUS_TEXT),
2497 FE(HTTP_QUERY_RAW_HEADERS),
2498 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2499 FE(HTTP_QUERY_CONNECTION),
2500 FE(HTTP_QUERY_ACCEPT),
2501 FE(HTTP_QUERY_ACCEPT_CHARSET),
2502 FE(HTTP_QUERY_ACCEPT_ENCODING),
2503 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2504 FE(HTTP_QUERY_AUTHORIZATION),
2505 FE(HTTP_QUERY_CONTENT_ENCODING),
2506 FE(HTTP_QUERY_FORWARDED),
2507 FE(HTTP_QUERY_FROM),
2508 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2509 FE(HTTP_QUERY_LOCATION),
2510 FE(HTTP_QUERY_ORIG_URI),
2511 FE(HTTP_QUERY_REFERER),
2512 FE(HTTP_QUERY_RETRY_AFTER),
2513 FE(HTTP_QUERY_SERVER),
2514 FE(HTTP_QUERY_TITLE),
2515 FE(HTTP_QUERY_USER_AGENT),
2516 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2517 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2518 FE(HTTP_QUERY_ACCEPT_RANGES),
2519 FE(HTTP_QUERY_SET_COOKIE),
2520 FE(HTTP_QUERY_COOKIE),
2521 FE(HTTP_QUERY_REQUEST_METHOD),
2522 FE(HTTP_QUERY_REFRESH),
2523 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2525 FE(HTTP_QUERY_CACHE_CONTROL),
2526 FE(HTTP_QUERY_CONTENT_BASE),
2527 FE(HTTP_QUERY_CONTENT_LOCATION),
2528 FE(HTTP_QUERY_CONTENT_MD5),
2529 FE(HTTP_QUERY_CONTENT_RANGE),
2530 FE(HTTP_QUERY_ETAG),
2531 FE(HTTP_QUERY_HOST),
2532 FE(HTTP_QUERY_IF_MATCH),
2533 FE(HTTP_QUERY_IF_NONE_MATCH),
2534 FE(HTTP_QUERY_IF_RANGE),
2535 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2536 FE(HTTP_QUERY_MAX_FORWARDS),
2537 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2538 FE(HTTP_QUERY_RANGE),
2539 FE(HTTP_QUERY_TRANSFER_ENCODING),
2540 FE(HTTP_QUERY_UPGRADE),
2541 FE(HTTP_QUERY_VARY),
2543 FE(HTTP_QUERY_WARNING),
2544 FE(HTTP_QUERY_CUSTOM)
2546 static const wininet_flag_info modifier_flags[] = {
2547 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2548 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2549 FE(HTTP_QUERY_FLAG_NUMBER),
2550 FE(HTTP_QUERY_FLAG_COALESCE)
2553 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2554 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2557 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2558 TRACE(" Attribute:");
2559 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2560 if (query_flags[i].val == info) {
2561 TRACE(" %s", query_flags[i].name);
2565 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2566 TRACE(" Unknown (%08x)", info);
2569 TRACE(" Modifier:");
2570 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2571 if (modifier_flags[i].val & info_mod) {
2572 TRACE(" %s", modifier_flags[i].name);
2573 info_mod &= ~ modifier_flags[i].val;
2578 TRACE(" Unknown (%08x)", info_mod);
2583 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2584 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2586 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2590 if (lpBuffer == NULL)
2591 *lpdwBufferLength = 0;
2592 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2593 lpBuffer, lpdwBufferLength, lpdwIndex);
2597 WININET_Release( &lpwhr->hdr );
2599 TRACE("%d <--\n", bSuccess);
2603 /***********************************************************************
2604 * HttpQueryInfoA (WININET.@)
2606 * Queries for information about an HTTP request
2613 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2614 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2620 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2621 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2623 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2624 lpdwBufferLength, lpdwIndex );
2630 len = (*lpdwBufferLength)*sizeof(WCHAR);
2631 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2633 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2639 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2640 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2641 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2642 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2649 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2653 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2654 lpBuffer, *lpdwBufferLength, NULL, NULL );
2655 *lpdwBufferLength = len - 1;
2657 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2660 /* since the strings being returned from HttpQueryInfoW should be
2661 * only ASCII characters, it is reasonable to assume that all of
2662 * the Unicode characters can be reduced to a single byte */
2663 *lpdwBufferLength = len / sizeof(WCHAR);
2665 HeapFree(GetProcessHeap(), 0, bufferW );
2670 /***********************************************************************
2671 * HttpSendRequestExA (WININET.@)
2673 * Sends the specified request to the HTTP server and allows chunked
2678 * Failure: FALSE, call GetLastError() for more information.
2680 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2681 LPINTERNET_BUFFERSA lpBuffersIn,
2682 LPINTERNET_BUFFERSA lpBuffersOut,
2683 DWORD dwFlags, DWORD_PTR dwContext)
2685 INTERNET_BUFFERSW BuffersInW;
2688 LPWSTR header = NULL;
2690 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2691 lpBuffersOut, dwFlags, dwContext);
2695 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2696 if (lpBuffersIn->lpcszHeader)
2698 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2699 lpBuffersIn->dwHeadersLength,0,0);
2700 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2701 if (!(BuffersInW.lpcszHeader = header))
2703 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2706 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2707 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2711 BuffersInW.lpcszHeader = NULL;
2712 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2713 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2714 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2715 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2716 BuffersInW.Next = NULL;
2719 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2721 HeapFree(GetProcessHeap(),0,header);
2726 /***********************************************************************
2727 * HttpSendRequestExW (WININET.@)
2729 * Sends the specified request to the HTTP server and allows chunked
2734 * Failure: FALSE, call GetLastError() for more information.
2736 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2737 LPINTERNET_BUFFERSW lpBuffersIn,
2738 LPINTERNET_BUFFERSW lpBuffersOut,
2739 DWORD dwFlags, DWORD_PTR dwContext)
2742 LPWININETHTTPREQW lpwhr;
2743 LPWININETHTTPSESSIONW lpwhs;
2744 LPWININETAPPINFOW hIC;
2746 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2747 lpBuffersOut, dwFlags, dwContext);
2749 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2751 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2753 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2757 lpwhs = lpwhr->lpHttpSession;
2758 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2759 hIC = lpwhs->lpAppInfo;
2760 assert(hIC->hdr.htype == WH_HINIT);
2762 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2764 WORKREQUEST workRequest;
2765 struct WORKREQ_HTTPSENDREQUESTW *req;
2767 workRequest.asyncproc = AsyncHttpSendRequestProc;
2768 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2769 req = &workRequest.u.HttpSendRequestW;
2772 if (lpBuffersIn->lpcszHeader)
2773 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2774 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2776 req->lpszHeader = NULL;
2777 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2778 req->lpOptional = lpBuffersIn->lpvBuffer;
2779 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2780 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2784 req->lpszHeader = NULL;
2785 req->dwHeaderLength = 0;
2786 req->lpOptional = NULL;
2787 req->dwOptionalLength = 0;
2788 req->dwContentLength = 0;
2791 req->bEndRequest = FALSE;
2793 INTERNET_AsyncCall(&workRequest);
2795 * This is from windows.
2797 INTERNET_SetLastError(ERROR_IO_PENDING);
2802 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2803 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2804 lpBuffersIn->dwBufferTotal, FALSE);
2806 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2811 WININET_Release( &lpwhr->hdr );
2817 /***********************************************************************
2818 * HttpSendRequestW (WININET.@)
2820 * Sends the specified request to the HTTP server
2827 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2828 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2830 LPWININETHTTPREQW lpwhr;
2831 LPWININETHTTPSESSIONW lpwhs = NULL;
2832 LPWININETAPPINFOW hIC = NULL;
2835 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2836 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2838 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2839 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2841 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2846 lpwhs = lpwhr->lpHttpSession;
2847 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2849 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2854 hIC = lpwhs->lpAppInfo;
2855 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2857 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2862 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2864 WORKREQUEST workRequest;
2865 struct WORKREQ_HTTPSENDREQUESTW *req;
2867 workRequest.asyncproc = AsyncHttpSendRequestProc;
2868 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2869 req = &workRequest.u.HttpSendRequestW;
2874 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
2875 else size = dwHeaderLength * sizeof(WCHAR);
2877 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, size);
2878 memcpy(req->lpszHeader, lpszHeaders, size);
2881 req->lpszHeader = 0;
2882 req->dwHeaderLength = dwHeaderLength;
2883 req->lpOptional = lpOptional;
2884 req->dwOptionalLength = dwOptionalLength;
2885 req->dwContentLength = dwOptionalLength;
2886 req->bEndRequest = TRUE;
2888 INTERNET_AsyncCall(&workRequest);
2890 * This is from windows.
2892 INTERNET_SetLastError(ERROR_IO_PENDING);
2897 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2898 dwHeaderLength, lpOptional, dwOptionalLength,
2899 dwOptionalLength, TRUE);
2903 WININET_Release( &lpwhr->hdr );
2907 /***********************************************************************
2908 * HttpSendRequestA (WININET.@)
2910 * Sends the specified request to the HTTP server
2917 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2918 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2921 LPWSTR szHeaders=NULL;
2922 DWORD nLen=dwHeaderLength;
2923 if(lpszHeaders!=NULL)
2925 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2926 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2927 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2929 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2930 HeapFree(GetProcessHeap(),0,szHeaders);
2934 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2936 LPHTTPHEADERW host_header;
2938 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2940 host_header = HTTP_GetHeader(req, szHost);
2944 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2948 /***********************************************************************
2949 * HTTP_GetRedirectURL (internal)
2951 static LPWSTR HTTP_GetRedirectURL(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2953 static WCHAR szHttp[] = {'h','t','t','p',0};
2954 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2955 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2956 URL_COMPONENTSW urlComponents;
2957 DWORD url_length = 0;
2959 LPWSTR combined_url;
2961 if (lpszUrl[0]=='/') return WININET_strdupW( lpszUrl );
2963 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2964 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2965 urlComponents.dwSchemeLength = 0;
2966 urlComponents.lpszHostName = lpwhs->lpszHostName;
2967 urlComponents.dwHostNameLength = 0;
2968 urlComponents.nPort = lpwhs->nHostPort;
2969 urlComponents.lpszUserName = lpwhs->lpszUserName;
2970 urlComponents.dwUserNameLength = 0;
2971 urlComponents.lpszPassword = NULL;
2972 urlComponents.dwPasswordLength = 0;
2973 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2974 urlComponents.dwUrlPathLength = 0;
2975 urlComponents.lpszExtraInfo = NULL;
2976 urlComponents.dwExtraInfoLength = 0;
2978 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2979 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2982 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2984 /* convert from bytes to characters */
2985 url_length = url_length / sizeof(WCHAR) - 1;
2986 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2988 HeapFree(GetProcessHeap(), 0, orig_url);
2993 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2994 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2996 HeapFree(GetProcessHeap(), 0, orig_url);
2999 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
3001 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
3003 HeapFree(GetProcessHeap(), 0, orig_url);
3004 HeapFree(GetProcessHeap(), 0, combined_url);
3007 HeapFree(GetProcessHeap(), 0, orig_url);
3008 return combined_url;
3012 /***********************************************************************
3013 * HTTP_HandleRedirect (internal)
3015 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
3017 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3018 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
3019 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
3020 WCHAR path[INTERNET_MAX_URL_LENGTH];
3025 /* if it's an absolute path, keep the same session info */
3026 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
3030 URL_COMPONENTSW urlComponents;
3031 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
3032 static WCHAR szHttp[] = {'h','t','t','p',0};
3033 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3039 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3040 urlComponents.lpszScheme = protocol;
3041 urlComponents.dwSchemeLength = 32;
3042 urlComponents.lpszHostName = hostName;
3043 urlComponents.dwHostNameLength = MAXHOSTNAME;
3044 urlComponents.lpszUserName = userName;
3045 urlComponents.dwUserNameLength = 1024;
3046 urlComponents.lpszPassword = NULL;
3047 urlComponents.dwPasswordLength = 0;
3048 urlComponents.lpszUrlPath = path;
3049 urlComponents.dwUrlPathLength = 2048;
3050 urlComponents.lpszExtraInfo = NULL;
3051 urlComponents.dwExtraInfoLength = 0;
3052 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
3055 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
3056 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3058 TRACE("redirect from secure page to non-secure page\n");
3059 /* FIXME: warn about from secure redirect to non-secure page */
3060 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
3062 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
3063 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3065 TRACE("redirect from non-secure page to secure page\n");
3066 /* FIXME: notify about redirect to secure page */
3067 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
3070 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3072 if (lstrlenW(protocol)>4) /*https*/
3073 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3075 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3080 * This upsets redirects to binary files on sourceforge.net
3081 * and gives an html page instead of the target file
3082 * Examination of the HTTP request sent by native wininet.dll
3083 * reveals that it doesn't send a referrer in that case.
3084 * Maybe there's a flag that enables this, or maybe a referrer
3085 * shouldn't be added in case of a redirect.
3088 /* consider the current host as the referrer */
3089 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3090 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3091 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3092 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3095 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3096 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3097 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3100 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3101 len = lstrlenW(hostName);
3102 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3103 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3104 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3107 lpwhs->lpszHostName = WININET_strdupW(hostName);
3109 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3111 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3112 lpwhs->lpszUserName = NULL;
3114 lpwhs->lpszUserName = WININET_strdupW(userName);
3118 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3120 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3121 lpwhs->lpszServerName = WININET_strdupW(hostName);
3122 lpwhs->nServerPort = urlComponents.nPort;
3124 NETCON_close(&lpwhr->netConnection);
3125 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3126 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3130 TRACE("Redirect through proxy\n");
3133 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3134 lpwhr->lpszPath=NULL;
3140 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3141 if (rc != E_POINTER)
3142 needed = strlenW(path)+1;
3143 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3144 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3145 URL_ESCAPE_SPACES_ONLY);
3148 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3149 strcpyW(lpwhr->lpszPath,path);
3153 /* Remove custom content-type/length headers on redirects. */
3154 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
3156 HTTP_DeleteCustomHeader(lpwhr, index);
3157 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
3159 HTTP_DeleteCustomHeader(lpwhr, index);
3164 /***********************************************************************
3165 * HTTP_build_req (internal)
3167 * concatenate all the strings in the request together
3169 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3174 for( t = list; *t ; t++ )
3175 len += strlenW( *t );
3178 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3181 for( t = list; *t ; t++ )
3187 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3190 LPWSTR requestString;
3196 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3197 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3198 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3202 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3203 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3204 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3205 HeapFree( GetProcessHeap(), 0, lpszPath );
3207 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3208 NULL, 0, NULL, NULL );
3209 len--; /* the nul terminator isn't needed */
3210 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3211 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3212 ascii_req, len, NULL, NULL );
3213 HeapFree( GetProcessHeap(), 0, requestString );
3215 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3217 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3218 HeapFree( GetProcessHeap(), 0, ascii_req );
3219 if (!ret || cnt < 0)
3222 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3229 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3231 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3232 LPWSTR lpszCookies, lpszUrl = NULL;
3233 DWORD nCookieSize, size;
3234 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3236 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm) + strlenW(lpwhr->lpszPath)) * sizeof(WCHAR);
3237 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3238 sprintfW( lpszUrl, szUrlForm, Host->lpszValue, lpwhr->lpszPath);
3240 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3243 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3245 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3246 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3248 cnt += sprintfW(lpszCookies, szCookie);
3249 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3250 strcatW(lpszCookies, szCrLf);
3252 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_REPLACE);
3253 HeapFree(GetProcessHeap(), 0, lpszCookies);
3256 HeapFree(GetProcessHeap(), 0, lpszUrl);
3259 /***********************************************************************
3260 * HTTP_HttpSendRequestW (internal)
3262 * Sends the specified request to the HTTP server
3269 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3270 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3271 DWORD dwContentLength, BOOL bEndRequest)
3274 BOOL bSuccess = FALSE, redirected = FALSE;
3275 LPWSTR requestString = NULL;
3278 INTERNET_ASYNC_RESULT iar;
3279 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3280 static const WCHAR szContentLength[] =
3281 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3282 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3284 TRACE("--> %p\n", lpwhr);
3286 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3288 /* if the verb is NULL default to GET */
3289 if (!lpwhr->lpszVerb)
3290 lpwhr->lpszVerb = WININET_strdupW(szGET);
3292 if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3294 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3295 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
3296 lpwhr->dwBytesToWrite = dwContentLength;
3298 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3300 WCHAR *agent_header;
3301 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3304 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3305 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3306 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3308 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3309 HeapFree(GetProcessHeap(), 0, agent_header);
3311 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3313 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3314 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3316 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3318 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3319 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3320 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3330 /* like native, just in case the caller forgot to call InternetReadFile
3331 * for all the data */
3332 HTTP_DrainContent(lpwhr);
3333 lpwhr->dwContentRead = 0;
3335 if (TRACE_ON(wininet))
3337 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3338 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3342 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3344 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3346 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3347 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3349 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3350 HTTP_InsertCookies(lpwhr);
3352 /* add the headers the caller supplied */
3353 if( lpszHeaders && dwHeaderLength )
3355 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3356 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3359 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3361 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3362 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3363 HeapFree(GetProcessHeap(), 0, url);
3366 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3369 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3371 /* Send the request and store the results */
3372 if (!HTTP_OpenConnection(lpwhr))
3375 /* send the request as ASCII, tack on the optional data */
3376 if (!lpOptional || redirected)
3377 dwOptionalLength = 0;
3378 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3379 NULL, 0, NULL, NULL );
3380 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3381 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3382 ascii_req, len, NULL, NULL );
3384 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3385 len = (len + dwOptionalLength - 1);
3387 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3389 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3390 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3392 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3393 HeapFree( GetProcessHeap(), 0, ascii_req );
3395 lpwhr->dwBytesWritten = dwOptionalLength;
3397 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3398 INTERNET_STATUS_REQUEST_SENT,
3399 &len, sizeof(DWORD));
3406 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3408 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3409 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3414 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3418 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3419 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3422 HTTP_ProcessCookies(lpwhr);
3424 dwBufferSize = sizeof(lpwhr->dwContentLength);
3425 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3426 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3427 lpwhr->dwContentLength = -1;
3429 if (lpwhr->dwContentLength == 0)
3430 HTTP_FinishedReading(lpwhr);
3432 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3434 dwBufferSize = sizeof(encoding);
3435 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3436 !strcmpiW(encoding, szChunked))
3438 lpwhr->dwContentLength = -1;
3441 dwBufferSize = sizeof(dwStatusCode);
3442 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3443 &dwStatusCode,&dwBufferSize,NULL))
3446 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3448 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
3449 dwBufferSize=sizeof(szNewLocation);
3450 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3451 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3453 /* redirects are always GETs */
3454 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3455 lpwhr->lpszVerb = WININET_strdupW(szGET);
3457 HTTP_DrainContent(lpwhr);
3458 if ((new_url = HTTP_GetRedirectURL( lpwhr, szNewLocation )))
3460 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REDIRECT,
3461 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
3462 bSuccess = HTTP_HandleRedirect(lpwhr, new_url);
3465 HeapFree(GetProcessHeap(), 0, requestString);
3468 HeapFree( GetProcessHeap(), 0, new_url );
3473 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3475 WCHAR szAuthValue[2048];
3477 if (dwStatusCode == HTTP_STATUS_DENIED)
3480 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3482 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3484 lpwhr->lpHttpSession->lpszUserName,
3485 lpwhr->lpHttpSession->lpszPassword))
3492 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3495 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3497 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3498 &lpwhr->pProxyAuthInfo,
3499 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3500 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3514 /* FIXME: Better check, when we have to create the cache file */
3515 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3516 WCHAR url[INTERNET_MAX_URL_LENGTH];
3517 WCHAR cacheFileName[MAX_PATH+1];
3520 b = HTTP_GetRequestURL(lpwhr, url);
3522 WARN("Could not get URL\n");
3526 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3528 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3529 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3530 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3531 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3532 WARN("Could not create file: %u\n", GetLastError());
3533 lpwhr->hCacheFile = NULL;
3536 WARN("Could not create cache entry: %08x\n", GetLastError());
3542 HeapFree(GetProcessHeap(), 0, requestString);
3544 /* TODO: send notification for P3P header */
3546 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3550 if (lpwhr->dwBytesWritten == lpwhr->dwBytesToWrite) HTTP_ReceiveRequestData(lpwhr, TRUE);
3553 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3556 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3557 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3558 sizeof(INTERNET_ASYNC_RESULT));
3563 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3564 iar.dwError = INTERNET_GetLastError();
3566 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3567 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3568 sizeof(INTERNET_ASYNC_RESULT));
3573 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3577 /***********************************************************************
3578 * HTTPSESSION_Destroy (internal)
3580 * Deallocate session handle
3583 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3585 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3587 TRACE("%p\n", lpwhs);
3589 WININET_Release(&lpwhs->lpAppInfo->hdr);
3591 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3592 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3593 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3594 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3595 HeapFree(GetProcessHeap(), 0, lpwhs);
3598 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3601 case INTERNET_OPTION_HANDLE_TYPE:
3602 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3604 if (*size < sizeof(ULONG))
3605 return ERROR_INSUFFICIENT_BUFFER;
3607 *size = sizeof(DWORD);
3608 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3609 return ERROR_SUCCESS;
3612 return INET_QueryOption(option, buffer, size, unicode);
3615 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3617 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3620 case INTERNET_OPTION_USERNAME:
3622 HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
3623 if (!(ses->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3624 return ERROR_SUCCESS;
3626 case INTERNET_OPTION_PASSWORD:
3628 HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
3629 if (!(ses->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3630 return ERROR_SUCCESS;
3635 return ERROR_INTERNET_INVALID_OPTION;
3638 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3639 HTTPSESSION_Destroy,
3641 HTTPSESSION_QueryOption,
3642 HTTPSESSION_SetOption,
3651 /***********************************************************************
3652 * HTTP_Connect (internal)
3654 * Create http session handle
3657 * HINTERNET a session handle on success
3661 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3662 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3663 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3664 DWORD dwInternalFlags)
3666 LPWININETHTTPSESSIONW lpwhs = NULL;
3667 HINTERNET handle = NULL;
3671 if (!lpszServerName || !lpszServerName[0])
3673 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3677 assert( hIC->hdr.htype == WH_HINIT );
3679 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3682 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3687 * According to my tests. The name is not resolved until a request is sent
3690 lpwhs->hdr.htype = WH_HHTTPSESSION;
3691 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3692 lpwhs->hdr.dwFlags = dwFlags;
3693 lpwhs->hdr.dwContext = dwContext;
3694 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3695 lpwhs->hdr.refs = 1;
3696 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3698 WININET_AddRef( &hIC->hdr );
3699 lpwhs->lpAppInfo = hIC;
3700 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3702 handle = WININET_AllocHandle( &lpwhs->hdr );
3705 ERR("Failed to alloc handle\n");
3706 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3710 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3711 if(strchrW(hIC->lpszProxy, ' '))
3712 FIXME("Several proxies not implemented.\n");
3713 if(hIC->lpszProxyBypass)
3714 FIXME("Proxy bypass is ignored.\n");
3716 if (lpszServerName && lpszServerName[0])
3718 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3719 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3721 if (lpszUserName && lpszUserName[0])
3722 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3723 if (lpszPassword && lpszPassword[0])
3724 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3725 lpwhs->nServerPort = nServerPort;
3726 lpwhs->nHostPort = nServerPort;
3728 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3729 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3731 INTERNET_SendCallback(&hIC->hdr, dwContext,
3732 INTERNET_STATUS_HANDLE_CREATED, &handle,
3738 WININET_Release( &lpwhs->hdr );
3741 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3745 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3750 /***********************************************************************
3751 * HTTP_OpenConnection (internal)
3753 * Connect to a web server
3760 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3762 BOOL bSuccess = FALSE;
3763 LPWININETHTTPSESSIONW lpwhs;
3764 LPWININETAPPINFOW hIC = NULL;
3770 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3772 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3776 if (NETCON_connected(&lpwhr->netConnection))
3781 if (!HTTP_ResolveName(lpwhr)) goto lend;
3783 lpwhs = lpwhr->lpHttpSession;
3785 hIC = lpwhs->lpAppInfo;
3786 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3787 szaddr, sizeof(szaddr));
3788 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3789 INTERNET_STATUS_CONNECTING_TO_SERVER,
3793 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3796 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3800 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3801 sizeof(lpwhs->socketAddress)))
3804 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3806 /* Note: we differ from Microsoft's WinINet here. they seem to have
3807 * a bug that causes no status callbacks to be sent when starting
3808 * a tunnel to a proxy server using the CONNECT verb. i believe our
3809 * behaviour to be more correct and to not cause any incompatibilities
3810 * because using a secure connection through a proxy server is a rare
3811 * case that would be hard for anyone to depend on */
3812 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3815 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3817 WARN("Couldn't connect securely to host\n");
3822 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3823 INTERNET_STATUS_CONNECTED_TO_SERVER,
3824 szaddr, strlen(szaddr)+1);
3829 TRACE("%d <--\n", bSuccess);
3834 /***********************************************************************
3835 * HTTP_clear_response_headers (internal)
3837 * clear out any old response headers
3839 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3843 for( i=0; i<lpwhr->nCustHeaders; i++)
3845 if( !lpwhr->pCustHeaders[i].lpszField )
3847 if( !lpwhr->pCustHeaders[i].lpszValue )
3849 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3851 HTTP_DeleteCustomHeader( lpwhr, i );
3856 /***********************************************************************
3857 * HTTP_GetResponseHeaders (internal)
3859 * Read server response
3866 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3869 WCHAR buffer[MAX_REPLY_LEN];
3870 DWORD buflen = MAX_REPLY_LEN;
3871 BOOL bSuccess = FALSE;
3873 static const WCHAR szHundred[] = {'1','0','0',0};
3874 char bufferA[MAX_REPLY_LEN];
3875 LPWSTR status_code, status_text;
3876 DWORD cchMaxRawHeaders = 1024;
3877 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3878 DWORD cchRawHeaders = 0;
3882 /* clear old response headers (eg. from a redirect response) */
3883 if (clear) HTTP_clear_response_headers( lpwhr );
3885 if (!NETCON_connected(&lpwhr->netConnection))
3890 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3892 buflen = MAX_REPLY_LEN;
3893 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3896 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3898 /* split the version from the status code */
3899 status_code = strchrW( buffer, ' ' );
3904 /* split the status code from the status text */
3905 status_text = strchrW( status_code, ' ' );
3910 TRACE("version [%s] status code [%s] status text [%s]\n",
3911 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3913 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3915 /* Add status code */
3916 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3917 HTTP_ADDHDR_FLAG_REPLACE);
3919 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3920 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3922 lpwhr->lpszVersion= WININET_strdupW(buffer);
3923 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3925 /* Restore the spaces */
3926 *(status_code-1) = ' ';
3927 *(status_text-1) = ' ';
3929 /* regenerate raw headers */
3930 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3932 cchMaxRawHeaders *= 2;
3933 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3935 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3936 cchRawHeaders += (buflen-1);
3937 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3938 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3939 lpszRawHeaders[cchRawHeaders] = '\0';
3941 /* Parse each response line */
3944 buflen = MAX_REPLY_LEN;
3945 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3947 LPWSTR * pFieldAndValue;
3949 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3951 if (!bufferA[0]) break;
3952 if (!strchr(bufferA, ':'))
3954 WARN("invalid header\n");
3957 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3959 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3961 cchMaxRawHeaders *= 2;
3962 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3964 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3965 cchRawHeaders += (buflen-1);
3966 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3967 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3968 lpszRawHeaders[cchRawHeaders] = '\0';
3970 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3971 if (!pFieldAndValue)
3974 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3975 HTTP_ADDREQ_FLAG_ADD );
3977 HTTP_FreeTokens(pFieldAndValue);
3987 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3988 lpwhr->lpszRawHeaders = lpszRawHeaders;
3989 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3999 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
4005 static void strip_spaces(LPWSTR start)
4010 while (*str == ' ' && *str != '\0')
4014 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
4016 end = start + strlenW(start) - 1;
4017 while (end >= start && *end == ' ')
4025 /***********************************************************************
4026 * HTTP_InterpretHttpHeader (internal)
4028 * Parse server response
4032 * Pointer to array of field, value, NULL on success.
4035 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
4037 LPWSTR * pTokenPair;
4041 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
4043 pszColon = strchrW(buffer, ':');
4044 /* must have two tokens */
4047 HTTP_FreeTokens(pTokenPair);
4049 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
4053 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
4056 HTTP_FreeTokens(pTokenPair);
4059 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
4060 pTokenPair[0][pszColon - buffer] = '\0';
4064 len = strlenW(pszColon);
4065 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
4068 HTTP_FreeTokens(pTokenPair);
4071 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
4073 strip_spaces(pTokenPair[0]);
4074 strip_spaces(pTokenPair[1]);
4076 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
4080 /***********************************************************************
4081 * HTTP_ProcessHeader (internal)
4083 * Stuff header into header tables according to <dwModifier>
4087 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4089 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4091 LPHTTPHEADERW lphttpHdr = NULL;
4092 BOOL bSuccess = FALSE;
4094 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4096 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
4098 /* REPLACE wins out over ADD */
4099 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4100 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
4102 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
4105 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
4109 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4113 lphttpHdr = &lpwhr->pCustHeaders[index];
4119 hdr.lpszField = (LPWSTR)field;
4120 hdr.lpszValue = (LPWSTR)value;
4121 hdr.wFlags = hdr.wCount = 0;
4123 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4124 hdr.wFlags |= HDR_ISREQUEST;
4126 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4128 /* no value to delete */
4131 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4132 lphttpHdr->wFlags |= HDR_ISREQUEST;
4134 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4136 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4138 HTTP_DeleteCustomHeader( lpwhr, index );
4144 hdr.lpszField = (LPWSTR)field;
4145 hdr.lpszValue = (LPWSTR)value;
4146 hdr.wFlags = hdr.wCount = 0;
4148 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4149 hdr.wFlags |= HDR_ISREQUEST;
4151 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4156 else if (dwModifier & COALESCEFLAGS)
4161 INT origlen = strlenW(lphttpHdr->lpszValue);
4162 INT valuelen = strlenW(value);
4164 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4167 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4169 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4172 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4175 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4177 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4180 lphttpHdr->lpszValue = lpsztmp;
4181 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4184 lphttpHdr->lpszValue[origlen] = ch;
4186 lphttpHdr->lpszValue[origlen] = ' ';
4190 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4191 lphttpHdr->lpszValue[len] = '\0';
4196 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4197 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4200 TRACE("<-- %d\n",bSuccess);
4205 /***********************************************************************
4206 * HTTP_FinishedReading (internal)
4208 * Called when all content from server has been read by client.
4211 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4213 WCHAR szVersion[10];
4214 WCHAR szConnectionResponse[20];
4215 DWORD dwBufferSize = sizeof(szVersion);
4216 BOOL keepalive = FALSE;
4220 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4221 * the connection is keep-alive by default */
4222 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4223 &dwBufferSize, NULL) &&
4224 !strcmpiW(szVersion, g_szHttp1_1))
4229 dwBufferSize = sizeof(szConnectionResponse);
4230 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4231 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4233 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4238 HTTPREQ_CloseConnection(&lpwhr->hdr);
4241 /* FIXME: store data in the URL cache here */
4247 /***********************************************************************
4248 * HTTP_GetCustomHeaderIndex (internal)
4250 * Return index of custom header from header array
4253 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4254 int requested_index, BOOL request_only)
4258 TRACE("%s\n", debugstr_w(lpszField));
4260 for (index = 0; index < lpwhr->nCustHeaders; index++)
4262 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4265 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4268 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4271 if (requested_index == 0)
4276 if (index >= lpwhr->nCustHeaders)
4279 TRACE("Return: %d\n", index);
4284 /***********************************************************************
4285 * HTTP_InsertCustomHeader (internal)
4287 * Insert header into array
4290 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4293 LPHTTPHEADERW lph = NULL;
4296 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4297 count = lpwhr->nCustHeaders + 1;
4299 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4301 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4305 lpwhr->pCustHeaders = lph;
4306 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4307 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4308 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4309 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4310 lpwhr->nCustHeaders++;
4315 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4322 /***********************************************************************
4323 * HTTP_DeleteCustomHeader (internal)
4325 * Delete header from array
4326 * If this function is called, the indexs may change.
4328 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4330 if( lpwhr->nCustHeaders <= 0 )
4332 if( index >= lpwhr->nCustHeaders )
4334 lpwhr->nCustHeaders--;
4336 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4337 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4339 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4340 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4341 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4347 /***********************************************************************
4348 * HTTP_VerifyValidHeader (internal)
4350 * Verify the given header is not invalid for the given http request
4353 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4355 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4356 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4362 /***********************************************************************
4363 * IsHostInProxyBypassList (@)
4368 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4370 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);