wininet: Send a 'Pragma: no-cache' header if asked for.
[wine/wine-kai.git] / dlls / wininet / http.c
blobea2afb39bace188ac27ebe4a144a84843cba7872
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"
58 #include "wincrypt.h"
60 #include "internet.h"
61 #include "wine/debug.h"
62 #include "wine/unicode.h"
64 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
66 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
67 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
68 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
69 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
70 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
71 static const WCHAR szHost[] = { 'H','o','s','t',0 };
72 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
74 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
75 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
76 static const WCHAR szGET[] = { 'G','E','T', 0 };
78 #define MAXHOSTNAME 100
79 #define MAX_FIELD_VALUE_LEN 256
80 #define MAX_FIELD_LEN 256
82 #define HTTP_REFERER g_szReferer
83 #define HTTP_ACCEPT g_szAccept
84 #define HTTP_USERAGENT g_szUserAgent
86 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
87 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
88 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
89 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
90 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
91 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
92 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
94 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
96 struct HttpAuthInfo
98 LPWSTR scheme;
99 CredHandle cred;
100 CtxtHandle ctx;
101 TimeStamp exp;
102 ULONG attr;
103 ULONG max_token;
104 void *auth_data;
105 unsigned int auth_data_len;
106 BOOL finished; /* finished authenticating */
109 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
110 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
111 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
112 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
113 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
114 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
115 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
116 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
117 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
118 dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
119 lpdwIndex);
120 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
121 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
122 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
123 static void HTTP_DrainContent(WININETHTTPREQW *req);
125 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
127 int HeaderIndex = 0;
128 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
129 if (HeaderIndex == -1)
130 return NULL;
131 else
132 return &req->pCustHeaders[HeaderIndex];
135 /***********************************************************************
136 * HTTP_Tokenize (internal)
138 * Tokenize a string, allocating memory for the tokens.
140 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
142 LPWSTR * token_array;
143 int tokens = 0;
144 int i;
145 LPCWSTR next_token;
147 /* empty string has no tokens */
148 if (*string)
149 tokens++;
150 /* count tokens */
151 for (i = 0; string[i]; i++)
152 if (!strncmpW(string+i, token_string, strlenW(token_string)))
154 DWORD j;
155 tokens++;
156 /* we want to skip over separators, but not the null terminator */
157 for (j = 0; j < strlenW(token_string) - 1; j++)
158 if (!string[i+j])
159 break;
160 i += j;
163 /* add 1 for terminating NULL */
164 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
165 token_array[tokens] = NULL;
166 if (!tokens)
167 return token_array;
168 for (i = 0; i < tokens; i++)
170 int len;
171 next_token = strstrW(string, token_string);
172 if (!next_token) next_token = string+strlenW(string);
173 len = next_token - string;
174 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
175 memcpy(token_array[i], string, len*sizeof(WCHAR));
176 token_array[i][len] = '\0';
177 string = next_token+strlenW(token_string);
179 return token_array;
182 /***********************************************************************
183 * HTTP_FreeTokens (internal)
185 * Frees memory returned from HTTP_Tokenize.
187 static void HTTP_FreeTokens(LPWSTR * token_array)
189 int i;
190 for (i = 0; token_array[i]; i++)
191 HeapFree(GetProcessHeap(), 0, token_array[i]);
192 HeapFree(GetProcessHeap(), 0, token_array);
195 /* **********************************************************************
197 * Helper functions for the HttpSendRequest(Ex) functions
200 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
202 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
203 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
205 TRACE("%p\n", lpwhr);
207 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
208 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
209 req->dwContentLength, req->bEndRequest);
211 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
214 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
216 static const WCHAR szSlash[] = { '/',0 };
217 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
219 /* If we don't have a path we set it to root */
220 if (NULL == lpwhr->lpszPath)
221 lpwhr->lpszPath = WININET_strdupW(szSlash);
222 else /* remove \r and \n*/
224 int nLen = strlenW(lpwhr->lpszPath);
225 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
227 nLen--;
228 lpwhr->lpszPath[nLen]='\0';
230 /* Replace '\' with '/' */
231 while (nLen>0) {
232 nLen--;
233 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
237 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
238 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
239 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
241 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
242 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
243 *fixurl = '/';
244 strcpyW(fixurl + 1, lpwhr->lpszPath);
245 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
246 lpwhr->lpszPath = fixurl;
250 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
252 LPWSTR requestString;
253 DWORD len, n;
254 LPCWSTR *req;
255 UINT i;
256 LPWSTR p;
258 static const WCHAR szSpace[] = { ' ',0 };
259 static const WCHAR szcrlf[] = {'\r','\n', 0};
260 static const WCHAR szColon[] = { ':',' ',0 };
261 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
263 /* allocate space for an array of all the string pointers to be added */
264 len = (lpwhr->nCustHeaders)*4 + 10;
265 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
267 /* add the verb, path and HTTP version string */
268 n = 0;
269 req[n++] = verb;
270 req[n++] = szSpace;
271 req[n++] = path;
272 req[n++] = szSpace;
273 req[n++] = version;
275 /* Append custom request headers */
276 for (i = 0; i < lpwhr->nCustHeaders; i++)
278 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
280 req[n++] = szcrlf;
281 req[n++] = lpwhr->pCustHeaders[i].lpszField;
282 req[n++] = szColon;
283 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
285 TRACE("Adding custom header %s (%s)\n",
286 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
287 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
291 if( n >= len )
292 ERR("oops. buffer overrun\n");
294 req[n] = NULL;
295 requestString = HTTP_build_req( req, 4 );
296 HeapFree( GetProcessHeap(), 0, req );
299 * Set (header) termination string for request
300 * Make sure there's exactly two new lines at the end of the request
302 p = &requestString[strlenW(requestString)-1];
303 while ( (*p == '\n') || (*p == '\r') )
304 p--;
305 strcpyW( p+1, sztwocrlf );
307 return requestString;
310 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
312 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
313 int HeaderIndex;
314 LPHTTPHEADERW setCookieHeader;
316 HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
317 if (HeaderIndex == -1)
318 return;
319 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
321 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
323 int nPosStart = 0, nPosEnd = 0, len;
324 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
326 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
328 LPWSTR buf_cookie, cookie_name, cookie_data;
329 LPWSTR buf_url;
330 LPWSTR domain = NULL;
331 LPHTTPHEADERW Host;
333 int nEqualPos = 0;
334 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
335 setCookieHeader->lpszValue[nPosEnd] != '\0')
337 nPosEnd++;
339 if (setCookieHeader->lpszValue[nPosEnd] == ';')
341 /* fixme: not case sensitive, strcasestr is gnu only */
342 int nDomainPosEnd = 0;
343 int nDomainPosStart = 0, nDomainLength = 0;
344 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
345 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
346 if (lpszDomain)
347 { /* they have specified their own domain, lets use it */
348 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
349 lpszDomain[nDomainPosEnd] != '\0')
351 nDomainPosEnd++;
353 nDomainPosStart = strlenW(szDomain);
354 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
355 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
356 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
359 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
360 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
361 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
362 TRACE("%s\n", debugstr_w(buf_cookie));
363 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
365 nEqualPos++;
367 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
369 HeapFree(GetProcessHeap(), 0, buf_cookie);
370 break;
373 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
374 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
375 cookie_data = &buf_cookie[nEqualPos + 1];
377 Host = HTTP_GetHeader(lpwhr,szHost);
378 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
379 strlenW(lpwhr->lpszPath) + 9;
380 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
381 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
382 InternetSetCookieW(buf_url, cookie_name, cookie_data);
384 HeapFree(GetProcessHeap(), 0, buf_url);
385 HeapFree(GetProcessHeap(), 0, buf_cookie);
386 HeapFree(GetProcessHeap(), 0, cookie_name);
387 HeapFree(GetProcessHeap(), 0, domain);
388 nPosStart = nPosEnd;
393 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
395 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
396 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
397 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
400 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
401 struct HttpAuthInfo **ppAuthInfo,
402 LPWSTR domain_and_username, LPWSTR password )
404 SECURITY_STATUS sec_status;
405 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
406 BOOL first = FALSE;
408 TRACE("%s\n", debugstr_w(pszAuthValue));
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 PVOID pAuthData;
440 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
442 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
443 if (!pAuthInfo->scheme)
445 HeapFree(GetProcessHeap(), 0, pAuthInfo);
446 return FALSE;
449 if (domain_and_username)
451 WCHAR *user = strchrW(domain_and_username, '\\');
452 WCHAR *domain = domain_and_username;
454 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
456 pAuthData = &nt_auth_identity;
458 if (user) user++;
459 else
461 user = domain_and_username;
462 domain = NULL;
465 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
466 nt_auth_identity.User = user;
467 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
468 nt_auth_identity.Domain = domain;
469 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
470 nt_auth_identity.Password = password;
471 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
473 else
474 /* use default credentials */
475 pAuthData = NULL;
477 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
478 SECPKG_CRED_OUTBOUND, NULL,
479 pAuthData, NULL,
480 NULL, &pAuthInfo->cred,
481 &exp);
482 if (sec_status == SEC_E_OK)
484 PSecPkgInfoW sec_pkg_info;
485 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
486 if (sec_status == SEC_E_OK)
488 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
489 FreeContextBuffer(sec_pkg_info);
492 if (sec_status != SEC_E_OK)
494 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
495 debugstr_w(pAuthInfo->scheme), sec_status);
496 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
497 HeapFree(GetProcessHeap(), 0, pAuthInfo);
498 return FALSE;
501 *ppAuthInfo = pAuthInfo;
503 else if (pAuthInfo->finished)
504 return FALSE;
506 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
507 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
509 ERR("authentication scheme changed from %s to %s\n",
510 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
511 return FALSE;
514 if (is_basic_auth_value(pszAuthValue))
516 int userlen;
517 int passlen;
518 char *auth_data;
520 TRACE("basic authentication\n");
522 /* we don't cache credentials for basic authentication, so we can't
523 * retrieve them if the application didn't pass us any credentials */
524 if (!domain_and_username) return FALSE;
526 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
527 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
529 /* length includes a nul terminator, which will be re-used for the ':' */
530 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
531 if (!auth_data)
532 return FALSE;
534 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
535 auth_data[userlen] = ':';
536 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
538 pAuthInfo->auth_data = auth_data;
539 pAuthInfo->auth_data_len = userlen + 1 + passlen;
540 pAuthInfo->finished = TRUE;
542 return TRUE;
544 else
546 LPCWSTR pszAuthData;
547 SecBufferDesc out_desc, in_desc;
548 SecBuffer out, in;
549 unsigned char *buffer;
550 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
551 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
553 in.BufferType = SECBUFFER_TOKEN;
554 in.cbBuffer = 0;
555 in.pvBuffer = NULL;
557 in_desc.ulVersion = 0;
558 in_desc.cBuffers = 1;
559 in_desc.pBuffers = &in;
561 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
562 if (*pszAuthData == ' ')
564 pszAuthData++;
565 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
566 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
567 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
570 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
572 out.BufferType = SECBUFFER_TOKEN;
573 out.cbBuffer = pAuthInfo->max_token;
574 out.pvBuffer = buffer;
576 out_desc.ulVersion = 0;
577 out_desc.cBuffers = 1;
578 out_desc.pBuffers = &out;
580 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
581 first ? NULL : &pAuthInfo->ctx,
582 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
583 context_req, 0, SECURITY_NETWORK_DREP,
584 in.pvBuffer ? &in_desc : NULL,
585 0, &pAuthInfo->ctx, &out_desc,
586 &pAuthInfo->attr, &pAuthInfo->exp);
587 if (sec_status == SEC_E_OK)
589 pAuthInfo->finished = TRUE;
590 pAuthInfo->auth_data = out.pvBuffer;
591 pAuthInfo->auth_data_len = out.cbBuffer;
592 TRACE("sending last auth packet\n");
594 else if (sec_status == SEC_I_CONTINUE_NEEDED)
596 pAuthInfo->auth_data = out.pvBuffer;
597 pAuthInfo->auth_data_len = out.cbBuffer;
598 TRACE("sending next auth packet\n");
600 else
602 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
603 pAuthInfo->finished = TRUE;
604 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
605 return FALSE;
609 return TRUE;
612 /***********************************************************************
613 * HTTP_HttpAddRequestHeadersW (internal)
615 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
616 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
618 LPWSTR lpszStart;
619 LPWSTR lpszEnd;
620 LPWSTR buffer;
621 BOOL bSuccess = FALSE;
622 DWORD len;
624 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
626 if( dwHeaderLength == ~0U )
627 len = strlenW(lpszHeader);
628 else
629 len = dwHeaderLength;
630 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
631 lstrcpynW( buffer, lpszHeader, len + 1);
633 lpszStart = buffer;
637 LPWSTR * pFieldAndValue;
639 lpszEnd = lpszStart;
641 while (*lpszEnd != '\0')
643 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
644 break;
645 lpszEnd++;
648 if (*lpszStart == '\0')
649 break;
651 if (*lpszEnd == '\r')
653 *lpszEnd = '\0';
654 lpszEnd += 2; /* Jump over \r\n */
656 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
657 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
658 if (pFieldAndValue)
660 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
661 if (bSuccess)
662 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
663 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
664 HTTP_FreeTokens(pFieldAndValue);
667 lpszStart = lpszEnd;
668 } while (bSuccess);
670 HeapFree(GetProcessHeap(), 0, buffer);
672 return bSuccess;
675 /***********************************************************************
676 * HttpAddRequestHeadersW (WININET.@)
678 * Adds one or more HTTP header to the request handler
680 * NOTE
681 * On Windows if dwHeaderLength includes the trailing '\0', then
682 * HttpAddRequestHeadersW() adds it too. However this results in an
683 * invalid Http header which is rejected by some servers so we probably
684 * don't need to match Windows on that point.
686 * RETURNS
687 * TRUE on success
688 * FALSE on failure
691 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
692 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
694 BOOL bSuccess = FALSE;
695 LPWININETHTTPREQW lpwhr;
697 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
699 if (!lpszHeader)
700 return TRUE;
702 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
703 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
705 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
706 goto lend;
708 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
709 lend:
710 if( lpwhr )
711 WININET_Release( &lpwhr->hdr );
713 return bSuccess;
716 /***********************************************************************
717 * HttpAddRequestHeadersA (WININET.@)
719 * Adds one or more HTTP header to the request handler
721 * RETURNS
722 * TRUE on success
723 * FALSE on failure
726 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
727 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
729 DWORD len;
730 LPWSTR hdr;
731 BOOL r;
733 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
735 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
736 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
737 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
738 if( dwHeaderLength != ~0U )
739 dwHeaderLength = len;
741 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
743 HeapFree( GetProcessHeap(), 0, hdr );
745 return r;
748 /***********************************************************************
749 * HttpEndRequestA (WININET.@)
751 * Ends an HTTP request that was started by HttpSendRequestEx
753 * RETURNS
754 * TRUE if successful
755 * FALSE on failure
758 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
759 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
761 LPINTERNET_BUFFERSA ptr;
762 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
763 BOOL rc = FALSE;
765 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
766 dwContext);
768 ptr = lpBuffersOut;
769 if (ptr)
770 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
771 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
772 else
773 lpBuffersOutW = NULL;
775 ptrW = lpBuffersOutW;
776 while (ptr)
778 if (ptr->lpvBuffer && ptr->dwBufferLength)
779 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
780 ptrW->dwBufferLength = ptr->dwBufferLength;
781 ptrW->dwBufferTotal= ptr->dwBufferTotal;
783 if (ptr->Next)
784 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
785 sizeof(INTERNET_BUFFERSW));
787 ptr = ptr->Next;
788 ptrW = ptrW->Next;
791 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
793 if (lpBuffersOutW)
795 ptrW = lpBuffersOutW;
796 while (ptrW)
798 LPINTERNET_BUFFERSW ptrW2;
800 FIXME("Do we need to translate info out of these buffer?\n");
802 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
803 ptrW2 = ptrW->Next;
804 HeapFree(GetProcessHeap(),0,ptrW);
805 ptrW = ptrW2;
809 return rc;
812 /***********************************************************************
813 * HttpEndRequestW (WININET.@)
815 * Ends an HTTP request that was started by HttpSendRequestEx
817 * RETURNS
818 * TRUE if successful
819 * FALSE on failure
822 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
823 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
825 BOOL rc = FALSE;
826 LPWININETHTTPREQW lpwhr;
827 INT responseLen;
828 DWORD dwBufferSize;
830 TRACE("-->\n");
831 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
833 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
835 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
836 if (lpwhr)
837 WININET_Release( &lpwhr->hdr );
838 return FALSE;
841 lpwhr->hdr.dwFlags |= dwFlags;
842 lpwhr->hdr.dwContext = dwContext;
844 /* We appear to do nothing with lpBuffersOut.. is that correct? */
846 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
847 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
849 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
850 if (responseLen)
851 rc = TRUE;
853 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
854 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
856 /* process cookies here. Is this right? */
857 HTTP_ProcessCookies(lpwhr);
859 dwBufferSize = sizeof(lpwhr->dwContentLength);
860 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
861 &lpwhr->dwContentLength,&dwBufferSize,NULL))
862 lpwhr->dwContentLength = -1;
864 if (lpwhr->dwContentLength == 0)
865 HTTP_FinishedReading(lpwhr);
867 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
869 DWORD dwCode,dwCodeLength=sizeof(DWORD);
870 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
871 (dwCode==302 || dwCode==301))
873 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
874 dwBufferSize=sizeof(szNewLocation);
875 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
877 /* redirects are always GETs */
878 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
879 lpwhr->lpszVerb = WININET_strdupW(szGET);
880 HTTP_DrainContent(lpwhr);
881 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
882 INTERNET_STATUS_REDIRECT, szNewLocation,
883 dwBufferSize);
884 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
885 if (rc)
886 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
891 WININET_Release( &lpwhr->hdr );
892 TRACE("%i <--\n",rc);
893 return rc;
896 /***********************************************************************
897 * HttpOpenRequestW (WININET.@)
899 * Open a HTTP request handle
901 * RETURNS
902 * HINTERNET a HTTP request handle on success
903 * NULL on failure
906 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
907 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
908 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
909 DWORD dwFlags, DWORD_PTR dwContext)
911 LPWININETHTTPSESSIONW lpwhs;
912 HINTERNET handle = NULL;
914 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
915 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
916 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
917 dwFlags, dwContext);
918 if(lpszAcceptTypes!=NULL)
920 int i;
921 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
922 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
925 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
926 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
928 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
929 goto lend;
933 * My tests seem to show that the windows version does not
934 * become asynchronous until after this point. And anyhow
935 * if this call was asynchronous then how would you get the
936 * necessary HINTERNET pointer returned by this function.
939 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
940 lpszVersion, lpszReferrer, lpszAcceptTypes,
941 dwFlags, dwContext);
942 lend:
943 if( lpwhs )
944 WININET_Release( &lpwhs->hdr );
945 TRACE("returning %p\n", handle);
946 return handle;
950 /***********************************************************************
951 * HttpOpenRequestA (WININET.@)
953 * Open a HTTP request handle
955 * RETURNS
956 * HINTERNET a HTTP request handle on success
957 * NULL on failure
960 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
961 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
962 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
963 DWORD dwFlags, DWORD_PTR dwContext)
965 LPWSTR szVerb = NULL, szObjectName = NULL;
966 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
967 INT len, acceptTypesCount;
968 HINTERNET rc = FALSE;
969 LPCSTR *types;
971 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
972 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
973 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
974 dwFlags, dwContext);
976 if (lpszVerb)
978 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
979 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
980 if ( !szVerb )
981 goto end;
982 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
985 if (lpszObjectName)
987 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
988 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
989 if ( !szObjectName )
990 goto end;
991 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
994 if (lpszVersion)
996 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
997 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
998 if ( !szVersion )
999 goto end;
1000 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
1003 if (lpszReferrer)
1005 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1006 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1007 if ( !szReferrer )
1008 goto end;
1009 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1012 if (lpszAcceptTypes)
1014 acceptTypesCount = 0;
1015 types = lpszAcceptTypes;
1016 while (*types)
1018 /* find out how many there are */
1019 if (((ULONG_PTR)*types >> 16) && **types)
1021 TRACE("accept type: %s\n", debugstr_a(*types));
1022 acceptTypesCount++;
1024 types++;
1026 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1027 if (!szAcceptTypes) goto end;
1029 acceptTypesCount = 0;
1030 types = lpszAcceptTypes;
1031 while (*types)
1033 if (((ULONG_PTR)*types >> 16) && **types)
1035 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1036 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1037 if (!szAcceptTypes[acceptTypesCount]) goto end;
1039 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1040 acceptTypesCount++;
1042 types++;
1044 szAcceptTypes[acceptTypesCount] = NULL;
1046 else szAcceptTypes = 0;
1048 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1049 szVersion, szReferrer,
1050 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1052 end:
1053 if (szAcceptTypes)
1055 acceptTypesCount = 0;
1056 while (szAcceptTypes[acceptTypesCount])
1058 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1059 acceptTypesCount++;
1061 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1063 HeapFree(GetProcessHeap(), 0, szReferrer);
1064 HeapFree(GetProcessHeap(), 0, szVersion);
1065 HeapFree(GetProcessHeap(), 0, szObjectName);
1066 HeapFree(GetProcessHeap(), 0, szVerb);
1068 return rc;
1071 /***********************************************************************
1072 * HTTP_EncodeBase64
1074 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1076 UINT n = 0, x;
1077 static const CHAR HTTP_Base64Enc[] =
1078 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1080 while( len > 0 )
1082 /* first 6 bits, all from bin[0] */
1083 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1084 x = (bin[0] & 3) << 4;
1086 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1087 if( len == 1 )
1089 base64[n++] = HTTP_Base64Enc[x];
1090 base64[n++] = '=';
1091 base64[n++] = '=';
1092 break;
1094 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1095 x = ( bin[1] & 0x0f ) << 2;
1097 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1098 if( len == 2 )
1100 base64[n++] = HTTP_Base64Enc[x];
1101 base64[n++] = '=';
1102 break;
1104 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1106 /* last 6 bits, all from bin [2] */
1107 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1108 bin += 3;
1109 len -= 3;
1111 base64[n] = 0;
1112 return n;
1115 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1116 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1117 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1118 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1119 static const signed char HTTP_Base64Dec[256] =
1121 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1122 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1123 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1124 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1125 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1126 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1127 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1128 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1129 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1130 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1131 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1132 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1133 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1134 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1135 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1136 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1137 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1138 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1139 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1140 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1141 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1142 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1143 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1144 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1145 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1146 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1148 #undef CH
1150 /***********************************************************************
1151 * HTTP_DecodeBase64
1153 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1155 unsigned int n = 0;
1157 while(*base64)
1159 signed char in[4];
1161 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1162 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1163 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1164 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1166 WARN("invalid base64: %s\n", debugstr_w(base64));
1167 return 0;
1169 if (bin)
1170 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1171 n++;
1173 if ((base64[2] == '=') && (base64[3] == '='))
1174 break;
1175 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1176 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1178 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1179 return 0;
1181 if (bin)
1182 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1183 n++;
1185 if (base64[3] == '=')
1186 break;
1187 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1188 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1190 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1191 return 0;
1193 if (bin)
1194 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1195 n++;
1197 base64 += 4;
1200 return n;
1203 /***********************************************************************
1204 * HTTP_InsertAuthorization
1206 * Insert or delete the authorization field in the request header.
1208 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1210 if (pAuthInfo)
1212 static const WCHAR wszSpace[] = {' ',0};
1213 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1214 unsigned int len;
1215 WCHAR *authorization = NULL;
1217 if (pAuthInfo->auth_data_len)
1219 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1220 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1221 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1222 if (!authorization)
1223 return FALSE;
1225 strcpyW(authorization, pAuthInfo->scheme);
1226 strcatW(authorization, wszSpace);
1227 HTTP_EncodeBase64(pAuthInfo->auth_data,
1228 pAuthInfo->auth_data_len,
1229 authorization+strlenW(authorization));
1231 /* clear the data as it isn't valid now that it has been sent to the
1232 * server, unless it's Basic authentication which doesn't do
1233 * connection tracking */
1234 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1236 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1237 pAuthInfo->auth_data = NULL;
1238 pAuthInfo->auth_data_len = 0;
1242 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1244 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1246 HeapFree(GetProcessHeap(), 0, authorization);
1248 return TRUE;
1251 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1253 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1254 DWORD size;
1256 size = sizeof(new_location);
1257 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1259 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1260 strcpyW( url, new_location );
1262 else
1264 static const WCHAR slash[] = { '/',0 };
1265 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1266 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1267 WININETHTTPSESSIONW *session = req->lpHttpSession;
1269 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1270 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1272 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1274 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1275 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1276 else
1277 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1278 if (req->lpszPath[0] != '/') strcatW( url, slash );
1279 strcatW( url, req->lpszPath );
1281 TRACE("url=%s\n", debugstr_w(url));
1282 return url;
1285 /***********************************************************************
1286 * HTTP_DealWithProxy
1288 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1289 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1291 WCHAR buf[MAXHOSTNAME];
1292 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1293 static WCHAR szNul[] = { 0 };
1294 URL_COMPONENTSW UrlComponents;
1295 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1296 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1298 memset( &UrlComponents, 0, sizeof UrlComponents );
1299 UrlComponents.dwStructSize = sizeof UrlComponents;
1300 UrlComponents.lpszHostName = buf;
1301 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1303 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1304 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1305 sprintfW(proxy, szFormat, hIC->lpszProxy);
1306 else
1307 strcpyW(proxy, hIC->lpszProxy);
1308 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1309 return FALSE;
1310 if( UrlComponents.dwHostNameLength == 0 )
1311 return FALSE;
1313 if( !lpwhr->lpszPath )
1314 lpwhr->lpszPath = szNul;
1316 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1317 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1319 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1320 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1321 lpwhs->nServerPort = UrlComponents.nPort;
1323 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1324 return TRUE;
1327 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1329 char szaddr[32];
1330 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1332 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1333 INTERNET_STATUS_RESOLVING_NAME,
1334 lpwhs->lpszServerName,
1335 strlenW(lpwhs->lpszServerName)+1);
1337 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1338 &lpwhs->socketAddress))
1340 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1341 return FALSE;
1344 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1345 szaddr, sizeof(szaddr));
1346 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1347 INTERNET_STATUS_NAME_RESOLVED,
1348 szaddr, strlen(szaddr)+1);
1350 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1351 return TRUE;
1355 /***********************************************************************
1356 * HTTPREQ_Destroy (internal)
1358 * Deallocate request handle
1361 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1363 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1364 DWORD i;
1366 TRACE("\n");
1368 if(lpwhr->hCacheFile)
1369 CloseHandle(lpwhr->hCacheFile);
1371 if(lpwhr->lpszCacheFile) {
1372 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1373 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1376 WININET_Release(&lpwhr->lpHttpSession->hdr);
1378 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1379 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1380 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1381 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1382 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1384 for (i = 0; i < lpwhr->nCustHeaders; i++)
1386 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1387 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1390 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1391 HeapFree(GetProcessHeap(), 0, lpwhr);
1394 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1396 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1397 LPWININETHTTPSESSIONW lpwhs = NULL;
1399 TRACE("%p\n",lpwhr);
1401 if (!NETCON_connected(&lpwhr->netConnection))
1402 return;
1404 if (lpwhr->pAuthInfo)
1406 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1407 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1408 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1409 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1411 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1412 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1413 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1414 lpwhr->pAuthInfo = NULL;
1416 if (lpwhr->pProxyAuthInfo)
1418 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1419 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1420 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1421 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1423 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1424 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1425 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1426 lpwhr->pProxyAuthInfo = NULL;
1429 lpwhs = lpwhr->lpHttpSession;
1431 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1432 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1434 NETCON_close(&lpwhr->netConnection);
1436 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1437 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1440 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1442 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1444 switch(option) {
1445 case INTERNET_OPTION_HANDLE_TYPE:
1446 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1448 if (*size < sizeof(ULONG))
1449 return ERROR_INSUFFICIENT_BUFFER;
1451 *size = sizeof(DWORD);
1452 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1453 return ERROR_SUCCESS;
1455 case INTERNET_OPTION_URL: {
1456 WCHAR url[INTERNET_MAX_URL_LENGTH];
1457 HTTPHEADERW *host;
1458 DWORD len;
1460 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
1461 static const WCHAR hostW[] = {'H','o','s','t',0};
1463 TRACE("INTERNET_OPTION_URL\n");
1465 host = HTTP_GetHeader(req, hostW);
1466 sprintfW(url, formatW, host->lpszValue, req->lpszPath);
1467 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1469 if(unicode) {
1470 len = (strlenW(url)+1) * sizeof(WCHAR);
1471 if(*size < len)
1472 return ERROR_INSUFFICIENT_BUFFER;
1474 *size = len;
1475 strcpyW(buffer, url);
1476 return ERROR_SUCCESS;
1477 }else {
1478 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1479 if(len > *size)
1480 return ERROR_INSUFFICIENT_BUFFER;
1482 *size = len;
1483 return ERROR_SUCCESS;
1487 case INTERNET_OPTION_DATAFILE_NAME: {
1488 DWORD req_size;
1490 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1492 if(!req->lpszCacheFile) {
1493 *size = 0;
1494 return ERROR_INTERNET_ITEM_NOT_FOUND;
1497 if(unicode) {
1498 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1499 if(*size < req_size)
1500 return ERROR_INSUFFICIENT_BUFFER;
1502 *size = req_size;
1503 memcpy(buffer, req->lpszCacheFile, *size);
1504 return ERROR_SUCCESS;
1505 }else {
1506 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1507 if (req_size > *size)
1508 return ERROR_INSUFFICIENT_BUFFER;
1510 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1511 -1, buffer, *size, NULL, NULL);
1512 return ERROR_SUCCESS;
1516 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1517 PCCERT_CONTEXT context;
1519 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1520 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1521 return ERROR_INSUFFICIENT_BUFFER;
1524 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1525 if(context) {
1526 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1527 DWORD len;
1529 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1530 info->ftExpiry = context->pCertInfo->NotAfter;
1531 info->ftStart = context->pCertInfo->NotBefore;
1532 if(unicode) {
1533 len = CertNameToStrW(context->dwCertEncodingType,
1534 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1535 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1536 if(info->lpszSubjectInfo)
1537 CertNameToStrW(context->dwCertEncodingType,
1538 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1539 info->lpszSubjectInfo, len);
1540 len = CertNameToStrW(context->dwCertEncodingType,
1541 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1542 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1543 if (info->lpszIssuerInfo)
1544 CertNameToStrW(context->dwCertEncodingType,
1545 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1546 info->lpszIssuerInfo, len);
1547 }else {
1548 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1550 len = CertNameToStrA(context->dwCertEncodingType,
1551 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1552 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1553 if(infoA->lpszSubjectInfo)
1554 CertNameToStrA(context->dwCertEncodingType,
1555 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1556 infoA->lpszSubjectInfo, len);
1557 len = CertNameToStrA(context->dwCertEncodingType,
1558 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1559 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1560 if(infoA->lpszIssuerInfo)
1561 CertNameToStrA(context->dwCertEncodingType,
1562 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1563 infoA->lpszIssuerInfo, len);
1567 * Contrary to MSDN, these do not appear to be set.
1568 * lpszProtocolName
1569 * lpszSignatureAlgName
1570 * lpszEncryptionAlgName
1571 * dwKeySize
1573 CertFreeCertificateContext(context);
1574 return ERROR_SUCCESS;
1579 FIXME("Not implemented option %d\n", option);
1580 return ERROR_INTERNET_INVALID_OPTION;
1583 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1585 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1587 switch(option) {
1588 case INTERNET_OPTION_SEND_TIMEOUT:
1589 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1590 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1592 if (size != sizeof(DWORD))
1593 return ERROR_INVALID_PARAMETER;
1595 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1596 *(DWORD*)buffer);
1599 return ERROR_INTERNET_INVALID_OPTION;
1602 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1604 int bytes_read;
1606 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1607 sync ? MSG_WAITALL : 0, &bytes_read)) {
1608 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1609 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1611 /* always return success, even if the network layer returns an error */
1612 *read = 0;
1613 HTTP_FinishedReading(req);
1614 return ERROR_SUCCESS;
1617 req->dwContentRead += bytes_read;
1618 *read = bytes_read;
1620 if(req->lpszCacheFile) {
1621 BOOL res;
1622 DWORD dwBytesWritten;
1624 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1625 if(!res)
1626 WARN("WriteFile failed: %u\n", GetLastError());
1629 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1630 HTTP_FinishedReading(req);
1632 return ERROR_SUCCESS;
1635 static DWORD get_chunk_size(const char *buffer)
1637 const char *p;
1638 DWORD size = 0;
1640 for (p = buffer; *p; p++)
1642 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1643 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1644 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1645 else if (*p == ';') break;
1647 return size;
1650 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1652 char reply[MAX_REPLY_LEN], *p = buffer;
1653 DWORD buflen, to_read, to_write = size;
1654 int bytes_read;
1656 *read = 0;
1657 for (;;)
1659 if (*read == size) break;
1661 if (req->dwContentLength == ~0UL) /* new chunk */
1663 buflen = sizeof(reply);
1664 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1666 if (!(req->dwContentLength = get_chunk_size(reply)))
1668 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1669 HTTP_GetResponseHeaders(req, FALSE);
1670 break;
1673 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1675 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1677 if (bytes_read != to_read)
1678 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1680 /* always return success, even if the network layer returns an error */
1681 *read = 0;
1682 break;
1684 if (!bytes_read) break;
1686 req->dwContentRead += bytes_read;
1687 to_write -= bytes_read;
1688 *read += bytes_read;
1690 if (req->lpszCacheFile)
1692 DWORD dwBytesWritten;
1694 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1695 WARN("WriteFile failed: %u\n", GetLastError());
1697 p += bytes_read;
1699 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1701 req->dwContentRead = 0;
1702 req->dwContentLength = ~0UL;
1704 buflen = sizeof(reply);
1705 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1707 ERR("Malformed chunk\n");
1708 *read = 0;
1709 break;
1713 if (!*read) HTTP_FinishedReading(req);
1714 return ERROR_SUCCESS;
1717 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1719 WCHAR encoding[20];
1720 DWORD buflen = sizeof(encoding);
1721 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1723 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1724 !strcmpiW(encoding, szChunked))
1726 return HTTP_ReadChunked(req, buffer, size, read, sync);
1728 else
1729 return HTTP_Read(req, buffer, size, read, sync);
1732 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1734 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1735 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1738 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1740 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1741 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1742 INTERNET_ASYNC_RESULT iar;
1743 DWORD res;
1745 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1747 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1748 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1750 iar.dwResult = res == ERROR_SUCCESS;
1751 iar.dwError = res;
1753 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1754 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1755 sizeof(INTERNET_ASYNC_RESULT));
1758 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1759 DWORD flags, DWORD_PTR context)
1762 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1763 DWORD res;
1765 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1766 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1768 if (buffers->dwStructSize != sizeof(*buffers))
1769 return ERROR_INVALID_PARAMETER;
1771 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1773 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1774 DWORD available = 0;
1776 NETCON_query_data_available(&req->netConnection, &available);
1777 if (!available)
1779 WORKREQUEST workRequest;
1781 workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1782 workRequest.hdr = WININET_AddRef(&req->hdr);
1783 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1785 INTERNET_AsyncCall(&workRequest);
1787 return ERROR_IO_PENDING;
1791 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1792 !(flags & IRF_NO_WAIT));
1794 if (res == ERROR_SUCCESS) {
1795 DWORD size = buffers->dwBufferLength;
1796 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1797 &size, sizeof(size));
1800 return res;
1803 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1805 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1807 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1810 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1812 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1813 INTERNET_ASYNC_RESULT iar;
1814 char buffer[4048];
1816 TRACE("%p\n", workRequest->hdr);
1818 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1819 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1820 MSG_PEEK, (int *)&iar.dwError);
1822 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1823 sizeof(INTERNET_ASYNC_RESULT));
1826 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1828 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1829 BYTE buffer[4048];
1830 BOOL async;
1832 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1834 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1835 return ERROR_SUCCESS;
1837 /* Even if we are in async mode, we need to determine whether
1838 * there is actually more data available. We do this by trying
1839 * to peek only a single byte in async mode. */
1840 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1842 if (NETCON_recv(&req->netConnection, buffer,
1843 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1844 MSG_PEEK, (int *)available) && async && *available)
1846 WORKREQUEST workRequest;
1848 *available = 0;
1849 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1850 workRequest.hdr = WININET_AddRef( &req->hdr );
1852 INTERNET_AsyncCall(&workRequest);
1854 return ERROR_IO_PENDING;
1857 return ERROR_SUCCESS;
1860 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1861 HTTPREQ_Destroy,
1862 HTTPREQ_CloseConnection,
1863 HTTPREQ_QueryOption,
1864 HTTPREQ_SetOption,
1865 HTTPREQ_ReadFile,
1866 HTTPREQ_ReadFileExA,
1867 HTTPREQ_WriteFile,
1868 HTTPREQ_QueryDataAvailable,
1869 NULL
1872 /***********************************************************************
1873 * HTTP_HttpOpenRequestW (internal)
1875 * Open a HTTP request handle
1877 * RETURNS
1878 * HINTERNET a HTTP request handle on success
1879 * NULL on failure
1882 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1883 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1884 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1885 DWORD dwFlags, DWORD_PTR dwContext)
1887 LPWININETAPPINFOW hIC = NULL;
1888 LPWININETHTTPREQW lpwhr;
1889 LPWSTR lpszCookies;
1890 LPWSTR lpszUrl = NULL;
1891 DWORD nCookieSize;
1892 HINTERNET handle = NULL;
1893 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
1894 DWORD len;
1895 LPHTTPHEADERW Host;
1897 TRACE("-->\n");
1899 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1900 hIC = lpwhs->lpAppInfo;
1902 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1903 if (NULL == lpwhr)
1905 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1906 goto lend;
1908 lpwhr->hdr.htype = WH_HHTTPREQ;
1909 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1910 lpwhr->hdr.dwFlags = dwFlags;
1911 lpwhr->hdr.dwContext = dwContext;
1912 lpwhr->hdr.refs = 1;
1913 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1914 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1916 WININET_AddRef( &lpwhs->hdr );
1917 lpwhr->lpHttpSession = lpwhs;
1918 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1920 handle = WININET_AllocHandle( &lpwhr->hdr );
1921 if (NULL == handle)
1923 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1924 goto lend;
1927 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1929 InternetCloseHandle( handle );
1930 handle = NULL;
1931 goto lend;
1934 if (lpszObjectName && *lpszObjectName) {
1935 HRESULT rc;
1937 len = 0;
1938 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1939 if (rc != E_POINTER)
1940 len = strlenW(lpszObjectName)+1;
1941 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1942 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1943 URL_ESCAPE_SPACES_ONLY);
1944 if (rc)
1946 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1947 strcpyW(lpwhr->lpszPath,lpszObjectName);
1951 if (lpszReferrer && *lpszReferrer)
1952 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1954 if (lpszAcceptTypes)
1956 int i;
1957 for (i = 0; lpszAcceptTypes[i]; i++)
1959 if (!*lpszAcceptTypes[i]) continue;
1960 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1961 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1962 HTTP_ADDHDR_FLAG_REQ |
1963 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1967 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1969 if (lpszVersion)
1970 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1971 else
1972 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1974 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1976 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1977 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1978 INTERNET_DEFAULT_HTTPS_PORT :
1979 INTERNET_DEFAULT_HTTP_PORT);
1981 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
1982 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
1983 INTERNET_DEFAULT_HTTPS_PORT :
1984 INTERNET_DEFAULT_HTTP_PORT);
1986 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
1987 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
1989 Host = HTTP_GetHeader(lpwhr,szHost);
1991 len = lstrlenW(Host->lpszValue) + strlenW(szUrlForm);
1992 lpszUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1993 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
1995 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) &&
1996 InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
1998 int cnt = 0;
1999 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
2000 static const WCHAR szcrlf[] = {'\r','\n',0};
2002 lpszCookies = HeapAlloc(GetProcessHeap(), 0, (nCookieSize + 1 + 8)*sizeof(WCHAR));
2004 cnt += sprintfW(lpszCookies, szCookie);
2005 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
2006 strcatW(lpszCookies, szcrlf);
2008 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies),
2009 HTTP_ADDREQ_FLAG_ADD);
2010 HeapFree(GetProcessHeap(), 0, lpszCookies);
2012 HeapFree(GetProcessHeap(), 0, lpszUrl);
2015 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2016 INTERNET_STATUS_HANDLE_CREATED, &handle,
2017 sizeof(handle));
2020 * A STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on windows
2023 if (!HTTP_ResolveName(lpwhr))
2025 InternetCloseHandle( handle );
2026 handle = NULL;
2029 lend:
2030 if( lpwhr )
2031 WININET_Release( &lpwhr->hdr );
2033 TRACE("<-- %p (%p)\n", handle, lpwhr);
2034 return handle;
2037 /* read any content returned by the server so that the connection can be
2038 * reused */
2039 static void HTTP_DrainContent(WININETHTTPREQW *req)
2041 DWORD bytes_read;
2043 if (!NETCON_connected(&req->netConnection)) return;
2045 if (req->dwContentLength == -1)
2046 NETCON_close(&req->netConnection);
2050 char buffer[2048];
2051 if (HTTP_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2052 return;
2053 } while (bytes_read);
2056 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2057 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2058 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2059 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2060 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2061 static const WCHAR szAge[] = { 'A','g','e',0 };
2062 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2063 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2064 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2065 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2066 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2067 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2068 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2069 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2070 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2071 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2072 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2073 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 };
2074 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2075 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2076 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2077 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2078 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2079 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2080 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2081 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2082 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2083 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2084 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2085 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2086 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2087 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2088 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2089 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2090 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2091 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2092 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2093 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2094 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2095 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2096 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2097 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2098 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2099 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2100 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 };
2101 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2102 static const WCHAR szURI[] = { 'U','R','I',0 };
2103 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2104 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2105 static const WCHAR szVia[] = { 'V','i','a',0 };
2106 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2107 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2109 static const LPCWSTR header_lookup[] = {
2110 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2111 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2112 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2113 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2114 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2115 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2116 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2117 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2118 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2119 szDate, /* HTTP_QUERY_DATE = 9 */
2120 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2121 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2122 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2123 szURI, /* HTTP_QUERY_URI = 13 */
2124 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2125 NULL, /* HTTP_QUERY_COST = 15 */
2126 NULL, /* HTTP_QUERY_LINK = 16 */
2127 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2128 NULL, /* HTTP_QUERY_VERSION = 18 */
2129 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2130 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2131 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2132 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2133 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2134 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2135 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2136 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2137 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2138 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2139 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2140 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2141 NULL, /* HTTP_QUERY_FROM = 31 */
2142 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2143 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2144 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2145 szReferer, /* HTTP_QUERY_REFERER = 35 */
2146 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2147 szServer, /* HTTP_QUERY_SERVER = 37 */
2148 NULL, /* HTTP_TITLE = 38 */
2149 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2150 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2151 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2152 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2153 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2154 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2155 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2156 NULL, /* HTTP_QUERY_REFRESH = 46 */
2157 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2158 szAge, /* HTTP_QUERY_AGE = 48 */
2159 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2160 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2161 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2162 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2163 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2164 szETag, /* HTTP_QUERY_ETAG = 54 */
2165 szHost, /* HTTP_QUERY_HOST = 55 */
2166 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2167 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2168 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2169 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2170 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2171 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2172 szRange, /* HTTP_QUERY_RANGE = 62 */
2173 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2174 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2175 szVary, /* HTTP_QUERY_VARY = 65 */
2176 szVia, /* HTTP_QUERY_VIA = 66 */
2177 szWarning, /* HTTP_QUERY_WARNING = 67 */
2178 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2179 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2180 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2183 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2185 /***********************************************************************
2186 * HTTP_HttpQueryInfoW (internal)
2188 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2189 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2191 LPHTTPHEADERW lphttpHdr = NULL;
2192 BOOL bSuccess = FALSE;
2193 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2194 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2195 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2196 INT index = -1;
2198 /* Find requested header structure */
2199 switch (level)
2201 case HTTP_QUERY_CUSTOM:
2202 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2203 break;
2205 case HTTP_QUERY_RAW_HEADERS_CRLF:
2207 LPWSTR headers;
2208 DWORD len;
2209 BOOL ret = FALSE;
2211 if (request_only)
2212 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2213 else
2214 headers = lpwhr->lpszRawHeaders;
2216 len = (strlenW(headers) + 1) * sizeof(WCHAR);
2217 if (len > *lpdwBufferLength)
2219 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2220 ret = FALSE;
2222 else if (lpBuffer)
2224 memcpy(lpBuffer, headers, len);
2225 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2226 ret = TRUE;
2228 *lpdwBufferLength = len;
2230 if (request_only)
2231 HeapFree(GetProcessHeap(), 0, headers);
2232 return ret;
2234 case HTTP_QUERY_RAW_HEADERS:
2236 static const WCHAR szCrLf[] = {'\r','\n',0};
2237 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2238 DWORD i, size = 0;
2239 LPWSTR pszString = (WCHAR*)lpBuffer;
2241 for (i = 0; ppszRawHeaderLines[i]; i++)
2242 size += strlenW(ppszRawHeaderLines[i]) + 1;
2244 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2246 HTTP_FreeTokens(ppszRawHeaderLines);
2247 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2248 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2249 return FALSE;
2252 for (i = 0; ppszRawHeaderLines[i]; i++)
2254 DWORD len = strlenW(ppszRawHeaderLines[i]);
2255 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2256 pszString += len+1;
2258 *pszString = '\0';
2260 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
2262 *lpdwBufferLength = size * sizeof(WCHAR);
2263 HTTP_FreeTokens(ppszRawHeaderLines);
2265 return TRUE;
2267 case HTTP_QUERY_STATUS_TEXT:
2268 if (lpwhr->lpszStatusText)
2270 DWORD len = strlenW(lpwhr->lpszStatusText);
2271 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2273 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2274 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2275 return FALSE;
2277 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
2278 *lpdwBufferLength = len * sizeof(WCHAR);
2280 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2282 return TRUE;
2284 break;
2285 case HTTP_QUERY_VERSION:
2286 if (lpwhr->lpszVersion)
2288 DWORD len = strlenW(lpwhr->lpszVersion);
2289 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2291 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2292 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2293 return FALSE;
2295 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
2296 *lpdwBufferLength = len * sizeof(WCHAR);
2298 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2300 return TRUE;
2302 break;
2303 default:
2304 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2306 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
2307 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2308 requested_index,request_only);
2311 if (index >= 0)
2312 lphttpHdr = &lpwhr->pCustHeaders[index];
2314 /* Ensure header satisfies requested attributes */
2315 if (!lphttpHdr ||
2316 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2317 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2319 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2320 return bSuccess;
2323 if (lpdwIndex)
2324 (*lpdwIndex)++;
2326 /* coalesce value to requested type */
2327 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
2329 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2330 bSuccess = TRUE;
2332 TRACE(" returning number : %d\n", *(int *)lpBuffer);
2334 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
2336 time_t tmpTime;
2337 struct tm tmpTM;
2338 SYSTEMTIME *STHook;
2340 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2342 tmpTM = *gmtime(&tmpTime);
2343 STHook = (SYSTEMTIME *) lpBuffer;
2344 if(STHook==NULL)
2345 return bSuccess;
2347 STHook->wDay = tmpTM.tm_mday;
2348 STHook->wHour = tmpTM.tm_hour;
2349 STHook->wMilliseconds = 0;
2350 STHook->wMinute = tmpTM.tm_min;
2351 STHook->wDayOfWeek = tmpTM.tm_wday;
2352 STHook->wMonth = tmpTM.tm_mon + 1;
2353 STHook->wSecond = tmpTM.tm_sec;
2354 STHook->wYear = tmpTM.tm_year;
2356 bSuccess = TRUE;
2358 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2359 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2360 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2362 else if (lphttpHdr->lpszValue)
2364 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2366 if (len > *lpdwBufferLength)
2368 *lpdwBufferLength = len;
2369 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2370 return bSuccess;
2373 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2374 *lpdwBufferLength = len - sizeof(WCHAR);
2375 bSuccess = TRUE;
2377 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
2379 return bSuccess;
2382 /***********************************************************************
2383 * HttpQueryInfoW (WININET.@)
2385 * Queries for information about an HTTP request
2387 * RETURNS
2388 * TRUE on success
2389 * FALSE on failure
2392 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2393 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2395 BOOL bSuccess = FALSE;
2396 LPWININETHTTPREQW lpwhr;
2398 if (TRACE_ON(wininet)) {
2399 #define FE(x) { x, #x }
2400 static const wininet_flag_info query_flags[] = {
2401 FE(HTTP_QUERY_MIME_VERSION),
2402 FE(HTTP_QUERY_CONTENT_TYPE),
2403 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2404 FE(HTTP_QUERY_CONTENT_ID),
2405 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2406 FE(HTTP_QUERY_CONTENT_LENGTH),
2407 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2408 FE(HTTP_QUERY_ALLOW),
2409 FE(HTTP_QUERY_PUBLIC),
2410 FE(HTTP_QUERY_DATE),
2411 FE(HTTP_QUERY_EXPIRES),
2412 FE(HTTP_QUERY_LAST_MODIFIED),
2413 FE(HTTP_QUERY_MESSAGE_ID),
2414 FE(HTTP_QUERY_URI),
2415 FE(HTTP_QUERY_DERIVED_FROM),
2416 FE(HTTP_QUERY_COST),
2417 FE(HTTP_QUERY_LINK),
2418 FE(HTTP_QUERY_PRAGMA),
2419 FE(HTTP_QUERY_VERSION),
2420 FE(HTTP_QUERY_STATUS_CODE),
2421 FE(HTTP_QUERY_STATUS_TEXT),
2422 FE(HTTP_QUERY_RAW_HEADERS),
2423 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2424 FE(HTTP_QUERY_CONNECTION),
2425 FE(HTTP_QUERY_ACCEPT),
2426 FE(HTTP_QUERY_ACCEPT_CHARSET),
2427 FE(HTTP_QUERY_ACCEPT_ENCODING),
2428 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2429 FE(HTTP_QUERY_AUTHORIZATION),
2430 FE(HTTP_QUERY_CONTENT_ENCODING),
2431 FE(HTTP_QUERY_FORWARDED),
2432 FE(HTTP_QUERY_FROM),
2433 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2434 FE(HTTP_QUERY_LOCATION),
2435 FE(HTTP_QUERY_ORIG_URI),
2436 FE(HTTP_QUERY_REFERER),
2437 FE(HTTP_QUERY_RETRY_AFTER),
2438 FE(HTTP_QUERY_SERVER),
2439 FE(HTTP_QUERY_TITLE),
2440 FE(HTTP_QUERY_USER_AGENT),
2441 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2442 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2443 FE(HTTP_QUERY_ACCEPT_RANGES),
2444 FE(HTTP_QUERY_SET_COOKIE),
2445 FE(HTTP_QUERY_COOKIE),
2446 FE(HTTP_QUERY_REQUEST_METHOD),
2447 FE(HTTP_QUERY_REFRESH),
2448 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2449 FE(HTTP_QUERY_AGE),
2450 FE(HTTP_QUERY_CACHE_CONTROL),
2451 FE(HTTP_QUERY_CONTENT_BASE),
2452 FE(HTTP_QUERY_CONTENT_LOCATION),
2453 FE(HTTP_QUERY_CONTENT_MD5),
2454 FE(HTTP_QUERY_CONTENT_RANGE),
2455 FE(HTTP_QUERY_ETAG),
2456 FE(HTTP_QUERY_HOST),
2457 FE(HTTP_QUERY_IF_MATCH),
2458 FE(HTTP_QUERY_IF_NONE_MATCH),
2459 FE(HTTP_QUERY_IF_RANGE),
2460 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2461 FE(HTTP_QUERY_MAX_FORWARDS),
2462 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2463 FE(HTTP_QUERY_RANGE),
2464 FE(HTTP_QUERY_TRANSFER_ENCODING),
2465 FE(HTTP_QUERY_UPGRADE),
2466 FE(HTTP_QUERY_VARY),
2467 FE(HTTP_QUERY_VIA),
2468 FE(HTTP_QUERY_WARNING),
2469 FE(HTTP_QUERY_CUSTOM)
2471 static const wininet_flag_info modifier_flags[] = {
2472 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2473 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2474 FE(HTTP_QUERY_FLAG_NUMBER),
2475 FE(HTTP_QUERY_FLAG_COALESCE)
2477 #undef FE
2478 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2479 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2480 DWORD i;
2482 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2483 TRACE(" Attribute:");
2484 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2485 if (query_flags[i].val == info) {
2486 TRACE(" %s", query_flags[i].name);
2487 break;
2490 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2491 TRACE(" Unknown (%08x)", info);
2494 TRACE(" Modifier:");
2495 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2496 if (modifier_flags[i].val & info_mod) {
2497 TRACE(" %s", modifier_flags[i].name);
2498 info_mod &= ~ modifier_flags[i].val;
2502 if (info_mod) {
2503 TRACE(" Unknown (%08x)", info_mod);
2505 TRACE("\n");
2508 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2509 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2511 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2512 goto lend;
2515 if (lpBuffer == NULL)
2516 *lpdwBufferLength = 0;
2517 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2518 lpBuffer, lpdwBufferLength, lpdwIndex);
2520 lend:
2521 if( lpwhr )
2522 WININET_Release( &lpwhr->hdr );
2524 TRACE("%d <--\n", bSuccess);
2525 return bSuccess;
2528 /***********************************************************************
2529 * HttpQueryInfoA (WININET.@)
2531 * Queries for information about an HTTP request
2533 * RETURNS
2534 * TRUE on success
2535 * FALSE on failure
2538 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2539 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2541 BOOL result;
2542 DWORD len;
2543 WCHAR* bufferW;
2545 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2546 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2548 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2549 lpdwBufferLength, lpdwIndex );
2552 if (lpBuffer)
2554 DWORD alloclen;
2555 len = (*lpdwBufferLength)*sizeof(WCHAR);
2556 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2558 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2559 if (alloclen < len)
2560 alloclen = len;
2562 else
2563 alloclen = len;
2564 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2565 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2566 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2567 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2568 } else
2570 bufferW = NULL;
2571 len = 0;
2574 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2575 &len, lpdwIndex );
2576 if( result )
2578 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2579 lpBuffer, *lpdwBufferLength, NULL, NULL );
2580 *lpdwBufferLength = len - 1;
2582 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2584 else
2585 /* since the strings being returned from HttpQueryInfoW should be
2586 * only ASCII characters, it is reasonable to assume that all of
2587 * the Unicode characters can be reduced to a single byte */
2588 *lpdwBufferLength = len / sizeof(WCHAR);
2590 HeapFree(GetProcessHeap(), 0, bufferW );
2592 return result;
2595 /***********************************************************************
2596 * HttpSendRequestExA (WININET.@)
2598 * Sends the specified request to the HTTP server and allows chunked
2599 * transfers.
2601 * RETURNS
2602 * Success: TRUE
2603 * Failure: FALSE, call GetLastError() for more information.
2605 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2606 LPINTERNET_BUFFERSA lpBuffersIn,
2607 LPINTERNET_BUFFERSA lpBuffersOut,
2608 DWORD dwFlags, DWORD_PTR dwContext)
2610 INTERNET_BUFFERSW BuffersInW;
2611 BOOL rc = FALSE;
2612 DWORD headerlen;
2613 LPWSTR header = NULL;
2615 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2616 lpBuffersOut, dwFlags, dwContext);
2618 if (lpBuffersIn)
2620 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2621 if (lpBuffersIn->lpcszHeader)
2623 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2624 lpBuffersIn->dwHeadersLength,0,0);
2625 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2626 if (!(BuffersInW.lpcszHeader = header))
2628 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2629 return FALSE;
2631 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2632 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2633 header, headerlen);
2635 else
2636 BuffersInW.lpcszHeader = NULL;
2637 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2638 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2639 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2640 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2641 BuffersInW.Next = NULL;
2644 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2646 HeapFree(GetProcessHeap(),0,header);
2648 return rc;
2651 /***********************************************************************
2652 * HttpSendRequestExW (WININET.@)
2654 * Sends the specified request to the HTTP server and allows chunked
2655 * transfers
2657 * RETURNS
2658 * Success: TRUE
2659 * Failure: FALSE, call GetLastError() for more information.
2661 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2662 LPINTERNET_BUFFERSW lpBuffersIn,
2663 LPINTERNET_BUFFERSW lpBuffersOut,
2664 DWORD dwFlags, DWORD_PTR dwContext)
2666 BOOL ret = FALSE;
2667 LPWININETHTTPREQW lpwhr;
2668 LPWININETHTTPSESSIONW lpwhs;
2669 LPWININETAPPINFOW hIC;
2671 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2672 lpBuffersOut, dwFlags, dwContext);
2674 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2676 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2678 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2679 goto lend;
2682 lpwhs = lpwhr->lpHttpSession;
2683 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2684 hIC = lpwhs->lpAppInfo;
2685 assert(hIC->hdr.htype == WH_HINIT);
2687 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2689 WORKREQUEST workRequest;
2690 struct WORKREQ_HTTPSENDREQUESTW *req;
2692 workRequest.asyncproc = AsyncHttpSendRequestProc;
2693 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2694 req = &workRequest.u.HttpSendRequestW;
2695 if (lpBuffersIn)
2697 if (lpBuffersIn->lpcszHeader)
2698 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2699 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2700 else
2701 req->lpszHeader = NULL;
2702 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2703 req->lpOptional = lpBuffersIn->lpvBuffer;
2704 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2705 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2707 else
2709 req->lpszHeader = NULL;
2710 req->dwHeaderLength = 0;
2711 req->lpOptional = NULL;
2712 req->dwOptionalLength = 0;
2713 req->dwContentLength = 0;
2716 req->bEndRequest = FALSE;
2718 INTERNET_AsyncCall(&workRequest);
2720 * This is from windows.
2722 INTERNET_SetLastError(ERROR_IO_PENDING);
2724 else
2726 if (lpBuffersIn)
2727 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2728 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2729 lpBuffersIn->dwBufferTotal, FALSE);
2730 else
2731 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2734 lend:
2735 if ( lpwhr )
2736 WININET_Release( &lpwhr->hdr );
2738 TRACE("<---\n");
2739 return ret;
2742 /***********************************************************************
2743 * HttpSendRequestW (WININET.@)
2745 * Sends the specified request to the HTTP server
2747 * RETURNS
2748 * TRUE on success
2749 * FALSE on failure
2752 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2753 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2755 LPWININETHTTPREQW lpwhr;
2756 LPWININETHTTPSESSIONW lpwhs = NULL;
2757 LPWININETAPPINFOW hIC = NULL;
2758 BOOL r;
2760 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2761 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2763 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2764 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2766 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2767 r = FALSE;
2768 goto lend;
2771 lpwhs = lpwhr->lpHttpSession;
2772 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2774 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2775 r = FALSE;
2776 goto lend;
2779 hIC = lpwhs->lpAppInfo;
2780 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2782 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2783 r = FALSE;
2784 goto lend;
2787 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2789 WORKREQUEST workRequest;
2790 struct WORKREQ_HTTPSENDREQUESTW *req;
2792 workRequest.asyncproc = AsyncHttpSendRequestProc;
2793 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2794 req = &workRequest.u.HttpSendRequestW;
2795 if (lpszHeaders)
2797 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2798 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2800 else
2801 req->lpszHeader = 0;
2802 req->dwHeaderLength = dwHeaderLength;
2803 req->lpOptional = lpOptional;
2804 req->dwOptionalLength = dwOptionalLength;
2805 req->dwContentLength = dwOptionalLength;
2806 req->bEndRequest = TRUE;
2808 INTERNET_AsyncCall(&workRequest);
2810 * This is from windows.
2812 INTERNET_SetLastError(ERROR_IO_PENDING);
2813 r = FALSE;
2815 else
2817 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2818 dwHeaderLength, lpOptional, dwOptionalLength,
2819 dwOptionalLength, TRUE);
2821 lend:
2822 if( lpwhr )
2823 WININET_Release( &lpwhr->hdr );
2824 return r;
2827 /***********************************************************************
2828 * HttpSendRequestA (WININET.@)
2830 * Sends the specified request to the HTTP server
2832 * RETURNS
2833 * TRUE on success
2834 * FALSE on failure
2837 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2838 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2840 BOOL result;
2841 LPWSTR szHeaders=NULL;
2842 DWORD nLen=dwHeaderLength;
2843 if(lpszHeaders!=NULL)
2845 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2846 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2847 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2849 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2850 HeapFree(GetProcessHeap(),0,szHeaders);
2851 return result;
2854 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2856 LPHTTPHEADERW host_header;
2858 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2860 host_header = HTTP_GetHeader(req, szHost);
2861 if(!host_header)
2862 return FALSE;
2864 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2865 return TRUE;
2868 /***********************************************************************
2869 * HTTP_HandleRedirect (internal)
2871 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2873 static const WCHAR szContentType[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
2874 static const WCHAR szContentLength[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
2875 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2876 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2877 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2878 WCHAR path[INTERNET_MAX_URL_LENGTH];
2879 int index;
2881 if(lpszUrl[0]=='/')
2883 /* if it's an absolute path, keep the same session info */
2884 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2886 else
2888 URL_COMPONENTSW urlComponents;
2889 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2890 static WCHAR szHttp[] = {'h','t','t','p',0};
2891 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2892 DWORD url_length = 0;
2893 LPWSTR orig_url;
2894 LPWSTR combined_url;
2896 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2897 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2898 urlComponents.dwSchemeLength = 0;
2899 urlComponents.lpszHostName = lpwhs->lpszHostName;
2900 urlComponents.dwHostNameLength = 0;
2901 urlComponents.nPort = lpwhs->nHostPort;
2902 urlComponents.lpszUserName = lpwhs->lpszUserName;
2903 urlComponents.dwUserNameLength = 0;
2904 urlComponents.lpszPassword = NULL;
2905 urlComponents.dwPasswordLength = 0;
2906 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2907 urlComponents.dwUrlPathLength = 0;
2908 urlComponents.lpszExtraInfo = NULL;
2909 urlComponents.dwExtraInfoLength = 0;
2911 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2912 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2913 return FALSE;
2915 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2917 /* convert from bytes to characters */
2918 url_length = url_length / sizeof(WCHAR) - 1;
2919 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2921 HeapFree(GetProcessHeap(), 0, orig_url);
2922 return FALSE;
2925 url_length = 0;
2926 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2927 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2929 HeapFree(GetProcessHeap(), 0, orig_url);
2930 return FALSE;
2932 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2934 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2936 HeapFree(GetProcessHeap(), 0, orig_url);
2937 HeapFree(GetProcessHeap(), 0, combined_url);
2938 return FALSE;
2940 HeapFree(GetProcessHeap(), 0, orig_url);
2942 userName[0] = 0;
2943 hostName[0] = 0;
2944 protocol[0] = 0;
2946 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2947 urlComponents.lpszScheme = protocol;
2948 urlComponents.dwSchemeLength = 32;
2949 urlComponents.lpszHostName = hostName;
2950 urlComponents.dwHostNameLength = MAXHOSTNAME;
2951 urlComponents.lpszUserName = userName;
2952 urlComponents.dwUserNameLength = 1024;
2953 urlComponents.lpszPassword = NULL;
2954 urlComponents.dwPasswordLength = 0;
2955 urlComponents.lpszUrlPath = path;
2956 urlComponents.dwUrlPathLength = 2048;
2957 urlComponents.lpszExtraInfo = NULL;
2958 urlComponents.dwExtraInfoLength = 0;
2959 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2961 HeapFree(GetProcessHeap(), 0, combined_url);
2962 return FALSE;
2965 HeapFree(GetProcessHeap(), 0, combined_url);
2967 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2968 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2970 TRACE("redirect from secure page to non-secure page\n");
2971 /* FIXME: warn about from secure redirect to non-secure page */
2972 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2974 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2975 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2977 TRACE("redirect from non-secure page to secure page\n");
2978 /* FIXME: notify about redirect to secure page */
2979 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2982 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2984 if (lstrlenW(protocol)>4) /*https*/
2985 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2986 else /*http*/
2987 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2990 #if 0
2992 * This upsets redirects to binary files on sourceforge.net
2993 * and gives an html page instead of the target file
2994 * Examination of the HTTP request sent by native wininet.dll
2995 * reveals that it doesn't send a referrer in that case.
2996 * Maybe there's a flag that enables this, or maybe a referrer
2997 * shouldn't be added in case of a redirect.
3000 /* consider the current host as the referrer */
3001 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3002 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3003 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3004 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3005 #endif
3007 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3008 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3009 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3011 int len;
3012 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3013 len = lstrlenW(hostName);
3014 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3015 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3016 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3018 else
3019 lpwhs->lpszHostName = WININET_strdupW(hostName);
3021 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3023 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3024 lpwhs->lpszUserName = NULL;
3025 if (userName[0])
3026 lpwhs->lpszUserName = WININET_strdupW(userName);
3028 if (!using_proxy)
3030 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3031 lpwhs->lpszServerName = WININET_strdupW(hostName);
3032 lpwhs->nServerPort = urlComponents.nPort;
3034 if (!HTTP_ResolveName(lpwhr))
3035 return FALSE;
3037 NETCON_close(&lpwhr->netConnection);
3039 if (!NETCON_init(&lpwhr->netConnection,lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3040 return FALSE;
3042 else
3043 TRACE("Redirect through proxy\n");
3046 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3047 lpwhr->lpszPath=NULL;
3048 if (*path)
3050 DWORD needed = 0;
3051 HRESULT rc;
3053 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3054 if (rc != E_POINTER)
3055 needed = strlenW(path)+1;
3056 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3057 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3058 URL_ESCAPE_SPACES_ONLY);
3059 if (rc)
3061 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3062 strcpyW(lpwhr->lpszPath,path);
3066 /* Remove custom content-type/length headers on redirects. */
3067 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentType, 0, TRUE);
3068 if (0 <= index)
3069 HTTP_DeleteCustomHeader(lpwhr, index);
3070 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentLength, 0, TRUE);
3071 if (0 <= index)
3072 HTTP_DeleteCustomHeader(lpwhr, index);
3074 return TRUE;
3077 /***********************************************************************
3078 * HTTP_build_req (internal)
3080 * concatenate all the strings in the request together
3082 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3084 LPCWSTR *t;
3085 LPWSTR str;
3087 for( t = list; *t ; t++ )
3088 len += strlenW( *t );
3089 len++;
3091 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3092 *str = 0;
3094 for( t = list; *t ; t++ )
3095 strcatW( str, *t );
3097 return str;
3100 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3102 LPWSTR lpszPath;
3103 LPWSTR requestString;
3104 INT len;
3105 INT cnt;
3106 INT responseLen;
3107 char *ascii_req;
3108 BOOL ret;
3109 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3110 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3111 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3113 TRACE("\n");
3115 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3116 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3117 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3118 HeapFree( GetProcessHeap(), 0, lpszPath );
3120 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3121 NULL, 0, NULL, NULL );
3122 len--; /* the nul terminator isn't needed */
3123 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3124 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3125 ascii_req, len, NULL, NULL );
3126 HeapFree( GetProcessHeap(), 0, requestString );
3128 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3130 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3131 HeapFree( GetProcessHeap(), 0, ascii_req );
3132 if (!ret || cnt < 0)
3133 return FALSE;
3135 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3136 if (!responseLen)
3137 return FALSE;
3139 return TRUE;
3142 /***********************************************************************
3143 * HTTP_HttpSendRequestW (internal)
3145 * Sends the specified request to the HTTP server
3147 * RETURNS
3148 * TRUE on success
3149 * FALSE on failure
3152 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3153 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3154 DWORD dwContentLength, BOOL bEndRequest)
3156 INT cnt;
3157 BOOL bSuccess = FALSE;
3158 LPWSTR requestString = NULL;
3159 INT responseLen;
3160 BOOL loop_next;
3161 INTERNET_ASYNC_RESULT iar;
3162 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3163 static const WCHAR szContentLength[] =
3164 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3165 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3167 TRACE("--> %p\n", lpwhr);
3169 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3171 /* if the verb is NULL default to GET */
3172 if (!lpwhr->lpszVerb)
3173 lpwhr->lpszVerb = WININET_strdupW(szGET);
3175 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
3177 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3178 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3180 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3182 WCHAR *agent_header;
3183 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3184 int len;
3186 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3187 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3188 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3190 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3191 HeapFree(GetProcessHeap(), 0, agent_header);
3193 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3195 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3196 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3201 DWORD len;
3202 char *ascii_req;
3204 loop_next = FALSE;
3206 /* like native, just in case the caller forgot to call InternetReadFile
3207 * for all the data */
3208 HTTP_DrainContent(lpwhr);
3209 lpwhr->dwContentRead = 0;
3211 if (TRACE_ON(wininet))
3213 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3214 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3217 HTTP_FixURL(lpwhr);
3218 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3220 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3222 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3223 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3225 /* add the headers the caller supplied */
3226 if( lpszHeaders && dwHeaderLength )
3228 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3229 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3232 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3234 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3235 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3236 HeapFree(GetProcessHeap(), 0, url);
3238 else
3239 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3242 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3244 /* Send the request and store the results */
3245 if (!HTTP_OpenConnection(lpwhr))
3246 goto lend;
3248 /* send the request as ASCII, tack on the optional data */
3249 if( !lpOptional )
3250 dwOptionalLength = 0;
3251 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3252 NULL, 0, NULL, NULL );
3253 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3254 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3255 ascii_req, len, NULL, NULL );
3256 if( lpOptional )
3257 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3258 len = (len + dwOptionalLength - 1);
3259 ascii_req[len] = 0;
3260 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3262 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3263 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3265 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3266 HeapFree( GetProcessHeap(), 0, ascii_req );
3268 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3269 INTERNET_STATUS_REQUEST_SENT,
3270 &len, sizeof(DWORD));
3272 if (bEndRequest)
3274 DWORD dwBufferSize;
3275 DWORD dwStatusCode;
3276 WCHAR encoding[20];
3277 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
3279 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3280 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3282 if (cnt < 0)
3283 goto lend;
3285 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3286 if (responseLen)
3287 bSuccess = TRUE;
3289 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3290 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3291 sizeof(DWORD));
3293 HTTP_ProcessCookies(lpwhr);
3295 dwBufferSize = sizeof(lpwhr->dwContentLength);
3296 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
3297 &lpwhr->dwContentLength,&dwBufferSize,NULL))
3298 lpwhr->dwContentLength = -1;
3300 if (lpwhr->dwContentLength == 0)
3301 HTTP_FinishedReading(lpwhr);
3303 /* Correct the case where both a Content-Length and Transfer-encoding = chunked are set */
3305 dwBufferSize = sizeof(encoding);
3306 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &dwBufferSize, NULL) &&
3307 !strcmpiW(encoding, szChunked))
3309 lpwhr->dwContentLength = -1;
3312 dwBufferSize = sizeof(dwStatusCode);
3313 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3314 &dwStatusCode,&dwBufferSize,NULL))
3315 dwStatusCode = 0;
3317 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3319 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
3320 dwBufferSize=sizeof(szNewLocation);
3321 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3322 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3324 HTTP_DrainContent(lpwhr);
3325 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3326 INTERNET_STATUS_REDIRECT, szNewLocation,
3327 dwBufferSize);
3328 bSuccess = HTTP_HandleRedirect(lpwhr, szNewLocation);
3329 if (bSuccess)
3331 HeapFree(GetProcessHeap(), 0, requestString);
3332 loop_next = TRUE;
3336 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3338 WCHAR szAuthValue[2048];
3339 dwBufferSize=2048;
3340 if (dwStatusCode == HTTP_STATUS_DENIED)
3342 DWORD dwIndex = 0;
3343 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3345 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3346 &lpwhr->pAuthInfo,
3347 lpwhr->lpHttpSession->lpszUserName,
3348 lpwhr->lpHttpSession->lpszPassword))
3350 loop_next = TRUE;
3351 break;
3355 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3357 DWORD dwIndex = 0;
3358 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3360 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3361 &lpwhr->pProxyAuthInfo,
3362 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3363 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3365 loop_next = TRUE;
3366 break;
3372 else
3373 bSuccess = TRUE;
3375 while (loop_next);
3377 /* FIXME: Better check, when we have to create the cache file */
3378 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3379 WCHAR url[INTERNET_MAX_URL_LENGTH];
3380 WCHAR cacheFileName[MAX_PATH+1];
3381 BOOL b;
3383 b = HTTP_GetRequestURL(lpwhr, url);
3384 if(!b) {
3385 WARN("Could not get URL\n");
3386 goto lend;
3389 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3390 if(b) {
3391 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3392 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3393 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3394 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3395 WARN("Could not create file: %u\n", GetLastError());
3396 lpwhr->hCacheFile = NULL;
3398 }else {
3399 WARN("Could not create cache entry: %08x\n", GetLastError());
3403 lend:
3405 HeapFree(GetProcessHeap(), 0, requestString);
3407 /* TODO: send notification for P3P header */
3409 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3410 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
3412 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3413 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3414 sizeof(INTERNET_ASYNC_RESULT));
3416 TRACE("<--\n");
3417 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3418 return bSuccess;
3421 /***********************************************************************
3422 * HTTPSESSION_Destroy (internal)
3424 * Deallocate session handle
3427 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3429 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3431 TRACE("%p\n", lpwhs);
3433 WININET_Release(&lpwhs->lpAppInfo->hdr);
3435 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3436 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3437 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3438 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3439 HeapFree(GetProcessHeap(), 0, lpwhs);
3442 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3444 switch(option) {
3445 case INTERNET_OPTION_HANDLE_TYPE:
3446 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3448 if (*size < sizeof(ULONG))
3449 return ERROR_INSUFFICIENT_BUFFER;
3451 *size = sizeof(DWORD);
3452 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3453 return ERROR_SUCCESS;
3456 FIXME("Not implemented option %d\n", option);
3457 return ERROR_INTERNET_INVALID_OPTION;
3460 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3461 HTTPSESSION_Destroy,
3462 NULL,
3463 HTTPSESSION_QueryOption,
3464 NULL,
3465 NULL,
3466 NULL,
3467 NULL,
3468 NULL,
3469 NULL
3473 /***********************************************************************
3474 * HTTP_Connect (internal)
3476 * Create http session handle
3478 * RETURNS
3479 * HINTERNET a session handle on success
3480 * NULL on failure
3483 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3484 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3485 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3486 DWORD dwInternalFlags)
3488 LPWININETHTTPSESSIONW lpwhs = NULL;
3489 HINTERNET handle = NULL;
3491 TRACE("-->\n");
3493 if (!lpszServerName || !lpszServerName[0])
3495 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3496 goto lerror;
3499 assert( hIC->hdr.htype == WH_HINIT );
3501 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3502 if (NULL == lpwhs)
3504 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3505 goto lerror;
3509 * According to my tests. The name is not resolved until a request is sent
3512 lpwhs->hdr.htype = WH_HHTTPSESSION;
3513 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3514 lpwhs->hdr.dwFlags = dwFlags;
3515 lpwhs->hdr.dwContext = dwContext;
3516 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3517 lpwhs->hdr.refs = 1;
3518 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3520 WININET_AddRef( &hIC->hdr );
3521 lpwhs->lpAppInfo = hIC;
3522 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3524 handle = WININET_AllocHandle( &lpwhs->hdr );
3525 if (NULL == handle)
3527 ERR("Failed to alloc handle\n");
3528 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3529 goto lerror;
3532 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3533 if(strchrW(hIC->lpszProxy, ' '))
3534 FIXME("Several proxies not implemented.\n");
3535 if(hIC->lpszProxyBypass)
3536 FIXME("Proxy bypass is ignored.\n");
3538 if (lpszServerName && lpszServerName[0])
3540 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3541 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3543 if (lpszUserName && lpszUserName[0])
3544 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3545 if (lpszPassword && lpszPassword[0])
3546 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3547 lpwhs->nServerPort = nServerPort;
3548 lpwhs->nHostPort = nServerPort;
3550 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3551 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3553 INTERNET_SendCallback(&hIC->hdr, dwContext,
3554 INTERNET_STATUS_HANDLE_CREATED, &handle,
3555 sizeof(handle));
3558 lerror:
3559 if( lpwhs )
3560 WININET_Release( &lpwhs->hdr );
3563 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3564 * windows
3567 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3568 return handle;
3572 /***********************************************************************
3573 * HTTP_OpenConnection (internal)
3575 * Connect to a web server
3577 * RETURNS
3579 * TRUE on success
3580 * FALSE on failure
3582 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3584 BOOL bSuccess = FALSE;
3585 LPWININETHTTPSESSIONW lpwhs;
3586 LPWININETAPPINFOW hIC = NULL;
3587 char szaddr[32];
3589 TRACE("-->\n");
3592 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
3594 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3595 goto lend;
3598 if (NETCON_connected(&lpwhr->netConnection))
3600 bSuccess = TRUE;
3601 goto lend;
3604 lpwhs = lpwhr->lpHttpSession;
3606 hIC = lpwhs->lpAppInfo;
3607 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3608 szaddr, sizeof(szaddr));
3609 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3610 INTERNET_STATUS_CONNECTING_TO_SERVER,
3611 szaddr,
3612 strlen(szaddr)+1);
3614 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3615 SOCK_STREAM, 0))
3617 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3618 goto lend;
3621 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3622 sizeof(lpwhs->socketAddress)))
3623 goto lend;
3625 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3627 /* Note: we differ from Microsoft's WinINet here. they seem to have
3628 * a bug that causes no status callbacks to be sent when starting
3629 * a tunnel to a proxy server using the CONNECT verb. i believe our
3630 * behaviour to be more correct and to not cause any incompatibilities
3631 * because using a secure connection through a proxy server is a rare
3632 * case that would be hard for anyone to depend on */
3633 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3634 goto lend;
3636 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3638 WARN("Couldn't connect securely to host\n");
3639 goto lend;
3643 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3644 INTERNET_STATUS_CONNECTED_TO_SERVER,
3645 szaddr, strlen(szaddr)+1);
3647 bSuccess = TRUE;
3649 lend:
3650 TRACE("%d <--\n", bSuccess);
3651 return bSuccess;
3655 /***********************************************************************
3656 * HTTP_clear_response_headers (internal)
3658 * clear out any old response headers
3660 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3662 DWORD i;
3664 for( i=0; i<lpwhr->nCustHeaders; i++)
3666 if( !lpwhr->pCustHeaders[i].lpszField )
3667 continue;
3668 if( !lpwhr->pCustHeaders[i].lpszValue )
3669 continue;
3670 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3671 continue;
3672 HTTP_DeleteCustomHeader( lpwhr, i );
3673 i--;
3677 /***********************************************************************
3678 * HTTP_GetResponseHeaders (internal)
3680 * Read server response
3682 * RETURNS
3684 * TRUE on success
3685 * FALSE on error
3687 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3689 INT cbreaks = 0;
3690 WCHAR buffer[MAX_REPLY_LEN];
3691 DWORD buflen = MAX_REPLY_LEN;
3692 BOOL bSuccess = FALSE;
3693 INT rc = 0;
3694 static const WCHAR szCrLf[] = {'\r','\n',0};
3695 static const WCHAR szHundred[] = {'1','0','0',0};
3696 char bufferA[MAX_REPLY_LEN];
3697 LPWSTR status_code, status_text;
3698 DWORD cchMaxRawHeaders = 1024;
3699 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3700 DWORD cchRawHeaders = 0;
3702 TRACE("-->\n");
3704 /* clear old response headers (eg. from a redirect response) */
3705 if (clear) HTTP_clear_response_headers( lpwhr );
3707 if (!NETCON_connected(&lpwhr->netConnection))
3708 goto lend;
3710 do {
3712 * HACK peek at the buffer
3714 buflen = MAX_REPLY_LEN;
3715 NETCON_recv(&lpwhr->netConnection, buffer, buflen, MSG_PEEK, &rc);
3718 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3720 memset(buffer, 0, MAX_REPLY_LEN);
3721 if (!NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3722 goto lend;
3723 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3725 /* split the version from the status code */
3726 status_code = strchrW( buffer, ' ' );
3727 if( !status_code )
3728 goto lend;
3729 *status_code++=0;
3731 /* split the status code from the status text */
3732 status_text = strchrW( status_code, ' ' );
3733 if( !status_text )
3734 goto lend;
3735 *status_text++=0;
3737 TRACE("version [%s] status code [%s] status text [%s]\n",
3738 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3740 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3742 /* Add status code */
3743 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3744 HTTP_ADDHDR_FLAG_REPLACE);
3746 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3747 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3749 lpwhr->lpszVersion= WININET_strdupW(buffer);
3750 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3752 /* Restore the spaces */
3753 *(status_code-1) = ' ';
3754 *(status_text-1) = ' ';
3756 /* regenerate raw headers */
3757 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3759 cchMaxRawHeaders *= 2;
3760 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3762 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3763 cchRawHeaders += (buflen-1);
3764 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3765 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3766 lpszRawHeaders[cchRawHeaders] = '\0';
3768 /* Parse each response line */
3771 buflen = MAX_REPLY_LEN;
3772 if (NETCON_getNextLine(&lpwhr->netConnection, bufferA, &buflen))
3774 LPWSTR * pFieldAndValue;
3776 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
3777 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3779 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
3781 cchMaxRawHeaders *= 2;
3782 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3784 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
3785 cchRawHeaders += (buflen-1);
3786 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
3787 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
3788 lpszRawHeaders[cchRawHeaders] = '\0';
3790 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
3791 if (!pFieldAndValue)
3792 break;
3794 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
3795 HTTP_ADDREQ_FLAG_ADD );
3797 HTTP_FreeTokens(pFieldAndValue);
3799 else
3801 cbreaks++;
3802 if (cbreaks >= 2)
3803 break;
3805 }while(1);
3807 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
3808 lpwhr->lpszRawHeaders = lpszRawHeaders;
3809 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
3810 bSuccess = TRUE;
3812 lend:
3814 TRACE("<--\n");
3815 if (bSuccess)
3816 return rc;
3817 else
3818 return 0;
3822 static void strip_spaces(LPWSTR start)
3824 LPWSTR str = start;
3825 LPWSTR end;
3827 while (*str == ' ' && *str != '\0')
3828 str++;
3830 if (str != start)
3831 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
3833 end = start + strlenW(start) - 1;
3834 while (end >= start && *end == ' ')
3836 *end = '\0';
3837 end--;
3842 /***********************************************************************
3843 * HTTP_InterpretHttpHeader (internal)
3845 * Parse server response
3847 * RETURNS
3849 * Pointer to array of field, value, NULL on success.
3850 * NULL on error.
3852 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
3854 LPWSTR * pTokenPair;
3855 LPWSTR pszColon;
3856 INT len;
3858 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
3860 pszColon = strchrW(buffer, ':');
3861 /* must have two tokens */
3862 if (!pszColon)
3864 HTTP_FreeTokens(pTokenPair);
3865 if (buffer[0])
3866 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
3867 return NULL;
3870 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
3871 if (!pTokenPair[0])
3873 HTTP_FreeTokens(pTokenPair);
3874 return NULL;
3876 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
3877 pTokenPair[0][pszColon - buffer] = '\0';
3879 /* skip colon */
3880 pszColon++;
3881 len = strlenW(pszColon);
3882 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
3883 if (!pTokenPair[1])
3885 HTTP_FreeTokens(pTokenPair);
3886 return NULL;
3888 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
3890 strip_spaces(pTokenPair[0]);
3891 strip_spaces(pTokenPair[1]);
3893 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
3894 return pTokenPair;
3897 /***********************************************************************
3898 * HTTP_ProcessHeader (internal)
3900 * Stuff header into header tables according to <dwModifier>
3904 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3906 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
3908 LPHTTPHEADERW lphttpHdr = NULL;
3909 BOOL bSuccess = FALSE;
3910 INT index = -1;
3911 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
3913 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
3915 /* REPLACE wins out over ADD */
3916 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3917 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
3919 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
3920 index = -1;
3921 else
3922 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
3924 if (index >= 0)
3926 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
3928 return FALSE;
3930 lphttpHdr = &lpwhr->pCustHeaders[index];
3932 else if (value)
3934 HTTPHEADERW hdr;
3936 hdr.lpszField = (LPWSTR)field;
3937 hdr.lpszValue = (LPWSTR)value;
3938 hdr.wFlags = hdr.wCount = 0;
3940 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3941 hdr.wFlags |= HDR_ISREQUEST;
3943 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3945 /* no value to delete */
3946 else return TRUE;
3948 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3949 lphttpHdr->wFlags |= HDR_ISREQUEST;
3950 else
3951 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
3953 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
3955 HTTP_DeleteCustomHeader( lpwhr, index );
3957 if (value)
3959 HTTPHEADERW hdr;
3961 hdr.lpszField = (LPWSTR)field;
3962 hdr.lpszValue = (LPWSTR)value;
3963 hdr.wFlags = hdr.wCount = 0;
3965 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
3966 hdr.wFlags |= HDR_ISREQUEST;
3968 return HTTP_InsertCustomHeader(lpwhr, &hdr);
3971 return TRUE;
3973 else if (dwModifier & COALESCEFLAGS)
3975 LPWSTR lpsztmp;
3976 WCHAR ch = 0;
3977 INT len = 0;
3978 INT origlen = strlenW(lphttpHdr->lpszValue);
3979 INT valuelen = strlenW(value);
3981 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
3983 ch = ',';
3984 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3986 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
3988 ch = ';';
3989 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
3992 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
3994 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
3995 if (lpsztmp)
3997 lphttpHdr->lpszValue = lpsztmp;
3998 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
3999 if (ch > 0)
4001 lphttpHdr->lpszValue[origlen] = ch;
4002 origlen++;
4003 lphttpHdr->lpszValue[origlen] = ' ';
4004 origlen++;
4007 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4008 lphttpHdr->lpszValue[len] = '\0';
4009 bSuccess = TRUE;
4011 else
4013 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4014 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4017 TRACE("<-- %d\n",bSuccess);
4018 return bSuccess;
4022 /***********************************************************************
4023 * HTTP_FinishedReading (internal)
4025 * Called when all content from server has been read by client.
4028 BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4030 WCHAR szVersion[10];
4031 DWORD dwBufferSize = sizeof(szVersion);
4033 TRACE("\n");
4035 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4036 * the connection is keep-alive by default */
4037 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4038 &dwBufferSize, NULL) ||
4039 strcmpiW(szVersion, g_szHttp1_1))
4041 WCHAR szConnectionResponse[20];
4042 dwBufferSize = sizeof(szConnectionResponse);
4043 if ((!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4044 strcmpiW(szConnectionResponse, szKeepAlive)) &&
4045 (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4046 strcmpiW(szConnectionResponse, szKeepAlive)))
4048 HTTPREQ_CloseConnection(&lpwhr->hdr);
4052 /* FIXME: store data in the URL cache here */
4054 return TRUE;
4058 /***********************************************************************
4059 * HTTP_GetCustomHeaderIndex (internal)
4061 * Return index of custom header from header array
4064 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4065 int requested_index, BOOL request_only)
4067 DWORD index;
4069 TRACE("%s\n", debugstr_w(lpszField));
4071 for (index = 0; index < lpwhr->nCustHeaders; index++)
4073 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4074 continue;
4076 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4077 continue;
4079 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4080 continue;
4082 if (requested_index == 0)
4083 break;
4084 requested_index --;
4087 if (index >= lpwhr->nCustHeaders)
4088 index = -1;
4090 TRACE("Return: %d\n", index);
4091 return index;
4095 /***********************************************************************
4096 * HTTP_InsertCustomHeader (internal)
4098 * Insert header into array
4101 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4103 INT count;
4104 LPHTTPHEADERW lph = NULL;
4105 BOOL r = FALSE;
4107 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4108 count = lpwhr->nCustHeaders + 1;
4109 if (count > 1)
4110 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4111 else
4112 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4114 if (NULL != lph)
4116 lpwhr->pCustHeaders = lph;
4117 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4118 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4119 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4120 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4121 lpwhr->nCustHeaders++;
4122 r = TRUE;
4124 else
4126 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4129 return r;
4133 /***********************************************************************
4134 * HTTP_DeleteCustomHeader (internal)
4136 * Delete header from array
4137 * If this function is called, the indexs may change.
4139 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4141 if( lpwhr->nCustHeaders <= 0 )
4142 return FALSE;
4143 if( index >= lpwhr->nCustHeaders )
4144 return FALSE;
4145 lpwhr->nCustHeaders--;
4147 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4148 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4150 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4151 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4152 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4154 return TRUE;
4158 /***********************************************************************
4159 * HTTP_VerifyValidHeader (internal)
4161 * Verify the given header is not invalid for the given http request
4164 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4166 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4167 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4168 return FALSE;
4170 return TRUE;
4173 /***********************************************************************
4174 * IsHostInProxyBypassList (@)
4176 * Undocumented
4179 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4181 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4182 return FALSE;