wininet: Send a content length header for all verbs other than GET.
[wine/testsucceed.git] / dlls / wininet / http.c
bloba5352e4642a8cd5782eb1286ab84a674d731711d
1 /*
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
11 * Ulrich Czekalla
12 * David Hammerton
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
29 #include "config.h"
30 #include "wine/port.h"
32 #if defined(__MINGW32__) || defined (_MSC_VER)
33 #include <ws2tcpip.h>
34 #endif
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 # include <arpa/inet.h>
42 #endif
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>
48 #endif
49 #include <time.h>
50 #include <assert.h>
52 #include "windef.h"
53 #include "winbase.h"
54 #include "wininet.h"
55 #include "winerror.h"
56 #define NO_SHLWAPI_STREAM
57 #define NO_SHLWAPI_REG
58 #define NO_SHLWAPI_STRFCNS
59 #define NO_SHLWAPI_GDI
60 #include "shlwapi.h"
61 #include "sspi.h"
62 #include "wincrypt.h"
64 #include "internet.h"
65 #include "wine/debug.h"
66 #include "wine/exception.h"
67 #include "wine/unicode.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
71 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
72 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
73 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
74 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
75 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
76 static const WCHAR szHost[] = { 'H','o','s','t',0 };
77 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
78 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
79 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
80 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
81 static const WCHAR szGET[] = { 'G','E','T', 0 };
82 static const WCHAR szCrLf[] = {'\r','\n', 0};
84 #define MAXHOSTNAME 100
85 #define MAX_FIELD_VALUE_LEN 256
86 #define MAX_FIELD_LEN 256
88 #define HTTP_REFERER g_szReferer
89 #define HTTP_ACCEPT g_szAccept
90 #define HTTP_USERAGENT g_szUserAgent
92 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
93 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
94 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
95 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
96 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
97 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
98 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
100 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
102 struct HttpAuthInfo
104 LPWSTR scheme;
105 CredHandle cred;
106 CtxtHandle ctx;
107 TimeStamp exp;
108 ULONG attr;
109 ULONG max_token;
110 void *auth_data;
111 unsigned int auth_data_len;
112 BOOL finished; /* finished authenticating */
115 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
116 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
117 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
118 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
119 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
120 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
121 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
122 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
123 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
124 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
125 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
126 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
127 static void HTTP_DrainContent(WININETHTTPREQW *req);
129 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
131 int HeaderIndex = 0;
132 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
133 if (HeaderIndex == -1)
134 return NULL;
135 else
136 return &req->pCustHeaders[HeaderIndex];
139 /***********************************************************************
140 * HTTP_Tokenize (internal)
142 * Tokenize a string, allocating memory for the tokens.
144 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
146 LPWSTR * token_array;
147 int tokens = 0;
148 int i;
149 LPCWSTR next_token;
151 if (string)
153 /* empty string has no tokens */
154 if (*string)
155 tokens++;
156 /* count tokens */
157 for (i = 0; string[i]; i++)
159 if (!strncmpW(string+i, token_string, strlenW(token_string)))
161 DWORD j;
162 tokens++;
163 /* we want to skip over separators, but not the null terminator */
164 for (j = 0; j < strlenW(token_string) - 1; j++)
165 if (!string[i+j])
166 break;
167 i += j;
172 /* add 1 for terminating NULL */
173 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
174 token_array[tokens] = NULL;
175 if (!tokens)
176 return token_array;
177 for (i = 0; i < tokens; i++)
179 int len;
180 next_token = strstrW(string, token_string);
181 if (!next_token) next_token = string+strlenW(string);
182 len = next_token - string;
183 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
184 memcpy(token_array[i], string, len*sizeof(WCHAR));
185 token_array[i][len] = '\0';
186 string = next_token+strlenW(token_string);
188 return token_array;
191 /***********************************************************************
192 * HTTP_FreeTokens (internal)
194 * Frees memory returned from HTTP_Tokenize.
196 static void HTTP_FreeTokens(LPWSTR * token_array)
198 int i;
199 for (i = 0; token_array[i]; i++)
200 HeapFree(GetProcessHeap(), 0, token_array[i]);
201 HeapFree(GetProcessHeap(), 0, token_array);
204 /* **********************************************************************
206 * Helper functions for the HttpSendRequest(Ex) functions
209 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
211 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
212 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
214 TRACE("%p\n", lpwhr);
216 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
217 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
218 req->dwContentLength, req->bEndRequest);
220 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
223 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
225 static const WCHAR szSlash[] = { '/',0 };
226 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
228 /* If we don't have a path we set it to root */
229 if (NULL == lpwhr->lpszPath)
230 lpwhr->lpszPath = WININET_strdupW(szSlash);
231 else /* remove \r and \n*/
233 int nLen = strlenW(lpwhr->lpszPath);
234 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
236 nLen--;
237 lpwhr->lpszPath[nLen]='\0';
239 /* Replace '\' with '/' */
240 while (nLen>0) {
241 nLen--;
242 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
246 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
247 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
248 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
250 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
251 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
252 *fixurl = '/';
253 strcpyW(fixurl + 1, lpwhr->lpszPath);
254 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
255 lpwhr->lpszPath = fixurl;
259 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
261 LPWSTR requestString;
262 DWORD len, n;
263 LPCWSTR *req;
264 UINT i;
265 LPWSTR p;
267 static const WCHAR szSpace[] = { ' ',0 };
268 static const WCHAR szColon[] = { ':',' ',0 };
269 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
271 /* allocate space for an array of all the string pointers to be added */
272 len = (lpwhr->nCustHeaders)*4 + 10;
273 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
275 /* add the verb, path and HTTP version string */
276 n = 0;
277 req[n++] = verb;
278 req[n++] = szSpace;
279 req[n++] = path;
280 req[n++] = szSpace;
281 req[n++] = version;
283 /* Append custom request headers */
284 for (i = 0; i < lpwhr->nCustHeaders; i++)
286 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
288 req[n++] = szCrLf;
289 req[n++] = lpwhr->pCustHeaders[i].lpszField;
290 req[n++] = szColon;
291 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
293 TRACE("Adding custom header %s (%s)\n",
294 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
295 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
299 if( n >= len )
300 ERR("oops. buffer overrun\n");
302 req[n] = NULL;
303 requestString = HTTP_build_req( req, 4 );
304 HeapFree( GetProcessHeap(), 0, req );
307 * Set (header) termination string for request
308 * Make sure there's exactly two new lines at the end of the request
310 p = &requestString[strlenW(requestString)-1];
311 while ( (*p == '\n') || (*p == '\r') )
312 p--;
313 strcpyW( p+1, sztwocrlf );
315 return requestString;
318 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
320 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
321 int HeaderIndex;
322 int numCookies = 0;
323 LPHTTPHEADERW setCookieHeader;
325 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
327 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
329 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
331 int nPosStart = 0, nPosEnd = 0, len;
332 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
334 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
336 LPWSTR buf_cookie, cookie_name, cookie_data;
337 LPWSTR buf_url;
338 LPWSTR domain = NULL;
339 LPHTTPHEADERW Host;
341 int nEqualPos = 0;
342 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
343 setCookieHeader->lpszValue[nPosEnd] != '\0')
345 nPosEnd++;
347 if (setCookieHeader->lpszValue[nPosEnd] == ';')
349 /* fixme: not case sensitive, strcasestr is gnu only */
350 int nDomainPosEnd = 0;
351 int nDomainPosStart = 0, nDomainLength = 0;
352 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
353 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
354 if (lpszDomain)
355 { /* they have specified their own domain, lets use it */
356 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
357 lpszDomain[nDomainPosEnd] != '\0')
359 nDomainPosEnd++;
361 nDomainPosStart = strlenW(szDomain);
362 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
363 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
364 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
367 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
368 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
369 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
370 TRACE("%s\n", debugstr_w(buf_cookie));
371 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
373 nEqualPos++;
375 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
377 HeapFree(GetProcessHeap(), 0, buf_cookie);
378 break;
381 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
382 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
383 cookie_data = &buf_cookie[nEqualPos + 1];
385 Host = HTTP_GetHeader(lpwhr,szHost);
386 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
387 strlenW(lpwhr->lpszPath) + 9;
388 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
389 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
390 InternetSetCookieW(buf_url, cookie_name, cookie_data);
392 HeapFree(GetProcessHeap(), 0, buf_url);
393 HeapFree(GetProcessHeap(), 0, buf_cookie);
394 HeapFree(GetProcessHeap(), 0, cookie_name);
395 HeapFree(GetProcessHeap(), 0, domain);
396 nPosStart = nPosEnd;
399 numCookies++;
403 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
405 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
406 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
407 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
410 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
411 struct HttpAuthInfo **ppAuthInfo,
412 LPWSTR domain_and_username, LPWSTR password )
414 SECURITY_STATUS sec_status;
415 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
416 BOOL first = FALSE;
418 TRACE("%s\n", debugstr_w(pszAuthValue));
420 if (!pAuthInfo)
422 TimeStamp exp;
424 first = TRUE;
425 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
426 if (!pAuthInfo)
427 return FALSE;
429 SecInvalidateHandle(&pAuthInfo->cred);
430 SecInvalidateHandle(&pAuthInfo->ctx);
431 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
432 pAuthInfo->attr = 0;
433 pAuthInfo->auth_data = NULL;
434 pAuthInfo->auth_data_len = 0;
435 pAuthInfo->finished = FALSE;
437 if (is_basic_auth_value(pszAuthValue))
439 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
440 pAuthInfo->scheme = WININET_strdupW(szBasic);
441 if (!pAuthInfo->scheme)
443 HeapFree(GetProcessHeap(), 0, pAuthInfo);
444 return FALSE;
447 else
449 PVOID pAuthData;
450 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
452 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
453 if (!pAuthInfo->scheme)
455 HeapFree(GetProcessHeap(), 0, pAuthInfo);
456 return FALSE;
459 if (domain_and_username)
461 WCHAR *user = strchrW(domain_and_username, '\\');
462 WCHAR *domain = domain_and_username;
464 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
466 pAuthData = &nt_auth_identity;
468 if (user) user++;
469 else
471 user = domain_and_username;
472 domain = NULL;
475 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
476 nt_auth_identity.User = user;
477 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
478 nt_auth_identity.Domain = domain;
479 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
480 nt_auth_identity.Password = password;
481 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
483 else
484 /* use default credentials */
485 pAuthData = NULL;
487 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
488 SECPKG_CRED_OUTBOUND, NULL,
489 pAuthData, NULL,
490 NULL, &pAuthInfo->cred,
491 &exp);
492 if (sec_status == SEC_E_OK)
494 PSecPkgInfoW sec_pkg_info;
495 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
496 if (sec_status == SEC_E_OK)
498 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
499 FreeContextBuffer(sec_pkg_info);
502 if (sec_status != SEC_E_OK)
504 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
505 debugstr_w(pAuthInfo->scheme), sec_status);
506 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
507 HeapFree(GetProcessHeap(), 0, pAuthInfo);
508 return FALSE;
511 *ppAuthInfo = pAuthInfo;
513 else if (pAuthInfo->finished)
514 return FALSE;
516 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
517 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
519 ERR("authentication scheme changed from %s to %s\n",
520 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
521 return FALSE;
524 if (is_basic_auth_value(pszAuthValue))
526 int userlen;
527 int passlen;
528 char *auth_data;
530 TRACE("basic authentication\n");
532 /* we don't cache credentials for basic authentication, so we can't
533 * retrieve them if the application didn't pass us any credentials */
534 if (!domain_and_username) return FALSE;
536 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
537 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
539 /* length includes a nul terminator, which will be re-used for the ':' */
540 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
541 if (!auth_data)
542 return FALSE;
544 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
545 auth_data[userlen] = ':';
546 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
548 pAuthInfo->auth_data = auth_data;
549 pAuthInfo->auth_data_len = userlen + 1 + passlen;
550 pAuthInfo->finished = TRUE;
552 return TRUE;
554 else
556 LPCWSTR pszAuthData;
557 SecBufferDesc out_desc, in_desc;
558 SecBuffer out, in;
559 unsigned char *buffer;
560 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
561 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
563 in.BufferType = SECBUFFER_TOKEN;
564 in.cbBuffer = 0;
565 in.pvBuffer = NULL;
567 in_desc.ulVersion = 0;
568 in_desc.cBuffers = 1;
569 in_desc.pBuffers = &in;
571 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
572 if (*pszAuthData == ' ')
574 pszAuthData++;
575 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
576 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
577 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
580 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
582 out.BufferType = SECBUFFER_TOKEN;
583 out.cbBuffer = pAuthInfo->max_token;
584 out.pvBuffer = buffer;
586 out_desc.ulVersion = 0;
587 out_desc.cBuffers = 1;
588 out_desc.pBuffers = &out;
590 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
591 first ? NULL : &pAuthInfo->ctx,
592 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
593 context_req, 0, SECURITY_NETWORK_DREP,
594 in.pvBuffer ? &in_desc : NULL,
595 0, &pAuthInfo->ctx, &out_desc,
596 &pAuthInfo->attr, &pAuthInfo->exp);
597 if (sec_status == SEC_E_OK)
599 pAuthInfo->finished = TRUE;
600 pAuthInfo->auth_data = out.pvBuffer;
601 pAuthInfo->auth_data_len = out.cbBuffer;
602 TRACE("sending last auth packet\n");
604 else if (sec_status == SEC_I_CONTINUE_NEEDED)
606 pAuthInfo->auth_data = out.pvBuffer;
607 pAuthInfo->auth_data_len = out.cbBuffer;
608 TRACE("sending next auth packet\n");
610 else
612 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
613 pAuthInfo->finished = TRUE;
614 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
615 return FALSE;
619 return TRUE;
622 /***********************************************************************
623 * HTTP_HttpAddRequestHeadersW (internal)
625 static BOOL HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
626 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
628 LPWSTR lpszStart;
629 LPWSTR lpszEnd;
630 LPWSTR buffer;
631 BOOL bSuccess = FALSE;
632 DWORD len;
634 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
636 if( dwHeaderLength == ~0U )
637 len = strlenW(lpszHeader);
638 else
639 len = dwHeaderLength;
640 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
641 lstrcpynW( buffer, lpszHeader, len + 1);
643 lpszStart = buffer;
647 LPWSTR * pFieldAndValue;
649 lpszEnd = lpszStart;
651 while (*lpszEnd != '\0')
653 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
654 break;
655 lpszEnd++;
658 if (*lpszStart == '\0')
659 break;
661 if (*lpszEnd == '\r')
663 *lpszEnd = '\0';
664 lpszEnd += 2; /* Jump over \r\n */
666 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
667 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
668 if (pFieldAndValue)
670 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
671 if (bSuccess)
672 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
673 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
674 HTTP_FreeTokens(pFieldAndValue);
677 lpszStart = lpszEnd;
678 } while (bSuccess);
680 HeapFree(GetProcessHeap(), 0, buffer);
682 return bSuccess;
685 /***********************************************************************
686 * HttpAddRequestHeadersW (WININET.@)
688 * Adds one or more HTTP header to the request handler
690 * NOTE
691 * On Windows if dwHeaderLength includes the trailing '\0', then
692 * HttpAddRequestHeadersW() adds it too. However this results in an
693 * invalid Http header which is rejected by some servers so we probably
694 * don't need to match Windows on that point.
696 * RETURNS
697 * TRUE on success
698 * FALSE on failure
701 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
702 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
704 BOOL bSuccess = FALSE;
705 LPWININETHTTPREQW lpwhr;
707 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
709 if (!lpszHeader)
710 return TRUE;
712 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
713 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
715 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
716 goto lend;
718 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
719 lend:
720 if( lpwhr )
721 WININET_Release( &lpwhr->hdr );
723 return bSuccess;
726 /***********************************************************************
727 * HttpAddRequestHeadersA (WININET.@)
729 * Adds one or more HTTP header to the request handler
731 * RETURNS
732 * TRUE on success
733 * FALSE on failure
736 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
737 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
739 DWORD len;
740 LPWSTR hdr;
741 BOOL r;
743 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
745 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
746 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
747 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
748 if( dwHeaderLength != ~0U )
749 dwHeaderLength = len;
751 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
753 HeapFree( GetProcessHeap(), 0, hdr );
755 return r;
758 /***********************************************************************
759 * HttpEndRequestA (WININET.@)
761 * Ends an HTTP request that was started by HttpSendRequestEx
763 * RETURNS
764 * TRUE if successful
765 * FALSE on failure
768 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
769 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
771 LPINTERNET_BUFFERSA ptr;
772 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
773 BOOL rc = FALSE;
775 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
776 dwContext);
778 ptr = lpBuffersOut;
779 if (ptr)
780 lpBuffersOutW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
781 sizeof(INTERNET_BUFFERSW));
782 else
783 lpBuffersOutW = NULL;
785 ptrW = lpBuffersOutW;
786 while (ptr)
788 if (ptr->lpvBuffer && ptr->dwBufferLength)
789 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
790 ptrW->dwBufferLength = ptr->dwBufferLength;
791 ptrW->dwBufferTotal= ptr->dwBufferTotal;
793 if (ptr->Next)
794 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
795 sizeof(INTERNET_BUFFERSW));
797 ptr = ptr->Next;
798 ptrW = ptrW->Next;
801 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
803 if (lpBuffersOutW)
805 ptrW = lpBuffersOutW;
806 while (ptrW)
808 LPINTERNET_BUFFERSW ptrW2;
810 FIXME("Do we need to translate info out of these buffer?\n");
812 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
813 ptrW2 = ptrW->Next;
814 HeapFree(GetProcessHeap(),0,ptrW);
815 ptrW = ptrW2;
819 return rc;
822 /***********************************************************************
823 * HttpEndRequestW (WININET.@)
825 * Ends an HTTP request that was started by HttpSendRequestEx
827 * RETURNS
828 * TRUE if successful
829 * FALSE on failure
832 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
833 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
835 BOOL rc = FALSE;
836 LPWININETHTTPREQW lpwhr;
837 INT responseLen;
838 DWORD dwBufferSize;
840 TRACE("-->\n");
841 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
843 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
845 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
846 if (lpwhr)
847 WININET_Release( &lpwhr->hdr );
848 return FALSE;
851 lpwhr->hdr.dwFlags |= dwFlags;
852 lpwhr->hdr.dwContext = dwContext;
854 /* We appear to do nothing with lpBuffersOut.. is that correct? */
856 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
857 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
859 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
860 if (responseLen)
861 rc = TRUE;
863 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
864 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
866 /* process cookies here. Is this right? */
867 HTTP_ProcessCookies(lpwhr);
869 dwBufferSize = sizeof(lpwhr->dwContentLength);
870 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
871 &lpwhr->dwContentLength,&dwBufferSize,NULL))
872 lpwhr->dwContentLength = -1;
874 if (lpwhr->dwContentLength == 0)
875 HTTP_FinishedReading(lpwhr);
877 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
879 DWORD dwCode,dwCodeLength=sizeof(DWORD);
880 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
881 (dwCode==302 || dwCode==301 || dwCode==303))
883 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
884 dwBufferSize=sizeof(szNewLocation);
885 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
887 /* redirects are always GETs */
888 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
889 lpwhr->lpszVerb = WININET_strdupW(szGET);
890 HTTP_DrainContent(lpwhr);
891 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
892 INTERNET_STATUS_REDIRECT, szNewLocation,
893 dwBufferSize);
894 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
895 if (rc)
896 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
901 WININET_Release( &lpwhr->hdr );
902 TRACE("%i <--\n",rc);
903 return rc;
906 /***********************************************************************
907 * HttpOpenRequestW (WININET.@)
909 * Open a HTTP request handle
911 * RETURNS
912 * HINTERNET a HTTP request handle on success
913 * NULL on failure
916 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
917 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
918 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
919 DWORD dwFlags, DWORD_PTR dwContext)
921 LPWININETHTTPSESSIONW lpwhs;
922 HINTERNET handle = NULL;
924 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
925 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
926 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
927 dwFlags, dwContext);
928 if(lpszAcceptTypes!=NULL)
930 int i;
931 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
932 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
935 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
936 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
938 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
939 goto lend;
943 * My tests seem to show that the windows version does not
944 * become asynchronous until after this point. And anyhow
945 * if this call was asynchronous then how would you get the
946 * necessary HINTERNET pointer returned by this function.
949 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
950 lpszVersion, lpszReferrer, lpszAcceptTypes,
951 dwFlags, dwContext);
952 lend:
953 if( lpwhs )
954 WININET_Release( &lpwhs->hdr );
955 TRACE("returning %p\n", handle);
956 return handle;
960 /***********************************************************************
961 * HttpOpenRequestA (WININET.@)
963 * Open a HTTP request handle
965 * RETURNS
966 * HINTERNET a HTTP request handle on success
967 * NULL on failure
970 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
971 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
972 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
973 DWORD dwFlags, DWORD_PTR dwContext)
975 LPWSTR szVerb = NULL, szObjectName = NULL;
976 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
977 INT len, acceptTypesCount;
978 HINTERNET rc = FALSE;
979 LPCSTR *types;
981 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
982 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
983 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
984 dwFlags, dwContext);
986 if (lpszVerb)
988 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
989 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
990 if ( !szVerb )
991 goto end;
992 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
995 if (lpszObjectName)
997 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
998 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
999 if ( !szObjectName )
1000 goto end;
1001 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
1004 if (lpszVersion)
1006 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
1007 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1008 if ( !szVersion )
1009 goto end;
1010 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
1013 if (lpszReferrer)
1015 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1016 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1017 if ( !szReferrer )
1018 goto end;
1019 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1022 if (lpszAcceptTypes)
1024 acceptTypesCount = 0;
1025 types = lpszAcceptTypes;
1026 while (*types)
1028 __TRY
1030 /* find out how many there are */
1031 if (*types && **types)
1033 TRACE("accept type: %s\n", debugstr_a(*types));
1034 acceptTypesCount++;
1037 __EXCEPT_PAGE_FAULT
1039 WARN("invalid accept type pointer\n");
1041 __ENDTRY;
1042 types++;
1044 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1045 if (!szAcceptTypes) goto end;
1047 acceptTypesCount = 0;
1048 types = lpszAcceptTypes;
1049 while (*types)
1051 __TRY
1053 if (*types && **types)
1055 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1056 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1058 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1059 acceptTypesCount++;
1062 __EXCEPT_PAGE_FAULT
1064 /* ignore invalid pointer */
1066 __ENDTRY;
1067 types++;
1069 szAcceptTypes[acceptTypesCount] = NULL;
1072 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1073 szVersion, szReferrer,
1074 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1076 end:
1077 if (szAcceptTypes)
1079 acceptTypesCount = 0;
1080 while (szAcceptTypes[acceptTypesCount])
1082 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1083 acceptTypesCount++;
1085 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1087 HeapFree(GetProcessHeap(), 0, szReferrer);
1088 HeapFree(GetProcessHeap(), 0, szVersion);
1089 HeapFree(GetProcessHeap(), 0, szObjectName);
1090 HeapFree(GetProcessHeap(), 0, szVerb);
1092 return rc;
1095 /***********************************************************************
1096 * HTTP_EncodeBase64
1098 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1100 UINT n = 0, x;
1101 static const CHAR HTTP_Base64Enc[] =
1102 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1104 while( len > 0 )
1106 /* first 6 bits, all from bin[0] */
1107 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1108 x = (bin[0] & 3) << 4;
1110 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1111 if( len == 1 )
1113 base64[n++] = HTTP_Base64Enc[x];
1114 base64[n++] = '=';
1115 base64[n++] = '=';
1116 break;
1118 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1119 x = ( bin[1] & 0x0f ) << 2;
1121 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1122 if( len == 2 )
1124 base64[n++] = HTTP_Base64Enc[x];
1125 base64[n++] = '=';
1126 break;
1128 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1130 /* last 6 bits, all from bin [2] */
1131 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1132 bin += 3;
1133 len -= 3;
1135 base64[n] = 0;
1136 return n;
1139 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1140 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1141 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1142 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1143 static const signed char HTTP_Base64Dec[256] =
1145 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1146 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1147 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1148 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1149 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1150 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1151 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1152 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1153 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1154 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1155 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1156 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1157 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1158 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1159 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1160 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1161 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1162 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1163 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1164 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1165 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1166 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1167 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1168 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1169 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1170 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1172 #undef CH
1174 /***********************************************************************
1175 * HTTP_DecodeBase64
1177 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1179 unsigned int n = 0;
1181 while(*base64)
1183 signed char in[4];
1185 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1186 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1187 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1188 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1190 WARN("invalid base64: %s\n", debugstr_w(base64));
1191 return 0;
1193 if (bin)
1194 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1195 n++;
1197 if ((base64[2] == '=') && (base64[3] == '='))
1198 break;
1199 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1200 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1202 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1203 return 0;
1205 if (bin)
1206 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1207 n++;
1209 if (base64[3] == '=')
1210 break;
1211 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1212 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1214 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1215 return 0;
1217 if (bin)
1218 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1219 n++;
1221 base64 += 4;
1224 return n;
1227 /***********************************************************************
1228 * HTTP_InsertAuthorization
1230 * Insert or delete the authorization field in the request header.
1232 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1234 if (pAuthInfo)
1236 static const WCHAR wszSpace[] = {' ',0};
1237 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1238 unsigned int len;
1239 WCHAR *authorization = NULL;
1241 if (pAuthInfo->auth_data_len)
1243 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1244 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1245 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1246 if (!authorization)
1247 return FALSE;
1249 strcpyW(authorization, pAuthInfo->scheme);
1250 strcatW(authorization, wszSpace);
1251 HTTP_EncodeBase64(pAuthInfo->auth_data,
1252 pAuthInfo->auth_data_len,
1253 authorization+strlenW(authorization));
1255 /* clear the data as it isn't valid now that it has been sent to the
1256 * server, unless it's Basic authentication which doesn't do
1257 * connection tracking */
1258 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1260 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1261 pAuthInfo->auth_data = NULL;
1262 pAuthInfo->auth_data_len = 0;
1266 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1268 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1270 HeapFree(GetProcessHeap(), 0, authorization);
1272 return TRUE;
1275 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1277 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1278 DWORD size;
1280 size = sizeof(new_location);
1281 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1283 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1284 strcpyW( url, new_location );
1286 else
1288 static const WCHAR slash[] = { '/',0 };
1289 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1290 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1291 WININETHTTPSESSIONW *session = req->lpHttpSession;
1293 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1294 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1296 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1298 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1299 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1300 else
1301 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1302 if (req->lpszPath[0] != '/') strcatW( url, slash );
1303 strcatW( url, req->lpszPath );
1305 TRACE("url=%s\n", debugstr_w(url));
1306 return url;
1309 /***********************************************************************
1310 * HTTP_DealWithProxy
1312 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1313 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1315 WCHAR buf[MAXHOSTNAME];
1316 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1317 static WCHAR szNul[] = { 0 };
1318 URL_COMPONENTSW UrlComponents;
1319 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1320 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1322 memset( &UrlComponents, 0, sizeof UrlComponents );
1323 UrlComponents.dwStructSize = sizeof UrlComponents;
1324 UrlComponents.lpszHostName = buf;
1325 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1327 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1328 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1329 sprintfW(proxy, szFormat, hIC->lpszProxy);
1330 else
1331 strcpyW(proxy, hIC->lpszProxy);
1332 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1333 return FALSE;
1334 if( UrlComponents.dwHostNameLength == 0 )
1335 return FALSE;
1337 if( !lpwhr->lpszPath )
1338 lpwhr->lpszPath = szNul;
1340 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1341 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1343 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1344 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1345 lpwhs->nServerPort = UrlComponents.nPort;
1347 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1348 return TRUE;
1351 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1353 char szaddr[32];
1354 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1356 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1357 INTERNET_STATUS_RESOLVING_NAME,
1358 lpwhs->lpszServerName,
1359 strlenW(lpwhs->lpszServerName)+1);
1361 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1362 &lpwhs->socketAddress))
1364 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1365 return FALSE;
1368 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1369 szaddr, sizeof(szaddr));
1370 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1371 INTERNET_STATUS_NAME_RESOLVED,
1372 szaddr, strlen(szaddr)+1);
1374 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1375 return TRUE;
1379 /***********************************************************************
1380 * HTTPREQ_Destroy (internal)
1382 * Deallocate request handle
1385 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1387 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1388 DWORD i;
1390 TRACE("\n");
1392 if(lpwhr->hCacheFile)
1393 CloseHandle(lpwhr->hCacheFile);
1395 if(lpwhr->lpszCacheFile) {
1396 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1397 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1400 WININET_Release(&lpwhr->lpHttpSession->hdr);
1402 if (lpwhr->pAuthInfo)
1404 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1405 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1406 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1407 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1409 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1410 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1411 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1412 lpwhr->pAuthInfo = NULL;
1415 if (lpwhr->pProxyAuthInfo)
1417 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1418 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1419 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1420 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1422 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1423 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1424 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1425 lpwhr->pProxyAuthInfo = NULL;
1428 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1429 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1430 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1431 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1432 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1434 for (i = 0; i < lpwhr->nCustHeaders; i++)
1436 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1437 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1440 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1441 HeapFree(GetProcessHeap(), 0, lpwhr);
1444 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1446 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1448 TRACE("%p\n",lpwhr);
1450 if (!NETCON_connected(&lpwhr->netConnection))
1451 return;
1453 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1454 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1456 NETCON_close(&lpwhr->netConnection);
1458 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1459 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1462 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1464 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1466 switch(option) {
1467 case INTERNET_OPTION_HANDLE_TYPE:
1468 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1470 if (*size < sizeof(ULONG))
1471 return ERROR_INSUFFICIENT_BUFFER;
1473 *size = sizeof(DWORD);
1474 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1475 return ERROR_SUCCESS;
1477 case INTERNET_OPTION_URL: {
1478 WCHAR url[INTERNET_MAX_URL_LENGTH];
1479 HTTPHEADERW *host;
1480 DWORD len;
1481 WCHAR *pch;
1483 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1484 static const WCHAR hostW[] = {'H','o','s','t',0};
1486 TRACE("INTERNET_OPTION_URL\n");
1488 host = HTTP_GetHeader(req, hostW);
1489 strcpyW(url, httpW);
1490 strcatW(url, host->lpszValue);
1491 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1492 *pch = 0;
1493 strcatW(url, req->lpszPath);
1495 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1497 if(unicode) {
1498 len = (strlenW(url)+1) * sizeof(WCHAR);
1499 if(*size < len)
1500 return ERROR_INSUFFICIENT_BUFFER;
1502 *size = len;
1503 strcpyW(buffer, url);
1504 return ERROR_SUCCESS;
1505 }else {
1506 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1507 if(len > *size)
1508 return ERROR_INSUFFICIENT_BUFFER;
1510 *size = len;
1511 return ERROR_SUCCESS;
1515 case INTERNET_OPTION_DATAFILE_NAME: {
1516 DWORD req_size;
1518 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1520 if(!req->lpszCacheFile) {
1521 *size = 0;
1522 return ERROR_INTERNET_ITEM_NOT_FOUND;
1525 if(unicode) {
1526 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1527 if(*size < req_size)
1528 return ERROR_INSUFFICIENT_BUFFER;
1530 *size = req_size;
1531 memcpy(buffer, req->lpszCacheFile, *size);
1532 return ERROR_SUCCESS;
1533 }else {
1534 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1535 if (req_size > *size)
1536 return ERROR_INSUFFICIENT_BUFFER;
1538 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1539 -1, buffer, *size, NULL, NULL);
1540 return ERROR_SUCCESS;
1544 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1545 PCCERT_CONTEXT context;
1547 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1548 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1549 return ERROR_INSUFFICIENT_BUFFER;
1552 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1553 if(context) {
1554 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1555 DWORD len;
1557 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1558 info->ftExpiry = context->pCertInfo->NotAfter;
1559 info->ftStart = context->pCertInfo->NotBefore;
1560 if(unicode) {
1561 len = CertNameToStrW(context->dwCertEncodingType,
1562 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1563 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1564 if(info->lpszSubjectInfo)
1565 CertNameToStrW(context->dwCertEncodingType,
1566 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1567 info->lpszSubjectInfo, len);
1568 len = CertNameToStrW(context->dwCertEncodingType,
1569 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1570 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1571 if (info->lpszIssuerInfo)
1572 CertNameToStrW(context->dwCertEncodingType,
1573 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1574 info->lpszIssuerInfo, len);
1575 }else {
1576 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1578 len = CertNameToStrA(context->dwCertEncodingType,
1579 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1580 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1581 if(infoA->lpszSubjectInfo)
1582 CertNameToStrA(context->dwCertEncodingType,
1583 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1584 infoA->lpszSubjectInfo, len);
1585 len = CertNameToStrA(context->dwCertEncodingType,
1586 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1587 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1588 if(infoA->lpszIssuerInfo)
1589 CertNameToStrA(context->dwCertEncodingType,
1590 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1591 infoA->lpszIssuerInfo, len);
1595 * Contrary to MSDN, these do not appear to be set.
1596 * lpszProtocolName
1597 * lpszSignatureAlgName
1598 * lpszEncryptionAlgName
1599 * dwKeySize
1601 CertFreeCertificateContext(context);
1602 return ERROR_SUCCESS;
1607 return INET_QueryOption(option, buffer, size, unicode);
1610 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1612 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1614 switch(option) {
1615 case INTERNET_OPTION_SEND_TIMEOUT:
1616 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1617 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1619 if (size != sizeof(DWORD))
1620 return ERROR_INVALID_PARAMETER;
1622 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1623 *(DWORD*)buffer);
1625 case INTERNET_OPTION_USERNAME:
1626 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1627 if (!(req->lpHttpSession->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1628 return ERROR_SUCCESS;
1630 case INTERNET_OPTION_PASSWORD:
1631 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1632 if (!(req->lpHttpSession->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1633 return ERROR_SUCCESS;
1636 return ERROR_INTERNET_INVALID_OPTION;
1639 static void HTTP_ReceiveRequestData(WININETHTTPREQW *req)
1641 INTERNET_ASYNC_RESULT iar;
1642 BYTE buffer[4096];
1643 BOOL res;
1645 TRACE("%p\n", req);
1647 res = NETCON_recv(&req->netConnection, buffer,
1648 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1649 MSG_PEEK, (int *)&iar.dwError);
1651 if(res) {
1652 iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
1653 }else {
1654 iar.dwResult = 0;
1655 iar.dwError = INTERNET_GetLastError();
1658 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1659 sizeof(INTERNET_ASYNC_RESULT));
1662 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1664 int bytes_read;
1666 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1667 sync ? MSG_WAITALL : 0, &bytes_read)) {
1668 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1669 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1671 /* always return success, even if the network layer returns an error */
1672 *read = 0;
1673 HTTP_FinishedReading(req);
1674 return ERROR_SUCCESS;
1677 req->dwContentRead += bytes_read;
1678 *read = bytes_read;
1680 if(req->lpszCacheFile) {
1681 BOOL res;
1682 DWORD dwBytesWritten;
1684 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1685 if(!res)
1686 WARN("WriteFile failed: %u\n", GetLastError());
1689 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1690 HTTP_FinishedReading(req);
1692 return ERROR_SUCCESS;
1695 static DWORD get_chunk_size(const char *buffer)
1697 const char *p;
1698 DWORD size = 0;
1700 for (p = buffer; *p; p++)
1702 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1703 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1704 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1705 else if (*p == ';') break;
1707 return size;
1710 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1712 char reply[MAX_REPLY_LEN], *p = buffer;
1713 DWORD buflen, to_read, to_write = size;
1714 int bytes_read;
1716 *read = 0;
1717 for (;;)
1719 if (*read == size) break;
1721 if (req->dwContentLength == ~0u) /* new chunk */
1723 buflen = sizeof(reply);
1724 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1726 if (!(req->dwContentLength = get_chunk_size(reply)))
1728 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1729 HTTP_GetResponseHeaders(req, FALSE);
1730 break;
1733 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1735 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1737 if (bytes_read != to_read)
1738 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1740 /* always return success, even if the network layer returns an error */
1741 *read = 0;
1742 break;
1744 if (!bytes_read) break;
1746 req->dwContentRead += bytes_read;
1747 to_write -= bytes_read;
1748 *read += bytes_read;
1750 if (req->lpszCacheFile)
1752 DWORD dwBytesWritten;
1754 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1755 WARN("WriteFile failed: %u\n", GetLastError());
1757 p += bytes_read;
1759 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1761 req->dwContentRead = 0;
1762 req->dwContentLength = ~0u;
1764 buflen = sizeof(reply);
1765 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1767 ERR("Malformed chunk\n");
1768 *read = 0;
1769 break;
1773 if (!*read) HTTP_FinishedReading(req);
1774 return ERROR_SUCCESS;
1777 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1779 WCHAR encoding[20];
1780 DWORD buflen = sizeof(encoding);
1781 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1783 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1784 !strcmpiW(encoding, szChunked))
1786 return HTTP_ReadChunked(req, buffer, size, read, sync);
1788 else
1789 return HTTP_Read(req, buffer, size, read, sync);
1792 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1794 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1795 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1798 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1800 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1801 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1802 INTERNET_ASYNC_RESULT iar;
1803 DWORD res;
1805 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1807 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1808 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1810 iar.dwResult = res == ERROR_SUCCESS;
1811 iar.dwError = res;
1813 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1814 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1815 sizeof(INTERNET_ASYNC_RESULT));
1818 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1819 DWORD flags, DWORD_PTR context)
1822 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1823 DWORD res;
1825 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1826 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1828 if (buffers->dwStructSize != sizeof(*buffers))
1829 return ERROR_INVALID_PARAMETER;
1831 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1833 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1834 DWORD available = 0;
1836 NETCON_query_data_available(&req->netConnection, &available);
1837 if (!available)
1839 WORKREQUEST workRequest;
1841 workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1842 workRequest.hdr = WININET_AddRef(&req->hdr);
1843 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1845 INTERNET_AsyncCall(&workRequest);
1847 return ERROR_IO_PENDING;
1851 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1852 !(flags & IRF_NO_WAIT));
1854 if (res == ERROR_SUCCESS) {
1855 DWORD size = buffers->dwBufferLength;
1856 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1857 &size, sizeof(size));
1860 return res;
1863 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1865 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1867 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1870 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1872 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1874 HTTP_ReceiveRequestData(req);
1877 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1879 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1880 BYTE buffer[4048];
1881 BOOL async;
1883 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1885 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1886 return ERROR_SUCCESS;
1888 /* Even if we are in async mode, we need to determine whether
1889 * there is actually more data available. We do this by trying
1890 * to peek only a single byte in async mode. */
1891 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1893 if (NETCON_recv(&req->netConnection, buffer,
1894 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1895 MSG_PEEK, (int *)available) && async && *available)
1897 WORKREQUEST workRequest;
1899 *available = 0;
1900 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1901 workRequest.hdr = WININET_AddRef( &req->hdr );
1903 INTERNET_AsyncCall(&workRequest);
1905 return ERROR_IO_PENDING;
1908 return ERROR_SUCCESS;
1911 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1912 HTTPREQ_Destroy,
1913 HTTPREQ_CloseConnection,
1914 HTTPREQ_QueryOption,
1915 HTTPREQ_SetOption,
1916 HTTPREQ_ReadFile,
1917 HTTPREQ_ReadFileExA,
1918 HTTPREQ_WriteFile,
1919 HTTPREQ_QueryDataAvailable,
1920 NULL
1923 /***********************************************************************
1924 * HTTP_HttpOpenRequestW (internal)
1926 * Open a HTTP request handle
1928 * RETURNS
1929 * HINTERNET a HTTP request handle on success
1930 * NULL on failure
1933 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1934 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1935 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1936 DWORD dwFlags, DWORD_PTR dwContext)
1938 LPWININETAPPINFOW hIC = NULL;
1939 LPWININETHTTPREQW lpwhr;
1940 LPWSTR lpszHostName = NULL;
1941 HINTERNET handle = NULL;
1942 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1943 DWORD len;
1945 TRACE("-->\n");
1947 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1948 hIC = lpwhs->lpAppInfo;
1950 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1951 if (NULL == lpwhr)
1953 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1954 goto lend;
1956 lpwhr->hdr.htype = WH_HHTTPREQ;
1957 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1958 lpwhr->hdr.dwFlags = dwFlags;
1959 lpwhr->hdr.dwContext = dwContext;
1960 lpwhr->hdr.refs = 1;
1961 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1962 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1964 WININET_AddRef( &lpwhs->hdr );
1965 lpwhr->lpHttpSession = lpwhs;
1966 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1968 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
1969 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
1970 if (NULL == lpszHostName)
1972 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1973 goto lend;
1976 handle = WININET_AllocHandle( &lpwhr->hdr );
1977 if (NULL == handle)
1979 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1980 goto lend;
1983 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1985 InternetCloseHandle( handle );
1986 handle = NULL;
1987 goto lend;
1990 if (lpszObjectName && *lpszObjectName) {
1991 HRESULT rc;
1993 len = 0;
1994 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1995 if (rc != E_POINTER)
1996 len = strlenW(lpszObjectName)+1;
1997 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1998 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1999 URL_ESCAPE_SPACES_ONLY);
2000 if (rc != S_OK)
2002 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2003 strcpyW(lpwhr->lpszPath,lpszObjectName);
2007 if (lpszReferrer && *lpszReferrer)
2008 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2010 if (lpszAcceptTypes)
2012 int i;
2013 for (i = 0; lpszAcceptTypes[i]; i++)
2015 if (!*lpszAcceptTypes[i]) continue;
2016 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2017 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
2018 HTTP_ADDHDR_FLAG_REQ |
2019 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
2023 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
2025 if (lpszVersion)
2026 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
2027 else
2028 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
2030 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
2031 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
2032 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
2034 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2035 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
2036 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2038 else
2039 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
2040 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2042 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2043 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2044 INTERNET_DEFAULT_HTTPS_PORT :
2045 INTERNET_DEFAULT_HTTP_PORT);
2047 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2048 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2049 INTERNET_DEFAULT_HTTPS_PORT :
2050 INTERNET_DEFAULT_HTTP_PORT);
2052 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2053 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2055 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2056 INTERNET_STATUS_HANDLE_CREATED, &handle,
2057 sizeof(handle));
2059 lend:
2060 HeapFree(GetProcessHeap(), 0, lpszHostName);
2061 if( lpwhr )
2062 WININET_Release( &lpwhr->hdr );
2064 TRACE("<-- %p (%p)\n", handle, lpwhr);
2065 return handle;
2068 /* read any content returned by the server so that the connection can be
2069 * reused */
2070 static void HTTP_DrainContent(WININETHTTPREQW *req)
2072 DWORD bytes_read;
2074 if (!NETCON_connected(&req->netConnection)) return;
2076 if (req->dwContentLength == -1)
2077 NETCON_close(&req->netConnection);
2081 char buffer[2048];
2082 if (HTTP_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2083 return;
2084 } while (bytes_read);
2087 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2088 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2089 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2090 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2091 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2092 static const WCHAR szAge[] = { 'A','g','e',0 };
2093 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2094 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2095 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2096 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2097 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2098 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2099 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2100 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2101 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2102 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2103 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2104 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 };
2105 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2106 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2107 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2108 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2109 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2110 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2111 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2112 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2113 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2114 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2115 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2116 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2117 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2118 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2119 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2120 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2121 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2122 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2123 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2124 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2125 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2126 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2127 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2128 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2129 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2130 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2131 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 };
2132 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2133 static const WCHAR szURI[] = { 'U','R','I',0 };
2134 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2135 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2136 static const WCHAR szVia[] = { 'V','i','a',0 };
2137 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2138 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2140 static const LPCWSTR header_lookup[] = {
2141 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2142 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2143 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2144 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2145 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2146 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2147 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2148 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2149 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2150 szDate, /* HTTP_QUERY_DATE = 9 */
2151 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2152 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2153 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2154 szURI, /* HTTP_QUERY_URI = 13 */
2155 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2156 NULL, /* HTTP_QUERY_COST = 15 */
2157 NULL, /* HTTP_QUERY_LINK = 16 */
2158 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2159 NULL, /* HTTP_QUERY_VERSION = 18 */
2160 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2161 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2162 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2163 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2164 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2165 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2166 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2167 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2168 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2169 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2170 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2171 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2172 NULL, /* HTTP_QUERY_FROM = 31 */
2173 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2174 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2175 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2176 szReferer, /* HTTP_QUERY_REFERER = 35 */
2177 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2178 szServer, /* HTTP_QUERY_SERVER = 37 */
2179 NULL, /* HTTP_TITLE = 38 */
2180 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2181 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2182 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2183 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2184 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2185 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2186 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2187 NULL, /* HTTP_QUERY_REFRESH = 46 */
2188 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2189 szAge, /* HTTP_QUERY_AGE = 48 */
2190 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2191 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2192 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2193 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2194 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2195 szETag, /* HTTP_QUERY_ETAG = 54 */
2196 szHost, /* HTTP_QUERY_HOST = 55 */
2197 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2198 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2199 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2200 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2201 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2202 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2203 szRange, /* HTTP_QUERY_RANGE = 62 */
2204 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2205 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2206 szVary, /* HTTP_QUERY_VARY = 65 */
2207 szVia, /* HTTP_QUERY_VIA = 66 */
2208 szWarning, /* HTTP_QUERY_WARNING = 67 */
2209 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2210 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2211 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2214 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2216 /***********************************************************************
2217 * HTTP_HttpQueryInfoW (internal)
2219 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2220 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2222 LPHTTPHEADERW lphttpHdr = NULL;
2223 BOOL bSuccess = FALSE;
2224 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2225 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2226 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2227 INT index = -1;
2229 /* Find requested header structure */
2230 switch (level)
2232 case HTTP_QUERY_CUSTOM:
2233 if (!lpBuffer) return FALSE;
2234 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2235 break;
2237 case HTTP_QUERY_RAW_HEADERS_CRLF:
2239 LPWSTR headers;
2240 DWORD len = 0;
2241 BOOL ret = FALSE;
2243 if (request_only)
2244 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2245 else
2246 headers = lpwhr->lpszRawHeaders;
2248 if (headers)
2249 len = strlenW(headers) * sizeof(WCHAR);
2251 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2253 len += sizeof(WCHAR);
2254 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2255 ret = FALSE;
2257 else if (lpBuffer)
2259 if (headers)
2260 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2261 else
2263 len = strlenW(szCrLf) * sizeof(WCHAR);
2264 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2266 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2267 ret = TRUE;
2269 *lpdwBufferLength = len;
2271 if (request_only)
2272 HeapFree(GetProcessHeap(), 0, headers);
2273 return ret;
2275 case HTTP_QUERY_RAW_HEADERS:
2277 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2278 DWORD i, size = 0;
2279 LPWSTR pszString = lpBuffer;
2281 for (i = 0; ppszRawHeaderLines[i]; i++)
2282 size += strlenW(ppszRawHeaderLines[i]) + 1;
2284 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2286 HTTP_FreeTokens(ppszRawHeaderLines);
2287 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2288 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2289 return FALSE;
2291 if (pszString)
2293 for (i = 0; ppszRawHeaderLines[i]; i++)
2295 DWORD len = strlenW(ppszRawHeaderLines[i]);
2296 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2297 pszString += len+1;
2299 *pszString = '\0';
2300 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2302 *lpdwBufferLength = size * sizeof(WCHAR);
2303 HTTP_FreeTokens(ppszRawHeaderLines);
2305 return TRUE;
2307 case HTTP_QUERY_STATUS_TEXT:
2308 if (lpwhr->lpszStatusText)
2310 DWORD len = strlenW(lpwhr->lpszStatusText);
2311 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2313 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2314 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2315 return FALSE;
2317 if (lpBuffer)
2319 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2320 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2322 *lpdwBufferLength = len * sizeof(WCHAR);
2323 return TRUE;
2325 break;
2326 case HTTP_QUERY_VERSION:
2327 if (lpwhr->lpszVersion)
2329 DWORD len = strlenW(lpwhr->lpszVersion);
2330 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2332 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2333 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2334 return FALSE;
2336 if (lpBuffer)
2338 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2339 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2341 *lpdwBufferLength = len * sizeof(WCHAR);
2342 return TRUE;
2344 break;
2345 default:
2346 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2348 if (level < LAST_TABLE_HEADER && header_lookup[level])
2349 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2350 requested_index,request_only);
2353 if (index >= 0)
2354 lphttpHdr = &lpwhr->pCustHeaders[index];
2356 /* Ensure header satisfies requested attributes */
2357 if (!lphttpHdr ||
2358 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2359 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2361 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2362 return bSuccess;
2365 if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2367 /* coalesce value to requested type */
2368 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2370 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2371 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2372 bSuccess = TRUE;
2374 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2376 time_t tmpTime;
2377 struct tm tmpTM;
2378 SYSTEMTIME *STHook;
2380 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2382 tmpTM = *gmtime(&tmpTime);
2383 STHook = (SYSTEMTIME *)lpBuffer;
2384 STHook->wDay = tmpTM.tm_mday;
2385 STHook->wHour = tmpTM.tm_hour;
2386 STHook->wMilliseconds = 0;
2387 STHook->wMinute = tmpTM.tm_min;
2388 STHook->wDayOfWeek = tmpTM.tm_wday;
2389 STHook->wMonth = tmpTM.tm_mon + 1;
2390 STHook->wSecond = tmpTM.tm_sec;
2391 STHook->wYear = tmpTM.tm_year;
2392 bSuccess = TRUE;
2394 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2395 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2396 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2398 else if (lphttpHdr->lpszValue)
2400 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2402 if (len > *lpdwBufferLength)
2404 *lpdwBufferLength = len;
2405 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2406 return bSuccess;
2408 if (lpBuffer)
2410 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2411 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2413 *lpdwBufferLength = len - sizeof(WCHAR);
2414 bSuccess = TRUE;
2416 return bSuccess;
2419 /***********************************************************************
2420 * HttpQueryInfoW (WININET.@)
2422 * Queries for information about an HTTP request
2424 * RETURNS
2425 * TRUE on success
2426 * FALSE on failure
2429 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2430 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2432 BOOL bSuccess = FALSE;
2433 LPWININETHTTPREQW lpwhr;
2435 if (TRACE_ON(wininet)) {
2436 #define FE(x) { x, #x }
2437 static const wininet_flag_info query_flags[] = {
2438 FE(HTTP_QUERY_MIME_VERSION),
2439 FE(HTTP_QUERY_CONTENT_TYPE),
2440 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2441 FE(HTTP_QUERY_CONTENT_ID),
2442 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2443 FE(HTTP_QUERY_CONTENT_LENGTH),
2444 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2445 FE(HTTP_QUERY_ALLOW),
2446 FE(HTTP_QUERY_PUBLIC),
2447 FE(HTTP_QUERY_DATE),
2448 FE(HTTP_QUERY_EXPIRES),
2449 FE(HTTP_QUERY_LAST_MODIFIED),
2450 FE(HTTP_QUERY_MESSAGE_ID),
2451 FE(HTTP_QUERY_URI),
2452 FE(HTTP_QUERY_DERIVED_FROM),
2453 FE(HTTP_QUERY_COST),
2454 FE(HTTP_QUERY_LINK),
2455 FE(HTTP_QUERY_PRAGMA),
2456 FE(HTTP_QUERY_VERSION),
2457 FE(HTTP_QUERY_STATUS_CODE),
2458 FE(HTTP_QUERY_STATUS_TEXT),
2459 FE(HTTP_QUERY_RAW_HEADERS),
2460 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2461 FE(HTTP_QUERY_CONNECTION),
2462 FE(HTTP_QUERY_ACCEPT),
2463 FE(HTTP_QUERY_ACCEPT_CHARSET),
2464 FE(HTTP_QUERY_ACCEPT_ENCODING),
2465 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2466 FE(HTTP_QUERY_AUTHORIZATION),
2467 FE(HTTP_QUERY_CONTENT_ENCODING),
2468 FE(HTTP_QUERY_FORWARDED),
2469 FE(HTTP_QUERY_FROM),
2470 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2471 FE(HTTP_QUERY_LOCATION),
2472 FE(HTTP_QUERY_ORIG_URI),
2473 FE(HTTP_QUERY_REFERER),
2474 FE(HTTP_QUERY_RETRY_AFTER),
2475 FE(HTTP_QUERY_SERVER),
2476 FE(HTTP_QUERY_TITLE),
2477 FE(HTTP_QUERY_USER_AGENT),
2478 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2479 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2480 FE(HTTP_QUERY_ACCEPT_RANGES),
2481 FE(HTTP_QUERY_SET_COOKIE),
2482 FE(HTTP_QUERY_COOKIE),
2483 FE(HTTP_QUERY_REQUEST_METHOD),
2484 FE(HTTP_QUERY_REFRESH),
2485 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2486 FE(HTTP_QUERY_AGE),
2487 FE(HTTP_QUERY_CACHE_CONTROL),
2488 FE(HTTP_QUERY_CONTENT_BASE),
2489 FE(HTTP_QUERY_CONTENT_LOCATION),
2490 FE(HTTP_QUERY_CONTENT_MD5),
2491 FE(HTTP_QUERY_CONTENT_RANGE),
2492 FE(HTTP_QUERY_ETAG),
2493 FE(HTTP_QUERY_HOST),
2494 FE(HTTP_QUERY_IF_MATCH),
2495 FE(HTTP_QUERY_IF_NONE_MATCH),
2496 FE(HTTP_QUERY_IF_RANGE),
2497 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2498 FE(HTTP_QUERY_MAX_FORWARDS),
2499 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2500 FE(HTTP_QUERY_RANGE),
2501 FE(HTTP_QUERY_TRANSFER_ENCODING),
2502 FE(HTTP_QUERY_UPGRADE),
2503 FE(HTTP_QUERY_VARY),
2504 FE(HTTP_QUERY_VIA),
2505 FE(HTTP_QUERY_WARNING),
2506 FE(HTTP_QUERY_CUSTOM)
2508 static const wininet_flag_info modifier_flags[] = {
2509 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2510 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2511 FE(HTTP_QUERY_FLAG_NUMBER),
2512 FE(HTTP_QUERY_FLAG_COALESCE)
2514 #undef FE
2515 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2516 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2517 DWORD i;
2519 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2520 TRACE(" Attribute:");
2521 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2522 if (query_flags[i].val == info) {
2523 TRACE(" %s", query_flags[i].name);
2524 break;
2527 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2528 TRACE(" Unknown (%08x)", info);
2531 TRACE(" Modifier:");
2532 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2533 if (modifier_flags[i].val & info_mod) {
2534 TRACE(" %s", modifier_flags[i].name);
2535 info_mod &= ~ modifier_flags[i].val;
2539 if (info_mod) {
2540 TRACE(" Unknown (%08x)", info_mod);
2542 TRACE("\n");
2545 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2546 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2548 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2549 goto lend;
2552 if (lpBuffer == NULL)
2553 *lpdwBufferLength = 0;
2554 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2555 lpBuffer, lpdwBufferLength, lpdwIndex);
2557 lend:
2558 if( lpwhr )
2559 WININET_Release( &lpwhr->hdr );
2561 TRACE("%d <--\n", bSuccess);
2562 return bSuccess;
2565 /***********************************************************************
2566 * HttpQueryInfoA (WININET.@)
2568 * Queries for information about an HTTP request
2570 * RETURNS
2571 * TRUE on success
2572 * FALSE on failure
2575 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2576 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2578 BOOL result;
2579 DWORD len;
2580 WCHAR* bufferW;
2582 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2583 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2585 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2586 lpdwBufferLength, lpdwIndex );
2589 if (lpBuffer)
2591 DWORD alloclen;
2592 len = (*lpdwBufferLength)*sizeof(WCHAR);
2593 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2595 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2596 if (alloclen < len)
2597 alloclen = len;
2599 else
2600 alloclen = len;
2601 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2602 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2603 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2604 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2605 } else
2607 bufferW = NULL;
2608 len = 0;
2611 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2612 &len, lpdwIndex );
2613 if( result )
2615 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2616 lpBuffer, *lpdwBufferLength, NULL, NULL );
2617 *lpdwBufferLength = len - 1;
2619 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2621 else
2622 /* since the strings being returned from HttpQueryInfoW should be
2623 * only ASCII characters, it is reasonable to assume that all of
2624 * the Unicode characters can be reduced to a single byte */
2625 *lpdwBufferLength = len / sizeof(WCHAR);
2627 HeapFree(GetProcessHeap(), 0, bufferW );
2629 return result;
2632 /***********************************************************************
2633 * HttpSendRequestExA (WININET.@)
2635 * Sends the specified request to the HTTP server and allows chunked
2636 * transfers.
2638 * RETURNS
2639 * Success: TRUE
2640 * Failure: FALSE, call GetLastError() for more information.
2642 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2643 LPINTERNET_BUFFERSA lpBuffersIn,
2644 LPINTERNET_BUFFERSA lpBuffersOut,
2645 DWORD dwFlags, DWORD_PTR dwContext)
2647 INTERNET_BUFFERSW BuffersInW;
2648 BOOL rc = FALSE;
2649 DWORD headerlen;
2650 LPWSTR header = NULL;
2652 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2653 lpBuffersOut, dwFlags, dwContext);
2655 if (lpBuffersIn)
2657 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2658 if (lpBuffersIn->lpcszHeader)
2660 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2661 lpBuffersIn->dwHeadersLength,0,0);
2662 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2663 if (!(BuffersInW.lpcszHeader = header))
2665 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2666 return FALSE;
2668 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2669 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2670 header, headerlen);
2672 else
2673 BuffersInW.lpcszHeader = NULL;
2674 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2675 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2676 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2677 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2678 BuffersInW.Next = NULL;
2681 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2683 HeapFree(GetProcessHeap(),0,header);
2685 return rc;
2688 /***********************************************************************
2689 * HttpSendRequestExW (WININET.@)
2691 * Sends the specified request to the HTTP server and allows chunked
2692 * transfers
2694 * RETURNS
2695 * Success: TRUE
2696 * Failure: FALSE, call GetLastError() for more information.
2698 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2699 LPINTERNET_BUFFERSW lpBuffersIn,
2700 LPINTERNET_BUFFERSW lpBuffersOut,
2701 DWORD dwFlags, DWORD_PTR dwContext)
2703 BOOL ret = FALSE;
2704 LPWININETHTTPREQW lpwhr;
2705 LPWININETHTTPSESSIONW lpwhs;
2706 LPWININETAPPINFOW hIC;
2708 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2709 lpBuffersOut, dwFlags, dwContext);
2711 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2713 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2715 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2716 goto lend;
2719 lpwhs = lpwhr->lpHttpSession;
2720 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2721 hIC = lpwhs->lpAppInfo;
2722 assert(hIC->hdr.htype == WH_HINIT);
2724 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2726 WORKREQUEST workRequest;
2727 struct WORKREQ_HTTPSENDREQUESTW *req;
2729 workRequest.asyncproc = AsyncHttpSendRequestProc;
2730 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2731 req = &workRequest.u.HttpSendRequestW;
2732 if (lpBuffersIn)
2734 if (lpBuffersIn->lpcszHeader)
2735 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2736 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2737 else
2738 req->lpszHeader = NULL;
2739 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2740 req->lpOptional = lpBuffersIn->lpvBuffer;
2741 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2742 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2744 else
2746 req->lpszHeader = NULL;
2747 req->dwHeaderLength = 0;
2748 req->lpOptional = NULL;
2749 req->dwOptionalLength = 0;
2750 req->dwContentLength = 0;
2753 req->bEndRequest = FALSE;
2755 INTERNET_AsyncCall(&workRequest);
2757 * This is from windows.
2759 INTERNET_SetLastError(ERROR_IO_PENDING);
2761 else
2763 if (lpBuffersIn)
2764 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2765 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2766 lpBuffersIn->dwBufferTotal, FALSE);
2767 else
2768 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2771 lend:
2772 if ( lpwhr )
2773 WININET_Release( &lpwhr->hdr );
2775 TRACE("<---\n");
2776 return ret;
2779 /***********************************************************************
2780 * HttpSendRequestW (WININET.@)
2782 * Sends the specified request to the HTTP server
2784 * RETURNS
2785 * TRUE on success
2786 * FALSE on failure
2789 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2790 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2792 LPWININETHTTPREQW lpwhr;
2793 LPWININETHTTPSESSIONW lpwhs = NULL;
2794 LPWININETAPPINFOW hIC = NULL;
2795 BOOL r;
2797 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2798 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2800 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2801 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2803 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2804 r = FALSE;
2805 goto lend;
2808 lpwhs = lpwhr->lpHttpSession;
2809 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2811 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2812 r = FALSE;
2813 goto lend;
2816 hIC = lpwhs->lpAppInfo;
2817 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2819 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2820 r = FALSE;
2821 goto lend;
2824 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2826 WORKREQUEST workRequest;
2827 struct WORKREQ_HTTPSENDREQUESTW *req;
2829 workRequest.asyncproc = AsyncHttpSendRequestProc;
2830 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2831 req = &workRequest.u.HttpSendRequestW;
2832 if (lpszHeaders)
2834 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2835 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2837 else
2838 req->lpszHeader = 0;
2839 req->dwHeaderLength = dwHeaderLength;
2840 req->lpOptional = lpOptional;
2841 req->dwOptionalLength = dwOptionalLength;
2842 req->dwContentLength = dwOptionalLength;
2843 req->bEndRequest = TRUE;
2845 INTERNET_AsyncCall(&workRequest);
2847 * This is from windows.
2849 INTERNET_SetLastError(ERROR_IO_PENDING);
2850 r = FALSE;
2852 else
2854 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2855 dwHeaderLength, lpOptional, dwOptionalLength,
2856 dwOptionalLength, TRUE);
2858 lend:
2859 if( lpwhr )
2860 WININET_Release( &lpwhr->hdr );
2861 return r;
2864 /***********************************************************************
2865 * HttpSendRequestA (WININET.@)
2867 * Sends the specified request to the HTTP server
2869 * RETURNS
2870 * TRUE on success
2871 * FALSE on failure
2874 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2875 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2877 BOOL result;
2878 LPWSTR szHeaders=NULL;
2879 DWORD nLen=dwHeaderLength;
2880 if(lpszHeaders!=NULL)
2882 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2883 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2884 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2886 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2887 HeapFree(GetProcessHeap(),0,szHeaders);
2888 return result;
2891 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2893 LPHTTPHEADERW host_header;
2895 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2897 host_header = HTTP_GetHeader(req, szHost);
2898 if(!host_header)
2899 return FALSE;
2901 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2902 return TRUE;
2905 /***********************************************************************
2906 * HTTP_HandleRedirect (internal)
2908 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2910 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2911 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2912 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2913 WCHAR path[INTERNET_MAX_URL_LENGTH];
2914 int index;
2916 if(lpszUrl[0]=='/')
2918 /* if it's an absolute path, keep the same session info */
2919 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2921 else
2923 URL_COMPONENTSW urlComponents;
2924 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2925 static WCHAR szHttp[] = {'h','t','t','p',0};
2926 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2927 DWORD url_length = 0;
2928 LPWSTR orig_url;
2929 LPWSTR combined_url;
2931 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2932 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2933 urlComponents.dwSchemeLength = 0;
2934 urlComponents.lpszHostName = lpwhs->lpszHostName;
2935 urlComponents.dwHostNameLength = 0;
2936 urlComponents.nPort = lpwhs->nHostPort;
2937 urlComponents.lpszUserName = lpwhs->lpszUserName;
2938 urlComponents.dwUserNameLength = 0;
2939 urlComponents.lpszPassword = NULL;
2940 urlComponents.dwPasswordLength = 0;
2941 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2942 urlComponents.dwUrlPathLength = 0;
2943 urlComponents.lpszExtraInfo = NULL;
2944 urlComponents.dwExtraInfoLength = 0;
2946 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2947 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2948 return FALSE;
2950 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2952 /* convert from bytes to characters */
2953 url_length = url_length / sizeof(WCHAR) - 1;
2954 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2956 HeapFree(GetProcessHeap(), 0, orig_url);
2957 return FALSE;
2960 url_length = 0;
2961 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2962 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2964 HeapFree(GetProcessHeap(), 0, orig_url);
2965 return FALSE;
2967 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2969 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2971 HeapFree(GetProcessHeap(), 0, orig_url);
2972 HeapFree(GetProcessHeap(), 0, combined_url);
2973 return FALSE;
2975 HeapFree(GetProcessHeap(), 0, orig_url);
2977 userName[0] = 0;
2978 hostName[0] = 0;
2979 protocol[0] = 0;
2981 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2982 urlComponents.lpszScheme = protocol;
2983 urlComponents.dwSchemeLength = 32;
2984 urlComponents.lpszHostName = hostName;
2985 urlComponents.dwHostNameLength = MAXHOSTNAME;
2986 urlComponents.lpszUserName = userName;
2987 urlComponents.dwUserNameLength = 1024;
2988 urlComponents.lpszPassword = NULL;
2989 urlComponents.dwPasswordLength = 0;
2990 urlComponents.lpszUrlPath = path;
2991 urlComponents.dwUrlPathLength = 2048;
2992 urlComponents.lpszExtraInfo = NULL;
2993 urlComponents.dwExtraInfoLength = 0;
2994 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2996 HeapFree(GetProcessHeap(), 0, combined_url);
2997 return FALSE;
3000 HeapFree(GetProcessHeap(), 0, combined_url);
3002 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
3003 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3005 TRACE("redirect from secure page to non-secure page\n");
3006 /* FIXME: warn about from secure redirect to non-secure page */
3007 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
3009 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
3010 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3012 TRACE("redirect from non-secure page to secure page\n");
3013 /* FIXME: notify about redirect to secure page */
3014 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
3017 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3019 if (lstrlenW(protocol)>4) /*https*/
3020 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3021 else /*http*/
3022 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3025 #if 0
3027 * This upsets redirects to binary files on sourceforge.net
3028 * and gives an html page instead of the target file
3029 * Examination of the HTTP request sent by native wininet.dll
3030 * reveals that it doesn't send a referrer in that case.
3031 * Maybe there's a flag that enables this, or maybe a referrer
3032 * shouldn't be added in case of a redirect.
3035 /* consider the current host as the referrer */
3036 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3037 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3038 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3039 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3040 #endif
3042 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3043 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3044 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3046 int len;
3047 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3048 len = lstrlenW(hostName);
3049 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3050 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3051 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3053 else
3054 lpwhs->lpszHostName = WININET_strdupW(hostName);
3056 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3058 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3059 lpwhs->lpszUserName = NULL;
3060 if (userName[0])
3061 lpwhs->lpszUserName = WININET_strdupW(userName);
3063 if (!using_proxy)
3065 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3067 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3068 lpwhs->lpszServerName = WININET_strdupW(hostName);
3069 lpwhs->nServerPort = urlComponents.nPort;
3071 NETCON_close(&lpwhr->netConnection);
3072 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3073 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3076 else
3077 TRACE("Redirect through proxy\n");
3080 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3081 lpwhr->lpszPath=NULL;
3082 if (*path)
3084 DWORD needed = 0;
3085 HRESULT rc;
3087 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3088 if (rc != E_POINTER)
3089 needed = strlenW(path)+1;
3090 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3091 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3092 URL_ESCAPE_SPACES_ONLY);
3093 if (rc != S_OK)
3095 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3096 strcpyW(lpwhr->lpszPath,path);
3100 /* Remove custom content-type/length headers on redirects. */
3101 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
3102 if (0 <= index)
3103 HTTP_DeleteCustomHeader(lpwhr, index);
3104 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
3105 if (0 <= index)
3106 HTTP_DeleteCustomHeader(lpwhr, index);
3108 return TRUE;
3111 /***********************************************************************
3112 * HTTP_build_req (internal)
3114 * concatenate all the strings in the request together
3116 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3118 LPCWSTR *t;
3119 LPWSTR str;
3121 for( t = list; *t ; t++ )
3122 len += strlenW( *t );
3123 len++;
3125 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3126 *str = 0;
3128 for( t = list; *t ; t++ )
3129 strcatW( str, *t );
3131 return str;
3134 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3136 LPWSTR lpszPath;
3137 LPWSTR requestString;
3138 INT len;
3139 INT cnt;
3140 INT responseLen;
3141 char *ascii_req;
3142 BOOL ret;
3143 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3144 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3145 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3147 TRACE("\n");
3149 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3150 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3151 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3152 HeapFree( GetProcessHeap(), 0, lpszPath );
3154 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3155 NULL, 0, NULL, NULL );
3156 len--; /* the nul terminator isn't needed */
3157 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3158 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3159 ascii_req, len, NULL, NULL );
3160 HeapFree( GetProcessHeap(), 0, requestString );
3162 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3164 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3165 HeapFree( GetProcessHeap(), 0, ascii_req );
3166 if (!ret || cnt < 0)
3167 return FALSE;
3169 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3170 if (!responseLen)
3171 return FALSE;
3173 return TRUE;
3176 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3178 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
3179 LPWSTR lpszCookies, lpszUrl = NULL;
3180 DWORD nCookieSize, size;
3181 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3183 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm)) * sizeof(WCHAR);
3184 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3185 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
3187 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3189 int cnt = 0;
3190 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3192 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3193 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3195 cnt += sprintfW(lpszCookies, szCookie);
3196 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3197 strcatW(lpszCookies, szCrLf);
3199 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_ADD);
3200 HeapFree(GetProcessHeap(), 0, lpszCookies);
3203 HeapFree(GetProcessHeap(), 0, lpszUrl);
3206 /***********************************************************************
3207 * HTTP_HttpSendRequestW (internal)
3209 * Sends the specified request to the HTTP server
3211 * RETURNS
3212 * TRUE on success
3213 * FALSE on failure
3216 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3217 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3218 DWORD dwContentLength, BOOL bEndRequest)
3220 INT cnt;
3221 BOOL bSuccess = FALSE;
3222 LPWSTR requestString = NULL;
3223 INT responseLen;
3224 BOOL loop_next;
3225 INTERNET_ASYNC_RESULT iar;
3226 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3227 static const WCHAR szContentLength[] =
3228 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3229 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3231 TRACE("--> %p\n", lpwhr);
3233 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3235 /* if the verb is NULL default to GET */
3236 if (!lpwhr->lpszVerb)
3237 lpwhr->lpszVerb = WININET_strdupW(szGET);
3239 if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3241 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3242 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3244 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3246 WCHAR *agent_header;
3247 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3248 int len;
3250 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3251 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3252 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3254 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3255 HeapFree(GetProcessHeap(), 0, agent_header);
3257 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3259 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3260 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3262 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3264 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3265 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3266 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3271 DWORD len;
3272 char *ascii_req;
3274 loop_next = FALSE;
3276 /* like native, just in case the caller forgot to call InternetReadFile
3277 * for all the data */
3278 HTTP_DrainContent(lpwhr);
3279 lpwhr->dwContentRead = 0;
3281 if (TRACE_ON(wininet))
3283 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3284 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3287 HTTP_FixURL(lpwhr);
3288 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3290 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3292 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3293 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3295 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3296 HTTP_InsertCookies(lpwhr);
3298 /* add the headers the caller supplied */
3299 if( lpszHeaders && dwHeaderLength )
3301 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3302 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3305 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3307 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3308 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3309 HeapFree(GetProcessHeap(), 0, url);
3311 else
3312 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3315 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3317 /* Send the request and store the results */
3318 if (!HTTP_OpenConnection(lpwhr))
3319 goto lend;
3321 /* send the request as ASCII, tack on the optional data */
3322 if( !lpOptional )
3323 dwOptionalLength = 0;
3324 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3325 NULL, 0, NULL, NULL );
3326 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3327 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3328 ascii_req, len, NULL, NULL );
3329 if( lpOptional )
3330 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3331 len = (len + dwOptionalLength - 1);
3332 ascii_req[len] = 0;
3333 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3335 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3336 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3338 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3339 HeapFree( GetProcessHeap(), 0, ascii_req );
3341 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3342 INTERNET_STATUS_REQUEST_SENT,
3343 &len, sizeof(DWORD));
3345 if (bEndRequest)
3347 DWORD dwBufferSize;
3348 DWORD dwStatusCode;
3349 WCHAR encoding[20];
3350 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3352 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3353 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3355 if (cnt < 0)
3356 goto lend;
3358 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3359 if (responseLen)
3360 bSuccess = TRUE;
3362 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3363 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3364 sizeof(DWORD));
3366 HTTP_ProcessCookies(lpwhr);
3368 dwBufferSize = sizeof(lpwhr->dwContentLength);
3369 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3370 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3371 lpwhr->dwContentLength = -1;
3373 if (lpwhr->dwContentLength == 0)
3374 HTTP_FinishedReading(lpwhr);
3376 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3378 dwBufferSize = sizeof(encoding);
3379 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3380 !strcmpiW(encoding, szChunked))
3382 lpwhr->dwContentLength = -1;
3385 dwBufferSize = sizeof(dwStatusCode);
3386 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3387 &dwStatusCode,&dwBufferSize,NULL))
3388 dwStatusCode = 0;
3390 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3392 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3393 dwBufferSize=sizeof(szNewLocation);
3394 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3395 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3397 HTTP_DrainContent(lpwhr);
3398 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3399 INTERNET_STATUS_REDIRECT, szNewLocation,
3400 dwBufferSize);
3401 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3402 if (bSuccess)
3404 HeapFree(GetProcessHeap(), 0, requestString);
3405 loop_next = TRUE;
3409 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3411 WCHAR szAuthValue[2048];
3412 dwBufferSize=2048;
3413 if (dwStatusCode == HTTP_STATUS_DENIED)
3415 DWORD dwIndex = 0;
3416 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3418 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3419 &lpwhr->pAuthInfo,
3420 lpwhr->lpHttpSession->lpszUserName,
3421 lpwhr->lpHttpSession->lpszPassword))
3423 loop_next = TRUE;
3424 break;
3428 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3430 DWORD dwIndex = 0;
3431 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3433 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3434 &lpwhr->pProxyAuthInfo,
3435 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3436 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3438 loop_next = TRUE;
3439 break;
3445 else
3446 bSuccess = TRUE;
3448 while (loop_next);
3450 /* FIXME: Better check, when we have to create the cache file */
3451 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3452 WCHAR url[INTERNET_MAX_URL_LENGTH];
3453 WCHAR cacheFileName[MAX_PATH+1];
3454 BOOL b;
3456 b = HTTP_GetRequestURL(lpwhr, url);
3457 if(!b) {
3458 WARN("Could not get URL\n");
3459 goto lend;
3462 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3463 if(b) {
3464 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3465 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3466 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3467 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3468 WARN("Could not create file: %u\n", GetLastError());
3469 lpwhr->hCacheFile = NULL;
3471 }else {
3472 WARN("Could not create cache entry: %08x\n", GetLastError());
3476 lend:
3478 HeapFree(GetProcessHeap(), 0, requestString);
3480 /* TODO: send notification for P3P header */
3482 if(lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) {
3483 if(bSuccess) {
3484 HTTP_ReceiveRequestData(lpwhr);
3485 }else {
3486 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3487 iar.dwError = INTERNET_GetLastError();
3489 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3490 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3491 sizeof(INTERNET_ASYNC_RESULT));
3495 TRACE("<--\n");
3496 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3497 return bSuccess;
3500 /***********************************************************************
3501 * HTTPSESSION_Destroy (internal)
3503 * Deallocate session handle
3506 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3508 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3510 TRACE("%p\n", lpwhs);
3512 WININET_Release(&lpwhs->lpAppInfo->hdr);
3514 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3515 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3516 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3517 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3518 HeapFree(GetProcessHeap(), 0, lpwhs);
3521 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3523 switch(option) {
3524 case INTERNET_OPTION_HANDLE_TYPE:
3525 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3527 if (*size < sizeof(ULONG))
3528 return ERROR_INSUFFICIENT_BUFFER;
3530 *size = sizeof(DWORD);
3531 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3532 return ERROR_SUCCESS;
3535 return INET_QueryOption(option, buffer, size, unicode);
3538 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3540 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3542 switch(option) {
3543 case INTERNET_OPTION_USERNAME:
3545 HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
3546 if (!(ses->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3547 return ERROR_SUCCESS;
3549 case INTERNET_OPTION_PASSWORD:
3551 HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
3552 if (!(ses->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3553 return ERROR_SUCCESS;
3555 default: break;
3558 return ERROR_INTERNET_INVALID_OPTION;
3561 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3562 HTTPSESSION_Destroy,
3563 NULL,
3564 HTTPSESSION_QueryOption,
3565 HTTPSESSION_SetOption,
3566 NULL,
3567 NULL,
3568 NULL,
3569 NULL,
3570 NULL
3574 /***********************************************************************
3575 * HTTP_Connect (internal)
3577 * Create http session handle
3579 * RETURNS
3580 * HINTERNET a session handle on success
3581 * NULL on failure
3584 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3585 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3586 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3587 DWORD dwInternalFlags)
3589 LPWININETHTTPSESSIONW lpwhs = NULL;
3590 HINTERNET handle = NULL;
3592 TRACE("-->\n");
3594 if (!lpszServerName || !lpszServerName[0])
3596 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3597 goto lerror;
3600 assert( hIC->hdr.htype == WH_HINIT );
3602 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3603 if (NULL == lpwhs)
3605 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3606 goto lerror;
3610 * According to my tests. The name is not resolved until a request is sent
3613 lpwhs->hdr.htype = WH_HHTTPSESSION;
3614 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3615 lpwhs->hdr.dwFlags = dwFlags;
3616 lpwhs->hdr.dwContext = dwContext;
3617 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3618 lpwhs->hdr.refs = 1;
3619 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3621 WININET_AddRef( &hIC->hdr );
3622 lpwhs->lpAppInfo = hIC;
3623 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3625 handle = WININET_AllocHandle( &lpwhs->hdr );
3626 if (NULL == handle)
3628 ERR("Failed to alloc handle\n");
3629 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3630 goto lerror;
3633 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3634 if(strchrW(hIC->lpszProxy, ' '))
3635 FIXME("Several proxies not implemented.\n");
3636 if(hIC->lpszProxyBypass)
3637 FIXME("Proxy bypass is ignored.\n");
3639 if (lpszServerName && lpszServerName[0])
3641 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3642 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3644 if (lpszUserName && lpszUserName[0])
3645 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3646 if (lpszPassword && lpszPassword[0])
3647 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3648 lpwhs->nServerPort = nServerPort;
3649 lpwhs->nHostPort = nServerPort;
3651 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3652 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3654 INTERNET_SendCallback(&hIC->hdr, dwContext,
3655 INTERNET_STATUS_HANDLE_CREATED, &handle,
3656 sizeof(handle));
3659 lerror:
3660 if( lpwhs )
3661 WININET_Release( &lpwhs->hdr );
3664 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3665 * windows
3668 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3669 return handle;
3673 /***********************************************************************
3674 * HTTP_OpenConnection (internal)
3676 * Connect to a web server
3678 * RETURNS
3680 * TRUE on success
3681 * FALSE on failure
3683 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3685 BOOL bSuccess = FALSE;
3686 LPWININETHTTPSESSIONW lpwhs;
3687 LPWININETAPPINFOW hIC = NULL;
3688 char szaddr[32];
3690 TRACE("-->\n");
3693 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3695 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3696 goto lend;
3699 if (NETCON_connected(&lpwhr->netConnection))
3701 bSuccess = TRUE;
3702 goto lend;
3704 if (!HTTP_ResolveName(lpwhr)) goto lend;
3706 lpwhs = lpwhr->lpHttpSession;
3708 hIC = lpwhs->lpAppInfo;
3709 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3710 szaddr, sizeof(szaddr));
3711 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3712 INTERNET_STATUS_CONNECTING_TO_SERVER,
3713 szaddr,
3714 strlen(szaddr)+1);
3716 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3717 SOCK_STREAM, 0))
3719 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3720 goto lend;
3723 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3724 sizeof(lpwhs->socketAddress)))
3725 goto lend;
3727 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3729 /* Note: we differ from Microsoft's WinINet here. they seem to have
3730 * a bug that causes no status callbacks to be sent when starting
3731 * a tunnel to a proxy server using the CONNECT verb. i believe our
3732 * behaviour to be more correct and to not cause any incompatibilities
3733 * because using a secure connection through a proxy server is a rare
3734 * case that would be hard for anyone to depend on */
3735 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3736 goto lend;
3738 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3740 WARN("Couldn't connect securely to host\n");
3741 goto lend;
3745 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3746 INTERNET_STATUS_CONNECTED_TO_SERVER,
3747 szaddr, strlen(szaddr)+1);
3749 bSuccess = TRUE;
3751 lend:
3752 TRACE("%d <--\n", bSuccess);
3753 return bSuccess;
3757 /***********************************************************************
3758 * HTTP_clear_response_headers (internal)
3760 * clear out any old response headers
3762 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3764 DWORD i;
3766 for( i=0; i<lpwhr->nCustHeaders; i++)
3768 if( !lpwhr->pCustHeaders[i].lpszField )
3769 continue;
3770 if( !lpwhr->pCustHeaders[i].lpszValue )
3771 continue;
3772 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3773 continue;
3774 HTTP_DeleteCustomHeader( lpwhr, i );
3775 i--;
3779 /***********************************************************************
3780 * HTTP_GetResponseHeaders (internal)
3782 * Read server response
3784 * RETURNS
3786 * TRUE on success
3787 * FALSE on error
3789 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3791 INT cbreaks = 0;
3792 WCHAR buffer[MAX_REPLY_LEN];
3793 DWORD buflen = MAX_REPLY_LEN;
3794 BOOL bSuccess = FALSE;
3795 INT rc = 0;
3796 static const WCHAR szHundred[] = {'1','0','0',0};
3797 char bufferA[MAX_REPLY_LEN];
3798 LPWSTR status_code, status_text;
3799 DWORD cchMaxRawHeaders = 1024;
3800 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3801 DWORD cchRawHeaders = 0;
3803 TRACE("-->\n");
3805 /* clear old response headers (eg. from a redirect response) */
3806 if (clear) HTTP_clear_response_headers( lpwhr );
3808 if (!NETCON_connected(&lpwhr->netConnection))
3809 goto lend;
3811 do {
3813 * HACK peek at the buffer
3815 buflen = MAX_REPLY_LEN;
3816 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3819 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3821 memset(buffer, 0, MAX_REPLY_LEN);
3822 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3823 goto lend;
3824 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3826 /* split the version from the status code */
3827 status_code = strchrW( buffer, ' ' );
3828 if( !status_code )
3829 goto lend;
3830 *status_code++=0;
3832 /* split the status code from the status text */
3833 status_text = strchrW( status_code, ' ' );
3834 if( !status_text )
3835 goto lend;
3836 *status_text++=0;
3838 TRACE("version [%s] status code [%s] status text [%s]\n",
3839 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3841 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3843 /* Add status code */
3844 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3845 HTTP_ADDHDR_FLAG_REPLACE);
3847 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3848 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3850 lpwhr->lpszVersion= WININET_strdupW(buffer);
3851 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3853 /* Restore the spaces */
3854 *(status_code-1) = ' ';
3855 *(status_text-1) = ' ';
3857 /* regenerate raw headers */
3858 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3860 cchMaxRawHeaders *= 2;
3861 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3863 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3864 cchRawHeaders += (buflen-1);
3865 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3866 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3867 lpszRawHeaders[cchRawHeaders] = '\0';
3869 /* Parse each response line */
3872 buflen = MAX_REPLY_LEN;
3873 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3875 LPWSTR * pFieldAndValue;
3877 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3878 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3880 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3882 cchMaxRawHeaders *= 2;
3883 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3885 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3886 cchRawHeaders += (buflen-1);
3887 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3888 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3889 lpszRawHeaders[cchRawHeaders] = '\0';
3891 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3892 if (!pFieldAndValue)
3893 break;
3895 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3896 HTTP_ADDREQ_FLAG_ADD );
3898 HTTP_FreeTokens(pFieldAndValue);
3900 else
3902 cbreaks++;
3903 if (cbreaks >= 2)
3904 break;
3906 }while(1);
3908 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3909 lpwhr->lpszRawHeaders = lpszRawHeaders;
3910 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3911 bSuccess = TRUE;
3913 lend:
3915 TRACE("<--\n");
3916 if (bSuccess)
3917 return rc;
3918 else
3920 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
3921 return 0;
3926 static void strip_spaces(LPWSTR start)
3928 LPWSTR str = start;
3929 LPWSTR end;
3931 while (*str == ' ' && *str != '\0')
3932 str++;
3934 if (str != start)
3935 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3937 end = start + strlenW(start) - 1;
3938 while (end >= start && *end == ' ')
3940 *end = '\0';
3941 end--;
3946 /***********************************************************************
3947 * HTTP_InterpretHttpHeader (internal)
3949 * Parse server response
3951 * RETURNS
3953 * Pointer to array of field, value, NULL on success.
3954 * NULL on error.
3956 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3958 LPWSTR * pTokenPair;
3959 LPWSTR pszColon;
3960 INT len;
3962 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3964 pszColon = strchrW(buffer, ':');
3965 /* must have two tokens */
3966 if (!pszColon)
3968 HTTP_FreeTokens(pTokenPair);
3969 if (buffer[0])
3970 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3971 return NULL;
3974 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3975 if (!pTokenPair[0])
3977 HTTP_FreeTokens(pTokenPair);
3978 return NULL;
3980 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3981 pTokenPair[0][pszColon - buffer] = '\0';
3983 /* skip colon */
3984 pszColon++;
3985 len = strlenW(pszColon);
3986 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3987 if (!pTokenPair[1])
3989 HTTP_FreeTokens(pTokenPair);
3990 return NULL;
3992 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3994 strip_spaces(pTokenPair[0]);
3995 strip_spaces(pTokenPair[1]);
3997 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3998 return pTokenPair;
4001 /***********************************************************************
4002 * HTTP_ProcessHeader (internal)
4004 * Stuff header into header tables according to <dwModifier>
4008 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4010 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4012 LPHTTPHEADERW lphttpHdr = NULL;
4013 BOOL bSuccess = FALSE;
4014 INT index = -1;
4015 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4017 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
4019 /* REPLACE wins out over ADD */
4020 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4021 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
4023 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
4024 index = -1;
4025 else
4026 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
4028 if (index >= 0)
4030 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4032 return FALSE;
4034 lphttpHdr = &lpwhr->pCustHeaders[index];
4036 else if (value)
4038 HTTPHEADERW hdr;
4040 hdr.lpszField = (LPWSTR)field;
4041 hdr.lpszValue = (LPWSTR)value;
4042 hdr.wFlags = hdr.wCount = 0;
4044 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4045 hdr.wFlags |= HDR_ISREQUEST;
4047 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4049 /* no value to delete */
4050 else return TRUE;
4052 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4053 lphttpHdr->wFlags |= HDR_ISREQUEST;
4054 else
4055 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4057 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4059 HTTP_DeleteCustomHeader( lpwhr, index );
4061 if (value)
4063 HTTPHEADERW hdr;
4065 hdr.lpszField = (LPWSTR)field;
4066 hdr.lpszValue = (LPWSTR)value;
4067 hdr.wFlags = hdr.wCount = 0;
4069 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4070 hdr.wFlags |= HDR_ISREQUEST;
4072 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4075 return TRUE;
4077 else if (dwModifier & COALESCEFLAGS)
4079 LPWSTR lpsztmp;
4080 WCHAR ch = 0;
4081 INT len = 0;
4082 INT origlen = strlenW(lphttpHdr->lpszValue);
4083 INT valuelen = strlenW(value);
4085 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4087 ch = ',';
4088 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4090 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4092 ch = ';';
4093 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4096 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4098 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4099 if (lpsztmp)
4101 lphttpHdr->lpszValue = lpsztmp;
4102 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4103 if (ch > 0)
4105 lphttpHdr->lpszValue[origlen] = ch;
4106 origlen++;
4107 lphttpHdr->lpszValue[origlen] = ' ';
4108 origlen++;
4111 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4112 lphttpHdr->lpszValue[len] = '\0';
4113 bSuccess = TRUE;
4115 else
4117 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4118 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4121 TRACE("<-- %d\n",bSuccess);
4122 return bSuccess;
4126 /***********************************************************************
4127 * HTTP_FinishedReading (internal)
4129 * Called when all content from server has been read by client.
4132 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4134 WCHAR szVersion[10];
4135 WCHAR szConnectionResponse[20];
4136 DWORD dwBufferSize = sizeof(szVersion);
4137 BOOL keepalive = FALSE;
4139 TRACE("\n");
4141 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4142 * the connection is keep-alive by default */
4143 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4144 &dwBufferSize, NULL) &&
4145 !strcmpiW(szVersion, g_szHttp1_1))
4147 keepalive = TRUE;
4150 dwBufferSize = sizeof(szConnectionResponse);
4151 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4152 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4154 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4157 if (!keepalive)
4159 HTTPREQ_CloseConnection(&lpwhr->hdr);
4162 /* FIXME: store data in the URL cache here */
4164 return TRUE;
4168 /***********************************************************************
4169 * HTTP_GetCustomHeaderIndex (internal)
4171 * Return index of custom header from header array
4174 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4175 int requested_index, BOOL request_only)
4177 DWORD index;
4179 TRACE("%s\n", debugstr_w(lpszField));
4181 for (index = 0; index < lpwhr->nCustHeaders; index++)
4183 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4184 continue;
4186 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4187 continue;
4189 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4190 continue;
4192 if (requested_index == 0)
4193 break;
4194 requested_index --;
4197 if (index >= lpwhr->nCustHeaders)
4198 index = -1;
4200 TRACE("Return: %d\n", index);
4201 return index;
4205 /***********************************************************************
4206 * HTTP_InsertCustomHeader (internal)
4208 * Insert header into array
4211 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4213 INT count;
4214 LPHTTPHEADERW lph = NULL;
4215 BOOL r = FALSE;
4217 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4218 count = lpwhr->nCustHeaders + 1;
4219 if (count > 1)
4220 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4221 else
4222 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4224 if (NULL != lph)
4226 lpwhr->pCustHeaders = lph;
4227 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4228 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4229 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4230 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4231 lpwhr->nCustHeaders++;
4232 r = TRUE;
4234 else
4236 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4239 return r;
4243 /***********************************************************************
4244 * HTTP_DeleteCustomHeader (internal)
4246 * Delete header from array
4247 * If this function is called, the indexs may change.
4249 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4251 if( lpwhr->nCustHeaders <= 0 )
4252 return FALSE;
4253 if( index >= lpwhr->nCustHeaders )
4254 return FALSE;
4255 lpwhr->nCustHeaders--;
4257 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4258 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4260 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4261 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4262 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4264 return TRUE;
4268 /***********************************************************************
4269 * HTTP_VerifyValidHeader (internal)
4271 * Verify the given header is not invalid for the given http request
4274 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4276 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4277 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4278 return FALSE;
4280 return TRUE;
4283 /***********************************************************************
4284 * IsHostInProxyBypassList (@)
4286 * Undocumented
4289 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4291 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4292 return FALSE;