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