push f2fb4b43e6a5ad960b5745b9c70e0a8fefaca935
[wine/hacks.git] / dlls / wininet / http.c
blobb9f56d2ccf8c0c07551a5544f37255a6f9445924
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 #include <sys/types.h>
33 #ifdef HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
35 #endif
36 #ifdef HAVE_ARPA_INET_H
37 # include <arpa/inet.h>
38 #endif
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45 #include <time.h>
46 #include <assert.h>
48 #include "windef.h"
49 #include "winbase.h"
50 #include "wininet.h"
51 #include "winerror.h"
52 #define NO_SHLWAPI_STREAM
53 #define NO_SHLWAPI_REG
54 #define NO_SHLWAPI_STRFCNS
55 #define NO_SHLWAPI_GDI
56 #include "shlwapi.h"
57 #include "sspi.h"
59 #include "internet.h"
60 #include "wine/debug.h"
61 #include "wine/unicode.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
65 static const WCHAR g_szHttp1_0[] = {' ','H','T','T','P','/','1','.','0',0 };
66 static const WCHAR g_szHttp1_1[] = {' ','H','T','T','P','/','1','.','1',0 };
67 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
68 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
69 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
70 static const WCHAR szHost[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
76 #define MAXHOSTNAME 100
77 #define MAX_FIELD_VALUE_LEN 256
78 #define MAX_FIELD_LEN 256
80 #define HTTP_REFERER g_szReferer
81 #define HTTP_ACCEPT g_szAccept
82 #define HTTP_USERAGENT g_szUserAgent
84 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
85 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
86 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
87 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
88 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
89 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
90 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
92 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
94 struct HttpAuthInfo
96 LPWSTR scheme;
97 CredHandle cred;
98 CtxtHandle ctx;
99 TimeStamp exp;
100 ULONG attr;
101 void *auth_data;
102 unsigned int auth_data_len;
103 BOOL finished; /* finished authenticating */
106 static void HTTP_CloseConnection(LPWININETHANDLEHEADER hdr);
107 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr);
108 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr);
109 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
110 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr);
111 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
112 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
113 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
114 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
115 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
116 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
117 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
118 dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
119 lpdwIndex);
120 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
121 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
122 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
125 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
127 int HeaderIndex = 0;
128 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
129 if (HeaderIndex == -1)
130 return NULL;
131 else
132 return &req->pCustHeaders[HeaderIndex];
135 /***********************************************************************
136 * HTTP_Tokenize (internal)
138 * Tokenize a string, allocating memory for the tokens.
140 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
142 LPWSTR * token_array;
143 int tokens = 0;
144 int i;
145 LPCWSTR next_token;
147 /* empty string has no tokens */
148 if (*string)
149 tokens++;
150 /* count tokens */
151 for (i = 0; string[i]; i++)
152 if (!strncmpW(string+i, token_string, strlenW(token_string)))
154 DWORD j;
155 tokens++;
156 /* we want to skip over separators, but not the null terminator */
157 for (j = 0; j < strlenW(token_string) - 1; j++)
158 if (!string[i+j])
159 break;
160 i += j;
163 /* add 1 for terminating NULL */
164 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
165 token_array[tokens] = NULL;
166 if (!tokens)
167 return token_array;
168 for (i = 0; i < tokens; i++)
170 int len;
171 next_token = strstrW(string, token_string);
172 if (!next_token) next_token = string+strlenW(string);
173 len = next_token - string;
174 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
175 memcpy(token_array[i], string, len*sizeof(WCHAR));
176 token_array[i][len] = '\0';
177 string = next_token+strlenW(token_string);
179 return token_array;
182 /***********************************************************************
183 * HTTP_FreeTokens (internal)
185 * Frees memory returned from HTTP_Tokenize.
187 static void HTTP_FreeTokens(LPWSTR * token_array)
189 int i;
190 for (i = 0; token_array[i]; i++)
191 HeapFree(GetProcessHeap(), 0, token_array[i]);
192 HeapFree(GetProcessHeap(), 0, token_array);
195 /* **********************************************************************
197 * Helper functions for the HttpSendRequest(Ex) functions
200 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
202 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
203 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
205 TRACE("%p\n", lpwhr);
207 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
208 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
209 req->dwContentLength, req->bEndRequest);
211 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
214 static void HTTP_FixVerb( LPWININETHTTPREQW lpwhr )
216 /* if the verb is NULL default to GET */
217 if (NULL == lpwhr->lpszVerb)
219 static const WCHAR szGET[] = { 'G','E','T', 0 };
220 lpwhr->lpszVerb = WININET_strdupW(szGET);
224 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
226 static const WCHAR szSlash[] = { '/',0 };
227 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
229 /* If we don't have a path we set it to root */
230 if (NULL == lpwhr->lpszPath)
231 lpwhr->lpszPath = WININET_strdupW(szSlash);
232 else /* remove \r and \n*/
234 int nLen = strlenW(lpwhr->lpszPath);
235 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
237 nLen--;
238 lpwhr->lpszPath[nLen]='\0';
240 /* Replace '\' with '/' */
241 while (nLen>0) {
242 nLen--;
243 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
247 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
248 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
249 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
251 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
252 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
253 *fixurl = '/';
254 strcpyW(fixurl + 1, lpwhr->lpszPath);
255 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
256 lpwhr->lpszPath = fixurl;
260 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, BOOL http1_1 )
262 LPWSTR requestString;
263 DWORD len, n;
264 LPCWSTR *req;
265 INT i;
266 LPWSTR p;
268 static const WCHAR szSpace[] = { ' ',0 };
269 static const WCHAR szcrlf[] = {'\r','\n', 0};
270 static const WCHAR szColon[] = { ':',' ',0 };
271 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
273 /* allocate space for an array of all the string pointers to be added */
274 len = (lpwhr->nCustHeaders)*4 + 9;
275 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
277 /* add the verb, path and HTTP version string */
278 n = 0;
279 req[n++] = verb;
280 req[n++] = szSpace;
281 req[n++] = path;
282 req[n++] = http1_1 ? g_szHttp1_1 : g_szHttp1_0;
284 /* Append custom request headers */
285 for (i = 0; i < lpwhr->nCustHeaders; i++)
287 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
289 req[n++] = szcrlf;
290 req[n++] = lpwhr->pCustHeaders[i].lpszField;
291 req[n++] = szColon;
292 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
294 TRACE("Adding custom header %s (%s)\n",
295 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
296 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
300 if( n >= len )
301 ERR("oops. buffer overrun\n");
303 req[n] = NULL;
304 requestString = HTTP_build_req( req, 4 );
305 HeapFree( GetProcessHeap(), 0, req );
308 * Set (header) termination string for request
309 * Make sure there's exactly two new lines at the end of the request
311 p = &requestString[strlenW(requestString)-1];
312 while ( (*p == '\n') || (*p == '\r') )
313 p--;
314 strcpyW( p+1, sztwocrlf );
316 return requestString;
319 static void HTTP_ProcessHeaders( LPWININETHTTPREQW lpwhr )
321 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
322 int HeaderIndex;
323 LPHTTPHEADERW setCookieHeader;
325 HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
326 if (HeaderIndex == -1)
327 return;
328 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
330 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
332 int nPosStart = 0, nPosEnd = 0, len;
333 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
335 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
337 LPWSTR buf_cookie, cookie_name, cookie_data;
338 LPWSTR buf_url;
339 LPWSTR domain = NULL;
340 LPHTTPHEADERW Host;
342 int nEqualPos = 0;
343 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
344 setCookieHeader->lpszValue[nPosEnd] != '\0')
346 nPosEnd++;
348 if (setCookieHeader->lpszValue[nPosEnd] == ';')
350 /* fixme: not case sensitive, strcasestr is gnu only */
351 int nDomainPosEnd = 0;
352 int nDomainPosStart = 0, nDomainLength = 0;
353 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
354 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
355 if (lpszDomain)
356 { /* they have specified their own domain, lets use it */
357 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
358 lpszDomain[nDomainPosEnd] != '\0')
360 nDomainPosEnd++;
362 nDomainPosStart = strlenW(szDomain);
363 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
364 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
365 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
368 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
369 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
370 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
371 TRACE("%s\n", debugstr_w(buf_cookie));
372 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
374 nEqualPos++;
376 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
378 HeapFree(GetProcessHeap(), 0, buf_cookie);
379 break;
382 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
383 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
384 cookie_data = &buf_cookie[nEqualPos + 1];
386 Host = HTTP_GetHeader(lpwhr,szHost);
387 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
388 strlenW(lpwhr->lpszPath) + 9;
389 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
390 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
391 InternetSetCookieW(buf_url, cookie_name, cookie_data);
393 HeapFree(GetProcessHeap(), 0, buf_url);
394 HeapFree(GetProcessHeap(), 0, buf_cookie);
395 HeapFree(GetProcessHeap(), 0, cookie_name);
396 HeapFree(GetProcessHeap(), 0, domain);
397 nPosStart = nPosEnd;
402 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
404 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
405 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
406 ((pszAuthValue[ARRAYSIZE(szBasic)] != ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
409 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
410 struct HttpAuthInfo **ppAuthInfo,
411 LPWSTR domain_and_username, LPWSTR password )
413 SECURITY_STATUS sec_status;
414 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
415 BOOL first = FALSE;
417 TRACE("%s\n", debugstr_w(pszAuthValue));
419 if (!domain_and_username) return FALSE;
421 if (!pAuthInfo)
423 TimeStamp exp;
425 first = TRUE;
426 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
427 if (!pAuthInfo)
428 return FALSE;
430 SecInvalidateHandle(&pAuthInfo->cred);
431 SecInvalidateHandle(&pAuthInfo->ctx);
432 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
433 pAuthInfo->attr = 0;
434 pAuthInfo->auth_data = NULL;
435 pAuthInfo->auth_data_len = 0;
436 pAuthInfo->finished = FALSE;
438 if (is_basic_auth_value(pszAuthValue))
440 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
441 pAuthInfo->scheme = WININET_strdupW(szBasic);
442 if (!pAuthInfo->scheme)
444 HeapFree(GetProcessHeap(), 0, pAuthInfo);
445 return FALSE;
448 else
450 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
451 WCHAR *user = strchrW(domain_and_username, '\\');
452 WCHAR *domain = domain_and_username;
454 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
455 if (!pAuthInfo->scheme)
457 HeapFree(GetProcessHeap(), 0, pAuthInfo);
458 return FALSE;
461 if (user) user++;
462 else
464 user = domain_and_username;
465 domain = NULL;
467 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
468 nt_auth_identity.User = user;
469 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
470 nt_auth_identity.Domain = domain;
471 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
472 nt_auth_identity.Password = password;
473 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
475 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
477 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
478 SECPKG_CRED_OUTBOUND, NULL,
479 &nt_auth_identity, NULL,
480 NULL, &pAuthInfo->cred,
481 &exp);
482 if (sec_status != SEC_E_OK)
484 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
485 debugstr_w(pAuthInfo->scheme), sec_status);
486 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
487 HeapFree(GetProcessHeap(), 0, pAuthInfo);
488 return FALSE;
491 *ppAuthInfo = pAuthInfo;
493 else if (pAuthInfo->finished)
494 return FALSE;
496 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
497 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
499 ERR("authentication scheme changed from %s to %s\n",
500 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
501 return FALSE;
504 if (is_basic_auth_value(pszAuthValue))
506 int userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
507 int passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
508 char *auth_data;
510 TRACE("basic authentication\n");
512 /* length includes a nul terminator, which will be re-used for the ':' */
513 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
514 if (!auth_data)
515 return FALSE;
517 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
518 auth_data[userlen] = ':';
519 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
521 pAuthInfo->auth_data = auth_data;
522 pAuthInfo->auth_data_len = userlen + 1 + passlen;
523 pAuthInfo->finished = TRUE;
525 return TRUE;
527 else
529 LPCWSTR pszAuthData;
530 SecBufferDesc out_desc, in_desc;
531 SecBuffer out, in;
532 unsigned char *buffer;
533 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
534 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
536 in.BufferType = SECBUFFER_TOKEN;
537 in.cbBuffer = 0;
538 in.pvBuffer = NULL;
540 in_desc.ulVersion = 0;
541 in_desc.cBuffers = 1;
542 in_desc.pBuffers = &in;
544 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
545 if (*pszAuthData == ' ')
547 pszAuthData++;
548 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
549 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
550 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
553 buffer = HeapAlloc(GetProcessHeap(), 0, 0x100);
555 out.BufferType = SECBUFFER_TOKEN;
556 out.cbBuffer = 0x100;
557 out.pvBuffer = buffer;
559 out_desc.ulVersion = 0;
560 out_desc.cBuffers = 1;
561 out_desc.pBuffers = &out;
563 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
564 first ? NULL : &pAuthInfo->ctx, NULL,
565 context_req, 0, SECURITY_NETWORK_DREP,
566 in.pvBuffer ? &in_desc : NULL,
567 0, &pAuthInfo->ctx, &out_desc,
568 &pAuthInfo->attr, &pAuthInfo->exp);
569 if (sec_status == SEC_E_OK)
571 pAuthInfo->finished = TRUE;
572 pAuthInfo->auth_data = out.pvBuffer;
573 pAuthInfo->auth_data_len = out.cbBuffer;
574 TRACE("sending last auth packet\n");
576 else if (sec_status == SEC_I_CONTINUE_NEEDED)
578 pAuthInfo->auth_data = out.pvBuffer;
579 pAuthInfo->auth_data_len = out.cbBuffer;
580 TRACE("sending next auth packet\n");
582 else
584 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
585 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
586 return FALSE;
590 return TRUE;
593 /***********************************************************************
594 * HTTP_HttpAddRequestHeadersW (internal)
596 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
597 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
599 LPWSTR lpszStart;
600 LPWSTR lpszEnd;
601 LPWSTR buffer;
602 BOOL bSuccess = FALSE;
603 DWORD len;
605 TRACE("copying header: %s\n", debugstr_w(lpszHeader));
607 if( dwHeaderLength == ~0U )
608 len = strlenW(lpszHeader);
609 else
610 len = dwHeaderLength;
611 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
612 lstrcpynW( buffer, lpszHeader, len + 1);
614 lpszStart = buffer;
618 LPWSTR * pFieldAndValue;
620 lpszEnd = lpszStart;
622 while (*lpszEnd != '\0')
624 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
625 break;
626 lpszEnd++;
629 if (*lpszStart == '\0')
630 break;
632 if (*lpszEnd == '\r')
634 *lpszEnd = '\0';
635 lpszEnd += 2; /* Jump over \r\n */
637 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
638 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
639 if (pFieldAndValue)
641 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
642 if (bSuccess)
643 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
644 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
645 HTTP_FreeTokens(pFieldAndValue);
648 lpszStart = lpszEnd;
649 } while (bSuccess);
651 HeapFree(GetProcessHeap(), 0, buffer);
653 return bSuccess;
656 /***********************************************************************
657 * HttpAddRequestHeadersW (WININET.@)
659 * Adds one or more HTTP header to the request handler
661 * RETURNS
662 * TRUE on success
663 * FALSE on failure
666 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
667 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
669 BOOL bSuccess = FALSE;
670 LPWININETHTTPREQW lpwhr;
672 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_w(lpszHeader), dwHeaderLength,
673 dwModifier);
675 if (!lpszHeader)
676 return TRUE;
678 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
679 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
681 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
682 goto lend;
684 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
685 lend:
686 if( lpwhr )
687 WININET_Release( &lpwhr->hdr );
689 return bSuccess;
692 /***********************************************************************
693 * HttpAddRequestHeadersA (WININET.@)
695 * Adds one or more HTTP header to the request handler
697 * RETURNS
698 * TRUE on success
699 * FALSE on failure
702 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
703 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
705 DWORD len;
706 LPWSTR hdr;
707 BOOL r;
709 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_a(lpszHeader), dwHeaderLength,
710 dwModifier);
712 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
713 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
714 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
715 if( dwHeaderLength != ~0U )
716 dwHeaderLength = len;
718 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
720 HeapFree( GetProcessHeap(), 0, hdr );
722 return r;
725 /* read any content returned by the server so that the connection can be
726 * reused */
727 static void HTTP_DrainContent(LPWININETHTTPREQW lpwhr)
729 DWORD bytes_read;
731 if (!NETCON_connected(&lpwhr->netConnection)) return;
733 if (lpwhr->dwContentLength == -1)
734 NETCON_close(&lpwhr->netConnection);
738 char buffer[2048];
739 if (!INTERNET_ReadFile(&lpwhr->hdr, buffer, sizeof(buffer), &bytes_read,
740 TRUE, FALSE))
741 return;
742 } while (bytes_read);
745 /***********************************************************************
746 * HttpEndRequestA (WININET.@)
748 * Ends an HTTP request that was started by HttpSendRequestEx
750 * RETURNS
751 * TRUE if successful
752 * FALSE on failure
755 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
756 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
758 LPINTERNET_BUFFERSA ptr;
759 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
760 BOOL rc = FALSE;
762 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
763 dwContext);
765 ptr = lpBuffersOut;
766 if (ptr)
767 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
768 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
769 else
770 lpBuffersOutW = NULL;
772 ptrW = lpBuffersOutW;
773 while (ptr)
775 if (ptr->lpvBuffer && ptr->dwBufferLength)
776 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
777 ptrW->dwBufferLength = ptr->dwBufferLength;
778 ptrW->dwBufferTotal= ptr->dwBufferTotal;
780 if (ptr->Next)
781 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
782 sizeof(INTERNET_BUFFERSW));
784 ptr = ptr->Next;
785 ptrW = ptrW->Next;
788 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
790 if (lpBuffersOutW)
792 ptrW = lpBuffersOutW;
793 while (ptrW)
795 LPINTERNET_BUFFERSW ptrW2;
797 FIXME("Do we need to translate info out of these buffer?\n");
799 HeapFree(GetProcessHeap(),0,(LPVOID)ptrW->lpvBuffer);
800 ptrW2 = ptrW->Next;
801 HeapFree(GetProcessHeap(),0,ptrW);
802 ptrW = ptrW2;
806 return rc;
809 /***********************************************************************
810 * HttpEndRequestW (WININET.@)
812 * Ends an HTTP request that was started by HttpSendRequestEx
814 * RETURNS
815 * TRUE if successful
816 * FALSE on failure
819 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
820 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
822 BOOL rc = FALSE;
823 LPWININETHTTPREQW lpwhr;
824 INT responseLen;
825 DWORD dwBufferSize;
827 TRACE("-->\n");
828 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
830 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
832 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
833 if (lpwhr)
834 WININET_Release( &lpwhr->hdr );
835 return FALSE;
838 lpwhr->hdr.dwFlags |= dwFlags;
839 lpwhr->hdr.dwContext = dwContext;
841 /* We appear to do nothing with lpBuffersOut.. is that correct? */
843 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
844 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
846 responseLen = HTTP_GetResponseHeaders(lpwhr);
847 if (responseLen)
848 rc = TRUE;
850 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
851 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
853 /* process headers here. Is this right? */
854 HTTP_ProcessHeaders(lpwhr);
856 dwBufferSize = sizeof(lpwhr->dwContentLength);
857 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
858 &lpwhr->dwContentLength,&dwBufferSize,NULL))
859 lpwhr->dwContentLength = -1;
861 if (lpwhr->dwContentLength == 0)
862 HTTP_FinishedReading(lpwhr);
864 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
866 DWORD dwCode,dwCodeLength=sizeof(DWORD);
867 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
868 (dwCode==302 || dwCode==301))
870 WCHAR szNewLocation[2048];
871 dwBufferSize=sizeof(szNewLocation);
872 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
874 static const WCHAR szGET[] = { 'G','E','T', 0 };
875 /* redirects are always GETs */
876 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
877 lpwhr->lpszVerb = WININET_strdupW(szGET);
878 HTTP_DrainContent(lpwhr);
879 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
880 if (rc)
881 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
886 WININET_Release( &lpwhr->hdr );
887 TRACE("%i <--\n",rc);
888 return rc;
891 /***********************************************************************
892 * HttpOpenRequestW (WININET.@)
894 * Open a HTTP request handle
896 * RETURNS
897 * HINTERNET a HTTP request handle on success
898 * NULL on failure
901 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
902 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
903 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
904 DWORD dwFlags, DWORD_PTR dwContext)
906 LPWININETHTTPSESSIONW lpwhs;
907 HINTERNET handle = NULL;
909 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
910 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
911 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
912 dwFlags, dwContext);
913 if(lpszAcceptTypes!=NULL)
915 int i;
916 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
917 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
920 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
921 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
923 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
924 goto lend;
928 * My tests seem to show that the windows version does not
929 * become asynchronous until after this point. And anyhow
930 * if this call was asynchronous then how would you get the
931 * necessary HINTERNET pointer returned by this function.
934 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
935 lpszVersion, lpszReferrer, lpszAcceptTypes,
936 dwFlags, dwContext);
937 lend:
938 if( lpwhs )
939 WININET_Release( &lpwhs->hdr );
940 TRACE("returning %p\n", handle);
941 return handle;
945 /***********************************************************************
946 * HttpOpenRequestA (WININET.@)
948 * Open a HTTP request handle
950 * RETURNS
951 * HINTERNET a HTTP request handle on success
952 * NULL on failure
955 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
956 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
957 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
958 DWORD dwFlags, DWORD_PTR dwContext)
960 LPWSTR szVerb = NULL, szObjectName = NULL;
961 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
962 INT len;
963 INT acceptTypesCount;
964 HINTERNET rc = FALSE;
965 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
966 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
967 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
968 dwFlags, dwContext);
970 if (lpszVerb)
972 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
973 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
974 if ( !szVerb )
975 goto end;
976 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
979 if (lpszObjectName)
981 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
982 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
983 if ( !szObjectName )
984 goto end;
985 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
988 if (lpszVersion)
990 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
991 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
992 if ( !szVersion )
993 goto end;
994 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
997 if (lpszReferrer)
999 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1000 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1001 if ( !szReferrer )
1002 goto end;
1003 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1006 acceptTypesCount = 0;
1007 if (lpszAcceptTypes)
1009 /* find out how many there are */
1010 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1011 acceptTypesCount++;
1012 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1013 acceptTypesCount = 0;
1014 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1016 len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1017 -1, NULL, 0 );
1018 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1019 if (!szAcceptTypes[acceptTypesCount] )
1020 goto end;
1021 MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1022 -1, szAcceptTypes[acceptTypesCount], len );
1023 acceptTypesCount++;
1025 szAcceptTypes[acceptTypesCount] = NULL;
1027 else szAcceptTypes = 0;
1029 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1030 szVersion, szReferrer,
1031 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1033 end:
1034 if (szAcceptTypes)
1036 acceptTypesCount = 0;
1037 while (szAcceptTypes[acceptTypesCount])
1039 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1040 acceptTypesCount++;
1042 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1044 HeapFree(GetProcessHeap(), 0, szReferrer);
1045 HeapFree(GetProcessHeap(), 0, szVersion);
1046 HeapFree(GetProcessHeap(), 0, szObjectName);
1047 HeapFree(GetProcessHeap(), 0, szVerb);
1049 return rc;
1052 /***********************************************************************
1053 * HTTP_EncodeBase64
1055 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1057 UINT n = 0, x;
1058 static const CHAR HTTP_Base64Enc[] =
1059 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1061 while( len > 0 )
1063 /* first 6 bits, all from bin[0] */
1064 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1065 x = (bin[0] & 3) << 4;
1067 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1068 if( len == 1 )
1070 base64[n++] = HTTP_Base64Enc[x];
1071 base64[n++] = '=';
1072 base64[n++] = '=';
1073 break;
1075 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1076 x = ( bin[1] & 0x0f ) << 2;
1078 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1079 if( len == 2 )
1081 base64[n++] = HTTP_Base64Enc[x];
1082 base64[n++] = '=';
1083 break;
1085 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1087 /* last 6 bits, all from bin [2] */
1088 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1089 bin += 3;
1090 len -= 3;
1092 base64[n] = 0;
1093 return n;
1096 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1097 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1098 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1099 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1100 static const signed char HTTP_Base64Dec[256] =
1102 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1103 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1104 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1105 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1106 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1107 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1108 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1109 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1110 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1111 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1112 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1113 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1114 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1115 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1116 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1117 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1118 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1119 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1120 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1121 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1122 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1123 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1124 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1125 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1126 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1127 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1129 #undef CH
1131 /***********************************************************************
1132 * HTTP_DecodeBase64
1134 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1136 unsigned int n = 0;
1138 while(*base64)
1140 signed char in[4];
1142 if (base64[0] > ARRAYSIZE(HTTP_Base64Dec) ||
1143 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1144 base64[1] > ARRAYSIZE(HTTP_Base64Dec) ||
1145 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1147 WARN("invalid base64: %s\n", debugstr_w(base64));
1148 return 0;
1150 if (bin)
1151 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1152 n++;
1154 if ((base64[2] == '=') && (base64[3] == '='))
1155 break;
1156 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1157 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1159 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1160 return 0;
1162 if (bin)
1163 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1164 n++;
1166 if (base64[3] == '=')
1167 break;
1168 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1169 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1171 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1172 return 0;
1174 if (bin)
1175 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1176 n++;
1178 base64 += 4;
1181 return n;
1184 /***********************************************************************
1185 * HTTP_InsertAuthorizationForHeader
1187 * Insert or delete the authorization field in the request header.
1189 static BOOL HTTP_InsertAuthorizationForHeader( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1191 WCHAR *authorization = NULL;
1193 if (pAuthInfo && pAuthInfo->auth_data_len)
1195 static const WCHAR wszSpace[] = {' ',0};
1196 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1197 unsigned int len;
1199 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1200 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1201 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1202 if (!authorization)
1203 return FALSE;
1205 strcpyW(authorization, pAuthInfo->scheme);
1206 strcatW(authorization, wszSpace);
1207 HTTP_EncodeBase64(pAuthInfo->auth_data,
1208 pAuthInfo->auth_data_len,
1209 authorization+strlenW(authorization));
1211 /* clear the data as it isn't valid now that it has been sent to the
1212 * server, unless it's Basic authentication which doesn't do
1213 * connection tracking */
1214 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1216 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1217 pAuthInfo->auth_data = NULL;
1218 pAuthInfo->auth_data_len = 0;
1222 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1224 HTTP_ProcessHeader(lpwhr, header, authorization,
1225 HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
1227 HeapFree(GetProcessHeap(), 0, authorization);
1229 return TRUE;
1232 /***********************************************************************
1233 * HTTP_InsertAuthorization
1235 * Insert the authorization field in the request header
1237 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr )
1239 return HTTP_InsertAuthorizationForHeader(lpwhr, lpwhr->pAuthInfo, szAuthorization);
1242 /***********************************************************************
1243 * HTTP_InsertProxyAuthorization
1245 * Insert the proxy authorization field in the request header
1247 static BOOL HTTP_InsertProxyAuthorization( LPWININETHTTPREQW lpwhr )
1249 return HTTP_InsertAuthorizationForHeader(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
1252 /***********************************************************************
1253 * HTTP_DealWithProxy
1255 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1256 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1258 WCHAR buf[MAXHOSTNAME];
1259 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1260 WCHAR* url;
1261 static WCHAR szNul[] = { 0 };
1262 URL_COMPONENTSW UrlComponents;
1263 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
1264 static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
1265 static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1266 int len;
1268 memset( &UrlComponents, 0, sizeof UrlComponents );
1269 UrlComponents.dwStructSize = sizeof UrlComponents;
1270 UrlComponents.lpszHostName = buf;
1271 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1273 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1274 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1275 sprintfW(proxy, szFormat1, hIC->lpszProxy);
1276 else
1277 strcpyW(proxy, hIC->lpszProxy);
1278 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1279 return FALSE;
1280 if( UrlComponents.dwHostNameLength == 0 )
1281 return FALSE;
1283 if( !lpwhr->lpszPath )
1284 lpwhr->lpszPath = szNul;
1285 TRACE("server=%s path=%s\n",
1286 debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
1287 /* for constant 15 see above */
1288 len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
1289 url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1291 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1292 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1294 sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
1296 if( lpwhr->lpszPath[0] != '/' )
1297 strcatW( url, szSlash );
1298 strcatW(url, lpwhr->lpszPath);
1299 if(lpwhr->lpszPath != szNul)
1300 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1301 lpwhr->lpszPath = url;
1303 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1304 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1305 lpwhs->nServerPort = UrlComponents.nPort;
1307 return TRUE;
1310 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1312 char szaddr[32];
1313 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1315 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1316 INTERNET_STATUS_RESOLVING_NAME,
1317 lpwhs->lpszServerName,
1318 strlenW(lpwhs->lpszServerName)+1);
1320 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1321 &lpwhs->socketAddress))
1323 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1324 return FALSE;
1327 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1328 szaddr, sizeof(szaddr));
1329 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1330 INTERNET_STATUS_NAME_RESOLVED,
1331 szaddr, strlen(szaddr)+1);
1332 return TRUE;
1335 /***********************************************************************
1336 * HTTP_HttpOpenRequestW (internal)
1338 * Open a HTTP request handle
1340 * RETURNS
1341 * HINTERNET a HTTP request handle on success
1342 * NULL on failure
1345 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1346 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1347 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1348 DWORD dwFlags, DWORD_PTR dwContext)
1350 LPWININETAPPINFOW hIC = NULL;
1351 LPWININETHTTPREQW lpwhr;
1352 LPWSTR lpszCookies;
1353 LPWSTR lpszUrl = NULL;
1354 DWORD nCookieSize;
1355 HINTERNET handle = NULL;
1356 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1357 DWORD len;
1358 LPHTTPHEADERW Host;
1360 TRACE("-->\n");
1362 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1363 hIC = lpwhs->lpAppInfo;
1365 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1366 if (NULL == lpwhr)
1368 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1369 goto lend;
1371 lpwhr->hdr.htype = WH_HHTTPREQ;
1372 lpwhr->hdr.dwFlags = dwFlags;
1373 lpwhr->hdr.dwContext = dwContext;
1374 lpwhr->hdr.dwRefCount = 1;
1375 lpwhr->hdr.close_connection = HTTP_CloseConnection;
1376 lpwhr->hdr.destroy = HTTP_CloseHTTPRequestHandle;
1377 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1378 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1380 WININET_AddRef( &lpwhs->hdr );
1381 lpwhr->lpHttpSession = lpwhs;
1382 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1384 handle = WININET_AllocHandle( &lpwhr->hdr );
1385 if (NULL == handle)
1387 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1388 goto lend;
1391 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1393 InternetCloseHandle( handle );
1394 handle = NULL;
1395 goto lend;
1398 if (NULL != lpszObjectName && strlenW(lpszObjectName)) {
1399 HRESULT rc;
1401 len = 0;
1402 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1403 if (rc != E_POINTER)
1404 len = strlenW(lpszObjectName)+1;
1405 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1406 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1407 URL_ESCAPE_SPACES_ONLY);
1408 if (rc)
1410 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1411 strcpyW(lpwhr->lpszPath,lpszObjectName);
1415 if (NULL != lpszReferrer && strlenW(lpszReferrer))
1416 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1418 if (lpszAcceptTypes)
1420 int i;
1421 for (i = 0; lpszAcceptTypes[i]; i++)
1423 if (!*lpszAcceptTypes[i]) continue;
1424 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1425 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1426 HTTP_ADDHDR_FLAG_REQ |
1427 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1431 if (NULL == lpszVerb)
1433 static const WCHAR szGet[] = {'G','E','T',0};
1434 lpwhr->lpszVerb = WININET_strdupW(szGet);
1436 else if (strlenW(lpszVerb))
1437 lpwhr->lpszVerb = WININET_strdupW(lpszVerb);
1439 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1441 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1442 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1443 INTERNET_DEFAULT_HTTPS_PORT :
1444 INTERNET_DEFAULT_HTTP_PORT);
1445 lpwhs->nHostPort = lpwhs->nServerPort;
1447 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1448 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1450 if (hIC->lpszAgent)
1452 WCHAR *agent_header;
1453 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1455 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1456 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1457 sprintfW(agent_header, user_agent, hIC->lpszAgent );
1459 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1460 HTTP_ADDREQ_FLAG_ADD);
1461 HeapFree(GetProcessHeap(), 0, agent_header);
1464 Host = HTTP_GetHeader(lpwhr,szHost);
1466 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1467 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1468 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1470 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1471 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1473 int cnt = 0;
1474 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1475 static const WCHAR szcrlf[] = {'\r','\n',0};
1477 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1479 cnt += sprintfW(lpszCookies, szCookie);
1480 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1481 strcatW(lpszCookies, szcrlf);
1483 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1484 HTTP_ADDREQ_FLAG_ADD);
1485 HeapFree(GetProcessHeap(), 0, lpszCookies);
1487 HeapFree(GetProcessHeap(), 0, lpszUrl);
1490 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1491 INTERNET_STATUS_HANDLE_CREATED, &handle,
1492 sizeof(handle));
1495 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1498 if (!HTTP_ResolveName(lpwhr))
1500 InternetCloseHandle( handle );
1501 handle = NULL;
1504 lend:
1505 if( lpwhr )
1506 WININET_Release( &lpwhr->hdr );
1508 TRACE("<-- %p (%p)\n", handle, lpwhr);
1509 return handle;
1512 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1513 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1514 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1515 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1516 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1517 static const WCHAR szAge[] = { 'A','g','e',0 };
1518 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1519 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1520 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1521 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1522 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1523 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1524 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1525 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1526 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1527 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1528 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1529 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 };
1530 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1531 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1532 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1533 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1534 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1535 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1536 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1537 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1538 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1539 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1540 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1541 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1542 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1543 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1544 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1545 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1546 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1547 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1548 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1549 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1550 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1551 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1552 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1553 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1554 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1555 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1556 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 };
1557 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1558 static const WCHAR szURI[] = { 'U','R','I',0 };
1559 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1560 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1561 static const WCHAR szVia[] = { 'V','i','a',0 };
1562 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1563 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1565 static const LPCWSTR header_lookup[] = {
1566 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
1567 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
1568 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1569 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
1570 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1571 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
1572 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
1573 szAllow, /* HTTP_QUERY_ALLOW = 7 */
1574 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
1575 szDate, /* HTTP_QUERY_DATE = 9 */
1576 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
1577 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
1578 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
1579 szURI, /* HTTP_QUERY_URI = 13 */
1580 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
1581 NULL, /* HTTP_QUERY_COST = 15 */
1582 NULL, /* HTTP_QUERY_LINK = 16 */
1583 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
1584 NULL, /* HTTP_QUERY_VERSION = 18 */
1585 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
1586 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
1587 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
1588 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
1589 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
1590 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
1591 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
1592 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
1593 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
1594 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
1595 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
1596 NULL, /* HTTP_QUERY_FORWARDED = 30 */
1597 NULL, /* HTTP_QUERY_FROM = 31 */
1598 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
1599 szLocation, /* HTTP_QUERY_LOCATION = 33 */
1600 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
1601 szReferer, /* HTTP_QUERY_REFERER = 35 */
1602 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
1603 szServer, /* HTTP_QUERY_SERVER = 37 */
1604 NULL, /* HTTP_TITLE = 38 */
1605 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
1606 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
1607 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
1608 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
1609 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
1610 szCookie, /* HTTP_QUERY_COOKIE = 44 */
1611 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
1612 NULL, /* HTTP_QUERY_REFRESH = 46 */
1613 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
1614 szAge, /* HTTP_QUERY_AGE = 48 */
1615 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
1616 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
1617 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
1618 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
1619 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
1620 szETag, /* HTTP_QUERY_ETAG = 54 */
1621 szHost, /* HTTP_QUERY_HOST = 55 */
1622 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
1623 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
1624 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
1625 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
1626 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
1627 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
1628 szRange, /* HTTP_QUERY_RANGE = 62 */
1629 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
1630 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
1631 szVary, /* HTTP_QUERY_VARY = 65 */
1632 szVia, /* HTTP_QUERY_VIA = 66 */
1633 szWarning, /* HTTP_QUERY_WARNING = 67 */
1634 szExpect, /* HTTP_QUERY_EXPECT = 68 */
1635 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
1636 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
1639 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
1641 /***********************************************************************
1642 * HTTP_HttpQueryInfoW (internal)
1644 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1645 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1647 LPHTTPHEADERW lphttpHdr = NULL;
1648 BOOL bSuccess = FALSE;
1649 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1650 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
1651 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
1652 INT index = -1;
1654 /* Find requested header structure */
1655 switch (level)
1657 case HTTP_QUERY_CUSTOM:
1658 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
1659 break;
1661 case HTTP_QUERY_RAW_HEADERS_CRLF:
1663 LPWSTR headers;
1664 DWORD len;
1665 BOOL ret;
1667 if (request_only)
1668 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, FALSE);
1669 else
1670 headers = lpwhr->lpszRawHeaders;
1672 len = strlenW(headers);
1673 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1675 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1676 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1677 ret = FALSE;
1678 } else
1680 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
1681 *lpdwBufferLength = len * sizeof(WCHAR);
1683 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1684 ret = TRUE;
1687 if (request_only)
1688 HeapFree(GetProcessHeap(), 0, headers);
1689 return ret;
1691 case HTTP_QUERY_RAW_HEADERS:
1693 static const WCHAR szCrLf[] = {'\r','\n',0};
1694 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1695 DWORD i, size = 0;
1696 LPWSTR pszString = (WCHAR*)lpBuffer;
1698 for (i = 0; ppszRawHeaderLines[i]; i++)
1699 size += strlenW(ppszRawHeaderLines[i]) + 1;
1701 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1703 HTTP_FreeTokens(ppszRawHeaderLines);
1704 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1705 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1706 return FALSE;
1709 for (i = 0; ppszRawHeaderLines[i]; i++)
1711 DWORD len = strlenW(ppszRawHeaderLines[i]);
1712 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1713 pszString += len+1;
1715 *pszString = '\0';
1717 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1719 *lpdwBufferLength = size * sizeof(WCHAR);
1720 HTTP_FreeTokens(ppszRawHeaderLines);
1722 return TRUE;
1724 case HTTP_QUERY_STATUS_TEXT:
1725 if (lpwhr->lpszStatusText)
1727 DWORD len = strlenW(lpwhr->lpszStatusText);
1728 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1730 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1731 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1732 return FALSE;
1734 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1735 *lpdwBufferLength = len * sizeof(WCHAR);
1737 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1739 return TRUE;
1741 break;
1742 case HTTP_QUERY_VERSION:
1743 if (lpwhr->lpszVersion)
1745 DWORD len = strlenW(lpwhr->lpszVersion);
1746 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1748 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1749 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1750 return FALSE;
1752 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
1753 *lpdwBufferLength = len * sizeof(WCHAR);
1755 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1757 return TRUE;
1759 break;
1760 default:
1761 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
1763 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
1764 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
1765 requested_index,request_only);
1768 if (index >= 0)
1769 lphttpHdr = &lpwhr->pCustHeaders[index];
1771 /* Ensure header satisfies requested attributes */
1772 if (!lphttpHdr ||
1773 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
1774 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
1776 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1777 return bSuccess;
1780 if (lpdwIndex)
1781 (*lpdwIndex)++;
1783 /* coalesce value to requested type */
1784 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
1786 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
1787 bSuccess = TRUE;
1789 TRACE(" returning number : %d\n", *(int *)lpBuffer);
1791 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
1793 time_t tmpTime;
1794 struct tm tmpTM;
1795 SYSTEMTIME *STHook;
1797 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
1799 tmpTM = *gmtime(&tmpTime);
1800 STHook = (SYSTEMTIME *) lpBuffer;
1801 if(STHook==NULL)
1802 return bSuccess;
1804 STHook->wDay = tmpTM.tm_mday;
1805 STHook->wHour = tmpTM.tm_hour;
1806 STHook->wMilliseconds = 0;
1807 STHook->wMinute = tmpTM.tm_min;
1808 STHook->wDayOfWeek = tmpTM.tm_wday;
1809 STHook->wMonth = tmpTM.tm_mon + 1;
1810 STHook->wSecond = tmpTM.tm_sec;
1811 STHook->wYear = tmpTM.tm_year;
1813 bSuccess = TRUE;
1815 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
1816 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
1817 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
1819 else if (lphttpHdr->lpszValue)
1821 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
1823 if (len > *lpdwBufferLength)
1825 *lpdwBufferLength = len;
1826 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1827 return bSuccess;
1830 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
1831 *lpdwBufferLength = len - sizeof(WCHAR);
1832 bSuccess = TRUE;
1834 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
1836 return bSuccess;
1839 /***********************************************************************
1840 * HttpQueryInfoW (WININET.@)
1842 * Queries for information about an HTTP request
1844 * RETURNS
1845 * TRUE on success
1846 * FALSE on failure
1849 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1850 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1852 BOOL bSuccess = FALSE;
1853 LPWININETHTTPREQW lpwhr;
1855 if (TRACE_ON(wininet)) {
1856 #define FE(x) { x, #x }
1857 static const wininet_flag_info query_flags[] = {
1858 FE(HTTP_QUERY_MIME_VERSION),
1859 FE(HTTP_QUERY_CONTENT_TYPE),
1860 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
1861 FE(HTTP_QUERY_CONTENT_ID),
1862 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
1863 FE(HTTP_QUERY_CONTENT_LENGTH),
1864 FE(HTTP_QUERY_CONTENT_LANGUAGE),
1865 FE(HTTP_QUERY_ALLOW),
1866 FE(HTTP_QUERY_PUBLIC),
1867 FE(HTTP_QUERY_DATE),
1868 FE(HTTP_QUERY_EXPIRES),
1869 FE(HTTP_QUERY_LAST_MODIFIED),
1870 FE(HTTP_QUERY_MESSAGE_ID),
1871 FE(HTTP_QUERY_URI),
1872 FE(HTTP_QUERY_DERIVED_FROM),
1873 FE(HTTP_QUERY_COST),
1874 FE(HTTP_QUERY_LINK),
1875 FE(HTTP_QUERY_PRAGMA),
1876 FE(HTTP_QUERY_VERSION),
1877 FE(HTTP_QUERY_STATUS_CODE),
1878 FE(HTTP_QUERY_STATUS_TEXT),
1879 FE(HTTP_QUERY_RAW_HEADERS),
1880 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
1881 FE(HTTP_QUERY_CONNECTION),
1882 FE(HTTP_QUERY_ACCEPT),
1883 FE(HTTP_QUERY_ACCEPT_CHARSET),
1884 FE(HTTP_QUERY_ACCEPT_ENCODING),
1885 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
1886 FE(HTTP_QUERY_AUTHORIZATION),
1887 FE(HTTP_QUERY_CONTENT_ENCODING),
1888 FE(HTTP_QUERY_FORWARDED),
1889 FE(HTTP_QUERY_FROM),
1890 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
1891 FE(HTTP_QUERY_LOCATION),
1892 FE(HTTP_QUERY_ORIG_URI),
1893 FE(HTTP_QUERY_REFERER),
1894 FE(HTTP_QUERY_RETRY_AFTER),
1895 FE(HTTP_QUERY_SERVER),
1896 FE(HTTP_QUERY_TITLE),
1897 FE(HTTP_QUERY_USER_AGENT),
1898 FE(HTTP_QUERY_WWW_AUTHENTICATE),
1899 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
1900 FE(HTTP_QUERY_ACCEPT_RANGES),
1901 FE(HTTP_QUERY_SET_COOKIE),
1902 FE(HTTP_QUERY_COOKIE),
1903 FE(HTTP_QUERY_REQUEST_METHOD),
1904 FE(HTTP_QUERY_REFRESH),
1905 FE(HTTP_QUERY_CONTENT_DISPOSITION),
1906 FE(HTTP_QUERY_AGE),
1907 FE(HTTP_QUERY_CACHE_CONTROL),
1908 FE(HTTP_QUERY_CONTENT_BASE),
1909 FE(HTTP_QUERY_CONTENT_LOCATION),
1910 FE(HTTP_QUERY_CONTENT_MD5),
1911 FE(HTTP_QUERY_CONTENT_RANGE),
1912 FE(HTTP_QUERY_ETAG),
1913 FE(HTTP_QUERY_HOST),
1914 FE(HTTP_QUERY_IF_MATCH),
1915 FE(HTTP_QUERY_IF_NONE_MATCH),
1916 FE(HTTP_QUERY_IF_RANGE),
1917 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
1918 FE(HTTP_QUERY_MAX_FORWARDS),
1919 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
1920 FE(HTTP_QUERY_RANGE),
1921 FE(HTTP_QUERY_TRANSFER_ENCODING),
1922 FE(HTTP_QUERY_UPGRADE),
1923 FE(HTTP_QUERY_VARY),
1924 FE(HTTP_QUERY_VIA),
1925 FE(HTTP_QUERY_WARNING),
1926 FE(HTTP_QUERY_CUSTOM)
1928 static const wininet_flag_info modifier_flags[] = {
1929 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
1930 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
1931 FE(HTTP_QUERY_FLAG_NUMBER),
1932 FE(HTTP_QUERY_FLAG_COALESCE)
1934 #undef FE
1935 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
1936 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
1937 DWORD i;
1939 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
1940 TRACE(" Attribute:");
1941 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
1942 if (query_flags[i].val == info) {
1943 TRACE(" %s", query_flags[i].name);
1944 break;
1947 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
1948 TRACE(" Unknown (%08x)", info);
1951 TRACE(" Modifier:");
1952 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
1953 if (modifier_flags[i].val & info_mod) {
1954 TRACE(" %s", modifier_flags[i].name);
1955 info_mod &= ~ modifier_flags[i].val;
1959 if (info_mod) {
1960 TRACE(" Unknown (%08x)", info_mod);
1962 TRACE("\n");
1965 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1966 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1968 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1969 goto lend;
1972 if (lpBuffer == NULL)
1973 *lpdwBufferLength = 0;
1974 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
1975 lpBuffer, lpdwBufferLength, lpdwIndex);
1977 lend:
1978 if( lpwhr )
1979 WININET_Release( &lpwhr->hdr );
1981 TRACE("%d <--\n", bSuccess);
1982 return bSuccess;
1985 /***********************************************************************
1986 * HttpQueryInfoA (WININET.@)
1988 * Queries for information about an HTTP request
1990 * RETURNS
1991 * TRUE on success
1992 * FALSE on failure
1995 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1996 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1998 BOOL result;
1999 DWORD len;
2000 WCHAR* bufferW;
2002 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2003 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2005 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2006 lpdwBufferLength, lpdwIndex );
2009 if (lpBuffer)
2011 len = (*lpdwBufferLength)*sizeof(WCHAR);
2012 bufferW = HeapAlloc( GetProcessHeap(), 0, len );
2013 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2014 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2015 MultiByteToWideChar(CP_ACP,0,lpBuffer,-1,bufferW,len);
2016 } else
2018 bufferW = NULL;
2019 len = 0;
2022 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2023 &len, lpdwIndex );
2024 if( result )
2026 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2027 lpBuffer, *lpdwBufferLength, NULL, NULL );
2028 *lpdwBufferLength = len - 1;
2030 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2032 else
2033 /* since the strings being returned from HttpQueryInfoW should be
2034 * only ASCII characters, it is reasonable to assume that all of
2035 * the Unicode characters can be reduced to a single byte */
2036 *lpdwBufferLength = len / sizeof(WCHAR);
2038 HeapFree(GetProcessHeap(), 0, bufferW );
2040 return result;
2043 /***********************************************************************
2044 * HttpSendRequestExA (WININET.@)
2046 * Sends the specified request to the HTTP server and allows chunked
2047 * transfers.
2049 * RETURNS
2050 * Success: TRUE
2051 * Failure: FALSE, call GetLastError() for more information.
2053 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2054 LPINTERNET_BUFFERSA lpBuffersIn,
2055 LPINTERNET_BUFFERSA lpBuffersOut,
2056 DWORD dwFlags, DWORD_PTR dwContext)
2058 INTERNET_BUFFERSW BuffersInW;
2059 BOOL rc = FALSE;
2060 DWORD headerlen;
2061 LPWSTR header = NULL;
2063 TRACE("(%p, %p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersIn,
2064 lpBuffersOut, dwFlags, dwContext);
2066 if (lpBuffersIn)
2068 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2069 if (lpBuffersIn->lpcszHeader)
2071 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2072 lpBuffersIn->dwHeadersLength,0,0);
2073 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2074 if (!(BuffersInW.lpcszHeader = header))
2076 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2077 return FALSE;
2079 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2080 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2081 header, headerlen);
2083 else
2084 BuffersInW.lpcszHeader = NULL;
2085 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2086 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2087 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2088 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2089 BuffersInW.Next = NULL;
2092 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2094 HeapFree(GetProcessHeap(),0,header);
2096 return rc;
2099 /***********************************************************************
2100 * HttpSendRequestExW (WININET.@)
2102 * Sends the specified request to the HTTP server and allows chunked
2103 * transfers
2105 * RETURNS
2106 * Success: TRUE
2107 * Failure: FALSE, call GetLastError() for more information.
2109 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2110 LPINTERNET_BUFFERSW lpBuffersIn,
2111 LPINTERNET_BUFFERSW lpBuffersOut,
2112 DWORD dwFlags, DWORD_PTR dwContext)
2114 BOOL ret = FALSE;
2115 LPWININETHTTPREQW lpwhr;
2116 LPWININETHTTPSESSIONW lpwhs;
2117 LPWININETAPPINFOW hIC;
2119 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2120 lpBuffersOut, dwFlags, dwContext);
2122 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2124 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2126 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2127 goto lend;
2130 lpwhs = lpwhr->lpHttpSession;
2131 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2132 hIC = lpwhs->lpAppInfo;
2133 assert(hIC->hdr.htype == WH_HINIT);
2135 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2137 WORKREQUEST workRequest;
2138 struct WORKREQ_HTTPSENDREQUESTW *req;
2140 workRequest.asyncproc = AsyncHttpSendRequestProc;
2141 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2142 req = &workRequest.u.HttpSendRequestW;
2143 if (lpBuffersIn)
2145 if (lpBuffersIn->lpcszHeader)
2146 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2147 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2148 else
2149 req->lpszHeader = NULL;
2150 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2151 req->lpOptional = lpBuffersIn->lpvBuffer;
2152 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2153 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2155 else
2157 req->lpszHeader = NULL;
2158 req->dwHeaderLength = 0;
2159 req->lpOptional = NULL;
2160 req->dwOptionalLength = 0;
2161 req->dwContentLength = 0;
2164 req->bEndRequest = FALSE;
2166 INTERNET_AsyncCall(&workRequest);
2168 * This is from windows.
2170 INTERNET_SetLastError(ERROR_IO_PENDING);
2172 else
2174 if (lpBuffersIn)
2175 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2176 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2177 lpBuffersIn->dwBufferTotal, FALSE);
2178 else
2179 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2182 lend:
2183 if ( lpwhr )
2184 WININET_Release( &lpwhr->hdr );
2186 TRACE("<---\n");
2187 return ret;
2190 /***********************************************************************
2191 * HttpSendRequestW (WININET.@)
2193 * Sends the specified request to the HTTP server
2195 * RETURNS
2196 * TRUE on success
2197 * FALSE on failure
2200 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2201 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2203 LPWININETHTTPREQW lpwhr;
2204 LPWININETHTTPSESSIONW lpwhs = NULL;
2205 LPWININETAPPINFOW hIC = NULL;
2206 BOOL r;
2208 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2209 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2211 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2212 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2214 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2215 r = FALSE;
2216 goto lend;
2219 lpwhs = lpwhr->lpHttpSession;
2220 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2222 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2223 r = FALSE;
2224 goto lend;
2227 hIC = lpwhs->lpAppInfo;
2228 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2230 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2231 r = FALSE;
2232 goto lend;
2235 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2237 WORKREQUEST workRequest;
2238 struct WORKREQ_HTTPSENDREQUESTW *req;
2240 workRequest.asyncproc = AsyncHttpSendRequestProc;
2241 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2242 req = &workRequest.u.HttpSendRequestW;
2243 if (lpszHeaders)
2245 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2246 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2248 else
2249 req->lpszHeader = 0;
2250 req->dwHeaderLength = dwHeaderLength;
2251 req->lpOptional = lpOptional;
2252 req->dwOptionalLength = dwOptionalLength;
2253 req->dwContentLength = dwOptionalLength;
2254 req->bEndRequest = TRUE;
2256 INTERNET_AsyncCall(&workRequest);
2258 * This is from windows.
2260 INTERNET_SetLastError(ERROR_IO_PENDING);
2261 r = FALSE;
2263 else
2265 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2266 dwHeaderLength, lpOptional, dwOptionalLength,
2267 dwOptionalLength, TRUE);
2269 lend:
2270 if( lpwhr )
2271 WININET_Release( &lpwhr->hdr );
2272 return r;
2275 /***********************************************************************
2276 * HttpSendRequestA (WININET.@)
2278 * Sends the specified request to the HTTP server
2280 * RETURNS
2281 * TRUE on success
2282 * FALSE on failure
2285 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2286 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2288 BOOL result;
2289 LPWSTR szHeaders=NULL;
2290 DWORD nLen=dwHeaderLength;
2291 if(lpszHeaders!=NULL)
2293 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2294 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2295 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2297 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2298 HeapFree(GetProcessHeap(),0,szHeaders);
2299 return result;
2302 /***********************************************************************
2303 * HTTP_HandleRedirect (internal)
2305 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2307 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2308 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2309 WCHAR path[2048];
2311 if(lpszUrl[0]=='/')
2313 /* if it's an absolute path, keep the same session info */
2314 lstrcpynW(path, lpszUrl, 2048);
2316 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2318 TRACE("Redirect through proxy\n");
2319 lstrcpynW(path, lpszUrl, 2048);
2321 else
2323 URL_COMPONENTSW urlComponents;
2324 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2325 static WCHAR szHttp[] = {'h','t','t','p',0};
2326 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2327 DWORD url_length = 0;
2328 LPWSTR orig_url;
2329 LPWSTR combined_url;
2331 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2332 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2333 urlComponents.dwSchemeLength = 0;
2334 urlComponents.lpszHostName = lpwhs->lpszHostName;
2335 urlComponents.dwHostNameLength = 0;
2336 urlComponents.nPort = lpwhs->nHostPort;
2337 urlComponents.lpszUserName = lpwhs->lpszUserName;
2338 urlComponents.dwUserNameLength = 0;
2339 urlComponents.lpszPassword = NULL;
2340 urlComponents.dwPasswordLength = 0;
2341 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2342 urlComponents.dwUrlPathLength = 0;
2343 urlComponents.lpszExtraInfo = NULL;
2344 urlComponents.dwExtraInfoLength = 0;
2346 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2347 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2348 return FALSE;
2350 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2352 /* convert from bytes to characters */
2353 url_length = url_length / sizeof(WCHAR) - 1;
2354 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2356 HeapFree(GetProcessHeap(), 0, orig_url);
2357 return FALSE;
2360 url_length = 0;
2361 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2362 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2364 HeapFree(GetProcessHeap(), 0, orig_url);
2365 return FALSE;
2367 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2369 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2371 HeapFree(GetProcessHeap(), 0, orig_url);
2372 HeapFree(GetProcessHeap(), 0, combined_url);
2373 return FALSE;
2375 HeapFree(GetProcessHeap(), 0, orig_url);
2377 userName[0] = 0;
2378 hostName[0] = 0;
2379 protocol[0] = 0;
2381 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2382 urlComponents.lpszScheme = protocol;
2383 urlComponents.dwSchemeLength = 32;
2384 urlComponents.lpszHostName = hostName;
2385 urlComponents.dwHostNameLength = MAXHOSTNAME;
2386 urlComponents.lpszUserName = userName;
2387 urlComponents.dwUserNameLength = 1024;
2388 urlComponents.lpszPassword = NULL;
2389 urlComponents.dwPasswordLength = 0;
2390 urlComponents.lpszUrlPath = path;
2391 urlComponents.dwUrlPathLength = 2048;
2392 urlComponents.lpszExtraInfo = NULL;
2393 urlComponents.dwExtraInfoLength = 0;
2394 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2396 HeapFree(GetProcessHeap(), 0, combined_url);
2397 return FALSE;
2399 HeapFree(GetProcessHeap(), 0, combined_url);
2401 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2402 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2404 TRACE("redirect from secure page to non-secure page\n");
2405 /* FIXME: warn about from secure redirect to non-secure page */
2406 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2408 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2409 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2411 TRACE("redirect from non-secure page to secure page\n");
2412 /* FIXME: notify about redirect to secure page */
2413 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2416 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2418 if (lstrlenW(protocol)>4) /*https*/
2419 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2420 else /*http*/
2421 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2424 #if 0
2426 * This upsets redirects to binary files on sourceforge.net
2427 * and gives an html page instead of the target file
2428 * Examination of the HTTP request sent by native wininet.dll
2429 * reveals that it doesn't send a referrer in that case.
2430 * Maybe there's a flag that enables this, or maybe a referrer
2431 * shouldn't be added in case of a redirect.
2434 /* consider the current host as the referrer */
2435 if (NULL != lpwhs->lpszServerName && strlenW(lpwhs->lpszServerName))
2436 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2437 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2438 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2439 #endif
2441 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2442 lpwhs->lpszServerName = WININET_strdupW(hostName);
2443 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2444 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2445 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2447 int len;
2448 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2449 len = lstrlenW(hostName);
2450 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2451 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2452 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2454 else
2455 lpwhs->lpszHostName = WININET_strdupW(hostName);
2457 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2460 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2461 lpwhs->lpszUserName = NULL;
2462 if (userName[0])
2463 lpwhs->lpszUserName = WININET_strdupW(userName);
2464 lpwhs->nServerPort = urlComponents.nPort;
2466 if (!HTTP_ResolveName(lpwhr))
2467 return FALSE;
2469 NETCON_close(&lpwhr->netConnection);
2471 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2472 return FALSE;
2475 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2476 lpwhr->lpszPath=NULL;
2477 if (strlenW(path))
2479 DWORD needed = 0;
2480 HRESULT rc;
2482 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2483 if (rc != E_POINTER)
2484 needed = strlenW(path)+1;
2485 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2486 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2487 URL_ESCAPE_SPACES_ONLY);
2488 if (rc)
2490 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2491 strcpyW(lpwhr->lpszPath,path);
2495 return TRUE;
2498 /***********************************************************************
2499 * HTTP_build_req (internal)
2501 * concatenate all the strings in the request together
2503 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2505 LPCWSTR *t;
2506 LPWSTR str;
2508 for( t = list; *t ; t++ )
2509 len += strlenW( *t );
2510 len++;
2512 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2513 *str = 0;
2515 for( t = list; *t ; t++ )
2516 strcatW( str, *t );
2518 return str;
2521 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2523 LPWSTR lpszPath;
2524 LPWSTR requestString;
2525 INT len;
2526 INT cnt;
2527 INT responseLen;
2528 char *ascii_req;
2529 BOOL ret;
2530 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2531 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2532 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2534 TRACE("\n");
2536 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2537 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2538 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, FALSE );
2539 HeapFree( GetProcessHeap(), 0, lpszPath );
2541 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2542 NULL, 0, NULL, NULL );
2543 len--; /* the nul terminator isn't needed */
2544 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2545 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2546 ascii_req, len, NULL, NULL );
2547 HeapFree( GetProcessHeap(), 0, requestString );
2549 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2551 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2552 HeapFree( GetProcessHeap(), 0, ascii_req );
2553 if (!ret || cnt < 0)
2554 return FALSE;
2556 responseLen = HTTP_GetResponseHeaders( lpwhr );
2557 if (!responseLen)
2558 return FALSE;
2560 return TRUE;
2563 /***********************************************************************
2564 * HTTP_HttpSendRequestW (internal)
2566 * Sends the specified request to the HTTP server
2568 * RETURNS
2569 * TRUE on success
2570 * FALSE on failure
2573 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2574 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2575 DWORD dwContentLength, BOOL bEndRequest)
2577 INT cnt;
2578 BOOL bSuccess = FALSE;
2579 LPWSTR requestString = NULL;
2580 INT responseLen;
2581 BOOL loop_next;
2582 INTERNET_ASYNC_RESULT iar;
2583 static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
2584 static const WCHAR szContentLength[] =
2585 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
2586 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
2588 TRACE("--> %p\n", lpwhr);
2590 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2592 /* Clear any error information */
2593 INTERNET_SetLastError(0);
2595 HTTP_FixVerb(lpwhr);
2597 sprintfW(contentLengthStr, szContentLength, dwContentLength);
2598 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2602 DWORD len;
2603 char *ascii_req;
2605 loop_next = FALSE;
2607 /* like native, just in case the caller forgot to call InternetReadFile
2608 * for all the data */
2609 HTTP_DrainContent(lpwhr);
2610 lpwhr->dwContentRead = 0;
2612 if (TRACE_ON(wininet))
2614 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
2615 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2618 HTTP_FixURL(lpwhr);
2619 HTTP_ProcessHeader(lpwhr, szConnection,
2620 lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
2621 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
2623 HTTP_InsertAuthorization(lpwhr);
2624 HTTP_InsertProxyAuthorization(lpwhr);
2626 /* add the headers the caller supplied */
2627 if( lpszHeaders && dwHeaderLength )
2629 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2630 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2633 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, FALSE);
2635 TRACE("Request header -> %s\n", debugstr_w(requestString) );
2637 /* Send the request and store the results */
2638 if (!HTTP_OpenConnection(lpwhr))
2639 goto lend;
2641 /* send the request as ASCII, tack on the optional data */
2642 if( !lpOptional )
2643 dwOptionalLength = 0;
2644 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2645 NULL, 0, NULL, NULL );
2646 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2647 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2648 ascii_req, len, NULL, NULL );
2649 if( lpOptional )
2650 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2651 len = (len + dwOptionalLength - 1);
2652 ascii_req[len] = 0;
2653 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2655 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2656 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2658 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2659 HeapFree( GetProcessHeap(), 0, ascii_req );
2661 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2662 INTERNET_STATUS_REQUEST_SENT,
2663 &len, sizeof(DWORD));
2665 if (bEndRequest)
2667 DWORD dwBufferSize;
2668 DWORD dwStatusCode;
2670 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2671 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2673 if (cnt < 0)
2674 goto lend;
2676 responseLen = HTTP_GetResponseHeaders(lpwhr);
2677 if (responseLen)
2678 bSuccess = TRUE;
2680 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2681 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2682 sizeof(DWORD));
2684 HTTP_ProcessHeaders(lpwhr);
2686 dwBufferSize = sizeof(lpwhr->dwContentLength);
2687 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2688 &lpwhr->dwContentLength,&dwBufferSize,NULL))
2689 lpwhr->dwContentLength = -1;
2691 if (lpwhr->dwContentLength == 0)
2692 HTTP_FinishedReading(lpwhr);
2694 dwBufferSize = sizeof(dwStatusCode);
2695 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
2696 &dwStatusCode,&dwBufferSize,NULL))
2697 dwStatusCode = 0;
2699 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
2701 WCHAR szNewLocation[2048];
2702 dwBufferSize=sizeof(szNewLocation);
2703 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
2704 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
2706 HTTP_DrainContent(lpwhr);
2707 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2708 INTERNET_STATUS_REDIRECT, szNewLocation,
2709 dwBufferSize);
2710 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
2711 if (bSuccess)
2713 HeapFree(GetProcessHeap(), 0, requestString);
2714 loop_next = TRUE;
2718 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
2720 WCHAR szAuthValue[2048];
2721 dwBufferSize=2048;
2722 if (dwStatusCode == HTTP_STATUS_DENIED)
2724 DWORD dwIndex = 0;
2725 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2727 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2728 &lpwhr->pAuthInfo,
2729 lpwhr->lpHttpSession->lpszUserName,
2730 lpwhr->lpHttpSession->lpszPassword))
2732 loop_next = TRUE;
2733 break;
2737 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
2739 DWORD dwIndex = 0;
2740 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2742 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2743 &lpwhr->pProxyAuthInfo,
2744 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
2745 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
2747 loop_next = TRUE;
2748 break;
2754 else
2755 bSuccess = TRUE;
2757 while (loop_next);
2759 lend:
2761 HeapFree(GetProcessHeap(), 0, requestString);
2763 /* TODO: send notification for P3P header */
2765 iar.dwResult = (DWORD)bSuccess;
2766 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2768 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2769 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2770 sizeof(INTERNET_ASYNC_RESULT));
2772 TRACE("<--\n");
2773 return bSuccess;
2776 /***********************************************************************
2777 * HTTP_Connect (internal)
2779 * Create http session handle
2781 * RETURNS
2782 * HINTERNET a session handle on success
2783 * NULL on failure
2786 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
2787 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2788 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
2789 DWORD dwInternalFlags)
2791 BOOL bSuccess = FALSE;
2792 LPWININETHTTPSESSIONW lpwhs = NULL;
2793 HINTERNET handle = NULL;
2795 TRACE("-->\n");
2797 assert( hIC->hdr.htype == WH_HINIT );
2799 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
2800 if (NULL == lpwhs)
2802 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2803 goto lerror;
2807 * According to my tests. The name is not resolved until a request is sent
2810 lpwhs->hdr.htype = WH_HHTTPSESSION;
2811 lpwhs->hdr.dwFlags = dwFlags;
2812 lpwhs->hdr.dwContext = dwContext;
2813 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
2814 lpwhs->hdr.dwRefCount = 1;
2815 lpwhs->hdr.close_connection = NULL;
2816 lpwhs->hdr.destroy = HTTP_CloseHTTPSessionHandle;
2817 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
2819 WININET_AddRef( &hIC->hdr );
2820 lpwhs->lpAppInfo = hIC;
2821 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
2823 handle = WININET_AllocHandle( &lpwhs->hdr );
2824 if (NULL == handle)
2826 ERR("Failed to alloc handle\n");
2827 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2828 goto lerror;
2831 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
2832 if(strchrW(hIC->lpszProxy, ' '))
2833 FIXME("Several proxies not implemented.\n");
2834 if(hIC->lpszProxyBypass)
2835 FIXME("Proxy bypass is ignored.\n");
2837 if (lpszServerName && lpszServerName[0])
2839 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
2840 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
2842 if (lpszUserName && lpszUserName[0])
2843 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
2844 if (lpszPassword && lpszPassword[0])
2845 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
2846 lpwhs->nServerPort = nServerPort;
2847 lpwhs->nHostPort = nServerPort;
2849 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
2850 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
2852 INTERNET_SendCallback(&hIC->hdr, dwContext,
2853 INTERNET_STATUS_HANDLE_CREATED, &handle,
2854 sizeof(handle));
2857 bSuccess = TRUE;
2859 lerror:
2860 if( lpwhs )
2861 WININET_Release( &lpwhs->hdr );
2864 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
2865 * windows
2868 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
2869 return handle;
2873 /***********************************************************************
2874 * HTTP_OpenConnection (internal)
2876 * Connect to a web server
2878 * RETURNS
2880 * TRUE on success
2881 * FALSE on failure
2883 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
2885 BOOL bSuccess = FALSE;
2886 LPWININETHTTPSESSIONW lpwhs;
2887 LPWININETAPPINFOW hIC = NULL;
2888 char szaddr[32];
2890 TRACE("-->\n");
2893 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2895 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2896 goto lend;
2899 if (NETCON_connected(&lpwhr->netConnection))
2901 bSuccess = TRUE;
2902 goto lend;
2905 lpwhs = lpwhr->lpHttpSession;
2907 hIC = lpwhs->lpAppInfo;
2908 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
2909 szaddr, sizeof(szaddr));
2910 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2911 INTERNET_STATUS_CONNECTING_TO_SERVER,
2912 szaddr,
2913 strlen(szaddr)+1);
2915 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
2916 SOCK_STREAM, 0))
2918 WARN("Socket creation failed\n");
2919 goto lend;
2922 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
2923 sizeof(lpwhs->socketAddress)))
2924 goto lend;
2926 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
2928 /* Note: we differ from Microsoft's WinINet here. they seem to have
2929 * a bug that causes no status callbacks to be sent when starting
2930 * a tunnel to a proxy server using the CONNECT verb. i believe our
2931 * behaviour to be more correct and to not cause any incompatibilities
2932 * because using a secure connection through a proxy server is a rare
2933 * case that would be hard for anyone to depend on */
2934 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
2935 goto lend;
2937 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
2939 WARN("Couldn't connect securely to host\n");
2940 goto lend;
2944 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2945 INTERNET_STATUS_CONNECTED_TO_SERVER,
2946 szaddr, strlen(szaddr)+1);
2948 bSuccess = TRUE;
2950 lend:
2951 TRACE("%d <--\n", bSuccess);
2952 return bSuccess;
2956 /***********************************************************************
2957 * HTTP_clear_response_headers (internal)
2959 * clear out any old response headers
2961 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
2963 DWORD i;
2965 for( i=0; i<lpwhr->nCustHeaders; i++)
2967 if( !lpwhr->pCustHeaders[i].lpszField )
2968 continue;
2969 if( !lpwhr->pCustHeaders[i].lpszValue )
2970 continue;
2971 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
2972 continue;
2973 HTTP_DeleteCustomHeader( lpwhr, i );
2974 i--;
2978 /***********************************************************************
2979 * HTTP_GetResponseHeaders (internal)
2981 * Read server response
2983 * RETURNS
2985 * TRUE on success
2986 * FALSE on error
2988 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
2990 INT cbreaks = 0;
2991 WCHAR buffer[MAX_REPLY_LEN];
2992 DWORD buflen = MAX_REPLY_LEN;
2993 BOOL bSuccess = FALSE;
2994 INT rc = 0;
2995 static const WCHAR szCrLf[] = {'\r','\n',0};
2996 char bufferA[MAX_REPLY_LEN];
2997 LPWSTR status_code, status_text;
2998 DWORD cchMaxRawHeaders = 1024;
2999 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3000 DWORD cchRawHeaders = 0;
3002 TRACE("-->\n");
3004 /* clear old response headers (eg. from a redirect response) */
3005 HTTP_clear_response_headers( lpwhr );
3007 if (!NETCON_connected(&lpwhr->netConnection))
3008 goto lend;
3011 * HACK peek at the buffer
3013 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3016 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3018 buflen = MAX_REPLY_LEN;
3019 memset(buffer, 0, MAX_REPLY_LEN);
3020 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3021 goto lend;
3022 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3024 /* regenerate raw headers */
3025 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3027 cchMaxRawHeaders *= 2;
3028 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3030 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3031 cchRawHeaders += (buflen-1);
3032 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3033 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3034 lpszRawHeaders[cchRawHeaders] = '\0';
3036 /* split the version from the status code */
3037 status_code = strchrW( buffer, ' ' );
3038 if( !status_code )
3039 goto lend;
3040 *status_code++=0;
3042 /* split the status code from the status text */
3043 status_text = strchrW( status_code, ' ' );
3044 if( !status_text )
3045 goto lend;
3046 *status_text++=0;
3048 TRACE("version [%s] status code [%s] status text [%s]\n",
3049 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3051 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3052 HTTP_ADDHDR_FLAG_REPLACE);
3054 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3055 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3057 lpwhr->lpszVersion= WININET_strdupW(buffer);
3058 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3060 /* Parse each response line */
3063 buflen = MAX_REPLY_LEN;
3064 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3066 LPWSTR * pFieldAndValue;
3068 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3069 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3071 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3073 cchMaxRawHeaders *= 2;
3074 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3076 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3077 cchRawHeaders += (buflen-1);
3078 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3079 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3080 lpszRawHeaders[cchRawHeaders] = '\0';
3082 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3083 if (!pFieldAndValue)
3084 break;
3086 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3087 HTTP_ADDREQ_FLAG_ADD );
3089 HTTP_FreeTokens(pFieldAndValue);
3091 else
3093 cbreaks++;
3094 if (cbreaks >= 2)
3095 break;
3097 }while(1);
3099 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3100 lpwhr->lpszRawHeaders = lpszRawHeaders;
3101 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3102 bSuccess = TRUE;
3104 lend:
3106 TRACE("<--\n");
3107 if (bSuccess)
3108 return rc;
3109 else
3110 return 0;
3114 static void strip_spaces(LPWSTR start)
3116 LPWSTR str = start;
3117 LPWSTR end;
3119 while (*str == ' ' && *str != '\0')
3120 str++;
3122 if (str != start)
3123 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3125 end = start + strlenW(start) - 1;
3126 while (end >= start && *end == ' ')
3128 *end = '\0';
3129 end--;
3134 /***********************************************************************
3135 * HTTP_InterpretHttpHeader (internal)
3137 * Parse server response
3139 * RETURNS
3141 * Pointer to array of field, value, NULL on success.
3142 * NULL on error.
3144 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3146 LPWSTR * pTokenPair;
3147 LPWSTR pszColon;
3148 INT len;
3150 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3152 pszColon = strchrW(buffer, ':');
3153 /* must have two tokens */
3154 if (!pszColon)
3156 HTTP_FreeTokens(pTokenPair);
3157 if (buffer[0])
3158 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3159 return NULL;
3162 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3163 if (!pTokenPair[0])
3165 HTTP_FreeTokens(pTokenPair);
3166 return NULL;
3168 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3169 pTokenPair[0][pszColon - buffer] = '\0';
3171 /* skip colon */
3172 pszColon++;
3173 len = strlenW(pszColon);
3174 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3175 if (!pTokenPair[1])
3177 HTTP_FreeTokens(pTokenPair);
3178 return NULL;
3180 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3182 strip_spaces(pTokenPair[0]);
3183 strip_spaces(pTokenPair[1]);
3185 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3186 return pTokenPair;
3189 /***********************************************************************
3190 * HTTP_ProcessHeader (internal)
3192 * Stuff header into header tables according to <dwModifier>
3196 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3198 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3200 LPHTTPHEADERW lphttpHdr = NULL;
3201 BOOL bSuccess = FALSE;
3202 INT index = -1;
3203 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3205 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3207 /* REPLACE wins out over ADD */
3208 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3209 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3211 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3212 index = -1;
3213 else
3214 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3216 if (index >= 0)
3218 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3220 return FALSE;
3222 lphttpHdr = &lpwhr->pCustHeaders[index];
3224 else if (value)
3226 HTTPHEADERW hdr;
3228 hdr.lpszField = (LPWSTR)field;
3229 hdr.lpszValue = (LPWSTR)value;
3230 hdr.wFlags = hdr.wCount = 0;
3232 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3233 hdr.wFlags |= HDR_ISREQUEST;
3235 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3237 /* no value to delete */
3238 else return TRUE;
3240 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3241 lphttpHdr->wFlags |= HDR_ISREQUEST;
3242 else
3243 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3245 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3247 HTTP_DeleteCustomHeader( lpwhr, index );
3249 if (value)
3251 HTTPHEADERW hdr;
3253 hdr.lpszField = (LPWSTR)field;
3254 hdr.lpszValue = (LPWSTR)value;
3255 hdr.wFlags = hdr.wCount = 0;
3257 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3258 hdr.wFlags |= HDR_ISREQUEST;
3260 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3263 return TRUE;
3265 else if (dwModifier & COALESCEFLAGS)
3267 LPWSTR lpsztmp;
3268 WCHAR ch = 0;
3269 INT len = 0;
3270 INT origlen = strlenW(lphttpHdr->lpszValue);
3271 INT valuelen = strlenW(value);
3273 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3275 ch = ',';
3276 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3278 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3280 ch = ';';
3281 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3284 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3286 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3287 if (lpsztmp)
3289 lphttpHdr->lpszValue = lpsztmp;
3290 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3291 if (ch > 0)
3293 lphttpHdr->lpszValue[origlen] = ch;
3294 origlen++;
3295 lphttpHdr->lpszValue[origlen] = ' ';
3296 origlen++;
3299 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3300 lphttpHdr->lpszValue[len] = '\0';
3301 bSuccess = TRUE;
3303 else
3305 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3306 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3309 TRACE("<-- %d\n",bSuccess);
3310 return bSuccess;
3314 /***********************************************************************
3315 * HTTP_CloseConnection (internal)
3317 * Close socket connection
3320 static void HTTP_CloseConnection(LPWININETHANDLEHEADER hdr)
3322 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
3323 LPWININETHTTPSESSIONW lpwhs = NULL;
3324 LPWININETAPPINFOW hIC = NULL;
3326 TRACE("%p\n",lpwhr);
3328 if (!NETCON_connected(&lpwhr->netConnection))
3329 return;
3331 if (lpwhr->pAuthInfo)
3333 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
3334 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
3336 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
3337 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
3338 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
3339 lpwhr->pAuthInfo = NULL;
3341 if (lpwhr->pProxyAuthInfo)
3343 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
3344 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
3346 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
3347 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
3348 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
3349 lpwhr->pProxyAuthInfo = NULL;
3352 lpwhs = lpwhr->lpHttpSession;
3353 hIC = lpwhs->lpAppInfo;
3355 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3356 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
3358 NETCON_close(&lpwhr->netConnection);
3360 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3361 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
3365 /***********************************************************************
3366 * HTTP_FinishedReading (internal)
3368 * Called when all content from server has been read by client.
3371 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
3373 WCHAR szConnectionResponse[20];
3374 DWORD dwBufferSize = sizeof(szConnectionResponse);
3376 TRACE("\n");
3378 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse,
3379 &dwBufferSize, NULL) ||
3380 strcmpiW(szConnectionResponse, szKeepAlive))
3382 HTTP_CloseConnection(&lpwhr->hdr);
3385 /* FIXME: store data in the URL cache here */
3387 return TRUE;
3390 /***********************************************************************
3391 * HTTP_CloseHTTPRequestHandle (internal)
3393 * Deallocate request handle
3396 static void HTTP_CloseHTTPRequestHandle(LPWININETHANDLEHEADER hdr)
3398 DWORD i;
3399 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
3401 TRACE("\n");
3403 WININET_Release(&lpwhr->lpHttpSession->hdr);
3405 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3406 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3407 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3408 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
3409 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
3411 for (i = 0; i < lpwhr->nCustHeaders; i++)
3413 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
3414 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
3417 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
3418 HeapFree(GetProcessHeap(), 0, lpwhr);
3422 /***********************************************************************
3423 * HTTP_CloseHTTPSessionHandle (internal)
3425 * Deallocate session handle
3428 static void HTTP_CloseHTTPSessionHandle(LPWININETHANDLEHEADER hdr)
3430 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3432 TRACE("%p\n", lpwhs);
3434 WININET_Release(&lpwhs->lpAppInfo->hdr);
3436 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3437 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3438 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3439 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3440 HeapFree(GetProcessHeap(), 0, lpwhs);
3444 /***********************************************************************
3445 * HTTP_GetCustomHeaderIndex (internal)
3447 * Return index of custom header from header array
3450 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
3451 int requested_index, BOOL request_only)
3453 DWORD index;
3455 TRACE("%s\n", debugstr_w(lpszField));
3457 for (index = 0; index < lpwhr->nCustHeaders; index++)
3459 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3460 continue;
3462 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3463 continue;
3465 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3466 continue;
3468 if (requested_index == 0)
3469 break;
3470 requested_index --;
3473 if (index >= lpwhr->nCustHeaders)
3474 index = -1;
3476 TRACE("Return: %d\n", index);
3477 return index;
3481 /***********************************************************************
3482 * HTTP_InsertCustomHeader (internal)
3484 * Insert header into array
3487 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3489 INT count;
3490 LPHTTPHEADERW lph = NULL;
3491 BOOL r = FALSE;
3493 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3494 count = lpwhr->nCustHeaders + 1;
3495 if (count > 1)
3496 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3497 else
3498 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3500 if (NULL != lph)
3502 lpwhr->pCustHeaders = lph;
3503 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3504 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3505 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3506 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3507 lpwhr->nCustHeaders++;
3508 r = TRUE;
3510 else
3512 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3515 return r;
3519 /***********************************************************************
3520 * HTTP_DeleteCustomHeader (internal)
3522 * Delete header from array
3523 * If this function is called, the indexs may change.
3525 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3527 if( lpwhr->nCustHeaders <= 0 )
3528 return FALSE;
3529 if( index >= lpwhr->nCustHeaders )
3530 return FALSE;
3531 lpwhr->nCustHeaders--;
3533 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3534 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3535 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3537 return TRUE;
3541 /***********************************************************************
3542 * HTTP_VerifyValidHeader (internal)
3544 * Verify the given header is not invalid for the given http request
3547 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
3549 BOOL rc = TRUE;
3551 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
3552 if (strcmpiW(field,szAccept_Encoding)==0)
3553 return FALSE;
3555 return rc;
3558 /***********************************************************************
3559 * IsHostInProxyBypassList (@)
3561 * Undocumented
3564 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3566 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
3567 return FALSE;