- Sync wininet with Wine 1.1.22. Tested on Firefox 2.0 and Downloader
[reactos.git] / reactos / dll / win32 / wininet / http.c
1 /*
2 * Wininet - Http Implementation
3 *
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 *
11 * Ulrich Czekalla
12 * David Hammerton
13 *
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
18 *
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
23 *
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 */
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #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 #include "inet_ntop.c"
70
71 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
72
73 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
74 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
75 static const WCHAR g_szReferer[] = {'R','e','f','e','r','e','r',0};
76 static const WCHAR g_szAccept[] = {'A','c','c','e','p','t',0};
77 static const WCHAR g_szUserAgent[] = {'U','s','e','r','-','A','g','e','n','t',0};
78 static const WCHAR szHost[] = { 'H','o','s','t',0 };
79 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
80 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
81 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
82 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
83 static const WCHAR szGET[] = { 'G','E','T', 0 };
84 static const WCHAR szCrLf[] = {'\r','\n', 0};
85
86 #define MAXHOSTNAME 100
87 #define MAX_FIELD_VALUE_LEN 256
88 #define MAX_FIELD_LEN 256
89
90 #define HTTP_REFERER g_szReferer
91 #define HTTP_ACCEPT g_szAccept
92 #define HTTP_USERAGENT g_szUserAgent
93
94 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
95 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
96 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
97 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
98 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
99 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
100 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
101
102 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
103
104 struct HttpAuthInfo
105 {
106 LPWSTR scheme;
107 CredHandle cred;
108 CtxtHandle ctx;
109 TimeStamp exp;
110 ULONG attr;
111 ULONG max_token;
112 void *auth_data;
113 unsigned int auth_data_len;
114 BOOL finished; /* finished authenticating */
115 };
116
117 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr);
118 static BOOL HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear);
119 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
120 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
121 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr);
122 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField, INT index, BOOL Request);
123 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index);
124 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
125 static BOOL HTTP_HttpQueryInfoW(LPWININETHTTPREQW, DWORD, LPVOID, LPDWORD, LPDWORD);
126 static LPWSTR HTTP_GetRedirectURL(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
127 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl);
128 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
129 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field);
130 static void HTTP_DrainContent(WININETHTTPREQW *req);
131 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr);
132
133 static LPHTTPHEADERW HTTP_GetHeader(LPWININETHTTPREQW req, LPCWSTR head)
134 {
135 int HeaderIndex = 0;
136 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
137 if (HeaderIndex == -1)
138 return NULL;
139 else
140 return &req->pCustHeaders[HeaderIndex];
141 }
142
143 /* set the request content length based on the headers */
144 static DWORD set_content_length( LPWININETHTTPREQW lpwhr )
145 {
146 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
147 WCHAR encoding[20];
148 DWORD size;
149
150 size = sizeof(lpwhr->dwContentLength);
151 if (!HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
152 &lpwhr->dwContentLength, &size, NULL))
153 lpwhr->dwContentLength = ~0u;
154
155 size = sizeof(encoding);
156 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) &&
157 !strcmpiW(encoding, szChunked))
158 {
159 lpwhr->dwContentLength = ~0u;
160 lpwhr->read_chunked = TRUE;
161 }
162
163 return lpwhr->dwContentLength;
164 }
165
166 /***********************************************************************
167 * HTTP_Tokenize (internal)
168 *
169 * Tokenize a string, allocating memory for the tokens.
170 */
171 static LPWSTR * HTTP_Tokenize(LPCWSTR string, LPCWSTR token_string)
172 {
173 LPWSTR * token_array;
174 int tokens = 0;
175 int i;
176 LPCWSTR next_token;
177
178 if (string)
179 {
180 /* empty string has no tokens */
181 if (*string)
182 tokens++;
183 /* count tokens */
184 for (i = 0; string[i]; i++)
185 {
186 if (!strncmpW(string+i, token_string, strlenW(token_string)))
187 {
188 DWORD j;
189 tokens++;
190 /* we want to skip over separators, but not the null terminator */
191 for (j = 0; j < strlenW(token_string) - 1; j++)
192 if (!string[i+j])
193 break;
194 i += j;
195 }
196 }
197 }
198
199 /* add 1 for terminating NULL */
200 token_array = HeapAlloc(GetProcessHeap(), 0, (tokens+1) * sizeof(*token_array));
201 token_array[tokens] = NULL;
202 if (!tokens)
203 return token_array;
204 for (i = 0; i < tokens; i++)
205 {
206 int len;
207 next_token = strstrW(string, token_string);
208 if (!next_token) next_token = string+strlenW(string);
209 len = next_token - string;
210 token_array[i] = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
211 memcpy(token_array[i], string, len*sizeof(WCHAR));
212 token_array[i][len] = '\0';
213 string = next_token+strlenW(token_string);
214 }
215 return token_array;
216 }
217
218 /***********************************************************************
219 * HTTP_FreeTokens (internal)
220 *
221 * Frees memory returned from HTTP_Tokenize.
222 */
223 static void HTTP_FreeTokens(LPWSTR * token_array)
224 {
225 int i;
226 for (i = 0; token_array[i]; i++)
227 HeapFree(GetProcessHeap(), 0, token_array[i]);
228 HeapFree(GetProcessHeap(), 0, token_array);
229 }
230
231 /* **********************************************************************
232 *
233 * Helper functions for the HttpSendRequest(Ex) functions
234 *
235 */
236 static void AsyncHttpSendRequestProc(WORKREQUEST *workRequest)
237 {
238 struct WORKREQ_HTTPSENDREQUESTW const *req = &workRequest->u.HttpSendRequestW;
239 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) workRequest->hdr;
240
241 TRACE("%p\n", lpwhr);
242
243 HTTP_HttpSendRequestW(lpwhr, req->lpszHeader,
244 req->dwHeaderLength, req->lpOptional, req->dwOptionalLength,
245 req->dwContentLength, req->bEndRequest);
246
247 HeapFree(GetProcessHeap(), 0, req->lpszHeader);
248 }
249
250 static void HTTP_FixURL( LPWININETHTTPREQW lpwhr)
251 {
252 static const WCHAR szSlash[] = { '/',0 };
253 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
254
255 /* If we don't have a path we set it to root */
256 if (NULL == lpwhr->lpszPath)
257 lpwhr->lpszPath = WININET_strdupW(szSlash);
258 else /* remove \r and \n*/
259 {
260 int nLen = strlenW(lpwhr->lpszPath);
261 while ((nLen >0 ) && ((lpwhr->lpszPath[nLen-1] == '\r')||(lpwhr->lpszPath[nLen-1] == '\n')))
262 {
263 nLen--;
264 lpwhr->lpszPath[nLen]='\0';
265 }
266 /* Replace '\' with '/' */
267 while (nLen>0) {
268 nLen--;
269 if (lpwhr->lpszPath[nLen] == '\\') lpwhr->lpszPath[nLen]='/';
270 }
271 }
272
273 if(CSTR_EQUAL != CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
274 lpwhr->lpszPath, strlenW(lpwhr->lpszPath), szHttp, strlenW(szHttp) )
275 && lpwhr->lpszPath[0] != '/') /* not an absolute path ?? --> fix it !! */
276 {
277 WCHAR *fixurl = HeapAlloc(GetProcessHeap(), 0,
278 (strlenW(lpwhr->lpszPath) + 2)*sizeof(WCHAR));
279 *fixurl = '/';
280 strcpyW(fixurl + 1, lpwhr->lpszPath);
281 HeapFree( GetProcessHeap(), 0, lpwhr->lpszPath );
282 lpwhr->lpszPath = fixurl;
283 }
284 }
285
286 static LPWSTR HTTP_BuildHeaderRequestString( LPWININETHTTPREQW lpwhr, LPCWSTR verb, LPCWSTR path, LPCWSTR version )
287 {
288 LPWSTR requestString;
289 DWORD len, n;
290 LPCWSTR *req;
291 UINT i;
292 LPWSTR p;
293
294 static const WCHAR szSpace[] = { ' ',0 };
295 static const WCHAR szColon[] = { ':',' ',0 };
296 static const WCHAR sztwocrlf[] = {'\r','\n','\r','\n', 0};
297
298 /* allocate space for an array of all the string pointers to be added */
299 len = (lpwhr->nCustHeaders)*4 + 10;
300 req = HeapAlloc( GetProcessHeap(), 0, len*sizeof(LPCWSTR) );
301
302 /* add the verb, path and HTTP version string */
303 n = 0;
304 req[n++] = verb;
305 req[n++] = szSpace;
306 req[n++] = path;
307 req[n++] = szSpace;
308 req[n++] = version;
309
310 /* Append custom request headers */
311 for (i = 0; i < lpwhr->nCustHeaders; i++)
312 {
313 if (lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST)
314 {
315 req[n++] = szCrLf;
316 req[n++] = lpwhr->pCustHeaders[i].lpszField;
317 req[n++] = szColon;
318 req[n++] = lpwhr->pCustHeaders[i].lpszValue;
319
320 TRACE("Adding custom header %s (%s)\n",
321 debugstr_w(lpwhr->pCustHeaders[i].lpszField),
322 debugstr_w(lpwhr->pCustHeaders[i].lpszValue));
323 }
324 }
325
326 if( n >= len )
327 ERR("oops. buffer overrun\n");
328
329 req[n] = NULL;
330 requestString = HTTP_build_req( req, 4 );
331 HeapFree( GetProcessHeap(), 0, req );
332
333 /*
334 * Set (header) termination string for request
335 * Make sure there's exactly two new lines at the end of the request
336 */
337 p = &requestString[strlenW(requestString)-1];
338 while ( (*p == '\n') || (*p == '\r') )
339 p--;
340 strcpyW( p+1, sztwocrlf );
341
342 return requestString;
343 }
344
345 static void HTTP_ProcessCookies( LPWININETHTTPREQW lpwhr )
346 {
347 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
348 int HeaderIndex;
349 int numCookies = 0;
350 LPHTTPHEADERW setCookieHeader;
351
352 while((HeaderIndex = HTTP_GetCustomHeaderIndex(lpwhr, szSet_Cookie, numCookies, FALSE)) != -1)
353 {
354 setCookieHeader = &lpwhr->pCustHeaders[HeaderIndex];
355
356 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES) && setCookieHeader->lpszValue)
357 {
358 int len;
359 static const WCHAR szFmt[] = { 'h','t','t','p',':','/','/','%','s','%','s',0};
360 LPWSTR buf_url;
361 LPHTTPHEADERW Host;
362
363 Host = HTTP_GetHeader(lpwhr,szHost);
364 len = lstrlenW(Host->lpszValue) + 9 + lstrlenW(lpwhr->lpszPath);
365 buf_url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
366 sprintfW(buf_url, szFmt, Host->lpszValue, lpwhr->lpszPath);
367 InternetSetCookieW(buf_url, NULL, setCookieHeader->lpszValue);
368
369 HeapFree(GetProcessHeap(), 0, buf_url);
370 }
371 numCookies++;
372 }
373 }
374
375 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue )
376 {
377 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
378 return !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
379 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
380 }
381
382 static BOOL HTTP_DoAuthorization( LPWININETHTTPREQW lpwhr, LPCWSTR pszAuthValue,
383 struct HttpAuthInfo **ppAuthInfo,
384 LPWSTR domain_and_username, LPWSTR password )
385 {
386 SECURITY_STATUS sec_status;
387 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
388 BOOL first = FALSE;
389
390 TRACE("%s\n", debugstr_w(pszAuthValue));
391
392 if (!pAuthInfo)
393 {
394 TimeStamp exp;
395
396 first = TRUE;
397 pAuthInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*pAuthInfo));
398 if (!pAuthInfo)
399 return FALSE;
400
401 SecInvalidateHandle(&pAuthInfo->cred);
402 SecInvalidateHandle(&pAuthInfo->ctx);
403 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
404 pAuthInfo->attr = 0;
405 pAuthInfo->auth_data = NULL;
406 pAuthInfo->auth_data_len = 0;
407 pAuthInfo->finished = FALSE;
408
409 if (is_basic_auth_value(pszAuthValue))
410 {
411 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
412 pAuthInfo->scheme = WININET_strdupW(szBasic);
413 if (!pAuthInfo->scheme)
414 {
415 HeapFree(GetProcessHeap(), 0, pAuthInfo);
416 return FALSE;
417 }
418 }
419 else
420 {
421 PVOID pAuthData;
422 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
423
424 pAuthInfo->scheme = WININET_strdupW(pszAuthValue);
425 if (!pAuthInfo->scheme)
426 {
427 HeapFree(GetProcessHeap(), 0, pAuthInfo);
428 return FALSE;
429 }
430
431 if (domain_and_username)
432 {
433 WCHAR *user = strchrW(domain_and_username, '\\');
434 WCHAR *domain = domain_and_username;
435
436 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
437
438 pAuthData = &nt_auth_identity;
439
440 if (user) user++;
441 else
442 {
443 user = domain_and_username;
444 domain = NULL;
445 }
446
447 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
448 nt_auth_identity.User = user;
449 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
450 nt_auth_identity.Domain = domain;
451 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
452 nt_auth_identity.Password = password;
453 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
454 }
455 else
456 /* use default credentials */
457 pAuthData = NULL;
458
459 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
460 SECPKG_CRED_OUTBOUND, NULL,
461 pAuthData, NULL,
462 NULL, &pAuthInfo->cred,
463 &exp);
464 if (sec_status == SEC_E_OK)
465 {
466 PSecPkgInfoW sec_pkg_info;
467 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
468 if (sec_status == SEC_E_OK)
469 {
470 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
471 FreeContextBuffer(sec_pkg_info);
472 }
473 }
474 if (sec_status != SEC_E_OK)
475 {
476 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
477 debugstr_w(pAuthInfo->scheme), sec_status);
478 HeapFree(GetProcessHeap(), 0, pAuthInfo->scheme);
479 HeapFree(GetProcessHeap(), 0, pAuthInfo);
480 return FALSE;
481 }
482 }
483 *ppAuthInfo = pAuthInfo;
484 }
485 else if (pAuthInfo->finished)
486 return FALSE;
487
488 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
489 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
490 {
491 ERR("authentication scheme changed from %s to %s\n",
492 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
493 return FALSE;
494 }
495
496 if (is_basic_auth_value(pszAuthValue))
497 {
498 int userlen;
499 int passlen;
500 char *auth_data;
501
502 TRACE("basic authentication\n");
503
504 /* we don't cache credentials for basic authentication, so we can't
505 * retrieve them if the application didn't pass us any credentials */
506 if (!domain_and_username) return FALSE;
507
508 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
509 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
510
511 /* length includes a nul terminator, which will be re-used for the ':' */
512 auth_data = HeapAlloc(GetProcessHeap(), 0, userlen + 1 + passlen);
513 if (!auth_data)
514 return FALSE;
515
516 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
517 auth_data[userlen] = ':';
518 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
519
520 pAuthInfo->auth_data = auth_data;
521 pAuthInfo->auth_data_len = userlen + 1 + passlen;
522 pAuthInfo->finished = TRUE;
523
524 return TRUE;
525 }
526 else
527 {
528 LPCWSTR pszAuthData;
529 SecBufferDesc out_desc, in_desc;
530 SecBuffer out, in;
531 unsigned char *buffer;
532 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
533 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
534
535 in.BufferType = SECBUFFER_TOKEN;
536 in.cbBuffer = 0;
537 in.pvBuffer = NULL;
538
539 in_desc.ulVersion = 0;
540 in_desc.cBuffers = 1;
541 in_desc.pBuffers = &in;
542
543 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
544 if (*pszAuthData == ' ')
545 {
546 pszAuthData++;
547 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
548 in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer);
549 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
550 }
551
552 buffer = HeapAlloc(GetProcessHeap(), 0, pAuthInfo->max_token);
553
554 out.BufferType = SECBUFFER_TOKEN;
555 out.cbBuffer = pAuthInfo->max_token;
556 out.pvBuffer = buffer;
557
558 out_desc.ulVersion = 0;
559 out_desc.cBuffers = 1;
560 out_desc.pBuffers = &out;
561
562 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
563 first ? NULL : &pAuthInfo->ctx,
564 first ? lpwhr->lpHttpSession->lpszServerName : NULL,
565 context_req, 0, SECURITY_NETWORK_DREP,
566 in.pvBuffer ? &in_desc : NULL,
567 0, &pAuthInfo->ctx, &out_desc,
568 &pAuthInfo->attr, &pAuthInfo->exp);
569 if (sec_status == SEC_E_OK)
570 {
571 pAuthInfo->finished = TRUE;
572 pAuthInfo->auth_data = out.pvBuffer;
573 pAuthInfo->auth_data_len = out.cbBuffer;
574 TRACE("sending last auth packet\n");
575 }
576 else if (sec_status == SEC_I_CONTINUE_NEEDED)
577 {
578 pAuthInfo->auth_data = out.pvBuffer;
579 pAuthInfo->auth_data_len = out.cbBuffer;
580 TRACE("sending next auth packet\n");
581 }
582 else
583 {
584 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
585 pAuthInfo->finished = TRUE;
586 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
587 return FALSE;
588 }
589 }
590
591 return TRUE;
592 }
593
594 /***********************************************************************
595 * HTTP_HttpAddRequestHeadersW (internal)
596 */
597 static BOOL HTTP_HttpAddRequestHeadersW(LPWININETHTTPREQW lpwhr,
598 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
599 {
600 LPWSTR lpszStart;
601 LPWSTR lpszEnd;
602 LPWSTR buffer;
603 BOOL bSuccess = FALSE;
604 DWORD len;
605
606 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
607
608 if( dwHeaderLength == ~0U )
609 len = strlenW(lpszHeader);
610 else
611 len = dwHeaderLength;
612 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR)*(len+1) );
613 lstrcpynW( buffer, lpszHeader, len + 1);
614
615 lpszStart = buffer;
616
617 do
618 {
619 LPWSTR * pFieldAndValue;
620
621 lpszEnd = lpszStart;
622
623 while (*lpszEnd != '\0')
624 {
625 if (*lpszEnd == '\r' && *(lpszEnd + 1) == '\n')
626 break;
627 lpszEnd++;
628 }
629
630 if (*lpszStart == '\0')
631 break;
632
633 if (*lpszEnd == '\r')
634 {
635 *lpszEnd = '\0';
636 lpszEnd += 2; /* Jump over \r\n */
637 }
638 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
639 if (*lpszStart == '\0')
640 {
641 /* Skip 0-length headers */
642 lpszStart = lpszEnd;
643 bSuccess = TRUE;
644 continue;
645 }
646 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
647 if (pFieldAndValue)
648 {
649 bSuccess = HTTP_VerifyValidHeader(lpwhr, pFieldAndValue[0]);
650 if (bSuccess)
651 bSuccess = HTTP_ProcessHeader(lpwhr, pFieldAndValue[0],
652 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
653 HTTP_FreeTokens(pFieldAndValue);
654 }
655
656 lpszStart = lpszEnd;
657 } while (bSuccess);
658
659 HeapFree(GetProcessHeap(), 0, buffer);
660
661 return bSuccess;
662 }
663
664 /***********************************************************************
665 * HttpAddRequestHeadersW (WININET.@)
666 *
667 * Adds one or more HTTP header to the request handler
668 *
669 * NOTE
670 * On Windows if dwHeaderLength includes the trailing '\0', then
671 * HttpAddRequestHeadersW() adds it too. However this results in an
672 * invalid Http header which is rejected by some servers so we probably
673 * don't need to match Windows on that point.
674 *
675 * RETURNS
676 * TRUE on success
677 * FALSE on failure
678 *
679 */
680 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
681 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
682 {
683 BOOL bSuccess = FALSE;
684 LPWININETHTTPREQW lpwhr;
685
686 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
687
688 if (!lpszHeader)
689 return TRUE;
690
691 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
692 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
693 {
694 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
695 goto lend;
696 }
697 bSuccess = HTTP_HttpAddRequestHeadersW( lpwhr, lpszHeader, dwHeaderLength, dwModifier );
698 lend:
699 if( lpwhr )
700 WININET_Release( &lpwhr->hdr );
701
702 return bSuccess;
703 }
704
705 /***********************************************************************
706 * HttpAddRequestHeadersA (WININET.@)
707 *
708 * Adds one or more HTTP header to the request handler
709 *
710 * RETURNS
711 * TRUE on success
712 * FALSE on failure
713 *
714 */
715 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
716 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
717 {
718 DWORD len;
719 LPWSTR hdr;
720 BOOL r;
721
722 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
723
724 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
725 hdr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
726 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
727 if( dwHeaderLength != ~0U )
728 dwHeaderLength = len;
729
730 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
731
732 HeapFree( GetProcessHeap(), 0, hdr );
733
734 return r;
735 }
736
737 /***********************************************************************
738 * HttpEndRequestA (WININET.@)
739 *
740 * Ends an HTTP request that was started by HttpSendRequestEx
741 *
742 * RETURNS
743 * TRUE if successful
744 * FALSE on failure
745 *
746 */
747 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
748 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
749 {
750 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
751
752 if (lpBuffersOut)
753 {
754 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
755 return FALSE;
756 }
757
758 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
759 }
760
761 static BOOL HTTP_HttpEndRequestW(LPWININETHTTPREQW lpwhr, DWORD dwFlags, DWORD_PTR dwContext)
762 {
763 BOOL rc = FALSE;
764 INT responseLen;
765 DWORD dwBufferSize;
766 INTERNET_ASYNC_RESULT iar;
767
768 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
769 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
770
771 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
772 if (responseLen)
773 rc = TRUE;
774
775 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
776 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
777
778 /* process cookies here. Is this right? */
779 HTTP_ProcessCookies(lpwhr);
780
781 if (!set_content_length( lpwhr )) HTTP_FinishedReading(lpwhr);
782
783 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
784 {
785 DWORD dwCode,dwCodeLength = sizeof(DWORD);
786 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE, &dwCode, &dwCodeLength, NULL) &&
787 (dwCode == 302 || dwCode == 301 || dwCode == 303))
788 {
789 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
790 dwBufferSize=sizeof(szNewLocation);
791 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL))
792 {
793 /* redirects are always GETs */
794 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
795 lpwhr->lpszVerb = WININET_strdupW(szGET);
796 HTTP_DrainContent(lpwhr);
797 if ((new_url = HTTP_GetRedirectURL( lpwhr, szNewLocation )))
798 {
799 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REDIRECT,
800 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
801 rc = HTTP_HandleRedirect(lpwhr, new_url);
802 if (rc)
803 rc = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, TRUE);
804 HeapFree( GetProcessHeap(), 0, new_url );
805 }
806 }
807 }
808 }
809
810 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
811 iar.dwError = rc ? 0 : INTERNET_GetLastError();
812
813 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
814 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
815 sizeof(INTERNET_ASYNC_RESULT));
816 return rc;
817 }
818
819 static void AsyncHttpEndRequestProc(WORKREQUEST *work)
820 {
821 struct WORKREQ_HTTPENDREQUESTW const *req = &work->u.HttpEndRequestW;
822 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)work->hdr;
823
824 TRACE("%p\n", lpwhr);
825
826 HTTP_HttpEndRequestW(lpwhr, req->dwFlags, req->dwContext);
827 }
828
829 /***********************************************************************
830 * HttpEndRequestW (WININET.@)
831 *
832 * Ends an HTTP request that was started by HttpSendRequestEx
833 *
834 * RETURNS
835 * TRUE if successful
836 * FALSE on failure
837 *
838 */
839 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
840 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
841 {
842 BOOL rc = FALSE;
843 LPWININETHTTPREQW lpwhr;
844
845 TRACE("-->\n");
846
847 if (lpBuffersOut)
848 {
849 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
850 return FALSE;
851 }
852
853 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
854
855 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
856 {
857 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
858 if (lpwhr)
859 WININET_Release( &lpwhr->hdr );
860 return FALSE;
861 }
862 lpwhr->hdr.dwFlags |= dwFlags;
863
864 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
865 {
866 WORKREQUEST work;
867 struct WORKREQ_HTTPENDREQUESTW *request;
868
869 work.asyncproc = AsyncHttpEndRequestProc;
870 work.hdr = WININET_AddRef( &lpwhr->hdr );
871
872 request = &work.u.HttpEndRequestW;
873 request->dwFlags = dwFlags;
874 request->dwContext = dwContext;
875
876 INTERNET_AsyncCall(&work);
877 INTERNET_SetLastError(ERROR_IO_PENDING);
878 }
879 else
880 rc = HTTP_HttpEndRequestW(lpwhr, dwFlags, dwContext);
881
882 WININET_Release( &lpwhr->hdr );
883 TRACE("%i <--\n",rc);
884 return rc;
885 }
886
887 /***********************************************************************
888 * HttpOpenRequestW (WININET.@)
889 *
890 * Open a HTTP request handle
891 *
892 * RETURNS
893 * HINTERNET a HTTP request handle on success
894 * NULL on failure
895 *
896 */
897 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
898 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
899 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
900 DWORD dwFlags, DWORD_PTR dwContext)
901 {
902 LPWININETHTTPSESSIONW lpwhs;
903 HINTERNET handle = NULL;
904
905 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
906 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
907 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
908 dwFlags, dwContext);
909 if(lpszAcceptTypes!=NULL)
910 {
911 int i;
912 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
913 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
914 }
915
916 lpwhs = (LPWININETHTTPSESSIONW) WININET_GetObject( hHttpSession );
917 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
918 {
919 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
920 goto lend;
921 }
922
923 /*
924 * My tests seem to show that the windows version does not
925 * become asynchronous until after this point. And anyhow
926 * if this call was asynchronous then how would you get the
927 * necessary HINTERNET pointer returned by this function.
928 *
929 */
930 handle = HTTP_HttpOpenRequestW(lpwhs, lpszVerb, lpszObjectName,
931 lpszVersion, lpszReferrer, lpszAcceptTypes,
932 dwFlags, dwContext);
933 lend:
934 if( lpwhs )
935 WININET_Release( &lpwhs->hdr );
936 TRACE("returning %p\n", handle);
937 return handle;
938 }
939
940
941 /***********************************************************************
942 * HttpOpenRequestA (WININET.@)
943 *
944 * Open a HTTP request handle
945 *
946 * RETURNS
947 * HINTERNET a HTTP request handle on success
948 * NULL on failure
949 *
950 */
951 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
952 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
953 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
954 DWORD dwFlags, DWORD_PTR dwContext)
955 {
956 LPWSTR szVerb = NULL, szObjectName = NULL;
957 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
958 INT len, acceptTypesCount;
959 HINTERNET rc = FALSE;
960 LPCSTR *types;
961
962 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
963 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
964 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
965 dwFlags, dwContext);
966
967 if (lpszVerb)
968 {
969 len = MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, NULL, 0 );
970 szVerb = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
971 if ( !szVerb )
972 goto end;
973 MultiByteToWideChar(CP_ACP, 0, lpszVerb, -1, szVerb, len);
974 }
975
976 if (lpszObjectName)
977 {
978 len = MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, NULL, 0 );
979 szObjectName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR) );
980 if ( !szObjectName )
981 goto end;
982 MultiByteToWideChar(CP_ACP, 0, lpszObjectName, -1, szObjectName, len );
983 }
984
985 if (lpszVersion)
986 {
987 len = MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, NULL, 0 );
988 szVersion = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
989 if ( !szVersion )
990 goto end;
991 MultiByteToWideChar(CP_ACP, 0, lpszVersion, -1, szVersion, len );
992 }
993
994 if (lpszReferrer)
995 {
996 len = MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, NULL, 0 );
997 szReferrer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
998 if ( !szReferrer )
999 goto end;
1000 MultiByteToWideChar(CP_ACP, 0, lpszReferrer, -1, szReferrer, len );
1001 }
1002
1003 if (lpszAcceptTypes)
1004 {
1005 acceptTypesCount = 0;
1006 types = lpszAcceptTypes;
1007 while (*types)
1008 {
1009 __TRY
1010 {
1011 /* find out how many there are */
1012 if (*types && **types)
1013 {
1014 TRACE("accept type: %s\n", debugstr_a(*types));
1015 acceptTypesCount++;
1016 }
1017 }
1018 __EXCEPT_PAGE_FAULT
1019 {
1020 WARN("invalid accept type pointer\n");
1021 }
1022 __ENDTRY;
1023 types++;
1024 }
1025 szAcceptTypes = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *) * (acceptTypesCount+1));
1026 if (!szAcceptTypes) goto end;
1027
1028 acceptTypesCount = 0;
1029 types = lpszAcceptTypes;
1030 while (*types)
1031 {
1032 __TRY
1033 {
1034 if (*types && **types)
1035 {
1036 len = MultiByteToWideChar(CP_ACP, 0, *types, -1, NULL, 0 );
1037 szAcceptTypes[acceptTypesCount] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1038
1039 MultiByteToWideChar(CP_ACP, 0, *types, -1, szAcceptTypes[acceptTypesCount], len);
1040 acceptTypesCount++;
1041 }
1042 }
1043 __EXCEPT_PAGE_FAULT
1044 {
1045 /* ignore invalid pointer */
1046 }
1047 __ENDTRY;
1048 types++;
1049 }
1050 szAcceptTypes[acceptTypesCount] = NULL;
1051 }
1052
1053 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName,
1054 szVersion, szReferrer,
1055 (LPCWSTR*)szAcceptTypes, dwFlags, dwContext);
1056
1057 end:
1058 if (szAcceptTypes)
1059 {
1060 acceptTypesCount = 0;
1061 while (szAcceptTypes[acceptTypesCount])
1062 {
1063 HeapFree(GetProcessHeap(), 0, szAcceptTypes[acceptTypesCount]);
1064 acceptTypesCount++;
1065 }
1066 HeapFree(GetProcessHeap(), 0, szAcceptTypes);
1067 }
1068 HeapFree(GetProcessHeap(), 0, szReferrer);
1069 HeapFree(GetProcessHeap(), 0, szVersion);
1070 HeapFree(GetProcessHeap(), 0, szObjectName);
1071 HeapFree(GetProcessHeap(), 0, szVerb);
1072
1073 return rc;
1074 }
1075
1076 /***********************************************************************
1077 * HTTP_EncodeBase64
1078 */
1079 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1080 {
1081 UINT n = 0, x;
1082 static const CHAR HTTP_Base64Enc[] =
1083 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1084
1085 while( len > 0 )
1086 {
1087 /* first 6 bits, all from bin[0] */
1088 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1089 x = (bin[0] & 3) << 4;
1090
1091 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1092 if( len == 1 )
1093 {
1094 base64[n++] = HTTP_Base64Enc[x];
1095 base64[n++] = '=';
1096 base64[n++] = '=';
1097 break;
1098 }
1099 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1100 x = ( bin[1] & 0x0f ) << 2;
1101
1102 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1103 if( len == 2 )
1104 {
1105 base64[n++] = HTTP_Base64Enc[x];
1106 base64[n++] = '=';
1107 break;
1108 }
1109 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1110
1111 /* last 6 bits, all from bin [2] */
1112 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1113 bin += 3;
1114 len -= 3;
1115 }
1116 base64[n] = 0;
1117 return n;
1118 }
1119
1120 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1121 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1122 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1123 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1124 static const signed char HTTP_Base64Dec[256] =
1125 {
1126 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1127 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1128 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1129 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1130 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1131 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1132 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1133 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1134 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1135 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1136 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1137 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1138 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1139 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1140 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1141 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1142 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1143 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1144 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1145 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1146 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1147 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1148 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1149 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1150 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1151 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1152 };
1153 #undef CH
1154
1155 /***********************************************************************
1156 * HTTP_DecodeBase64
1157 */
1158 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1159 {
1160 unsigned int n = 0;
1161
1162 while(*base64)
1163 {
1164 signed char in[4];
1165
1166 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1167 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1168 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1169 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1170 {
1171 WARN("invalid base64: %s\n", debugstr_w(base64));
1172 return 0;
1173 }
1174 if (bin)
1175 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1176 n++;
1177
1178 if ((base64[2] == '=') && (base64[3] == '='))
1179 break;
1180 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1181 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1182 {
1183 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1184 return 0;
1185 }
1186 if (bin)
1187 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1188 n++;
1189
1190 if (base64[3] == '=')
1191 break;
1192 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1193 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1194 {
1195 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1196 return 0;
1197 }
1198 if (bin)
1199 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1200 n++;
1201
1202 base64 += 4;
1203 }
1204
1205 return n;
1206 }
1207
1208 /***********************************************************************
1209 * HTTP_InsertAuthorization
1210 *
1211 * Insert or delete the authorization field in the request header.
1212 */
1213 static BOOL HTTP_InsertAuthorization( LPWININETHTTPREQW lpwhr, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1214 {
1215 if (pAuthInfo)
1216 {
1217 static const WCHAR wszSpace[] = {' ',0};
1218 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1219 unsigned int len;
1220 WCHAR *authorization = NULL;
1221
1222 if (pAuthInfo->auth_data_len)
1223 {
1224 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1225 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1226 authorization = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(WCHAR));
1227 if (!authorization)
1228 return FALSE;
1229
1230 strcpyW(authorization, pAuthInfo->scheme);
1231 strcatW(authorization, wszSpace);
1232 HTTP_EncodeBase64(pAuthInfo->auth_data,
1233 pAuthInfo->auth_data_len,
1234 authorization+strlenW(authorization));
1235
1236 /* clear the data as it isn't valid now that it has been sent to the
1237 * server, unless it's Basic authentication which doesn't do
1238 * connection tracking */
1239 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1240 {
1241 HeapFree(GetProcessHeap(), 0, pAuthInfo->auth_data);
1242 pAuthInfo->auth_data = NULL;
1243 pAuthInfo->auth_data_len = 0;
1244 }
1245 }
1246
1247 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1248
1249 HTTP_ProcessHeader(lpwhr, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1250
1251 HeapFree(GetProcessHeap(), 0, authorization);
1252 }
1253 return TRUE;
1254 }
1255
1256 static WCHAR *HTTP_BuildProxyRequestUrl(WININETHTTPREQW *req)
1257 {
1258 WCHAR new_location[INTERNET_MAX_URL_LENGTH], *url;
1259 DWORD size;
1260
1261 size = sizeof(new_location);
1262 if (HTTP_HttpQueryInfoW(req, HTTP_QUERY_LOCATION, new_location, &size, NULL))
1263 {
1264 if (!(url = HeapAlloc( GetProcessHeap(), 0, size + sizeof(WCHAR) ))) return NULL;
1265 strcpyW( url, new_location );
1266 }
1267 else
1268 {
1269 static const WCHAR slash[] = { '/',0 };
1270 static const WCHAR format[] = { 'h','t','t','p',':','/','/','%','s',':','%','d',0 };
1271 static const WCHAR formatSSL[] = { 'h','t','t','p','s',':','/','/','%','s',':','%','d',0 };
1272 WININETHTTPSESSIONW *session = req->lpHttpSession;
1273
1274 size = 16; /* "https://" + sizeof(port#) + ":/\0" */
1275 size += strlenW( session->lpszHostName ) + strlenW( req->lpszPath );
1276
1277 if (!(url = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
1278
1279 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1280 sprintfW( url, formatSSL, session->lpszHostName, session->nHostPort );
1281 else
1282 sprintfW( url, format, session->lpszHostName, session->nHostPort );
1283 if (req->lpszPath[0] != '/') strcatW( url, slash );
1284 strcatW( url, req->lpszPath );
1285 }
1286 TRACE("url=%s\n", debugstr_w(url));
1287 return url;
1288 }
1289
1290 /***********************************************************************
1291 * HTTP_DealWithProxy
1292 */
1293 static BOOL HTTP_DealWithProxy( LPWININETAPPINFOW hIC,
1294 LPWININETHTTPSESSIONW lpwhs, LPWININETHTTPREQW lpwhr)
1295 {
1296 WCHAR buf[MAXHOSTNAME];
1297 WCHAR proxy[MAXHOSTNAME + 15]; /* 15 == "http://" + sizeof(port#) + ":/\0" */
1298 static WCHAR szNul[] = { 0 };
1299 URL_COMPONENTSW UrlComponents;
1300 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1301 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1302
1303 memset( &UrlComponents, 0, sizeof UrlComponents );
1304 UrlComponents.dwStructSize = sizeof UrlComponents;
1305 UrlComponents.lpszHostName = buf;
1306 UrlComponents.dwHostNameLength = MAXHOSTNAME;
1307
1308 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1309 hIC->lpszProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1310 sprintfW(proxy, szFormat, hIC->lpszProxy);
1311 else
1312 strcpyW(proxy, hIC->lpszProxy);
1313 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1314 return FALSE;
1315 if( UrlComponents.dwHostNameLength == 0 )
1316 return FALSE;
1317
1318 if( !lpwhr->lpszPath )
1319 lpwhr->lpszPath = szNul;
1320
1321 if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1322 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1323
1324 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
1325 lpwhs->lpszServerName = WININET_strdupW(UrlComponents.lpszHostName);
1326 lpwhs->nServerPort = UrlComponents.nPort;
1327
1328 TRACE("proxy server=%s port=%d\n", debugstr_w(lpwhs->lpszServerName), lpwhs->nServerPort);
1329 return TRUE;
1330 }
1331
1332 static BOOL HTTP_ResolveName(LPWININETHTTPREQW lpwhr)
1333 {
1334 char szaddr[32];
1335 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
1336
1337 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1338 INTERNET_STATUS_RESOLVING_NAME,
1339 lpwhs->lpszServerName,
1340 strlenW(lpwhs->lpszServerName)+1);
1341
1342 if (!GetAddress(lpwhs->lpszServerName, lpwhs->nServerPort,
1343 &lpwhs->socketAddress))
1344 {
1345 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
1346 return FALSE;
1347 }
1348
1349 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
1350 szaddr, sizeof(szaddr));
1351 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1352 INTERNET_STATUS_NAME_RESOLVED,
1353 szaddr, strlen(szaddr)+1);
1354
1355 TRACE("resolved %s to %s\n", debugstr_w(lpwhs->lpszServerName), szaddr);
1356 return TRUE;
1357 }
1358
1359
1360 /***********************************************************************
1361 * HTTPREQ_Destroy (internal)
1362 *
1363 * Deallocate request handle
1364 *
1365 */
1366 static void HTTPREQ_Destroy(WININETHANDLEHEADER *hdr)
1367 {
1368 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1369 DWORD i;
1370
1371 TRACE("\n");
1372
1373 if(lpwhr->hCacheFile)
1374 CloseHandle(lpwhr->hCacheFile);
1375
1376 if(lpwhr->lpszCacheFile) {
1377 DeleteFileW(lpwhr->lpszCacheFile); /* FIXME */
1378 HeapFree(GetProcessHeap(), 0, lpwhr->lpszCacheFile);
1379 }
1380
1381 WININET_Release(&lpwhr->lpHttpSession->hdr);
1382
1383 if (lpwhr->pAuthInfo)
1384 {
1385 if (SecIsValidHandle(&lpwhr->pAuthInfo->ctx))
1386 DeleteSecurityContext(&lpwhr->pAuthInfo->ctx);
1387 if (SecIsValidHandle(&lpwhr->pAuthInfo->cred))
1388 FreeCredentialsHandle(&lpwhr->pAuthInfo->cred);
1389
1390 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->auth_data);
1391 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo->scheme);
1392 HeapFree(GetProcessHeap(), 0, lpwhr->pAuthInfo);
1393 lpwhr->pAuthInfo = NULL;
1394 }
1395
1396 if (lpwhr->pProxyAuthInfo)
1397 {
1398 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->ctx))
1399 DeleteSecurityContext(&lpwhr->pProxyAuthInfo->ctx);
1400 if (SecIsValidHandle(&lpwhr->pProxyAuthInfo->cred))
1401 FreeCredentialsHandle(&lpwhr->pProxyAuthInfo->cred);
1402
1403 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->auth_data);
1404 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo->scheme);
1405 HeapFree(GetProcessHeap(), 0, lpwhr->pProxyAuthInfo);
1406 lpwhr->pProxyAuthInfo = NULL;
1407 }
1408
1409 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
1410 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
1411 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
1412 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVersion);
1413 HeapFree(GetProcessHeap(), 0, lpwhr->lpszStatusText);
1414
1415 for (i = 0; i < lpwhr->nCustHeaders; i++)
1416 {
1417 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszField);
1418 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[i].lpszValue);
1419 }
1420
1421 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders);
1422 HeapFree(GetProcessHeap(), 0, lpwhr);
1423 }
1424
1425 static void HTTPREQ_CloseConnection(WININETHANDLEHEADER *hdr)
1426 {
1427 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW) hdr;
1428
1429 TRACE("%p\n",lpwhr);
1430
1431 if (!NETCON_connected(&lpwhr->netConnection))
1432 return;
1433
1434 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1435 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1436
1437 NETCON_close(&lpwhr->netConnection);
1438
1439 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
1440 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1441 }
1442
1443 static DWORD HTTPREQ_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1444 {
1445 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1446
1447 switch(option) {
1448 case INTERNET_OPTION_HANDLE_TYPE:
1449 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1450
1451 if (*size < sizeof(ULONG))
1452 return ERROR_INSUFFICIENT_BUFFER;
1453
1454 *size = sizeof(DWORD);
1455 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
1456 return ERROR_SUCCESS;
1457
1458 case INTERNET_OPTION_URL: {
1459 WCHAR url[INTERNET_MAX_URL_LENGTH];
1460 HTTPHEADERW *host;
1461 DWORD len;
1462 WCHAR *pch;
1463
1464 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
1465 static const WCHAR hostW[] = {'H','o','s','t',0};
1466
1467 TRACE("INTERNET_OPTION_URL\n");
1468
1469 host = HTTP_GetHeader(req, hostW);
1470 strcpyW(url, httpW);
1471 strcatW(url, host->lpszValue);
1472 if (NULL != (pch = strchrW(url + strlenW(httpW), ':')))
1473 *pch = 0;
1474 strcatW(url, req->lpszPath);
1475
1476 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
1477
1478 if(unicode) {
1479 len = (strlenW(url)+1) * sizeof(WCHAR);
1480 if(*size < len)
1481 return ERROR_INSUFFICIENT_BUFFER;
1482
1483 *size = len;
1484 strcpyW(buffer, url);
1485 return ERROR_SUCCESS;
1486 }else {
1487 len = WideCharToMultiByte(CP_ACP, 0, url, -1, buffer, *size, NULL, NULL);
1488 if(len > *size)
1489 return ERROR_INSUFFICIENT_BUFFER;
1490
1491 *size = len;
1492 return ERROR_SUCCESS;
1493 }
1494 }
1495
1496 case INTERNET_OPTION_DATAFILE_NAME: {
1497 DWORD req_size;
1498
1499 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1500
1501 if(!req->lpszCacheFile) {
1502 *size = 0;
1503 return ERROR_INTERNET_ITEM_NOT_FOUND;
1504 }
1505
1506 if(unicode) {
1507 req_size = (lstrlenW(req->lpszCacheFile)+1) * sizeof(WCHAR);
1508 if(*size < req_size)
1509 return ERROR_INSUFFICIENT_BUFFER;
1510
1511 *size = req_size;
1512 memcpy(buffer, req->lpszCacheFile, *size);
1513 return ERROR_SUCCESS;
1514 }else {
1515 req_size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile, -1, NULL, 0, NULL, NULL);
1516 if (req_size > *size)
1517 return ERROR_INSUFFICIENT_BUFFER;
1518
1519 *size = WideCharToMultiByte(CP_ACP, 0, req->lpszCacheFile,
1520 -1, buffer, *size, NULL, NULL);
1521 return ERROR_SUCCESS;
1522 }
1523 }
1524
1525 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
1526 PCCERT_CONTEXT context;
1527
1528 if(*size < sizeof(INTERNET_CERTIFICATE_INFOW)) {
1529 *size = sizeof(INTERNET_CERTIFICATE_INFOW);
1530 return ERROR_INSUFFICIENT_BUFFER;
1531 }
1532
1533 context = (PCCERT_CONTEXT)NETCON_GetCert(&(req->netConnection));
1534 if(context) {
1535 INTERNET_CERTIFICATE_INFOW *info = (INTERNET_CERTIFICATE_INFOW*)buffer;
1536 DWORD len;
1537
1538 memset(info, 0, sizeof(INTERNET_CERTIFICATE_INFOW));
1539 info->ftExpiry = context->pCertInfo->NotAfter;
1540 info->ftStart = context->pCertInfo->NotBefore;
1541 if(unicode) {
1542 len = CertNameToStrW(context->dwCertEncodingType,
1543 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1544 info->lpszSubjectInfo = LocalAlloc(0, len*sizeof(WCHAR));
1545 if(info->lpszSubjectInfo)
1546 CertNameToStrW(context->dwCertEncodingType,
1547 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1548 info->lpszSubjectInfo, len);
1549 len = CertNameToStrW(context->dwCertEncodingType,
1550 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1551 info->lpszIssuerInfo = LocalAlloc(0, len*sizeof(WCHAR));
1552 if (info->lpszIssuerInfo)
1553 CertNameToStrW(context->dwCertEncodingType,
1554 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1555 info->lpszIssuerInfo, len);
1556 }else {
1557 INTERNET_CERTIFICATE_INFOA *infoA = (INTERNET_CERTIFICATE_INFOA*)info;
1558
1559 len = CertNameToStrA(context->dwCertEncodingType,
1560 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR, NULL, 0);
1561 infoA->lpszSubjectInfo = LocalAlloc(0, len);
1562 if(infoA->lpszSubjectInfo)
1563 CertNameToStrA(context->dwCertEncodingType,
1564 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR,
1565 infoA->lpszSubjectInfo, len);
1566 len = CertNameToStrA(context->dwCertEncodingType,
1567 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR, NULL, 0);
1568 infoA->lpszIssuerInfo = LocalAlloc(0, len);
1569 if(infoA->lpszIssuerInfo)
1570 CertNameToStrA(context->dwCertEncodingType,
1571 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR,
1572 infoA->lpszIssuerInfo, len);
1573 }
1574
1575 /*
1576 * Contrary to MSDN, these do not appear to be set.
1577 * lpszProtocolName
1578 * lpszSignatureAlgName
1579 * lpszEncryptionAlgName
1580 * dwKeySize
1581 */
1582 CertFreeCertificateContext(context);
1583 return ERROR_SUCCESS;
1584 }
1585 }
1586 }
1587
1588 return INET_QueryOption(option, buffer, size, unicode);
1589 }
1590
1591 static DWORD HTTPREQ_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
1592 {
1593 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1594
1595 switch(option) {
1596 case INTERNET_OPTION_SEND_TIMEOUT:
1597 case INTERNET_OPTION_RECEIVE_TIMEOUT:
1598 TRACE("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
1599
1600 if (size != sizeof(DWORD))
1601 return ERROR_INVALID_PARAMETER;
1602
1603 return NETCON_set_timeout(&req->netConnection, option == INTERNET_OPTION_SEND_TIMEOUT,
1604 *(DWORD*)buffer);
1605
1606 case INTERNET_OPTION_USERNAME:
1607 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszUserName);
1608 if (!(req->lpHttpSession->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1609 return ERROR_SUCCESS;
1610
1611 case INTERNET_OPTION_PASSWORD:
1612 HeapFree(GetProcessHeap(), 0, req->lpHttpSession->lpszPassword);
1613 if (!(req->lpHttpSession->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
1614 return ERROR_SUCCESS;
1615 }
1616
1617 return ERROR_INTERNET_INVALID_OPTION;
1618 }
1619
1620 /* read some more data into the read buffer */
1621 static BOOL read_more_data( WININETHTTPREQW *req, int maxlen )
1622 {
1623 int len;
1624
1625 if (req->read_size && req->read_pos)
1626 {
1627 /* move existing data to the start of the buffer */
1628 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
1629 req->read_pos = 0;
1630 }
1631
1632 if (maxlen == -1) maxlen = sizeof(req->read_buf);
1633 if (!NETCON_recv( &req->netConnection, req->read_buf + req->read_size,
1634 maxlen - req->read_size, 0, &len )) return FALSE;
1635 req->read_size += len;
1636 return TRUE;
1637 }
1638
1639 /* remove some amount of data from the read buffer */
1640 static void remove_data( WININETHTTPREQW *req, int count )
1641 {
1642 if (!(req->read_size -= count)) req->read_pos = 0;
1643 else req->read_pos += count;
1644 }
1645
1646 static BOOL read_line( WININETHTTPREQW *req, LPSTR buffer, DWORD *len )
1647 {
1648 int count, bytes_read, pos = 0;
1649
1650 for (;;)
1651 {
1652 char *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
1653
1654 if (eol)
1655 {
1656 count = eol - (req->read_buf + req->read_pos);
1657 bytes_read = count + 1;
1658 }
1659 else count = bytes_read = req->read_size;
1660
1661 count = min( count, *len - pos );
1662 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
1663 pos += count;
1664 remove_data( req, bytes_read );
1665 if (eol) break;
1666
1667 if (!read_more_data( req, -1 )) return FALSE;
1668 if (!req->read_size)
1669 {
1670 *len = 0;
1671 TRACE( "returning empty string\n" );
1672 return FALSE;
1673 }
1674 }
1675
1676 if (pos < *len)
1677 {
1678 if (pos && buffer[pos - 1] == '\r') pos--;
1679 *len = pos + 1;
1680 }
1681 buffer[*len - 1] = 0;
1682 TRACE( "returning %s\n", debugstr_a(buffer));
1683 return TRUE;
1684 }
1685
1686 /* discard data contents until we reach end of line */
1687 static BOOL discard_eol( WININETHTTPREQW *req )
1688 {
1689 do
1690 {
1691 char *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
1692 if (eol)
1693 {
1694 remove_data( req, (eol + 1) - (req->read_buf + req->read_pos) );
1695 break;
1696 }
1697 req->read_pos = req->read_size = 0; /* discard everything */
1698 if (!read_more_data( req, -1 )) return FALSE;
1699 } while (req->read_size);
1700 return TRUE;
1701 }
1702
1703 /* read the size of the next chunk */
1704 static BOOL start_next_chunk( WININETHTTPREQW *req )
1705 {
1706 DWORD chunk_size = 0;
1707
1708 if (!req->dwContentLength) return TRUE;
1709 if (req->dwContentLength == req->dwContentRead)
1710 {
1711 /* read terminator for the previous chunk */
1712 if (!discard_eol( req )) return FALSE;
1713 req->dwContentLength = ~0u;
1714 req->dwContentRead = 0;
1715 }
1716 for (;;)
1717 {
1718 while (req->read_size)
1719 {
1720 char ch = req->read_buf[req->read_pos];
1721 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1722 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1723 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1724 else if (ch == ';' || ch == '\r' || ch == '\n')
1725 {
1726 TRACE( "reading %u byte chunk\n", chunk_size );
1727 req->dwContentLength = chunk_size;
1728 req->dwContentRead = 0;
1729 if (!discard_eol( req )) return FALSE;
1730 return TRUE;
1731 }
1732 remove_data( req, 1 );
1733 }
1734 if (!read_more_data( req, -1 )) return FALSE;
1735 if (!req->read_size)
1736 {
1737 req->dwContentLength = req->dwContentRead = 0;
1738 return TRUE;
1739 }
1740 }
1741 }
1742
1743 /* return the size of data available to be read immediately */
1744 static DWORD get_avail_data( WININETHTTPREQW *req )
1745 {
1746 if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
1747 return 0;
1748 return min( req->read_size, req->dwContentLength - req->dwContentRead );
1749 }
1750
1751 /* check if we have reached the end of the data to read */
1752 static BOOL end_of_read_data( WININETHTTPREQW *req )
1753 {
1754 if (req->read_chunked) return (req->dwContentLength == 0);
1755 if (req->dwContentLength == ~0u) return FALSE;
1756 return (req->dwContentLength == req->dwContentRead);
1757 }
1758
1759 static BOOL refill_buffer( WININETHTTPREQW *req )
1760 {
1761 int len = sizeof(req->read_buf);
1762
1763 if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
1764 {
1765 if (!start_next_chunk( req )) return FALSE;
1766 }
1767
1768 if (req->dwContentLength != ~0u) len = min( len, req->dwContentLength - req->dwContentRead );
1769 if (len <= req->read_size) return TRUE;
1770
1771 if (!read_more_data( req, len )) return FALSE;
1772 if (!req->read_size) req->dwContentLength = req->dwContentRead = 0;
1773 return TRUE;
1774 }
1775
1776 static void HTTP_ReceiveRequestData(WININETHTTPREQW *req, BOOL first_notif)
1777 {
1778 INTERNET_ASYNC_RESULT iar;
1779
1780 TRACE("%p\n", req);
1781
1782 if (refill_buffer( req )) {
1783 iar.dwResult = (DWORD_PTR)req->hdr.hInternet;
1784 iar.dwError = first_notif ? 0 : get_avail_data(req);
1785 }else {
1786 iar.dwResult = 0;
1787 iar.dwError = INTERNET_GetLastError();
1788 }
1789
1790 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1791 sizeof(INTERNET_ASYNC_RESULT));
1792 }
1793
1794 static DWORD HTTPREQ_Read(WININETHTTPREQW *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
1795 {
1796 int len, bytes_read = 0;
1797
1798 if (req->read_chunked && (req->dwContentLength == ~0u || req->dwContentLength == req->dwContentRead))
1799 {
1800 if (!start_next_chunk( req )) goto done;
1801 }
1802 if (req->dwContentLength != ~0u) size = min( size, req->dwContentLength - req->dwContentRead );
1803
1804 if (req->read_size)
1805 {
1806 bytes_read = min( req->read_size, size );
1807 memcpy( buffer, req->read_buf + req->read_pos, bytes_read );
1808 remove_data( req, bytes_read );
1809 }
1810
1811 if (size > bytes_read && (!bytes_read || sync))
1812 {
1813 if (NETCON_recv( &req->netConnection, (char *)buffer + bytes_read, size - bytes_read,
1814 sync ? MSG_WAITALL : 0, &len))
1815 bytes_read += len;
1816 /* always return success, even if the network layer returns an error */
1817 }
1818 done:
1819 req->dwContentRead += bytes_read;
1820 *read = bytes_read;
1821
1822 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, req->dwContentRead, req->dwContentLength );
1823 if(req->lpszCacheFile) {
1824 BOOL res;
1825 DWORD dwBytesWritten;
1826
1827 res = WriteFile(req->hCacheFile, buffer, bytes_read, &dwBytesWritten, NULL);
1828 if(!res)
1829 WARN("WriteFile failed: %u\n", GetLastError());
1830 }
1831
1832 if(!bytes_read && (req->dwContentRead == req->dwContentLength))
1833 HTTP_FinishedReading(req);
1834
1835 return ERROR_SUCCESS;
1836 }
1837
1838
1839 static DWORD HTTPREQ_ReadFile(WININETHANDLEHEADER *hdr, void *buffer, DWORD size, DWORD *read)
1840 {
1841 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1842 return HTTPREQ_Read(req, buffer, size, read, TRUE);
1843 }
1844
1845 static void HTTPREQ_AsyncReadFileExAProc(WORKREQUEST *workRequest)
1846 {
1847 struct WORKREQ_INTERNETREADFILEEXA const *data = &workRequest->u.InternetReadFileExA;
1848 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1849 INTERNET_ASYNC_RESULT iar;
1850 DWORD res;
1851
1852 TRACE("INTERNETREADFILEEXA %p\n", workRequest->hdr);
1853
1854 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1855 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1856
1857 iar.dwResult = res == ERROR_SUCCESS;
1858 iar.dwError = res;
1859
1860 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1861 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1862 sizeof(INTERNET_ASYNC_RESULT));
1863 }
1864
1865 static DWORD HTTPREQ_ReadFileExA(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSA *buffers,
1866 DWORD flags, DWORD_PTR context)
1867 {
1868
1869 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1870 DWORD res;
1871
1872 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1873 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1874
1875 if (buffers->dwStructSize != sizeof(*buffers))
1876 return ERROR_INVALID_PARAMETER;
1877
1878 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1879
1880 if ((hdr->dwFlags & INTERNET_FLAG_ASYNC) && !get_avail_data(req))
1881 {
1882 WORKREQUEST workRequest;
1883
1884 workRequest.asyncproc = HTTPREQ_AsyncReadFileExAProc;
1885 workRequest.hdr = WININET_AddRef(&req->hdr);
1886 workRequest.u.InternetReadFileExA.lpBuffersOut = buffers;
1887
1888 INTERNET_AsyncCall(&workRequest);
1889
1890 return ERROR_IO_PENDING;
1891 }
1892
1893 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1894 !(flags & IRF_NO_WAIT));
1895
1896 if (res == ERROR_SUCCESS) {
1897 DWORD size = buffers->dwBufferLength;
1898 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1899 &size, sizeof(size));
1900 }
1901
1902 return res;
1903 }
1904
1905 static void HTTPREQ_AsyncReadFileExWProc(WORKREQUEST *workRequest)
1906 {
1907 struct WORKREQ_INTERNETREADFILEEXW const *data = &workRequest->u.InternetReadFileExW;
1908 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1909 INTERNET_ASYNC_RESULT iar;
1910 DWORD res;
1911
1912 TRACE("INTERNETREADFILEEXW %p\n", workRequest->hdr);
1913
1914 res = HTTPREQ_Read(req, data->lpBuffersOut->lpvBuffer,
1915 data->lpBuffersOut->dwBufferLength, &data->lpBuffersOut->dwBufferLength, TRUE);
1916
1917 iar.dwResult = res == ERROR_SUCCESS;
1918 iar.dwError = res;
1919
1920 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1921 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1922 sizeof(INTERNET_ASYNC_RESULT));
1923 }
1924
1925 static DWORD HTTPREQ_ReadFileExW(WININETHANDLEHEADER *hdr, INTERNET_BUFFERSW *buffers,
1926 DWORD flags, DWORD_PTR context)
1927 {
1928
1929 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1930 DWORD res;
1931
1932 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
1933 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
1934
1935 if (buffers->dwStructSize != sizeof(*buffers))
1936 return ERROR_INVALID_PARAMETER;
1937
1938 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
1939
1940 if ((hdr->dwFlags & INTERNET_FLAG_ASYNC) && !get_avail_data(req))
1941 {
1942 WORKREQUEST workRequest;
1943
1944 workRequest.asyncproc = HTTPREQ_AsyncReadFileExWProc;
1945 workRequest.hdr = WININET_AddRef(&req->hdr);
1946 workRequest.u.InternetReadFileExW.lpBuffersOut = buffers;
1947
1948 INTERNET_AsyncCall(&workRequest);
1949
1950 return ERROR_IO_PENDING;
1951 }
1952
1953 res = HTTPREQ_Read(req, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength,
1954 !(flags & IRF_NO_WAIT));
1955
1956 if (res == ERROR_SUCCESS) {
1957 DWORD size = buffers->dwBufferLength;
1958 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
1959 &size, sizeof(size));
1960 }
1961
1962 return res;
1963 }
1964
1965 static BOOL HTTPREQ_WriteFile(WININETHANDLEHEADER *hdr, const void *buffer, DWORD size, DWORD *written)
1966 {
1967 BOOL ret;
1968 LPWININETHTTPREQW lpwhr = (LPWININETHTTPREQW)hdr;
1969
1970 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
1971
1972 *written = 0;
1973 if ((ret = NETCON_send(&lpwhr->netConnection, buffer, size, 0, (LPINT)written)))
1974 lpwhr->dwBytesWritten += *written;
1975
1976 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
1977 return ret;
1978 }
1979
1980 static void HTTPREQ_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1981 {
1982 WININETHTTPREQW *req = (WININETHTTPREQW*)workRequest->hdr;
1983
1984 HTTP_ReceiveRequestData(req, FALSE);
1985 }
1986
1987 static DWORD HTTPREQ_QueryDataAvailable(WININETHANDLEHEADER *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1988 {
1989 WININETHTTPREQW *req = (WININETHTTPREQW*)hdr;
1990
1991 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
1992
1993 if (!(*available = get_avail_data( req )))
1994 {
1995 if (end_of_read_data( req )) return ERROR_SUCCESS;
1996
1997 if (req->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1998 {
1999 WORKREQUEST workRequest;
2000
2001 workRequest.asyncproc = HTTPREQ_AsyncQueryDataAvailableProc;
2002 workRequest.hdr = WININET_AddRef( &req->hdr );
2003
2004 INTERNET_AsyncCall(&workRequest);
2005
2006 return ERROR_IO_PENDING;
2007 }
2008 else
2009 {
2010 refill_buffer( req );
2011 *available = get_avail_data( req );
2012 }
2013 }
2014
2015 if (*available == sizeof(req->read_buf)) /* check if we have even more pending in the socket */
2016 {
2017 DWORD extra;
2018 if (NETCON_query_data_available(&req->netConnection, &extra))
2019 *available = min( *available + extra, req->dwContentLength - req->dwContentRead );
2020 }
2021
2022 TRACE( "returning %u\n", *available );
2023 return ERROR_SUCCESS;
2024 }
2025
2026 static const HANDLEHEADERVtbl HTTPREQVtbl = {
2027 HTTPREQ_Destroy,
2028 HTTPREQ_CloseConnection,
2029 HTTPREQ_QueryOption,
2030 HTTPREQ_SetOption,
2031 HTTPREQ_ReadFile,
2032 HTTPREQ_ReadFileExA,
2033 HTTPREQ_ReadFileExW,
2034 HTTPREQ_WriteFile,
2035 HTTPREQ_QueryDataAvailable,
2036 NULL
2037 };
2038
2039 /***********************************************************************
2040 * HTTP_HttpOpenRequestW (internal)
2041 *
2042 * Open a HTTP request handle
2043 *
2044 * RETURNS
2045 * HINTERNET a HTTP request handle on success
2046 * NULL on failure
2047 *
2048 */
2049 HINTERNET WINAPI HTTP_HttpOpenRequestW(LPWININETHTTPSESSIONW lpwhs,
2050 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
2051 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
2052 DWORD dwFlags, DWORD_PTR dwContext)
2053 {
2054 LPWININETAPPINFOW hIC = NULL;
2055 LPWININETHTTPREQW lpwhr;
2056 LPWSTR lpszHostName = NULL;
2057 HINTERNET handle = NULL;
2058 static const WCHAR szHostForm[] = {'%','s',':','%','u',0};
2059 DWORD len;
2060
2061 TRACE("-->\n");
2062
2063 assert( lpwhs->hdr.htype == WH_HHTTPSESSION );
2064 hIC = lpwhs->lpAppInfo;
2065
2066 lpwhr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPREQW));
2067 if (NULL == lpwhr)
2068 {
2069 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2070 goto lend;
2071 }
2072 lpwhr->hdr.htype = WH_HHTTPREQ;
2073 lpwhr->hdr.vtbl = &HTTPREQVtbl;
2074 lpwhr->hdr.dwFlags = dwFlags;
2075 lpwhr->hdr.dwContext = dwContext;
2076 lpwhr->hdr.refs = 1;
2077 lpwhr->hdr.lpfnStatusCB = lpwhs->hdr.lpfnStatusCB;
2078 lpwhr->hdr.dwInternalFlags = lpwhs->hdr.dwInternalFlags & INET_CALLBACKW;
2079 lpwhr->dwContentLength = ~0u;
2080
2081 WININET_AddRef( &lpwhs->hdr );
2082 lpwhr->lpHttpSession = lpwhs;
2083 list_add_head( &lpwhs->hdr.children, &lpwhr->hdr.entry );
2084
2085 lpszHostName = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) *
2086 (strlenW(lpwhs->lpszHostName) + 7 /* length of ":65535" + 1 */));
2087 if (NULL == lpszHostName)
2088 {
2089 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2090 goto lend;
2091 }
2092
2093 handle = WININET_AllocHandle( &lpwhr->hdr );
2094 if (NULL == handle)
2095 {
2096 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2097 goto lend;
2098 }
2099
2100 if (!NETCON_init(&lpwhr->netConnection, dwFlags & INTERNET_FLAG_SECURE))
2101 {
2102 InternetCloseHandle( handle );
2103 handle = NULL;
2104 goto lend;
2105 }
2106
2107 if (lpszObjectName && *lpszObjectName) {
2108 HRESULT rc;
2109
2110 len = 0;
2111 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
2112 if (rc != E_POINTER)
2113 len = strlenW(lpszObjectName)+1;
2114 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2115 rc = UrlEscapeW(lpszObjectName, lpwhr->lpszPath, &len,
2116 URL_ESCAPE_SPACES_ONLY);
2117 if (rc != S_OK)
2118 {
2119 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
2120 strcpyW(lpwhr->lpszPath,lpszObjectName);
2121 }
2122 }
2123
2124 if (lpszReferrer && *lpszReferrer)
2125 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2126
2127 if (lpszAcceptTypes)
2128 {
2129 int i;
2130 for (i = 0; lpszAcceptTypes[i]; i++)
2131 {
2132 if (!*lpszAcceptTypes[i]) continue;
2133 HTTP_ProcessHeader(lpwhr, HTTP_ACCEPT, lpszAcceptTypes[i],
2134 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
2135 HTTP_ADDHDR_FLAG_REQ |
2136 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
2137 }
2138 }
2139
2140 lpwhr->lpszVerb = WININET_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
2141
2142 if (lpszVersion)
2143 lpwhr->lpszVersion = WININET_strdupW(lpszVersion);
2144 else
2145 lpwhr->lpszVersion = WININET_strdupW(g_szHttp1_1);
2146
2147 if (lpwhs->nHostPort != INTERNET_INVALID_PORT_NUMBER &&
2148 lpwhs->nHostPort != INTERNET_DEFAULT_HTTP_PORT &&
2149 lpwhs->nHostPort != INTERNET_DEFAULT_HTTPS_PORT)
2150 {
2151 sprintfW(lpszHostName, szHostForm, lpwhs->lpszHostName, lpwhs->nHostPort);
2152 HTTP_ProcessHeader(lpwhr, szHost, lpszHostName,
2153 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2154 }
2155 else
2156 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName,
2157 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
2158
2159 if (lpwhs->nServerPort == INTERNET_INVALID_PORT_NUMBER)
2160 lpwhs->nServerPort = (dwFlags & INTERNET_FLAG_SECURE ?
2161 INTERNET_DEFAULT_HTTPS_PORT :
2162 INTERNET_DEFAULT_HTTP_PORT);
2163
2164 if (lpwhs->nHostPort == INTERNET_INVALID_PORT_NUMBER)
2165 lpwhs->nHostPort = (dwFlags & INTERNET_FLAG_SECURE ?
2166 INTERNET_DEFAULT_HTTPS_PORT :
2167 INTERNET_DEFAULT_HTTP_PORT);
2168
2169 if (NULL != hIC->lpszProxy && hIC->lpszProxy[0] != 0)
2170 HTTP_DealWithProxy( hIC, lpwhs, lpwhr );
2171
2172 INTERNET_SendCallback(&lpwhs->hdr, dwContext,
2173 INTERNET_STATUS_HANDLE_CREATED, &handle,
2174 sizeof(handle));
2175
2176 lend:
2177 HeapFree(GetProcessHeap(), 0, lpszHostName);
2178 if( lpwhr )
2179 WININET_Release( &lpwhr->hdr );
2180
2181 TRACE("<-- %p (%p)\n", handle, lpwhr);
2182 return handle;
2183 }
2184
2185 /* read any content returned by the server so that the connection can be
2186 * reused */
2187 static void HTTP_DrainContent(WININETHTTPREQW *req)
2188 {
2189 DWORD bytes_read;
2190
2191 if (!NETCON_connected(&req->netConnection)) return;
2192
2193 if (req->dwContentLength == -1)
2194 {
2195 NETCON_close(&req->netConnection);
2196 return;
2197 }
2198
2199 do
2200 {
2201 char buffer[2048];
2202 if (HTTPREQ_Read(req, buffer, sizeof(buffer), &bytes_read, TRUE) != ERROR_SUCCESS)
2203 return;
2204 } while (bytes_read);
2205 }
2206
2207 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
2208 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
2209 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
2210 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
2211 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
2212 static const WCHAR szAge[] = { 'A','g','e',0 };
2213 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
2214 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
2215 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
2216 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
2217 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
2218 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
2219 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
2220 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
2221 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
2222 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
2223 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
2224 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 };
2225 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
2226 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
2227 static const WCHAR szDate[] = { 'D','a','t','e',0 };
2228 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
2229 static const WCHAR szETag[] = { 'E','T','a','g',0 };
2230 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
2231 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
2232 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
2233 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2234 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
2235 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
2236 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
2237 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
2238 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
2239 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
2240 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
2241 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
2242 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2243 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
2244 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
2245 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
2246 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
2247 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
2248 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
2249 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
2250 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
2251 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 };
2252 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
2253 static const WCHAR szURI[] = { 'U','R','I',0 };
2254 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
2255 static const WCHAR szVary[] = { 'V','a','r','y',0 };
2256 static const WCHAR szVia[] = { 'V','i','a',0 };
2257 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
2258 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
2259
2260 static const LPCWSTR header_lookup[] = {
2261 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
2262 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
2263 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
2264 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
2265 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
2266 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
2267 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
2268 szAllow, /* HTTP_QUERY_ALLOW = 7 */
2269 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
2270 szDate, /* HTTP_QUERY_DATE = 9 */
2271 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
2272 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
2273 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
2274 szURI, /* HTTP_QUERY_URI = 13 */
2275 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
2276 NULL, /* HTTP_QUERY_COST = 15 */
2277 NULL, /* HTTP_QUERY_LINK = 16 */
2278 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
2279 NULL, /* HTTP_QUERY_VERSION = 18 */
2280 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
2281 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
2282 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
2283 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
2284 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
2285 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
2286 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
2287 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
2288 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
2289 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
2290 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
2291 NULL, /* HTTP_QUERY_FORWARDED = 30 */
2292 NULL, /* HTTP_QUERY_FROM = 31 */
2293 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
2294 szLocation, /* HTTP_QUERY_LOCATION = 33 */
2295 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
2296 szReferer, /* HTTP_QUERY_REFERER = 35 */
2297 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
2298 szServer, /* HTTP_QUERY_SERVER = 37 */
2299 NULL, /* HTTP_TITLE = 38 */
2300 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
2301 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
2302 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
2303 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
2304 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
2305 szCookie, /* HTTP_QUERY_COOKIE = 44 */
2306 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
2307 NULL, /* HTTP_QUERY_REFRESH = 46 */
2308 NULL, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
2309 szAge, /* HTTP_QUERY_AGE = 48 */
2310 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
2311 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
2312 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
2313 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
2314 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
2315 szETag, /* HTTP_QUERY_ETAG = 54 */
2316 szHost, /* HTTP_QUERY_HOST = 55 */
2317 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
2318 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
2319 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
2320 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
2321 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
2322 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
2323 szRange, /* HTTP_QUERY_RANGE = 62 */
2324 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
2325 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
2326 szVary, /* HTTP_QUERY_VARY = 65 */
2327 szVia, /* HTTP_QUERY_VIA = 66 */
2328 szWarning, /* HTTP_QUERY_WARNING = 67 */
2329 szExpect, /* HTTP_QUERY_EXPECT = 68 */
2330 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
2331 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
2332 };
2333
2334 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
2335
2336 /***********************************************************************
2337 * HTTP_HttpQueryInfoW (internal)
2338 */
2339 static BOOL HTTP_HttpQueryInfoW( LPWININETHTTPREQW lpwhr, DWORD dwInfoLevel,
2340 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2341 {
2342 LPHTTPHEADERW lphttpHdr = NULL;
2343 BOOL bSuccess = FALSE;
2344 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
2345 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
2346 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
2347 INT index = -1;
2348
2349 /* Find requested header structure */
2350 switch (level)
2351 {
2352 case HTTP_QUERY_CUSTOM:
2353 if (!lpBuffer) return FALSE;
2354 index = HTTP_GetCustomHeaderIndex(lpwhr, lpBuffer, requested_index, request_only);
2355 break;
2356
2357 case HTTP_QUERY_RAW_HEADERS_CRLF:
2358 {
2359 LPWSTR headers;
2360 DWORD len = 0;
2361 BOOL ret = FALSE;
2362
2363 if (request_only)
2364 headers = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
2365 else
2366 headers = lpwhr->lpszRawHeaders;
2367
2368 if (headers)
2369 len = strlenW(headers) * sizeof(WCHAR);
2370
2371 if (len + sizeof(WCHAR) > *lpdwBufferLength)
2372 {
2373 len += sizeof(WCHAR);
2374 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2375 ret = FALSE;
2376 }
2377 else if (lpBuffer)
2378 {
2379 if (headers)
2380 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
2381 else
2382 {
2383 len = strlenW(szCrLf) * sizeof(WCHAR);
2384 memcpy(lpBuffer, szCrLf, sizeof(szCrLf));
2385 }
2386 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
2387 ret = TRUE;
2388 }
2389 *lpdwBufferLength = len;
2390
2391 if (request_only)
2392 HeapFree(GetProcessHeap(), 0, headers);
2393 return ret;
2394 }
2395 case HTTP_QUERY_RAW_HEADERS:
2396 {
2397 LPWSTR * ppszRawHeaderLines = HTTP_Tokenize(lpwhr->lpszRawHeaders, szCrLf);
2398 DWORD i, size = 0;
2399 LPWSTR pszString = lpBuffer;
2400
2401 for (i = 0; ppszRawHeaderLines[i]; i++)
2402 size += strlenW(ppszRawHeaderLines[i]) + 1;
2403
2404 if (size + 1 > *lpdwBufferLength/sizeof(WCHAR))
2405 {
2406 HTTP_FreeTokens(ppszRawHeaderLines);
2407 *lpdwBufferLength = (size + 1) * sizeof(WCHAR);
2408 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2409 return FALSE;
2410 }
2411 if (pszString)
2412 {
2413 for (i = 0; ppszRawHeaderLines[i]; i++)
2414 {
2415 DWORD len = strlenW(ppszRawHeaderLines[i]);
2416 memcpy(pszString, ppszRawHeaderLines[i], (len+1)*sizeof(WCHAR));
2417 pszString += len+1;
2418 }
2419 *pszString = '\0';
2420 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, size));
2421 }
2422 *lpdwBufferLength = size * sizeof(WCHAR);
2423 HTTP_FreeTokens(ppszRawHeaderLines);
2424
2425 return TRUE;
2426 }
2427 case HTTP_QUERY_STATUS_TEXT:
2428 if (lpwhr->lpszStatusText)
2429 {
2430 DWORD len = strlenW(lpwhr->lpszStatusText);
2431 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2432 {
2433 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2434 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2435 return FALSE;
2436 }
2437 if (lpBuffer)
2438 {
2439 memcpy(lpBuffer, lpwhr->lpszStatusText, (len + 1) * sizeof(WCHAR));
2440 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2441 }
2442 *lpdwBufferLength = len * sizeof(WCHAR);
2443 return TRUE;
2444 }
2445 break;
2446 case HTTP_QUERY_VERSION:
2447 if (lpwhr->lpszVersion)
2448 {
2449 DWORD len = strlenW(lpwhr->lpszVersion);
2450 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
2451 {
2452 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
2453 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2454 return FALSE;
2455 }
2456 if (lpBuffer)
2457 {
2458 memcpy(lpBuffer, lpwhr->lpszVersion, (len + 1) * sizeof(WCHAR));
2459 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
2460 }
2461 *lpdwBufferLength = len * sizeof(WCHAR);
2462 return TRUE;
2463 }
2464 break;
2465 default:
2466 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
2467
2468 if (level < LAST_TABLE_HEADER && header_lookup[level])
2469 index = HTTP_GetCustomHeaderIndex(lpwhr, header_lookup[level],
2470 requested_index,request_only);
2471 }
2472
2473 if (index >= 0)
2474 lphttpHdr = &lpwhr->pCustHeaders[index];
2475
2476 /* Ensure header satisfies requested attributes */
2477 if (!lphttpHdr ||
2478 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
2479 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
2480 {
2481 INTERNET_SetLastError(ERROR_HTTP_HEADER_NOT_FOUND);
2482 return bSuccess;
2483 }
2484
2485 if (lpdwIndex && level != HTTP_QUERY_STATUS_CODE) (*lpdwIndex)++;
2486
2487 /* coalesce value to requested type */
2488 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
2489 {
2490 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
2491 TRACE(" returning number: %d\n", *(int *)lpBuffer);
2492 bSuccess = TRUE;
2493 }
2494 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
2495 {
2496 time_t tmpTime;
2497 struct tm tmpTM;
2498 SYSTEMTIME *STHook;
2499
2500 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
2501
2502 tmpTM = *gmtime(&tmpTime);
2503 STHook = (SYSTEMTIME *)lpBuffer;
2504 STHook->wDay = tmpTM.tm_mday;
2505 STHook->wHour = tmpTM.tm_hour;
2506 STHook->wMilliseconds = 0;
2507 STHook->wMinute = tmpTM.tm_min;
2508 STHook->wDayOfWeek = tmpTM.tm_wday;
2509 STHook->wMonth = tmpTM.tm_mon + 1;
2510 STHook->wSecond = tmpTM.tm_sec;
2511 STHook->wYear = tmpTM.tm_year;
2512 bSuccess = TRUE;
2513
2514 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
2515 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
2516 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
2517 }
2518 else if (lphttpHdr->lpszValue)
2519 {
2520 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
2521
2522 if (len > *lpdwBufferLength)
2523 {
2524 *lpdwBufferLength = len;
2525 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2526 return bSuccess;
2527 }
2528 if (lpBuffer)
2529 {
2530 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
2531 TRACE(" returning string: %s\n", debugstr_w(lpBuffer));
2532 }
2533 *lpdwBufferLength = len - sizeof(WCHAR);
2534 bSuccess = TRUE;
2535 }
2536 return bSuccess;
2537 }
2538
2539 /***********************************************************************
2540 * HttpQueryInfoW (WININET.@)
2541 *
2542 * Queries for information about an HTTP request
2543 *
2544 * RETURNS
2545 * TRUE on success
2546 * FALSE on failure
2547 *
2548 */
2549 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2550 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2551 {
2552 BOOL bSuccess = FALSE;
2553 LPWININETHTTPREQW lpwhr;
2554
2555 if (TRACE_ON(wininet)) {
2556 #define FE(x) { x, #x }
2557 static const wininet_flag_info query_flags[] = {
2558 FE(HTTP_QUERY_MIME_VERSION),
2559 FE(HTTP_QUERY_CONTENT_TYPE),
2560 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
2561 FE(HTTP_QUERY_CONTENT_ID),
2562 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
2563 FE(HTTP_QUERY_CONTENT_LENGTH),
2564 FE(HTTP_QUERY_CONTENT_LANGUAGE),
2565 FE(HTTP_QUERY_ALLOW),
2566 FE(HTTP_QUERY_PUBLIC),
2567 FE(HTTP_QUERY_DATE),
2568 FE(HTTP_QUERY_EXPIRES),
2569 FE(HTTP_QUERY_LAST_MODIFIED),
2570 FE(HTTP_QUERY_MESSAGE_ID),
2571 FE(HTTP_QUERY_URI),
2572 FE(HTTP_QUERY_DERIVED_FROM),
2573 FE(HTTP_QUERY_COST),
2574 FE(HTTP_QUERY_LINK),
2575 FE(HTTP_QUERY_PRAGMA),
2576 FE(HTTP_QUERY_VERSION),
2577 FE(HTTP_QUERY_STATUS_CODE),
2578 FE(HTTP_QUERY_STATUS_TEXT),
2579 FE(HTTP_QUERY_RAW_HEADERS),
2580 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
2581 FE(HTTP_QUERY_CONNECTION),
2582 FE(HTTP_QUERY_ACCEPT),
2583 FE(HTTP_QUERY_ACCEPT_CHARSET),
2584 FE(HTTP_QUERY_ACCEPT_ENCODING),
2585 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
2586 FE(HTTP_QUERY_AUTHORIZATION),
2587 FE(HTTP_QUERY_CONTENT_ENCODING),
2588 FE(HTTP_QUERY_FORWARDED),
2589 FE(HTTP_QUERY_FROM),
2590 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
2591 FE(HTTP_QUERY_LOCATION),
2592 FE(HTTP_QUERY_ORIG_URI),
2593 FE(HTTP_QUERY_REFERER),
2594 FE(HTTP_QUERY_RETRY_AFTER),
2595 FE(HTTP_QUERY_SERVER),
2596 FE(HTTP_QUERY_TITLE),
2597 FE(HTTP_QUERY_USER_AGENT),
2598 FE(HTTP_QUERY_WWW_AUTHENTICATE),
2599 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
2600 FE(HTTP_QUERY_ACCEPT_RANGES),
2601 FE(HTTP_QUERY_SET_COOKIE),
2602 FE(HTTP_QUERY_COOKIE),
2603 FE(HTTP_QUERY_REQUEST_METHOD),
2604 FE(HTTP_QUERY_REFRESH),
2605 FE(HTTP_QUERY_CONTENT_DISPOSITION),
2606 FE(HTTP_QUERY_AGE),
2607 FE(HTTP_QUERY_CACHE_CONTROL),
2608 FE(HTTP_QUERY_CONTENT_BASE),
2609 FE(HTTP_QUERY_CONTENT_LOCATION),
2610 FE(HTTP_QUERY_CONTENT_MD5),
2611 FE(HTTP_QUERY_CONTENT_RANGE),
2612 FE(HTTP_QUERY_ETAG),
2613 FE(HTTP_QUERY_HOST),
2614 FE(HTTP_QUERY_IF_MATCH),
2615 FE(HTTP_QUERY_IF_NONE_MATCH),
2616 FE(HTTP_QUERY_IF_RANGE),
2617 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
2618 FE(HTTP_QUERY_MAX_FORWARDS),
2619 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
2620 FE(HTTP_QUERY_RANGE),
2621 FE(HTTP_QUERY_TRANSFER_ENCODING),
2622 FE(HTTP_QUERY_UPGRADE),
2623 FE(HTTP_QUERY_VARY),
2624 FE(HTTP_QUERY_VIA),
2625 FE(HTTP_QUERY_WARNING),
2626 FE(HTTP_QUERY_CUSTOM)
2627 };
2628 static const wininet_flag_info modifier_flags[] = {
2629 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
2630 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
2631 FE(HTTP_QUERY_FLAG_NUMBER),
2632 FE(HTTP_QUERY_FLAG_COALESCE)
2633 };
2634 #undef FE
2635 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
2636 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
2637 DWORD i;
2638
2639 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, dwInfoLevel);
2640 TRACE(" Attribute:");
2641 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
2642 if (query_flags[i].val == info) {
2643 TRACE(" %s", query_flags[i].name);
2644 break;
2645 }
2646 }
2647 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
2648 TRACE(" Unknown (%08x)", info);
2649 }
2650
2651 TRACE(" Modifier:");
2652 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
2653 if (modifier_flags[i].val & info_mod) {
2654 TRACE(" %s", modifier_flags[i].name);
2655 info_mod &= ~ modifier_flags[i].val;
2656 }
2657 }
2658
2659 if (info_mod) {
2660 TRACE(" Unknown (%08x)", info_mod);
2661 }
2662 TRACE("\n");
2663 }
2664
2665 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2666 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2667 {
2668 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2669 goto lend;
2670 }
2671
2672 if (lpBuffer == NULL)
2673 *lpdwBufferLength = 0;
2674 bSuccess = HTTP_HttpQueryInfoW( lpwhr, dwInfoLevel,
2675 lpBuffer, lpdwBufferLength, lpdwIndex);
2676
2677 lend:
2678 if( lpwhr )
2679 WININET_Release( &lpwhr->hdr );
2680
2681 TRACE("%d <--\n", bSuccess);
2682 return bSuccess;
2683 }
2684
2685 /***********************************************************************
2686 * HttpQueryInfoA (WININET.@)
2687 *
2688 * Queries for information about an HTTP request
2689 *
2690 * RETURNS
2691 * TRUE on success
2692 * FALSE on failure
2693 *
2694 */
2695 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
2696 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
2697 {
2698 BOOL result;
2699 DWORD len;
2700 WCHAR* bufferW;
2701
2702 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
2703 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
2704 {
2705 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
2706 lpdwBufferLength, lpdwIndex );
2707 }
2708
2709 if (lpBuffer)
2710 {
2711 DWORD alloclen;
2712 len = (*lpdwBufferLength)*sizeof(WCHAR);
2713 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2714 {
2715 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
2716 if (alloclen < len)
2717 alloclen = len;
2718 }
2719 else
2720 alloclen = len;
2721 bufferW = HeapAlloc( GetProcessHeap(), 0, alloclen );
2722 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
2723 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
2724 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
2725 } else
2726 {
2727 bufferW = NULL;
2728 len = 0;
2729 }
2730
2731 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
2732 &len, lpdwIndex );
2733 if( result )
2734 {
2735 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
2736 lpBuffer, *lpdwBufferLength, NULL, NULL );
2737 *lpdwBufferLength = len - 1;
2738
2739 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
2740 }
2741 else
2742 /* since the strings being returned from HttpQueryInfoW should be
2743 * only ASCII characters, it is reasonable to assume that all of
2744 * the Unicode characters can be reduced to a single byte */
2745 *lpdwBufferLength = len / sizeof(WCHAR);
2746
2747 HeapFree(GetProcessHeap(), 0, bufferW );
2748
2749 return result;
2750 }
2751
2752 /***********************************************************************
2753 * HttpSendRequestExA (WININET.@)
2754 *
2755 * Sends the specified request to the HTTP server and allows chunked
2756 * transfers.
2757 *
2758 * RETURNS
2759 * Success: TRUE
2760 * Failure: FALSE, call GetLastError() for more information.
2761 */
2762 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
2763 LPINTERNET_BUFFERSA lpBuffersIn,
2764 LPINTERNET_BUFFERSA lpBuffersOut,
2765 DWORD dwFlags, DWORD_PTR dwContext)
2766 {
2767 INTERNET_BUFFERSW BuffersInW;
2768 BOOL rc = FALSE;
2769 DWORD headerlen;
2770 LPWSTR header = NULL;
2771
2772 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2773 lpBuffersOut, dwFlags, dwContext);
2774
2775 if (lpBuffersIn)
2776 {
2777 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
2778 if (lpBuffersIn->lpcszHeader)
2779 {
2780 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
2781 lpBuffersIn->dwHeadersLength,0,0);
2782 header = HeapAlloc(GetProcessHeap(),0,headerlen*sizeof(WCHAR));
2783 if (!(BuffersInW.lpcszHeader = header))
2784 {
2785 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2786 return FALSE;
2787 }
2788 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
2789 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2790 header, headerlen);
2791 }
2792 else
2793 BuffersInW.lpcszHeader = NULL;
2794 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
2795 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
2796 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
2797 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
2798 BuffersInW.Next = NULL;
2799 }
2800
2801 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
2802
2803 HeapFree(GetProcessHeap(),0,header);
2804
2805 return rc;
2806 }
2807
2808 /***********************************************************************
2809 * HttpSendRequestExW (WININET.@)
2810 *
2811 * Sends the specified request to the HTTP server and allows chunked
2812 * transfers
2813 *
2814 * RETURNS
2815 * Success: TRUE
2816 * Failure: FALSE, call GetLastError() for more information.
2817 */
2818 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
2819 LPINTERNET_BUFFERSW lpBuffersIn,
2820 LPINTERNET_BUFFERSW lpBuffersOut,
2821 DWORD dwFlags, DWORD_PTR dwContext)
2822 {
2823 BOOL ret = FALSE;
2824 LPWININETHTTPREQW lpwhr;
2825 LPWININETHTTPSESSIONW lpwhs;
2826 LPWININETAPPINFOW hIC;
2827
2828 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
2829 lpBuffersOut, dwFlags, dwContext);
2830
2831 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hRequest );
2832
2833 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2834 {
2835 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2836 goto lend;
2837 }
2838
2839 lpwhs = lpwhr->lpHttpSession;
2840 assert(lpwhs->hdr.htype == WH_HHTTPSESSION);
2841 hIC = lpwhs->lpAppInfo;
2842 assert(hIC->hdr.htype == WH_HINIT);
2843
2844 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2845 {
2846 WORKREQUEST workRequest;
2847 struct WORKREQ_HTTPSENDREQUESTW *req;
2848
2849 workRequest.asyncproc = AsyncHttpSendRequestProc;
2850 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2851 req = &workRequest.u.HttpSendRequestW;
2852 if (lpBuffersIn)
2853 {
2854 if (lpBuffersIn->lpcszHeader)
2855 /* FIXME: this should use dwHeadersLength or may not be necessary at all */
2856 req->lpszHeader = WININET_strdupW(lpBuffersIn->lpcszHeader);
2857 else
2858 req->lpszHeader = NULL;
2859 req->dwHeaderLength = lpBuffersIn->dwHeadersLength;
2860 req->lpOptional = lpBuffersIn->lpvBuffer;
2861 req->dwOptionalLength = lpBuffersIn->dwBufferLength;
2862 req->dwContentLength = lpBuffersIn->dwBufferTotal;
2863 }
2864 else
2865 {
2866 req->lpszHeader = NULL;
2867 req->dwHeaderLength = 0;
2868 req->lpOptional = NULL;
2869 req->dwOptionalLength = 0;
2870 req->dwContentLength = 0;
2871 }
2872
2873 req->bEndRequest = FALSE;
2874
2875 INTERNET_AsyncCall(&workRequest);
2876 /*
2877 * This is from windows.
2878 */
2879 INTERNET_SetLastError(ERROR_IO_PENDING);
2880 }
2881 else
2882 {
2883 if (lpBuffersIn)
2884 ret = HTTP_HttpSendRequestW(lpwhr, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
2885 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
2886 lpBuffersIn->dwBufferTotal, FALSE);
2887 else
2888 ret = HTTP_HttpSendRequestW(lpwhr, NULL, 0, NULL, 0, 0, FALSE);
2889 }
2890
2891 lend:
2892 if ( lpwhr )
2893 WININET_Release( &lpwhr->hdr );
2894
2895 TRACE("<---\n");
2896 return ret;
2897 }
2898
2899 /***********************************************************************
2900 * HttpSendRequestW (WININET.@)
2901 *
2902 * Sends the specified request to the HTTP server
2903 *
2904 * RETURNS
2905 * TRUE on success
2906 * FALSE on failure
2907 *
2908 */
2909 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
2910 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
2911 {
2912 LPWININETHTTPREQW lpwhr;
2913 LPWININETHTTPSESSIONW lpwhs = NULL;
2914 LPWININETAPPINFOW hIC = NULL;
2915 BOOL r;
2916
2917 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
2918 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
2919
2920 lpwhr = (LPWININETHTTPREQW) WININET_GetObject( hHttpRequest );
2921 if (NULL == lpwhr || lpwhr->hdr.htype != WH_HHTTPREQ)
2922 {
2923 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2924 r = FALSE;
2925 goto lend;
2926 }
2927
2928 lpwhs = lpwhr->lpHttpSession;
2929 if (NULL == lpwhs || lpwhs->hdr.htype != WH_HHTTPSESSION)
2930 {
2931 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2932 r = FALSE;
2933 goto lend;
2934 }
2935
2936 hIC = lpwhs->lpAppInfo;
2937 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
2938 {
2939 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2940 r = FALSE;
2941 goto lend;
2942 }
2943
2944 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2945 {
2946 WORKREQUEST workRequest;
2947 struct WORKREQ_HTTPSENDREQUESTW *req;
2948
2949 workRequest.asyncproc = AsyncHttpSendRequestProc;
2950 workRequest.hdr = WININET_AddRef( &lpwhr->hdr );
2951 req = &workRequest.u.HttpSendRequestW;
2952 if (lpszHeaders)
2953 {
2954 DWORD size;
2955
2956 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
2957 else size = dwHeaderLength * sizeof(WCHAR);
2958
2959 req->lpszHeader = HeapAlloc(GetProcessHeap(), 0, size);
2960 memcpy(req->lpszHeader, lpszHeaders, size);
2961 }
2962 else
2963 req->lpszHeader = 0;
2964 req->dwHeaderLength = dwHeaderLength;
2965 req->lpOptional = lpOptional;
2966 req->dwOptionalLength = dwOptionalLength;
2967 req->dwContentLength = dwOptionalLength;
2968 req->bEndRequest = TRUE;
2969
2970 INTERNET_AsyncCall(&workRequest);
2971 /*
2972 * This is from windows.
2973 */
2974 INTERNET_SetLastError(ERROR_IO_PENDING);
2975 r = FALSE;
2976 }
2977 else
2978 {
2979 r = HTTP_HttpSendRequestW(lpwhr, lpszHeaders,
2980 dwHeaderLength, lpOptional, dwOptionalLength,
2981 dwOptionalLength, TRUE);
2982 }
2983 lend:
2984 if( lpwhr )
2985 WININET_Release( &lpwhr->hdr );
2986 return r;
2987 }
2988
2989 /***********************************************************************
2990 * HttpSendRequestA (WININET.@)
2991 *
2992 * Sends the specified request to the HTTP server
2993 *
2994 * RETURNS
2995 * TRUE on success
2996 * FALSE on failure
2997 *
2998 */
2999 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
3000 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
3001 {
3002 BOOL result;
3003 LPWSTR szHeaders=NULL;
3004 DWORD nLen=dwHeaderLength;
3005 if(lpszHeaders!=NULL)
3006 {
3007 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
3008 szHeaders=HeapAlloc(GetProcessHeap(),0,nLen*sizeof(WCHAR));
3009 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
3010 }
3011 result=HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
3012 HeapFree(GetProcessHeap(),0,szHeaders);
3013 return result;
3014 }
3015
3016 static BOOL HTTP_GetRequestURL(WININETHTTPREQW *req, LPWSTR buf)
3017 {
3018 LPHTTPHEADERW host_header;
3019
3020 static const WCHAR formatW[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3021
3022 host_header = HTTP_GetHeader(req, szHost);
3023 if(!host_header)
3024 return FALSE;
3025
3026 sprintfW(buf, formatW, host_header->lpszValue, req->lpszPath); /* FIXME */
3027 return TRUE;
3028 }
3029
3030 /***********************************************************************
3031 * HTTP_GetRedirectURL (internal)
3032 */
3033 static LPWSTR HTTP_GetRedirectURL(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
3034 {
3035 static WCHAR szHttp[] = {'h','t','t','p',0};
3036 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3037 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3038 URL_COMPONENTSW urlComponents;
3039 DWORD url_length = 0;
3040 LPWSTR orig_url;
3041 LPWSTR combined_url;
3042
3043 if (lpszUrl[0]=='/') return WININET_strdupW( lpszUrl );
3044
3045 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3046 urlComponents.lpszScheme = (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3047 urlComponents.dwSchemeLength = 0;
3048 urlComponents.lpszHostName = lpwhs->lpszHostName;
3049 urlComponents.dwHostNameLength = 0;
3050 urlComponents.nPort = lpwhs->nHostPort;
3051 urlComponents.lpszUserName = lpwhs->lpszUserName;
3052 urlComponents.dwUserNameLength = 0;
3053 urlComponents.lpszPassword = NULL;
3054 urlComponents.dwPasswordLength = 0;
3055 urlComponents.lpszUrlPath = lpwhr->lpszPath;
3056 urlComponents.dwUrlPathLength = 0;
3057 urlComponents.lpszExtraInfo = NULL;
3058 urlComponents.dwExtraInfoLength = 0;
3059
3060 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
3061 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3062 return NULL;
3063
3064 orig_url = HeapAlloc(GetProcessHeap(), 0, url_length);
3065
3066 /* convert from bytes to characters */
3067 url_length = url_length / sizeof(WCHAR) - 1;
3068 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
3069 {
3070 HeapFree(GetProcessHeap(), 0, orig_url);
3071 return NULL;
3072 }
3073
3074 url_length = 0;
3075 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
3076 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3077 {
3078 HeapFree(GetProcessHeap(), 0, orig_url);
3079 return NULL;
3080 }
3081 combined_url = HeapAlloc(GetProcessHeap(), 0, url_length * sizeof(WCHAR));
3082
3083 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
3084 {
3085 HeapFree(GetProcessHeap(), 0, orig_url);
3086 HeapFree(GetProcessHeap(), 0, combined_url);
3087 return NULL;
3088 }
3089 HeapFree(GetProcessHeap(), 0, orig_url);
3090 return combined_url;
3091 }
3092
3093
3094 /***********************************************************************
3095 * HTTP_HandleRedirect (internal)
3096 */
3097 static BOOL HTTP_HandleRedirect(LPWININETHTTPREQW lpwhr, LPCWSTR lpszUrl)
3098 {
3099 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3100 LPWININETAPPINFOW hIC = lpwhs->lpAppInfo;
3101 BOOL using_proxy = hIC->lpszProxy && hIC->lpszProxy[0];
3102 WCHAR path[INTERNET_MAX_URL_LENGTH];
3103 int index;
3104
3105 if(lpszUrl[0]=='/')
3106 {
3107 /* if it's an absolute path, keep the same session info */
3108 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
3109 }
3110 else
3111 {
3112 URL_COMPONENTSW urlComponents;
3113 WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
3114 static WCHAR szHttp[] = {'h','t','t','p',0};
3115 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3116
3117 userName[0] = 0;
3118 hostName[0] = 0;
3119 protocol[0] = 0;
3120
3121 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3122 urlComponents.lpszScheme = protocol;
3123 urlComponents.dwSchemeLength = 32;
3124 urlComponents.lpszHostName = hostName;
3125 urlComponents.dwHostNameLength = MAXHOSTNAME;
3126 urlComponents.lpszUserName = userName;
3127 urlComponents.dwUserNameLength = 1024;
3128 urlComponents.lpszPassword = NULL;
3129 urlComponents.dwPasswordLength = 0;
3130 urlComponents.lpszUrlPath = path;
3131 urlComponents.dwUrlPathLength = 2048;
3132 urlComponents.lpszExtraInfo = NULL;
3133 urlComponents.dwExtraInfoLength = 0;
3134 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
3135 return FALSE;
3136
3137 if (!strncmpW(szHttp, urlComponents.lpszScheme, strlenW(szHttp)) &&
3138 (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3139 {
3140 TRACE("redirect from secure page to non-secure page\n");
3141 /* FIXME: warn about from secure redirect to non-secure page */
3142 lpwhr->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
3143 }
3144 if (!strncmpW(szHttps, urlComponents.lpszScheme, strlenW(szHttps)) &&
3145 !(lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE))
3146 {
3147 TRACE("redirect from non-secure page to secure page\n");
3148 /* FIXME: notify about redirect to secure page */
3149 lpwhr->hdr.dwFlags |= INTERNET_FLAG_SECURE;
3150 }
3151
3152 if (urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
3153 {
3154 if (lstrlenW(protocol)>4) /*https*/
3155 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3156 else /*http*/
3157 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3158 }
3159
3160 #if 0
3161 /*
3162 * This upsets redirects to binary files on sourceforge.net
3163 * and gives an html page instead of the target file
3164 * Examination of the HTTP request sent by native wininet.dll
3165 * reveals that it doesn't send a referrer in that case.
3166 * Maybe there's a flag that enables this, or maybe a referrer
3167 * shouldn't be added in case of a redirect.
3168 */
3169
3170 /* consider the current host as the referrer */
3171 if (lpwhs->lpszServerName && *lpwhs->lpszServerName)
3172 HTTP_ProcessHeader(lpwhr, HTTP_REFERER, lpwhs->lpszServerName,
3173 HTTP_ADDHDR_FLAG_REQ|HTTP_ADDREQ_FLAG_REPLACE|
3174 HTTP_ADDHDR_FLAG_ADD_IF_NEW);
3175 #endif
3176
3177 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3178 if (urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT &&
3179 urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
3180 {
3181 int len;
3182 static const WCHAR fmt[] = {'%','s',':','%','i',0};
3183 len = lstrlenW(hostName);
3184 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
3185 lpwhs->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
3186 sprintfW(lpwhs->lpszHostName, fmt, hostName, urlComponents.nPort);
3187 }
3188 else
3189 lpwhs->lpszHostName = WININET_strdupW(hostName);
3190
3191 HTTP_ProcessHeader(lpwhr, szHost, lpwhs->lpszHostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
3192
3193 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3194 lpwhs->lpszUserName = NULL;
3195 if (userName[0])
3196 lpwhs->lpszUserName = WININET_strdupW(userName);
3197
3198 if (!using_proxy)
3199 {
3200 if (strcmpiW(lpwhs->lpszServerName, hostName) || lpwhs->nServerPort != urlComponents.nPort)
3201 {
3202 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3203 lpwhs->lpszServerName = WININET_strdupW(hostName);
3204 lpwhs->nServerPort = urlComponents.nPort;
3205
3206 NETCON_close(&lpwhr->netConnection);
3207 if (!HTTP_ResolveName(lpwhr)) return FALSE;
3208 if (!NETCON_init(&lpwhr->netConnection, lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)) return FALSE;
3209 lpwhr->read_pos = lpwhr->read_size = 0;
3210 lpwhr->read_chunked = FALSE;
3211 }
3212 }
3213 else
3214 TRACE("Redirect through proxy\n");
3215 }
3216
3217 HeapFree(GetProcessHeap(), 0, lpwhr->lpszPath);
3218 lpwhr->lpszPath=NULL;
3219 if (*path)
3220 {
3221 DWORD needed = 0;
3222 HRESULT rc;
3223
3224 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
3225 if (rc != E_POINTER)
3226 needed = strlenW(path)+1;
3227 lpwhr->lpszPath = HeapAlloc(GetProcessHeap(), 0, needed*sizeof(WCHAR));
3228 rc = UrlEscapeW(path, lpwhr->lpszPath, &needed,
3229 URL_ESCAPE_SPACES_ONLY);
3230 if (rc != S_OK)
3231 {
3232 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
3233 strcpyW(lpwhr->lpszPath,path);
3234 }
3235 }
3236
3237 /* Remove custom content-type/length headers on redirects. */
3238 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Type, 0, TRUE);
3239 if (0 <= index)
3240 HTTP_DeleteCustomHeader(lpwhr, index);
3241 index = HTTP_GetCustomHeaderIndex(lpwhr, szContent_Length, 0, TRUE);
3242 if (0 <= index)
3243 HTTP_DeleteCustomHeader(lpwhr, index);
3244
3245 return TRUE;
3246 }
3247
3248 /***********************************************************************
3249 * HTTP_build_req (internal)
3250 *
3251 * concatenate all the strings in the request together
3252 */
3253 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
3254 {
3255 LPCWSTR *t;
3256 LPWSTR str;
3257
3258 for( t = list; *t ; t++ )
3259 len += strlenW( *t );
3260 len++;
3261
3262 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
3263 *str = 0;
3264
3265 for( t = list; *t ; t++ )
3266 strcatW( str, *t );
3267
3268 return str;
3269 }
3270
3271 static BOOL HTTP_SecureProxyConnect(LPWININETHTTPREQW lpwhr)
3272 {
3273 LPWSTR lpszPath;
3274 LPWSTR requestString;
3275 INT len;
3276 INT cnt;
3277 INT responseLen;
3278 char *ascii_req;
3279 BOOL ret;
3280 static const WCHAR szConnect[] = {'C','O','N','N','E','C','T',0};
3281 static const WCHAR szFormat[] = {'%','s',':','%','d',0};
3282 LPWININETHTTPSESSIONW lpwhs = lpwhr->lpHttpSession;
3283
3284 TRACE("\n");
3285
3286 lpszPath = HeapAlloc( GetProcessHeap(), 0, (lstrlenW( lpwhs->lpszHostName ) + 13)*sizeof(WCHAR) );
3287 sprintfW( lpszPath, szFormat, lpwhs->lpszHostName, lpwhs->nHostPort );
3288 requestString = HTTP_BuildHeaderRequestString( lpwhr, szConnect, lpszPath, g_szHttp1_1 );
3289 HeapFree( GetProcessHeap(), 0, lpszPath );
3290
3291 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3292 NULL, 0, NULL, NULL );
3293 len--; /* the nul terminator isn't needed */
3294 ascii_req = HeapAlloc( GetProcessHeap(), 0, len );
3295 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3296 ascii_req, len, NULL, NULL );
3297 HeapFree( GetProcessHeap(), 0, requestString );
3298
3299 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
3300
3301 ret = NETCON_send( &lpwhr->netConnection, ascii_req, len, 0, &cnt );
3302 HeapFree( GetProcessHeap(), 0, ascii_req );
3303 if (!ret || cnt < 0)
3304 return FALSE;
3305
3306 responseLen = HTTP_GetResponseHeaders( lpwhr, TRUE );
3307 if (!responseLen)
3308 return FALSE;
3309
3310 return TRUE;
3311 }
3312
3313 static void HTTP_InsertCookies(LPWININETHTTPREQW lpwhr)
3314 {
3315 static const WCHAR szUrlForm[] = {'h','t','t','p',':','/','/','%','s','%','s',0};
3316 LPWSTR lpszCookies, lpszUrl = NULL;
3317 DWORD nCookieSize, size;
3318 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3319
3320 size = (strlenW(Host->lpszValue) + strlenW(szUrlForm) + strlenW(lpwhr->lpszPath)) * sizeof(WCHAR);
3321 if (!(lpszUrl = HeapAlloc(GetProcessHeap(), 0, size))) return;
3322 sprintfW( lpszUrl, szUrlForm, Host->lpszValue, lpwhr->lpszPath);
3323
3324 if (InternetGetCookieW(lpszUrl, NULL, NULL, &nCookieSize))
3325 {
3326 int cnt = 0;
3327 static const WCHAR szCookie[] = {'C','o','o','k','i','e',':',' ',0};
3328
3329 size = sizeof(szCookie) + nCookieSize * sizeof(WCHAR) + sizeof(szCrLf);
3330 if ((lpszCookies = HeapAlloc(GetProcessHeap(), 0, size)))
3331 {
3332 cnt += sprintfW(lpszCookies, szCookie);
3333 InternetGetCookieW(lpszUrl, NULL, lpszCookies + cnt, &nCookieSize);
3334 strcatW(lpszCookies, szCrLf);
3335
3336 HTTP_HttpAddRequestHeadersW(lpwhr, lpszCookies, strlenW(lpszCookies), HTTP_ADDREQ_FLAG_REPLACE);
3337 HeapFree(GetProcessHeap(), 0, lpszCookies);
3338 }
3339 }
3340 HeapFree(GetProcessHeap(), 0, lpszUrl);
3341 }
3342
3343 /***********************************************************************
3344 * HTTP_HttpSendRequestW (internal)
3345 *
3346 * Sends the specified request to the HTTP server
3347 *
3348 * RETURNS
3349 * TRUE on success
3350 * FALSE on failure
3351 *
3352 */
3353 BOOL WINAPI HTTP_HttpSendRequestW(LPWININETHTTPREQW lpwhr, LPCWSTR lpszHeaders,
3354 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
3355 DWORD dwContentLength, BOOL bEndRequest)
3356 {
3357 INT cnt;
3358 BOOL bSuccess = FALSE, redirected = FALSE;
3359 LPWSTR requestString = NULL;
3360 INT responseLen;
3361 BOOL loop_next;
3362 INTERNET_ASYNC_RESULT iar;
3363 static const WCHAR szPost[] = { 'P','O','S','T',0 };
3364 static const WCHAR szContentLength[] =
3365 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
3366 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
3367
3368 TRACE("--> %p\n", lpwhr);
3369
3370 assert(lpwhr->hdr.htype == WH_HHTTPREQ);
3371
3372 /* if the verb is NULL default to GET */
3373 if (!lpwhr->lpszVerb)
3374 lpwhr->lpszVerb = WININET_strdupW(szGET);
3375
3376 if (dwContentLength || strcmpW(lpwhr->lpszVerb, szGET))
3377 {
3378 sprintfW(contentLengthStr, szContentLength, dwContentLength);
3379 HTTP_HttpAddRequestHeadersW(lpwhr, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
3380 lpwhr->dwBytesToWrite = dwContentLength;
3381 }
3382 if (lpwhr->lpHttpSession->lpAppInfo->lpszAgent)
3383 {
3384 WCHAR *agent_header;
3385 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
3386 int len;
3387
3388 len = strlenW(lpwhr->lpHttpSession->lpAppInfo->lpszAgent) + strlenW(user_agent);
3389 agent_header = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3390 sprintfW(agent_header, user_agent, lpwhr->lpHttpSession->lpAppInfo->lpszAgent);
3391
3392 HTTP_HttpAddRequestHeadersW(lpwhr, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3393 HeapFree(GetProcessHeap(), 0, agent_header);
3394 }
3395 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
3396 {
3397 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
3398 HTTP_HttpAddRequestHeadersW(lpwhr, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3399 }
3400 if ((lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(lpwhr->lpszVerb, szPost))
3401 {
3402 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
3403 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
3404 HTTP_HttpAddRequestHeadersW(lpwhr, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
3405 }
3406
3407 do
3408 {
3409 DWORD len;
3410 char *ascii_req;
3411
3412 loop_next = FALSE;
3413
3414 /* like native, just in case the caller forgot to call InternetReadFile
3415 * for all the data */
3416 HTTP_DrainContent(lpwhr);
3417 lpwhr->dwContentRead = 0;
3418
3419 if (TRACE_ON(wininet))
3420 {
3421 LPHTTPHEADERW Host = HTTP_GetHeader(lpwhr,szHost);
3422 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(lpwhr->lpszPath));
3423 }
3424
3425 HTTP_FixURL(lpwhr);
3426 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
3427 {
3428 HTTP_ProcessHeader(lpwhr, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
3429 }
3430 HTTP_InsertAuthorization(lpwhr, lpwhr->pAuthInfo, szAuthorization);
3431 HTTP_InsertAuthorization(lpwhr, lpwhr->pProxyAuthInfo, szProxy_Authorization);
3432
3433 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
3434 HTTP_InsertCookies(lpwhr);
3435
3436 /* add the headers the caller supplied */
3437 if( lpszHeaders && dwHeaderLength )
3438 {
3439 HTTP_HttpAddRequestHeadersW(lpwhr, lpszHeaders, dwHeaderLength,
3440 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
3441 }
3442
3443 if (lpwhr->lpHttpSession->lpAppInfo->lpszProxy && lpwhr->lpHttpSession->lpAppInfo->lpszProxy[0])
3444 {
3445 WCHAR *url = HTTP_BuildProxyRequestUrl(lpwhr);
3446 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, url, lpwhr->lpszVersion);
3447 HeapFree(GetProcessHeap(), 0, url);
3448 }
3449 else
3450 requestString = HTTP_BuildHeaderRequestString(lpwhr, lpwhr->lpszVerb, lpwhr->lpszPath, lpwhr->lpszVersion);
3451
3452
3453 TRACE("Request header -> %s\n", debugstr_w(requestString) );
3454
3455 /* Send the request and store the results */
3456 if (!HTTP_OpenConnection(lpwhr))
3457 goto lend;
3458
3459 /* send the request as ASCII, tack on the optional data */
3460 if (!lpOptional || redirected)
3461 dwOptionalLength = 0;
3462 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3463 NULL, 0, NULL, NULL );
3464 ascii_req = HeapAlloc( GetProcessHeap(), 0, len + dwOptionalLength );
3465 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
3466 ascii_req, len, NULL, NULL );
3467 if( lpOptional )
3468 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
3469 len = (len + dwOptionalLength - 1);
3470 ascii_req[len] = 0;
3471 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
3472
3473 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3474 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3475
3476 NETCON_send(&lpwhr->netConnection, ascii_req, len, 0, &cnt);
3477 HeapFree( GetProcessHeap(), 0, ascii_req );
3478
3479 lpwhr->dwBytesWritten = dwOptionalLength;
3480
3481 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3482 INTERNET_STATUS_REQUEST_SENT,
3483 &len, sizeof(DWORD));
3484
3485 if (bEndRequest)
3486 {
3487 DWORD dwBufferSize;
3488 DWORD dwStatusCode;
3489
3490 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3491 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3492
3493 if (cnt < 0)
3494 goto lend;
3495
3496 responseLen = HTTP_GetResponseHeaders(lpwhr, TRUE);
3497 if (responseLen)
3498 bSuccess = TRUE;
3499
3500 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3501 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
3502 sizeof(DWORD));
3503
3504 HTTP_ProcessCookies(lpwhr);
3505
3506 if (!set_content_length( lpwhr )) HTTP_FinishedReading(lpwhr);
3507
3508 dwBufferSize = sizeof(dwStatusCode);
3509 if (!HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_STATUS_CODE,
3510 &dwStatusCode,&dwBufferSize,NULL))
3511 dwStatusCode = 0;
3512
3513 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && bSuccess)
3514 {
3515 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
3516 dwBufferSize=sizeof(szNewLocation);
3517 if ((dwStatusCode==HTTP_STATUS_REDIRECT || dwStatusCode==HTTP_STATUS_MOVED) &&
3518 HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL))
3519 {
3520 /* redirects are always GETs */
3521 HeapFree(GetProcessHeap(), 0, lpwhr->lpszVerb);
3522 lpwhr->lpszVerb = WININET_strdupW(szGET);
3523
3524 HTTP_DrainContent(lpwhr);
3525 if ((new_url = HTTP_GetRedirectURL( lpwhr, szNewLocation )))
3526 {
3527 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext, INTERNET_STATUS_REDIRECT,
3528 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
3529 bSuccess = HTTP_HandleRedirect(lpwhr, new_url);
3530 if (bSuccess)
3531 {
3532 HeapFree(GetProcessHeap(), 0, requestString);
3533 loop_next = TRUE;
3534 }
3535 HeapFree( GetProcessHeap(), 0, new_url );
3536 }
3537 redirected = TRUE;
3538 }
3539 }
3540 if (!(lpwhr->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && bSuccess)
3541 {
3542 WCHAR szAuthValue[2048];
3543 dwBufferSize=2048;
3544 if (dwStatusCode == HTTP_STATUS_DENIED)
3545 {
3546 DWORD dwIndex = 0;
3547 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3548 {
3549 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3550 &lpwhr->pAuthInfo,
3551 lpwhr->lpHttpSession->lpszUserName,
3552 lpwhr->lpHttpSession->lpszPassword))
3553 {
3554 loop_next = TRUE;
3555 break;
3556 }
3557 }
3558 }
3559 if (dwStatusCode == HTTP_STATUS_PROXY_AUTH_REQ)
3560 {
3561 DWORD dwIndex = 0;
3562 while (HTTP_HttpQueryInfoW(lpwhr,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex))
3563 {
3564 if (HTTP_DoAuthorization(lpwhr, szAuthValue,
3565 &lpwhr->pProxyAuthInfo,
3566 lpwhr->lpHttpSession->lpAppInfo->lpszProxyUsername,
3567 lpwhr->lpHttpSession->lpAppInfo->lpszProxyPassword))
3568 {
3569 loop_next = TRUE;
3570 break;
3571 }
3572 }
3573 }
3574 }
3575 }
3576 else
3577 bSuccess = TRUE;
3578 }
3579 while (loop_next);
3580
3581 /* FIXME: Better check, when we have to create the cache file */
3582 if(bSuccess && (lpwhr->hdr.dwFlags & INTERNET_FLAG_NEED_FILE)) {
3583 WCHAR url[INTERNET_MAX_URL_LENGTH];
3584 WCHAR cacheFileName[MAX_PATH+1];
3585 BOOL b;
3586
3587 b = HTTP_GetRequestURL(lpwhr, url);
3588 if(!b) {
3589 WARN("Could not get URL\n");
3590 goto lend;
3591 }
3592
3593 b = CreateUrlCacheEntryW(url, lpwhr->dwContentLength > 0 ? lpwhr->dwContentLength : 0, NULL, cacheFileName, 0);
3594 if(b) {
3595 lpwhr->lpszCacheFile = WININET_strdupW(cacheFileName);
3596 lpwhr->hCacheFile = CreateFileW(lpwhr->lpszCacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
3597 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3598 if(lpwhr->hCacheFile == INVALID_HANDLE_VALUE) {
3599 WARN("Could not create file: %u\n", GetLastError());
3600 lpwhr->hCacheFile = NULL;
3601 }
3602 }else {
3603 WARN("Could not create cache entry: %08x\n", GetLastError());
3604 }
3605 }
3606
3607 lend:
3608
3609 HeapFree(GetProcessHeap(), 0, requestString);
3610
3611 /* TODO: send notification for P3P header */
3612
3613 if (lpwhr->lpHttpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3614 {
3615 if (bSuccess)
3616 {
3617 if (lpwhr->dwBytesWritten == lpwhr->dwBytesToWrite) HTTP_ReceiveRequestData(lpwhr, TRUE);
3618 else
3619 {
3620 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3621 iar.dwError = 0;
3622
3623 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3624 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3625 sizeof(INTERNET_ASYNC_RESULT));
3626 }
3627 }
3628 else
3629 {
3630 iar.dwResult = (DWORD_PTR)lpwhr->hdr.hInternet;
3631 iar.dwError = INTERNET_GetLastError();
3632
3633 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3634 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3635 sizeof(INTERNET_ASYNC_RESULT));
3636 }
3637 }
3638
3639 TRACE("<--\n");
3640 if (bSuccess) INTERNET_SetLastError(ERROR_SUCCESS);
3641 return bSuccess;
3642 }
3643
3644 /***********************************************************************
3645 * HTTPSESSION_Destroy (internal)
3646 *
3647 * Deallocate session handle
3648 *
3649 */
3650 static void HTTPSESSION_Destroy(WININETHANDLEHEADER *hdr)
3651 {
3652 LPWININETHTTPSESSIONW lpwhs = (LPWININETHTTPSESSIONW) hdr;
3653
3654 TRACE("%p\n", lpwhs);
3655
3656 WININET_Release(&lpwhs->lpAppInfo->hdr);
3657
3658 HeapFree(GetProcessHeap(), 0, lpwhs->lpszHostName);
3659 HeapFree(GetProcessHeap(), 0, lpwhs->lpszServerName);
3660 HeapFree(GetProcessHeap(), 0, lpwhs->lpszPassword);
3661 HeapFree(GetProcessHeap(), 0, lpwhs->lpszUserName);
3662 HeapFree(GetProcessHeap(), 0, lpwhs);
3663 }
3664
3665 static DWORD HTTPSESSION_QueryOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3666 {
3667 switch(option) {
3668 case INTERNET_OPTION_HANDLE_TYPE:
3669 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3670
3671 if (*size < sizeof(ULONG))
3672 return ERROR_INSUFFICIENT_BUFFER;
3673
3674 *size = sizeof(DWORD);
3675 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
3676 return ERROR_SUCCESS;
3677 }
3678
3679 return INET_QueryOption(option, buffer, size, unicode);
3680 }
3681
3682 static DWORD HTTPSESSION_SetOption(WININETHANDLEHEADER *hdr, DWORD option, void *buffer, DWORD size)
3683 {
3684 WININETHTTPSESSIONW *ses = (WININETHTTPSESSIONW*)hdr;
3685
3686 switch(option) {
3687 case INTERNET_OPTION_USERNAME:
3688 {
3689 HeapFree(GetProcessHeap(), 0, ses->lpszUserName);
3690 if (!(ses->lpszUserName = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3691 return ERROR_SUCCESS;
3692 }
3693 case INTERNET_OPTION_PASSWORD:
3694 {
3695 HeapFree(GetProcessHeap(), 0, ses->lpszPassword);
3696 if (!(ses->lpszPassword = WININET_strdupW(buffer))) return ERROR_OUTOFMEMORY;
3697 return ERROR_SUCCESS;
3698 }
3699 default: break;
3700 }
3701
3702 return ERROR_INTERNET_INVALID_OPTION;
3703 }
3704
3705 static const HANDLEHEADERVtbl HTTPSESSIONVtbl = {
3706 HTTPSESSION_Destroy,
3707 NULL,
3708 HTTPSESSION_QueryOption,
3709 HTTPSESSION_SetOption,
3710 NULL,
3711 NULL,
3712 NULL,
3713 NULL,
3714 NULL
3715 };
3716
3717
3718 /***********************************************************************
3719 * HTTP_Connect (internal)
3720 *
3721 * Create http session handle
3722 *
3723 * RETURNS
3724 * HINTERNET a session handle on success
3725 * NULL on failure
3726 *
3727 */
3728 HINTERNET HTTP_Connect(LPWININETAPPINFOW hIC, LPCWSTR lpszServerName,
3729 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
3730 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
3731 DWORD dwInternalFlags)
3732 {
3733 LPWININETHTTPSESSIONW lpwhs = NULL;
3734 HINTERNET handle = NULL;
3735
3736 TRACE("-->\n");
3737
3738 if (!lpszServerName || !lpszServerName[0])
3739 {
3740 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3741 goto lerror;
3742 }
3743
3744 assert( hIC->hdr.htype == WH_HINIT );
3745
3746 lpwhs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETHTTPSESSIONW));
3747 if (NULL == lpwhs)
3748 {
3749 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3750 goto lerror;
3751 }
3752
3753 /*
3754 * According to my tests. The name is not resolved until a request is sent
3755 */
3756
3757 lpwhs->hdr.htype = WH_HHTTPSESSION;
3758 lpwhs->hdr.vtbl = &HTTPSESSIONVtbl;
3759 lpwhs->hdr.dwFlags = dwFlags;
3760 lpwhs->hdr.dwContext = dwContext;
3761 lpwhs->hdr.dwInternalFlags = dwInternalFlags | (hIC->hdr.dwInternalFlags & INET_CALLBACKW);
3762 lpwhs->hdr.refs = 1;
3763 lpwhs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
3764
3765 WININET_AddRef( &hIC->hdr );
3766 lpwhs->lpAppInfo = hIC;
3767 list_add_head( &hIC->hdr.children, &lpwhs->hdr.entry );
3768
3769 handle = WININET_AllocHandle( &lpwhs->hdr );
3770 if (NULL == handle)
3771 {
3772 ERR("Failed to alloc handle\n");
3773 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3774 goto lerror;
3775 }
3776
3777 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
3778 if(strchrW(hIC->lpszProxy, ' '))
3779 FIXME("Several proxies not implemented.\n");
3780 if(hIC->lpszProxyBypass)
3781 FIXME("Proxy bypass is ignored.\n");
3782 }
3783 if (lpszServerName && lpszServerName[0])
3784 {
3785 lpwhs->lpszServerName = WININET_strdupW(lpszServerName);
3786 lpwhs->lpszHostName = WININET_strdupW(lpszServerName);
3787 }
3788 if (lpszUserName && lpszUserName[0])
3789 lpwhs->lpszUserName = WININET_strdupW(lpszUserName);
3790 if (lpszPassword && lpszPassword[0])
3791 lpwhs->lpszPassword = WININET_strdupW(lpszPassword);
3792 lpwhs->nServerPort = nServerPort;
3793 lpwhs->nHostPort = nServerPort;
3794
3795 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
3796 if (!(lpwhs->hdr.dwInternalFlags & INET_OPENURL))
3797 {
3798 INTERNET_SendCallback(&hIC->hdr, dwContext,
3799 INTERNET_STATUS_HANDLE_CREATED, &handle,
3800 sizeof(handle));
3801 }
3802
3803 lerror:
3804 if( lpwhs )
3805 WININET_Release( &lpwhs->hdr );
3806
3807 /*
3808 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
3809 * windows
3810 */
3811
3812 TRACE("%p --> %p (%p)\n", hIC, handle, lpwhs);
3813 return handle;
3814 }
3815
3816
3817 /***********************************************************************
3818 * HTTP_OpenConnection (internal)
3819 *
3820 * Connect to a web server
3821 *
3822 * RETURNS
3823 *
3824 * TRUE on success
3825 * FALSE on failure
3826 */
3827 static BOOL HTTP_OpenConnection(LPWININETHTTPREQW lpwhr)
3828 {
3829 BOOL bSuccess = FALSE;
3830 LPWININETHTTPSESSIONW lpwhs;
3831 LPWININETAPPINFOW hIC = NULL;
3832 char szaddr[32];
3833
3834 TRACE("-->\n");
3835
3836
3837 if (lpwhr->hdr.htype != WH_HHTTPREQ)
3838 {
3839 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3840 goto lend;
3841 }
3842
3843 if (NETCON_connected(&lpwhr->netConnection))
3844 {
3845 bSuccess = TRUE;
3846 goto lend;
3847 }
3848 if (!HTTP_ResolveName(lpwhr)) goto lend;
3849
3850 lpwhs = lpwhr->lpHttpSession;
3851
3852 hIC = lpwhs->lpAppInfo;
3853 inet_ntop(lpwhs->socketAddress.sin_family, &lpwhs->socketAddress.sin_addr,
3854 szaddr, sizeof(szaddr));
3855 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3856 INTERNET_STATUS_CONNECTING_TO_SERVER,
3857 szaddr,
3858 strlen(szaddr)+1);
3859
3860 if (!NETCON_create(&lpwhr->netConnection, lpwhs->socketAddress.sin_family,
3861 SOCK_STREAM, 0))
3862 {
3863 WARN("Socket creation failed: %u\n", INTERNET_GetLastError());
3864 goto lend;
3865 }
3866
3867 if (!NETCON_connect(&lpwhr->netConnection, (struct sockaddr *)&lpwhs->socketAddress,
3868 sizeof(lpwhs->socketAddress)))
3869 goto lend;
3870
3871 if (lpwhr->hdr.dwFlags & INTERNET_FLAG_SECURE)
3872 {
3873 /* Note: we differ from Microsoft's WinINet here. they seem to have
3874 * a bug that causes no status callbacks to be sent when starting
3875 * a tunnel to a proxy server using the CONNECT verb. i believe our
3876 * behaviour to be more correct and to not cause any incompatibilities
3877 * because using a secure connection through a proxy server is a rare
3878 * case that would be hard for anyone to depend on */
3879 if (hIC->lpszProxy && !HTTP_SecureProxyConnect(lpwhr))
3880 goto lend;
3881
3882 if (!NETCON_secure_connect(&lpwhr->netConnection, lpwhs->lpszHostName))
3883 {
3884 WARN("Couldn't connect securely to host\n");
3885 goto lend;
3886 }
3887 }
3888
3889 INTERNET_SendCallback(&lpwhr->hdr, lpwhr->hdr.dwContext,
3890 INTERNET_STATUS_CONNECTED_TO_SERVER,
3891 szaddr, strlen(szaddr)+1);
3892
3893 bSuccess = TRUE;
3894
3895 lend:
3896 lpwhr->read_pos = lpwhr->read_size = 0;
3897 lpwhr->read_chunked = FALSE;
3898
3899 TRACE("%d <--\n", bSuccess);
3900 return bSuccess;
3901 }
3902
3903
3904 /***********************************************************************
3905 * HTTP_clear_response_headers (internal)
3906 *
3907 * clear out any old response headers
3908 */
3909 static void HTTP_clear_response_headers( LPWININETHTTPREQW lpwhr )
3910 {
3911 DWORD i;
3912
3913 for( i=0; i<lpwhr->nCustHeaders; i++)
3914 {
3915 if( !lpwhr->pCustHeaders[i].lpszField )
3916 continue;
3917 if( !lpwhr->pCustHeaders[i].lpszValue )
3918 continue;
3919 if ( lpwhr->pCustHeaders[i].wFlags & HDR_ISREQUEST )
3920 continue;
3921 HTTP_DeleteCustomHeader( lpwhr, i );
3922 i--;
3923 }
3924 }
3925
3926 /***********************************************************************
3927 * HTTP_GetResponseHeaders (internal)
3928 *
3929 * Read server response
3930 *
3931 * RETURNS
3932 *
3933 * TRUE on success
3934 * FALSE on error
3935 */
3936 static INT HTTP_GetResponseHeaders(LPWININETHTTPREQW lpwhr, BOOL clear)
3937 {
3938 INT cbreaks = 0;
3939 WCHAR buffer[MAX_REPLY_LEN];
3940 DWORD buflen = MAX_REPLY_LEN;
3941 BOOL bSuccess = FALSE;
3942 INT rc = 0;
3943 static const WCHAR szHundred[] = {'1','0','0',0};
3944 char bufferA[MAX_REPLY_LEN];
3945 LPWSTR status_code, status_text;
3946 DWORD cchMaxRawHeaders = 1024;
3947 LPWSTR lpszRawHeaders = HeapAlloc(GetProcessHeap(), 0, (cchMaxRawHeaders+1)*sizeof(WCHAR));
3948 DWORD cchRawHeaders = 0;
3949
3950 TRACE("-->\n");
3951
3952 /* clear old response headers (eg. from a redirect response) */
3953 if (clear) HTTP_clear_response_headers( lpwhr );
3954
3955 if (!NETCON_connected(&lpwhr->netConnection))
3956 goto lend;
3957
3958 do {
3959 /*
3960 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
3961 */
3962 buflen = MAX_REPLY_LEN;
3963 if (!read_line(lpwhr, bufferA, &buflen))
3964 goto lend;
3965 rc += buflen;
3966 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
3967
3968 /* split the version from the status code */
3969 status_code = strchrW( buffer, ' ' );
3970 if( !status_code )
3971 goto lend;
3972 *status_code++=0;
3973
3974 /* split the status code from the status text */
3975 status_text = strchrW( status_code, ' ' );
3976 if( !status_text )
3977 goto lend;
3978 *status_text++=0;
3979
3980 TRACE("version [%s] status code [%s] status text [%s]\n",
3981 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
3982
3983 } while (!strcmpW(status_code, szHundred)); /* ignore "100 Continue" responses */
3984
3985 /* Add status code */
3986 HTTP_ProcessHeader(lpwhr, szStatus, status_code,
3987 HTTP_ADDHDR_FLAG_REPLACE);
3988
3989 HeapFree(GetProcessHeap(),0,lpwhr->lpszVersion);
3990 HeapFree(GetProcessHeap(),0,lpwhr->lpszStatusText);
3991
3992 lpwhr->lpszVersion= WININET_strdupW(buffer);
3993 lpwhr->lpszStatusText = WININET_strdupW(status_text);
3994
3995 /* Restore the spaces */
3996 *(status_code-1) = ' ';
3997 *(status_text-1) = ' ';
3998
3999 /* regenerate raw headers */
4000 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
4001 {
4002 cchMaxRawHeaders *= 2;
4003 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
4004 }
4005 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
4006 cchRawHeaders += (buflen-1);
4007 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
4008 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
4009 lpszRawHeaders[cchRawHeaders] = '\0';
4010
4011 /* Parse each response line */
4012 do
4013 {
4014 buflen = MAX_REPLY_LEN;
4015 if (read_line(lpwhr, bufferA, &buflen))
4016 {
4017 LPWSTR * pFieldAndValue;
4018
4019 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
4020
4021 if (!bufferA[0]) break;
4022 if (!strchr(bufferA, ':'))
4023 {
4024 WARN("invalid header\n");
4025 continue;
4026 }
4027 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
4028
4029 while (cchRawHeaders + buflen + strlenW(szCrLf) > cchMaxRawHeaders)
4030 {
4031 cchMaxRawHeaders *= 2;
4032 lpszRawHeaders = HeapReAlloc(GetProcessHeap(), 0, lpszRawHeaders, (cchMaxRawHeaders+1)*sizeof(WCHAR));
4033 }
4034 memcpy(lpszRawHeaders+cchRawHeaders, buffer, (buflen-1)*sizeof(WCHAR));
4035 cchRawHeaders += (buflen-1);
4036 memcpy(lpszRawHeaders+cchRawHeaders, szCrLf, sizeof(szCrLf));
4037 cchRawHeaders += sizeof(szCrLf)/sizeof(szCrLf[0])-1;
4038 lpszRawHeaders[cchRawHeaders] = '\0';
4039
4040 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
4041 if (!pFieldAndValue)
4042 break;
4043
4044 HTTP_ProcessHeader(lpwhr, pFieldAndValue[0], pFieldAndValue[1],
4045 HTTP_ADDREQ_FLAG_ADD );
4046
4047 HTTP_FreeTokens(pFieldAndValue);
4048 }
4049 else
4050 {
4051 cbreaks++;
4052 if (cbreaks >= 2)
4053 break;
4054 }
4055 }while(1);
4056
4057 HeapFree(GetProcessHeap(), 0, lpwhr->lpszRawHeaders);
4058 lpwhr->lpszRawHeaders = lpszRawHeaders;
4059 TRACE("raw headers: %s\n", debugstr_w(lpszRawHeaders));
4060 bSuccess = TRUE;
4061
4062 lend:
4063
4064 TRACE("<--\n");
4065 if (bSuccess)
4066 return rc;
4067 else
4068 {
4069 HeapFree(GetProcessHeap(), 0, lpszRawHeaders);
4070 return 0;
4071 }
4072 }
4073
4074
4075 static void strip_spaces(LPWSTR start)
4076 {
4077 LPWSTR str = start;
4078 LPWSTR end;
4079
4080 while (*str == ' ' && *str != '\0')
4081 str++;
4082
4083 if (str != start)
4084 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
4085
4086 end = start + strlenW(start) - 1;
4087 while (end >= start && *end == ' ')
4088 {
4089 *end = '\0';
4090 end--;
4091 }
4092 }
4093
4094
4095 /***********************************************************************
4096 * HTTP_InterpretHttpHeader (internal)
4097 *
4098 * Parse server response
4099 *
4100 * RETURNS
4101 *
4102 * Pointer to array of field, value, NULL on success.
4103 * NULL on error.
4104 */
4105 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
4106 {
4107 LPWSTR * pTokenPair;
4108 LPWSTR pszColon;
4109 INT len;
4110
4111 pTokenPair = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pTokenPair)*3);
4112
4113 pszColon = strchrW(buffer, ':');
4114 /* must have two tokens */
4115 if (!pszColon)
4116 {
4117 HTTP_FreeTokens(pTokenPair);
4118 if (buffer[0])
4119 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
4120 return NULL;
4121 }
4122
4123 pTokenPair[0] = HeapAlloc(GetProcessHeap(), 0, (pszColon - buffer + 1) * sizeof(WCHAR));
4124 if (!pTokenPair[0])
4125 {
4126 HTTP_FreeTokens(pTokenPair);
4127 return NULL;
4128 }
4129 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
4130 pTokenPair[0][pszColon - buffer] = '\0';
4131
4132 /* skip colon */
4133 pszColon++;
4134 len = strlenW(pszColon);
4135 pTokenPair[1] = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
4136 if (!pTokenPair[1])
4137 {
4138 HTTP_FreeTokens(pTokenPair);
4139 return NULL;
4140 }
4141 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
4142
4143 strip_spaces(pTokenPair[0]);
4144 strip_spaces(pTokenPair[1]);
4145
4146 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
4147 return pTokenPair;
4148 }
4149
4150 /***********************************************************************
4151 * HTTP_ProcessHeader (internal)
4152 *
4153 * Stuff header into header tables according to <dwModifier>
4154 *
4155 */
4156
4157 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4158
4159 static BOOL HTTP_ProcessHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
4160 {
4161 LPHTTPHEADERW lphttpHdr = NULL;
4162 BOOL bSuccess = FALSE;
4163 INT index = -1;
4164 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
4165
4166 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
4167
4168 /* REPLACE wins out over ADD */
4169 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4170 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
4171
4172 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
4173 index = -1;
4174 else
4175 index = HTTP_GetCustomHeaderIndex(lpwhr, field, 0, request_only);
4176
4177 if (index >= 0)
4178 {
4179 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
4180 {
4181 return FALSE;
4182 }
4183 lphttpHdr = &lpwhr->pCustHeaders[index];
4184 }
4185 else if (value)
4186 {
4187 HTTPHEADERW hdr;
4188
4189 hdr.lpszField = (LPWSTR)field;
4190 hdr.lpszValue = (LPWSTR)value;
4191 hdr.wFlags = hdr.wCount = 0;
4192
4193 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4194 hdr.wFlags |= HDR_ISREQUEST;
4195
4196 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4197 }
4198 /* no value to delete */
4199 else return TRUE;
4200
4201 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4202 lphttpHdr->wFlags |= HDR_ISREQUEST;
4203 else
4204 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
4205
4206 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
4207 {
4208 HTTP_DeleteCustomHeader( lpwhr, index );
4209
4210 if (value)
4211 {
4212 HTTPHEADERW hdr;
4213
4214 hdr.lpszField = (LPWSTR)field;
4215 hdr.lpszValue = (LPWSTR)value;
4216 hdr.wFlags = hdr.wCount = 0;
4217
4218 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
4219 hdr.wFlags |= HDR_ISREQUEST;
4220
4221 return HTTP_InsertCustomHeader(lpwhr, &hdr);
4222 }
4223
4224 return TRUE;
4225 }
4226 else if (dwModifier & COALESCEFLAGS)
4227 {
4228 LPWSTR lpsztmp;
4229 WCHAR ch = 0;
4230 INT len = 0;
4231 INT origlen = strlenW(lphttpHdr->lpszValue);
4232 INT valuelen = strlenW(value);
4233
4234 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
4235 {
4236 ch = ',';
4237 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4238 }
4239 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
4240 {
4241 ch = ';';
4242 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
4243 }
4244
4245 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
4246
4247 lpsztmp = HeapReAlloc(GetProcessHeap(), 0, lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
4248 if (lpsztmp)
4249 {
4250 lphttpHdr->lpszValue = lpsztmp;
4251 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
4252 if (ch > 0)
4253 {
4254 lphttpHdr->lpszValue[origlen] = ch;
4255 origlen++;
4256 lphttpHdr->lpszValue[origlen] = ' ';
4257 origlen++;
4258 }
4259
4260 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
4261 lphttpHdr->lpszValue[len] = '\0';
4262 bSuccess = TRUE;
4263 }
4264 else
4265 {
4266 WARN("HeapReAlloc (%d bytes) failed\n",len+1);
4267 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4268 }
4269 }
4270 TRACE("<-- %d\n",bSuccess);
4271 return bSuccess;
4272 }
4273
4274
4275 /***********************************************************************
4276 * HTTP_FinishedReading (internal)
4277 *
4278 * Called when all content from server has been read by client.
4279 *
4280 */
4281 static BOOL HTTP_FinishedReading(LPWININETHTTPREQW lpwhr)
4282 {
4283 WCHAR szVersion[10];
4284 WCHAR szConnectionResponse[20];
4285 DWORD dwBufferSize = sizeof(szVersion);
4286 BOOL keepalive = FALSE;
4287
4288 TRACE("\n");
4289
4290 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
4291 * the connection is keep-alive by default */
4292 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_VERSION, szVersion,
4293 &dwBufferSize, NULL) &&
4294 !strcmpiW(szVersion, g_szHttp1_1))
4295 {
4296 keepalive = TRUE;
4297 }
4298
4299 dwBufferSize = sizeof(szConnectionResponse);
4300 if (HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) ||
4301 HTTP_HttpQueryInfoW(lpwhr, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL))
4302 {
4303 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
4304 }
4305
4306 if (!keepalive)
4307 {
4308 HTTPREQ_CloseConnection(&lpwhr->hdr);
4309 }
4310
4311 /* FIXME: store data in the URL cache here */
4312
4313 return TRUE;
4314 }
4315
4316
4317 /***********************************************************************
4318 * HTTP_GetCustomHeaderIndex (internal)
4319 *
4320 * Return index of custom header from header array
4321 *
4322 */
4323 static INT HTTP_GetCustomHeaderIndex(LPWININETHTTPREQW lpwhr, LPCWSTR lpszField,
4324 int requested_index, BOOL request_only)
4325 {
4326 DWORD index;
4327
4328 TRACE("%s\n", debugstr_w(lpszField));
4329
4330 for (index = 0; index < lpwhr->nCustHeaders; index++)
4331 {
4332 if (strcmpiW(lpwhr->pCustHeaders[index].lpszField, lpszField))
4333 continue;
4334
4335 if (request_only && !(lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4336 continue;
4337
4338 if (!request_only && (lpwhr->pCustHeaders[index].wFlags & HDR_ISREQUEST))
4339 continue;
4340
4341 if (requested_index == 0)
4342 break;
4343 requested_index --;
4344 }
4345
4346 if (index >= lpwhr->nCustHeaders)
4347 index = -1;
4348
4349 TRACE("Return: %d\n", index);
4350 return index;
4351 }
4352
4353
4354 /***********************************************************************
4355 * HTTP_InsertCustomHeader (internal)
4356 *
4357 * Insert header into array
4358 *
4359 */
4360 static BOOL HTTP_InsertCustomHeader(LPWININETHTTPREQW lpwhr, LPHTTPHEADERW lpHdr)
4361 {
4362 INT count;
4363 LPHTTPHEADERW lph = NULL;
4364 BOOL r = FALSE;
4365
4366 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
4367 count = lpwhr->nCustHeaders + 1;
4368 if (count > 1)
4369 lph = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpwhr->pCustHeaders, sizeof(HTTPHEADERW) * count);
4370 else
4371 lph = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(HTTPHEADERW) * count);
4372
4373 if (NULL != lph)
4374 {
4375 lpwhr->pCustHeaders = lph;
4376 lpwhr->pCustHeaders[count-1].lpszField = WININET_strdupW(lpHdr->lpszField);
4377 lpwhr->pCustHeaders[count-1].lpszValue = WININET_strdupW(lpHdr->lpszValue);
4378 lpwhr->pCustHeaders[count-1].wFlags = lpHdr->wFlags;
4379 lpwhr->pCustHeaders[count-1].wCount= lpHdr->wCount;
4380 lpwhr->nCustHeaders++;
4381 r = TRUE;
4382 }
4383 else
4384 {
4385 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
4386 }
4387
4388 return r;
4389 }
4390
4391
4392 /***********************************************************************
4393 * HTTP_DeleteCustomHeader (internal)
4394 *
4395 * Delete header from array
4396 * If this function is called, the indexs may change.
4397 */
4398 static BOOL HTTP_DeleteCustomHeader(LPWININETHTTPREQW lpwhr, DWORD index)
4399 {
4400 if( lpwhr->nCustHeaders <= 0 )
4401 return FALSE;
4402 if( index >= lpwhr->nCustHeaders )
4403 return FALSE;
4404 lpwhr->nCustHeaders--;
4405
4406 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszField);
4407 HeapFree(GetProcessHeap(), 0, lpwhr->pCustHeaders[index].lpszValue);
4408
4409 memmove( &lpwhr->pCustHeaders[index], &lpwhr->pCustHeaders[index+1],
4410 (lpwhr->nCustHeaders - index)* sizeof(HTTPHEADERW) );
4411 memset( &lpwhr->pCustHeaders[lpwhr->nCustHeaders], 0, sizeof(HTTPHEADERW) );
4412
4413 return TRUE;
4414 }
4415
4416
4417 /***********************************************************************
4418 * HTTP_VerifyValidHeader (internal)
4419 *
4420 * Verify the given header is not invalid for the given http request
4421 *
4422 */
4423 static BOOL HTTP_VerifyValidHeader(LPWININETHTTPREQW lpwhr, LPCWSTR field)
4424 {
4425 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
4426 if (!strcmpW(lpwhr->lpszVersion, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
4427 return FALSE;
4428
4429 return TRUE;
4430 }
4431
4432 /***********************************************************************
4433 * IsHostInProxyBypassList (@)
4434 *
4435 * Undocumented
4436 *
4437 */
4438 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
4439 {
4440 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
4441 return FALSE;
4442 }