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