wininet: Moved handle destructor to vtbl.
[wine.git] / dlls / wininet / http.c
blobc9fa5e0d54312fad59d890bf382cbbf09653db1e
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_1[] = {'H','T','T','P','/','1','.','1',0};
66 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
67 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
68 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
69 static const WCHAR szHost[] = { 'H','o','s','t',0 };
70 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
71 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
73 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
74 static const WCHAR szGET[] = { 'G','E','T', 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 BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
108 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr);
109 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
110 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
111 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
112 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
113 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
114 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
115 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
116 dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
117 lpdwIndex);
118 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
119 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
120 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
123 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
125 int HeaderIndex = 0;
126 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
127 if (HeaderIndex == -1)
128 return NULL;
129 else
130 return &req->pCustHeaders[HeaderIndex];
133 /***********************************************************************
134 * HTTP_Tokenize (internal)
136 * Tokenize a string, allocating memory for the tokens.
138 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
140 LPWSTR * token_array;
141 int tokens = 0;
142 int i;
143 LPCWSTR next_token;
145 /* empty string has no tokens */
146 if (*string)
147 tokens++;
148 /* count tokens */
149 for (i = 0; string[i]; i++)
150 if (!strncmpW(string+i, token_string, strlenW(token_string)))
152 DWORD j;
153 tokens++;
154 /* we want to skip over separators, but not the null terminator */
155 for (j = 0; j < strlenW(token_string) - 1; j++)
156 if (!string[i+j])
157 break;
158 i += j;
161 /* add 1 for terminating NULL */
162 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
163 token_array[tokens] = NULL;
164 if (!tokens)
165 return token_array;
166 for (i = 0; i < tokens; i++)
168 int len;
169 next_token = strstrW(string, token_string);
170 if (!next_token) next_token = string+strlenW(string);
171 len = next_token - string;
172 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
173 memcpy(token_array[i], string, len*sizeof(WCHAR));
174 token_array[i][len] = '\0';
175 string = next_token+strlenW(token_string);
177 return token_array;
180 /***********************************************************************
181 * HTTP_FreeTokens (internal)
183 * Frees memory returned from HTTP_Tokenize.
185 static void HTTP_FreeTokens(LPWSTR * token_array)
187 int i;
188 for (i = 0; token_array[i]; i++)
189 HeapFree(GetProcessHeap(), 0, token_array[i]);
190 HeapFree(GetProcessHeap(), 0, token_array);
193 /* **********************************************************************
195 * Helper functions for the HttpSendRequest(Ex) functions
198 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
200 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
201 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
203 TRACE("%p\n", lpwhr);
205 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
206 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
207 req->dwContentLength, req->bEndRequest);
209 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
212 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
214 static const WCHAR szSlash[] = { '/',0 };
215 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
217 /* If we don't have a path we set it to root */
218 if (NULL == lpwhr->lpszPath)
219 lpwhr->lpszPath = WININET_strdupW(szSlash);
220 else /* remove \r and \n*/
222 int nLen = strlenW(lpwhr->lpszPath);
223 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
225 nLen--;
226 lpwhr->lpszPath[nLen]='\0';
228 /* Replace '\' with '/' */
229 while (nLen>0) {
230 nLen--;
231 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
235 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
236 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
237 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
239 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
240 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
241 *fixurl = '/';
242 strcpyW(fixurl + 1, lpwhr->lpszPath);
243 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
244 lpwhr->lpszPath = fixurl;
248 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
250 LPWSTR requestString;
251 DWORD len, n;
252 LPCWSTR *req;
253 UINT i;
254 LPWSTR p;
256 static const WCHAR szSpace[] = { ' ',0 };
257 static const WCHAR szcrlf[] = {'\r','\n', 0};
258 static const WCHAR szColon[] = { ':',' ',0 };
259 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
261 /* allocate space for an array of all the string pointers to be added */
262 len = (lpwhr->nCustHeaders)*4 + 10;
263 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
265 /* add the verb, path and HTTP version string */
266 n = 0;
267 req[n++] = verb;
268 req[n++] = szSpace;
269 req[n++] = path;
270 req[n++] = szSpace;
271 req[n++] = version;
273 /* Append custom request headers */
274 for (i = 0; i < lpwhr->nCustHeaders; i++)
276 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
278 req[n++] = szcrlf;
279 req[n++] = lpwhr->pCustHeaders[i].lpszField;
280 req[n++] = szColon;
281 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
283 TRACE("Adding custom header %s (%s)\n",
284 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
285 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
289 if( n >= len )
290 ERR("oops. buffer overrun\n");
292 req[n] = NULL;
293 requestString = HTTP_build_req( req, 4 );
294 HeapFree( GetProcessHeap(), 0, req );
297 * Set (header) termination string for request
298 * Make sure there's exactly two new lines at the end of the request
300 p = &requestString[strlenW(requestString)-1];
301 while ( (*p == '\n') || (*p == '\r') )
302 p--;
303 strcpyW( p+1, sztwocrlf );
305 return requestString;
308 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
310 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
311 int HeaderIndex;
312 LPHTTPHEADERW setCookieHeader;
314 HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
315 if (HeaderIndex == -1)
316 return;
317 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
319 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
321 int nPosStart = 0, nPosEnd = 0, len;
322 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
324 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
326 LPWSTR buf_cookie, cookie_name, cookie_data;
327 LPWSTR buf_url;
328 LPWSTR domain = NULL;
329 LPHTTPHEADERW Host;
331 int nEqualPos = 0;
332 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
333 setCookieHeader->lpszValue[nPosEnd] != '\0')
335 nPosEnd++;
337 if (setCookieHeader->lpszValue[nPosEnd] == ';')
339 /* fixme: not case sensitive, strcasestr is gnu only */
340 int nDomainPosEnd = 0;
341 int nDomainPosStart = 0, nDomainLength = 0;
342 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
343 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
344 if (lpszDomain)
345 { /* they have specified their own domain, lets use it */
346 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
347 lpszDomain[nDomainPosEnd] != '\0')
349 nDomainPosEnd++;
351 nDomainPosStart = strlenW(szDomain);
352 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
353 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
354 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
357 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
358 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
359 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
360 TRACE("%s\n", debugstr_w(buf_cookie));
361 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
363 nEqualPos++;
365 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
367 HeapFree(GetProcessHeap(), 0, buf_cookie);
368 break;
371 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
372 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
373 cookie_data = &buf_cookie[nEqualPos + 1];
375 Host = HTTP_GetHeader(lpwhr,szHost);
376 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
377 strlenW(lpwhr->lpszPath) + 9;
378 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
379 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
380 InternetSetCookieW(buf_url, cookie_name, cookie_data);
382 HeapFree(GetProcessHeap(), 0, buf_url);
383 HeapFree(GetProcessHeap(), 0, buf_cookie);
384 HeapFree(GetProcessHeap(), 0, cookie_name);
385 HeapFree(GetProcessHeap(), 0, domain);
386 nPosStart = nPosEnd;
391 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
393 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
394 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
395 ((pszAuthValue[ARRAYSIZE(szBasic)] != ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
398 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
399 struct HttpAuthInfo **ppAuthInfo,
400 LPWSTR domain_and_username, LPWSTR password )
402 SECURITY_STATUS sec_status;
403 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
404 BOOL first = FALSE;
406 TRACE("%s\n", debugstr_w(pszAuthValue));
408 if (!domain_and_username) return FALSE;
410 if (!pAuthInfo)
412 TimeStamp exp;
414 first = TRUE;
415 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
416 if (!pAuthInfo)
417 return FALSE;
419 SecInvalidateHandle(&pAuthInfo->cred);
420 SecInvalidateHandle(&pAuthInfo->ctx);
421 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
422 pAuthInfo->attr = 0;
423 pAuthInfo->auth_data = NULL;
424 pAuthInfo->auth_data_len = 0;
425 pAuthInfo->finished = FALSE;
427 if (is_basic_auth_value(pszAuthValue))
429 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
430 pAuthInfo->scheme = WININET_strdupW(szBasic);
431 if (!pAuthInfo->scheme)
433 HeapFree(GetProcessHeap(), 0, pAuthInfo);
434 return FALSE;
437 else
439 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
440 WCHAR *user = strchrW(domain_and_username, '\\');
441 WCHAR *domain = domain_and_username;
443 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
444 if (!pAuthInfo->scheme)
446 HeapFree(GetProcessHeap(), 0, pAuthInfo);
447 return FALSE;
450 if (user) user++;
451 else
453 user = domain_and_username;
454 domain = NULL;
456 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
457 nt_auth_identity.User = user;
458 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
459 nt_auth_identity.Domain = domain;
460 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
461 nt_auth_identity.Password = password;
462 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
464 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
466 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
467 SECPKG_CRED_OUTBOUND, NULL,
468 &nt_auth_identity, NULL,
469 NULL, &pAuthInfo->cred,
470 &exp);
471 if (sec_status != SEC_E_OK)
473 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
474 debugstr_w(pAuthInfo->scheme), sec_status);
475 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
476 HeapFree(GetProcessHeap(), 0, pAuthInfo);
477 return FALSE;
480 *ppAuthInfo = pAuthInfo;
482 else if (pAuthInfo->finished)
483 return FALSE;
485 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
486 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
488 ERR("authentication scheme changed from %s to %s\n",
489 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
490 return FALSE;
493 if (is_basic_auth_value(pszAuthValue))
495 int userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
496 int passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
497 char *auth_data;
499 TRACE("basic authentication\n");
501 /* length includes a nul terminator, which will be re-used for the ':' */
502 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
503 if (!auth_data)
504 return FALSE;
506 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
507 auth_data[userlen] = ':';
508 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
510 pAuthInfo->auth_data = auth_data;
511 pAuthInfo->auth_data_len = userlen + 1 + passlen;
512 pAuthInfo->finished = TRUE;
514 return TRUE;
516 else
518 LPCWSTR pszAuthData;
519 SecBufferDesc out_desc, in_desc;
520 SecBuffer out, in;
521 unsigned char *buffer;
522 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
523 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
525 in.BufferType = SECBUFFER_TOKEN;
526 in.cbBuffer = 0;
527 in.pvBuffer = NULL;
529 in_desc.ulVersion = 0;
530 in_desc.cBuffers = 1;
531 in_desc.pBuffers = &in;
533 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
534 if (*pszAuthData == ' ')
536 pszAuthData++;
537 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
538 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
539 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
542 buffer = HeapAlloc(GetProcessHeap(), 0, 0x100);
544 out.BufferType = SECBUFFER_TOKEN;
545 out.cbBuffer = 0x100;
546 out.pvBuffer = buffer;
548 out_desc.ulVersion = 0;
549 out_desc.cBuffers = 1;
550 out_desc.pBuffers = &out;
552 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
553 first ? NULL : &pAuthInfo->ctx,
554 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
555 context_req, 0, SECURITY_NETWORK_DREP,
556 in.pvBuffer ? &in_desc : NULL,
557 0, &pAuthInfo->ctx, &out_desc,
558 &pAuthInfo->attr, &pAuthInfo->exp);
559 if (sec_status == SEC_E_OK)
561 pAuthInfo->finished = TRUE;
562 pAuthInfo->auth_data = out.pvBuffer;
563 pAuthInfo->auth_data_len = out.cbBuffer;
564 TRACE("sending last auth packet\n");
566 else if (sec_status == SEC_I_CONTINUE_NEEDED)
568 pAuthInfo->auth_data = out.pvBuffer;
569 pAuthInfo->auth_data_len = out.cbBuffer;
570 TRACE("sending next auth packet\n");
572 else
574 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
575 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
576 return FALSE;
580 return TRUE;
583 /***********************************************************************
584 * HTTP_HttpAddRequestHeadersW (internal)
586 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
587 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
589 LPWSTR lpszStart;
590 LPWSTR lpszEnd;
591 LPWSTR buffer;
592 BOOL bSuccess = FALSE;
593 DWORD len;
595 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
597 if( dwHeaderLength == ~0U )
598 len = strlenW(lpszHeader);
599 else
600 len = dwHeaderLength;
601 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
602 lstrcpynW( buffer, lpszHeader, len + 1);
604 lpszStart = buffer;
608 LPWSTR * pFieldAndValue;
610 lpszEnd = lpszStart;
612 while (*lpszEnd != '\0')
614 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
615 break;
616 lpszEnd++;
619 if (*lpszStart == '\0')
620 break;
622 if (*lpszEnd == '\r')
624 *lpszEnd = '\0';
625 lpszEnd += 2; /* Jump over \r\n */
627 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
628 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
629 if (pFieldAndValue)
631 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
632 if (bSuccess)
633 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
634 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
635 HTTP_FreeTokens(pFieldAndValue);
638 lpszStart = lpszEnd;
639 } while (bSuccess);
641 HeapFree(GetProcessHeap(), 0, buffer);
643 return bSuccess;
646 /***********************************************************************
647 * HttpAddRequestHeadersW (WININET.@)
649 * Adds one or more HTTP header to the request handler
651 * NOTE
652 * On Windows if dwHeaderLength includes the trailing '\0', then
653 * HttpAddRequestHeadersW() adds it too. However this results in an
654 * invalid Http header which is rejected by some servers so we probably
655 * don't need to match Windows on that point.
657 * RETURNS
658 * TRUE on success
659 * FALSE on failure
662 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
663 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
665 BOOL bSuccess = FALSE;
666 LPWININETHTTPREQW lpwhr;
668 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
670 if (!lpszHeader)
671 return TRUE;
673 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
674 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
676 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
677 goto lend;
679 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
680 lend:
681 if( lpwhr )
682 WININET_Release( &lpwhr->hdr );
684 return bSuccess;
687 /***********************************************************************
688 * HttpAddRequestHeadersA (WININET.@)
690 * Adds one or more HTTP header to the request handler
692 * RETURNS
693 * TRUE on success
694 * FALSE on failure
697 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
698 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
700 DWORD len;
701 LPWSTR hdr;
702 BOOL r;
704 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
706 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
707 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
708 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
709 if( dwHeaderLength != ~0U )
710 dwHeaderLength = len;
712 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
714 HeapFree( GetProcessHeap(), 0, hdr );
716 return r;
719 /* read any content returned by the server so that the connection can be
720 * reused */
721 static void HTTP_DrainContent(LPWININETHTTPREQW lpwhr)
723 DWORD bytes_read;
725 if (!NETCON_connected(&lpwhr->netConnection)) return;
727 if (lpwhr->dwContentLength == -1)
728 NETCON_close(&lpwhr->netConnection);
732 char buffer[2048];
733 if (!INTERNET_ReadFile(&lpwhr->hdr, buffer, sizeof(buffer), &bytes_read,
734 TRUE, FALSE))
735 return;
736 } while (bytes_read);
739 /***********************************************************************
740 * HttpEndRequestA (WININET.@)
742 * Ends an HTTP request that was started by HttpSendRequestEx
744 * RETURNS
745 * TRUE if successful
746 * FALSE on failure
749 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
750 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
752 LPINTERNET_BUFFERSA ptr;
753 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
754 BOOL rc = FALSE;
756 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
757 dwContext);
759 ptr = lpBuffersOut;
760 if (ptr)
761 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
762 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
763 else
764 lpBuffersOutW = NULL;
766 ptrW = lpBuffersOutW;
767 while (ptr)
769 if (ptr->lpvBuffer && ptr->dwBufferLength)
770 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
771 ptrW->dwBufferLength = ptr->dwBufferLength;
772 ptrW->dwBufferTotal= ptr->dwBufferTotal;
774 if (ptr->Next)
775 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
776 sizeof(INTERNET_BUFFERSW));
778 ptr = ptr->Next;
779 ptrW = ptrW->Next;
782 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
784 if (lpBuffersOutW)
786 ptrW = lpBuffersOutW;
787 while (ptrW)
789 LPINTERNET_BUFFERSW ptrW2;
791 FIXME("Do we need to translate info out of these buffer?\n");
793 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
794 ptrW2 = ptrW->Next;
795 HeapFree(GetProcessHeap(),0,ptrW);
796 ptrW = ptrW2;
800 return rc;
803 /***********************************************************************
804 * HttpEndRequestW (WININET.@)
806 * Ends an HTTP request that was started by HttpSendRequestEx
808 * RETURNS
809 * TRUE if successful
810 * FALSE on failure
813 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
814 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
816 BOOL rc = FALSE;
817 LPWININETHTTPREQW lpwhr;
818 INT responseLen;
819 DWORD dwBufferSize;
821 TRACE("-->\n");
822 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
824 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
826 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
827 if (lpwhr)
828 WININET_Release( &lpwhr->hdr );
829 return FALSE;
832 lpwhr->hdr.dwFlags |= dwFlags;
833 lpwhr->hdr.dwContext = dwContext;
835 /* We appear to do nothing with lpBuffersOut.. is that correct? */
837 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
838 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
840 responseLen = HTTP_GetResponseHeaders(lpwhr);
841 if (responseLen)
842 rc = TRUE;
844 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
845 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
847 /* process cookies here. Is this right? */
848 HTTP_ProcessCookies(lpwhr);
850 dwBufferSize = sizeof(lpwhr->dwContentLength);
851 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
852 &lpwhr->dwContentLength,&dwBufferSize,NULL))
853 lpwhr->dwContentLength = -1;
855 if (lpwhr->dwContentLength == 0)
856 HTTP_FinishedReading(lpwhr);
858 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
860 DWORD dwCode,dwCodeLength=sizeof(DWORD);
861 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
862 (dwCode==302 || dwCode==301))
864 WCHAR szNewLocation[2048];
865 dwBufferSize=sizeof(szNewLocation);
866 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
868 /* redirects are always GETs */
869 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
870 lpwhr->lpszVerb = WININET_strdupW(szGET);
871 HTTP_DrainContent(lpwhr);
872 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
873 if (rc)
874 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
879 WININET_Release( &lpwhr->hdr );
880 TRACE("%i <--\n",rc);
881 return rc;
884 /***********************************************************************
885 * HttpOpenRequestW (WININET.@)
887 * Open a HTTP request handle
889 * RETURNS
890 * HINTERNET a HTTP request handle on success
891 * NULL on failure
894 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
895 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
896 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
897 DWORD dwFlags, DWORD_PTR dwContext)
899 LPWININETHTTPSESSIONW lpwhs;
900 HINTERNET handle = NULL;
902 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
903 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
904 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
905 dwFlags, dwContext);
906 if(lpszAcceptTypes!=NULL)
908 int i;
909 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
910 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
913 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
914 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
916 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
917 goto lend;
921 * My tests seem to show that the windows version does not
922 * become asynchronous until after this point. And anyhow
923 * if this call was asynchronous then how would you get the
924 * necessary HINTERNET pointer returned by this function.
927 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
928 lpszVersion, lpszReferrer, lpszAcceptTypes,
929 dwFlags, dwContext);
930 lend:
931 if( lpwhs )
932 WININET_Release( &lpwhs->hdr );
933 TRACE("returning %p\n", handle);
934 return handle;
938 /***********************************************************************
939 * HttpOpenRequestA (WININET.@)
941 * Open a HTTP request handle
943 * RETURNS
944 * HINTERNET a HTTP request handle on success
945 * NULL on failure
948 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
949 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
950 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
951 DWORD dwFlags, DWORD_PTR dwContext)
953 LPWSTR szVerb = NULL, szObjectName = NULL;
954 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
955 INT len;
956 INT acceptTypesCount;
957 HINTERNET rc = FALSE;
958 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
959 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
960 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
961 dwFlags, dwContext);
963 if (lpszVerb)
965 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
966 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
967 if ( !szVerb )
968 goto end;
969 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
972 if (lpszObjectName)
974 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
975 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
976 if ( !szObjectName )
977 goto end;
978 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
981 if (lpszVersion)
983 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
984 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
985 if ( !szVersion )
986 goto end;
987 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
990 if (lpszReferrer)
992 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
993 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
994 if ( !szReferrer )
995 goto end;
996 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
999 acceptTypesCount = 0;
1000 if (lpszAcceptTypes)
1002 /* find out how many there are */
1003 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1004 acceptTypesCount++;
1005 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1006 acceptTypesCount = 0;
1007 while (lpszAcceptTypes[acceptTypesCount] && *lpszAcceptTypes[acceptTypesCount])
1009 len = MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1010 -1, NULL, 0 );
1011 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1012 if (!szAcceptTypes[acceptTypesCount] )
1013 goto end;
1014 MultiByteToWideChar(CP_ACP, 0, lpszAcceptTypes[acceptTypesCount],
1015 -1, szAcceptTypes[acceptTypesCount], len );
1016 acceptTypesCount++;
1018 szAcceptTypes[acceptTypesCount] = NULL;
1020 else szAcceptTypes = 0;
1022 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1023 szVersion, szReferrer,
1024 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1026 end:
1027 if (szAcceptTypes)
1029 acceptTypesCount = 0;
1030 while (szAcceptTypes[acceptTypesCount])
1032 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1033 acceptTypesCount++;
1035 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1037 HeapFree(GetProcessHeap(), 0, szReferrer);
1038 HeapFree(GetProcessHeap(), 0, szVersion);
1039 HeapFree(GetProcessHeap(), 0, szObjectName);
1040 HeapFree(GetProcessHeap(), 0, szVerb);
1042 return rc;
1045 /***********************************************************************
1046 * HTTP_EncodeBase64
1048 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1050 UINT n = 0, x;
1051 static const CHAR HTTP_Base64Enc[] =
1052 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1054 while( len > 0 )
1056 /* first 6 bits, all from bin[0] */
1057 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1058 x = (bin[0] & 3) << 4;
1060 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1061 if( len == 1 )
1063 base64[n++] = HTTP_Base64Enc[x];
1064 base64[n++] = '=';
1065 base64[n++] = '=';
1066 break;
1068 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1069 x = ( bin[1] & 0x0f ) << 2;
1071 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1072 if( len == 2 )
1074 base64[n++] = HTTP_Base64Enc[x];
1075 base64[n++] = '=';
1076 break;
1078 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1080 /* last 6 bits, all from bin [2] */
1081 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1082 bin += 3;
1083 len -= 3;
1085 base64[n] = 0;
1086 return n;
1089 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1090 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1091 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1092 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1093 static const signed char HTTP_Base64Dec[256] =
1095 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1096 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1097 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1098 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1099 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1100 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1101 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1102 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1103 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1104 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1105 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1106 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1107 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1108 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1109 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1110 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1111 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1112 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1113 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1114 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1115 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1116 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1117 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1118 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1119 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1120 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1122 #undef CH
1124 /***********************************************************************
1125 * HTTP_DecodeBase64
1127 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1129 unsigned int n = 0;
1131 while(*base64)
1133 signed char in[4];
1135 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1136 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1137 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1138 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1140 WARN("invalid base64: %s\n", debugstr_w(base64));
1141 return 0;
1143 if (bin)
1144 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1145 n++;
1147 if ((base64[2] == '=') && (base64[3] == '='))
1148 break;
1149 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1150 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1152 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1153 return 0;
1155 if (bin)
1156 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1157 n++;
1159 if (base64[3] == '=')
1160 break;
1161 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1162 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1164 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1165 return 0;
1167 if (bin)
1168 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1169 n++;
1171 base64 += 4;
1174 return n;
1177 /***********************************************************************
1178 * HTTP_InsertAuthorizationForHeader
1180 * Insert or delete the authorization field in the request header.
1182 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR header, BOOL first )
1184 WCHAR *authorization = NULL;
1185 struct HttpAuthInfo *pAuthInfo = lpwhr->pAuthInfo;
1186 DWORD flags;
1188 if (pAuthInfo && pAuthInfo->auth_data_len)
1190 static const WCHAR wszSpace[] = {' ',0};
1191 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1192 unsigned int len;
1194 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1195 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1196 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1197 if (!authorization)
1198 return FALSE;
1200 strcpyW(authorization, pAuthInfo->scheme);
1201 strcatW(authorization, wszSpace);
1202 HTTP_EncodeBase64(pAuthInfo->auth_data,
1203 pAuthInfo->auth_data_len,
1204 authorization+strlenW(authorization));
1206 /* clear the data as it isn't valid now that it has been sent to the
1207 * server, unless it's Basic authentication which doesn't do
1208 * connection tracking */
1209 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1211 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1212 pAuthInfo->auth_data = NULL;
1213 pAuthInfo->auth_data_len = 0;
1217 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1219 /* make sure not to overwrite any caller supplied authorization header */
1220 flags = HTTP_ADDHDR_FLAG_REQ;
1221 flags |= first ? HTTP_ADDHDR_FLAG_ADD_IF_NEW : HTTP_ADDHDR_FLAG_REPLACE;
1223 HTTP_ProcessHeader(lpwhr, header, authorization, flags);
1225 HeapFree(GetProcessHeap(), 0, authorization);
1226 return TRUE;
1229 /***********************************************************************
1230 * HTTP_DealWithProxy
1232 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1233 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1235 WCHAR buf[MAXHOSTNAME];
1236 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1237 WCHAR* url;
1238 static WCHAR szNul[] = { 0 };
1239 URL_COMPONENTSW UrlComponents;
1240 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 }, szSlash[] = { '/',0 } ;
1241 static const WCHAR szFormat1[] = { 'h','t','t','p',':','/','/','%','s',0 };
1242 static const WCHAR szFormat2[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1243 int len;
1245 memset( &UrlComponents, 0, sizeof UrlComponents );
1246 UrlComponents.dwStructSize = sizeof UrlComponents;
1247 UrlComponents.lpszHostName = buf;
1248 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1250 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1251 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1252 sprintfW(proxy, szFormat1, hIC->lpszProxy);
1253 else
1254 strcpyW(proxy, hIC->lpszProxy);
1255 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1256 return FALSE;
1257 if( UrlComponents.dwHostNameLength == 0 )
1258 return FALSE;
1260 if( !lpwhr->lpszPath )
1261 lpwhr->lpszPath = szNul;
1262 TRACE("server=%s path=%s\n",
1263 debugstr_w(lpwhs->lpszHostName), debugstr_w(lpwhr->lpszPath));
1264 /* for constant 15 see above */
1265 len = strlenW(lpwhs->lpszHostName) + strlenW(lpwhr->lpszPath) + 15;
1266 url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1268 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1269 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1271 sprintfW(url, szFormat2, lpwhs->lpszHostName, lpwhs->nHostPort);
1273 if( lpwhr->lpszPath[0] != '/' )
1274 strcatW( url, szSlash );
1275 strcatW(url, lpwhr->lpszPath);
1276 if(lpwhr->lpszPath != szNul)
1277 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1278 lpwhr->lpszPath = url;
1280 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1281 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1282 lpwhs->nServerPort = UrlComponents.nPort;
1284 return TRUE;
1287 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1289 char szaddr[32];
1290 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1292 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1293 INTERNET_STATUS_RESOLVING_NAME,
1294 lpwhs->lpszServerName,
1295 strlenW(lpwhs->lpszServerName)+1);
1297 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1298 &lpwhs->socketAddress))
1300 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1301 return FALSE;
1304 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1305 szaddr, sizeof(szaddr));
1306 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1307 INTERNET_STATUS_NAME_RESOLVED,
1308 szaddr, strlen(szaddr)+1);
1309 return TRUE;
1313 /***********************************************************************
1314 * HTTPREQ_Destroy (internal)
1316 * Deallocate request handle
1319 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1321 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1322 DWORD i;
1324 TRACE("\n");
1326 if(lpwhr->hCacheFile)
1327 CloseHandle(lpwhr->hCacheFile);
1329 if(lpwhr->lpszCacheFile) {
1330 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1331 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1334 WININET_Release(&lpwhr->lpHttpSession->hdr);
1336 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1337 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1338 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1339 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1340 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1342 for (i = 0; i < lpwhr->nCustHeaders; i++)
1344 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1345 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1348 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1349 HeapFree(GetProcessHeap(), 0, lpwhr);
1352 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1353 HTTPREQ_Destroy
1356 /***********************************************************************
1357 * HTTP_HttpOpenRequestW (internal)
1359 * Open a HTTP request handle
1361 * RETURNS
1362 * HINTERNET a HTTP request handle on success
1363 * NULL on failure
1366 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1367 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1368 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1369 DWORD dwFlags, DWORD_PTR dwContext)
1371 LPWININETAPPINFOW hIC = NULL;
1372 LPWININETHTTPREQW lpwhr;
1373 LPWSTR lpszCookies;
1374 LPWSTR lpszUrl = NULL;
1375 DWORD nCookieSize;
1376 HINTERNET handle = NULL;
1377 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1378 DWORD len;
1379 LPHTTPHEADERW Host;
1381 TRACE("-->\n");
1383 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1384 hIC = lpwhs->lpAppInfo;
1386 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1387 if (NULL == lpwhr)
1389 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1390 goto lend;
1392 lpwhr->hdr.htype = WH_HHTTPREQ;
1393 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1394 lpwhr->hdr.dwFlags = dwFlags;
1395 lpwhr->hdr.dwContext = dwContext;
1396 lpwhr->hdr.dwRefCount = 1;
1397 lpwhr->hdr.close_connection = HTTP_CloseConnection;
1398 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1399 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1401 WININET_AddRef( &lpwhs->hdr );
1402 lpwhr->lpHttpSession = lpwhs;
1403 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1405 handle = WININET_AllocHandle( &lpwhr->hdr );
1406 if (NULL == handle)
1408 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1409 goto lend;
1412 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1414 InternetCloseHandle( handle );
1415 handle = NULL;
1416 goto lend;
1419 if (lpszObjectName && *lpszObjectName) {
1420 HRESULT rc;
1422 len = 0;
1423 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1424 if (rc != E_POINTER)
1425 len = strlenW(lpszObjectName)+1;
1426 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1427 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1428 URL_ESCAPE_SPACES_ONLY);
1429 if (rc)
1431 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1432 strcpyW(lpwhr->lpszPath,lpszObjectName);
1436 if (lpszReferrer && *lpszReferrer)
1437 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1439 if (lpszAcceptTypes)
1441 int i;
1442 for (i = 0; lpszAcceptTypes[i]; i++)
1444 if (!*lpszAcceptTypes[i]) continue;
1445 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1446 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1447 HTTP_ADDHDR_FLAG_REQ |
1448 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1452 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1454 if (lpszVersion)
1455 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1456 else
1457 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1459 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1461 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1462 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1463 INTERNET_DEFAULT_HTTPS_PORT :
1464 INTERNET_DEFAULT_HTTP_PORT);
1465 lpwhs->nHostPort = lpwhs->nServerPort;
1467 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1468 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1470 if (hIC->lpszAgent)
1472 WCHAR *agent_header;
1473 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0 };
1475 len = strlenW(hIC->lpszAgent) + strlenW(user_agent);
1476 agent_header = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1477 sprintfW(agent_header, user_agent, hIC->lpszAgent );
1479 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header),
1480 HTTP_ADDREQ_FLAG_ADD);
1481 HeapFree(GetProcessHeap(), 0, agent_header);
1484 Host = HTTP_GetHeader(lpwhr,szHost);
1486 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1487 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1488 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1490 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1491 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1493 int cnt = 0;
1494 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
1495 static const WCHAR szcrlf[] = {'\r','\n',0};
1497 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
1499 cnt += sprintfW(lpszCookies, szCookie);
1500 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
1501 strcatW(lpszCookies, szcrlf);
1503 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
1504 HTTP_ADDREQ_FLAG_ADD);
1505 HeapFree(GetProcessHeap(), 0, lpszCookies);
1507 HeapFree(GetProcessHeap(), 0, lpszUrl);
1510 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
1511 INTERNET_STATUS_HANDLE_CREATED, &handle,
1512 sizeof(handle));
1515 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
1518 if (!HTTP_ResolveName(lpwhr))
1520 InternetCloseHandle( handle );
1521 handle = NULL;
1524 lend:
1525 if( lpwhr )
1526 WININET_Release( &lpwhr->hdr );
1528 TRACE("<-- %p (%p)\n", handle, lpwhr);
1529 return handle;
1532 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
1533 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
1534 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
1535 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
1536 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
1537 static const WCHAR szAge[] = { 'A','g','e',0 };
1538 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
1539 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
1540 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
1541 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
1542 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
1543 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
1544 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
1545 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
1546 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
1547 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
1548 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
1549 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 };
1550 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
1551 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
1552 static const WCHAR szDate[] = { 'D','a','t','e',0 };
1553 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
1554 static const WCHAR szETag[] = { 'E','T','a','g',0 };
1555 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
1556 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
1557 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
1558 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1559 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
1560 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
1561 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
1562 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
1563 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
1564 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
1565 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
1566 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
1567 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1568 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
1569 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
1570 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
1571 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
1572 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
1573 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
1574 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
1575 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
1576 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 };
1577 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
1578 static const WCHAR szURI[] = { 'U','R','I',0 };
1579 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
1580 static const WCHAR szVary[] = { 'V','a','r','y',0 };
1581 static const WCHAR szVia[] = { 'V','i','a',0 };
1582 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
1583 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
1585 static const LPCWSTR header_lookup[] = {
1586 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
1587 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
1588 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
1589 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
1590 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
1591 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
1592 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
1593 szAllow, /* HTTP_QUERY_ALLOW = 7 */
1594 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
1595 szDate, /* HTTP_QUERY_DATE = 9 */
1596 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
1597 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
1598 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
1599 szURI, /* HTTP_QUERY_URI = 13 */
1600 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
1601 NULL, /* HTTP_QUERY_COST = 15 */
1602 NULL, /* HTTP_QUERY_LINK = 16 */
1603 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
1604 NULL, /* HTTP_QUERY_VERSION = 18 */
1605 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
1606 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
1607 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
1608 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
1609 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
1610 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
1611 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
1612 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
1613 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
1614 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
1615 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
1616 NULL, /* HTTP_QUERY_FORWARDED = 30 */
1617 NULL, /* HTTP_QUERY_FROM = 31 */
1618 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
1619 szLocation, /* HTTP_QUERY_LOCATION = 33 */
1620 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
1621 szReferer, /* HTTP_QUERY_REFERER = 35 */
1622 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
1623 szServer, /* HTTP_QUERY_SERVER = 37 */
1624 NULL, /* HTTP_TITLE = 38 */
1625 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
1626 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
1627 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
1628 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
1629 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
1630 szCookie, /* HTTP_QUERY_COOKIE = 44 */
1631 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
1632 NULL, /* HTTP_QUERY_REFRESH = 46 */
1633 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
1634 szAge, /* HTTP_QUERY_AGE = 48 */
1635 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
1636 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
1637 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
1638 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
1639 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
1640 szETag, /* HTTP_QUERY_ETAG = 54 */
1641 szHost, /* HTTP_QUERY_HOST = 55 */
1642 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
1643 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
1644 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
1645 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
1646 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
1647 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
1648 szRange, /* HTTP_QUERY_RANGE = 62 */
1649 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
1650 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
1651 szVary, /* HTTP_QUERY_VARY = 65 */
1652 szVia, /* HTTP_QUERY_VIA = 66 */
1653 szWarning, /* HTTP_QUERY_WARNING = 67 */
1654 szExpect, /* HTTP_QUERY_EXPECT = 68 */
1655 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
1656 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
1659 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
1661 /***********************************************************************
1662 * HTTP_HttpQueryInfoW (internal)
1664 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
1665 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1667 LPHTTPHEADERW lphttpHdr = NULL;
1668 BOOL bSuccess = FALSE;
1669 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
1670 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
1671 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
1672 INT index = -1;
1674 /* Find requested header structure */
1675 switch (level)
1677 case HTTP_QUERY_CUSTOM:
1678 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
1679 break;
1681 case HTTP_QUERY_RAW_HEADERS_CRLF:
1683 LPWSTR headers;
1684 DWORD len;
1685 BOOL ret;
1687 if (request_only)
1688 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
1689 else
1690 headers = lpwhr->lpszRawHeaders;
1692 len = strlenW(headers);
1693 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1695 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1696 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1697 ret = FALSE;
1698 } else
1700 memcpy(lpBuffer, headers, (len+1)*sizeof(WCHAR));
1701 *lpdwBufferLength = len * sizeof(WCHAR);
1703 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1704 ret = TRUE;
1707 if (request_only)
1708 HeapFree(GetProcessHeap(), 0, headers);
1709 return ret;
1711 case HTTP_QUERY_RAW_HEADERS:
1713 static const WCHAR szCrLf[] = {'\r','\n',0};
1714 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
1715 DWORD i, size = 0;
1716 LPWSTR pszString = (WCHAR*)lpBuffer;
1718 for (i = 0; ppszRawHeaderLines[i]; i++)
1719 size += strlenW(ppszRawHeaderLines[i]) + 1;
1721 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
1723 HTTP_FreeTokens(ppszRawHeaderLines);
1724 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
1725 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1726 return FALSE;
1729 for (i = 0; ppszRawHeaderLines[i]; i++)
1731 DWORD len = strlenW(ppszRawHeaderLines[i]);
1732 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
1733 pszString += len+1;
1735 *pszString = '\0';
1737 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
1739 *lpdwBufferLength = size * sizeof(WCHAR);
1740 HTTP_FreeTokens(ppszRawHeaderLines);
1742 return TRUE;
1744 case HTTP_QUERY_STATUS_TEXT:
1745 if (lpwhr->lpszStatusText)
1747 DWORD len = strlenW(lpwhr->lpszStatusText);
1748 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1750 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1751 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1752 return FALSE;
1754 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
1755 *lpdwBufferLength = len * sizeof(WCHAR);
1757 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1759 return TRUE;
1761 break;
1762 case HTTP_QUERY_VERSION:
1763 if (lpwhr->lpszVersion)
1765 DWORD len = strlenW(lpwhr->lpszVersion);
1766 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
1768 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
1769 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1770 return FALSE;
1772 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
1773 *lpdwBufferLength = len * sizeof(WCHAR);
1775 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
1777 return TRUE;
1779 break;
1780 default:
1781 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
1783 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
1784 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
1785 requested_index,request_only);
1788 if (index >= 0)
1789 lphttpHdr = &lpwhr->pCustHeaders[index];
1791 /* Ensure header satisfies requested attributes */
1792 if (!lphttpHdr ||
1793 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
1794 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
1796 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
1797 return bSuccess;
1800 if (lpdwIndex)
1801 (*lpdwIndex)++;
1803 /* coalesce value to requested type */
1804 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
1806 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
1807 bSuccess = TRUE;
1809 TRACE(" returning number : %d\n", *(int *)lpBuffer);
1811 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
1813 time_t tmpTime;
1814 struct tm tmpTM;
1815 SYSTEMTIME *STHook;
1817 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
1819 tmpTM = *gmtime(&tmpTime);
1820 STHook = (SYSTEMTIME *) lpBuffer;
1821 if(STHook==NULL)
1822 return bSuccess;
1824 STHook->wDay = tmpTM.tm_mday;
1825 STHook->wHour = tmpTM.tm_hour;
1826 STHook->wMilliseconds = 0;
1827 STHook->wMinute = tmpTM.tm_min;
1828 STHook->wDayOfWeek = tmpTM.tm_wday;
1829 STHook->wMonth = tmpTM.tm_mon + 1;
1830 STHook->wSecond = tmpTM.tm_sec;
1831 STHook->wYear = tmpTM.tm_year;
1833 bSuccess = TRUE;
1835 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
1836 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
1837 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
1839 else if (lphttpHdr->lpszValue)
1841 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
1843 if (len > *lpdwBufferLength)
1845 *lpdwBufferLength = len;
1846 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1847 return bSuccess;
1850 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
1851 *lpdwBufferLength = len - sizeof(WCHAR);
1852 bSuccess = TRUE;
1854 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
1856 return bSuccess;
1859 /***********************************************************************
1860 * HttpQueryInfoW (WININET.@)
1862 * Queries for information about an HTTP request
1864 * RETURNS
1865 * TRUE on success
1866 * FALSE on failure
1869 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
1870 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
1872 BOOL bSuccess = FALSE;
1873 LPWININETHTTPREQW lpwhr;
1875 if (TRACE_ON(wininet)) {
1876 #define FE(x) { x, #x }
1877 static const wininet_flag_info query_flags[] = {
1878 FE(HTTP_QUERY_MIME_VERSION),
1879 FE(HTTP_QUERY_CONTENT_TYPE),
1880 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
1881 FE(HTTP_QUERY_CONTENT_ID),
1882 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
1883 FE(HTTP_QUERY_CONTENT_LENGTH),
1884 FE(HTTP_QUERY_CONTENT_LANGUAGE),
1885 FE(HTTP_QUERY_ALLOW),
1886 FE(HTTP_QUERY_PUBLIC),
1887 FE(HTTP_QUERY_DATE),
1888 FE(HTTP_QUERY_EXPIRES),
1889 FE(HTTP_QUERY_LAST_MODIFIED),
1890 FE(HTTP_QUERY_MESSAGE_ID),
1891 FE(HTTP_QUERY_URI),
1892 FE(HTTP_QUERY_DERIVED_FROM),
1893 FE(HTTP_QUERY_COST),
1894 FE(HTTP_QUERY_LINK),
1895 FE(HTTP_QUERY_PRAGMA),
1896 FE(HTTP_QUERY_VERSION),
1897 FE(HTTP_QUERY_STATUS_CODE),
1898 FE(HTTP_QUERY_STATUS_TEXT),
1899 FE(HTTP_QUERY_RAW_HEADERS),
1900 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
1901 FE(HTTP_QUERY_CONNECTION),
1902 FE(HTTP_QUERY_ACCEPT),
1903 FE(HTTP_QUERY_ACCEPT_CHARSET),
1904 FE(HTTP_QUERY_ACCEPT_ENCODING),
1905 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
1906 FE(HTTP_QUERY_AUTHORIZATION),
1907 FE(HTTP_QUERY_CONTENT_ENCODING),
1908 FE(HTTP_QUERY_FORWARDED),
1909 FE(HTTP_QUERY_FROM),
1910 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
1911 FE(HTTP_QUERY_LOCATION),
1912 FE(HTTP_QUERY_ORIG_URI),
1913 FE(HTTP_QUERY_REFERER),
1914 FE(HTTP_QUERY_RETRY_AFTER),
1915 FE(HTTP_QUERY_SERVER),
1916 FE(HTTP_QUERY_TITLE),
1917 FE(HTTP_QUERY_USER_AGENT),
1918 FE(HTTP_QUERY_WWW_AUTHENTICATE),
1919 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
1920 FE(HTTP_QUERY_ACCEPT_RANGES),
1921 FE(HTTP_QUERY_SET_COOKIE),
1922 FE(HTTP_QUERY_COOKIE),
1923 FE(HTTP_QUERY_REQUEST_METHOD),
1924 FE(HTTP_QUERY_REFRESH),
1925 FE(HTTP_QUERY_CONTENT_DISPOSITION),
1926 FE(HTTP_QUERY_AGE),
1927 FE(HTTP_QUERY_CACHE_CONTROL),
1928 FE(HTTP_QUERY_CONTENT_BASE),
1929 FE(HTTP_QUERY_CONTENT_LOCATION),
1930 FE(HTTP_QUERY_CONTENT_MD5),
1931 FE(HTTP_QUERY_CONTENT_RANGE),
1932 FE(HTTP_QUERY_ETAG),
1933 FE(HTTP_QUERY_HOST),
1934 FE(HTTP_QUERY_IF_MATCH),
1935 FE(HTTP_QUERY_IF_NONE_MATCH),
1936 FE(HTTP_QUERY_IF_RANGE),
1937 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
1938 FE(HTTP_QUERY_MAX_FORWARDS),
1939 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
1940 FE(HTTP_QUERY_RANGE),
1941 FE(HTTP_QUERY_TRANSFER_ENCODING),
1942 FE(HTTP_QUERY_UPGRADE),
1943 FE(HTTP_QUERY_VARY),
1944 FE(HTTP_QUERY_VIA),
1945 FE(HTTP_QUERY_WARNING),
1946 FE(HTTP_QUERY_CUSTOM)
1948 static const wininet_flag_info modifier_flags[] = {
1949 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
1950 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
1951 FE(HTTP_QUERY_FLAG_NUMBER),
1952 FE(HTTP_QUERY_FLAG_COALESCE)
1954 #undef FE
1955 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
1956 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
1957 DWORD i;
1959 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
1960 TRACE(" Attribute:");
1961 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
1962 if (query_flags[i].val == info) {
1963 TRACE(" %s", query_flags[i].name);
1964 break;
1967 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
1968 TRACE(" Unknown (%08x)", info);
1971 TRACE(" Modifier:");
1972 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
1973 if (modifier_flags[i].val & info_mod) {
1974 TRACE(" %s", modifier_flags[i].name);
1975 info_mod &= ~ modifier_flags[i].val;
1979 if (info_mod) {
1980 TRACE(" Unknown (%08x)", info_mod);
1982 TRACE("\n");
1985 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
1986 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
1988 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1989 goto lend;
1992 if (lpBuffer == NULL)
1993 *lpdwBufferLength = 0;
1994 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
1995 lpBuffer, lpdwBufferLength, lpdwIndex);
1997 lend:
1998 if( lpwhr )
1999 WININET_Release( &lpwhr->hdr );
2001 TRACE("%d <--\n", bSuccess);
2002 return bSuccess;
2005 /***********************************************************************
2006 * HttpQueryInfoA (WININET.@)
2008 * Queries for information about an HTTP request
2010 * RETURNS
2011 * TRUE on success
2012 * FALSE on failure
2015 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2016 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2018 BOOL result;
2019 DWORD len;
2020 WCHAR* bufferW;
2022 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2023 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2025 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2026 lpdwBufferLength, lpdwIndex );
2029 if (lpBuffer)
2031 DWORD alloclen;
2032 len = (*lpdwBufferLength)*sizeof(WCHAR);
2033 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2035 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2036 if (alloclen < len)
2037 alloclen = len;
2039 else
2040 alloclen = len;
2041 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2042 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2043 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2044 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2045 } else
2047 bufferW = NULL;
2048 len = 0;
2051 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2052 &len, lpdwIndex );
2053 if( result )
2055 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2056 lpBuffer, *lpdwBufferLength, NULL, NULL );
2057 *lpdwBufferLength = len - 1;
2059 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2061 else
2062 /* since the strings being returned from HttpQueryInfoW should be
2063 * only ASCII characters, it is reasonable to assume that all of
2064 * the Unicode characters can be reduced to a single byte */
2065 *lpdwBufferLength = len / sizeof(WCHAR);
2067 HeapFree(GetProcessHeap(), 0, bufferW );
2069 return result;
2072 /***********************************************************************
2073 * HttpSendRequestExA (WININET.@)
2075 * Sends the specified request to the HTTP server and allows chunked
2076 * transfers.
2078 * RETURNS
2079 * Success: TRUE
2080 * Failure: FALSE, call GetLastError() for more information.
2082 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2083 LPINTERNET_BUFFERSA lpBuffersIn,
2084 LPINTERNET_BUFFERSA lpBuffersOut,
2085 DWORD dwFlags, DWORD_PTR dwContext)
2087 INTERNET_BUFFERSW BuffersInW;
2088 BOOL rc = FALSE;
2089 DWORD headerlen;
2090 LPWSTR header = NULL;
2092 TRACE("(%p, %p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersIn,
2093 lpBuffersOut, dwFlags, dwContext);
2095 if (lpBuffersIn)
2097 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2098 if (lpBuffersIn->lpcszHeader)
2100 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2101 lpBuffersIn->dwHeadersLength,0,0);
2102 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2103 if (!(BuffersInW.lpcszHeader = header))
2105 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2106 return FALSE;
2108 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2109 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2110 header, headerlen);
2112 else
2113 BuffersInW.lpcszHeader = NULL;
2114 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2115 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2116 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2117 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2118 BuffersInW.Next = NULL;
2121 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2123 HeapFree(GetProcessHeap(),0,header);
2125 return rc;
2128 /***********************************************************************
2129 * HttpSendRequestExW (WININET.@)
2131 * Sends the specified request to the HTTP server and allows chunked
2132 * transfers
2134 * RETURNS
2135 * Success: TRUE
2136 * Failure: FALSE, call GetLastError() for more information.
2138 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2139 LPINTERNET_BUFFERSW lpBuffersIn,
2140 LPINTERNET_BUFFERSW lpBuffersOut,
2141 DWORD dwFlags, DWORD_PTR dwContext)
2143 BOOL ret = FALSE;
2144 LPWININETHTTPREQW lpwhr;
2145 LPWININETHTTPSESSIONW lpwhs;
2146 LPWININETAPPINFOW hIC;
2148 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2149 lpBuffersOut, dwFlags, dwContext);
2151 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2153 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2155 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2156 goto lend;
2159 lpwhs = lpwhr->lpHttpSession;
2160 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2161 hIC = lpwhs->lpAppInfo;
2162 assert(hIC->hdr.htype == WH_HINIT);
2164 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2166 WORKREQUEST workRequest;
2167 struct WORKREQ_HTTPSENDREQUESTW *req;
2169 workRequest.asyncproc = AsyncHttpSendRequestProc;
2170 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2171 req = &workRequest.u.HttpSendRequestW;
2172 if (lpBuffersIn)
2174 if (lpBuffersIn->lpcszHeader)
2175 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2176 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2177 else
2178 req->lpszHeader = NULL;
2179 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2180 req->lpOptional = lpBuffersIn->lpvBuffer;
2181 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2182 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2184 else
2186 req->lpszHeader = NULL;
2187 req->dwHeaderLength = 0;
2188 req->lpOptional = NULL;
2189 req->dwOptionalLength = 0;
2190 req->dwContentLength = 0;
2193 req->bEndRequest = FALSE;
2195 INTERNET_AsyncCall(&workRequest);
2197 * This is from windows.
2199 INTERNET_SetLastError(ERROR_IO_PENDING);
2201 else
2203 if (lpBuffersIn)
2204 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2205 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2206 lpBuffersIn->dwBufferTotal, FALSE);
2207 else
2208 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2211 lend:
2212 if ( lpwhr )
2213 WININET_Release( &lpwhr->hdr );
2215 TRACE("<---\n");
2216 return ret;
2219 /***********************************************************************
2220 * HttpSendRequestW (WININET.@)
2222 * Sends the specified request to the HTTP server
2224 * RETURNS
2225 * TRUE on success
2226 * FALSE on failure
2229 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2230 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2232 LPWININETHTTPREQW lpwhr;
2233 LPWININETHTTPSESSIONW lpwhs = NULL;
2234 LPWININETAPPINFOW hIC = NULL;
2235 BOOL r;
2237 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2238 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2240 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2241 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2243 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2244 r = FALSE;
2245 goto lend;
2248 lpwhs = lpwhr->lpHttpSession;
2249 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2251 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2252 r = FALSE;
2253 goto lend;
2256 hIC = lpwhs->lpAppInfo;
2257 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2259 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2260 r = FALSE;
2261 goto lend;
2264 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2266 WORKREQUEST workRequest;
2267 struct WORKREQ_HTTPSENDREQUESTW *req;
2269 workRequest.asyncproc = AsyncHttpSendRequestProc;
2270 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2271 req = &workRequest.u.HttpSendRequestW;
2272 if (lpszHeaders)
2274 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2275 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2277 else
2278 req->lpszHeader = 0;
2279 req->dwHeaderLength = dwHeaderLength;
2280 req->lpOptional = lpOptional;
2281 req->dwOptionalLength = dwOptionalLength;
2282 req->dwContentLength = dwOptionalLength;
2283 req->bEndRequest = TRUE;
2285 INTERNET_AsyncCall(&workRequest);
2287 * This is from windows.
2289 INTERNET_SetLastError(ERROR_IO_PENDING);
2290 r = FALSE;
2292 else
2294 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2295 dwHeaderLength, lpOptional, dwOptionalLength,
2296 dwOptionalLength, TRUE);
2298 lend:
2299 if( lpwhr )
2300 WININET_Release( &lpwhr->hdr );
2301 return r;
2304 /***********************************************************************
2305 * HttpSendRequestA (WININET.@)
2307 * Sends the specified request to the HTTP server
2309 * RETURNS
2310 * TRUE on success
2311 * FALSE on failure
2314 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2315 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2317 BOOL result;
2318 LPWSTR szHeaders=NULL;
2319 DWORD nLen=dwHeaderLength;
2320 if(lpszHeaders!=NULL)
2322 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2323 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2324 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2326 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2327 HeapFree(GetProcessHeap(),0,szHeaders);
2328 return result;
2331 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2333 LPHTTPHEADERW host_header;
2335 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2337 host_header = HTTP_GetHeader(req, szHost);
2338 if(!host_header)
2339 return FALSE;
2341 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2342 return TRUE;
2345 /***********************************************************************
2346 * HTTP_HandleRedirect (internal)
2348 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2350 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2351 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2352 WCHAR path[2048];
2354 if(lpszUrl[0]=='/')
2356 /* if it's an absolute path, keep the same session info */
2357 lstrcpynW(path, lpszUrl, 2048);
2359 else if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2361 TRACE("Redirect through proxy\n");
2362 lstrcpynW(path, lpszUrl, 2048);
2364 else
2366 URL_COMPONENTSW urlComponents;
2367 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2368 static WCHAR szHttp[] = {'h','t','t','p',0};
2369 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2370 DWORD url_length = 0;
2371 LPWSTR orig_url;
2372 LPWSTR combined_url;
2374 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2375 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2376 urlComponents.dwSchemeLength = 0;
2377 urlComponents.lpszHostName = lpwhs->lpszHostName;
2378 urlComponents.dwHostNameLength = 0;
2379 urlComponents.nPort = lpwhs->nHostPort;
2380 urlComponents.lpszUserName = lpwhs->lpszUserName;
2381 urlComponents.dwUserNameLength = 0;
2382 urlComponents.lpszPassword = NULL;
2383 urlComponents.dwPasswordLength = 0;
2384 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2385 urlComponents.dwUrlPathLength = 0;
2386 urlComponents.lpszExtraInfo = NULL;
2387 urlComponents.dwExtraInfoLength = 0;
2389 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2390 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2391 return FALSE;
2393 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2395 /* convert from bytes to characters */
2396 url_length = url_length / sizeof(WCHAR) - 1;
2397 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2399 HeapFree(GetProcessHeap(), 0, orig_url);
2400 return FALSE;
2403 url_length = 0;
2404 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2405 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2407 HeapFree(GetProcessHeap(), 0, orig_url);
2408 return FALSE;
2410 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2412 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2414 HeapFree(GetProcessHeap(), 0, orig_url);
2415 HeapFree(GetProcessHeap(), 0, combined_url);
2416 return FALSE;
2418 HeapFree(GetProcessHeap(), 0, orig_url);
2420 userName[0] = 0;
2421 hostName[0] = 0;
2422 protocol[0] = 0;
2424 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2425 urlComponents.lpszScheme = protocol;
2426 urlComponents.dwSchemeLength = 32;
2427 urlComponents.lpszHostName = hostName;
2428 urlComponents.dwHostNameLength = MAXHOSTNAME;
2429 urlComponents.lpszUserName = userName;
2430 urlComponents.dwUserNameLength = 1024;
2431 urlComponents.lpszPassword = NULL;
2432 urlComponents.dwPasswordLength = 0;
2433 urlComponents.lpszUrlPath = path;
2434 urlComponents.dwUrlPathLength = 2048;
2435 urlComponents.lpszExtraInfo = NULL;
2436 urlComponents.dwExtraInfoLength = 0;
2437 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2439 HeapFree(GetProcessHeap(), 0, combined_url);
2440 return FALSE;
2443 HeapFree(GetProcessHeap(), 0, combined_url);
2445 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2446 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2448 TRACE("redirect from secure page to non-secure page\n");
2449 /* FIXME: warn about from secure redirect to non-secure page */
2450 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2452 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2453 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2455 TRACE("redirect from non-secure page to secure page\n");
2456 /* FIXME: notify about redirect to secure page */
2457 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2460 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2462 if (lstrlenW(protocol)>4) /*https*/
2463 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2464 else /*http*/
2465 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2468 #if 0
2470 * This upsets redirects to binary files on sourceforge.net
2471 * and gives an html page instead of the target file
2472 * Examination of the HTTP request sent by native wininet.dll
2473 * reveals that it doesn't send a referrer in that case.
2474 * Maybe there's a flag that enables this, or maybe a referrer
2475 * shouldn't be added in case of a redirect.
2478 /* consider the current host as the referrer */
2479 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2480 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2481 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2482 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2483 #endif
2485 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2486 lpwhs->lpszServerName = WININET_strdupW(hostName);
2487 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2488 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2489 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2491 int len;
2492 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2493 len = lstrlenW(hostName);
2494 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2495 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2496 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
2498 else
2499 lpwhs->lpszHostName = WININET_strdupW(hostName);
2501 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
2504 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2505 lpwhs->lpszUserName = NULL;
2506 if (userName[0])
2507 lpwhs->lpszUserName = WININET_strdupW(userName);
2508 lpwhs->nServerPort = urlComponents.nPort;
2510 if (!HTTP_ResolveName(lpwhr))
2511 return FALSE;
2513 NETCON_close(&lpwhr->netConnection);
2515 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2516 return FALSE;
2519 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
2520 lpwhr->lpszPath=NULL;
2521 if (*path)
2523 DWORD needed = 0;
2524 HRESULT rc;
2526 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
2527 if (rc != E_POINTER)
2528 needed = strlenW(path)+1;
2529 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
2530 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
2531 URL_ESCAPE_SPACES_ONLY);
2532 if (rc)
2534 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
2535 strcpyW(lpwhr->lpszPath,path);
2539 return TRUE;
2542 /***********************************************************************
2543 * HTTP_build_req (internal)
2545 * concatenate all the strings in the request together
2547 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
2549 LPCWSTR *t;
2550 LPWSTR str;
2552 for( t = list; *t ; t++ )
2553 len += strlenW( *t );
2554 len++;
2556 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
2557 *str = 0;
2559 for( t = list; *t ; t++ )
2560 strcatW( str, *t );
2562 return str;
2565 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
2567 LPWSTR lpszPath;
2568 LPWSTR requestString;
2569 INT len;
2570 INT cnt;
2571 INT responseLen;
2572 char *ascii_req;
2573 BOOL ret;
2574 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
2575 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
2576 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2578 TRACE("\n");
2580 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
2581 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
2582 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
2583 HeapFree( GetProcessHeap(), 0, lpszPath );
2585 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2586 NULL, 0, NULL, NULL );
2587 len--; /* the nul terminator isn't needed */
2588 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
2589 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2590 ascii_req, len, NULL, NULL );
2591 HeapFree( GetProcessHeap(), 0, requestString );
2593 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
2595 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
2596 HeapFree( GetProcessHeap(), 0, ascii_req );
2597 if (!ret || cnt < 0)
2598 return FALSE;
2600 responseLen = HTTP_GetResponseHeaders( lpwhr );
2601 if (!responseLen)
2602 return FALSE;
2604 return TRUE;
2607 /***********************************************************************
2608 * HTTP_HttpSendRequestW (internal)
2610 * Sends the specified request to the HTTP server
2612 * RETURNS
2613 * TRUE on success
2614 * FALSE on failure
2617 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
2618 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
2619 DWORD dwContentLength, BOOL bEndRequest)
2621 INT cnt;
2622 BOOL bSuccess = FALSE;
2623 LPWSTR requestString = NULL;
2624 INT responseLen;
2625 BOOL loop_next;
2626 INTERNET_ASYNC_RESULT iar;
2627 static const WCHAR szClose[] = { 'C','l','o','s','e',0 };
2628 static const WCHAR szPost[] = { 'P','O','S','T',0 };
2629 static const WCHAR szContentLength[] =
2630 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
2631 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
2633 TRACE("--> %p\n", lpwhr);
2635 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
2637 /* Clear any error information */
2638 INTERNET_SetLastError(0);
2640 /* if the verb is NULL default to GET */
2641 if (!lpwhr->lpszVerb)
2642 lpwhr->lpszVerb = WININET_strdupW(szGET);
2644 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
2646 sprintfW(contentLengthStr, szContentLength, dwContentLength);
2647 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2652 DWORD len;
2653 char *ascii_req;
2655 loop_next = FALSE;
2657 /* like native, just in case the caller forgot to call InternetReadFile
2658 * for all the data */
2659 HTTP_DrainContent(lpwhr);
2660 lpwhr->dwContentRead = 0;
2662 if (TRACE_ON(wininet))
2664 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
2665 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
2668 HTTP_FixURL(lpwhr);
2669 HTTP_ProcessHeader(lpwhr, szConnection,
2670 lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION ? szKeepAlive : szClose,
2671 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
2673 HTTP_InsertAuthorization(lpwhr, szAuthorization, !loop_next);
2674 HTTP_InsertAuthorization(lpwhr, szProxy_Authorization, !loop_next);
2676 /* add the headers the caller supplied */
2677 if( lpszHeaders && dwHeaderLength )
2679 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
2680 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
2683 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2685 TRACE("Request header -> %s\n", debugstr_w(requestString) );
2687 /* Send the request and store the results */
2688 if (!HTTP_OpenConnection(lpwhr))
2689 goto lend;
2691 /* send the request as ASCII, tack on the optional data */
2692 if( !lpOptional )
2693 dwOptionalLength = 0;
2694 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2695 NULL, 0, NULL, NULL );
2696 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
2697 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
2698 ascii_req, len, NULL, NULL );
2699 if( lpOptional )
2700 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
2701 len = (len + dwOptionalLength - 1);
2702 ascii_req[len] = 0;
2703 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
2705 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2706 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2708 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
2709 HeapFree( GetProcessHeap(), 0, ascii_req );
2711 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2712 INTERNET_STATUS_REQUEST_SENT,
2713 &len, sizeof(DWORD));
2715 if (bEndRequest)
2717 DWORD dwBufferSize;
2718 DWORD dwStatusCode;
2720 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2721 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2723 if (cnt < 0)
2724 goto lend;
2726 responseLen = HTTP_GetResponseHeaders(lpwhr);
2727 if (responseLen)
2728 bSuccess = TRUE;
2730 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2731 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
2732 sizeof(DWORD));
2734 HTTP_ProcessCookies(lpwhr);
2736 dwBufferSize = sizeof(lpwhr->dwContentLength);
2737 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2738 &lpwhr->dwContentLength,&dwBufferSize,NULL))
2739 lpwhr->dwContentLength = -1;
2741 if (lpwhr->dwContentLength == 0)
2742 HTTP_FinishedReading(lpwhr);
2744 dwBufferSize = sizeof(dwStatusCode);
2745 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
2746 &dwStatusCode,&dwBufferSize,NULL))
2747 dwStatusCode = 0;
2749 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
2751 WCHAR szNewLocation[2048];
2752 dwBufferSize=sizeof(szNewLocation);
2753 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
2754 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
2756 HTTP_DrainContent(lpwhr);
2757 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2758 INTERNET_STATUS_REDIRECT, szNewLocation,
2759 dwBufferSize);
2760 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
2761 if (bSuccess)
2763 HeapFree(GetProcessHeap(), 0, requestString);
2764 loop_next = TRUE;
2768 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
2770 WCHAR szAuthValue[2048];
2771 dwBufferSize=2048;
2772 if (dwStatusCode == HTTP_STATUS_DENIED)
2774 DWORD dwIndex = 0;
2775 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2777 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2778 &lpwhr->pAuthInfo,
2779 lpwhr->lpHttpSession->lpszUserName,
2780 lpwhr->lpHttpSession->lpszPassword))
2782 loop_next = TRUE;
2783 break;
2787 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
2789 DWORD dwIndex = 0;
2790 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
2792 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
2793 &lpwhr->pProxyAuthInfo,
2794 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
2795 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
2797 loop_next = TRUE;
2798 break;
2804 else
2805 bSuccess = TRUE;
2807 while (loop_next);
2809 /* FIXME: Better check, when we have to create the cache file */
2810 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
2811 WCHAR url[INTERNET_MAX_URL_LENGTH];
2812 WCHAR cacheFileName[MAX_PATH+1];
2813 BOOL b;
2815 b = HTTP_GetRequestURL(lpwhr, url);
2816 if(!b) {
2817 WARN("Could not get URL\n");
2818 goto lend;
2821 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
2822 if(b) {
2823 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
2824 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2825 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2826 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
2827 WARN("Could not create file: %u\n", GetLastError());
2828 lpwhr->hCacheFile = NULL;
2830 }else {
2831 WARN("Could not create cache entry: %08x\n", GetLastError());
2835 lend:
2837 HeapFree(GetProcessHeap(), 0, requestString);
2839 /* TODO: send notification for P3P header */
2841 iar.dwResult = (DWORD)bSuccess;
2842 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2844 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
2845 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2846 sizeof(INTERNET_ASYNC_RESULT));
2848 TRACE("<--\n");
2849 return bSuccess;
2852 /***********************************************************************
2853 * HTTPSESSION_Destroy (internal)
2855 * Deallocate session handle
2858 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
2860 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
2862 TRACE("%p\n", lpwhs);
2864 WININET_Release(&lpwhs->lpAppInfo->hdr);
2866 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2867 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
2868 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
2869 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
2870 HeapFree(GetProcessHeap(), 0, lpwhs);
2874 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
2875 HTTPSESSION_Destroy
2879 /***********************************************************************
2880 * HTTP_Connect (internal)
2882 * Create http session handle
2884 * RETURNS
2885 * HINTERNET a session handle on success
2886 * NULL on failure
2889 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
2890 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2891 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
2892 DWORD dwInternalFlags)
2894 BOOL bSuccess = FALSE;
2895 LPWININETHTTPSESSIONW lpwhs = NULL;
2896 HINTERNET handle = NULL;
2898 TRACE("-->\n");
2900 if (!lpszServerName || !lpszServerName[0])
2902 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2903 goto lerror;
2906 assert( hIC->hdr.htype == WH_HINIT );
2908 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
2909 if (NULL == lpwhs)
2911 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2912 goto lerror;
2916 * According to my tests. The name is not resolved until a request is sent
2919 lpwhs->hdr.htype = WH_HHTTPSESSION;
2920 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
2921 lpwhs->hdr.dwFlags = dwFlags;
2922 lpwhs->hdr.dwContext = dwContext;
2923 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
2924 lpwhs->hdr.dwRefCount = 1;
2925 lpwhs->hdr.close_connection = NULL;
2926 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
2928 WININET_AddRef( &hIC->hdr );
2929 lpwhs->lpAppInfo = hIC;
2930 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
2932 handle = WININET_AllocHandle( &lpwhs->hdr );
2933 if (NULL == handle)
2935 ERR("Failed to alloc handle\n");
2936 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2937 goto lerror;
2940 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
2941 if(strchrW(hIC->lpszProxy, ' '))
2942 FIXME("Several proxies not implemented.\n");
2943 if(hIC->lpszProxyBypass)
2944 FIXME("Proxy bypass is ignored.\n");
2946 if (lpszServerName && lpszServerName[0])
2948 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
2949 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
2951 if (lpszUserName && lpszUserName[0])
2952 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
2953 if (lpszPassword && lpszPassword[0])
2954 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
2955 lpwhs->nServerPort = nServerPort;
2956 lpwhs->nHostPort = nServerPort;
2958 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
2959 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
2961 INTERNET_SendCallback(&hIC->hdr, dwContext,
2962 INTERNET_STATUS_HANDLE_CREATED, &handle,
2963 sizeof(handle));
2966 bSuccess = TRUE;
2968 lerror:
2969 if( lpwhs )
2970 WININET_Release( &lpwhs->hdr );
2973 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
2974 * windows
2977 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
2978 return handle;
2982 /***********************************************************************
2983 * HTTP_OpenConnection (internal)
2985 * Connect to a web server
2987 * RETURNS
2989 * TRUE on success
2990 * FALSE on failure
2992 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
2994 BOOL bSuccess = FALSE;
2995 LPWININETHTTPSESSIONW lpwhs;
2996 LPWININETAPPINFOW hIC = NULL;
2997 char szaddr[32];
2999 TRACE("-->\n");
3002 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3004 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3005 goto lend;
3008 if (NETCON_connected(&lpwhr->netConnection))
3010 bSuccess = TRUE;
3011 goto lend;
3014 lpwhs = lpwhr->lpHttpSession;
3016 hIC = lpwhs->lpAppInfo;
3017 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3018 szaddr, sizeof(szaddr));
3019 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3020 INTERNET_STATUS_CONNECTING_TO_SERVER,
3021 szaddr,
3022 strlen(szaddr)+1);
3024 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3025 SOCK_STREAM, 0))
3027 WARN("Socket creation failed\n");
3028 goto lend;
3031 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3032 sizeof(lpwhs->socketAddress)))
3033 goto lend;
3035 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3037 /* Note: we differ from Microsoft's WinINet here. they seem to have
3038 * a bug that causes no status callbacks to be sent when starting
3039 * a tunnel to a proxy server using the CONNECT verb. i believe our
3040 * behaviour to be more correct and to not cause any incompatibilities
3041 * because using a secure connection through a proxy server is a rare
3042 * case that would be hard for anyone to depend on */
3043 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3044 goto lend;
3046 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3048 WARN("Couldn't connect securely to host\n");
3049 goto lend;
3053 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3054 INTERNET_STATUS_CONNECTED_TO_SERVER,
3055 szaddr, strlen(szaddr)+1);
3057 bSuccess = TRUE;
3059 lend:
3060 TRACE("%d <--\n", bSuccess);
3061 return bSuccess;
3065 /***********************************************************************
3066 * HTTP_clear_response_headers (internal)
3068 * clear out any old response headers
3070 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3072 DWORD i;
3074 for( i=0; i<lpwhr->nCustHeaders; i++)
3076 if( !lpwhr->pCustHeaders[i].lpszField )
3077 continue;
3078 if( !lpwhr->pCustHeaders[i].lpszValue )
3079 continue;
3080 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3081 continue;
3082 HTTP_DeleteCustomHeader( lpwhr, i );
3083 i--;
3087 /***********************************************************************
3088 * HTTP_GetResponseHeaders (internal)
3090 * Read server response
3092 * RETURNS
3094 * TRUE on success
3095 * FALSE on error
3097 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr)
3099 INT cbreaks = 0;
3100 WCHAR buffer[MAX_REPLY_LEN];
3101 DWORD buflen = MAX_REPLY_LEN;
3102 BOOL bSuccess = FALSE;
3103 INT rc = 0;
3104 static const WCHAR szCrLf[] = {'\r','\n',0};
3105 static const WCHAR szHundred[] = {'1','0','0',0};
3106 char bufferA[MAX_REPLY_LEN];
3107 LPWSTR status_code, status_text;
3108 DWORD cchMaxRawHeaders = 1024;
3109 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3110 DWORD cchRawHeaders = 0;
3112 TRACE("-->\n");
3114 /* clear old response headers (eg. from a redirect response) */
3115 HTTP_clear_response_headers( lpwhr );
3117 if (!NETCON_connected(&lpwhr->netConnection))
3118 goto lend;
3120 do {
3122 * HACK peek at the buffer
3124 buflen = MAX_REPLY_LEN;
3125 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3128 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3130 memset(buffer, 0, MAX_REPLY_LEN);
3131 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3132 goto lend;
3133 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3135 /* split the version from the status code */
3136 status_code = strchrW( buffer, ' ' );
3137 if( !status_code )
3138 goto lend;
3139 *status_code++=0;
3141 /* split the status code from the status text */
3142 status_text = strchrW( status_code, ' ' );
3143 if( !status_text )
3144 goto lend;
3145 *status_text++=0;
3147 TRACE("version [%s] status code [%s] status text [%s]\n",
3148 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3150 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3152 /* Add status code */
3153 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3154 HTTP_ADDHDR_FLAG_REPLACE);
3156 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3157 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3159 lpwhr->lpszVersion= WININET_strdupW(buffer);
3160 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3162 /* Restore the spaces */
3163 *(status_code-1) = ' ';
3164 *(status_text-1) = ' ';
3166 /* regenerate raw headers */
3167 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3169 cchMaxRawHeaders *= 2;
3170 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3172 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3173 cchRawHeaders += (buflen-1);
3174 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3175 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3176 lpszRawHeaders[cchRawHeaders] = '\0';
3178 /* Parse each response line */
3181 buflen = MAX_REPLY_LEN;
3182 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3184 LPWSTR * pFieldAndValue;
3186 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3187 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3189 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3191 cchMaxRawHeaders *= 2;
3192 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3194 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3195 cchRawHeaders += (buflen-1);
3196 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3197 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3198 lpszRawHeaders[cchRawHeaders] = '\0';
3200 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3201 if (!pFieldAndValue)
3202 break;
3204 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3205 HTTP_ADDREQ_FLAG_ADD );
3207 HTTP_FreeTokens(pFieldAndValue);
3209 else
3211 cbreaks++;
3212 if (cbreaks >= 2)
3213 break;
3215 }while(1);
3217 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3218 lpwhr->lpszRawHeaders = lpszRawHeaders;
3219 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3220 bSuccess = TRUE;
3222 lend:
3224 TRACE("<--\n");
3225 if (bSuccess)
3226 return rc;
3227 else
3228 return 0;
3232 static void strip_spaces(LPWSTR start)
3234 LPWSTR str = start;
3235 LPWSTR end;
3237 while (*str == ' ' && *str != '\0')
3238 str++;
3240 if (str != start)
3241 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3243 end = start + strlenW(start) - 1;
3244 while (end >= start && *end == ' ')
3246 *end = '\0';
3247 end--;
3252 /***********************************************************************
3253 * HTTP_InterpretHttpHeader (internal)
3255 * Parse server response
3257 * RETURNS
3259 * Pointer to array of field, value, NULL on success.
3260 * NULL on error.
3262 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3264 LPWSTR * pTokenPair;
3265 LPWSTR pszColon;
3266 INT len;
3268 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3270 pszColon = strchrW(buffer, ':');
3271 /* must have two tokens */
3272 if (!pszColon)
3274 HTTP_FreeTokens(pTokenPair);
3275 if (buffer[0])
3276 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3277 return NULL;
3280 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3281 if (!pTokenPair[0])
3283 HTTP_FreeTokens(pTokenPair);
3284 return NULL;
3286 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3287 pTokenPair[0][pszColon - buffer] = '\0';
3289 /* skip colon */
3290 pszColon++;
3291 len = strlenW(pszColon);
3292 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3293 if (!pTokenPair[1])
3295 HTTP_FreeTokens(pTokenPair);
3296 return NULL;
3298 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3300 strip_spaces(pTokenPair[0]);
3301 strip_spaces(pTokenPair[1]);
3303 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3304 return pTokenPair;
3307 /***********************************************************************
3308 * HTTP_ProcessHeader (internal)
3310 * Stuff header into header tables according to <dwModifier>
3314 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3316 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3318 LPHTTPHEADERW lphttpHdr = NULL;
3319 BOOL bSuccess = FALSE;
3320 INT index = -1;
3321 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3323 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3325 /* REPLACE wins out over ADD */
3326 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3327 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3329 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3330 index = -1;
3331 else
3332 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3334 if (index >= 0)
3336 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3338 return FALSE;
3340 lphttpHdr = &lpwhr->pCustHeaders[index];
3342 else if (value)
3344 HTTPHEADERW hdr;
3346 hdr.lpszField = (LPWSTR)field;
3347 hdr.lpszValue = (LPWSTR)value;
3348 hdr.wFlags = hdr.wCount = 0;
3350 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3351 hdr.wFlags |= HDR_ISREQUEST;
3353 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3355 /* no value to delete */
3356 else return TRUE;
3358 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3359 lphttpHdr->wFlags |= HDR_ISREQUEST;
3360 else
3361 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3363 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3365 HTTP_DeleteCustomHeader( lpwhr, index );
3367 if (value)
3369 HTTPHEADERW hdr;
3371 hdr.lpszField = (LPWSTR)field;
3372 hdr.lpszValue = (LPWSTR)value;
3373 hdr.wFlags = hdr.wCount = 0;
3375 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3376 hdr.wFlags |= HDR_ISREQUEST;
3378 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3381 return TRUE;
3383 else if (dwModifier & COALESCEFLAGS)
3385 LPWSTR lpsztmp;
3386 WCHAR ch = 0;
3387 INT len = 0;
3388 INT origlen = strlenW(lphttpHdr->lpszValue);
3389 INT valuelen = strlenW(value);
3391 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3393 ch = ',';
3394 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3396 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3398 ch = ';';
3399 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3402 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3404 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3405 if (lpsztmp)
3407 lphttpHdr->lpszValue = lpsztmp;
3408 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3409 if (ch > 0)
3411 lphttpHdr->lpszValue[origlen] = ch;
3412 origlen++;
3413 lphttpHdr->lpszValue[origlen] = ' ';
3414 origlen++;
3417 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
3418 lphttpHdr->lpszValue[len] = '\0';
3419 bSuccess = TRUE;
3421 else
3423 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
3424 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3427 TRACE("<-- %d\n",bSuccess);
3428 return bSuccess;
3432 /***********************************************************************
3433 * HTTP_CloseConnection (internal)
3435 * Close socket connection
3438 static void HTTP_CloseConnection(LPWININETHANDLEHEADER hdr)
3440 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
3441 LPWININETHTTPSESSIONW lpwhs = NULL;
3442 LPWININETAPPINFOW hIC = NULL;
3444 TRACE("%p\n",lpwhr);
3446 if (!NETCON_connected(&lpwhr->netConnection))
3447 return;
3449 if (lpwhr->pAuthInfo)
3451 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
3452 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
3454 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
3455 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
3456 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
3457 lpwhr->pAuthInfo = NULL;
3459 if (lpwhr->pProxyAuthInfo)
3461 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
3462 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
3464 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
3465 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
3466 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
3467 lpwhr->pProxyAuthInfo = NULL;
3470 lpwhs = lpwhr->lpHttpSession;
3471 hIC = lpwhs->lpAppInfo;
3473 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3474 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
3476 NETCON_close(&lpwhr->netConnection);
3478 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3479 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
3483 /***********************************************************************
3484 * HTTP_FinishedReading (internal)
3486 * Called when all content from server has been read by client.
3489 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
3491 WCHAR szConnectionResponse[20];
3492 DWORD dwBufferSize = sizeof(szConnectionResponse);
3494 TRACE("\n");
3496 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse,
3497 &dwBufferSize, NULL) ||
3498 strcmpiW(szConnectionResponse, szKeepAlive))
3500 HTTP_CloseConnection(&lpwhr->hdr);
3503 /* FIXME: store data in the URL cache here */
3505 return TRUE;
3509 /***********************************************************************
3510 * HTTP_GetCustomHeaderIndex (internal)
3512 * Return index of custom header from header array
3515 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
3516 int requested_index, BOOL request_only)
3518 DWORD index;
3520 TRACE("%s\n", debugstr_w(lpszField));
3522 for (index = 0; index < lpwhr->nCustHeaders; index++)
3524 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
3525 continue;
3527 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3528 continue;
3530 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
3531 continue;
3533 if (requested_index == 0)
3534 break;
3535 requested_index --;
3538 if (index >= lpwhr->nCustHeaders)
3539 index = -1;
3541 TRACE("Return: %d\n", index);
3542 return index;
3546 /***********************************************************************
3547 * HTTP_InsertCustomHeader (internal)
3549 * Insert header into array
3552 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
3554 INT count;
3555 LPHTTPHEADERW lph = NULL;
3556 BOOL r = FALSE;
3558 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
3559 count = lpwhr->nCustHeaders + 1;
3560 if (count > 1)
3561 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
3562 else
3563 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
3565 if (NULL != lph)
3567 lpwhr->pCustHeaders = lph;
3568 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
3569 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
3570 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
3571 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
3572 lpwhr->nCustHeaders++;
3573 r = TRUE;
3575 else
3577 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3580 return r;
3584 /***********************************************************************
3585 * HTTP_DeleteCustomHeader (internal)
3587 * Delete header from array
3588 * If this function is called, the indexs may change.
3590 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
3592 if( lpwhr->nCustHeaders <= 0 )
3593 return FALSE;
3594 if( index >= lpwhr->nCustHeaders )
3595 return FALSE;
3596 lpwhr->nCustHeaders--;
3598 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
3599 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
3600 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
3602 return TRUE;
3606 /***********************************************************************
3607 * HTTP_VerifyValidHeader (internal)
3609 * Verify the given header is not invalid for the given http request
3612 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
3614 BOOL rc = TRUE;
3616 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
3617 if (strcmpiW(field,szAccept_Encoding)==0)
3618 return FALSE;
3620 return rc;
3623 /***********************************************************************
3624 * IsHostInProxyBypassList (@)
3626 * Undocumented
3629 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
3631 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
3632 return FALSE;