2 * Wininet - Http Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
30 #include "wine/port.h"
32 #if defined(__MINGW32__) || defined (_MSC_VER)
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
40 #ifdef HAVE_ARPA_INET_H
41 # include <arpa/inet.h>
59 #define NO_SHLWAPI_STREAM
60 #define NO_SHLWAPI_REG
61 #define NO_SHLWAPI_STRFCNS
62 #define NO_SHLWAPI_GDI
68 #include "wine/debug.h"
69 #include "wine/exception.h"
70 #include "wine/unicode.h"
72 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
74 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
75 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
76 static const WCHAR hostW[] = { 'H','o','s','t',0 };
77 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
78 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
79 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
80 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
81 static const WCHAR szGET[] = { 'G','E','T', 0 };
82 static const WCHAR szCrLf[] = {'\r','\n', 0};
84 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
85 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
86 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
87 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
88 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
89 static const WCHAR szAge[] = { 'A','g','e',0 };
90 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
91 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
92 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
93 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
94 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
95 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
96 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
97 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
98 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
99 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
100 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
101 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 };
102 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
103 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
104 static const WCHAR szDate[] = { 'D','a','t','e',0 };
105 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
106 static const WCHAR szETag[] = { 'E','T','a','g',0 };
107 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
108 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
109 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
110 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
111 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
112 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
113 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
114 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
115 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
116 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
117 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
118 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
119 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
120 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
121 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
122 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
123 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
124 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
125 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
126 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
127 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
128 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 };
129 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
130 static const WCHAR szURI[] = { 'U','R','I',0 };
131 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
132 static const WCHAR szVary[] = { 'V','a','r','y',0 };
133 static const WCHAR szVia[] = { 'V','i','a',0 };
134 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
135 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
137 #define MAXHOSTNAME 100
138 #define MAX_FIELD_VALUE_LEN 256
139 #define MAX_FIELD_LEN 256
141 #define HTTP_REFERER szReferer
142 #define HTTP_ACCEPT szAccept
143 #define HTTP_USERAGENT szUser_Agent
145 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
146 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
147 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
148 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
149 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
150 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
151 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
153 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
164 unsigned int auth_data_len;
165 BOOL finished; /* finished authenticating */
170 struct gzip_stream_t {
177 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
178 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
179 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
180 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
181 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
182 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
183 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
184 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
185 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
186 static LPWSTR HTTP_GetRedirectURL(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
187 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
188 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
189 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
190 static void HTTP_DrainContent(WININETHTTPREQW *req);
191 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr);
193 static LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
196 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
197 if (HeaderIndex == -1)
200 return &req->pCustHeaders[HeaderIndex];
205 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
207 return HeapAlloc(GetProcessHeap(), 0, items*size);
210 static void wininet_zfree(voidpf opaque, voidpf address)
212 HeapFree(GetProcessHeap(), 0, address);
215 static void init_gzip_stream(WININETHTTPREQW *req)
217 gzip_stream_t *gzip_stream;
220 gzip_stream = HeapAlloc(GetProcessHeap(), 0, sizeof(gzip_stream_t));
221 gzip_stream->zstream.zalloc = wininet_zalloc;
222 gzip_stream->zstream.zfree = wininet_zfree;
223 gzip_stream->zstream.opaque = NULL;
224 gzip_stream->zstream.next_in = NULL;
225 gzip_stream->zstream.avail_in = 0;
227 zres = inflateInit2(&gzip_stream->zstream, 0x1f);
229 ERR("inflateInit failed: %d\n", zres);
230 HeapFree(GetProcessHeap(), 0, gzip_stream);
234 req->gzip_stream = gzip_stream;
235 req->dwContentLength = ~0u;
238 memcpy(gzip_stream->buf, req->read_buf + req->read_pos, req->read_size);
239 gzip_stream->zstream.next_in = gzip_stream->buf;
240 gzip_stream->zstream.avail_in = req->read_size;
247 static void init_gzip_stream(WININETHTTPREQW *req)
249 ERR("gzip stream not supported, missing zlib.\n");
254 /* set the request content length based on the headers */
255 static DWORD set_content_length( LPWININETHTTPREQW lpwhr )
257 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
261 size = sizeof(lpwhr->dwContentLength);
262 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
263 &lpwhr->dwContentLength, &size, NULL))
264 lpwhr->dwContentLength = ~0u;
266 size = sizeof(encoding);
267 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) &&
268 !strcmpiW(encoding, szChunked))
270 lpwhr->dwContentLength = ~0u;
271 lpwhr->read_chunked = TRUE;
274 if(lpwhr->decoding) {
277 static const WCHAR gzipW[] = {'g','z','i','p',0};
279 encoding_idx = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Encoding, 0, FALSE);
280 if(encoding_idx != -1 && !strcmpiW(lpwhr->pCustHeaders[encoding_idx].lpszValue, gzipW))
281 init_gzip_stream(lpwhr);
284 return lpwhr->dwContentLength;
287 /***********************************************************************
288 * HTTP_Tokenize (internal)
290 * Tokenize a string, allocating memory for the tokens.
292 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
294 LPWSTR * token_array;
301 /* empty string has no tokens */
305 for (i = 0; string[i]; i++)
307 if (!strncmpW(string+i, token_string, strlenW(token_string)))
311 /* we want to skip over separators, but not the null terminator */
312 for (j = 0; j < strlenW(token_string) - 1; j++)
320 /* add 1 for terminating NULL */
321 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
322 token_array[tokens] = NULL;
325 for (i = 0; i < tokens; i++)
328 next_token = strstrW(string, token_string);
329 if (!next_token) next_token = string+strlenW(string);
330 len = next_token - string;
331 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
332 memcpy(token_array[i], string, len*sizeof(WCHAR));
333 token_array[i][len] = '\0';
334 string = next_token+strlenW(token_string);
339 /***********************************************************************
340 * HTTP_FreeTokens (internal)
342 * Frees memory returned from HTTP_Tokenize.
344 static void HTTP_FreeTokens(LPWSTR * token_array)
347 for (i = 0; token_array[i]; i++)
348 HeapFree(GetProcessHeap(), 0, token_array[i]);
349 HeapFree(GetProcessHeap(), 0, token_array);
352 /* **********************************************************************
354 * Helper functions for the HttpSendRequest(Ex) functions
357 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
359 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
360 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
362 TRACE("%p\n", lpwhr);
364 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
365 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
366 req->dwContentLength, req->bEndRequest);
368 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
371 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
373 static const WCHAR szSlash[] = { '/',0 };
374 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
376 /* If we don't have a path we set it to root */
377 if (NULL == lpwhr->lpszPath)
378 lpwhr->lpszPath = WININET_strdupW(szSlash);
379 else /* remove \r and \n*/
381 int nLen = strlenW(lpwhr->lpszPath);
382 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
385 lpwhr->lpszPath[nLen]='\0';
387 /* Replace '\' with '/' */
390 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
394 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
395 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
396 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
398 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
399 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
401 strcpyW(fixurl + 1, lpwhr->lpszPath);
402 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
403 lpwhr->lpszPath = fixurl;
407 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
409 LPWSTR requestString;
415 static const WCHAR szSpace[] = { ' ',0 };
416 static const WCHAR szColon[] = { ':',' ',0 };
417 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
419 /* allocate space for an array of all the string pointers to be added */
420 len = (lpwhr->nCustHeaders)*4 + 10;
421 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
423 /* add the verb, path and HTTP version string */
431 /* Append custom request headers */
432 for (i = 0; i < lpwhr->nCustHeaders; i++)
434 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
437 req[n++] = lpwhr->pCustHeaders[i].lpszField;
439 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
441 TRACE("Adding custom header %s (%s)\n",
442 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
443 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
448 ERR("oops. buffer overrun\n");
451 requestString = HTTP_build_req( req, 4 );
452 HeapFree( GetProcessHeap(), 0, req );
455 * Set (header) termination string for request
456 * Make sure there's exactly two new lines at the end of the request
458 p = &requestString[strlenW(requestString)-1];
459 while ( (*p == '\n') || (*p == '\r') )
461 strcpyW( p+1, sztwocrlf );
463 return requestString;
466 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
470 LPHTTPHEADERW setCookieHeader;
472 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
474 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
476 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
479 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','%','s',0};
483 Host = HTTP_GetHeader(lpwhr, hostW);
484 len = lstrlenW(Host->lpszValue) + 9 + lstrlenW(lpwhr->lpszPath);
485 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
486 sprintfW(buf_url, szFmt, Host->lpszValue, lpwhr->lpszPath);
487 InternetSetCookieW(buf_url, NULL, setCookieHeader->lpszValue);
489 HeapFree(GetProcessHeap(), 0, buf_url);
495 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
497 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
498 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
499 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
502 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
503 struct HttpAuthInfo **ppAuthInfo,
504 LPWSTR domain_and_username, LPWSTR password )
506 SECURITY_STATUS sec_status;
507 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
510 TRACE("%s\n", debugstr_w(pszAuthValue));
517 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
521 SecInvalidateHandle(&pAuthInfo->cred);
522 SecInvalidateHandle(&pAuthInfo->ctx);
523 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
525 pAuthInfo->auth_data = NULL;
526 pAuthInfo->auth_data_len = 0;
527 pAuthInfo->finished = FALSE;
529 if (is_basic_auth_value(pszAuthValue))
531 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
532 pAuthInfo->scheme = WININET_strdupW(szBasic);
533 if (!pAuthInfo->scheme)
535 HeapFree(GetProcessHeap(), 0, pAuthInfo);
542 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
544 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
545 if (!pAuthInfo->scheme)
547 HeapFree(GetProcessHeap(), 0, pAuthInfo);
551 if (domain_and_username)
553 WCHAR *user = strchrW(domain_and_username, '\\');
554 WCHAR *domain = domain_and_username;
556 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
558 pAuthData = &nt_auth_identity;
563 user = domain_and_username;
567 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
568 nt_auth_identity.User = user;
569 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
570 nt_auth_identity.Domain = domain;
571 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
572 nt_auth_identity.Password = password;
573 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
576 /* use default credentials */
579 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
580 SECPKG_CRED_OUTBOUND, NULL,
582 NULL, &pAuthInfo->cred,
584 if (sec_status == SEC_E_OK)
586 PSecPkgInfoW sec_pkg_info;
587 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
588 if (sec_status == SEC_E_OK)
590 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
591 FreeContextBuffer(sec_pkg_info);
594 if (sec_status != SEC_E_OK)
596 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
597 debugstr_w(pAuthInfo->scheme), sec_status);
598 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
599 HeapFree(GetProcessHeap(), 0, pAuthInfo);
603 *ppAuthInfo = pAuthInfo;
605 else if (pAuthInfo->finished)
608 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
609 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
611 ERR("authentication scheme changed from %s to %s\n",
612 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
616 if (is_basic_auth_value(pszAuthValue))
622 TRACE("basic authentication\n");
624 /* we don't cache credentials for basic authentication, so we can't
625 * retrieve them if the application didn't pass us any credentials */
626 if (!domain_and_username) return FALSE;
628 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
629 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
631 /* length includes a nul terminator, which will be re-used for the ':' */
632 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
636 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
637 auth_data[userlen] = ':';
638 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
640 pAuthInfo->auth_data = auth_data;
641 pAuthInfo->auth_data_len = userlen + 1 + passlen;
642 pAuthInfo->finished = TRUE;
649 SecBufferDesc out_desc, in_desc;
651 unsigned char *buffer;
652 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
653 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
655 in.BufferType = SECBUFFER_TOKEN;
659 in_desc.ulVersion = 0;
660 in_desc.cBuffers = 1;
661 in_desc.pBuffers = ∈
663 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
664 if (*pszAuthData == ' ')
667 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
668 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
669 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
672 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
674 out.BufferType = SECBUFFER_TOKEN;
675 out.cbBuffer = pAuthInfo->max_token;
676 out.pvBuffer = buffer;
678 out_desc.ulVersion = 0;
679 out_desc.cBuffers = 1;
680 out_desc.pBuffers = &out;
682 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
683 first ? NULL : &pAuthInfo->ctx,
684 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
685 context_req, 0, SECURITY_NETWORK_DREP,
686 in.pvBuffer ? &in_desc : NULL,
687 0, &pAuthInfo->ctx, &out_desc,
688 &pAuthInfo->attr, &pAuthInfo->exp);
689 if (sec_status == SEC_E_OK)
691 pAuthInfo->finished = TRUE;
692 pAuthInfo->auth_data = out.pvBuffer;
693 pAuthInfo->auth_data_len = out.cbBuffer;
694 TRACE("sending last auth packet\n");
696 else if (sec_status == SEC_I_CONTINUE_NEEDED)
698 pAuthInfo->auth_data = out.pvBuffer;
699 pAuthInfo->auth_data_len = out.cbBuffer;
700 TRACE("sending next auth packet\n");
704 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
705 pAuthInfo->finished = TRUE;
706 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
714 /***********************************************************************
715 * HTTP_HttpAddRequestHeadersW (internal)
717 static BOOL HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
718 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
723 BOOL bSuccess = FALSE;
726 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
728 if( dwHeaderLength == ~0U )
729 len = strlenW(lpszHeader);
731 len = dwHeaderLength;
732 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
733 lstrcpynW( buffer, lpszHeader, len + 1);
739 LPWSTR * pFieldAndValue;
743 while (*lpszEnd != '\0')
745 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
750 if (*lpszStart == '\0')
753 if (*lpszEnd == '\r')
756 lpszEnd += 2; /* Jump over \r\n */
758 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
759 if (*lpszStart == '\0')
761 /* Skip 0-length headers */
766 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
769 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
771 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
772 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
773 HTTP_FreeTokens(pFieldAndValue);
779 HeapFree(GetProcessHeap(), 0, buffer);
784 /***********************************************************************
785 * HttpAddRequestHeadersW (WININET.@)
787 * Adds one or more HTTP header to the request handler
790 * On Windows if dwHeaderLength includes the trailing '\0', then
791 * HttpAddRequestHeadersW() adds it too. However this results in an
792 * invalid Http header which is rejected by some servers so we probably
793 * don't need to match Windows on that point.
800 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
801 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
803 BOOL bSuccess = FALSE;
804 LPWININETHTTPREQW lpwhr;
806 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
811 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
812 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
814 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
817 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
820 WININET_Release( &lpwhr->hdr );
825 /***********************************************************************
826 * HttpAddRequestHeadersA (WININET.@)
828 * Adds one or more HTTP header to the request handler
835 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
836 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
842 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
844 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
845 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
846 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
847 if( dwHeaderLength != ~0U )
848 dwHeaderLength = len;
850 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
852 HeapFree( GetProcessHeap(), 0, hdr );
857 /***********************************************************************
858 * HttpEndRequestA (WININET.@)
860 * Ends an HTTP request that was started by HttpSendRequestEx
867 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
868 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
870 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
874 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
878 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
881 static BOOL HTTP_HttpEndRequestW(LPWININETHTTPREQW lpwhr, DWORD dwFlags, DWORD_PTR dwContext)
886 INTERNET_ASYNC_RESULT iar;
888 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
889 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
891 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
895 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
896 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
898 /* process cookies here. Is this right? */
899 HTTP_ProcessCookies(lpwhr);
901 if (!set_content_length( lpwhr )) HTTP_FinishedReading(lpwhr);
903 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
905 DWORD dwCode,dwCodeLength = sizeof(DWORD);
906 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE, &dwCode, &dwCodeLength, NULL) &&
907 (dwCode == 302 || dwCode == 301 || dwCode == 303))
909 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
910 dwBufferSize=sizeof(szNewLocation);
911 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL))
913 /* redirects are always GETs */
914 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
915 lpwhr->lpszVerb = WININET_strdupW(szGET);
916 HTTP_DrainContent(lpwhr);
917 if ((new_url = HTTP_GetRedirectURL( lpwhr, szNewLocation )))
919 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REDIRECT,
920 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
921 rc = HTTP_HandleRedirect(lpwhr, new_url);
923 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
924 HeapFree( GetProcessHeap(), 0, new_url );
930 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
931 iar.dwError = rc ? 0 : INTERNET_GetLastError();
933 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
934 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
935 sizeof(INTERNET_ASYNC_RESULT));
939 static void AsyncHttpEndRequestProc(WORKREQUEST *work)
941 struct WORKREQ_HTTPENDREQUESTW const *req = &work->u.HttpEndRequestW;
942 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)work->hdr;
944 TRACE("%p\n", lpwhr);
946 HTTP_HttpEndRequestW(lpwhr, req->dwFlags, req->dwContext);
949 /***********************************************************************
950 * HttpEndRequestW (WININET.@)
952 * Ends an HTTP request that was started by HttpSendRequestEx
959 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
960 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
963 LPWININETHTTPREQW lpwhr;
969 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
973 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
975 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
977 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
979 WININET_Release( &lpwhr->hdr );
982 lpwhr->hdr.dwFlags |= dwFlags;
984 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
987 struct WORKREQ_HTTPENDREQUESTW *request;
989 work.asyncproc = AsyncHttpEndRequestProc;
990 work.hdr = WININET_AddRef( &lpwhr->hdr );
992 request = &work.u.HttpEndRequestW;
993 request->dwFlags = dwFlags;
994 request->dwContext = dwContext;
996 INTERNET_AsyncCall(&work);
997 INTERNET_SetLastError(ERROR_IO_PENDING);
1000 rc = HTTP_HttpEndRequestW(lpwhr, dwFlags, dwContext);
1002 WININET_Release( &lpwhr->hdr );
1003 TRACE("%i <--\n",rc);
1007 /***********************************************************************
1008 * HttpOpenRequestW (WININET.@)
1010 * Open a HTTP request handle
1013 * HINTERNET a HTTP request handle on success
1017 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
1018 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1019 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1020 DWORD dwFlags, DWORD_PTR dwContext)
1022 LPWININETHTTPSESSIONW lpwhs;
1023 HINTERNET handle = NULL;
1025 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1026 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
1027 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
1028 dwFlags, dwContext);
1029 if(lpszAcceptTypes!=NULL)
1032 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
1033 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
1036 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
1037 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
1039 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1044 * My tests seem to show that the windows version does not
1045 * become asynchronous until after this point. And anyhow
1046 * if this call was asynchronous then how would you get the
1047 * necessary HINTERNET pointer returned by this function.
1050 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
1051 lpszVersion, lpszReferrer, lpszAcceptTypes,
1052 dwFlags, dwContext);
1055 WININET_Release( &lpwhs->hdr );
1056 TRACE("returning %p\n", handle);
1061 /***********************************************************************
1062 * HttpOpenRequestA (WININET.@)
1064 * Open a HTTP request handle
1067 * HINTERNET a HTTP request handle on success
1071 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1072 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1073 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1074 DWORD dwFlags, DWORD_PTR dwContext)
1076 LPWSTR szVerb = NULL, szObjectName = NULL;
1077 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1078 INT len, acceptTypesCount;
1079 HINTERNET rc = FALSE;
1082 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1083 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1084 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1085 dwFlags, dwContext);
1089 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
1090 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
1093 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
1098 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
1099 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
1100 if ( !szObjectName )
1102 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
1107 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
1108 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1111 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
1116 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1117 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1120 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1123 if (lpszAcceptTypes)
1125 acceptTypesCount = 0;
1126 types = lpszAcceptTypes;
1131 /* find out how many there are */
1132 if (*types && **types)
1134 TRACE("accept type: %s\n", debugstr_a(*types));
1140 WARN("invalid accept type pointer\n");
1145 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1146 if (!szAcceptTypes) goto end;
1148 acceptTypesCount = 0;
1149 types = lpszAcceptTypes;
1154 if (*types && **types)
1156 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1157 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1159 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1165 /* ignore invalid pointer */
1170 szAcceptTypes[acceptTypesCount] = NULL;
1173 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1174 szVersion, szReferrer,
1175 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1180 acceptTypesCount = 0;
1181 while (szAcceptTypes[acceptTypesCount])
1183 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1186 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1188 HeapFree(GetProcessHeap(), 0, szReferrer);
1189 HeapFree(GetProcessHeap(), 0, szVersion);
1190 HeapFree(GetProcessHeap(), 0, szObjectName);
1191 HeapFree(GetProcessHeap(), 0, szVerb);
1196 /***********************************************************************
1199 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1202 static const CHAR HTTP_Base64Enc[] =
1203 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1207 /* first 6 bits, all from bin[0] */
1208 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1209 x = (bin[0] & 3) << 4;
1211 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1214 base64[n++] = HTTP_Base64Enc[x];
1219 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1220 x = ( bin[1] & 0x0f ) << 2;
1222 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1225 base64[n++] = HTTP_Base64Enc[x];
1229 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1231 /* last 6 bits, all from bin [2] */
1232 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1240 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1241 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1242 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1243 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1244 static const signed char HTTP_Base64Dec[256] =
1246 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1247 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1248 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1249 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1250 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1251 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1252 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1253 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1254 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1255 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1256 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1257 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1258 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1259 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1260 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1261 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1262 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1263 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1264 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1265 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1266 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1267 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1268 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1269 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1270 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1271 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1275 /***********************************************************************
1278 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1286 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1287 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1288 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1289 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1291 WARN("invalid base64: %s\n", debugstr_w(base64));
1295 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1298 if ((base64[2] == '=') && (base64[3] == '='))
1300 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1301 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1303 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1307 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1310 if (base64[3] == '=')
1312 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1313 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1315 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1319 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1328 /***********************************************************************
1329 * HTTP_InsertAuthorization
1331 * Insert or delete the authorization field in the request header.
1333 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1337 static const WCHAR wszSpace[] = {' ',0};
1338 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1340 WCHAR *authorization = NULL;
1342 if (pAuthInfo->auth_data_len)
1344 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1345 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1346 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1350 strcpyW(authorization, pAuthInfo->scheme);
1351 strcatW(authorization, wszSpace);
1352 HTTP_EncodeBase64(pAuthInfo->auth_data,
1353 pAuthInfo->auth_data_len,
1354 authorization+strlenW(authorization));
1356 /* clear the data as it isn't valid now that it has been sent to the
1357 * server, unless it's Basic authentication which doesn't do
1358 * connection tracking */
1359 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1361 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1362 pAuthInfo->auth_data = NULL;
1363 pAuthInfo->auth_data_len = 0;
1367 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1369 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1371 HeapFree(GetProcessHeap(), 0, authorization);
1376 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1378 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1381 size = sizeof(new_location);
1382 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1384 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1385 strcpyW( url, new_location );
1389 static const WCHAR slash[] = { '/',0 };
1390 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1391 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1392 WININETHTTPSESSIONW *session = req->lpHttpSession;
1394 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1395 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1397 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1399 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1400 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1402 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1403 if (req->lpszPath[0] != '/') strcatW( url, slash );
1404 strcatW( url, req->lpszPath );
1406 TRACE("url=%s\n", debugstr_w(url));
1410 /***********************************************************************
1411 * HTTP_DealWithProxy
1413 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1414 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1416 WCHAR buf[MAXHOSTNAME];
1417 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1418 static WCHAR szNul[] = { 0 };
1419 URL_COMPONENTSW UrlComponents;
1420 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1421 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1423 memset( &UrlComponents, 0, sizeof UrlComponents );
1424 UrlComponents.dwStructSize = sizeof UrlComponents;
1425 UrlComponents.lpszHostName = buf;
1426 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1428 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1429 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1430 sprintfW(proxy, szFormat, hIC->lpszProxy);
1432 strcpyW(proxy, hIC->lpszProxy);
1433 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1435 if( UrlComponents.dwHostNameLength == 0 )
1438 if( !lpwhr->lpszPath )
1439 lpwhr->lpszPath = szNul;
1441 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1442 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1444 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1445 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1446 lpwhs->nServerPort = UrlComponents.nPort;
1448 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1452 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1455 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1457 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1458 INTERNET_STATUS_RESOLVING_NAME,
1459 lpwhs->lpszServerName,
1460 strlenW(lpwhs->lpszServerName)+1);
1462 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1463 &lpwhs->socketAddress))
1465 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1469 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1470 szaddr, sizeof(szaddr));
1471 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1472 INTERNET_STATUS_NAME_RESOLVED,
1473 szaddr, strlen(szaddr)+1);
1475 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1480 /***********************************************************************
1481 * HTTPREQ_Destroy (internal)
1483 * Deallocate request handle
1486 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1488 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1493 if(lpwhr->hCacheFile)
1494 CloseHandle(lpwhr->hCacheFile);
1496 if(lpwhr->lpszCacheFile) {
1497 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1498 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1501 DeleteCriticalSection( &lpwhr->read_section );
1502 WININET_Release(&lpwhr->lpHttpSession->hdr);
1504 if (lpwhr->pAuthInfo)
1506 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1507 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1508 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1509 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1511 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1512 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1513 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1514 lpwhr->pAuthInfo = NULL;
1517 if (lpwhr->pProxyAuthInfo)
1519 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1520 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1521 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1522 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1524 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1525 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1526 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1527 lpwhr->pProxyAuthInfo = NULL;
1530 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1531 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1532 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1533 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1534 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1536 for (i = 0; i < lpwhr->nCustHeaders; i++)
1538 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1539 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1542 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1543 HeapFree(GetProcessHeap(), 0, lpwhr);
1546 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1548 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1550 TRACE("%p\n",lpwhr);
1553 if(lpwhr->gzip_stream) {
1554 inflateEnd(&lpwhr->gzip_stream->zstream);
1555 HeapFree(GetProcessHeap(), 0, lpwhr->gzip_stream);
1556 lpwhr->gzip_stream = NULL;
1560 if (!NETCON_connected(&lpwhr->netConnection))
1563 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1564 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1566 NETCON_close(&lpwhr->netConnection);
1568 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1569 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1572 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1574 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1577 case INTERNET_OPTION_HANDLE_TYPE:
1578 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1580 if (*size < sizeof(ULONG))
1581 return ERROR_INSUFFICIENT_BUFFER;
1583 *size = sizeof(DWORD);
1584 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1585 return ERROR_SUCCESS;
1587 case INTERNET_OPTION_URL: {
1588 WCHAR url[INTERNET_MAX_URL_LENGTH];
1593 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1595 TRACE("INTERNET_OPTION_URL\n");
1597 host = HTTP_GetHeader(req, hostW);
1598 strcpyW(url, httpW);
1599 strcatW(url, host->lpszValue);
1600 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1602 strcatW(url, req->lpszPath);
1604 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1607 len = (strlenW(url)+1) * sizeof(WCHAR);
1609 return ERROR_INSUFFICIENT_BUFFER;
1612 strcpyW(buffer, url);
1613 return ERROR_SUCCESS;
1615 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1617 return ERROR_INSUFFICIENT_BUFFER;
1620 return ERROR_SUCCESS;
1624 case INTERNET_OPTION_DATAFILE_NAME: {
1627 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1629 if(!req->lpszCacheFile) {
1631 return ERROR_INTERNET_ITEM_NOT_FOUND;
1635 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1636 if(*size < req_size)
1637 return ERROR_INSUFFICIENT_BUFFER;
1640 memcpy(buffer, req->lpszCacheFile, *size);
1641 return ERROR_SUCCESS;
1643 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1644 if (req_size > *size)
1645 return ERROR_INSUFFICIENT_BUFFER;
1647 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1648 -1, buffer, *size, NULL, NULL);
1649 return ERROR_SUCCESS;
1653 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1654 PCCERT_CONTEXT context;
1656 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1657 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1658 return ERROR_INSUFFICIENT_BUFFER;
1661 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1663 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1666 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1667 info->ftExpiry = context->pCertInfo->NotAfter;
1668 info->ftStart = context->pCertInfo->NotBefore;
1670 len = CertNameToStrW(context->dwCertEncodingType,
1671 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1672 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1673 if(info->lpszSubjectInfo)
1674 CertNameToStrW(context->dwCertEncodingType,
1675 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1676 info->lpszSubjectInfo, len);
1677 len = CertNameToStrW(context->dwCertEncodingType,
1678 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1679 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1680 if (info->lpszIssuerInfo)
1681 CertNameToStrW(context->dwCertEncodingType,
1682 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1683 info->lpszIssuerInfo, len);
1685 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1687 len = CertNameToStrA(context->dwCertEncodingType,
1688 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1689 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1690 if(infoA->lpszSubjectInfo)
1691 CertNameToStrA(context->dwCertEncodingType,
1692 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1693 infoA->lpszSubjectInfo, len);
1694 len = CertNameToStrA(context->dwCertEncodingType,
1695 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1696 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1697 if(infoA->lpszIssuerInfo)
1698 CertNameToStrA(context->dwCertEncodingType,
1699 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1700 infoA->lpszIssuerInfo, len);
1704 * Contrary to MSDN, these do not appear to be set.
1706 * lpszSignatureAlgName
1707 * lpszEncryptionAlgName
1710 CertFreeCertificateContext(context);
1711 return ERROR_SUCCESS;
1716 return INET_QueryOption(option, buffer, size, unicode);
1719 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1721 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1724 case INTERNET_OPTION_SEND_TIMEOUT:
1725 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1726 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1728 if (size != sizeof(DWORD))
1729 return ERROR_INVALID_PARAMETER;
1731 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1734 case INTERNET_OPTION_USERNAME:
1735 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1736 if (!(req->lpHttpSession->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1737 return ERROR_SUCCESS;
1739 case INTERNET_OPTION_PASSWORD:
1740 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1741 if (!(req->lpHttpSession->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1742 return ERROR_SUCCESS;
1743 case INTERNET_OPTION_HTTP_DECODING:
1744 if(size != sizeof(BOOL))
1745 return ERROR_INVALID_PARAMETER;
1746 req->decoding = *(BOOL*)buffer;
1747 return ERROR_SUCCESS;
1750 return ERROR_INTERNET_INVALID_OPTION;
1753 static inline BOOL is_gzip_buf_empty(gzip_stream_t *gzip_stream)
1756 return gzip_stream->zstream.avail_in == 0;
1762 static DWORD read_gzip_data(WININETHTTPREQW *req, BYTE *buf, int size, int flags, int *read_ret)
1764 DWORD ret = ERROR_SUCCESS;
1771 zstream = &req->gzip_stream->zstream;
1773 while(read < size) {
1774 if(is_gzip_buf_empty(req->gzip_stream)) {
1775 res = NETCON_recv( &req->netConnection, req->gzip_stream->buf,
1776 sizeof(req->gzip_stream->buf), flags, &len);
1779 ret = INTERNET_GetLastError();
1783 zstream->next_in = req->gzip_stream->buf;
1784 zstream->avail_in = len;
1787 zstream->next_out = buf+read;
1788 zstream->avail_out = size-read;
1789 zres = inflate(zstream, Z_FULL_FLUSH);
1790 read = size - zstream->avail_out;
1791 if(zres == Z_STREAM_END) {
1792 TRACE("end of data\n");
1793 req->dwContentLength = req->dwContentRead + req->read_size + read;
1795 }else if(zres != Z_OK) {
1796 WARN("inflate failed %d\n", zres);
1798 ret = ERROR_INTERNET_DECODING_FAILED;
1808 /* read some more data into the read buffer (the read section must be held) */
1809 static BOOL read_more_data( WININETHTTPREQW *req, int maxlen )
1815 /* move existing data to the start of the buffer */
1817 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
1821 if (maxlen == -1) maxlen = sizeof(req->read_buf);
1823 if (req->gzip_stream) {
1824 if(read_gzip_data(req, req->read_buf + req->read_size, maxlen - req->read_size, 0, &len) != ERROR_SUCCESS)
1827 if(!NETCON_recv( &req->netConnection, req->read_buf + req->read_size,
1828 maxlen - req->read_size, 0, &len ))
1832 req->read_size += len;
1836 /* remove some amount of data from the read buffer (the read section must be held) */
1837 static void remove_data( WININETHTTPREQW *req, int count )
1839 if (!(req->read_size -= count)) req->read_pos = 0;
1840 else req->read_pos += count;
1843 static BOOL read_line( WININETHTTPREQW *req, LPSTR buffer, DWORD *len )
1845 int count, bytes_read, pos = 0;
1847 EnterCriticalSection( &req->read_section );
1850 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
1854 count = eol - (req->read_buf + req->read_pos);
1855 bytes_read = count + 1;
1857 else count = bytes_read = req->read_size;
1859 count = min( count, *len - pos );
1860 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
1862 remove_data( req, bytes_read );
1865 if (!read_more_data( req, -1 ) || !req->read_size)
1868 TRACE( "returning empty string\n" );
1869 LeaveCriticalSection( &req->read_section );
1873 LeaveCriticalSection( &req->read_section );
1877 if (pos && buffer[pos - 1] == '\r') pos--;
1880 buffer[*len - 1] = 0;
1881 TRACE( "returning %s\n", debugstr_a(buffer));
1885 /* discard data contents until we reach end of line (the read section must be held) */
1886 static BOOL discard_eol( WININETHTTPREQW *req )
1890 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
1893 remove_data( req, (eol + 1) - (req->read_buf + req->read_pos) );
1896 req->read_pos = req->read_size = 0; /* discard everything */
1897 if (!read_more_data( req, -1 )) return FALSE;
1898 } while (req->read_size);
1902 /* read the size of the next chunk (the read section must be held) */
1903 static BOOL start_next_chunk( WININETHTTPREQW *req )
1905 DWORD chunk_size = 0;
1907 if (!req->dwContentLength) return TRUE;
1908 if (req->dwContentLength == req->dwContentRead)
1910 /* read terminator for the previous chunk */
1911 if (!discard_eol( req )) return FALSE;
1912 req->dwContentLength = ~0u;
1913 req->dwContentRead = 0;
1917 while (req->read_size)
1919 char ch = req->read_buf[req->read_pos];
1920 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1921 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1922 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1923 else if (ch == ';' || ch == '\r' || ch == '\n')
1925 TRACE( "reading %u byte chunk\n", chunk_size );
1926 req->dwContentLength = chunk_size;
1927 req->dwContentRead = 0;
1928 if (!discard_eol( req )) return FALSE;
1931 remove_data( req, 1 );
1933 if (!read_more_data( req, -1 )) return FALSE;
1934 if (!req->read_size)
1936 req->dwContentLength = req->dwContentRead = 0;
1942 /* return the size of data available to be read immediately (the read section must be held) */
1943 static DWORD get_avail_data( WININETHTTPREQW *req )
1945 if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
1947 return min( req->read_size, req->dwContentLength - req->dwContentRead );
1950 /* check if we have reached the end of the data to read (the read section must be held) */
1951 static BOOL end_of_read_data( WININETHTTPREQW *req )
1953 if (req->read_chunked) return (req->dwContentLength == 0);
1954 if (req->dwContentLength == ~0u) return FALSE;
1955 return (req->dwContentLength == req->dwContentRead);
1958 /* fetch some more data into the read buffer (the read section must be held) */
1959 static BOOL refill_buffer( WININETHTTPREQW *req )
1961 int len = sizeof(req->read_buf);
1963 if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
1965 if (!start_next_chunk( req )) return FALSE;
1968 if (req->dwContentLength != ~0u) len = min( len, req->dwContentLength - req->dwContentRead );
1969 if (len <= req->read_size) return TRUE;
1971 if (!read_more_data( req, len )) return FALSE;
1972 if (!req->read_size) req->dwContentLength = req->dwContentRead = 0;
1976 static void HTTP_ReceiveRequestData(WININETHTTPREQW *req, BOOL first_notif)
1978 INTERNET_ASYNC_RESULT iar;
1982 EnterCriticalSection( &req->read_section );
1983 if (refill_buffer( req )) {
1984 iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
1985 iar.dwError = first_notif ? 0 : get_avail_data(req);
1988 iar.dwError = INTERNET_GetLastError();
1990 LeaveCriticalSection( &req->read_section );
1992 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1993 sizeof(INTERNET_ASYNC_RESULT));
1996 /* read data from the http connection (the read section must be held) */
1997 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1999 int len, bytes_read = 0;
2000 DWORD ret = ERROR_SUCCESS;
2002 EnterCriticalSection( &req->read_section );
2003 if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
2005 if (!start_next_chunk( req )) goto done;
2007 if (req->dwContentLength != ~0u) size = min( size, req->dwContentLength - req->dwContentRead );
2011 bytes_read = min( req->read_size, size );
2012 memcpy( buffer, req->read_buf + req->read_pos, bytes_read );
2013 remove_data( req, bytes_read );
2016 if (size > bytes_read)
2018 if (req->gzip_stream) {
2019 if(is_gzip_buf_empty(req->gzip_stream) || !bytes_read || sync) {
2020 ret = read_gzip_data(req, (BYTE*)buffer+bytes_read, size - bytes_read, sync ? MSG_WAITALL : 0, &len);
2021 if(ret == ERROR_SUCCESS)
2024 }else if (!bytes_read || sync) {
2025 if (NETCON_recv( &req->netConnection, (char *)buffer + bytes_read, size - bytes_read,
2026 sync ? MSG_WAITALL : 0, &len))
2028 /* always return success, even if the network layer returns an error */
2032 req->dwContentRead += bytes_read;
2035 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, req->dwContentRead, req->dwContentLength );
2036 LeaveCriticalSection( &req->read_section );
2038 if(ret == ERROR_SUCCESS && req->lpszCacheFile) {
2040 DWORD dwBytesWritten;
2042 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
2044 WARN("WriteFile failed: %u\n", GetLastError());
2047 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
2048 HTTP_FinishedReading(req);
2054 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
2056 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
2057 return HTTPREQ_Read(req, buffer, size, read, TRUE);
2060 static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
2062 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
2063 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
2064 INTERNET_ASYNC_RESULT iar;
2067 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
2069 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
2070 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
2072 iar.dwResult = res == ERROR_SUCCESS;
2075 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
2076 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2077 sizeof(INTERNET_ASYNC_RESULT));
2080 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
2081 DWORD flags, DWORD_PTR context)
2084 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
2087 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
2088 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
2090 if (buffers->dwStructSize != sizeof(*buffers))
2091 return ERROR_INVALID_PARAMETER;
2093 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2095 if ((hdr->dwFlags & INTERNET_FLAG_ASYNC) && !get_avail_data(req))
2097 WORKREQUEST workRequest;
2099 if (TryEnterCriticalSection( &req->read_section ))
2101 if (get_avail_data(req))
2103 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength,
2104 &buffers->dwBufferLength, FALSE);
2105 LeaveCriticalSection( &req->read_section );
2108 LeaveCriticalSection( &req->read_section );
2111 workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
2112 workRequest.hdr = WININET_AddRef(&req->hdr);
2113 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
2115 INTERNET_AsyncCall(&workRequest);
2117 return ERROR_IO_PENDING;
2120 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
2121 !(flags & IRF_NO_WAIT));
2124 if (res == ERROR_SUCCESS) {
2125 DWORD size = buffers->dwBufferLength;
2126 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
2127 &size, sizeof(size));
2133 static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
2135 struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
2136 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
2137 INTERNET_ASYNC_RESULT iar;
2140 TRACE("INTERNETREADFILEEXW %p\n", workRequest->hdr);
2142 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
2143 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
2145 iar.dwResult = res == ERROR_SUCCESS;
2148 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
2149 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2150 sizeof(INTERNET_ASYNC_RESULT));
2153 static DWORD HTTPREQ_ReadFileExW(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSW *buffers,
2154 DWORD flags, DWORD_PTR context)
2157 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
2160 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
2161 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
2163 if (buffers->dwStructSize != sizeof(*buffers))
2164 return ERROR_INVALID_PARAMETER;
2166 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2168 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
2170 WORKREQUEST workRequest;
2172 if (TryEnterCriticalSection( &req->read_section ))
2174 if (get_avail_data(req))
2176 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength,
2177 &buffers->dwBufferLength, FALSE);
2178 LeaveCriticalSection( &req->read_section );
2181 LeaveCriticalSection( &req->read_section );
2184 workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
2185 workRequest.hdr = WININET_AddRef(&req->hdr);
2186 workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
2188 INTERNET_AsyncCall(&workRequest);
2190 return ERROR_IO_PENDING;
2193 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
2194 !(flags & IRF_NO_WAIT));
2197 if (res == ERROR_SUCCESS) {
2198 DWORD size = buffers->dwBufferLength;
2199 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
2200 &size, sizeof(size));
2206 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
2209 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
2211 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2214 if ((ret = NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written)))
2215 lpwhr->dwBytesWritten += *written;
2217 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
2221 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
2223 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
2225 HTTP_ReceiveRequestData(req, FALSE);
2228 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
2230 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
2232 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
2234 if (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2236 WORKREQUEST workRequest;
2238 /* never wait, if we can't enter the section we queue an async request right away */
2239 if (TryEnterCriticalSection( &req->read_section ))
2241 if ((*available = get_avail_data( req ))) goto done;
2242 if (end_of_read_data( req )) goto done;
2243 LeaveCriticalSection( &req->read_section );
2246 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
2247 workRequest.hdr = WININET_AddRef( &req->hdr );
2249 INTERNET_AsyncCall(&workRequest);
2251 return ERROR_IO_PENDING;
2254 EnterCriticalSection( &req->read_section );
2256 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
2258 refill_buffer( req );
2259 *available = get_avail_data( req );
2263 if (*available == sizeof(req->read_buf) && !req->gzip_stream) /* check if we have even more pending in the socket */
2266 if (NETCON_query_data_available(&req->netConnection, &extra))
2267 *available = min( *available + extra, req->dwContentLength - req->dwContentRead );
2269 LeaveCriticalSection( &req->read_section );
2271 TRACE( "returning %u\n", *available );
2272 return ERROR_SUCCESS;
2275 static const HANDLEHEADERVtbl HTTPREQVtbl = {
2277 HTTPREQ_CloseConnection,
2278 HTTPREQ_QueryOption,
2281 HTTPREQ_ReadFileExA,
2282 HTTPREQ_ReadFileExW,
2284 HTTPREQ_QueryDataAvailable,
2288 /***********************************************************************
2289 * HTTP_HttpOpenRequestW (internal)
2291 * Open a HTTP request handle
2294 * HINTERNET a HTTP request handle on success
2298 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
2299 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
2300 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
2301 DWORD dwFlags, DWORD_PTR dwContext)
2303 LPWININETAPPINFOW hIC = NULL;
2304 LPWININETHTTPREQW lpwhr;
2305 LPWSTR lpszHostName = NULL;
2306 HINTERNET handle = NULL;
2307 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
2312 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
2313 hIC = lpwhs->lpAppInfo;
2315 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
2318 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2321 lpwhr->hdr.htype = WH_HHTTPREQ;
2322 lpwhr->hdr.vtbl = &HTTPREQVtbl;
2323 lpwhr->hdr.dwFlags = dwFlags;
2324 lpwhr->hdr.dwContext = dwContext;
2325 lpwhr->hdr.refs = 1;
2326 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
2327 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
2328 lpwhr->dwContentLength = ~0u;
2329 InitializeCriticalSection( &lpwhr->read_section );
2331 WININET_AddRef( &lpwhs->hdr );
2332 lpwhr->lpHttpSession = lpwhs;
2333 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
2335 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
2336 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
2337 if (NULL == lpszHostName)
2339 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2343 handle = WININET_AllocHandle( &lpwhr->hdr );
2346 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2350 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
2352 InternetCloseHandle( handle );
2357 if (lpszObjectName && *lpszObjectName) {
2361 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
2362 if (rc != E_POINTER)
2363 len = strlenW(lpszObjectName)+1;
2364 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2365 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
2366 URL_ESCAPE_SPACES_ONLY);
2369 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2370 strcpyW(lpwhr->lpszPath,lpszObjectName);
2373 static const WCHAR slashW[] = {'/',0};
2375 lpwhr->lpszPath = WININET_strdupW(slashW);
2378 if (lpszReferrer && *lpszReferrer)
2379 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2381 if (lpszAcceptTypes)
2384 for (i = 0; lpszAcceptTypes[i]; i++)
2386 if (!*lpszAcceptTypes[i]) continue;
2387 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2388 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
2389 HTTP_ADDHDR_FLAG_REQ |
2390 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
2394 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
2397 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
2399 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
2401 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
2402 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
2403 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
2405 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2406 HTTP_ProcessHeader(lpwhr, hostW, lpszHostName,
2407 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2410 HTTP_ProcessHeader(lpwhr, hostW, lpwhs->lpszHostName,
2411 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2413 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2414 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2415 INTERNET_DEFAULT_HTTPS_PORT :
2416 INTERNET_DEFAULT_HTTP_PORT);
2418 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2419 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2420 INTERNET_DEFAULT_HTTPS_PORT :
2421 INTERNET_DEFAULT_HTTP_PORT);
2423 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2424 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2426 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2427 INTERNET_STATUS_HANDLE_CREATED, &handle,
2431 HeapFree(GetProcessHeap(), 0, lpszHostName);
2433 WININET_Release( &lpwhr->hdr );
2435 TRACE("<-- %p (%p)\n", handle, lpwhr);
2439 /* read any content returned by the server so that the connection can be
2441 static void HTTP_DrainContent(WININETHTTPREQW *req)
2445 if (!NETCON_connected(&req->netConnection)) return;
2447 if (req->dwContentLength == -1)
2449 NETCON_close(&req->netConnection);
2456 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2458 } while (bytes_read);
2461 static const LPCWSTR header_lookup[] = {
2462 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2463 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2464 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2465 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2466 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2467 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2468 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2469 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2470 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2471 szDate, /* HTTP_QUERY_DATE = 9 */
2472 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2473 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2474 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2475 szURI, /* HTTP_QUERY_URI = 13 */
2476 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2477 NULL, /* HTTP_QUERY_COST = 15 */
2478 NULL, /* HTTP_QUERY_LINK = 16 */
2479 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2480 NULL, /* HTTP_QUERY_VERSION = 18 */
2481 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2482 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2483 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2484 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2485 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2486 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2487 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2488 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2489 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2490 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2491 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2492 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2493 NULL, /* HTTP_QUERY_FROM = 31 */
2494 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2495 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2496 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2497 szReferer, /* HTTP_QUERY_REFERER = 35 */
2498 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2499 szServer, /* HTTP_QUERY_SERVER = 37 */
2500 NULL, /* HTTP_TITLE = 38 */
2501 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2502 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2503 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2504 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2505 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2506 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2507 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2508 NULL, /* HTTP_QUERY_REFRESH = 46 */
2509 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2510 szAge, /* HTTP_QUERY_AGE = 48 */
2511 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2512 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2513 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2514 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2515 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2516 szETag, /* HTTP_QUERY_ETAG = 54 */
2517 hostW, /* HTTP_QUERY_HOST = 55 */
2518 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2519 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2520 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2521 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2522 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2523 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2524 szRange, /* HTTP_QUERY_RANGE = 62 */
2525 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2526 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2527 szVary, /* HTTP_QUERY_VARY = 65 */
2528 szVia, /* HTTP_QUERY_VIA = 66 */
2529 szWarning, /* HTTP_QUERY_WARNING = 67 */
2530 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2531 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2532 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2535 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2537 /***********************************************************************
2538 * HTTP_HttpQueryInfoW (internal)
2540 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2541 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2543 LPHTTPHEADERW lphttpHdr = NULL;
2544 BOOL bSuccess = FALSE;
2545 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2546 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2547 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2550 /* Find requested header structure */
2553 case HTTP_QUERY_CUSTOM:
2554 if (!lpBuffer) return FALSE;
2555 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2558 case HTTP_QUERY_CONTENT_LENGTH:
2559 if(lpwhr->gzip_stream) {
2560 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2564 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2565 requested_index,request_only);
2568 case HTTP_QUERY_RAW_HEADERS_CRLF:
2575 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2577 headers = lpwhr->lpszRawHeaders;
2580 len = strlenW(headers) * sizeof(WCHAR);
2582 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2584 len += sizeof(WCHAR);
2585 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2591 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2594 len = strlenW(szCrLf) * sizeof(WCHAR);
2595 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2597 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2600 *lpdwBufferLength = len;
2603 HeapFree(GetProcessHeap(), 0, headers);
2606 case HTTP_QUERY_RAW_HEADERS:
2608 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2610 LPWSTR pszString = lpBuffer;
2612 for (i = 0; ppszRawHeaderLines[i]; i++)
2613 size += strlenW(ppszRawHeaderLines[i]) + 1;
2615 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2617 HTTP_FreeTokens(ppszRawHeaderLines);
2618 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2619 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2624 for (i = 0; ppszRawHeaderLines[i]; i++)
2626 DWORD len = strlenW(ppszRawHeaderLines[i]);
2627 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2631 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2633 *lpdwBufferLength = size * sizeof(WCHAR);
2634 HTTP_FreeTokens(ppszRawHeaderLines);
2638 case HTTP_QUERY_STATUS_TEXT:
2639 if (lpwhr->lpszStatusText)
2641 DWORD len = strlenW(lpwhr->lpszStatusText);
2642 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2644 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2645 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2650 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2651 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2653 *lpdwBufferLength = len * sizeof(WCHAR);
2657 case HTTP_QUERY_VERSION:
2658 if (lpwhr->lpszVersion)
2660 DWORD len = strlenW(lpwhr->lpszVersion);
2661 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2663 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2664 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2669 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2670 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2672 *lpdwBufferLength = len * sizeof(WCHAR);
2676 case HTTP_QUERY_CONTENT_ENCODING:
2677 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[lpwhr->gzip_stream ? HTTP_QUERY_CONTENT_TYPE : level],
2678 requested_index,request_only);
2681 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2683 if (level < LAST_TABLE_HEADER && header_lookup[level])
2684 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2685 requested_index,request_only);
2689 lphttpHdr = &lpwhr->pCustHeaders[index];
2691 /* Ensure header satisfies requested attributes */
2693 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2694 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2696 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2700 if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2702 /* coalesce value to requested type */
2703 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2705 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2706 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2709 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2715 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2717 tmpTM = *gmtime(&tmpTime);
2718 STHook = (SYSTEMTIME *)lpBuffer;
2719 STHook->wDay = tmpTM.tm_mday;
2720 STHook->wHour = tmpTM.tm_hour;
2721 STHook->wMilliseconds = 0;
2722 STHook->wMinute = tmpTM.tm_min;
2723 STHook->wDayOfWeek = tmpTM.tm_wday;
2724 STHook->wMonth = tmpTM.tm_mon + 1;
2725 STHook->wSecond = tmpTM.tm_sec;
2726 STHook->wYear = tmpTM.tm_year;
2729 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2730 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2731 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2733 else if (lphttpHdr->lpszValue)
2735 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2737 if (len > *lpdwBufferLength)
2739 *lpdwBufferLength = len;
2740 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2745 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2746 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2748 *lpdwBufferLength = len - sizeof(WCHAR);
2754 /***********************************************************************
2755 * HttpQueryInfoW (WININET.@)
2757 * Queries for information about an HTTP request
2764 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2765 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2767 BOOL bSuccess = FALSE;
2768 LPWININETHTTPREQW lpwhr;
2770 if (TRACE_ON(wininet)) {
2771 #define FE(x) { x, #x }
2772 static const wininet_flag_info query_flags[] = {
2773 FE(HTTP_QUERY_MIME_VERSION),
2774 FE(HTTP_QUERY_CONTENT_TYPE),
2775 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2776 FE(HTTP_QUERY_CONTENT_ID),
2777 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2778 FE(HTTP_QUERY_CONTENT_LENGTH),
2779 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2780 FE(HTTP_QUERY_ALLOW),
2781 FE(HTTP_QUERY_PUBLIC),
2782 FE(HTTP_QUERY_DATE),
2783 FE(HTTP_QUERY_EXPIRES),
2784 FE(HTTP_QUERY_LAST_MODIFIED),
2785 FE(HTTP_QUERY_MESSAGE_ID),
2787 FE(HTTP_QUERY_DERIVED_FROM),
2788 FE(HTTP_QUERY_COST),
2789 FE(HTTP_QUERY_LINK),
2790 FE(HTTP_QUERY_PRAGMA),
2791 FE(HTTP_QUERY_VERSION),
2792 FE(HTTP_QUERY_STATUS_CODE),
2793 FE(HTTP_QUERY_STATUS_TEXT),
2794 FE(HTTP_QUERY_RAW_HEADERS),
2795 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2796 FE(HTTP_QUERY_CONNECTION),
2797 FE(HTTP_QUERY_ACCEPT),
2798 FE(HTTP_QUERY_ACCEPT_CHARSET),
2799 FE(HTTP_QUERY_ACCEPT_ENCODING),
2800 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2801 FE(HTTP_QUERY_AUTHORIZATION),
2802 FE(HTTP_QUERY_CONTENT_ENCODING),
2803 FE(HTTP_QUERY_FORWARDED),
2804 FE(HTTP_QUERY_FROM),
2805 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2806 FE(HTTP_QUERY_LOCATION),
2807 FE(HTTP_QUERY_ORIG_URI),
2808 FE(HTTP_QUERY_REFERER),
2809 FE(HTTP_QUERY_RETRY_AFTER),
2810 FE(HTTP_QUERY_SERVER),
2811 FE(HTTP_QUERY_TITLE),
2812 FE(HTTP_QUERY_USER_AGENT),
2813 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2814 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2815 FE(HTTP_QUERY_ACCEPT_RANGES),
2816 FE(HTTP_QUERY_SET_COOKIE),
2817 FE(HTTP_QUERY_COOKIE),
2818 FE(HTTP_QUERY_REQUEST_METHOD),
2819 FE(HTTP_QUERY_REFRESH),
2820 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2822 FE(HTTP_QUERY_CACHE_CONTROL),
2823 FE(HTTP_QUERY_CONTENT_BASE),
2824 FE(HTTP_QUERY_CONTENT_LOCATION),
2825 FE(HTTP_QUERY_CONTENT_MD5),
2826 FE(HTTP_QUERY_CONTENT_RANGE),
2827 FE(HTTP_QUERY_ETAG),
2828 FE(HTTP_QUERY_HOST),
2829 FE(HTTP_QUERY_IF_MATCH),
2830 FE(HTTP_QUERY_IF_NONE_MATCH),
2831 FE(HTTP_QUERY_IF_RANGE),
2832 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2833 FE(HTTP_QUERY_MAX_FORWARDS),
2834 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2835 FE(HTTP_QUERY_RANGE),
2836 FE(HTTP_QUERY_TRANSFER_ENCODING),
2837 FE(HTTP_QUERY_UPGRADE),
2838 FE(HTTP_QUERY_VARY),
2840 FE(HTTP_QUERY_WARNING),
2841 FE(HTTP_QUERY_CUSTOM)
2843 static const wininet_flag_info modifier_flags[] = {
2844 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2845 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2846 FE(HTTP_QUERY_FLAG_NUMBER),
2847 FE(HTTP_QUERY_FLAG_COALESCE)
2850 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2851 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2854 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2855 TRACE(" Attribute:");
2856 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2857 if (query_flags[i].val == info) {
2858 TRACE(" %s", query_flags[i].name);
2862 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2863 TRACE(" Unknown (%08x)", info);
2866 TRACE(" Modifier:");
2867 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2868 if (modifier_flags[i].val & info_mod) {
2869 TRACE(" %s", modifier_flags[i].name);
2870 info_mod &= ~ modifier_flags[i].val;
2875 TRACE(" Unknown (%08x)", info_mod);
2880 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2881 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2883 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2887 if (lpBuffer == NULL)
2888 *lpdwBufferLength = 0;
2889 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2890 lpBuffer, lpdwBufferLength, lpdwIndex);
2894 WININET_Release( &lpwhr->hdr );
2896 TRACE("%d <--\n", bSuccess);
2900 /***********************************************************************
2901 * HttpQueryInfoA (WININET.@)
2903 * Queries for information about an HTTP request
2910 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2911 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2917 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2918 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2920 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2921 lpdwBufferLength, lpdwIndex );
2927 len = (*lpdwBufferLength)*sizeof(WCHAR);
2928 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2930 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2936 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2937 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2938 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2939 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2946 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2950 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2951 lpBuffer, *lpdwBufferLength, NULL, NULL );
2952 *lpdwBufferLength = len - 1;
2954 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2957 /* since the strings being returned from HttpQueryInfoW should be
2958 * only ASCII characters, it is reasonable to assume that all of
2959 * the Unicode characters can be reduced to a single byte */
2960 *lpdwBufferLength = len / sizeof(WCHAR);
2962 HeapFree(GetProcessHeap(), 0, bufferW );
2967 /***********************************************************************
2968 * HttpSendRequestExA (WININET.@)
2970 * Sends the specified request to the HTTP server and allows chunked
2975 * Failure: FALSE, call GetLastError() for more information.
2977 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2978 LPINTERNET_BUFFERSA lpBuffersIn,
2979 LPINTERNET_BUFFERSA lpBuffersOut,
2980 DWORD dwFlags, DWORD_PTR dwContext)
2982 INTERNET_BUFFERSW BuffersInW;
2985 LPWSTR header = NULL;
2987 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2988 lpBuffersOut, dwFlags, dwContext);
2992 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2993 if (lpBuffersIn->lpcszHeader)
2995 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2996 lpBuffersIn->dwHeadersLength,0,0);
2997 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2998 if (!(BuffersInW.lpcszHeader = header))
3000 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3003 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
3004 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
3008 BuffersInW.lpcszHeader = NULL;
3009 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
3010 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
3011 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
3012 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
3013 BuffersInW.Next = NULL;
3016 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
3018 HeapFree(GetProcessHeap(),0,header);
3023 /***********************************************************************
3024 * HttpSendRequestExW (WININET.@)
3026 * Sends the specified request to the HTTP server and allows chunked
3031 * Failure: FALSE, call GetLastError() for more information.
3033 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
3034 LPINTERNET_BUFFERSW lpBuffersIn,
3035 LPINTERNET_BUFFERSW lpBuffersOut,
3036 DWORD dwFlags, DWORD_PTR dwContext)
3039 LPWININETHTTPREQW lpwhr;
3040 LPWININETHTTPSESSIONW lpwhs;
3041 LPWININETAPPINFOW hIC;
3043 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
3044 lpBuffersOut, dwFlags, dwContext);
3046 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
3048 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3050 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
3054 lpwhs = lpwhr->lpHttpSession;
3055 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
3056 hIC = lpwhs->lpAppInfo;
3057 assert(hIC->hdr.htype == WH_HINIT);
3059 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3061 WORKREQUEST workRequest;
3062 struct WORKREQ_HTTPSENDREQUESTW *req;
3064 workRequest.asyncproc = AsyncHttpSendRequestProc;
3065 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
3066 req = &workRequest.u.HttpSendRequestW;
3069 if (lpBuffersIn->lpcszHeader)
3070 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
3071 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
3073 req->lpszHeader = NULL;
3074 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
3075 req->lpOptional = lpBuffersIn->lpvBuffer;
3076 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
3077 req->dwContentLength = lpBuffersIn->dwBufferTotal;
3081 req->lpszHeader = NULL;
3082 req->dwHeaderLength = 0;
3083 req->lpOptional = NULL;
3084 req->dwOptionalLength = 0;
3085 req->dwContentLength = 0;
3088 req->bEndRequest = FALSE;
3090 INTERNET_AsyncCall(&workRequest);
3092 * This is from windows.
3094 INTERNET_SetLastError(ERROR_IO_PENDING);
3099 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
3100 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
3101 lpBuffersIn->dwBufferTotal, FALSE);
3103 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
3108 WININET_Release( &lpwhr->hdr );
3114 /***********************************************************************
3115 * HttpSendRequestW (WININET.@)
3117 * Sends the specified request to the HTTP server
3124 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
3125 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
3127 LPWININETHTTPREQW lpwhr;
3128 LPWININETHTTPSESSIONW lpwhs = NULL;
3129 LPWININETAPPINFOW hIC = NULL;
3132 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
3133 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
3135 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
3136 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3138 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
3143 lpwhs = lpwhr->lpHttpSession;
3144 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
3146 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
3151 hIC = lpwhs->lpAppInfo;
3152 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
3154 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
3159 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3161 WORKREQUEST workRequest;
3162 struct WORKREQ_HTTPSENDREQUESTW *req;
3164 workRequest.asyncproc = AsyncHttpSendRequestProc;
3165 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
3166 req = &workRequest.u.HttpSendRequestW;
3171 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
3172 else size = dwHeaderLength * sizeof(WCHAR);
3174 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, size);
3175 memcpy(req->lpszHeader, lpszHeaders, size);
3178 req->lpszHeader = 0;
3179 req->dwHeaderLength = dwHeaderLength;
3180 req->lpOptional = lpOptional;
3181 req->dwOptionalLength = dwOptionalLength;
3182 req->dwContentLength = dwOptionalLength;
3183 req->bEndRequest = TRUE;
3185 INTERNET_AsyncCall(&workRequest);
3187 * This is from windows.
3189 INTERNET_SetLastError(ERROR_IO_PENDING);
3194 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
3195 dwHeaderLength, lpOptional, dwOptionalLength,
3196 dwOptionalLength, TRUE);
3200 WININET_Release( &lpwhr->hdr );
3204 /***********************************************************************
3205 * HttpSendRequestA (WININET.@)
3207 * Sends the specified request to the HTTP server
3214 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
3215 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
3218 LPWSTR szHeaders=NULL;
3219 DWORD nLen=dwHeaderLength;
3220 if(lpszHeaders!=NULL)
3222 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
3223 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
3224 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
3226 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
3227 HeapFree(GetProcessHeap(),0,szHeaders);
3231 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
3233 LPHTTPHEADERW host_header;
3235 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3237 host_header = HTTP_GetHeader(req, hostW);
3241 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
3245 /***********************************************************************
3246 * HTTP_GetRedirectURL (internal)
3248 static LPWSTR HTTP_GetRedirectURL(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
3250 static WCHAR szHttp[] = {'h','t','t','p',0};
3251 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3252 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3253 URL_COMPONENTSW urlComponents;
3254 DWORD url_length = 0;
3256 LPWSTR combined_url;
3258 if (lpszUrl[0]=='/') return WININET_strdupW( lpszUrl );
3260 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3261 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3262 urlComponents.dwSchemeLength = 0;
3263 urlComponents.lpszHostName = lpwhs->lpszHostName;
3264 urlComponents.dwHostNameLength = 0;
3265 urlComponents.nPort = lpwhs->nHostPort;
3266 urlComponents.lpszUserName = lpwhs->lpszUserName;
3267 urlComponents.dwUserNameLength = 0;
3268 urlComponents.lpszPassword = NULL;
3269 urlComponents.dwPasswordLength = 0;
3270 urlComponents.lpszUrlPath = lpwhr->lpszPath;
3271 urlComponents.dwUrlPathLength = 0;
3272 urlComponents.lpszExtraInfo = NULL;
3273 urlComponents.dwExtraInfoLength = 0;
3275 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
3276 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3279 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
3281 /* convert from bytes to characters */
3282 url_length = url_length / sizeof(WCHAR) - 1;
3283 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
3285 HeapFree(GetProcessHeap(), 0, orig_url);
3290 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
3291 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3293 HeapFree(GetProcessHeap(), 0, orig_url);
3296 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
3298 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
3300 HeapFree(GetProcessHeap(), 0, orig_url);
3301 HeapFree(GetProcessHeap(), 0, combined_url);
3304 HeapFree(GetProcessHeap(), 0, orig_url);
3305 return combined_url;
3309 /***********************************************************************
3310 * HTTP_HandleRedirect (internal)
3312 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
3314 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3315 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
3316 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
3317 WCHAR path[INTERNET_MAX_URL_LENGTH];
3322 /* if it's an absolute path, keep the same session info */
3323 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
3327 URL_COMPONENTSW urlComponents;
3328 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
3329 static WCHAR szHttp[] = {'h','t','t','p',0};
3330 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3336 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3337 urlComponents.lpszScheme = protocol;
3338 urlComponents.dwSchemeLength = 32;
3339 urlComponents.lpszHostName = hostName;
3340 urlComponents.dwHostNameLength = MAXHOSTNAME;
3341 urlComponents.lpszUserName = userName;
3342 urlComponents.dwUserNameLength = 1024;
3343 urlComponents.lpszPassword = NULL;
3344 urlComponents.dwPasswordLength = 0;
3345 urlComponents.lpszUrlPath = path;
3346 urlComponents.dwUrlPathLength = 2048;
3347 urlComponents.lpszExtraInfo = NULL;
3348 urlComponents.dwExtraInfoLength = 0;
3349 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
3352 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
3353 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3355 TRACE("redirect from secure page to non-secure page\n");
3356 /* FIXME: warn about from secure redirect to non-secure page */
3357 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
3359 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
3360 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3362 TRACE("redirect from non-secure page to secure page\n");
3363 /* FIXME: notify about redirect to secure page */
3364 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
3367 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3369 if (lstrlenW(protocol)>4) /*https*/
3370 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3372 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3377 * This upsets redirects to binary files on sourceforge.net
3378 * and gives an html page instead of the target file
3379 * Examination of the HTTP request sent by native wininet.dll
3380 * reveals that it doesn't send a referrer in that case.
3381 * Maybe there's a flag that enables this, or maybe a referrer
3382 * shouldn't be added in case of a redirect.
3385 /* consider the current host as the referrer */
3386 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3387 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3388 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3389 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3392 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3393 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3394 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3397 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3398 len = lstrlenW(hostName);
3399 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3400 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3401 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3404 lpwhs->lpszHostName = WININET_strdupW(hostName);
3406 HTTP_ProcessHeader(lpwhr, hostW, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3408 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3409 lpwhs->lpszUserName = NULL;
3411 lpwhs->lpszUserName = WININET_strdupW(userName);
3415 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3417 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3418 lpwhs->lpszServerName = WININET_strdupW(hostName);
3419 lpwhs->nServerPort = urlComponents.nPort;
3421 NETCON_close(&lpwhr->netConnection);
3422 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3423 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3424 lpwhr->read_pos = lpwhr->read_size = 0;
3425 lpwhr->read_chunked = FALSE;
3429 TRACE("Redirect through proxy\n");
3432 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3433 lpwhr->lpszPath=NULL;
3439 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3440 if (rc != E_POINTER)
3441 needed = strlenW(path)+1;
3442 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3443 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3444 URL_ESCAPE_SPACES_ONLY);
3447 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3448 strcpyW(lpwhr->lpszPath,path);
3452 /* Remove custom content-type/length headers on redirects. */
3453 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
3455 HTTP_DeleteCustomHeader(lpwhr, index);
3456 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
3458 HTTP_DeleteCustomHeader(lpwhr, index);
3463 /***********************************************************************
3464 * HTTP_build_req (internal)
3466 * concatenate all the strings in the request together
3468 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3473 for( t = list; *t ; t++ )
3474 len += strlenW( *t );
3477 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3480 for( t = list; *t ; t++ )
3486 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3489 LPWSTR requestString;
3495 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3496 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3497 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3501 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3502 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3503 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3504 HeapFree( GetProcessHeap(), 0, lpszPath );
3506 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3507 NULL, 0, NULL, NULL );
3508 len--; /* the nul terminator isn't needed */
3509 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3510 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3511 ascii_req, len, NULL, NULL );
3512 HeapFree( GetProcessHeap(), 0, requestString );
3514 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3516 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3517 HeapFree( GetProcessHeap(), 0, ascii_req );
3518 if (!ret || cnt < 0)
3521 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3528 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3530 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3531 LPWSTR lpszCookies, lpszUrl = NULL;
3532 DWORD nCookieSize, size;
3533 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr, hostW);
3535 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm) + strlenW(lpwhr->lpszPath)) * sizeof(WCHAR);
3536 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3537 sprintfW( lpszUrl, szUrlForm, Host->lpszValue, lpwhr->lpszPath);
3539 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3542 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3544 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3545 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3547 cnt += sprintfW(lpszCookies, szCookie);
3548 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3549 strcatW(lpszCookies, szCrLf);
3551 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_REPLACE);
3552 HeapFree(GetProcessHeap(), 0, lpszCookies);
3555 HeapFree(GetProcessHeap(), 0, lpszUrl);
3558 /***********************************************************************
3559 * HTTP_HttpSendRequestW (internal)
3561 * Sends the specified request to the HTTP server
3568 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3569 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3570 DWORD dwContentLength, BOOL bEndRequest)
3573 BOOL bSuccess = FALSE, redirected = FALSE;
3574 LPWSTR requestString = NULL;
3577 INTERNET_ASYNC_RESULT iar;
3578 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3579 static const WCHAR szContentLength[] =
3580 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3581 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3583 TRACE("--> %p\n", lpwhr);
3585 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3587 /* if the verb is NULL default to GET */
3588 if (!lpwhr->lpszVerb)
3589 lpwhr->lpszVerb = WININET_strdupW(szGET);
3591 if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3593 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3594 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
3595 lpwhr->dwBytesToWrite = dwContentLength;
3597 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3599 WCHAR *agent_header;
3600 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3603 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3604 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3605 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3607 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3608 HeapFree(GetProcessHeap(), 0, agent_header);
3610 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3612 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3613 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3615 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3617 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3618 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3619 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3629 /* like native, just in case the caller forgot to call InternetReadFile
3630 * for all the data */
3631 HTTP_DrainContent(lpwhr);
3632 lpwhr->dwContentRead = 0;
3634 if (TRACE_ON(wininet))
3636 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr, hostW);
3637 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3641 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3643 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3645 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3646 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3648 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3649 HTTP_InsertCookies(lpwhr);
3651 /* add the headers the caller supplied */
3652 if( lpszHeaders && dwHeaderLength )
3654 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3655 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3658 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3660 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3661 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3662 HeapFree(GetProcessHeap(), 0, url);
3665 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3668 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3670 /* Send the request and store the results */
3671 if (!HTTP_OpenConnection(lpwhr))
3674 /* send the request as ASCII, tack on the optional data */
3675 if (!lpOptional || redirected)
3676 dwOptionalLength = 0;
3677 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3678 NULL, 0, NULL, NULL );
3679 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3680 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3681 ascii_req, len, NULL, NULL );
3683 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3684 len = (len + dwOptionalLength - 1);
3686 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3688 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3689 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3691 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3692 HeapFree( GetProcessHeap(), 0, ascii_req );
3694 lpwhr->dwBytesWritten = dwOptionalLength;
3696 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3697 INTERNET_STATUS_REQUEST_SENT,
3698 &len, sizeof(DWORD));
3705 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3706 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3711 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3715 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3716 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3719 HTTP_ProcessCookies(lpwhr);
3721 if (!set_content_length( lpwhr )) HTTP_FinishedReading(lpwhr);
3723 dwBufferSize = sizeof(dwStatusCode);
3724 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3725 &dwStatusCode,&dwBufferSize,NULL))
3728 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3730 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
3731 dwBufferSize=sizeof(szNewLocation);
3732 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3733 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3735 /* redirects are always GETs */
3736 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3737 lpwhr->lpszVerb = WININET_strdupW(szGET);
3739 HTTP_DrainContent(lpwhr);
3740 if ((new_url = HTTP_GetRedirectURL( lpwhr, szNewLocation )))
3742 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REDIRECT,
3743 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
3744 bSuccess = HTTP_HandleRedirect(lpwhr, new_url);
3747 HeapFree(GetProcessHeap(), 0, requestString);
3750 HeapFree( GetProcessHeap(), 0, new_url );
3755 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3757 WCHAR szAuthValue[2048];
3759 if (dwStatusCode == HTTP_STATUS_DENIED)
3762 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3764 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3766 lpwhr->lpHttpSession->lpszUserName,
3767 lpwhr->lpHttpSession->lpszPassword))
3774 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3777 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3779 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3780 &lpwhr->pProxyAuthInfo,
3781 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3782 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3796 /* FIXME: Better check, when we have to create the cache file */
3797 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3798 WCHAR url[INTERNET_MAX_URL_LENGTH];
3799 WCHAR cacheFileName[MAX_PATH+1];
3802 b = HTTP_GetRequestURL(lpwhr, url);
3804 WARN("Could not get URL\n");
3808 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3810 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3811 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3812 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3813 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3814 WARN("Could not create file: %u\n", GetLastError());
3815 lpwhr->hCacheFile = NULL;
3818 WARN("Could not create cache entry: %08x\n", GetLastError());
3824 HeapFree(GetProcessHeap(), 0, requestString);
3826 /* TODO: send notification for P3P header */
3828 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3832 if (lpwhr->dwBytesWritten == lpwhr->dwBytesToWrite) HTTP_ReceiveRequestData(lpwhr, TRUE);
3835 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3838 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3839 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3840 sizeof(INTERNET_ASYNC_RESULT));
3845 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3846 iar.dwError = INTERNET_GetLastError();
3848 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3849 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3850 sizeof(INTERNET_ASYNC_RESULT));
3855 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3859 /***********************************************************************
3860 * HTTPSESSION_Destroy (internal)
3862 * Deallocate session handle
3865 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3867 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3869 TRACE("%p\n", lpwhs);
3871 WININET_Release(&lpwhs->lpAppInfo->hdr);
3873 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3874 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3875 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3876 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3877 HeapFree(GetProcessHeap(), 0, lpwhs);
3880 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3883 case INTERNET_OPTION_HANDLE_TYPE:
3884 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3886 if (*size < sizeof(ULONG))
3887 return ERROR_INSUFFICIENT_BUFFER;
3889 *size = sizeof(DWORD);
3890 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3891 return ERROR_SUCCESS;
3894 return INET_QueryOption(option, buffer, size, unicode);
3897 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3899 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3902 case INTERNET_OPTION_USERNAME:
3904 HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
3905 if (!(ses->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3906 return ERROR_SUCCESS;
3908 case INTERNET_OPTION_PASSWORD:
3910 HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
3911 if (!(ses->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3912 return ERROR_SUCCESS;
3917 return ERROR_INTERNET_INVALID_OPTION;
3920 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3921 HTTPSESSION_Destroy,
3923 HTTPSESSION_QueryOption,
3924 HTTPSESSION_SetOption,
3933 /***********************************************************************
3934 * HTTP_Connect (internal)
3936 * Create http session handle
3939 * HINTERNET a session handle on success
3943 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3944 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3945 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3946 DWORD dwInternalFlags)
3948 LPWININETHTTPSESSIONW lpwhs = NULL;
3949 HINTERNET handle = NULL;
3953 if (!lpszServerName || !lpszServerName[0])
3955 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3959 assert( hIC->hdr.htype == WH_HINIT );
3961 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3964 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3969 * According to my tests. The name is not resolved until a request is sent
3972 lpwhs->hdr.htype = WH_HHTTPSESSION;
3973 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3974 lpwhs->hdr.dwFlags = dwFlags;
3975 lpwhs->hdr.dwContext = dwContext;
3976 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3977 lpwhs->hdr.refs = 1;
3978 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3980 WININET_AddRef( &hIC->hdr );
3981 lpwhs->lpAppInfo = hIC;
3982 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3984 handle = WININET_AllocHandle( &lpwhs->hdr );
3987 ERR("Failed to alloc handle\n");
3988 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3992 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3993 if(strchrW(hIC->lpszProxy, ' '))
3994 FIXME("Several proxies not implemented.\n");
3995 if(hIC->lpszProxyBypass)
3996 FIXME("Proxy bypass is ignored.\n");
3998 if (lpszServerName && lpszServerName[0])
4000 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
4001 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
4003 if (lpszUserName && lpszUserName[0])
4004 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
4005 if (lpszPassword && lpszPassword[0])
4006 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
4007 lpwhs->nServerPort = nServerPort;
4008 lpwhs->nHostPort = nServerPort;
4010 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
4011 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
4013 INTERNET_SendCallback(&hIC->hdr, dwContext,
4014 INTERNET_STATUS_HANDLE_CREATED, &handle,
4020 WININET_Release( &lpwhs->hdr );
4023 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
4027 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
4032 /***********************************************************************
4033 * HTTP_OpenConnection (internal)
4035 * Connect to a web server
4042 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
4044 BOOL bSuccess = FALSE;
4045 LPWININETHTTPSESSIONW lpwhs;
4046 LPWININETAPPINFOW hIC = NULL;
4052 if (lpwhr->hdr.htype != WH_HHTTPREQ)
4054 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
4058 if (NETCON_connected(&lpwhr->netConnection))
4063 if (!HTTP_ResolveName(lpwhr)) goto lend;
4065 lpwhs = lpwhr->lpHttpSession;
4067 hIC = lpwhs->lpAppInfo;
4068 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
4069 szaddr, sizeof(szaddr));
4070 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
4071 INTERNET_STATUS_CONNECTING_TO_SERVER,
4075 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
4078 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
4082 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
4083 sizeof(lpwhs->socketAddress)))
4086 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
4088 /* Note: we differ from Microsoft's WinINet here. they seem to have
4089 * a bug that causes no status callbacks to be sent when starting
4090 * a tunnel to a proxy server using the CONNECT verb. i believe our
4091 * behaviour to be more correct and to not cause any incompatibilities
4092 * because using a secure connection through a proxy server is a rare
4093 * case that would be hard for anyone to depend on */
4094 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
4097 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
4099 WARN("Couldn't connect securely to host\n");
4104 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
4105 INTERNET_STATUS_CONNECTED_TO_SERVER,
4106 szaddr, strlen(szaddr)+1);
4111 lpwhr->read_pos = lpwhr->read_size = 0;
4112 lpwhr->read_chunked = FALSE;
4114 TRACE("%d <--\n", bSuccess);
4119 /***********************************************************************
4120 * HTTP_clear_response_headers (internal)
4122 * clear out any old response headers
4124 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
4128 for( i=0; i<lpwhr->nCustHeaders; i++)
4130 if( !lpwhr->pCustHeaders[i].lpszField )
4132 if( !lpwhr->pCustHeaders[i].lpszValue )
4134 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
4136 HTTP_DeleteCustomHeader( lpwhr, i );
4141 /***********************************************************************
4142 * HTTP_GetResponseHeaders (internal)
4144 * Read server response
4151 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
4154 WCHAR buffer[MAX_REPLY_LEN];
4155 DWORD buflen = MAX_REPLY_LEN;
4156 BOOL bSuccess = FALSE;
4158 static const WCHAR szHundred[] = {'1','0','0',0};
4159 char bufferA[MAX_REPLY_LEN];
4160 LPWSTR status_code, status_text;
4161 DWORD cchMaxRawHeaders = 1024;
4162 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
4163 DWORD cchRawHeaders = 0;
4167 /* clear old response headers (eg. from a redirect response) */
4168 if (clear) HTTP_clear_response_headers( lpwhr );
4170 if (!NETCON_connected(&lpwhr->netConnection))
4175 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
4177 buflen = MAX_REPLY_LEN;
4178 if (!read_line(lpwhr, bufferA, &buflen))
4181 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
4183 /* split the version from the status code */
4184 status_code = strchrW( buffer, ' ' );
4189 /* split the status code from the status text */
4190 status_text = strchrW( status_code, ' ' );
4195 TRACE("version [%s] status code [%s] status text [%s]\n",
4196 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
4198 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
4200 /* Add status code */
4201 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
4202 HTTP_ADDHDR_FLAG_REPLACE);
4204 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
4205 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
4207 lpwhr->lpszVersion= WININET_strdupW(buffer);
4208 lpwhr->lpszStatusText = WININET_strdupW(status_text);
4210 /* Restore the spaces */
4211 *(status_code-1) = ' ';
4212 *(status_text-1) = ' ';
4214 /* regenerate raw headers */
4215 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
4217 cchMaxRawHeaders *= 2;
4218 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
4220 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
4221 cchRawHeaders += (buflen-1);
4222 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
4223 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
4224 lpszRawHeaders[cchRawHeaders] = '\0';
4226 /* Parse each response line */
4229 buflen = MAX_REPLY_LEN;
4230 if (read_line(lpwhr, bufferA, &buflen))
4232 LPWSTR * pFieldAndValue;
4234 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
4236 if (!bufferA[0]) break;
4237 if (!strchr(bufferA, ':'))
4239 WARN("invalid header\n");
4242 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
4244 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
4246 cchMaxRawHeaders *= 2;
4247 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
4249 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
4250 cchRawHeaders += (buflen-1);
4251 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
4252 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
4253 lpszRawHeaders[cchRawHeaders] = '\0';
4255 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
4256 if (!pFieldAndValue)
4259 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
4260 HTTP_ADDREQ_FLAG_ADD );
4262 HTTP_FreeTokens(pFieldAndValue);
4272 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
4273 lpwhr->lpszRawHeaders = lpszRawHeaders;
4274 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
4284 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
4290 static void strip_spaces(LPWSTR start)
4295 while (*str == ' ' && *str != '\0')
4299 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
4301 end = start + strlenW(start) - 1;
4302 while (end >= start && *end == ' ')
4310 /***********************************************************************
4311 * HTTP_InterpretHttpHeader (internal)
4313 * Parse server response
4317 * Pointer to array of field, value, NULL on success.
4320 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
4322 LPWSTR * pTokenPair;
4326 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
4328 pszColon = strchrW(buffer, ':');
4329 /* must have two tokens */
4332 HTTP_FreeTokens(pTokenPair);
4334 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
4338 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
4341 HTTP_FreeTokens(pTokenPair);
4344 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
4345 pTokenPair[0][pszColon - buffer] = '\0';
4349 len = strlenW(pszColon);
4350 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
4353 HTTP_FreeTokens(pTokenPair);
4356 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
4358 strip_spaces(pTokenPair[0]);
4359 strip_spaces(pTokenPair[1]);
4361 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
4365 /***********************************************************************
4366 * HTTP_ProcessHeader (internal)
4368 * Stuff header into header tables according to <dwModifier>
4372 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4374 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4376 LPHTTPHEADERW lphttpHdr = NULL;
4377 BOOL bSuccess = FALSE;
4379 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4381 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
4383 /* REPLACE wins out over ADD */
4384 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4385 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
4387 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
4390 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
4394 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4398 lphttpHdr = &lpwhr->pCustHeaders[index];
4404 hdr.lpszField = (LPWSTR)field;
4405 hdr.lpszValue = (LPWSTR)value;
4406 hdr.wFlags = hdr.wCount = 0;
4408 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4409 hdr.wFlags |= HDR_ISREQUEST;
4411 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4413 /* no value to delete */
4416 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4417 lphttpHdr->wFlags |= HDR_ISREQUEST;
4419 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4421 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4423 HTTP_DeleteCustomHeader( lpwhr, index );
4429 hdr.lpszField = (LPWSTR)field;
4430 hdr.lpszValue = (LPWSTR)value;
4431 hdr.wFlags = hdr.wCount = 0;
4433 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4434 hdr.wFlags |= HDR_ISREQUEST;
4436 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4441 else if (dwModifier & COALESCEFLAGS)
4446 INT origlen = strlenW(lphttpHdr->lpszValue);
4447 INT valuelen = strlenW(value);
4449 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4452 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4454 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4457 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4460 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4462 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4465 lphttpHdr->lpszValue = lpsztmp;
4466 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4469 lphttpHdr->lpszValue[origlen] = ch;
4471 lphttpHdr->lpszValue[origlen] = ' ';
4475 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4476 lphttpHdr->lpszValue[len] = '\0';
4481 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4482 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4485 TRACE("<-- %d\n",bSuccess);
4490 /***********************************************************************
4491 * HTTP_FinishedReading (internal)
4493 * Called when all content from server has been read by client.
4496 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4498 WCHAR szVersion[10];
4499 WCHAR szConnectionResponse[20];
4500 DWORD dwBufferSize = sizeof(szVersion);
4501 BOOL keepalive = FALSE;
4505 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4506 * the connection is keep-alive by default */
4507 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4508 &dwBufferSize, NULL) &&
4509 !strcmpiW(szVersion, g_szHttp1_1))
4514 dwBufferSize = sizeof(szConnectionResponse);
4515 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4516 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4518 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4523 HTTPREQ_CloseConnection(&lpwhr->hdr);
4526 /* FIXME: store data in the URL cache here */
4532 /***********************************************************************
4533 * HTTP_GetCustomHeaderIndex (internal)
4535 * Return index of custom header from header array
4538 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4539 int requested_index, BOOL request_only)
4543 TRACE("%s\n", debugstr_w(lpszField));
4545 for (index = 0; index < lpwhr->nCustHeaders; index++)
4547 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4550 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4553 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4556 if (requested_index == 0)
4561 if (index >= lpwhr->nCustHeaders)
4564 TRACE("Return: %d\n", index);
4569 /***********************************************************************
4570 * HTTP_InsertCustomHeader (internal)
4572 * Insert header into array
4575 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4578 LPHTTPHEADERW lph = NULL;
4581 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4582 count = lpwhr->nCustHeaders + 1;
4584 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4586 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4590 lpwhr->pCustHeaders = lph;
4591 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4592 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4593 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4594 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4595 lpwhr->nCustHeaders++;
4600 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4607 /***********************************************************************
4608 * HTTP_DeleteCustomHeader (internal)
4610 * Delete header from array
4611 * If this function is called, the indexs may change.
4613 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4615 if( lpwhr->nCustHeaders <= 0 )
4617 if( index >= lpwhr->nCustHeaders )
4619 lpwhr->nCustHeaders--;
4621 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4622 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4624 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4625 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4626 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4632 /***********************************************************************
4633 * HTTP_VerifyValidHeader (internal)
4635 * Verify the given header is not invalid for the given http request
4638 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4640 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4641 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4647 /***********************************************************************
4648 * IsHostInProxyBypassList (@)
4653 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4655 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);