2 * Wininet - Http Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
30 #include "wine/port.h"
32 #include <sys/types.h>
33 #ifdef HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
36 #ifdef HAVE_ARPA_INET_H
37 # include <arpa/inet.h>
52 #define NO_SHLWAPI_STREAM
53 #define NO_SHLWAPI_REG
54 #define NO_SHLWAPI_STRFCNS
55 #define NO_SHLWAPI_GDI
61 #include "wine/debug.h"
62 #include "wine/unicode.h"
64 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
66 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
67 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
68 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
69 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
70 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
71 static const WCHAR szHost[] = { 'H','o','s','t',0 };
72 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
74 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
75 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
76 static const WCHAR szGET[] = { 'G','E','T', 0 };
77 static const WCHAR szCrLf[] = {'\r','\n', 0};
79 #define MAXHOSTNAME 100
80 #define MAX_FIELD_VALUE_LEN 256
81 #define MAX_FIELD_LEN 256
83 #define HTTP_REFERER g_szReferer
84 #define HTTP_ACCEPT g_szAccept
85 #define HTTP_USERAGENT g_szUserAgent
87 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
88 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
89 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
90 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
91 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
92 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
93 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
95 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
106 unsigned int auth_data_len;
107 BOOL finished; /* finished authenticating */
110 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
111 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
112 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
113 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
114 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
115 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
116 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
117 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
118 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
119 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
120 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
121 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
122 static void HTTP_DrainContent(WININETHTTPREQW *req);
124 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
127 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
128 if (HeaderIndex == -1)
131 return &req->pCustHeaders[HeaderIndex];
134 /***********************************************************************
135 * HTTP_Tokenize (internal)
137 * Tokenize a string, allocating memory for the tokens.
139 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
141 LPWSTR * token_array;
148 /* empty string has no tokens */
152 for (i = 0; string[i]; i++)
154 if (!strncmpW(string+i, token_string, strlenW(token_string)))
158 /* we want to skip over separators, but not the null terminator */
159 for (j = 0; j < strlenW(token_string) - 1; j++)
167 /* add 1 for terminating NULL */
168 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
169 token_array[tokens] = NULL;
172 for (i = 0; i < tokens; i++)
175 next_token = strstrW(string, token_string);
176 if (!next_token) next_token = string+strlenW(string);
177 len = next_token - string;
178 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
179 memcpy(token_array[i], string, len*sizeof(WCHAR));
180 token_array[i][len] = '\0';
181 string = next_token+strlenW(token_string);
186 /***********************************************************************
187 * HTTP_FreeTokens (internal)
189 * Frees memory returned from HTTP_Tokenize.
191 static void HTTP_FreeTokens(LPWSTR * token_array)
194 for (i = 0; token_array[i]; i++)
195 HeapFree(GetProcessHeap(), 0, token_array[i]);
196 HeapFree(GetProcessHeap(), 0, token_array);
199 /* **********************************************************************
201 * Helper functions for the HttpSendRequest(Ex) functions
204 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
206 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
207 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
209 TRACE("%p\n", lpwhr);
211 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
212 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
213 req->dwContentLength, req->bEndRequest);
215 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
218 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
220 static const WCHAR szSlash[] = { '/',0 };
221 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
223 /* If we don't have a path we set it to root */
224 if (NULL == lpwhr->lpszPath)
225 lpwhr->lpszPath = WININET_strdupW(szSlash);
226 else /* remove \r and \n*/
228 int nLen = strlenW(lpwhr->lpszPath);
229 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
232 lpwhr->lpszPath[nLen]='\0';
234 /* Replace '\' with '/' */
237 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
241 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
242 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
243 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
245 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
246 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
248 strcpyW(fixurl + 1, lpwhr->lpszPath);
249 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
250 lpwhr->lpszPath = fixurl;
254 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
256 LPWSTR requestString;
262 static const WCHAR szSpace[] = { ' ',0 };
263 static const WCHAR szColon[] = { ':',' ',0 };
264 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
266 /* allocate space for an array of all the string pointers to be added */
267 len = (lpwhr->nCustHeaders)*4 + 10;
268 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
270 /* add the verb, path and HTTP version string */
278 /* Append custom request headers */
279 for (i = 0; i < lpwhr->nCustHeaders; i++)
281 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
284 req[n++] = lpwhr->pCustHeaders[i].lpszField;
286 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
288 TRACE("Adding custom header %s (%s)\n",
289 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
290 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
295 ERR("oops. buffer overrun\n");
298 requestString = HTTP_build_req( req, 4 );
299 HeapFree( GetProcessHeap(), 0, req );
302 * Set (header) termination string for request
303 * Make sure there's exactly two new lines at the end of the request
305 p = &requestString[strlenW(requestString)-1];
306 while ( (*p == '\n') || (*p == '\r') )
308 strcpyW( p+1, sztwocrlf );
310 return requestString;
313 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
315 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
318 LPHTTPHEADERW setCookieHeader;
320 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
322 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
324 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
326 int nPosStart = 0, nPosEnd = 0, len;
327 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
329 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
331 LPWSTR buf_cookie, cookie_name, cookie_data;
333 LPWSTR domain = NULL;
337 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
338 setCookieHeader->lpszValue[nPosEnd] != '\0')
342 if (setCookieHeader->lpszValue[nPosEnd] == ';')
344 /* fixme: not case sensitive, strcasestr is gnu only */
345 int nDomainPosEnd = 0;
346 int nDomainPosStart = 0, nDomainLength = 0;
347 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
348 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
350 { /* they have specified their own domain, lets use it */
351 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
352 lpszDomain[nDomainPosEnd] != '\0')
356 nDomainPosStart = strlenW(szDomain);
357 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
358 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
359 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
362 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
363 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
364 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
365 TRACE("%s\n", debugstr_w(buf_cookie));
366 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
370 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
372 HeapFree(GetProcessHeap(), 0, buf_cookie);
376 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
377 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
378 cookie_data = &buf_cookie[nEqualPos + 1];
380 Host = HTTP_GetHeader(lpwhr,szHost);
381 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
382 strlenW(lpwhr->lpszPath) + 9;
383 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
384 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
385 InternetSetCookieW(buf_url, cookie_name, cookie_data);
387 HeapFree(GetProcessHeap(), 0, buf_url);
388 HeapFree(GetProcessHeap(), 0, buf_cookie);
389 HeapFree(GetProcessHeap(), 0, cookie_name);
390 HeapFree(GetProcessHeap(), 0, domain);
398 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
400 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
401 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
402 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
405 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
406 struct HttpAuthInfo **ppAuthInfo,
407 LPWSTR domain_and_username, LPWSTR password )
409 SECURITY_STATUS sec_status;
410 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
413 TRACE("%s\n", debugstr_w(pszAuthValue));
420 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
424 SecInvalidateHandle(&pAuthInfo->cred);
425 SecInvalidateHandle(&pAuthInfo->ctx);
426 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
428 pAuthInfo->auth_data = NULL;
429 pAuthInfo->auth_data_len = 0;
430 pAuthInfo->finished = FALSE;
432 if (is_basic_auth_value(pszAuthValue))
434 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
435 pAuthInfo->scheme = WININET_strdupW(szBasic);
436 if (!pAuthInfo->scheme)
438 HeapFree(GetProcessHeap(), 0, pAuthInfo);
445 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
447 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
448 if (!pAuthInfo->scheme)
450 HeapFree(GetProcessHeap(), 0, pAuthInfo);
454 if (domain_and_username)
456 WCHAR *user = strchrW(domain_and_username, '\\');
457 WCHAR *domain = domain_and_username;
459 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
461 pAuthData = &nt_auth_identity;
466 user = domain_and_username;
470 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
471 nt_auth_identity.User = user;
472 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
473 nt_auth_identity.Domain = domain;
474 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
475 nt_auth_identity.Password = password;
476 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
479 /* use default credentials */
482 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
483 SECPKG_CRED_OUTBOUND, NULL,
485 NULL, &pAuthInfo->cred,
487 if (sec_status == SEC_E_OK)
489 PSecPkgInfoW sec_pkg_info;
490 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
491 if (sec_status == SEC_E_OK)
493 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
494 FreeContextBuffer(sec_pkg_info);
497 if (sec_status != SEC_E_OK)
499 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
500 debugstr_w(pAuthInfo->scheme), sec_status);
501 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
502 HeapFree(GetProcessHeap(), 0, pAuthInfo);
506 *ppAuthInfo = pAuthInfo;
508 else if (pAuthInfo->finished)
511 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
512 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
514 ERR("authentication scheme changed from %s to %s\n",
515 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
519 if (is_basic_auth_value(pszAuthValue))
525 TRACE("basic authentication\n");
527 /* we don't cache credentials for basic authentication, so we can't
528 * retrieve them if the application didn't pass us any credentials */
529 if (!domain_and_username) return FALSE;
531 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
532 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
534 /* length includes a nul terminator, which will be re-used for the ':' */
535 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
539 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
540 auth_data[userlen] = ':';
541 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
543 pAuthInfo->auth_data = auth_data;
544 pAuthInfo->auth_data_len = userlen + 1 + passlen;
545 pAuthInfo->finished = TRUE;
552 SecBufferDesc out_desc, in_desc;
554 unsigned char *buffer;
555 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
556 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
558 in.BufferType = SECBUFFER_TOKEN;
562 in_desc.ulVersion = 0;
563 in_desc.cBuffers = 1;
564 in_desc.pBuffers = ∈
566 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
567 if (*pszAuthData == ' ')
570 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
571 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
572 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
575 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
577 out.BufferType = SECBUFFER_TOKEN;
578 out.cbBuffer = pAuthInfo->max_token;
579 out.pvBuffer = buffer;
581 out_desc.ulVersion = 0;
582 out_desc.cBuffers = 1;
583 out_desc.pBuffers = &out;
585 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
586 first ? NULL : &pAuthInfo->ctx,
587 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
588 context_req, 0, SECURITY_NETWORK_DREP,
589 in.pvBuffer ? &in_desc : NULL,
590 0, &pAuthInfo->ctx, &out_desc,
591 &pAuthInfo->attr, &pAuthInfo->exp);
592 if (sec_status == SEC_E_OK)
594 pAuthInfo->finished = TRUE;
595 pAuthInfo->auth_data = out.pvBuffer;
596 pAuthInfo->auth_data_len = out.cbBuffer;
597 TRACE("sending last auth packet\n");
599 else if (sec_status == SEC_I_CONTINUE_NEEDED)
601 pAuthInfo->auth_data = out.pvBuffer;
602 pAuthInfo->auth_data_len = out.cbBuffer;
603 TRACE("sending next auth packet\n");
607 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
608 pAuthInfo->finished = TRUE;
609 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
617 /***********************************************************************
618 * HTTP_HttpAddRequestHeadersW (internal)
620 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
621 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
626 BOOL bSuccess = FALSE;
629 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
631 if( dwHeaderLength == ~0U )
632 len = strlenW(lpszHeader);
634 len = dwHeaderLength;
635 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
636 lstrcpynW( buffer, lpszHeader, len + 1);
642 LPWSTR * pFieldAndValue;
646 while (*lpszEnd != '\0')
648 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
653 if (*lpszStart == '\0')
656 if (*lpszEnd == '\r')
659 lpszEnd += 2; /* Jump over \r\n */
661 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
662 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
665 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
667 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
668 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
669 HTTP_FreeTokens(pFieldAndValue);
675 HeapFree(GetProcessHeap(), 0, buffer);
680 /***********************************************************************
681 * HttpAddRequestHeadersW (WININET.@)
683 * Adds one or more HTTP header to the request handler
686 * On Windows if dwHeaderLength includes the trailing '\0', then
687 * HttpAddRequestHeadersW() adds it too. However this results in an
688 * invalid Http header which is rejected by some servers so we probably
689 * don't need to match Windows on that point.
696 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
697 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
699 BOOL bSuccess = FALSE;
700 LPWININETHTTPREQW lpwhr;
702 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
707 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
708 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
710 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
713 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
716 WININET_Release( &lpwhr->hdr );
721 /***********************************************************************
722 * HttpAddRequestHeadersA (WININET.@)
724 * Adds one or more HTTP header to the request handler
731 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
732 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
738 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
740 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
741 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
742 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
743 if( dwHeaderLength != ~0U )
744 dwHeaderLength = len;
746 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
748 HeapFree( GetProcessHeap(), 0, hdr );
753 /***********************************************************************
754 * HttpEndRequestA (WININET.@)
756 * Ends an HTTP request that was started by HttpSendRequestEx
763 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
764 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
766 LPINTERNET_BUFFERSA ptr;
767 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
770 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
775 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
776 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
778 lpBuffersOutW = NULL;
780 ptrW = lpBuffersOutW;
783 if (ptr->lpvBuffer && ptr->dwBufferLength)
784 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
785 ptrW->dwBufferLength = ptr->dwBufferLength;
786 ptrW->dwBufferTotal= ptr->dwBufferTotal;
789 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
790 sizeof(INTERNET_BUFFERSW));
796 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
800 ptrW = lpBuffersOutW;
803 LPINTERNET_BUFFERSW ptrW2;
805 FIXME("Do we need to translate info out of these buffer?\n");
807 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
809 HeapFree(GetProcessHeap(),0,ptrW);
817 /***********************************************************************
818 * HttpEndRequestW (WININET.@)
820 * Ends an HTTP request that was started by HttpSendRequestEx
827 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
828 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
831 LPWININETHTTPREQW lpwhr;
836 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
838 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
840 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
842 WININET_Release( &lpwhr->hdr );
846 lpwhr->hdr.dwFlags |= dwFlags;
847 lpwhr->hdr.dwContext = dwContext;
849 /* We appear to do nothing with lpBuffersOut.. is that correct? */
851 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
852 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
854 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
858 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
859 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
861 /* process cookies here. Is this right? */
862 HTTP_ProcessCookies(lpwhr);
864 dwBufferSize = sizeof(lpwhr->dwContentLength);
865 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
866 &lpwhr->dwContentLength,&dwBufferSize,NULL))
867 lpwhr->dwContentLength = -1;
869 if (lpwhr->dwContentLength == 0)
870 HTTP_FinishedReading(lpwhr);
872 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
874 DWORD dwCode,dwCodeLength=sizeof(DWORD);
875 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
876 (dwCode==302 || dwCode==301))
878 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
879 dwBufferSize=sizeof(szNewLocation);
880 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
882 /* redirects are always GETs */
883 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
884 lpwhr->lpszVerb = WININET_strdupW(szGET);
885 HTTP_DrainContent(lpwhr);
886 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
887 INTERNET_STATUS_REDIRECT, szNewLocation,
889 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
891 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
896 WININET_Release( &lpwhr->hdr );
897 TRACE("%i <--\n",rc);
901 /***********************************************************************
902 * HttpOpenRequestW (WININET.@)
904 * Open a HTTP request handle
907 * HINTERNET a HTTP request handle on success
911 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
912 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
913 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
914 DWORD dwFlags, DWORD_PTR dwContext)
916 LPWININETHTTPSESSIONW lpwhs;
917 HINTERNET handle = NULL;
919 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
920 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
921 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
923 if(lpszAcceptTypes!=NULL)
926 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
927 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
930 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
931 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
933 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
938 * My tests seem to show that the windows version does not
939 * become asynchronous until after this point. And anyhow
940 * if this call was asynchronous then how would you get the
941 * necessary HINTERNET pointer returned by this function.
944 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
945 lpszVersion, lpszReferrer, lpszAcceptTypes,
949 WININET_Release( &lpwhs->hdr );
950 TRACE("returning %p\n", handle);
955 /***********************************************************************
956 * HttpOpenRequestA (WININET.@)
958 * Open a HTTP request handle
961 * HINTERNET a HTTP request handle on success
965 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
966 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
967 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
968 DWORD dwFlags, DWORD_PTR dwContext)
970 LPWSTR szVerb = NULL, szObjectName = NULL;
971 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
972 INT len, acceptTypesCount;
973 HINTERNET rc = FALSE;
976 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
977 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
978 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
983 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
984 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
987 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
992 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
993 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
996 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
1001 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
1002 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1005 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
1010 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1011 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1014 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1017 if (lpszAcceptTypes)
1019 acceptTypesCount = 0;
1020 types = lpszAcceptTypes;
1023 /* find out how many there are */
1024 if (((ULONG_PTR)*types >> 16) && **types)
1026 TRACE("accept type: %s\n", debugstr_a(*types));
1031 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1032 if (!szAcceptTypes) goto end;
1034 acceptTypesCount = 0;
1035 types = lpszAcceptTypes;
1038 if (((ULONG_PTR)*types >> 16) && **types)
1040 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1041 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1042 if (!szAcceptTypes[acceptTypesCount]) goto end;
1044 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1049 szAcceptTypes[acceptTypesCount] = NULL;
1051 else szAcceptTypes = 0;
1053 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1054 szVersion, szReferrer,
1055 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1060 acceptTypesCount = 0;
1061 while (szAcceptTypes[acceptTypesCount])
1063 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1066 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1068 HeapFree(GetProcessHeap(), 0, szReferrer);
1069 HeapFree(GetProcessHeap(), 0, szVersion);
1070 HeapFree(GetProcessHeap(), 0, szObjectName);
1071 HeapFree(GetProcessHeap(), 0, szVerb);
1076 /***********************************************************************
1079 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1082 static const CHAR HTTP_Base64Enc[] =
1083 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1087 /* first 6 bits, all from bin[0] */
1088 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1089 x = (bin[0] & 3) << 4;
1091 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1094 base64[n++] = HTTP_Base64Enc[x];
1099 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1100 x = ( bin[1] & 0x0f ) << 2;
1102 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1105 base64[n++] = HTTP_Base64Enc[x];
1109 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1111 /* last 6 bits, all from bin [2] */
1112 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1120 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1121 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1122 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1123 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1124 static const signed char HTTP_Base64Dec[256] =
1126 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1127 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1128 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1129 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1130 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1131 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1132 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1133 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1134 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1135 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1136 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1137 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1138 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1139 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1140 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1141 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1142 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1143 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1144 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1145 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1146 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1147 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1148 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1149 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1150 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1151 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1155 /***********************************************************************
1158 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1166 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1167 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1168 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1169 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1171 WARN("invalid base64: %s\n", debugstr_w(base64));
1175 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1178 if ((base64[2] == '=') && (base64[3] == '='))
1180 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1181 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1183 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1187 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1190 if (base64[3] == '=')
1192 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1193 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1195 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1199 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1208 /***********************************************************************
1209 * HTTP_InsertAuthorization
1211 * Insert or delete the authorization field in the request header.
1213 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1217 static const WCHAR wszSpace[] = {' ',0};
1218 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1220 WCHAR *authorization = NULL;
1222 if (pAuthInfo->auth_data_len)
1224 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1225 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1226 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1230 strcpyW(authorization, pAuthInfo->scheme);
1231 strcatW(authorization, wszSpace);
1232 HTTP_EncodeBase64(pAuthInfo->auth_data,
1233 pAuthInfo->auth_data_len,
1234 authorization+strlenW(authorization));
1236 /* clear the data as it isn't valid now that it has been sent to the
1237 * server, unless it's Basic authentication which doesn't do
1238 * connection tracking */
1239 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1241 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1242 pAuthInfo->auth_data = NULL;
1243 pAuthInfo->auth_data_len = 0;
1247 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1249 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1251 HeapFree(GetProcessHeap(), 0, authorization);
1256 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1258 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1261 size = sizeof(new_location);
1262 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1264 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1265 strcpyW( url, new_location );
1269 static const WCHAR slash[] = { '/',0 };
1270 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1271 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1272 WININETHTTPSESSIONW *session = req->lpHttpSession;
1274 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1275 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1277 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1279 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1280 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1282 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1283 if (req->lpszPath[0] != '/') strcatW( url, slash );
1284 strcatW( url, req->lpszPath );
1286 TRACE("url=%s\n", debugstr_w(url));
1290 /***********************************************************************
1291 * HTTP_DealWithProxy
1293 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1294 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1296 WCHAR buf[MAXHOSTNAME];
1297 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1298 static WCHAR szNul[] = { 0 };
1299 URL_COMPONENTSW UrlComponents;
1300 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1301 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1303 memset( &UrlComponents, 0, sizeof UrlComponents );
1304 UrlComponents.dwStructSize = sizeof UrlComponents;
1305 UrlComponents.lpszHostName = buf;
1306 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1308 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1309 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1310 sprintfW(proxy, szFormat, hIC->lpszProxy);
1312 strcpyW(proxy, hIC->lpszProxy);
1313 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1315 if( UrlComponents.dwHostNameLength == 0 )
1318 if( !lpwhr->lpszPath )
1319 lpwhr->lpszPath = szNul;
1321 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1322 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1324 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1325 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1326 lpwhs->nServerPort = UrlComponents.nPort;
1328 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1332 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1335 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1337 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1338 INTERNET_STATUS_RESOLVING_NAME,
1339 lpwhs->lpszServerName,
1340 strlenW(lpwhs->lpszServerName)+1);
1342 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1343 &lpwhs->socketAddress))
1345 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1349 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1350 szaddr, sizeof(szaddr));
1351 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1352 INTERNET_STATUS_NAME_RESOLVED,
1353 szaddr, strlen(szaddr)+1);
1355 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1360 /***********************************************************************
1361 * HTTPREQ_Destroy (internal)
1363 * Deallocate request handle
1366 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1368 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1373 if(lpwhr->hCacheFile)
1374 CloseHandle(lpwhr->hCacheFile);
1376 if(lpwhr->lpszCacheFile) {
1377 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1378 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1381 WININET_Release(&lpwhr->lpHttpSession->hdr);
1383 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1384 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1385 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1386 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1387 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1389 for (i = 0; i < lpwhr->nCustHeaders; i++)
1391 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1392 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1395 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1396 HeapFree(GetProcessHeap(), 0, lpwhr);
1399 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1401 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1403 TRACE("%p\n",lpwhr);
1405 if (!NETCON_connected(&lpwhr->netConnection))
1408 if (lpwhr->pAuthInfo)
1410 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1411 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1412 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1413 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1415 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1416 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1417 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1418 lpwhr->pAuthInfo = NULL;
1420 if (lpwhr->pProxyAuthInfo)
1422 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1423 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1424 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1425 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1427 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1428 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1429 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1430 lpwhr->pProxyAuthInfo = NULL;
1433 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1434 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1436 NETCON_close(&lpwhr->netConnection);
1438 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1439 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1442 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1444 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1447 case INTERNET_OPTION_HANDLE_TYPE:
1448 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1450 if (*size < sizeof(ULONG))
1451 return ERROR_INSUFFICIENT_BUFFER;
1453 *size = sizeof(DWORD);
1454 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1455 return ERROR_SUCCESS;
1457 case INTERNET_OPTION_URL: {
1458 WCHAR url[INTERNET_MAX_URL_LENGTH];
1463 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1464 static const WCHAR hostW[] = {'H','o','s','t',0};
1466 TRACE("INTERNET_OPTION_URL\n");
1468 host = HTTP_GetHeader(req, hostW);
1469 strcpyW(url, httpW);
1470 strcatW(url, host->lpszValue);
1471 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1473 strcatW(url, req->lpszPath);
1475 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1478 len = (strlenW(url)+1) * sizeof(WCHAR);
1480 return ERROR_INSUFFICIENT_BUFFER;
1483 strcpyW(buffer, url);
1484 return ERROR_SUCCESS;
1486 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1488 return ERROR_INSUFFICIENT_BUFFER;
1491 return ERROR_SUCCESS;
1495 case INTERNET_OPTION_DATAFILE_NAME: {
1498 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1500 if(!req->lpszCacheFile) {
1502 return ERROR_INTERNET_ITEM_NOT_FOUND;
1506 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1507 if(*size < req_size)
1508 return ERROR_INSUFFICIENT_BUFFER;
1511 memcpy(buffer, req->lpszCacheFile, *size);
1512 return ERROR_SUCCESS;
1514 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1515 if (req_size > *size)
1516 return ERROR_INSUFFICIENT_BUFFER;
1518 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1519 -1, buffer, *size, NULL, NULL);
1520 return ERROR_SUCCESS;
1524 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1525 PCCERT_CONTEXT context;
1527 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1528 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1529 return ERROR_INSUFFICIENT_BUFFER;
1532 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1534 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1537 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1538 info->ftExpiry = context->pCertInfo->NotAfter;
1539 info->ftStart = context->pCertInfo->NotBefore;
1541 len = CertNameToStrW(context->dwCertEncodingType,
1542 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1543 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1544 if(info->lpszSubjectInfo)
1545 CertNameToStrW(context->dwCertEncodingType,
1546 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1547 info->lpszSubjectInfo, len);
1548 len = CertNameToStrW(context->dwCertEncodingType,
1549 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1550 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1551 if (info->lpszIssuerInfo)
1552 CertNameToStrW(context->dwCertEncodingType,
1553 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1554 info->lpszIssuerInfo, len);
1556 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1558 len = CertNameToStrA(context->dwCertEncodingType,
1559 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1560 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1561 if(infoA->lpszSubjectInfo)
1562 CertNameToStrA(context->dwCertEncodingType,
1563 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1564 infoA->lpszSubjectInfo, len);
1565 len = CertNameToStrA(context->dwCertEncodingType,
1566 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1567 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1568 if(infoA->lpszIssuerInfo)
1569 CertNameToStrA(context->dwCertEncodingType,
1570 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1571 infoA->lpszIssuerInfo, len);
1575 * Contrary to MSDN, these do not appear to be set.
1577 * lpszSignatureAlgName
1578 * lpszEncryptionAlgName
1581 CertFreeCertificateContext(context);
1582 return ERROR_SUCCESS;
1587 return INET_QueryOption(option, buffer, size, unicode);
1590 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1592 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1595 case INTERNET_OPTION_SEND_TIMEOUT:
1596 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1597 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1599 if (size != sizeof(DWORD))
1600 return ERROR_INVALID_PARAMETER;
1602 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1606 return ERROR_INTERNET_INVALID_OPTION;
1609 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1613 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1614 sync ? MSG_WAITALL : 0, &bytes_read)) {
1615 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1616 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1618 /* always return success, even if the network layer returns an error */
1620 HTTP_FinishedReading(req);
1621 return ERROR_SUCCESS;
1624 req->dwContentRead += bytes_read;
1627 if(req->lpszCacheFile) {
1629 DWORD dwBytesWritten;
1631 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1633 WARN("WriteFile failed: %u\n", GetLastError());
1636 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1637 HTTP_FinishedReading(req);
1639 return ERROR_SUCCESS;
1642 static DWORD get_chunk_size(const char *buffer)
1647 for (p = buffer; *p; p++)
1649 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1650 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1651 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1652 else if (*p == ';') break;
1657 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1659 char reply[MAX_REPLY_LEN], *p = buffer;
1660 DWORD buflen, to_read, to_write = size;
1666 if (*read == size) break;
1668 if (req->dwContentLength == ~0UL) /* new chunk */
1670 buflen = sizeof(reply);
1671 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1673 if (!(req->dwContentLength = get_chunk_size(reply)))
1675 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1676 HTTP_GetResponseHeaders(req, FALSE);
1680 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1682 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1684 if (bytes_read != to_read)
1685 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1687 /* always return success, even if the network layer returns an error */
1691 if (!bytes_read) break;
1693 req->dwContentRead += bytes_read;
1694 to_write -= bytes_read;
1695 *read += bytes_read;
1697 if (req->lpszCacheFile)
1699 DWORD dwBytesWritten;
1701 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1702 WARN("WriteFile failed: %u\n", GetLastError());
1706 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1708 req->dwContentRead = 0;
1709 req->dwContentLength = ~0UL;
1711 buflen = sizeof(reply);
1712 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1714 ERR("Malformed chunk\n");
1720 if (!*read) HTTP_FinishedReading(req);
1721 return ERROR_SUCCESS;
1724 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1727 DWORD buflen = sizeof(encoding);
1728 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1730 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1731 !strcmpiW(encoding, szChunked))
1733 return HTTP_ReadChunked(req, buffer, size, read, sync);
1736 return HTTP_Read(req, buffer, size, read, sync);
1739 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1741 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1742 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1745 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1747 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1748 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1749 INTERNET_ASYNC_RESULT iar;
1752 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1754 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1755 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1757 iar.dwResult = res == ERROR_SUCCESS;
1760 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1761 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1762 sizeof(INTERNET_ASYNC_RESULT));
1765 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1766 DWORD flags, DWORD_PTR context)
1769 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1772 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1773 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1775 if (buffers->dwStructSize != sizeof(*buffers))
1776 return ERROR_INVALID_PARAMETER;
1778 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1780 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1781 DWORD available = 0;
1783 NETCON_query_data_available(&req->netConnection, &available);
1786 WORKREQUEST workRequest;
1788 workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1789 workRequest.hdr = WININET_AddRef(&req->hdr);
1790 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1792 INTERNET_AsyncCall(&workRequest);
1794 return ERROR_IO_PENDING;
1798 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1799 !(flags & IRF_NO_WAIT));
1801 if (res == ERROR_SUCCESS) {
1802 DWORD size = buffers->dwBufferLength;
1803 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1804 &size, sizeof(size));
1810 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1812 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1814 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1817 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1819 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1820 INTERNET_ASYNC_RESULT iar;
1823 TRACE("%p\n", workRequest->hdr);
1825 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1826 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1827 MSG_PEEK, (int *)&iar.dwError);
1829 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1830 sizeof(INTERNET_ASYNC_RESULT));
1833 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1835 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1839 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1841 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1842 return ERROR_SUCCESS;
1844 /* Even if we are in async mode, we need to determine whether
1845 * there is actually more data available. We do this by trying
1846 * to peek only a single byte in async mode. */
1847 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1849 if (NETCON_recv(&req->netConnection, buffer,
1850 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1851 MSG_PEEK, (int *)available) && async && *available)
1853 WORKREQUEST workRequest;
1856 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1857 workRequest.hdr = WININET_AddRef( &req->hdr );
1859 INTERNET_AsyncCall(&workRequest);
1861 return ERROR_IO_PENDING;
1864 return ERROR_SUCCESS;
1867 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1869 HTTPREQ_CloseConnection,
1870 HTTPREQ_QueryOption,
1873 HTTPREQ_ReadFileExA,
1875 HTTPREQ_QueryDataAvailable,
1879 /***********************************************************************
1880 * HTTP_HttpOpenRequestW (internal)
1882 * Open a HTTP request handle
1885 * HINTERNET a HTTP request handle on success
1889 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1890 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1891 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1892 DWORD dwFlags, DWORD_PTR dwContext)
1894 LPWININETAPPINFOW hIC = NULL;
1895 LPWININETHTTPREQW lpwhr;
1896 LPWSTR lpszHostName = NULL;
1897 HINTERNET handle = NULL;
1898 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1903 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1904 hIC = lpwhs->lpAppInfo;
1906 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1909 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1912 lpwhr->hdr.htype = WH_HHTTPREQ;
1913 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1914 lpwhr->hdr.dwFlags = dwFlags;
1915 lpwhr->hdr.dwContext = dwContext;
1916 lpwhr->hdr.refs = 1;
1917 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1918 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1920 WININET_AddRef( &lpwhs->hdr );
1921 lpwhr->lpHttpSession = lpwhs;
1922 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1924 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
1925 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
1926 if (NULL == lpszHostName)
1928 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1932 handle = WININET_AllocHandle( &lpwhr->hdr );
1935 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1939 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1941 InternetCloseHandle( handle );
1946 if (lpszObjectName && *lpszObjectName) {
1950 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1951 if (rc != E_POINTER)
1952 len = strlenW(lpszObjectName)+1;
1953 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1954 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1955 URL_ESCAPE_SPACES_ONLY);
1958 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1959 strcpyW(lpwhr->lpszPath,lpszObjectName);
1963 if (lpszReferrer && *lpszReferrer)
1964 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1966 if (lpszAcceptTypes)
1969 for (i = 0; lpszAcceptTypes[i]; i++)
1971 if (!*lpszAcceptTypes[i]) continue;
1972 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1973 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1974 HTTP_ADDHDR_FLAG_REQ |
1975 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1979 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1982 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1984 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1986 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
1987 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
1988 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
1990 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
1991 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
1992 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1995 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
1996 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1998 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1999 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2000 INTERNET_DEFAULT_HTTPS_PORT :
2001 INTERNET_DEFAULT_HTTP_PORT);
2003 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2004 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2005 INTERNET_DEFAULT_HTTPS_PORT :
2006 INTERNET_DEFAULT_HTTP_PORT);
2008 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2009 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2011 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2012 INTERNET_STATUS_HANDLE_CREATED, &handle,
2016 HeapFree(GetProcessHeap(), 0, lpszHostName);
2018 WININET_Release( &lpwhr->hdr );
2020 TRACE("<-- %p (%p)\n", handle, lpwhr);
2024 /* read any content returned by the server so that the connection can be
2026 static void HTTP_DrainContent(WININETHTTPREQW *req)
2030 if (!NETCON_connected(&req->netConnection)) return;
2032 if (req->dwContentLength == -1)
2033 NETCON_close(&req->netConnection);
2038 if (HTTP_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2040 } while (bytes_read);
2043 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2044 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2045 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2046 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2047 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2048 static const WCHAR szAge[] = { 'A','g','e',0 };
2049 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2050 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2051 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2052 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2053 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2054 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2055 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2056 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2057 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2058 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2059 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2060 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 };
2061 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2062 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2063 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2064 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2065 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2066 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2067 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2068 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2069 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2070 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2071 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2072 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2073 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2074 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2075 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2076 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2077 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2078 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2079 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2080 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2081 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2082 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2083 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2084 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2085 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2086 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2087 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 };
2088 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2089 static const WCHAR szURI[] = { 'U','R','I',0 };
2090 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2091 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2092 static const WCHAR szVia[] = { 'V','i','a',0 };
2093 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2094 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2096 static const LPCWSTR header_lookup[] = {
2097 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2098 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2099 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2100 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2101 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2102 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2103 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2104 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2105 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2106 szDate, /* HTTP_QUERY_DATE = 9 */
2107 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2108 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2109 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2110 szURI, /* HTTP_QUERY_URI = 13 */
2111 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2112 NULL, /* HTTP_QUERY_COST = 15 */
2113 NULL, /* HTTP_QUERY_LINK = 16 */
2114 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2115 NULL, /* HTTP_QUERY_VERSION = 18 */
2116 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2117 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2118 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2119 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2120 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2121 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2122 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2123 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2124 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2125 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2126 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2127 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2128 NULL, /* HTTP_QUERY_FROM = 31 */
2129 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2130 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2131 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2132 szReferer, /* HTTP_QUERY_REFERER = 35 */
2133 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2134 szServer, /* HTTP_QUERY_SERVER = 37 */
2135 NULL, /* HTTP_TITLE = 38 */
2136 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2137 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2138 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2139 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2140 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2141 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2142 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2143 NULL, /* HTTP_QUERY_REFRESH = 46 */
2144 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2145 szAge, /* HTTP_QUERY_AGE = 48 */
2146 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2147 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2148 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2149 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2150 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2151 szETag, /* HTTP_QUERY_ETAG = 54 */
2152 szHost, /* HTTP_QUERY_HOST = 55 */
2153 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2154 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2155 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2156 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2157 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2158 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2159 szRange, /* HTTP_QUERY_RANGE = 62 */
2160 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2161 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2162 szVary, /* HTTP_QUERY_VARY = 65 */
2163 szVia, /* HTTP_QUERY_VIA = 66 */
2164 szWarning, /* HTTP_QUERY_WARNING = 67 */
2165 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2166 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2167 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2170 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2172 /***********************************************************************
2173 * HTTP_HttpQueryInfoW (internal)
2175 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2176 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2178 LPHTTPHEADERW lphttpHdr = NULL;
2179 BOOL bSuccess = FALSE;
2180 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2181 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2182 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2185 /* Find requested header structure */
2188 case HTTP_QUERY_CUSTOM:
2189 if (!lpBuffer) return FALSE;
2190 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2193 case HTTP_QUERY_RAW_HEADERS_CRLF:
2200 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2202 headers = lpwhr->lpszRawHeaders;
2205 len = strlenW(headers) * sizeof(WCHAR);
2207 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2209 len += sizeof(WCHAR);
2210 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2216 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2219 len = strlenW(szCrLf) * sizeof(WCHAR);
2220 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2222 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2225 *lpdwBufferLength = len;
2228 HeapFree(GetProcessHeap(), 0, headers);
2231 case HTTP_QUERY_RAW_HEADERS:
2233 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2235 LPWSTR pszString = lpBuffer;
2237 for (i = 0; ppszRawHeaderLines[i]; i++)
2238 size += strlenW(ppszRawHeaderLines[i]) + 1;
2240 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2242 HTTP_FreeTokens(ppszRawHeaderLines);
2243 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2244 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2249 for (i = 0; ppszRawHeaderLines[i]; i++)
2251 DWORD len = strlenW(ppszRawHeaderLines[i]);
2252 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2256 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2258 *lpdwBufferLength = size * sizeof(WCHAR);
2259 HTTP_FreeTokens(ppszRawHeaderLines);
2263 case HTTP_QUERY_STATUS_TEXT:
2264 if (lpwhr->lpszStatusText)
2266 DWORD len = strlenW(lpwhr->lpszStatusText);
2267 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2269 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2270 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2275 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2276 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2278 *lpdwBufferLength = len * sizeof(WCHAR);
2282 case HTTP_QUERY_VERSION:
2283 if (lpwhr->lpszVersion)
2285 DWORD len = strlenW(lpwhr->lpszVersion);
2286 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2288 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2289 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2294 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2295 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2297 *lpdwBufferLength = len * sizeof(WCHAR);
2302 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2304 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
2305 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2306 requested_index,request_only);
2310 lphttpHdr = &lpwhr->pCustHeaders[index];
2312 /* Ensure header satisfies requested attributes */
2314 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2315 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2317 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2324 /* coalesce value to requested type */
2325 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2327 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2328 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2331 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2337 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2339 tmpTM = *gmtime(&tmpTime);
2340 STHook = (SYSTEMTIME *)lpBuffer;
2341 if (!STHook) return bSuccess;
2343 STHook->wDay = tmpTM.tm_mday;
2344 STHook->wHour = tmpTM.tm_hour;
2345 STHook->wMilliseconds = 0;
2346 STHook->wMinute = tmpTM.tm_min;
2347 STHook->wDayOfWeek = tmpTM.tm_wday;
2348 STHook->wMonth = tmpTM.tm_mon + 1;
2349 STHook->wSecond = tmpTM.tm_sec;
2350 STHook->wYear = tmpTM.tm_year;
2353 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2354 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2355 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2357 else if (lphttpHdr->lpszValue)
2359 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2361 if (len > *lpdwBufferLength)
2363 *lpdwBufferLength = len;
2364 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2369 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2370 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2372 *lpdwBufferLength = len - sizeof(WCHAR);
2378 /***********************************************************************
2379 * HttpQueryInfoW (WININET.@)
2381 * Queries for information about an HTTP request
2388 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2389 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2391 BOOL bSuccess = FALSE;
2392 LPWININETHTTPREQW lpwhr;
2394 if (TRACE_ON(wininet)) {
2395 #define FE(x) { x, #x }
2396 static const wininet_flag_info query_flags[] = {
2397 FE(HTTP_QUERY_MIME_VERSION),
2398 FE(HTTP_QUERY_CONTENT_TYPE),
2399 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2400 FE(HTTP_QUERY_CONTENT_ID),
2401 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2402 FE(HTTP_QUERY_CONTENT_LENGTH),
2403 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2404 FE(HTTP_QUERY_ALLOW),
2405 FE(HTTP_QUERY_PUBLIC),
2406 FE(HTTP_QUERY_DATE),
2407 FE(HTTP_QUERY_EXPIRES),
2408 FE(HTTP_QUERY_LAST_MODIFIED),
2409 FE(HTTP_QUERY_MESSAGE_ID),
2411 FE(HTTP_QUERY_DERIVED_FROM),
2412 FE(HTTP_QUERY_COST),
2413 FE(HTTP_QUERY_LINK),
2414 FE(HTTP_QUERY_PRAGMA),
2415 FE(HTTP_QUERY_VERSION),
2416 FE(HTTP_QUERY_STATUS_CODE),
2417 FE(HTTP_QUERY_STATUS_TEXT),
2418 FE(HTTP_QUERY_RAW_HEADERS),
2419 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2420 FE(HTTP_QUERY_CONNECTION),
2421 FE(HTTP_QUERY_ACCEPT),
2422 FE(HTTP_QUERY_ACCEPT_CHARSET),
2423 FE(HTTP_QUERY_ACCEPT_ENCODING),
2424 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2425 FE(HTTP_QUERY_AUTHORIZATION),
2426 FE(HTTP_QUERY_CONTENT_ENCODING),
2427 FE(HTTP_QUERY_FORWARDED),
2428 FE(HTTP_QUERY_FROM),
2429 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2430 FE(HTTP_QUERY_LOCATION),
2431 FE(HTTP_QUERY_ORIG_URI),
2432 FE(HTTP_QUERY_REFERER),
2433 FE(HTTP_QUERY_RETRY_AFTER),
2434 FE(HTTP_QUERY_SERVER),
2435 FE(HTTP_QUERY_TITLE),
2436 FE(HTTP_QUERY_USER_AGENT),
2437 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2438 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2439 FE(HTTP_QUERY_ACCEPT_RANGES),
2440 FE(HTTP_QUERY_SET_COOKIE),
2441 FE(HTTP_QUERY_COOKIE),
2442 FE(HTTP_QUERY_REQUEST_METHOD),
2443 FE(HTTP_QUERY_REFRESH),
2444 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2446 FE(HTTP_QUERY_CACHE_CONTROL),
2447 FE(HTTP_QUERY_CONTENT_BASE),
2448 FE(HTTP_QUERY_CONTENT_LOCATION),
2449 FE(HTTP_QUERY_CONTENT_MD5),
2450 FE(HTTP_QUERY_CONTENT_RANGE),
2451 FE(HTTP_QUERY_ETAG),
2452 FE(HTTP_QUERY_HOST),
2453 FE(HTTP_QUERY_IF_MATCH),
2454 FE(HTTP_QUERY_IF_NONE_MATCH),
2455 FE(HTTP_QUERY_IF_RANGE),
2456 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2457 FE(HTTP_QUERY_MAX_FORWARDS),
2458 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2459 FE(HTTP_QUERY_RANGE),
2460 FE(HTTP_QUERY_TRANSFER_ENCODING),
2461 FE(HTTP_QUERY_UPGRADE),
2462 FE(HTTP_QUERY_VARY),
2464 FE(HTTP_QUERY_WARNING),
2465 FE(HTTP_QUERY_CUSTOM)
2467 static const wininet_flag_info modifier_flags[] = {
2468 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2469 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2470 FE(HTTP_QUERY_FLAG_NUMBER),
2471 FE(HTTP_QUERY_FLAG_COALESCE)
2474 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2475 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2478 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2479 TRACE(" Attribute:");
2480 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2481 if (query_flags[i].val == info) {
2482 TRACE(" %s", query_flags[i].name);
2486 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2487 TRACE(" Unknown (%08x)", info);
2490 TRACE(" Modifier:");
2491 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2492 if (modifier_flags[i].val & info_mod) {
2493 TRACE(" %s", modifier_flags[i].name);
2494 info_mod &= ~ modifier_flags[i].val;
2499 TRACE(" Unknown (%08x)", info_mod);
2504 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2505 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2507 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2511 if (lpBuffer == NULL)
2512 *lpdwBufferLength = 0;
2513 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2514 lpBuffer, lpdwBufferLength, lpdwIndex);
2518 WININET_Release( &lpwhr->hdr );
2520 TRACE("%d <--\n", bSuccess);
2524 /***********************************************************************
2525 * HttpQueryInfoA (WININET.@)
2527 * Queries for information about an HTTP request
2534 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2535 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2541 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2542 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2544 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2545 lpdwBufferLength, lpdwIndex );
2551 len = (*lpdwBufferLength)*sizeof(WCHAR);
2552 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2554 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2560 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2561 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2562 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2563 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2570 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2574 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2575 lpBuffer, *lpdwBufferLength, NULL, NULL );
2576 *lpdwBufferLength = len - 1;
2578 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2581 /* since the strings being returned from HttpQueryInfoW should be
2582 * only ASCII characters, it is reasonable to assume that all of
2583 * the Unicode characters can be reduced to a single byte */
2584 *lpdwBufferLength = len / sizeof(WCHAR);
2586 HeapFree(GetProcessHeap(), 0, bufferW );
2591 /***********************************************************************
2592 * HttpSendRequestExA (WININET.@)
2594 * Sends the specified request to the HTTP server and allows chunked
2599 * Failure: FALSE, call GetLastError() for more information.
2601 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2602 LPINTERNET_BUFFERSA lpBuffersIn,
2603 LPINTERNET_BUFFERSA lpBuffersOut,
2604 DWORD dwFlags, DWORD_PTR dwContext)
2606 INTERNET_BUFFERSW BuffersInW;
2609 LPWSTR header = NULL;
2611 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2612 lpBuffersOut, dwFlags, dwContext);
2616 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2617 if (lpBuffersIn->lpcszHeader)
2619 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2620 lpBuffersIn->dwHeadersLength,0,0);
2621 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2622 if (!(BuffersInW.lpcszHeader = header))
2624 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2627 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2628 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2632 BuffersInW.lpcszHeader = NULL;
2633 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2634 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2635 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2636 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2637 BuffersInW.Next = NULL;
2640 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2642 HeapFree(GetProcessHeap(),0,header);
2647 /***********************************************************************
2648 * HttpSendRequestExW (WININET.@)
2650 * Sends the specified request to the HTTP server and allows chunked
2655 * Failure: FALSE, call GetLastError() for more information.
2657 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2658 LPINTERNET_BUFFERSW lpBuffersIn,
2659 LPINTERNET_BUFFERSW lpBuffersOut,
2660 DWORD dwFlags, DWORD_PTR dwContext)
2663 LPWININETHTTPREQW lpwhr;
2664 LPWININETHTTPSESSIONW lpwhs;
2665 LPWININETAPPINFOW hIC;
2667 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2668 lpBuffersOut, dwFlags, dwContext);
2670 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2672 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2674 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2678 lpwhs = lpwhr->lpHttpSession;
2679 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2680 hIC = lpwhs->lpAppInfo;
2681 assert(hIC->hdr.htype == WH_HINIT);
2683 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2685 WORKREQUEST workRequest;
2686 struct WORKREQ_HTTPSENDREQUESTW *req;
2688 workRequest.asyncproc = AsyncHttpSendRequestProc;
2689 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2690 req = &workRequest.u.HttpSendRequestW;
2693 if (lpBuffersIn->lpcszHeader)
2694 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2695 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2697 req->lpszHeader = NULL;
2698 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2699 req->lpOptional = lpBuffersIn->lpvBuffer;
2700 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2701 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2705 req->lpszHeader = NULL;
2706 req->dwHeaderLength = 0;
2707 req->lpOptional = NULL;
2708 req->dwOptionalLength = 0;
2709 req->dwContentLength = 0;
2712 req->bEndRequest = FALSE;
2714 INTERNET_AsyncCall(&workRequest);
2716 * This is from windows.
2718 INTERNET_SetLastError(ERROR_IO_PENDING);
2723 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2724 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2725 lpBuffersIn->dwBufferTotal, FALSE);
2727 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2732 WININET_Release( &lpwhr->hdr );
2738 /***********************************************************************
2739 * HttpSendRequestW (WININET.@)
2741 * Sends the specified request to the HTTP server
2748 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2749 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2751 LPWININETHTTPREQW lpwhr;
2752 LPWININETHTTPSESSIONW lpwhs = NULL;
2753 LPWININETAPPINFOW hIC = NULL;
2756 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2757 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2759 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2760 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2762 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2767 lpwhs = lpwhr->lpHttpSession;
2768 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2770 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2775 hIC = lpwhs->lpAppInfo;
2776 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2778 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2783 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2785 WORKREQUEST workRequest;
2786 struct WORKREQ_HTTPSENDREQUESTW *req;
2788 workRequest.asyncproc = AsyncHttpSendRequestProc;
2789 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2790 req = &workRequest.u.HttpSendRequestW;
2793 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2794 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2797 req->lpszHeader = 0;
2798 req->dwHeaderLength = dwHeaderLength;
2799 req->lpOptional = lpOptional;
2800 req->dwOptionalLength = dwOptionalLength;
2801 req->dwContentLength = dwOptionalLength;
2802 req->bEndRequest = TRUE;
2804 INTERNET_AsyncCall(&workRequest);
2806 * This is from windows.
2808 INTERNET_SetLastError(ERROR_IO_PENDING);
2813 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2814 dwHeaderLength, lpOptional, dwOptionalLength,
2815 dwOptionalLength, TRUE);
2819 WININET_Release( &lpwhr->hdr );
2823 /***********************************************************************
2824 * HttpSendRequestA (WININET.@)
2826 * Sends the specified request to the HTTP server
2833 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2834 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2837 LPWSTR szHeaders=NULL;
2838 DWORD nLen=dwHeaderLength;
2839 if(lpszHeaders!=NULL)
2841 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2842 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2843 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2845 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2846 HeapFree(GetProcessHeap(),0,szHeaders);
2850 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2852 LPHTTPHEADERW host_header;
2854 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2856 host_header = HTTP_GetHeader(req, szHost);
2860 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2864 /***********************************************************************
2865 * HTTP_HandleRedirect (internal)
2867 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2869 static const WCHAR szContentType[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
2870 static const WCHAR szContentLength[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
2871 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2872 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2873 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2874 WCHAR path[INTERNET_MAX_URL_LENGTH];
2879 /* if it's an absolute path, keep the same session info */
2880 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2884 URL_COMPONENTSW urlComponents;
2885 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2886 static WCHAR szHttp[] = {'h','t','t','p',0};
2887 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2888 DWORD url_length = 0;
2890 LPWSTR combined_url;
2892 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2893 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2894 urlComponents.dwSchemeLength = 0;
2895 urlComponents.lpszHostName = lpwhs->lpszHostName;
2896 urlComponents.dwHostNameLength = 0;
2897 urlComponents.nPort = lpwhs->nHostPort;
2898 urlComponents.lpszUserName = lpwhs->lpszUserName;
2899 urlComponents.dwUserNameLength = 0;
2900 urlComponents.lpszPassword = NULL;
2901 urlComponents.dwPasswordLength = 0;
2902 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2903 urlComponents.dwUrlPathLength = 0;
2904 urlComponents.lpszExtraInfo = NULL;
2905 urlComponents.dwExtraInfoLength = 0;
2907 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2908 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2911 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2913 /* convert from bytes to characters */
2914 url_length = url_length / sizeof(WCHAR) - 1;
2915 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2917 HeapFree(GetProcessHeap(), 0, orig_url);
2922 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2923 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2925 HeapFree(GetProcessHeap(), 0, orig_url);
2928 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2930 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2932 HeapFree(GetProcessHeap(), 0, orig_url);
2933 HeapFree(GetProcessHeap(), 0, combined_url);
2936 HeapFree(GetProcessHeap(), 0, orig_url);
2942 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2943 urlComponents.lpszScheme = protocol;
2944 urlComponents.dwSchemeLength = 32;
2945 urlComponents.lpszHostName = hostName;
2946 urlComponents.dwHostNameLength = MAXHOSTNAME;
2947 urlComponents.lpszUserName = userName;
2948 urlComponents.dwUserNameLength = 1024;
2949 urlComponents.lpszPassword = NULL;
2950 urlComponents.dwPasswordLength = 0;
2951 urlComponents.lpszUrlPath = path;
2952 urlComponents.dwUrlPathLength = 2048;
2953 urlComponents.lpszExtraInfo = NULL;
2954 urlComponents.dwExtraInfoLength = 0;
2955 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2957 HeapFree(GetProcessHeap(), 0, combined_url);
2961 HeapFree(GetProcessHeap(), 0, combined_url);
2963 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2964 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2966 TRACE("redirect from secure page to non-secure page\n");
2967 /* FIXME: warn about from secure redirect to non-secure page */
2968 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2970 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2971 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2973 TRACE("redirect from non-secure page to secure page\n");
2974 /* FIXME: notify about redirect to secure page */
2975 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2978 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2980 if (lstrlenW(protocol)>4) /*https*/
2981 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2983 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2988 * This upsets redirects to binary files on sourceforge.net
2989 * and gives an html page instead of the target file
2990 * Examination of the HTTP request sent by native wininet.dll
2991 * reveals that it doesn't send a referrer in that case.
2992 * Maybe there's a flag that enables this, or maybe a referrer
2993 * shouldn't be added in case of a redirect.
2996 /* consider the current host as the referrer */
2997 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2998 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2999 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3000 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3003 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3004 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3005 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3008 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3009 len = lstrlenW(hostName);
3010 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3011 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3012 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3015 lpwhs->lpszHostName = WININET_strdupW(hostName);
3017 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3019 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3020 lpwhs->lpszUserName = NULL;
3022 lpwhs->lpszUserName = WININET_strdupW(userName);
3026 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3028 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3029 lpwhs->lpszServerName = WININET_strdupW(hostName);
3030 lpwhs->nServerPort = urlComponents.nPort;
3032 NETCON_close(&lpwhr->netConnection);
3033 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3034 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3038 TRACE("Redirect through proxy\n");
3041 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3042 lpwhr->lpszPath=NULL;
3048 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3049 if (rc != E_POINTER)
3050 needed = strlenW(path)+1;
3051 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3052 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3053 URL_ESCAPE_SPACES_ONLY);
3056 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3057 strcpyW(lpwhr->lpszPath,path);
3061 /* Remove custom content-type/length headers on redirects. */
3062 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentType, 0, TRUE);
3064 HTTP_DeleteCustomHeader(lpwhr, index);
3065 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentLength, 0, TRUE);
3067 HTTP_DeleteCustomHeader(lpwhr, index);
3072 /***********************************************************************
3073 * HTTP_build_req (internal)
3075 * concatenate all the strings in the request together
3077 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3082 for( t = list; *t ; t++ )
3083 len += strlenW( *t );
3086 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3089 for( t = list; *t ; t++ )
3095 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3098 LPWSTR requestString;
3104 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3105 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3106 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3110 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3111 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3112 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3113 HeapFree( GetProcessHeap(), 0, lpszPath );
3115 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3116 NULL, 0, NULL, NULL );
3117 len--; /* the nul terminator isn't needed */
3118 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3119 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3120 ascii_req, len, NULL, NULL );
3121 HeapFree( GetProcessHeap(), 0, requestString );
3123 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3125 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3126 HeapFree( GetProcessHeap(), 0, ascii_req );
3127 if (!ret || cnt < 0)
3130 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3137 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3139 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
3140 LPWSTR lpszCookies, lpszUrl = NULL;
3141 DWORD nCookieSize, size;
3142 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3144 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm)) * sizeof(WCHAR);
3145 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3146 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
3148 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3151 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3153 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3154 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3156 cnt += sprintfW(lpszCookies, szCookie);
3157 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3158 strcatW(lpszCookies, szCrLf);
3160 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_ADD);
3161 HeapFree(GetProcessHeap(), 0, lpszCookies);
3164 HeapFree(GetProcessHeap(), 0, lpszUrl);
3167 /***********************************************************************
3168 * HTTP_HttpSendRequestW (internal)
3170 * Sends the specified request to the HTTP server
3177 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3178 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3179 DWORD dwContentLength, BOOL bEndRequest)
3182 BOOL bSuccess = FALSE;
3183 LPWSTR requestString = NULL;
3186 INTERNET_ASYNC_RESULT iar;
3187 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3188 static const WCHAR szContentLength[] =
3189 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3190 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3192 TRACE("--> %p\n", lpwhr);
3194 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3196 /* if the verb is NULL default to GET */
3197 if (!lpwhr->lpszVerb)
3198 lpwhr->lpszVerb = WININET_strdupW(szGET);
3200 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
3202 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3203 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3205 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3207 WCHAR *agent_header;
3208 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3211 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3212 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3213 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3215 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3216 HeapFree(GetProcessHeap(), 0, agent_header);
3218 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3220 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3221 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3223 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3225 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3226 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3227 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3237 /* like native, just in case the caller forgot to call InternetReadFile
3238 * for all the data */
3239 HTTP_DrainContent(lpwhr);
3240 lpwhr->dwContentRead = 0;
3242 if (TRACE_ON(wininet))
3244 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3245 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3249 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3251 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3253 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3254 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3256 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3257 HTTP_InsertCookies(lpwhr);
3259 /* add the headers the caller supplied */
3260 if( lpszHeaders && dwHeaderLength )
3262 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3263 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3266 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3268 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3269 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3270 HeapFree(GetProcessHeap(), 0, url);
3273 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3276 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3278 /* Send the request and store the results */
3279 if (!HTTP_OpenConnection(lpwhr))
3282 /* send the request as ASCII, tack on the optional data */
3284 dwOptionalLength = 0;
3285 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3286 NULL, 0, NULL, NULL );
3287 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3288 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3289 ascii_req, len, NULL, NULL );
3291 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3292 len = (len + dwOptionalLength - 1);
3294 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3296 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3297 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3299 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3300 HeapFree( GetProcessHeap(), 0, ascii_req );
3302 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3303 INTERNET_STATUS_REQUEST_SENT,
3304 &len, sizeof(DWORD));
3311 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3313 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3314 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3319 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3323 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3324 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3327 HTTP_ProcessCookies(lpwhr);
3329 dwBufferSize = sizeof(lpwhr->dwContentLength);
3330 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3331 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3332 lpwhr->dwContentLength = -1;
3334 if (lpwhr->dwContentLength == 0)
3335 HTTP_FinishedReading(lpwhr);
3337 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3339 dwBufferSize = sizeof(encoding);
3340 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3341 !strcmpiW(encoding, szChunked))
3343 lpwhr->dwContentLength = -1;
3346 dwBufferSize = sizeof(dwStatusCode);
3347 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3348 &dwStatusCode,&dwBufferSize,NULL))
3351 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3353 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3354 dwBufferSize=sizeof(szNewLocation);
3355 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3356 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3358 HTTP_DrainContent(lpwhr);
3359 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3360 INTERNET_STATUS_REDIRECT, szNewLocation,
3362 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3365 HeapFree(GetProcessHeap(), 0, requestString);
3370 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3372 WCHAR szAuthValue[2048];
3374 if (dwStatusCode == HTTP_STATUS_DENIED)
3377 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3379 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3381 lpwhr->lpHttpSession->lpszUserName,
3382 lpwhr->lpHttpSession->lpszPassword))
3389 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3392 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3394 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3395 &lpwhr->pProxyAuthInfo,
3396 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3397 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3411 /* FIXME: Better check, when we have to create the cache file */
3412 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3413 WCHAR url[INTERNET_MAX_URL_LENGTH];
3414 WCHAR cacheFileName[MAX_PATH+1];
3417 b = HTTP_GetRequestURL(lpwhr, url);
3419 WARN("Could not get URL\n");
3423 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3425 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3426 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3427 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3428 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3429 WARN("Could not create file: %u\n", GetLastError());
3430 lpwhr->hCacheFile = NULL;
3433 WARN("Could not create cache entry: %08x\n", GetLastError());
3439 HeapFree(GetProcessHeap(), 0, requestString);
3441 /* TODO: send notification for P3P header */
3443 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3444 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
3446 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3447 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3448 sizeof(INTERNET_ASYNC_RESULT));
3451 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3455 /***********************************************************************
3456 * HTTPSESSION_Destroy (internal)
3458 * Deallocate session handle
3461 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3463 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3465 TRACE("%p\n", lpwhs);
3467 WININET_Release(&lpwhs->lpAppInfo->hdr);
3469 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3470 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3471 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3472 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3473 HeapFree(GetProcessHeap(), 0, lpwhs);
3476 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3479 case INTERNET_OPTION_HANDLE_TYPE:
3480 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3482 if (*size < sizeof(ULONG))
3483 return ERROR_INSUFFICIENT_BUFFER;
3485 *size = sizeof(DWORD);
3486 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3487 return ERROR_SUCCESS;
3490 return INET_QueryOption(option, buffer, size, unicode);
3493 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3495 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3498 case INTERNET_OPTION_USERNAME:
3500 if (!(ses->lpszUserName = WININET_strdupW(buffer))) break;
3501 return ERROR_SUCCESS;
3503 case INTERNET_OPTION_PASSWORD:
3505 if (!(ses->lpszPassword = WININET_strdupW(buffer))) break;
3506 return ERROR_SUCCESS;
3511 return ERROR_INTERNET_INVALID_OPTION;
3514 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3515 HTTPSESSION_Destroy,
3517 HTTPSESSION_QueryOption,
3518 HTTPSESSION_SetOption,
3527 /***********************************************************************
3528 * HTTP_Connect (internal)
3530 * Create http session handle
3533 * HINTERNET a session handle on success
3537 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3538 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3539 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3540 DWORD dwInternalFlags)
3542 LPWININETHTTPSESSIONW lpwhs = NULL;
3543 HINTERNET handle = NULL;
3547 if (!lpszServerName || !lpszServerName[0])
3549 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3553 assert( hIC->hdr.htype == WH_HINIT );
3555 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3558 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3563 * According to my tests. The name is not resolved until a request is sent
3566 lpwhs->hdr.htype = WH_HHTTPSESSION;
3567 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3568 lpwhs->hdr.dwFlags = dwFlags;
3569 lpwhs->hdr.dwContext = dwContext;
3570 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3571 lpwhs->hdr.refs = 1;
3572 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3574 WININET_AddRef( &hIC->hdr );
3575 lpwhs->lpAppInfo = hIC;
3576 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3578 handle = WININET_AllocHandle( &lpwhs->hdr );
3581 ERR("Failed to alloc handle\n");
3582 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3586 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3587 if(strchrW(hIC->lpszProxy, ' '))
3588 FIXME("Several proxies not implemented.\n");
3589 if(hIC->lpszProxyBypass)
3590 FIXME("Proxy bypass is ignored.\n");
3592 if (lpszServerName && lpszServerName[0])
3594 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3595 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3597 if (lpszUserName && lpszUserName[0])
3598 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3599 if (lpszPassword && lpszPassword[0])
3600 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3601 lpwhs->nServerPort = nServerPort;
3602 lpwhs->nHostPort = nServerPort;
3604 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3605 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3607 INTERNET_SendCallback(&hIC->hdr, dwContext,
3608 INTERNET_STATUS_HANDLE_CREATED, &handle,
3614 WININET_Release( &lpwhs->hdr );
3617 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3621 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3626 /***********************************************************************
3627 * HTTP_OpenConnection (internal)
3629 * Connect to a web server
3636 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3638 BOOL bSuccess = FALSE;
3639 LPWININETHTTPSESSIONW lpwhs;
3640 LPWININETAPPINFOW hIC = NULL;
3646 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3648 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3652 if (NETCON_connected(&lpwhr->netConnection))
3657 if (!HTTP_ResolveName(lpwhr)) goto lend;
3659 lpwhs = lpwhr->lpHttpSession;
3661 hIC = lpwhs->lpAppInfo;
3662 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3663 szaddr, sizeof(szaddr));
3664 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3665 INTERNET_STATUS_CONNECTING_TO_SERVER,
3669 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3672 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3676 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3677 sizeof(lpwhs->socketAddress)))
3680 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3682 /* Note: we differ from Microsoft's WinINet here. they seem to have
3683 * a bug that causes no status callbacks to be sent when starting
3684 * a tunnel to a proxy server using the CONNECT verb. i believe our
3685 * behaviour to be more correct and to not cause any incompatibilities
3686 * because using a secure connection through a proxy server is a rare
3687 * case that would be hard for anyone to depend on */
3688 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3691 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3693 WARN("Couldn't connect securely to host\n");
3698 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3699 INTERNET_STATUS_CONNECTED_TO_SERVER,
3700 szaddr, strlen(szaddr)+1);
3705 TRACE("%d <--\n", bSuccess);
3710 /***********************************************************************
3711 * HTTP_clear_response_headers (internal)
3713 * clear out any old response headers
3715 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3719 for( i=0; i<lpwhr->nCustHeaders; i++)
3721 if( !lpwhr->pCustHeaders[i].lpszField )
3723 if( !lpwhr->pCustHeaders[i].lpszValue )
3725 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3727 HTTP_DeleteCustomHeader( lpwhr, i );
3732 /***********************************************************************
3733 * HTTP_GetResponseHeaders (internal)
3735 * Read server response
3742 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3745 WCHAR buffer[MAX_REPLY_LEN];
3746 DWORD buflen = MAX_REPLY_LEN;
3747 BOOL bSuccess = FALSE;
3749 static const WCHAR szHundred[] = {'1','0','0',0};
3750 char bufferA[MAX_REPLY_LEN];
3751 LPWSTR status_code, status_text;
3752 DWORD cchMaxRawHeaders = 1024;
3753 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3754 DWORD cchRawHeaders = 0;
3758 /* clear old response headers (eg. from a redirect response) */
3759 if (clear) HTTP_clear_response_headers( lpwhr );
3761 if (!NETCON_connected(&lpwhr->netConnection))
3766 * HACK peek at the buffer
3768 buflen = MAX_REPLY_LEN;
3769 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3772 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3774 memset(buffer, 0, MAX_REPLY_LEN);
3775 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3777 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3779 /* split the version from the status code */
3780 status_code = strchrW( buffer, ' ' );
3785 /* split the status code from the status text */
3786 status_text = strchrW( status_code, ' ' );
3791 TRACE("version [%s] status code [%s] status text [%s]\n",
3792 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3794 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3796 /* Add status code */
3797 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3798 HTTP_ADDHDR_FLAG_REPLACE);
3800 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3801 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3803 lpwhr->lpszVersion= WININET_strdupW(buffer);
3804 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3806 /* Restore the spaces */
3807 *(status_code-1) = ' ';
3808 *(status_text-1) = ' ';
3810 /* regenerate raw headers */
3811 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3813 cchMaxRawHeaders *= 2;
3814 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3816 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3817 cchRawHeaders += (buflen-1);
3818 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3819 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3820 lpszRawHeaders[cchRawHeaders] = '\0';
3822 /* Parse each response line */
3825 buflen = MAX_REPLY_LEN;
3826 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3828 LPWSTR * pFieldAndValue;
3830 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3831 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3833 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3835 cchMaxRawHeaders *= 2;
3836 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3838 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3839 cchRawHeaders += (buflen-1);
3840 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3841 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3842 lpszRawHeaders[cchRawHeaders] = '\0';
3844 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3845 if (!pFieldAndValue)
3848 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3849 HTTP_ADDREQ_FLAG_ADD );
3851 HTTP_FreeTokens(pFieldAndValue);
3861 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3862 lpwhr->lpszRawHeaders = lpszRawHeaders;
3863 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3873 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
3879 static void strip_spaces(LPWSTR start)
3884 while (*str == ' ' && *str != '\0')
3888 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3890 end = start + strlenW(start) - 1;
3891 while (end >= start && *end == ' ')
3899 /***********************************************************************
3900 * HTTP_InterpretHttpHeader (internal)
3902 * Parse server response
3906 * Pointer to array of field, value, NULL on success.
3909 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3911 LPWSTR * pTokenPair;
3915 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3917 pszColon = strchrW(buffer, ':');
3918 /* must have two tokens */
3921 HTTP_FreeTokens(pTokenPair);
3923 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3927 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3930 HTTP_FreeTokens(pTokenPair);
3933 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3934 pTokenPair[0][pszColon - buffer] = '\0';
3938 len = strlenW(pszColon);
3939 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3942 HTTP_FreeTokens(pTokenPair);
3945 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3947 strip_spaces(pTokenPair[0]);
3948 strip_spaces(pTokenPair[1]);
3950 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3954 /***********************************************************************
3955 * HTTP_ProcessHeader (internal)
3957 * Stuff header into header tables according to <dwModifier>
3961 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3963 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3965 LPHTTPHEADERW lphttpHdr = NULL;
3966 BOOL bSuccess = FALSE;
3968 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3970 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3972 /* REPLACE wins out over ADD */
3973 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3974 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3976 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3979 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3983 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3987 lphttpHdr = &lpwhr->pCustHeaders[index];
3993 hdr.lpszField = (LPWSTR)field;
3994 hdr.lpszValue = (LPWSTR)value;
3995 hdr.wFlags = hdr.wCount = 0;
3997 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3998 hdr.wFlags |= HDR_ISREQUEST;
4000 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4002 /* no value to delete */
4005 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4006 lphttpHdr->wFlags |= HDR_ISREQUEST;
4008 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4010 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4012 HTTP_DeleteCustomHeader( lpwhr, index );
4018 hdr.lpszField = (LPWSTR)field;
4019 hdr.lpszValue = (LPWSTR)value;
4020 hdr.wFlags = hdr.wCount = 0;
4022 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4023 hdr.wFlags |= HDR_ISREQUEST;
4025 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4030 else if (dwModifier & COALESCEFLAGS)
4035 INT origlen = strlenW(lphttpHdr->lpszValue);
4036 INT valuelen = strlenW(value);
4038 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4041 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4043 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4046 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4049 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4051 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4054 lphttpHdr->lpszValue = lpsztmp;
4055 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4058 lphttpHdr->lpszValue[origlen] = ch;
4060 lphttpHdr->lpszValue[origlen] = ' ';
4064 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4065 lphttpHdr->lpszValue[len] = '\0';
4070 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4071 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4074 TRACE("<-- %d\n",bSuccess);
4079 /***********************************************************************
4080 * HTTP_FinishedReading (internal)
4082 * Called when all content from server has been read by client.
4085 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4087 WCHAR szVersion[10];
4088 WCHAR szConnectionResponse[20];
4089 DWORD dwBufferSize = sizeof(szVersion);
4090 BOOL keepalive = FALSE;
4094 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4095 * the connection is keep-alive by default */
4096 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4097 &dwBufferSize, NULL) &&
4098 !strcmpiW(szVersion, g_szHttp1_1))
4103 dwBufferSize = sizeof(szConnectionResponse);
4104 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4105 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4107 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4112 HTTPREQ_CloseConnection(&lpwhr->hdr);
4115 /* FIXME: store data in the URL cache here */
4121 /***********************************************************************
4122 * HTTP_GetCustomHeaderIndex (internal)
4124 * Return index of custom header from header array
4127 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4128 int requested_index, BOOL request_only)
4132 TRACE("%s\n", debugstr_w(lpszField));
4134 for (index = 0; index < lpwhr->nCustHeaders; index++)
4136 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4139 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4142 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4145 if (requested_index == 0)
4150 if (index >= lpwhr->nCustHeaders)
4153 TRACE("Return: %d\n", index);
4158 /***********************************************************************
4159 * HTTP_InsertCustomHeader (internal)
4161 * Insert header into array
4164 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4167 LPHTTPHEADERW lph = NULL;
4170 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4171 count = lpwhr->nCustHeaders + 1;
4173 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4175 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4179 lpwhr->pCustHeaders = lph;
4180 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4181 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4182 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4183 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4184 lpwhr->nCustHeaders++;
4189 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4196 /***********************************************************************
4197 * HTTP_DeleteCustomHeader (internal)
4199 * Delete header from array
4200 * If this function is called, the indexs may change.
4202 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4204 if( lpwhr->nCustHeaders <= 0 )
4206 if( index >= lpwhr->nCustHeaders )
4208 lpwhr->nCustHeaders--;
4210 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4211 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4213 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4214 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4215 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4221 /***********************************************************************
4222 * HTTP_VerifyValidHeader (internal)
4224 * Verify the given header is not invalid for the given http request
4227 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4229 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4230 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4236 /***********************************************************************
4237 * IsHostInProxyBypassList (@)
4242 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4244 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);