f0ad6beddc1eb0df59cc8579921e9af934983949
[reactos.git] / reactos / dll / win32 / wininet / http.c
1 /*
2 * Wininet - Http Implementation
3 *
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
10 *
11 * Ulrich Czekalla
12 * David Hammerton
13 *
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.
18 *
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.
23 *
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
27 */
28
29 #include "config.h"
30 #include "wine/port.h"
31
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>
47
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"
59
60 #include "internet.h"
61 #include "wine/debug.h"
62 #include "wine/unicode.h"
63
64 #include "inet_ntop.c"
65
66 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
67
68 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
69 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
70 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
71 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
72 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
73 static const WCHAR szHost[] = { 'H','o','s','t',0 };
74 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
75 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
76 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
77 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
78 static const WCHAR szGET[] = { 'G','E','T', 0 };
79
80 #define MAXHOSTNAME 100
81 #define MAX_FIELD_VALUE_LEN 256
82 #define MAX_FIELD_LEN 256
83
84 #define HTTP_REFERER g_szReferer
85 #define HTTP_ACCEPT g_szAccept
86 #define HTTP_USERAGENT g_szUserAgent
87
88 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
89 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
90 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
91 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
92 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
93 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
94 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
95
96 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
97
98 struct HttpAuthInfo
99 {
100 LPWSTR scheme;
101 CredHandle cred;
102 CtxtHandle ctx;
103 TimeStamp exp;
104 ULONG attr;
105 ULONG max_token;
106 void *auth_data;
107 unsigned int auth_data_len;
108 BOOL finished; /* finished authenticating */
109 };
110
111 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
112 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
113 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
114 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
115 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
116 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
117 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
118 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
119 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD
120 dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD
121 lpdwIndex);
122 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
123 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
124 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
125 static void HTTP_DrainContent(WININETHTTPREQW *req);
126
127 LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
128 {
129 int HeaderIndex = 0;
130 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
131 if (HeaderIndex == -1)
132 return NULL;
133 else
134 return &req->pCustHeaders[HeaderIndex];
135 }
136
137 /***********************************************************************
138 * HTTP_Tokenize (internal)
139 *
140 * Tokenize a string, allocating memory for the tokens.
141 */
142 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
143 {
144 LPWSTR * token_array;
145 int tokens = 0;
146 int i;
147 LPCWSTR next_token;
148
149 /* empty string has no tokens */
150 if (*string)
151 tokens++;
152 /* count tokens */
153 for (i = 0; string[i]; i++)
154 if (!strncmpW(string+i, token_string, strlenW(token_string)))
155 {
156 DWORD j;
157 tokens++;
158 /* we want to skip over separators, but not the null terminator */
159 for (j = 0; j < strlenW(token_string) - 1; j++)
160 if (!string[i+j])
161 break;
162 i += j;
163 }
164
165 /* add 1 for terminating NULL */
166 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
167 token_array[tokens] = NULL;
168 if (!tokens)
169 return token_array;
170 for (i = 0; i < tokens; i++)
171 {
172 int len;
173 next_token = strstrW(string, token_string);
174 if (!next_token) next_token = string+strlenW(string);
175 len = next_token - string;
176 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
177 memcpy(token_array[i], string, len*sizeof(WCHAR));
178 token_array[i][len] = '\0';
179 string = next_token+strlenW(token_string);
180 }
181 return token_array;
182 }
183
184 /***********************************************************************
185 * HTTP_FreeTokens (internal)
186 *
187 * Frees memory returned from HTTP_Tokenize.
188 */
189 static void HTTP_FreeTokens(LPWSTR * token_array)
190 {
191 int i;
192 for (i = 0; token_array[i]; i++)
193 HeapFree(GetProcessHeap(), 0, token_array[i]);
194 HeapFree(GetProcessHeap(), 0, token_array);
195 }
196
197 /* **********************************************************************
198 *
199 * Helper functions for the HttpSendRequest(Ex) functions
200 *
201 */
202 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
203 {
204 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
205 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
206
207 TRACE("%p\n", lpwhr);
208
209 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
210 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
211 req->dwContentLength, req->bEndRequest);
212
213 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
214 }
215
216 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
217 {
218 static const WCHAR szSlash[] = { '/',0 };
219 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
220
221 /* If we don't have a path we set it to root */
222 if (NULL == lpwhr->lpszPath)
223 lpwhr->lpszPath = WININET_strdupW(szSlash);
224 else /* remove \r and \n*/
225 {
226 int nLen = strlenW(lpwhr->lpszPath);
227 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
228 {
229 nLen--;
230 lpwhr->lpszPath[nLen]='\0';
231 }
232 /* Replace '\' with '/' */
233 while (nLen>0) {
234 nLen--;
235 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
236 }
237 }
238
239 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
240 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
241 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
242 {
243 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
244 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
245 *fixurl = '/';
246 strcpyW(fixurl + 1, lpwhr->lpszPath);
247 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
248 lpwhr->lpszPath = fixurl;
249 }
250 }
251
252 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
253 {
254 LPWSTR requestString;
255 DWORD len, n;
256 LPCWSTR *req;
257 UINT i;
258 LPWSTR p;
259
260 static const WCHAR szSpace[] = { ' ',0 };
261 static const WCHAR szcrlf[] = {'\r','\n', 0};
262 static const WCHAR szColon[] = { ':',' ',0 };
263 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
264
265 /* allocate space for an array of all the string pointers to be added */
266 len = (lpwhr->nCustHeaders)*4 + 10;
267 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
268
269 /* add the verb, path and HTTP version string */
270 n = 0;
271 req[n++] = verb;
272 req[n++] = szSpace;
273 req[n++] = path;
274 req[n++] = szSpace;
275 req[n++] = version;
276
277 /* Append custom request headers */
278 for (i = 0; i < lpwhr->nCustHeaders; i++)
279 {
280 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
281 {
282 req[n++] = szcrlf;
283 req[n++] = lpwhr->pCustHeaders[i].lpszField;
284 req[n++] = szColon;
285 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
286
287 TRACE("Adding custom header %s (%s)\n",
288 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
289 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
290 }
291 }
292
293 if( n >= len )
294 ERR("oops. buffer overrun\n");
295
296 req[n] = NULL;
297 requestString = HTTP_build_req( req, 4 );
298 HeapFree( GetProcessHeap(), 0, req );
299
300 /*
301 * Set (header) termination string for request
302 * Make sure there's exactly two new lines at the end of the request
303 */
304 p = &requestString[strlenW(requestString)-1];
305 while ( (*p == '\n') || (*p == '\r') )
306 p--;
307 strcpyW( p+1, sztwocrlf );
308
309 return requestString;
310 }
311
312 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
313 {
314 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
315 int HeaderIndex;
316 LPHTTPHEADERW setCookieHeader;
317
318 HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, 0, FALSE);
319 if (HeaderIndex == -1)
320 return;
321 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
322
323 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
324 {
325 int nPosStart = 0, nPosEnd = 0, len;
326 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','/',0};
327
328 while (setCookieHeader->lpszValue[nPosEnd] != '\0')
329 {
330 LPWSTR buf_cookie, cookie_name, cookie_data;
331 LPWSTR buf_url;
332 LPWSTR domain = NULL;
333 LPHTTPHEADERW Host;
334
335 int nEqualPos = 0;
336 while (setCookieHeader->lpszValue[nPosEnd] != ';' && setCookieHeader->lpszValue[nPosEnd] != ',' &&
337 setCookieHeader->lpszValue[nPosEnd] != '\0')
338 {
339 nPosEnd++;
340 }
341 if (setCookieHeader->lpszValue[nPosEnd] == ';')
342 {
343 /* fixme: not case sensitive, strcasestr is gnu only */
344 int nDomainPosEnd = 0;
345 int nDomainPosStart = 0, nDomainLength = 0;
346 static const WCHAR szDomain[] = {'d','o','m','a','i','n','=',0};
347 LPWSTR lpszDomain = strstrW(&setCookieHeader->lpszValue[nPosEnd], szDomain);
348 if (lpszDomain)
349 { /* they have specified their own domain, lets use it */
350 while (lpszDomain[nDomainPosEnd] != ';' && lpszDomain[nDomainPosEnd] != ',' &&
351 lpszDomain[nDomainPosEnd] != '\0')
352 {
353 nDomainPosEnd++;
354 }
355 nDomainPosStart = strlenW(szDomain);
356 nDomainLength = (nDomainPosEnd - nDomainPosStart) + 1;
357 domain = HeapAlloc(GetProcessHeap(), 0, (nDomainLength + 1)*sizeof(WCHAR));
358 lstrcpynW(domain, &lpszDomain[nDomainPosStart], nDomainLength + 1);
359 }
360 }
361 if (setCookieHeader->lpszValue[nPosEnd] == '\0') break;
362 buf_cookie = HeapAlloc(GetProcessHeap(), 0, ((nPosEnd - nPosStart) + 1)*sizeof(WCHAR));
363 lstrcpynW(buf_cookie, &setCookieHeader->lpszValue[nPosStart], (nPosEnd - nPosStart) + 1);
364 TRACE("%s\n", debugstr_w(buf_cookie));
365 while (buf_cookie[nEqualPos] != '=' && buf_cookie[nEqualPos] != '\0')
366 {
367 nEqualPos++;
368 }
369 if (buf_cookie[nEqualPos] == '\0' || buf_cookie[nEqualPos + 1] == '\0')
370 {
371 HeapFree(GetProcessHeap(), 0, buf_cookie);
372 break;
373 }
374
375 cookie_name = HeapAlloc(GetProcessHeap(), 0, (nEqualPos + 1)*sizeof(WCHAR));
376 lstrcpynW(cookie_name, buf_cookie, nEqualPos + 1);
377 cookie_data = &buf_cookie[nEqualPos + 1];
378
379 Host = HTTP_GetHeader(lpwhr,szHost);
380 len = lstrlenW((domain ? domain : (Host?Host->lpszValue:NULL))) +
381 strlenW(lpwhr->lpszPath) + 9;
382 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
383 sprintfW(buf_url, szFmt, (domain ? domain : (Host?Host->lpszValue:NULL))); /* FIXME PATH!!! */
384 InternetSetCookieW(buf_url, cookie_name, cookie_data);
385
386 HeapFree(GetProcessHeap(), 0, buf_url);
387 HeapFree(GetProcessHeap(), 0, buf_cookie);
388 HeapFree(GetProcessHeap(), 0, cookie_name);
389 HeapFree(GetProcessHeap(), 0, domain);
390 nPosStart = nPosEnd;
391 }
392 }
393 }
394
395 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
396 {
397 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
398 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
399 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
400 }
401
402 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
403 struct HttpAuthInfo **ppAuthInfo,
404 LPWSTR domain_and_username, LPWSTR password )
405 {
406 SECURITY_STATUS sec_status;
407 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
408 BOOL first = FALSE;
409
410 TRACE("%s\n", debugstr_w(pszAuthValue));
411
412 if (!pAuthInfo)
413 {
414 TimeStamp exp;
415
416 first = TRUE;
417 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
418 if (!pAuthInfo)
419 return FALSE;
420
421 SecInvalidateHandle(&pAuthInfo->cred);
422 SecInvalidateHandle(&pAuthInfo->ctx);
423 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
424 pAuthInfo->attr = 0;
425 pAuthInfo->auth_data = NULL;
426 pAuthInfo->auth_data_len = 0;
427 pAuthInfo->finished = FALSE;
428
429 if (is_basic_auth_value(pszAuthValue))
430 {
431 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
432 pAuthInfo->scheme = WININET_strdupW(szBasic);
433 if (!pAuthInfo->scheme)
434 {
435 HeapFree(GetProcessHeap(), 0, pAuthInfo);
436 return FALSE;
437 }
438 }
439 else
440 {
441 PVOID pAuthData;
442 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
443
444 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
445 if (!pAuthInfo->scheme)
446 {
447 HeapFree(GetProcessHeap(), 0, pAuthInfo);
448 return FALSE;
449 }
450
451 if (domain_and_username)
452 {
453 WCHAR *user = strchrW(domain_and_username, '\\');
454 WCHAR *domain = domain_and_username;
455
456 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
457
458 pAuthData = &nt_auth_identity;
459
460 if (user) user++;
461 else
462 {
463 user = domain_and_username;
464 domain = NULL;
465 }
466
467 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
468 nt_auth_identity.User = user;
469 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
470 nt_auth_identity.Domain = domain;
471 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
472 nt_auth_identity.Password = password;
473 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
474 }
475 else
476 /* use default credentials */
477 pAuthData = NULL;
478
479 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
480 SECPKG_CRED_OUTBOUND, NULL,
481 pAuthData, NULL,
482 NULL, &pAuthInfo->cred,
483 &exp);
484 if (sec_status == SEC_E_OK)
485 {
486 PSecPkgInfoW sec_pkg_info;
487 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
488 if (sec_status == SEC_E_OK)
489 {
490 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
491 FreeContextBuffer(sec_pkg_info);
492 }
493 }
494 if (sec_status != SEC_E_OK)
495 {
496 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
497 debugstr_w(pAuthInfo->scheme), sec_status);
498 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
499 HeapFree(GetProcessHeap(), 0, pAuthInfo);
500 return FALSE;
501 }
502 }
503 *ppAuthInfo = pAuthInfo;
504 }
505 else if (pAuthInfo->finished)
506 return FALSE;
507
508 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
509 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
510 {
511 ERR("authentication scheme changed from %s to %s\n",
512 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
513 return FALSE;
514 }
515
516 if (is_basic_auth_value(pszAuthValue))
517 {
518 int userlen;
519 int passlen;
520 char *auth_data;
521
522 TRACE("basic authentication\n");
523
524 /* we don't cache credentials for basic authentication, so we can't
525 * retrieve them if the application didn't pass us any credentials */
526 if (!domain_and_username) return FALSE;
527
528 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
529 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
530
531 /* length includes a nul terminator, which will be re-used for the ':' */
532 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
533 if (!auth_data)
534 return FALSE;
535
536 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
537 auth_data[userlen] = ':';
538 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
539
540 pAuthInfo->auth_data = auth_data;
541 pAuthInfo->auth_data_len = userlen + 1 + passlen;
542 pAuthInfo->finished = TRUE;
543
544 return TRUE;
545 }
546 else
547 {
548 LPCWSTR pszAuthData;
549 SecBufferDesc out_desc, in_desc;
550 SecBuffer out, in;
551 unsigned char *buffer;
552 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
553 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
554
555 in.BufferType = SECBUFFER_TOKEN;
556 in.cbBuffer = 0;
557 in.pvBuffer = NULL;
558
559 in_desc.ulVersion = 0;
560 in_desc.cBuffers = 1;
561 in_desc.pBuffers = &in;
562
563 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
564 if (*pszAuthData == ' ')
565 {
566 pszAuthData++;
567 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
568 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
569 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
570 }
571
572 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
573
574 out.BufferType = SECBUFFER_TOKEN;
575 out.cbBuffer = pAuthInfo->max_token;
576 out.pvBuffer = buffer;
577
578 out_desc.ulVersion = 0;
579 out_desc.cBuffers = 1;
580 out_desc.pBuffers = &out;
581
582 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
583 first ? NULL : &pAuthInfo->ctx,
584 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
585 context_req, 0, SECURITY_NETWORK_DREP,
586 in.pvBuffer ? &in_desc : NULL,
587 0, &pAuthInfo->ctx, &out_desc,
588 &pAuthInfo->attr, &pAuthInfo->exp);
589 if (sec_status == SEC_E_OK)
590 {
591 pAuthInfo->finished = TRUE;
592 pAuthInfo->auth_data = out.pvBuffer;
593 pAuthInfo->auth_data_len = out.cbBuffer;
594 TRACE("sending last auth packet\n");
595 }
596 else if (sec_status == SEC_I_CONTINUE_NEEDED)
597 {
598 pAuthInfo->auth_data = out.pvBuffer;
599 pAuthInfo->auth_data_len = out.cbBuffer;
600 TRACE("sending next auth packet\n");
601 }
602 else
603 {
604 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
605 pAuthInfo->finished = TRUE;
606 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
607 return FALSE;
608 }
609 }
610
611 return TRUE;
612 }
613
614 /***********************************************************************
615 * HTTP_HttpAddRequestHeadersW (internal)
616 */
617 static BOOL WINAPI HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
618 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
619 {
620 LPWSTR lpszStart;
621 LPWSTR lpszEnd;
622 LPWSTR buffer;
623 BOOL bSuccess = FALSE;
624 DWORD len;
625
626 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
627
628 if( dwHeaderLength == ~0U )
629 len = strlenW(lpszHeader);
630 else
631 len = dwHeaderLength;
632 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
633 lstrcpynW( buffer, lpszHeader, len + 1);
634
635 lpszStart = buffer;
636
637 do
638 {
639 LPWSTR * pFieldAndValue;
640
641 lpszEnd = lpszStart;
642
643 while (*lpszEnd != '\0')
644 {
645 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
646 break;
647 lpszEnd++;
648 }
649
650 if (*lpszStart == '\0')
651 break;
652
653 if (*lpszEnd == '\r')
654 {
655 *lpszEnd = '\0';
656 lpszEnd += 2; /* Jump over \r\n */
657 }
658 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
659 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
660 if (pFieldAndValue)
661 {
662 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
663 if (bSuccess)
664 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
665 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
666 HTTP_FreeTokens(pFieldAndValue);
667 }
668
669 lpszStart = lpszEnd;
670 } while (bSuccess);
671
672 HeapFree(GetProcessHeap(), 0, buffer);
673
674 return bSuccess;
675 }
676
677 /***********************************************************************
678 * HttpAddRequestHeadersW (WININET.@)
679 *
680 * Adds one or more HTTP header to the request handler
681 *
682 * NOTE
683 * On Windows if dwHeaderLength includes the trailing '\0', then
684 * HttpAddRequestHeadersW() adds it too. However this results in an
685 * invalid Http header which is rejected by some servers so we probably
686 * don't need to match Windows on that point.
687 *
688 * RETURNS
689 * TRUE on success
690 * FALSE on failure
691 *
692 */
693 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
694 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
695 {
696 BOOL bSuccess = FALSE;
697 LPWININETHTTPREQW lpwhr;
698
699 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
700
701 if (!lpszHeader)
702 return TRUE;
703
704 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
705 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
706 {
707 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
708 goto lend;
709 }
710 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
711 lend:
712 if( lpwhr )
713 WININET_Release( &lpwhr->hdr );
714
715 return bSuccess;
716 }
717
718 /***********************************************************************
719 * HttpAddRequestHeadersA (WININET.@)
720 *
721 * Adds one or more HTTP header to the request handler
722 *
723 * RETURNS
724 * TRUE on success
725 * FALSE on failure
726 *
727 */
728 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
729 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
730 {
731 DWORD len;
732 LPWSTR hdr;
733 BOOL r;
734
735 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
736
737 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
738 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
739 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
740 if( dwHeaderLength != ~0U )
741 dwHeaderLength = len;
742
743 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
744
745 HeapFree( GetProcessHeap(), 0, hdr );
746
747 return r;
748 }
749
750 /***********************************************************************
751 * HttpEndRequestA (WININET.@)
752 *
753 * Ends an HTTP request that was started by HttpSendRequestEx
754 *
755 * RETURNS
756 * TRUE if successful
757 * FALSE on failure
758 *
759 */
760 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
761 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
762 {
763 LPINTERNET_BUFFERSA ptr;
764 LPINTERNET_BUFFERSW lpBuffersOutW,ptrW;
765 BOOL rc = FALSE;
766
767 TRACE("(%p, %p, %08x, %08lx): stub\n", hRequest, lpBuffersOut, dwFlags,
768 dwContext);
769
770 ptr = lpBuffersOut;
771 if (ptr)
772 lpBuffersOutW = (LPINTERNET_BUFFERSW)HeapAlloc(GetProcessHeap(),
773 HEAP_ZERO_MEMORY, sizeof(INTERNET_BUFFERSW));
774 else
775 lpBuffersOutW = NULL;
776
777 ptrW = lpBuffersOutW;
778 while (ptr)
779 {
780 if (ptr->lpvBuffer && ptr->dwBufferLength)
781 ptrW->lpvBuffer = HeapAlloc(GetProcessHeap(),0,ptr->dwBufferLength);
782 ptrW->dwBufferLength = ptr->dwBufferLength;
783 ptrW->dwBufferTotal= ptr->dwBufferTotal;
784
785 if (ptr->Next)
786 ptrW->Next = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
787 sizeof(INTERNET_BUFFERSW));
788
789 ptr = ptr->Next;
790 ptrW = ptrW->Next;
791 }
792
793 rc = HttpEndRequestW(hRequest, lpBuffersOutW, dwFlags, dwContext);
794
795 if (lpBuffersOutW)
796 {
797 ptrW = lpBuffersOutW;
798 while (ptrW)
799 {
800 LPINTERNET_BUFFERSW ptrW2;
801
802 FIXME("Do we need to translate info out of these buffer?\n");
803
804 HeapFree(GetProcessHeap(),0,ptrW->lpvBuffer);
805 ptrW2 = ptrW->Next;
806 HeapFree(GetProcessHeap(),0,ptrW);
807 ptrW = ptrW2;
808 }
809 }
810
811 return rc;
812 }
813
814 /***********************************************************************
815 * HttpEndRequestW (WININET.@)
816 *
817 * Ends an HTTP request that was started by HttpSendRequestEx
818 *
819 * RETURNS
820 * TRUE if successful
821 * FALSE on failure
822 *
823 */
824 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
825 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
826 {
827 BOOL rc = FALSE;
828 LPWININETHTTPREQW lpwhr;
829 INT responseLen;
830 DWORD dwBufferSize;
831
832 TRACE("-->\n");
833 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
834
835 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
836 {
837 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
838 if (lpwhr)
839 WININET_Release( &lpwhr->hdr );
840 return FALSE;
841 }
842
843 lpwhr->hdr.dwFlags |= dwFlags;
844 lpwhr->hdr.dwContext = dwContext;
845
846 /* We appear to do nothing with lpBuffersOut.. is that correct? */
847
848 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
849 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
850
851 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
852 if (responseLen)
853 rc = TRUE;
854
855 SendAsyncCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
856 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
857
858 /* process cookies here. Is this right? */
859 HTTP_ProcessCookies(lpwhr);
860
861 dwBufferSize = sizeof(lpwhr->dwContentLength);
862 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
863 &lpwhr->dwContentLength,&dwBufferSize,NULL))
864 lpwhr->dwContentLength = -1;
865
866 if (lpwhr->dwContentLength == 0)
867 HTTP_FinishedReading(lpwhr);
868
869 if(!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
870 {
871 DWORD dwCode,dwCodeLength=sizeof(DWORD);
872 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,&dwCode,&dwCodeLength,NULL) &&
873 (dwCode==302 || dwCode==301))
874 {
875 WCHAR szNewLocation[INTERNET_MAX_URL_LENGTH];
876 dwBufferSize=sizeof(szNewLocation);
877 if(HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
878 {
879 /* redirects are always GETs */
880 HeapFree(GetProcessHeap(),0,lpwhr->lpszVerb);
881 lpwhr->lpszVerb = WININET_strdupW(szGET);
882 HTTP_DrainContent(lpwhr);
883 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
884 INTERNET_STATUS_REDIRECT, szNewLocation,
885 dwBufferSize);
886 rc = HTTP_HandleRedirect(lpwhr, szNewLocation);
887 if (rc)
888 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
889 }
890 }
891 }
892
893 WININET_Release( &lpwhr->hdr );
894 TRACE("%i <--\n",rc);
895 return rc;
896 }
897
898 /***********************************************************************
899 * HttpOpenRequestW (WININET.@)
900 *
901 * Open a HTTP request handle
902 *
903 * RETURNS
904 * HINTERNET a HTTP request handle on success
905 * NULL on failure
906 *
907 */
908 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
909 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
910 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
911 DWORD dwFlags, DWORD_PTR dwContext)
912 {
913 LPWININETHTTPSESSIONW lpwhs;
914 HINTERNET handle = NULL;
915
916 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
917 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
918 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
919 dwFlags, dwContext);
920 if(lpszAcceptTypes!=NULL)
921 {
922 int i;
923 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
924 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
925 }
926
927 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
928 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
929 {
930 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
931 goto lend;
932 }
933
934 /*
935 * My tests seem to show that the windows version does not
936 * become asynchronous until after this point. And anyhow
937 * if this call was asynchronous then how would you get the
938 * necessary HINTERNET pointer returned by this function.
939 *
940 */
941 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
942 lpszVersion, lpszReferrer, lpszAcceptTypes,
943 dwFlags, dwContext);
944 lend:
945 if( lpwhs )
946 WININET_Release( &lpwhs->hdr );
947 TRACE("returning %p\n", handle);
948 return handle;
949 }
950
951
952 /***********************************************************************
953 * HttpOpenRequestA (WININET.@)
954 *
955 * Open a HTTP request handle
956 *
957 * RETURNS
958 * HINTERNET a HTTP request handle on success
959 * NULL on failure
960 *
961 */
962 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
963 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
964 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
965 DWORD dwFlags, DWORD_PTR dwContext)
966 {
967 LPWSTR szVerb = NULL, szObjectName = NULL;
968 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
969 INT len, acceptTypesCount;
970 HINTERNET rc = FALSE;
971 LPCSTR *types;
972
973 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
974 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
975 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
976 dwFlags, dwContext);
977
978 if (lpszVerb)
979 {
980 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
981 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
982 if ( !szVerb )
983 goto end;
984 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
985 }
986
987 if (lpszObjectName)
988 {
989 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
990 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
991 if ( !szObjectName )
992 goto end;
993 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
994 }
995
996 if (lpszVersion)
997 {
998 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
999 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1000 if ( !szVersion )
1001 goto end;
1002 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
1003 }
1004
1005 if (lpszReferrer)
1006 {
1007 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
1008 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1009 if ( !szReferrer )
1010 goto end;
1011 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1012 }
1013
1014 if (lpszAcceptTypes)
1015 {
1016 acceptTypesCount = 0;
1017 types = lpszAcceptTypes;
1018 while (*types)
1019 {
1020 /* find out how many there are */
1021 if (((ULONG_PTR)*types >> 16) && **types)
1022 {
1023 TRACE("accept type: %s\n", debugstr_a(*types));
1024 acceptTypesCount++;
1025 }
1026 types++;
1027 }
1028 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1029 if (!szAcceptTypes) goto end;
1030
1031 acceptTypesCount = 0;
1032 types = lpszAcceptTypes;
1033 while (*types)
1034 {
1035 if (((ULONG_PTR)*types >> 16) && **types)
1036 {
1037 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1038 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1039 if (!szAcceptTypes[acceptTypesCount]) goto end;
1040
1041 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1042 acceptTypesCount++;
1043 }
1044 types++;
1045 }
1046 szAcceptTypes[acceptTypesCount] = NULL;
1047 }
1048 else szAcceptTypes = 0;
1049
1050 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1051 szVersion, szReferrer,
1052 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1053
1054 end:
1055 if (szAcceptTypes)
1056 {
1057 acceptTypesCount = 0;
1058 while (szAcceptTypes[acceptTypesCount])
1059 {
1060 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1061 acceptTypesCount++;
1062 }
1063 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1064 }
1065 HeapFree(GetProcessHeap(), 0, szReferrer);
1066 HeapFree(GetProcessHeap(), 0, szVersion);
1067 HeapFree(GetProcessHeap(), 0, szObjectName);
1068 HeapFree(GetProcessHeap(), 0, szVerb);
1069
1070 return rc;
1071 }
1072
1073 /***********************************************************************
1074 * HTTP_EncodeBase64
1075 */
1076 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1077 {
1078 UINT n = 0, x;
1079 static const CHAR HTTP_Base64Enc[] =
1080 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1081
1082 while( len > 0 )
1083 {
1084 /* first 6 bits, all from bin[0] */
1085 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1086 x = (bin[0] & 3) << 4;
1087
1088 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1089 if( len == 1 )
1090 {
1091 base64[n++] = HTTP_Base64Enc[x];
1092 base64[n++] = '=';
1093 base64[n++] = '=';
1094 break;
1095 }
1096 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1097 x = ( bin[1] & 0x0f ) << 2;
1098
1099 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1100 if( len == 2 )
1101 {
1102 base64[n++] = HTTP_Base64Enc[x];
1103 base64[n++] = '=';
1104 break;
1105 }
1106 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1107
1108 /* last 6 bits, all from bin [2] */
1109 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1110 bin += 3;
1111 len -= 3;
1112 }
1113 base64[n] = 0;
1114 return n;
1115 }
1116
1117 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1118 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1119 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1120 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1121 static const signed char HTTP_Base64Dec[256] =
1122 {
1123 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1124 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1125 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1126 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1127 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1128 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1129 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1130 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1131 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1132 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1133 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1134 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1135 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1136 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1137 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1138 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1139 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1140 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1141 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1142 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1143 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1144 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1145 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1146 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1147 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1148 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1149 };
1150 #undef CH
1151
1152 /***********************************************************************
1153 * HTTP_DecodeBase64
1154 */
1155 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1156 {
1157 unsigned int n = 0;
1158
1159 while(*base64)
1160 {
1161 signed char in[4];
1162
1163 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1164 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1165 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1166 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1167 {
1168 WARN("invalid base64: %s\n", debugstr_w(base64));
1169 return 0;
1170 }
1171 if (bin)
1172 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1173 n++;
1174
1175 if ((base64[2] == '=') && (base64[3] == '='))
1176 break;
1177 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1178 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1179 {
1180 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1181 return 0;
1182 }
1183 if (bin)
1184 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1185 n++;
1186
1187 if (base64[3] == '=')
1188 break;
1189 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1190 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1191 {
1192 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1193 return 0;
1194 }
1195 if (bin)
1196 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1197 n++;
1198
1199 base64 += 4;
1200 }
1201
1202 return n;
1203 }
1204
1205 /***********************************************************************
1206 * HTTP_InsertAuthorization
1207 *
1208 * Insert or delete the authorization field in the request header.
1209 */
1210 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1211 {
1212 if (pAuthInfo)
1213 {
1214 static const WCHAR wszSpace[] = {' ',0};
1215 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1216 unsigned int len;
1217 WCHAR *authorization = NULL;
1218
1219 if (pAuthInfo->auth_data_len)
1220 {
1221 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1222 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1223 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1224 if (!authorization)
1225 return FALSE;
1226
1227 strcpyW(authorization, pAuthInfo->scheme);
1228 strcatW(authorization, wszSpace);
1229 HTTP_EncodeBase64(pAuthInfo->auth_data,
1230 pAuthInfo->auth_data_len,
1231 authorization+strlenW(authorization));
1232
1233 /* clear the data as it isn't valid now that it has been sent to the
1234 * server, unless it's Basic authentication which doesn't do
1235 * connection tracking */
1236 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1237 {
1238 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1239 pAuthInfo->auth_data = NULL;
1240 pAuthInfo->auth_data_len = 0;
1241 }
1242 }
1243
1244 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1245
1246 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1247
1248 HeapFree(GetProcessHeap(), 0, authorization);
1249 }
1250 return TRUE;
1251 }
1252
1253 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1254 {
1255 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1256 DWORD size;
1257
1258 size = sizeof(new_location);
1259 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1260 {
1261 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1262 strcpyW( url, new_location );
1263 }
1264 else
1265 {
1266 static const WCHAR slash[] = { '/',0 };
1267 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1268 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1269 WININETHTTPSESSIONW *session = req->lpHttpSession;
1270
1271 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1272 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1273
1274 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1275
1276 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1277 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1278 else
1279 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1280 if (req->lpszPath[0] != '/') strcatW( url, slash );
1281 strcatW( url, req->lpszPath );
1282 }
1283 TRACE("url=%s\n", debugstr_w(url));
1284 return url;
1285 }
1286
1287 /***********************************************************************
1288 * HTTP_DealWithProxy
1289 */
1290 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1291 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1292 {
1293 WCHAR buf[MAXHOSTNAME];
1294 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1295 static WCHAR szNul[] = { 0 };
1296 URL_COMPONENTSW UrlComponents;
1297 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1298 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1299
1300 memset( &UrlComponents, 0, sizeof UrlComponents );
1301 UrlComponents.dwStructSize = sizeof UrlComponents;
1302 UrlComponents.lpszHostName = buf;
1303 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1304
1305 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1306 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1307 sprintfW(proxy, szFormat, hIC->lpszProxy);
1308 else
1309 strcpyW(proxy, hIC->lpszProxy);
1310 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1311 return FALSE;
1312 if( UrlComponents.dwHostNameLength == 0 )
1313 return FALSE;
1314
1315 if( !lpwhr->lpszPath )
1316 lpwhr->lpszPath = szNul;
1317
1318 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1319 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1320
1321 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1322 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1323 lpwhs->nServerPort = UrlComponents.nPort;
1324
1325 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1326 return TRUE;
1327 }
1328
1329 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1330 {
1331 char szaddr[32];
1332 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1333
1334 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1335 INTERNET_STATUS_RESOLVING_NAME,
1336 lpwhs->lpszServerName,
1337 strlenW(lpwhs->lpszServerName)+1);
1338
1339 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1340 &lpwhs->socketAddress))
1341 {
1342 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1343 return FALSE;
1344 }
1345
1346 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1347 szaddr, sizeof(szaddr));
1348 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1349 INTERNET_STATUS_NAME_RESOLVED,
1350 szaddr, strlen(szaddr)+1);
1351
1352 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1353 return TRUE;
1354 }
1355
1356
1357 /***********************************************************************
1358 * HTTPREQ_Destroy (internal)
1359 *
1360 * Deallocate request handle
1361 *
1362 */
1363 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1364 {
1365 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1366 DWORD i;
1367
1368 TRACE("\n");
1369
1370 if(lpwhr->hCacheFile)
1371 CloseHandle(lpwhr->hCacheFile);
1372
1373 if(lpwhr->lpszCacheFile) {
1374 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1375 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1376 }
1377
1378 WININET_Release(&lpwhr->lpHttpSession->hdr);
1379
1380 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1381 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1382 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1383 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1384 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1385
1386 for (i = 0; i < lpwhr->nCustHeaders; i++)
1387 {
1388 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1389 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1390 }
1391
1392 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1393 HeapFree(GetProcessHeap(), 0, lpwhr);
1394 }
1395
1396 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1397 {
1398 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1399
1400 TRACE("%p\n",lpwhr);
1401
1402 if (!NETCON_connected(&lpwhr->netConnection))
1403 return;
1404
1405 if (lpwhr->pAuthInfo)
1406 {
1407 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1408 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1409 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1410 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1411
1412 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1413 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1414 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1415 lpwhr->pAuthInfo = NULL;
1416 }
1417 if (lpwhr->pProxyAuthInfo)
1418 {
1419 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1420 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1421 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1422 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1423
1424 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1425 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1426 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1427 lpwhr->pProxyAuthInfo = NULL;
1428 }
1429
1430 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1431 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1432
1433 NETCON_close(&lpwhr->netConnection);
1434
1435 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1436 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1437 }
1438
1439 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1440 {
1441 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1442
1443 switch(option) {
1444 case INTERNET_OPTION_HANDLE_TYPE:
1445 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1446
1447 if (*size < sizeof(ULONG))
1448 return ERROR_INSUFFICIENT_BUFFER;
1449
1450 *size = sizeof(DWORD);
1451 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1452 return ERROR_SUCCESS;
1453
1454 case INTERNET_OPTION_URL: {
1455 WCHAR url[INTERNET_MAX_URL_LENGTH];
1456 HTTPHEADERW *host;
1457 DWORD len;
1458 WCHAR *pch;
1459
1460 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1461 static const WCHAR hostW[] = {'H','o','s','t',0};
1462
1463 TRACE("INTERNET_OPTION_URL\n");
1464
1465 host = HTTP_GetHeader(req, hostW);
1466 strcpyW(url, httpW);
1467 strcatW(url, host->lpszValue);
1468 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1469 *pch = 0;
1470 strcatW(url, req->lpszPath);
1471
1472 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1473
1474 if(unicode) {
1475 len = (strlenW(url)+1) * sizeof(WCHAR);
1476 if(*size < len)
1477 return ERROR_INSUFFICIENT_BUFFER;
1478
1479 *size = len;
1480 strcpyW(buffer, url);
1481 return ERROR_SUCCESS;
1482 }else {
1483 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1484 if(len > *size)
1485 return ERROR_INSUFFICIENT_BUFFER;
1486
1487 *size = len;
1488 return ERROR_SUCCESS;
1489 }
1490 }
1491
1492 case INTERNET_OPTION_DATAFILE_NAME: {
1493 DWORD req_size;
1494
1495 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1496
1497 if(!req->lpszCacheFile) {
1498 *size = 0;
1499 return ERROR_INTERNET_ITEM_NOT_FOUND;
1500 }
1501
1502 if(unicode) {
1503 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1504 if(*size < req_size)
1505 return ERROR_INSUFFICIENT_BUFFER;
1506
1507 *size = req_size;
1508 memcpy(buffer, req->lpszCacheFile, *size);
1509 return ERROR_SUCCESS;
1510 }else {
1511 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1512 if (req_size > *size)
1513 return ERROR_INSUFFICIENT_BUFFER;
1514
1515 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1516 -1, buffer, *size, NULL, NULL);
1517 return ERROR_SUCCESS;
1518 }
1519 }
1520
1521 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1522 PCCERT_CONTEXT context;
1523
1524 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1525 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1526 return ERROR_INSUFFICIENT_BUFFER;
1527 }
1528
1529 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1530 if(context) {
1531 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1532 DWORD len;
1533
1534 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1535 info->ftExpiry = context->pCertInfo->NotAfter;
1536 info->ftStart = context->pCertInfo->NotBefore;
1537 if(unicode) {
1538 len = CertNameToStrW(context->dwCertEncodingType,
1539 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1540 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1541 if(info->lpszSubjectInfo)
1542 CertNameToStrW(context->dwCertEncodingType,
1543 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1544 info->lpszSubjectInfo, len);
1545 len = CertNameToStrW(context->dwCertEncodingType,
1546 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1547 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1548 if (info->lpszIssuerInfo)
1549 CertNameToStrW(context->dwCertEncodingType,
1550 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1551 info->lpszIssuerInfo, len);
1552 }else {
1553 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1554
1555 len = CertNameToStrA(context->dwCertEncodingType,
1556 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1557 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1558 if(infoA->lpszSubjectInfo)
1559 CertNameToStrA(context->dwCertEncodingType,
1560 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1561 infoA->lpszSubjectInfo, len);
1562 len = CertNameToStrA(context->dwCertEncodingType,
1563 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1564 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1565 if(infoA->lpszIssuerInfo)
1566 CertNameToStrA(context->dwCertEncodingType,
1567 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1568 infoA->lpszIssuerInfo, len);
1569 }
1570
1571 /*
1572 * Contrary to MSDN, these do not appear to be set.
1573 * lpszProtocolName
1574 * lpszSignatureAlgName
1575 * lpszEncryptionAlgName
1576 * dwKeySize
1577 */
1578 CertFreeCertificateContext(context);
1579 return ERROR_SUCCESS;
1580 }
1581 }
1582 }
1583
1584 return INET_QueryOption(option, buffer, size, unicode);
1585 }
1586
1587 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1588 {
1589 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1590
1591 switch(option) {
1592 case INTERNET_OPTION_SEND_TIMEOUT:
1593 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1594 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1595
1596 if (size != sizeof(DWORD))
1597 return ERROR_INVALID_PARAMETER;
1598
1599 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1600 *(DWORD*)buffer);
1601 }
1602
1603 return ERROR_INTERNET_INVALID_OPTION;
1604 }
1605
1606 static DWORD HTTP_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1607 {
1608 int bytes_read;
1609
1610 if(!NETCON_recv(&req->netConnection, buffer, min(size, req->dwContentLength - req->dwContentRead),
1611 sync ? MSG_WAITALL : 0, &bytes_read)) {
1612 if(req->dwContentLength != -1 && req->dwContentRead != req->dwContentLength)
1613 ERR("not all data received %d/%d\n", req->dwContentRead, req->dwContentLength);
1614
1615 /* always return success, even if the network layer returns an error */
1616 *read = 0;
1617 HTTP_FinishedReading(req);
1618 return ERROR_SUCCESS;
1619 }
1620
1621 req->dwContentRead += bytes_read;
1622 *read = bytes_read;
1623
1624 if(req->lpszCacheFile) {
1625 BOOL res;
1626 DWORD dwBytesWritten;
1627
1628 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1629 if(!res)
1630 WARN("WriteFile failed: %u\n", GetLastError());
1631 }
1632
1633 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1634 HTTP_FinishedReading(req);
1635
1636 return ERROR_SUCCESS;
1637 }
1638
1639 static DWORD get_chunk_size(const char *buffer)
1640 {
1641 const char *p;
1642 DWORD size = 0;
1643
1644 for (p = buffer; *p; p++)
1645 {
1646 if (*p >= '0' && *p <= '9') size = size * 16 + *p - '0';
1647 else if (*p >= 'a' && *p <= 'f') size = size * 16 + *p - 'a' + 10;
1648 else if (*p >= 'A' && *p <= 'F') size = size * 16 + *p - 'A' + 10;
1649 else if (*p == ';') break;
1650 }
1651 return size;
1652 }
1653
1654 static DWORD HTTP_ReadChunked(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1655 {
1656 char reply[MAX_REPLY_LEN], *p = buffer;
1657 DWORD buflen, to_read, to_write = size;
1658 int bytes_read;
1659
1660 *read = 0;
1661 for (;;)
1662 {
1663 if (*read == size) break;
1664
1665 if (req->dwContentLength == ~0UL) /* new chunk */
1666 {
1667 buflen = sizeof(reply);
1668 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen)) break;
1669
1670 if (!(req->dwContentLength = get_chunk_size(reply)))
1671 {
1672 /* zero sized chunk marks end of transfer; read any trailing headers and return */
1673 HTTP_GetResponseHeaders(req, FALSE);
1674 break;
1675 }
1676 }
1677 to_read = min(to_write, req->dwContentLength - req->dwContentRead);
1678
1679 if (!NETCON_recv(&req->netConnection, p, to_read, sync ? MSG_WAITALL : 0, &bytes_read))
1680 {
1681 if (bytes_read != to_read)
1682 ERR("Not all data received %d/%d\n", bytes_read, to_read);
1683
1684 /* always return success, even if the network layer returns an error */
1685 *read = 0;
1686 break;
1687 }
1688 if (!bytes_read) break;
1689
1690 req->dwContentRead += bytes_read;
1691 to_write -= bytes_read;
1692 *read += bytes_read;
1693
1694 if (req->lpszCacheFile)
1695 {
1696 DWORD dwBytesWritten;
1697
1698 if (!WriteFile(req->hCacheFile, p, bytes_read, &dwBytesWritten, NULL))
1699 WARN("WriteFile failed: %u\n", GetLastError());
1700 }
1701 p += bytes_read;
1702
1703 if (req->dwContentRead == req->dwContentLength) /* chunk complete */
1704 {
1705 req->dwContentRead = 0;
1706 req->dwContentLength = ~0UL;
1707
1708 buflen = sizeof(reply);
1709 if (!NETCON_getNextLine(&req->netConnection, reply, &buflen))
1710 {
1711 ERR("Malformed chunk\n");
1712 *read = 0;
1713 break;
1714 }
1715 }
1716 }
1717 if (!*read) HTTP_FinishedReading(req);
1718 return ERROR_SUCCESS;
1719 }
1720
1721 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1722 {
1723 WCHAR encoding[20];
1724 DWORD buflen = sizeof(encoding);
1725 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
1726
1727 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_TRANSFER_ENCODING, encoding, &buflen, NULL) &&
1728 !strcmpiW(encoding, szChunked))
1729 {
1730 return HTTP_ReadChunked(req, buffer, size, read, sync);
1731 }
1732 else
1733 return HTTP_Read(req, buffer, size, read, sync);
1734 }
1735
1736 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1737 {
1738 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1739 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1740 }
1741
1742 static void HTTPREQ_AsyncReadFileExProc(WORKREQUEST *workRequest)
1743 {
1744 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1745 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1746 INTERNET_ASYNC_RESULT iar;
1747 DWORD res;
1748
1749 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1750
1751 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1752 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1753
1754 iar.dwResult = res == ERROR_SUCCESS;
1755 iar.dwError = res;
1756
1757 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1758 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1759 sizeof(INTERNET_ASYNC_RESULT));
1760 }
1761
1762 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1763 DWORD flags, DWORD_PTR context)
1764 {
1765
1766 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1767 DWORD res;
1768
1769 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1770 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1771
1772 if (buffers->dwStructSize != sizeof(*buffers))
1773 return ERROR_INVALID_PARAMETER;
1774
1775 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1776
1777 if (hdr->dwFlags & INTERNET_FLAG_ASYNC) {
1778 DWORD available = 0;
1779
1780 NETCON_query_data_available(&req->netConnection, &available);
1781 if (!available)
1782 {
1783 WORKREQUEST workRequest;
1784
1785 workRequest.asyncproc = HTTPREQ_AsyncReadFileExProc;
1786 workRequest.hdr = WININET_AddRef(&req->hdr);
1787 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1788
1789 INTERNET_AsyncCall(&workRequest);
1790
1791 return ERROR_IO_PENDING;
1792 }
1793 }
1794
1795 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1796 !(flags & IRF_NO_WAIT));
1797
1798 if (res == ERROR_SUCCESS) {
1799 DWORD size = buffers->dwBufferLength;
1800 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1801 &size, sizeof(size));
1802 }
1803
1804 return res;
1805 }
1806
1807 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1808 {
1809 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1810
1811 return NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written);
1812 }
1813
1814 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1815 {
1816 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1817 INTERNET_ASYNC_RESULT iar;
1818 char buffer[4048];
1819
1820 TRACE("%p\n", workRequest->hdr);
1821
1822 iar.dwResult = NETCON_recv(&req->netConnection, buffer,
1823 min(sizeof(buffer), req->dwContentLength - req->dwContentRead),
1824 MSG_PEEK, (int *)&iar.dwError);
1825
1826 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1827 sizeof(INTERNET_ASYNC_RESULT));
1828 }
1829
1830 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1831 {
1832 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1833 BYTE buffer[4048];
1834 BOOL async;
1835
1836 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1837
1838 if(!NETCON_query_data_available(&req->netConnection, available) || *available)
1839 return ERROR_SUCCESS;
1840
1841 /* Even if we are in async mode, we need to determine whether
1842 * there is actually more data available. We do this by trying
1843 * to peek only a single byte in async mode. */
1844 async = (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC) != 0;
1845
1846 if (NETCON_recv(&req->netConnection, buffer,
1847 min(async ? 1 : sizeof(buffer), req->dwContentLength - req->dwContentRead),
1848 MSG_PEEK, (int *)available) && async && *available)
1849 {
1850 WORKREQUEST workRequest;
1851
1852 *available = 0;
1853 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
1854 workRequest.hdr = WININET_AddRef( &req->hdr );
1855
1856 INTERNET_AsyncCall(&workRequest);
1857
1858 return ERROR_IO_PENDING;
1859 }
1860
1861 return ERROR_SUCCESS;
1862 }
1863
1864 static const HANDLEHEADERVtbl HTTPREQVtbl = {
1865 HTTPREQ_Destroy,
1866 HTTPREQ_CloseConnection,
1867 HTTPREQ_QueryOption,
1868 HTTPREQ_SetOption,
1869 HTTPREQ_ReadFile,
1870 HTTPREQ_ReadFileExA,
1871 HTTPREQ_WriteFile,
1872 HTTPREQ_QueryDataAvailable,
1873 NULL
1874 };
1875
1876 /***********************************************************************
1877 * HTTP_HttpOpenRequestW (internal)
1878 *
1879 * Open a HTTP request handle
1880 *
1881 * RETURNS
1882 * HINTERNET a HTTP request handle on success
1883 * NULL on failure
1884 *
1885 */
1886 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
1887 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
1888 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
1889 DWORD dwFlags, DWORD_PTR dwContext)
1890 {
1891 LPWININETAPPINFOW hIC = NULL;
1892 LPWININETHTTPREQW lpwhr;
1893 LPWSTR lpszHostName = NULL;
1894 HINTERNET handle = NULL;
1895 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
1896 DWORD len;
1897
1898 TRACE("-->\n");
1899
1900 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
1901 hIC = lpwhs->lpAppInfo;
1902
1903 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
1904 if (NULL == lpwhr)
1905 {
1906 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1907 goto lend;
1908 }
1909 lpwhr->hdr.htype = WH_HHTTPREQ;
1910 lpwhr->hdr.vtbl = &HTTPREQVtbl;
1911 lpwhr->hdr.dwFlags = dwFlags;
1912 lpwhr->hdr.dwContext = dwContext;
1913 lpwhr->hdr.refs = 1;
1914 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
1915 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
1916
1917 WININET_AddRef( &lpwhs->hdr );
1918 lpwhr->lpHttpSession = lpwhs;
1919 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
1920
1921 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
1922 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
1923 if (NULL == lpszHostName)
1924 {
1925 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1926 goto lend;
1927 }
1928
1929 handle = WININET_AllocHandle( &lpwhr->hdr );
1930 if (NULL == handle)
1931 {
1932 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1933 goto lend;
1934 }
1935
1936 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
1937 {
1938 InternetCloseHandle( handle );
1939 handle = NULL;
1940 goto lend;
1941 }
1942
1943 if (lpszObjectName && *lpszObjectName) {
1944 HRESULT rc;
1945
1946 len = 0;
1947 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
1948 if (rc != E_POINTER)
1949 len = strlenW(lpszObjectName)+1;
1950 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1951 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
1952 URL_ESCAPE_SPACES_ONLY);
1953 if (rc)
1954 {
1955 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
1956 strcpyW(lpwhr->lpszPath,lpszObjectName);
1957 }
1958 }
1959
1960 if (lpszReferrer && *lpszReferrer)
1961 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1962
1963 if (lpszAcceptTypes)
1964 {
1965 int i;
1966 for (i = 0; lpszAcceptTypes[i]; i++)
1967 {
1968 if (!*lpszAcceptTypes[i]) continue;
1969 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
1970 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
1971 HTTP_ADDHDR_FLAG_REQ |
1972 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
1973 }
1974 }
1975
1976 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
1977
1978 if (lpszVersion)
1979 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
1980 else
1981 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
1982
1983 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
1984 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
1985 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
1986 {
1987 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
1988 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
1989 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1990 }
1991 else
1992 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
1993 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
1994
1995 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
1996 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
1997 INTERNET_DEFAULT_HTTPS_PORT :
1998 INTERNET_DEFAULT_HTTP_PORT);
1999
2000 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2001 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2002 INTERNET_DEFAULT_HTTPS_PORT :
2003 INTERNET_DEFAULT_HTTP_PORT);
2004
2005 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2006 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2007
2008 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2009 INTERNET_STATUS_HANDLE_CREATED, &handle,
2010 sizeof(handle));
2011
2012 lend:
2013 HeapFree(GetProcessHeap(), 0, lpszHostName);
2014 if( lpwhr )
2015 WININET_Release( &lpwhr->hdr );
2016
2017 TRACE("<-- %p (%p)\n", handle, lpwhr);
2018 return handle;
2019 }
2020
2021 /* read any content returned by the server so that the connection can be
2022 * reused */
2023 static void HTTP_DrainContent(WININETHTTPREQW *req)
2024 {
2025 DWORD bytes_read;
2026
2027 if (!NETCON_connected(&req->netConnection)) return;
2028
2029 if (req->dwContentLength == -1)
2030 NETCON_close(&req->netConnection);
2031
2032 do
2033 {
2034 char buffer[2048];
2035 if (HTTP_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2036 return;
2037 } while (bytes_read);
2038 }
2039
2040 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2041 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2042 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2043 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2044 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2045 static const WCHAR szAge[] = { 'A','g','e',0 };
2046 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2047 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2048 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2049 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2050 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2051 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2052 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2053 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2054 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2055 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2056 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2057 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 };
2058 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2059 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2060 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2061 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2062 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2063 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2064 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2065 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2066 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2067 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2068 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2069 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2070 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2071 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2072 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2073 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2074 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2075 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2076 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2077 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2078 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2079 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2080 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2081 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2082 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2083 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2084 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 };
2085 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2086 static const WCHAR szURI[] = { 'U','R','I',0 };
2087 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2088 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2089 static const WCHAR szVia[] = { 'V','i','a',0 };
2090 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2091 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2092
2093 static const LPCWSTR header_lookup[] = {
2094 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2095 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2096 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2097 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2098 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2099 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2100 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2101 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2102 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2103 szDate, /* HTTP_QUERY_DATE = 9 */
2104 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2105 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2106 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2107 szURI, /* HTTP_QUERY_URI = 13 */
2108 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2109 NULL, /* HTTP_QUERY_COST = 15 */
2110 NULL, /* HTTP_QUERY_LINK = 16 */
2111 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2112 NULL, /* HTTP_QUERY_VERSION = 18 */
2113 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2114 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2115 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2116 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2117 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2118 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2119 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2120 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2121 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2122 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2123 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2124 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2125 NULL, /* HTTP_QUERY_FROM = 31 */
2126 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2127 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2128 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2129 szReferer, /* HTTP_QUERY_REFERER = 35 */
2130 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2131 szServer, /* HTTP_QUERY_SERVER = 37 */
2132 NULL, /* HTTP_TITLE = 38 */
2133 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2134 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2135 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2136 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2137 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2138 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2139 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2140 NULL, /* HTTP_QUERY_REFRESH = 46 */
2141 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2142 szAge, /* HTTP_QUERY_AGE = 48 */
2143 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2144 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2145 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2146 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2147 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2148 szETag, /* HTTP_QUERY_ETAG = 54 */
2149 szHost, /* HTTP_QUERY_HOST = 55 */
2150 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2151 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2152 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2153 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2154 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2155 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2156 szRange, /* HTTP_QUERY_RANGE = 62 */
2157 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2158 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2159 szVary, /* HTTP_QUERY_VARY = 65 */
2160 szVia, /* HTTP_QUERY_VIA = 66 */
2161 szWarning, /* HTTP_QUERY_WARNING = 67 */
2162 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2163 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2164 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2165 };
2166
2167 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2168
2169 /***********************************************************************
2170 * HTTP_HttpQueryInfoW (internal)
2171 */
2172 static BOOL WINAPI HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2173 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2174 {
2175 LPHTTPHEADERW lphttpHdr = NULL;
2176 BOOL bSuccess = FALSE;
2177 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2178 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2179 INT level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2180 INT index = -1;
2181
2182 /* Find requested header structure */
2183 switch (level)
2184 {
2185 case HTTP_QUERY_CUSTOM:
2186 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2187 break;
2188
2189 case HTTP_QUERY_RAW_HEADERS_CRLF:
2190 {
2191 LPWSTR headers;
2192 DWORD len;
2193 BOOL ret = FALSE;
2194
2195 if (request_only)
2196 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2197 else
2198 headers = lpwhr->lpszRawHeaders;
2199
2200 len = (strlenW(headers) + 1) * sizeof(WCHAR);
2201 if (len > *lpdwBufferLength)
2202 {
2203 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2204 ret = FALSE;
2205 }
2206 else if (lpBuffer)
2207 {
2208 memcpy(lpBuffer, headers, len);
2209 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2210 ret = TRUE;
2211 }
2212 *lpdwBufferLength = len;
2213
2214 if (request_only)
2215 HeapFree(GetProcessHeap(), 0, headers);
2216 return ret;
2217 }
2218 case HTTP_QUERY_RAW_HEADERS:
2219 {
2220 static const WCHAR szCrLf[] = {'\r','\n',0};
2221 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2222 DWORD i, size = 0;
2223 LPWSTR pszString = (WCHAR*)lpBuffer;
2224
2225 for (i = 0; ppszRawHeaderLines[i]; i++)
2226 size += strlenW(ppszRawHeaderLines[i]) + 1;
2227
2228 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2229 {
2230 HTTP_FreeTokens(ppszRawHeaderLines);
2231 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2232 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2233 return FALSE;
2234 }
2235
2236 for (i = 0; ppszRawHeaderLines[i]; i++)
2237 {
2238 DWORD len = strlenW(ppszRawHeaderLines[i]);
2239 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2240 pszString += len+1;
2241 }
2242 *pszString = '\0';
2243
2244 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, size));
2245
2246 *lpdwBufferLength = size * sizeof(WCHAR);
2247 HTTP_FreeTokens(ppszRawHeaderLines);
2248
2249 return TRUE;
2250 }
2251 case HTTP_QUERY_STATUS_TEXT:
2252 if (lpwhr->lpszStatusText)
2253 {
2254 DWORD len = strlenW(lpwhr->lpszStatusText);
2255 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2256 {
2257 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2258 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2259 return FALSE;
2260 }
2261 memcpy(lpBuffer, lpwhr->lpszStatusText, (len+1)*sizeof(WCHAR));
2262 *lpdwBufferLength = len * sizeof(WCHAR);
2263
2264 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2265
2266 return TRUE;
2267 }
2268 break;
2269 case HTTP_QUERY_VERSION:
2270 if (lpwhr->lpszVersion)
2271 {
2272 DWORD len = strlenW(lpwhr->lpszVersion);
2273 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2274 {
2275 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2276 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2277 return FALSE;
2278 }
2279 memcpy(lpBuffer, lpwhr->lpszVersion, (len+1)*sizeof(WCHAR));
2280 *lpdwBufferLength = len * sizeof(WCHAR);
2281
2282 TRACE("returning data: %s\n", debugstr_wn((WCHAR*)lpBuffer, len));
2283
2284 return TRUE;
2285 }
2286 break;
2287 default:
2288 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2289
2290 if (level >= 0 && level < LAST_TABLE_HEADER && header_lookup[level])
2291 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2292 requested_index,request_only);
2293 }
2294
2295 if (index >= 0)
2296 lphttpHdr = &lpwhr->pCustHeaders[index];
2297
2298 /* Ensure header satisfies requested attributes */
2299 if (!lphttpHdr ||
2300 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2301 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2302 {
2303 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2304 return bSuccess;
2305 }
2306
2307 if (lpdwIndex)
2308 (*lpdwIndex)++;
2309
2310 /* coalesce value to requested type */
2311 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER)
2312 {
2313 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2314 bSuccess = TRUE;
2315
2316 TRACE(" returning number : %d\n", *(int *)lpBuffer);
2317 }
2318 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME)
2319 {
2320 time_t tmpTime;
2321 struct tm tmpTM;
2322 SYSTEMTIME *STHook;
2323
2324 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2325
2326 tmpTM = *gmtime(&tmpTime);
2327 STHook = (SYSTEMTIME *) lpBuffer;
2328 if(STHook==NULL)
2329 return bSuccess;
2330
2331 STHook->wDay = tmpTM.tm_mday;
2332 STHook->wHour = tmpTM.tm_hour;
2333 STHook->wMilliseconds = 0;
2334 STHook->wMinute = tmpTM.tm_min;
2335 STHook->wDayOfWeek = tmpTM.tm_wday;
2336 STHook->wMonth = tmpTM.tm_mon + 1;
2337 STHook->wSecond = tmpTM.tm_sec;
2338 STHook->wYear = tmpTM.tm_year;
2339
2340 bSuccess = TRUE;
2341
2342 TRACE(" returning time : %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2343 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2344 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2345 }
2346 else if (lphttpHdr->lpszValue)
2347 {
2348 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2349
2350 if (len > *lpdwBufferLength)
2351 {
2352 *lpdwBufferLength = len;
2353 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2354 return bSuccess;
2355 }
2356
2357 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2358 *lpdwBufferLength = len - sizeof(WCHAR);
2359 bSuccess = TRUE;
2360
2361 TRACE(" returning string : %s\n", debugstr_w(lpBuffer));
2362 }
2363 return bSuccess;
2364 }
2365
2366 /***********************************************************************
2367 * HttpQueryInfoW (WININET.@)
2368 *
2369 * Queries for information about an HTTP request
2370 *
2371 * RETURNS
2372 * TRUE on success
2373 * FALSE on failure
2374 *
2375 */
2376 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2377 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2378 {
2379 BOOL bSuccess = FALSE;
2380 LPWININETHTTPREQW lpwhr;
2381
2382 if (TRACE_ON(wininet)) {
2383 #define FE(x) { x, #x }
2384 static const wininet_flag_info query_flags[] = {
2385 FE(HTTP_QUERY_MIME_VERSION),
2386 FE(HTTP_QUERY_CONTENT_TYPE),
2387 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2388 FE(HTTP_QUERY_CONTENT_ID),
2389 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2390 FE(HTTP_QUERY_CONTENT_LENGTH),
2391 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2392 FE(HTTP_QUERY_ALLOW),
2393 FE(HTTP_QUERY_PUBLIC),
2394 FE(HTTP_QUERY_DATE),
2395 FE(HTTP_QUERY_EXPIRES),
2396 FE(HTTP_QUERY_LAST_MODIFIED),
2397 FE(HTTP_QUERY_MESSAGE_ID),
2398 FE(HTTP_QUERY_URI),
2399 FE(HTTP_QUERY_DERIVED_FROM),
2400 FE(HTTP_QUERY_COST),
2401 FE(HTTP_QUERY_LINK),
2402 FE(HTTP_QUERY_PRAGMA),
2403 FE(HTTP_QUERY_VERSION),
2404 FE(HTTP_QUERY_STATUS_CODE),
2405 FE(HTTP_QUERY_STATUS_TEXT),
2406 FE(HTTP_QUERY_RAW_HEADERS),
2407 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2408 FE(HTTP_QUERY_CONNECTION),
2409 FE(HTTP_QUERY_ACCEPT),
2410 FE(HTTP_QUERY_ACCEPT_CHARSET),
2411 FE(HTTP_QUERY_ACCEPT_ENCODING),
2412 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2413 FE(HTTP_QUERY_AUTHORIZATION),
2414 FE(HTTP_QUERY_CONTENT_ENCODING),
2415 FE(HTTP_QUERY_FORWARDED),
2416 FE(HTTP_QUERY_FROM),
2417 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2418 FE(HTTP_QUERY_LOCATION),
2419 FE(HTTP_QUERY_ORIG_URI),
2420 FE(HTTP_QUERY_REFERER),
2421 FE(HTTP_QUERY_RETRY_AFTER),
2422 FE(HTTP_QUERY_SERVER),
2423 FE(HTTP_QUERY_TITLE),
2424 FE(HTTP_QUERY_USER_AGENT),
2425 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2426 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2427 FE(HTTP_QUERY_ACCEPT_RANGES),
2428 FE(HTTP_QUERY_SET_COOKIE),
2429 FE(HTTP_QUERY_COOKIE),
2430 FE(HTTP_QUERY_REQUEST_METHOD),
2431 FE(HTTP_QUERY_REFRESH),
2432 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2433 FE(HTTP_QUERY_AGE),
2434 FE(HTTP_QUERY_CACHE_CONTROL),
2435 FE(HTTP_QUERY_CONTENT_BASE),
2436 FE(HTTP_QUERY_CONTENT_LOCATION),
2437 FE(HTTP_QUERY_CONTENT_MD5),
2438 FE(HTTP_QUERY_CONTENT_RANGE),
2439 FE(HTTP_QUERY_ETAG),
2440 FE(HTTP_QUERY_HOST),
2441 FE(HTTP_QUERY_IF_MATCH),
2442 FE(HTTP_QUERY_IF_NONE_MATCH),
2443 FE(HTTP_QUERY_IF_RANGE),
2444 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2445 FE(HTTP_QUERY_MAX_FORWARDS),
2446 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2447 FE(HTTP_QUERY_RANGE),
2448 FE(HTTP_QUERY_TRANSFER_ENCODING),
2449 FE(HTTP_QUERY_UPGRADE),
2450 FE(HTTP_QUERY_VARY),
2451 FE(HTTP_QUERY_VIA),
2452 FE(HTTP_QUERY_WARNING),
2453 FE(HTTP_QUERY_CUSTOM)
2454 };
2455 static const wininet_flag_info modifier_flags[] = {
2456 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2457 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2458 FE(HTTP_QUERY_FLAG_NUMBER),
2459 FE(HTTP_QUERY_FLAG_COALESCE)
2460 };
2461 #undef FE
2462 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2463 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2464 DWORD i;
2465
2466 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2467 TRACE(" Attribute:");
2468 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2469 if (query_flags[i].val == info) {
2470 TRACE(" %s", query_flags[i].name);
2471 break;
2472 }
2473 }
2474 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2475 TRACE(" Unknown (%08x)", info);
2476 }
2477
2478 TRACE(" Modifier:");
2479 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2480 if (modifier_flags[i].val & info_mod) {
2481 TRACE(" %s", modifier_flags[i].name);
2482 info_mod &= ~ modifier_flags[i].val;
2483 }
2484 }
2485
2486 if (info_mod) {
2487 TRACE(" Unknown (%08x)", info_mod);
2488 }
2489 TRACE("\n");
2490 }
2491
2492 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2493 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2494 {
2495 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2496 goto lend;
2497 }
2498
2499 if (lpBuffer == NULL)
2500 *lpdwBufferLength = 0;
2501 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2502 lpBuffer, lpdwBufferLength, lpdwIndex);
2503
2504 lend:
2505 if( lpwhr )
2506 WININET_Release( &lpwhr->hdr );
2507
2508 TRACE("%d <--\n", bSuccess);
2509 return bSuccess;
2510 }
2511
2512 /***********************************************************************
2513 * HttpQueryInfoA (WININET.@)
2514 *
2515 * Queries for information about an HTTP request
2516 *
2517 * RETURNS
2518 * TRUE on success
2519 * FALSE on failure
2520 *
2521 */
2522 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2523 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2524 {
2525 BOOL result;
2526 DWORD len;
2527 WCHAR* bufferW;
2528
2529 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2530 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2531 {
2532 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2533 lpdwBufferLength, lpdwIndex );
2534 }
2535
2536 if (lpBuffer)
2537 {
2538 DWORD alloclen;
2539 len = (*lpdwBufferLength)*sizeof(WCHAR);
2540 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2541 {
2542 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2543 if (alloclen < len)
2544 alloclen = len;
2545 }
2546 else
2547 alloclen = len;
2548 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2549 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2550 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2551 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2552 } else
2553 {
2554 bufferW = NULL;
2555 len = 0;
2556 }
2557
2558 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2559 &len, lpdwIndex );
2560 if( result )
2561 {
2562 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2563 lpBuffer, *lpdwBufferLength, NULL, NULL );
2564 *lpdwBufferLength = len - 1;
2565
2566 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2567 }
2568 else
2569 /* since the strings being returned from HttpQueryInfoW should be
2570 * only ASCII characters, it is reasonable to assume that all of
2571 * the Unicode characters can be reduced to a single byte */
2572 *lpdwBufferLength = len / sizeof(WCHAR);
2573
2574 HeapFree(GetProcessHeap(), 0, bufferW );
2575
2576 return result;
2577 }
2578
2579 /***********************************************************************
2580 * HttpSendRequestExA (WININET.@)
2581 *
2582 * Sends the specified request to the HTTP server and allows chunked
2583 * transfers.
2584 *
2585 * RETURNS
2586 * Success: TRUE
2587 * Failure: FALSE, call GetLastError() for more information.
2588 */
2589 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2590 LPINTERNET_BUFFERSA lpBuffersIn,
2591 LPINTERNET_BUFFERSA lpBuffersOut,
2592 DWORD dwFlags, DWORD_PTR dwContext)
2593 {
2594 INTERNET_BUFFERSW BuffersInW;
2595 BOOL rc = FALSE;
2596 DWORD headerlen;
2597 LPWSTR header = NULL;
2598
2599 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2600 lpBuffersOut, dwFlags, dwContext);
2601
2602 if (lpBuffersIn)
2603 {
2604 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2605 if (lpBuffersIn->lpcszHeader)
2606 {
2607 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2608 lpBuffersIn->dwHeadersLength,0,0);
2609 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2610 if (!(BuffersInW.lpcszHeader = header))
2611 {
2612 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2613 return FALSE;
2614 }
2615 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2616 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2617 header, headerlen);
2618 }
2619 else
2620 BuffersInW.lpcszHeader = NULL;
2621 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2622 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2623 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2624 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2625 BuffersInW.Next = NULL;
2626 }
2627
2628 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2629
2630 HeapFree(GetProcessHeap(),0,header);
2631
2632 return rc;
2633 }
2634
2635 /***********************************************************************
2636 * HttpSendRequestExW (WININET.@)
2637 *
2638 * Sends the specified request to the HTTP server and allows chunked
2639 * transfers
2640 *
2641 * RETURNS
2642 * Success: TRUE
2643 * Failure: FALSE, call GetLastError() for more information.
2644 */
2645 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2646 LPINTERNET_BUFFERSW lpBuffersIn,
2647 LPINTERNET_BUFFERSW lpBuffersOut,
2648 DWORD dwFlags, DWORD_PTR dwContext)
2649 {
2650 BOOL ret = FALSE;
2651 LPWININETHTTPREQW lpwhr;
2652 LPWININETHTTPSESSIONW lpwhs;
2653 LPWININETAPPINFOW hIC;
2654
2655 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2656 lpBuffersOut, dwFlags, dwContext);
2657
2658 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2659
2660 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2661 {
2662 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2663 goto lend;
2664 }
2665
2666 lpwhs = lpwhr->lpHttpSession;
2667 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2668 hIC = lpwhs->lpAppInfo;
2669 assert(hIC->hdr.htype == WH_HINIT);
2670
2671 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2672 {
2673 WORKREQUEST workRequest;
2674 struct WORKREQ_HTTPSENDREQUESTW *req;
2675
2676 workRequest.asyncproc = AsyncHttpSendRequestProc;
2677 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2678 req = &workRequest.u.HttpSendRequestW;
2679 if (lpBuffersIn)
2680 {
2681 if (lpBuffersIn->lpcszHeader)
2682 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2683 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2684 else
2685 req->lpszHeader = NULL;
2686 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2687 req->lpOptional = lpBuffersIn->lpvBuffer;
2688 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2689 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2690 }
2691 else
2692 {
2693 req->lpszHeader = NULL;
2694 req->dwHeaderLength = 0;
2695 req->lpOptional = NULL;
2696 req->dwOptionalLength = 0;
2697 req->dwContentLength = 0;
2698 }
2699
2700 req->bEndRequest = FALSE;
2701
2702 INTERNET_AsyncCall(&workRequest);
2703 /*
2704 * This is from windows.
2705 */
2706 INTERNET_SetLastError(ERROR_IO_PENDING);
2707 }
2708 else
2709 {
2710 if (lpBuffersIn)
2711 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2712 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2713 lpBuffersIn->dwBufferTotal, FALSE);
2714 else
2715 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2716 }
2717
2718 lend:
2719 if ( lpwhr )
2720 WININET_Release( &lpwhr->hdr );
2721
2722 TRACE("<---\n");
2723 return ret;
2724 }
2725
2726 /***********************************************************************
2727 * HttpSendRequestW (WININET.@)
2728 *
2729 * Sends the specified request to the HTTP server
2730 *
2731 * RETURNS
2732 * TRUE on success
2733 * FALSE on failure
2734 *
2735 */
2736 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2737 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2738 {
2739 LPWININETHTTPREQW lpwhr;
2740 LPWININETHTTPSESSIONW lpwhs = NULL;
2741 LPWININETAPPINFOW hIC = NULL;
2742 BOOL r;
2743
2744 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2745 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2746
2747 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2748 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2749 {
2750 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2751 r = FALSE;
2752 goto lend;
2753 }
2754
2755 lpwhs = lpwhr->lpHttpSession;
2756 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2757 {
2758 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2759 r = FALSE;
2760 goto lend;
2761 }
2762
2763 hIC = lpwhs->lpAppInfo;
2764 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2765 {
2766 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2767 r = FALSE;
2768 goto lend;
2769 }
2770
2771 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2772 {
2773 WORKREQUEST workRequest;
2774 struct WORKREQ_HTTPSENDREQUESTW *req;
2775
2776 workRequest.asyncproc = AsyncHttpSendRequestProc;
2777 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2778 req = &workRequest.u.HttpSendRequestW;
2779 if (lpszHeaders)
2780 {
2781 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, dwHeaderLength * sizeof(WCHAR));
2782 memcpy(req->lpszHeader, lpszHeaders, dwHeaderLength * sizeof(WCHAR));
2783 }
2784 else
2785 req->lpszHeader = 0;
2786 req->dwHeaderLength = dwHeaderLength;
2787 req->lpOptional = lpOptional;
2788 req->dwOptionalLength = dwOptionalLength;
2789 req->dwContentLength = dwOptionalLength;
2790 req->bEndRequest = TRUE;
2791
2792 INTERNET_AsyncCall(&workRequest);
2793 /*
2794 * This is from windows.
2795 */
2796 INTERNET_SetLastError(ERROR_IO_PENDING);
2797 r = FALSE;
2798 }
2799 else
2800 {
2801 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2802 dwHeaderLength, lpOptional, dwOptionalLength,
2803 dwOptionalLength, TRUE);
2804 }
2805 lend:
2806 if( lpwhr )
2807 WININET_Release( &lpwhr->hdr );
2808 return r;
2809 }
2810
2811 /***********************************************************************
2812 * HttpSendRequestA (WININET.@)
2813 *
2814 * Sends the specified request to the HTTP server
2815 *
2816 * RETURNS
2817 * TRUE on success
2818 * FALSE on failure
2819 *
2820 */
2821 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
2822 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2823 {
2824 BOOL result;
2825 LPWSTR szHeaders=NULL;
2826 DWORD nLen=dwHeaderLength;
2827 if(lpszHeaders!=NULL)
2828 {
2829 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
2830 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
2831 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
2832 }
2833 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
2834 HeapFree(GetProcessHeap(),0,szHeaders);
2835 return result;
2836 }
2837
2838 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
2839 {
2840 LPHTTPHEADERW host_header;
2841
2842 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
2843
2844 host_header = HTTP_GetHeader(req, szHost);
2845 if(!host_header)
2846 return FALSE;
2847
2848 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
2849 return TRUE;
2850 }
2851
2852 /***********************************************************************
2853 * HTTP_HandleRedirect (internal)
2854 */
2855 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
2856 {
2857 static const WCHAR szContentType[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
2858 static const WCHAR szContentLength[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
2859 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
2860 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
2861 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
2862 WCHAR path[INTERNET_MAX_URL_LENGTH];
2863 int index;
2864
2865 if(lpszUrl[0]=='/')
2866 {
2867 /* if it's an absolute path, keep the same session info */
2868 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
2869 }
2870 else
2871 {
2872 URL_COMPONENTSW urlComponents;
2873 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2874 static WCHAR szHttp[] = {'h','t','t','p',0};
2875 static WCHAR szHttps[] = {'h','t','t','p','s',0};
2876 DWORD url_length = 0;
2877 LPWSTR orig_url;
2878 LPWSTR combined_url;
2879
2880 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2881 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
2882 urlComponents.dwSchemeLength = 0;
2883 urlComponents.lpszHostName = lpwhs->lpszHostName;
2884 urlComponents.dwHostNameLength = 0;
2885 urlComponents.nPort = lpwhs->nHostPort;
2886 urlComponents.lpszUserName = lpwhs->lpszUserName;
2887 urlComponents.dwUserNameLength = 0;
2888 urlComponents.lpszPassword = NULL;
2889 urlComponents.dwPasswordLength = 0;
2890 urlComponents.lpszUrlPath = lpwhr->lpszPath;
2891 urlComponents.dwUrlPathLength = 0;
2892 urlComponents.lpszExtraInfo = NULL;
2893 urlComponents.dwExtraInfoLength = 0;
2894
2895 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
2896 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2897 return FALSE;
2898
2899 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
2900
2901 /* convert from bytes to characters */
2902 url_length = url_length / sizeof(WCHAR) - 1;
2903 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
2904 {
2905 HeapFree(GetProcessHeap(), 0, orig_url);
2906 return FALSE;
2907 }
2908
2909 url_length = 0;
2910 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
2911 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2912 {
2913 HeapFree(GetProcessHeap(), 0, orig_url);
2914 return FALSE;
2915 }
2916 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
2917
2918 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
2919 {
2920 HeapFree(GetProcessHeap(), 0, orig_url);
2921 HeapFree(GetProcessHeap(), 0, combined_url);
2922 return FALSE;
2923 }
2924 HeapFree(GetProcessHeap(), 0, orig_url);
2925
2926 userName[0] = 0;
2927 hostName[0] = 0;
2928 protocol[0] = 0;
2929
2930 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2931 urlComponents.lpszScheme = protocol;
2932 urlComponents.dwSchemeLength = 32;
2933 urlComponents.lpszHostName = hostName;
2934 urlComponents.dwHostNameLength = MAXHOSTNAME;
2935 urlComponents.lpszUserName = userName;
2936 urlComponents.dwUserNameLength = 1024;
2937 urlComponents.lpszPassword = NULL;
2938 urlComponents.dwPasswordLength = 0;
2939 urlComponents.lpszUrlPath = path;
2940 urlComponents.dwUrlPathLength = 2048;
2941 urlComponents.lpszExtraInfo = NULL;
2942 urlComponents.dwExtraInfoLength = 0;
2943 if(!InternetCrackUrlW(combined_url, strlenW(combined_url), 0, &urlComponents))
2944 {
2945 HeapFree(GetProcessHeap(), 0, combined_url);
2946 return FALSE;
2947 }
2948
2949 HeapFree(GetProcessHeap(), 0, combined_url);
2950
2951 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
2952 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2953 {
2954 TRACE("redirect from secure page to non-secure page\n");
2955 /* FIXME: warn about from secure redirect to non-secure page */
2956 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
2957 }
2958 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
2959 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
2960 {
2961 TRACE("redirect from non-secure page to secure page\n");
2962 /* FIXME: notify about redirect to secure page */
2963 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
2964 }
2965
2966 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
2967 {
2968 if (lstrlenW(protocol)>4) /*https*/
2969 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2970 else /*http*/
2971 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2972 }
2973
2974 #if 0
2975 /*
2976 * This upsets redirects to binary files on sourceforge.net
2977 * and gives an html page instead of the target file
2978 * Examination of the HTTP request sent by native wininet.dll
2979 * reveals that it doesn't send a referrer in that case.
2980 * Maybe there's a flag that enables this, or maybe a referrer
2981 * shouldn't be added in case of a redirect.
2982 */
2983
2984 /* consider the current host as the referrer */
2985 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
2986 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
2987 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
2988 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
2989 #endif
2990
2991 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
2992 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
2993 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
2994 {
2995 int len;
2996 static const WCHAR fmt[] = {'%','s',':','%','i',0};
2997 len = lstrlenW(hostName);
2998 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
2999 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3000 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3001 }
3002 else
3003 lpwhs->lpszHostName = WININET_strdupW(hostName);
3004
3005 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3006
3007 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3008 lpwhs->lpszUserName = NULL;
3009 if (userName[0])
3010 lpwhs->lpszUserName = WININET_strdupW(userName);
3011
3012 if (!using_proxy)
3013 {
3014 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3015 {
3016 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3017 lpwhs->lpszServerName = WININET_strdupW(hostName);
3018 lpwhs->nServerPort = urlComponents.nPort;
3019
3020 NETCON_close(&lpwhr->netConnection);
3021 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3022 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3023 }
3024 }
3025 else
3026 TRACE("Redirect through proxy\n");
3027 }
3028
3029 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3030 lpwhr->lpszPath=NULL;
3031 if (*path)
3032 {
3033 DWORD needed = 0;
3034 HRESULT rc;
3035
3036 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3037 if (rc != E_POINTER)
3038 needed = strlenW(path)+1;
3039 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3040 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3041 URL_ESCAPE_SPACES_ONLY);
3042 if (rc)
3043 {
3044 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3045 strcpyW(lpwhr->lpszPath,path);
3046 }
3047 }
3048
3049 /* Remove custom content-type/length headers on redirects. */
3050 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentType, 0, TRUE);
3051 if (0 <= index)
3052 HTTP_DeleteCustomHeader(lpwhr, index);
3053 index = HTTP_GetCustomHeaderIndex(lpwhr, szContentLength, 0, TRUE);
3054 if (0 <= index)
3055 HTTP_DeleteCustomHeader(lpwhr, index);
3056
3057 return TRUE;
3058 }
3059
3060 /***********************************************************************
3061 * HTTP_build_req (internal)
3062 *
3063 * concatenate all the strings in the request together
3064 */
3065 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3066 {
3067 LPCWSTR *t;
3068 LPWSTR str;
3069
3070 for( t = list; *t ; t++ )
3071 len += strlenW( *t );
3072 len++;
3073
3074 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3075 *str = 0;
3076
3077 for( t = list; *t ; t++ )
3078 strcatW( str, *t );
3079
3080 return str;
3081 }
3082
3083 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3084 {
3085 LPWSTR lpszPath;
3086 LPWSTR requestString;
3087 INT len;
3088 INT cnt;
3089 INT responseLen;
3090 char *ascii_req;
3091 BOOL ret;
3092 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3093 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3094 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3095
3096 TRACE("\n");
3097
3098 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3099 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3100 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3101 HeapFree( GetProcessHeap(), 0, lpszPath );
3102
3103 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3104 NULL, 0, NULL, NULL );
3105 len--; /* the nul terminator isn't needed */
3106 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3107 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3108 ascii_req, len, NULL, NULL );
3109 HeapFree( GetProcessHeap(), 0, requestString );
3110
3111 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3112
3113 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3114 HeapFree( GetProcessHeap(), 0, ascii_req );
3115 if (!ret || cnt < 0)
3116 return FALSE;
3117
3118 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3119 if (!responseLen)
3120 return FALSE;
3121
3122 return TRUE;
3123 }
3124
3125 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3126 {
3127 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s',0};
3128 LPWSTR lpszCookies, lpszUrl = NULL;
3129 DWORD nCookieSize, size;
3130 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3131
3132 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm)) * sizeof(WCHAR);
3133 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3134 sprintfW( lpszUrl, szUrlForm, Host->lpszValue );
3135
3136 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3137 {
3138 int cnt = 0;
3139 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3140 static const WCHAR szcrlf[] = {'\r','\n',0};
3141
3142 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szcrlf);
3143 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3144 {
3145 cnt += sprintfW(lpszCookies, szCookie);
3146 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3147 strcatW(lpszCookies, szcrlf);
3148
3149 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_ADD);
3150 HeapFree(GetProcessHeap(), 0, lpszCookies);
3151 }
3152 }
3153 HeapFree(GetProcessHeap(), 0, lpszUrl);
3154 }
3155
3156 /***********************************************************************
3157 * HTTP_HttpSendRequestW (internal)
3158 *
3159 * Sends the specified request to the HTTP server
3160 *
3161 * RETURNS
3162 * TRUE on success
3163 * FALSE on failure
3164 *
3165 */
3166 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3167 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3168 DWORD dwContentLength, BOOL bEndRequest)
3169 {
3170 INT cnt;
3171 BOOL bSuccess = FALSE;
3172 LPWSTR requestString = NULL;
3173 INT responseLen;
3174 BOOL loop_next;
3175 INTERNET_ASYNC_RESULT iar;
3176 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3177 static const WCHAR szContentLength[] =
3178 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3179 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3180
3181 TRACE("--> %p\n", lpwhr);
3182
3183 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3184
3185 /* if the verb is NULL default to GET */
3186 if (!lpwhr->lpszVerb)
3187 lpwhr->lpszVerb = WININET_strdupW(szGET);
3188
3189 if (dwContentLength || !strcmpW(lpwhr->lpszVerb, szPost))
3190 {
3191 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3192 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3193 }
3194 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3195 {
3196 WCHAR *agent_header;
3197 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3198 int len;
3199
3200 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3201 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3202 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3203
3204 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3205 HeapFree(GetProcessHeap(), 0, agent_header);
3206 }
3207 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3208 {
3209 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3210 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3211 }
3212 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr