8da3a2e72f3e24e49009699220be774bdb48585b
[reactos.git] / reactos / dll / win32 / winhttp / request.c
1 /*
2 * Copyright 2004 Mike McCormack for CodeWeavers
3 * Copyright 2006 Rob Shearman for CodeWeavers
4 * Copyright 2008, 2011 Hans Leidekker for CodeWeavers
5 * Copyright 2009 Juan Lang
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 */
21
22 #define WIN32_NO_STATUS
23 #define _INC_WINDOWS
24 #define COM_NO_WINDOWS_H
25
26 #define COBJMACROS
27 #include <config.h>
28 //#include "wine/port.h"
29 #include <wine/debug.h>
30
31 #include <stdarg.h>
32 #ifdef HAVE_ARPA_INET_H
33 # include <arpa/inet.h>
34 #endif
35
36 #include <windef.h>
37 #include <winbase.h>
38 #include <ole2.h>
39 //#include "initguid.h"
40 #include <httprequest.h>
41 #include <winhttp.h>
42
43 #include "winhttp_private.h"
44
45 #include "inet_ntop.c"
46
47 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
48
49 static const WCHAR attr_accept[] = {'A','c','c','e','p','t',0};
50 static const WCHAR attr_accept_charset[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
51 static const WCHAR attr_accept_encoding[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
52 static const WCHAR attr_accept_language[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
53 static const WCHAR attr_accept_ranges[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
54 static const WCHAR attr_age[] = {'A','g','e',0};
55 static const WCHAR attr_allow[] = {'A','l','l','o','w',0};
56 static const WCHAR attr_authorization[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
57 static const WCHAR attr_cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
58 static const WCHAR attr_connection[] = {'C','o','n','n','e','c','t','i','o','n',0};
59 static const WCHAR attr_content_base[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
60 static const WCHAR attr_content_encoding[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
61 static const WCHAR attr_content_id[] = {'C','o','n','t','e','n','t','-','I','D',0};
62 static const WCHAR attr_content_language[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
63 static const WCHAR attr_content_length[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
64 static const WCHAR attr_content_location[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
65 static const WCHAR attr_content_md5[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
66 static const WCHAR attr_content_range[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
67 static const WCHAR attr_content_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};
68 static const WCHAR attr_content_type[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
69 static const WCHAR attr_cookie[] = {'C','o','o','k','i','e',0};
70 static const WCHAR attr_date[] = {'D','a','t','e',0};
71 static const WCHAR attr_from[] = {'F','r','o','m',0};
72 static const WCHAR attr_etag[] = {'E','T','a','g',0};
73 static const WCHAR attr_expect[] = {'E','x','p','e','c','t',0};
74 static const WCHAR attr_expires[] = {'E','x','p','i','r','e','s',0};
75 static const WCHAR attr_host[] = {'H','o','s','t',0};
76 static const WCHAR attr_if_match[] = {'I','f','-','M','a','t','c','h',0};
77 static const WCHAR attr_if_modified_since[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
78 static const WCHAR attr_if_none_match[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
79 static const WCHAR attr_if_range[] = {'I','f','-','R','a','n','g','e',0};
80 static const WCHAR attr_if_unmodified_since[] = {'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
81 static const WCHAR attr_last_modified[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
82 static const WCHAR attr_location[] = {'L','o','c','a','t','i','o','n',0};
83 static const WCHAR attr_max_forwards[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
84 static const WCHAR attr_mime_version[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
85 static const WCHAR attr_pragma[] = {'P','r','a','g','m','a',0};
86 static const WCHAR attr_proxy_authenticate[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
87 static const WCHAR attr_proxy_authorization[] = {'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0};
88 static const WCHAR attr_proxy_connection[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
89 static const WCHAR attr_public[] = {'P','u','b','l','i','c',0};
90 static const WCHAR attr_range[] = {'R','a','n','g','e',0};
91 static const WCHAR attr_referer[] = {'R','e','f','e','r','e','r',0};
92 static const WCHAR attr_retry_after[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
93 static const WCHAR attr_server[] = {'S','e','r','v','e','r',0};
94 static const WCHAR attr_set_cookie[] = {'S','e','t','-','C','o','o','k','i','e',0};
95 static const WCHAR attr_status[] = {'S','t','a','t','u','s',0};
96 static const WCHAR attr_transfer_encoding[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
97 static const WCHAR attr_unless_modified_since[] = {'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
98 static const WCHAR attr_upgrade[] = {'U','p','g','r','a','d','e',0};
99 static const WCHAR attr_uri[] = {'U','R','I',0};
100 static const WCHAR attr_user_agent[] = {'U','s','e','r','-','A','g','e','n','t',0};
101 static const WCHAR attr_vary[] = {'V','a','r','y',0};
102 static const WCHAR attr_via[] = {'V','i','a',0};
103 static const WCHAR attr_warning[] = {'W','a','r','n','i','n','g',0};
104 static const WCHAR attr_www_authenticate[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
105
106 static const WCHAR *attribute_table[] =
107 {
108 attr_mime_version, /* WINHTTP_QUERY_MIME_VERSION = 0 */
109 attr_content_type, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
110 attr_content_transfer_encoding, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
111 attr_content_id, /* WINHTTP_QUERY_CONTENT_ID = 3 */
112 NULL, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
113 attr_content_length, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
114 attr_content_language, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
115 attr_allow, /* WINHTTP_QUERY_ALLOW = 7 */
116 attr_public, /* WINHTTP_QUERY_PUBLIC = 8 */
117 attr_date, /* WINHTTP_QUERY_DATE = 9 */
118 attr_expires, /* WINHTTP_QUERY_EXPIRES = 10 */
119 attr_last_modified, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
120 NULL, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
121 attr_uri, /* WINHTTP_QUERY_URI = 13 */
122 attr_from, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
123 NULL, /* WINHTTP_QUERY_COST = 15 */
124 NULL, /* WINHTTP_QUERY_LINK = 16 */
125 attr_pragma, /* WINHTTP_QUERY_PRAGMA = 17 */
126 NULL, /* WINHTTP_QUERY_VERSION = 18 */
127 attr_status, /* WINHTTP_QUERY_STATUS_CODE = 19 */
128 NULL, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
129 NULL, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
130 NULL, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
131 attr_connection, /* WINHTTP_QUERY_CONNECTION = 23 */
132 attr_accept, /* WINHTTP_QUERY_ACCEPT = 24 */
133 attr_accept_charset, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
134 attr_accept_encoding, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
135 attr_accept_language, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
136 attr_authorization, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
137 attr_content_encoding, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
138 NULL, /* WINHTTP_QUERY_FORWARDED = 30 */
139 NULL, /* WINHTTP_QUERY_FROM = 31 */
140 attr_if_modified_since, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
141 attr_location, /* WINHTTP_QUERY_LOCATION = 33 */
142 NULL, /* WINHTTP_QUERY_ORIG_URI = 34 */
143 attr_referer, /* WINHTTP_QUERY_REFERER = 35 */
144 attr_retry_after, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
145 attr_server, /* WINHTTP_QUERY_SERVER = 37 */
146 NULL, /* WINHTTP_TITLE = 38 */
147 attr_user_agent, /* WINHTTP_QUERY_USER_AGENT = 39 */
148 attr_www_authenticate, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
149 attr_proxy_authenticate, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
150 attr_accept_ranges, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
151 attr_set_cookie, /* WINHTTP_QUERY_SET_COOKIE = 43 */
152 attr_cookie, /* WINHTTP_QUERY_COOKIE = 44 */
153 NULL, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
154 NULL, /* WINHTTP_QUERY_REFRESH = 46 */
155 NULL, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
156 attr_age, /* WINHTTP_QUERY_AGE = 48 */
157 attr_cache_control, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
158 attr_content_base, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
159 attr_content_location, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
160 attr_content_md5, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
161 attr_content_range, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
162 attr_etag, /* WINHTTP_QUERY_ETAG = 54 */
163 attr_host, /* WINHTTP_QUERY_HOST = 55 */
164 attr_if_match, /* WINHTTP_QUERY_IF_MATCH = 56 */
165 attr_if_none_match, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
166 attr_if_range, /* WINHTTP_QUERY_IF_RANGE = 58 */
167 attr_if_unmodified_since, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
168 attr_max_forwards, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
169 attr_proxy_authorization, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
170 attr_range, /* WINHTTP_QUERY_RANGE = 62 */
171 attr_transfer_encoding, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
172 attr_upgrade, /* WINHTTP_QUERY_UPGRADE = 64 */
173 attr_vary, /* WINHTTP_QUERY_VARY = 65 */
174 attr_via, /* WINHTTP_QUERY_VIA = 66 */
175 attr_warning, /* WINHTTP_QUERY_WARNING = 67 */
176 attr_expect, /* WINHTTP_QUERY_EXPECT = 68 */
177 attr_proxy_connection, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
178 attr_unless_modified_since, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
179 NULL, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
180 NULL, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
181 NULL, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
182 NULL /* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
183 };
184
185 static DWORD CALLBACK task_thread( LPVOID param )
186 {
187 task_header_t *task = param;
188
189 task->proc( task );
190
191 release_object( &task->request->hdr );
192 heap_free( task );
193 return ERROR_SUCCESS;
194 }
195
196 static BOOL queue_task( task_header_t *task )
197 {
198 return QueueUserWorkItem( task_thread, task, WT_EXECUTELONGFUNCTION );
199 }
200
201 static void free_header( header_t *header )
202 {
203 heap_free( header->field );
204 heap_free( header->value );
205 heap_free( header );
206 }
207
208 static BOOL valid_token_char( WCHAR c )
209 {
210 if (c < 32 || c == 127) return FALSE;
211 switch (c)
212 {
213 case '(': case ')':
214 case '<': case '>':
215 case '@': case ',':
216 case ';': case ':':
217 case '\\': case '\"':
218 case '/': case '[':
219 case ']': case '?':
220 case '=': case '{':
221 case '}': case ' ':
222 case '\t':
223 return FALSE;
224 default:
225 return TRUE;
226 }
227 }
228
229 static header_t *parse_header( LPCWSTR string )
230 {
231 const WCHAR *p, *q;
232 header_t *header;
233 int len;
234
235 p = string;
236 if (!(q = strchrW( p, ':' )))
237 {
238 WARN("no ':' in line %s\n", debugstr_w(string));
239 return NULL;
240 }
241 if (q == string)
242 {
243 WARN("empty field name in line %s\n", debugstr_w(string));
244 return NULL;
245 }
246 while (*p != ':')
247 {
248 if (!valid_token_char( *p ))
249 {
250 WARN("invalid character in field name %s\n", debugstr_w(string));
251 return NULL;
252 }
253 p++;
254 }
255 len = q - string;
256 if (!(header = heap_alloc_zero( sizeof(header_t) ))) return NULL;
257 if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
258 {
259 heap_free( header );
260 return NULL;
261 }
262 memcpy( header->field, string, len * sizeof(WCHAR) );
263 header->field[len] = 0;
264
265 q++; /* skip past colon */
266 while (*q == ' ') q++;
267 if (!*q)
268 {
269 WARN("no value in line %s\n", debugstr_w(string));
270 return header;
271 }
272 len = strlenW( q );
273 if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
274 {
275 free_header( header );
276 return NULL;
277 }
278 memcpy( header->value, q, len * sizeof(WCHAR) );
279 header->value[len] = 0;
280
281 return header;
282 }
283
284 static int get_header_index( request_t *request, LPCWSTR field, int requested_index, BOOL request_only )
285 {
286 int index;
287
288 TRACE("%s\n", debugstr_w(field));
289
290 for (index = 0; index < request->num_headers; index++)
291 {
292 if (strcmpiW( request->headers[index].field, field )) continue;
293 if (request_only && !request->headers[index].is_request) continue;
294 if (!request_only && request->headers[index].is_request) continue;
295
296 if (!requested_index) break;
297 requested_index--;
298 }
299 if (index >= request->num_headers) index = -1;
300 TRACE("returning %d\n", index);
301 return index;
302 }
303
304 static BOOL insert_header( request_t *request, header_t *header )
305 {
306 DWORD count;
307 header_t *hdrs;
308
309 count = request->num_headers + 1;
310 if (count > 1)
311 hdrs = heap_realloc_zero( request->headers, sizeof(header_t) * count );
312 else
313 hdrs = heap_alloc_zero( sizeof(header_t) * count );
314
315 if (hdrs)
316 {
317 request->headers = hdrs;
318 request->headers[count - 1].field = strdupW( header->field );
319 request->headers[count - 1].value = strdupW( header->value );
320 request->headers[count - 1].is_request = header->is_request;
321 request->num_headers++;
322 return TRUE;
323 }
324 return FALSE;
325 }
326
327 static BOOL delete_header( request_t *request, DWORD index )
328 {
329 if (!request->num_headers) return FALSE;
330 if (index >= request->num_headers) return FALSE;
331 request->num_headers--;
332
333 heap_free( request->headers[index].field );
334 heap_free( request->headers[index].value );
335
336 memmove( &request->headers[index], &request->headers[index + 1], (request->num_headers - index) * sizeof(header_t) );
337 memset( &request->headers[request->num_headers], 0, sizeof(header_t) );
338 return TRUE;
339 }
340
341 static BOOL process_header( request_t *request, LPCWSTR field, LPCWSTR value, DWORD flags, BOOL request_only )
342 {
343 int index;
344 header_t *header;
345
346 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
347
348 /* replace wins out over add */
349 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE) flags &= ~WINHTTP_ADDREQ_FLAG_ADD;
350
351 if (flags & WINHTTP_ADDREQ_FLAG_ADD) index = -1;
352 else
353 index = get_header_index( request, field, 0, request_only );
354
355 if (index >= 0)
356 {
357 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
358 header = &request->headers[index];
359 }
360 else if (value)
361 {
362 header_t hdr;
363
364 hdr.field = (LPWSTR)field;
365 hdr.value = (LPWSTR)value;
366 hdr.is_request = request_only;
367
368 return insert_header( request, &hdr );
369 }
370 /* no value to delete */
371 else return TRUE;
372
373 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
374 {
375 delete_header( request, index );
376 if (value)
377 {
378 header_t hdr;
379
380 hdr.field = (LPWSTR)field;
381 hdr.value = (LPWSTR)value;
382 hdr.is_request = request_only;
383
384 return insert_header( request, &hdr );
385 }
386 return TRUE;
387 }
388 else if (flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON))
389 {
390 WCHAR sep, *tmp;
391 int len, orig_len, value_len;
392
393 orig_len = strlenW( header->value );
394 value_len = strlenW( value );
395
396 if (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) sep = ',';
397 else sep = ';';
398
399 len = orig_len + value_len + 2;
400 if ((tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) )))
401 {
402 header->value = tmp;
403
404 header->value[orig_len] = sep;
405 orig_len++;
406 header->value[orig_len] = ' ';
407 orig_len++;
408
409 memcpy( &header->value[orig_len], value, value_len * sizeof(WCHAR) );
410 header->value[len] = 0;
411 return TRUE;
412 }
413 }
414 return TRUE;
415 }
416
417 BOOL add_request_headers( request_t *request, LPCWSTR headers, DWORD len, DWORD flags )
418 {
419 BOOL ret = FALSE;
420 WCHAR *buffer, *p, *q;
421 header_t *header;
422
423 if (len == ~0u) len = strlenW( headers );
424 if (!len) return TRUE;
425 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
426 strcpyW( buffer, headers );
427
428 p = buffer;
429 do
430 {
431 q = p;
432 while (*q)
433 {
434 if (q[0] == '\n' && q[1] == '\r')
435 {
436 q[0] = '\r';
437 q[1] = '\n';
438 }
439 if (q[0] == '\r' && q[1] == '\n') break;
440 q++;
441 }
442 if (!*p) break;
443 if (*q == '\r')
444 {
445 *q = 0;
446 q += 2; /* jump over \r\n */
447 }
448 if ((header = parse_header( p )))
449 {
450 ret = process_header( request, header->field, header->value, flags, TRUE );
451 free_header( header );
452 }
453 p = q;
454 } while (ret);
455
456 heap_free( buffer );
457 return ret;
458 }
459
460 /***********************************************************************
461 * WinHttpAddRequestHeaders (winhttp.@)
462 */
463 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
464 {
465 BOOL ret;
466 request_t *request;
467
468 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest, debugstr_w(headers), len, flags);
469
470 if (!headers)
471 {
472 set_last_error( ERROR_INVALID_PARAMETER );
473 return FALSE;
474 }
475 if (!(request = (request_t *)grab_object( hrequest )))
476 {
477 set_last_error( ERROR_INVALID_HANDLE );
478 return FALSE;
479 }
480 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
481 {
482 release_object( &request->hdr );
483 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
484 return FALSE;
485 }
486
487 ret = add_request_headers( request, headers, len, flags );
488
489 release_object( &request->hdr );
490 return ret;
491 }
492
493 static WCHAR *build_request_path( request_t *request )
494 {
495 WCHAR *ret;
496
497 if (strcmpiW( request->connect->hostname, request->connect->servername ))
498 {
499 static const WCHAR http[] = { 'h','t','t','p',0 };
500 static const WCHAR https[] = { 'h','t','t','p','s',0 };
501 static const WCHAR fmt[] = { '%','s',':','/','/','%','s',0 };
502 LPCWSTR scheme = request->netconn.secure ? https : http;
503 int len;
504
505 len = strlenW( scheme ) + strlenW( request->connect->hostname );
506 /* 3 characters for '://', 1 for NUL. */
507 len += 4;
508 if (request->connect->hostport)
509 {
510 /* 1 for ':' between host and port, up to 5 for port */
511 len += 6;
512 }
513 if (request->path)
514 len += strlenW( request->path );
515 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
516 {
517 sprintfW( ret, fmt, scheme, request->connect->hostname );
518 if (request->connect->hostport)
519 {
520 static const WCHAR colonFmt[] = { ':','%','u',0 };
521
522 sprintfW( ret + strlenW( ret ), colonFmt,
523 request->connect->hostport );
524 }
525 if (request->path)
526 strcatW( ret, request->path );
527 }
528 }
529 else
530 ret = request->path;
531 return ret;
532 }
533
534 static WCHAR *build_request_string( request_t *request )
535 {
536 static const WCHAR space[] = {' ',0};
537 static const WCHAR crlf[] = {'\r','\n',0};
538 static const WCHAR colon[] = {':',' ',0};
539 static const WCHAR twocrlf[] = {'\r','\n','\r','\n',0};
540
541 WCHAR *path, *ret;
542 const WCHAR **headers, **p;
543 unsigned int len, i = 0, j;
544
545 /* allocate space for an array of all the string pointers to be added */
546 len = request->num_headers * 4 + 7;
547 if (!(headers = heap_alloc( len * sizeof(LPCWSTR) ))) return NULL;
548
549 path = build_request_path( request );
550 headers[i++] = request->verb;
551 headers[i++] = space;
552 headers[i++] = path;
553 headers[i++] = space;
554 headers[i++] = request->version;
555
556 for (j = 0; j < request->num_headers; j++)
557 {
558 if (request->headers[j].is_request)
559 {
560 headers[i++] = crlf;
561 headers[i++] = request->headers[j].field;
562 headers[i++] = colon;
563 headers[i++] = request->headers[j].value;
564
565 TRACE("adding header %s (%s)\n", debugstr_w(request->headers[j].field),
566 debugstr_w(request->headers[j].value));
567 }
568 }
569 headers[i++] = twocrlf;
570 headers[i] = NULL;
571
572 len = 0;
573 for (p = headers; *p; p++) len += strlenW( *p );
574 len++;
575
576 if (!(ret = heap_alloc( len * sizeof(WCHAR) )))
577 goto out;
578 *ret = 0;
579 for (p = headers; *p; p++) strcatW( ret, *p );
580
581 out:
582 if (path != request->path)
583 heap_free( path );
584 heap_free( headers );
585 return ret;
586 }
587
588 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
589
590 static BOOL query_headers( request_t *request, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
591 {
592 header_t *header = NULL;
593 BOOL request_only, ret = FALSE;
594 int requested_index, header_index = -1;
595 DWORD attr, len;
596
597 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
598 requested_index = index ? *index : 0;
599
600 attr = level & ~QUERY_MODIFIER_MASK;
601 switch (attr)
602 {
603 case WINHTTP_QUERY_CUSTOM:
604 {
605 header_index = get_header_index( request, name, requested_index, request_only );
606 break;
607 }
608 case WINHTTP_QUERY_RAW_HEADERS:
609 {
610 WCHAR *headers, *p, *q;
611
612 if (request_only)
613 headers = build_request_string( request );
614 else
615 headers = request->raw_headers;
616
617 if (!(p = headers)) return FALSE;
618 for (len = 0; *p; p++) if (*p != '\r') len++;
619
620 if (!buffer || (len + 1) * sizeof(WCHAR) > *buflen)
621 {
622 len++;
623 set_last_error( ERROR_INSUFFICIENT_BUFFER );
624 }
625 else
626 {
627 for (p = headers, q = buffer; *p; p++, q++)
628 {
629 if (*p != '\r') *q = *p;
630 else
631 {
632 *q = 0;
633 p++; /* skip '\n' */
634 }
635 }
636 *q = 0;
637 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
638 ret = TRUE;
639 }
640 *buflen = len * sizeof(WCHAR);
641 if (request_only) heap_free( headers );
642 return ret;
643 }
644 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
645 {
646 WCHAR *headers;
647
648 if (request_only)
649 headers = build_request_string( request );
650 else
651 headers = request->raw_headers;
652
653 if (!headers) return FALSE;
654 len = strlenW( headers ) * sizeof(WCHAR);
655 if (!buffer || len + sizeof(WCHAR) > *buflen)
656 {
657 len += sizeof(WCHAR);
658 set_last_error( ERROR_INSUFFICIENT_BUFFER );
659 }
660 else
661 {
662 memcpy( buffer, headers, len + sizeof(WCHAR) );
663 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
664 ret = TRUE;
665 }
666 *buflen = len;
667 if (request_only) heap_free( headers );
668 return ret;
669 }
670 case WINHTTP_QUERY_VERSION:
671 len = strlenW( request->version ) * sizeof(WCHAR);
672 if (!buffer || len + sizeof(WCHAR) > *buflen)
673 {
674 len += sizeof(WCHAR);
675 set_last_error( ERROR_INSUFFICIENT_BUFFER );
676 }
677 else
678 {
679 strcpyW( buffer, request->version );
680 TRACE("returning string: %s\n", debugstr_w(buffer));
681 ret = TRUE;
682 }
683 *buflen = len;
684 return ret;
685
686 case WINHTTP_QUERY_STATUS_TEXT:
687 len = strlenW( request->status_text ) * sizeof(WCHAR);
688 if (!buffer || len + sizeof(WCHAR) > *buflen)
689 {
690 len += sizeof(WCHAR);
691 set_last_error( ERROR_INSUFFICIENT_BUFFER );
692 }
693 else
694 {
695 strcpyW( buffer, request->status_text );
696 TRACE("returning string: %s\n", debugstr_w(buffer));
697 ret = TRUE;
698 }
699 *buflen = len;
700 return ret;
701
702 default:
703 if (attr >= sizeof(attribute_table)/sizeof(attribute_table[0]) || !attribute_table[attr])
704 {
705 FIXME("attribute %u not implemented\n", attr);
706 return FALSE;
707 }
708 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
709 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
710 break;
711 }
712
713 if (header_index >= 0)
714 {
715 header = &request->headers[header_index];
716 }
717 if (!header || (request_only && !header->is_request))
718 {
719 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
720 return FALSE;
721 }
722 if (index) *index += 1;
723 if (level & WINHTTP_QUERY_FLAG_NUMBER)
724 {
725 if (!buffer || sizeof(int) > *buflen)
726 {
727 set_last_error( ERROR_INSUFFICIENT_BUFFER );
728 }
729 else
730 {
731 int *number = buffer;
732 *number = atoiW( header->value );
733 TRACE("returning number: %d\n", *number);
734 ret = TRUE;
735 }
736 *buflen = sizeof(int);
737 }
738 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
739 {
740 SYSTEMTIME *st = buffer;
741 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
742 {
743 set_last_error( ERROR_INSUFFICIENT_BUFFER );
744 }
745 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
746 {
747 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
748 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
749 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
750 }
751 *buflen = sizeof(SYSTEMTIME);
752 }
753 else if (header->value)
754 {
755 len = strlenW( header->value ) * sizeof(WCHAR);
756 if (!buffer || len + sizeof(WCHAR) > *buflen)
757 {
758 len += sizeof(WCHAR);
759 set_last_error( ERROR_INSUFFICIENT_BUFFER );
760 }
761 else
762 {
763 strcpyW( buffer, header->value );
764 TRACE("returning string: %s\n", debugstr_w(buffer));
765 ret = TRUE;
766 }
767 *buflen = len;
768 }
769 return ret;
770 }
771
772 /***********************************************************************
773 * WinHttpQueryHeaders (winhttp.@)
774 */
775 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
776 {
777 BOOL ret;
778 request_t *request;
779
780 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
781
782 if (!(request = (request_t *)grab_object( hrequest )))
783 {
784 set_last_error( ERROR_INVALID_HANDLE );
785 return FALSE;
786 }
787 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
788 {
789 release_object( &request->hdr );
790 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
791 return FALSE;
792 }
793
794 ret = query_headers( request, level, name, buffer, buflen, index );
795
796 release_object( &request->hdr );
797 return ret;
798 }
799
800 static LPWSTR concatenate_string_list( LPCWSTR *list, int len )
801 {
802 LPCWSTR *t;
803 LPWSTR str;
804
805 for( t = list; *t ; t++ )
806 len += strlenW( *t );
807 len++;
808
809 str = heap_alloc( len * sizeof(WCHAR) );
810 if (!str) return NULL;
811 *str = 0;
812
813 for( t = list; *t ; t++ )
814 strcatW( str, *t );
815
816 return str;
817 }
818
819 static LPWSTR build_header_request_string( request_t *request, LPCWSTR verb,
820 LPCWSTR path, LPCWSTR version )
821 {
822 static const WCHAR crlf[] = {'\r','\n',0};
823 static const WCHAR space[] = { ' ',0 };
824 static const WCHAR colon[] = { ':',' ',0 };
825 static const WCHAR twocrlf[] = {'\r','\n','\r','\n', 0};
826 LPWSTR requestString;
827 DWORD len, n;
828 LPCWSTR *req;
829 UINT i;
830 LPWSTR p;
831
832 /* allocate space for an array of all the string pointers to be added */
833 len = (request->num_headers) * 4 + 10;
834 req = heap_alloc( len * sizeof(LPCWSTR) );
835 if (!req) return NULL;
836
837 /* add the verb, path and HTTP version string */
838 n = 0;
839 req[n++] = verb;
840 req[n++] = space;
841 req[n++] = path;
842 req[n++] = space;
843 req[n++] = version;
844
845 /* Append custom request headers */
846 for (i = 0; i < request->num_headers; i++)
847 {
848 if (request->headers[i].is_request)
849 {
850 req[n++] = crlf;
851 req[n++] = request->headers[i].field;
852 req[n++] = colon;
853 req[n++] = request->headers[i].value;
854
855 TRACE("Adding custom header %s (%s)\n",
856 debugstr_w(request->headers[i].field),
857 debugstr_w(request->headers[i].value));
858 }
859 }
860
861 if( n >= len )
862 ERR("oops. buffer overrun\n");
863
864 req[n] = NULL;
865 requestString = concatenate_string_list( req, 4 );
866 heap_free( req );
867 if (!requestString) return NULL;
868
869 /*
870 * Set (header) termination string for request
871 * Make sure there's exactly two new lines at the end of the request
872 */
873 p = &requestString[strlenW(requestString)-1];
874 while ( (*p == '\n') || (*p == '\r') )
875 p--;
876 strcpyW( p+1, twocrlf );
877
878 return requestString;
879 }
880
881 static BOOL read_reply( request_t *request );
882
883 static BOOL secure_proxy_connect( request_t *request )
884 {
885 static const WCHAR verbConnect[] = {'C','O','N','N','E','C','T',0};
886 static const WCHAR fmt[] = {'%','s',':','%','u',0};
887 BOOL ret = FALSE;
888 LPWSTR path;
889 connect_t *connect = request->connect;
890
891 path = heap_alloc( (strlenW( connect->hostname ) + 13) * sizeof(WCHAR) );
892 if (path)
893 {
894 LPWSTR requestString;
895
896 sprintfW( path, fmt, connect->hostname, connect->hostport );
897 requestString = build_header_request_string( request, verbConnect,
898 path, http1_1 );
899 heap_free( path );
900 if (requestString)
901 {
902 LPSTR req_ascii = strdupWA( requestString );
903
904 heap_free( requestString );
905 if (req_ascii)
906 {
907 int len = strlen( req_ascii ), bytes_sent;
908
909 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
910 heap_free( req_ascii );
911 if (ret)
912 ret = read_reply( request );
913 }
914 }
915 }
916 return ret;
917 }
918
919 #ifndef INET6_ADDRSTRLEN
920 #define INET6_ADDRSTRLEN 46
921 #endif
922
923 static WCHAR *addr_to_str( const struct sockaddr *addr )
924 {
925 char buf[INET6_ADDRSTRLEN];
926 const void *src;
927
928 switch (addr->sa_family)
929 {
930 case AF_INET:
931 src = &((struct sockaddr_in *)addr)->sin_addr;
932 break;
933 case AF_INET6:
934 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
935 break;
936 default:
937 WARN("unsupported address family %d\n", addr->sa_family);
938 return NULL;
939 }
940 if (!inet_ntop( addr->sa_family, src, buf, sizeof(buf) )) return NULL;
941 return strdupAW( buf );
942 }
943
944 static BOOL open_connection( request_t *request )
945 {
946 connect_t *connect;
947 WCHAR *addressW = NULL;
948 INTERNET_PORT port;
949 socklen_t slen;
950 struct sockaddr *saddr;
951 DWORD len;
952
953 if (netconn_connected( &request->netconn )) goto done;
954
955 connect = request->connect;
956 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
957 saddr = (struct sockaddr *)&connect->sockaddr;
958 slen = sizeof(struct sockaddr);
959
960 if (!connect->resolved)
961 {
962 len = strlenW( connect->servername ) + 1;
963 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, connect->servername, len );
964
965 if (!netconn_resolve( connect->servername, port, saddr, &slen, request->resolve_timeout )) return FALSE;
966 connect->resolved = TRUE;
967
968 if (!(addressW = addr_to_str( saddr ))) return FALSE;
969 len = strlenW( addressW ) + 1;
970 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
971 }
972 if (!addressW && !(addressW = addr_to_str( saddr ))) return FALSE;
973 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
974
975 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
976
977 if (!netconn_create( &request->netconn, saddr->sa_family, SOCK_STREAM, 0 ))
978 {
979 heap_free( addressW );
980 return FALSE;
981 }
982 netconn_set_timeout( &request->netconn, TRUE, request->send_timeout );
983 netconn_set_timeout( &request->netconn, FALSE, request->recv_timeout );
984 if (!netconn_connect( &request->netconn, saddr, slen, request->connect_timeout ))
985 {
986 netconn_close( &request->netconn );
987 heap_free( addressW );
988 return FALSE;
989 }
990 if (request->hdr.flags & WINHTTP_FLAG_SECURE)
991 {
992 if (connect->session->proxy_server &&
993 strcmpiW( connect->hostname, connect->servername ))
994 {
995 if (!secure_proxy_connect( request ))
996 {
997 heap_free( addressW );
998 return FALSE;
999 }
1000 }
1001 if (!netconn_secure_connect( &request->netconn, connect->servername ))
1002 {
1003 netconn_close( &request->netconn );
1004 heap_free( addressW );
1005 return FALSE;
1006 }
1007 }
1008
1009 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
1010
1011 done:
1012 request->read_pos = request->read_size = 0;
1013 request->read_chunked = FALSE;
1014 heap_free( addressW );
1015 return TRUE;
1016 }
1017
1018 void close_connection( request_t *request )
1019 {
1020 if (!netconn_connected( &request->netconn )) return;
1021
1022 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1023 netconn_close( &request->netconn );
1024 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1025 }
1026
1027 static BOOL add_host_header( request_t *request, DWORD modifier )
1028 {
1029 BOOL ret;
1030 DWORD len;
1031 WCHAR *host;
1032 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1033 connect_t *connect = request->connect;
1034 INTERNET_PORT port;
1035
1036 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1037
1038 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1039 {
1040 return process_header( request, attr_host, connect->hostname, modifier, TRUE );
1041 }
1042 len = strlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1043 if (!(host = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1044 sprintfW( host, fmt, connect->hostname, port );
1045 ret = process_header( request, attr_host, host, modifier, TRUE );
1046 heap_free( host );
1047 return ret;
1048 }
1049
1050 static void clear_response_headers( request_t *request )
1051 {
1052 unsigned int i;
1053
1054 for (i = 0; i < request->num_headers; i++)
1055 {
1056 if (!request->headers[i].field) continue;
1057 if (!request->headers[i].value) continue;
1058 if (request->headers[i].is_request) continue;
1059 delete_header( request, i );
1060 i--;
1061 }
1062 }
1063
1064 static BOOL send_request( request_t *request, LPCWSTR headers, DWORD headers_len, LPVOID optional,
1065 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
1066 {
1067 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
1068 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
1069 static const WCHAR length_fmt[] = {'%','l','d',0};
1070
1071 BOOL ret = FALSE;
1072 connect_t *connect = request->connect;
1073 session_t *session = connect->session;
1074 WCHAR *req = NULL;
1075 char *req_ascii;
1076 int bytes_sent;
1077 DWORD len, i, flags;
1078
1079 clear_response_headers( request );
1080
1081 flags = WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
1082 for (i = 0; i < request->num_accept_types; i++)
1083 {
1084 process_header( request, attr_accept, request->accept_types[i], flags, TRUE );
1085 }
1086 if (session->agent)
1087 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1088
1089 if (connect->hostname)
1090 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
1091
1092 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
1093 {
1094 WCHAR length[21]; /* decimal long int + null */
1095 sprintfW( length, length_fmt, total_len );
1096 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1097 }
1098 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
1099 {
1100 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1101 }
1102 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
1103 {
1104 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1105 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1106 }
1107 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
1108 {
1109 TRACE("failed to add request headers\n");
1110 return FALSE;
1111 }
1112 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
1113 {
1114 WARN("failed to add cookie headers\n");
1115 return FALSE;
1116 }
1117
1118 if (context) request->hdr.context = context;
1119
1120 if (!(ret = open_connection( request ))) goto end;
1121 if (!(req = build_request_string( request ))) goto end;
1122
1123 if (!(req_ascii = strdupWA( req ))) goto end;
1124 TRACE("full request: %s\n", debugstr_a(req_ascii));
1125 len = strlen(req_ascii);
1126
1127 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
1128
1129 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
1130 heap_free( req_ascii );
1131 if (!ret) goto end;
1132
1133 if (optional_len)
1134 {
1135 if (!netconn_send( &request->netconn, optional, optional_len, &bytes_sent )) goto end;
1136 request->optional = optional;
1137 request->optional_len = optional_len;
1138 len += optional_len;
1139 }
1140 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(DWORD) );
1141
1142 end:
1143 if (async)
1144 {
1145 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
1146 else
1147 {
1148 WINHTTP_ASYNC_RESULT result;
1149 result.dwResult = API_SEND_REQUEST;
1150 result.dwError = get_last_error();
1151 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
1152 }
1153 }
1154 heap_free( req );
1155 return ret;
1156 }
1157
1158 static void task_send_request( task_header_t *task )
1159 {
1160 send_request_t *s = (send_request_t *)task;
1161 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
1162 heap_free( s->headers );
1163 }
1164
1165 /***********************************************************************
1166 * WinHttpSendRequest (winhttp.@)
1167 */
1168 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
1169 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
1170 {
1171 BOOL ret;
1172 request_t *request;
1173
1174 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1175 hrequest, debugstr_w(headers), headers_len, optional_len, total_len, context);
1176
1177 if (!(request = (request_t *)grab_object( hrequest )))
1178 {
1179 set_last_error( ERROR_INVALID_HANDLE );
1180 return FALSE;
1181 }
1182 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1183 {
1184 release_object( &request->hdr );
1185 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1186 return FALSE;
1187 }
1188
1189 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
1190 {
1191 send_request_t *s;
1192
1193 if (!(s = heap_alloc( sizeof(send_request_t) ))) return FALSE;
1194 s->hdr.request = request;
1195 s->hdr.proc = task_send_request;
1196 s->headers = strdupW( headers );
1197 s->headers_len = headers_len;
1198 s->optional = optional;
1199 s->optional_len = optional_len;
1200 s->total_len = total_len;
1201 s->context = context;
1202
1203 addref_object( &request->hdr );
1204 ret = queue_task( (task_header_t *)s );
1205 }
1206 else
1207 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
1208
1209 release_object( &request->hdr );
1210 return ret;
1211 }
1212
1213 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1214
1215 static const WCHAR basicW[] = {'B','a','s','i','c',0};
1216 static const WCHAR ntlmW[] = {'N','T','L','M',0};
1217 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
1218 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
1219 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
1220
1221 static const struct
1222 {
1223 const WCHAR *str;
1224 unsigned int len;
1225 DWORD scheme;
1226 }
1227 auth_schemes[] =
1228 {
1229 { basicW, ARRAYSIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
1230 { ntlmW, ARRAYSIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
1231 { passportW, ARRAYSIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
1232 { digestW, ARRAYSIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
1233 { negotiateW, ARRAYSIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
1234 };
1235 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
1236
1237 static enum auth_scheme scheme_from_flag( DWORD flag )
1238 {
1239 int i;
1240
1241 for (i = 0; i < num_auth_schemes; i++) if (flag == auth_schemes[i].scheme) return i;
1242 return SCHEME_INVALID;
1243 }
1244
1245 static DWORD auth_scheme_from_header( WCHAR *header )
1246 {
1247 unsigned int i;
1248
1249 for (i = 0; i < num_auth_schemes; i++)
1250 {
1251 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
1252 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
1253 }
1254 return 0;
1255 }
1256
1257 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
1258 {
1259 DWORD index = 0;
1260 BOOL ret = FALSE;
1261
1262 for (;;)
1263 {
1264 WCHAR *buffer;
1265 DWORD size, scheme;
1266
1267 size = 0;
1268 query_headers( request, level, NULL, NULL, &size, &index );
1269 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) break;
1270
1271 index--;
1272 if (!(buffer = heap_alloc( size ))) return FALSE;
1273 if (!query_headers( request, level, NULL, buffer, &size, &index ))
1274 {
1275 heap_free( buffer );
1276 return FALSE;
1277 }
1278 scheme = auth_scheme_from_header( buffer );
1279 heap_free( buffer );
1280 if (!scheme) break;
1281
1282 if (first && index == 1)
1283 *first = *supported = scheme;
1284 else
1285 *supported |= scheme;
1286
1287 ret = TRUE;
1288 }
1289 return ret;
1290 }
1291
1292 /***********************************************************************
1293 * WinHttpQueryAuthSchemes (winhttp.@)
1294 */
1295 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
1296 {
1297 BOOL ret = FALSE;
1298 request_t *request;
1299
1300 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
1301
1302 if (!(request = (request_t *)grab_object( hrequest )))
1303 {
1304 set_last_error( ERROR_INVALID_HANDLE );
1305 return FALSE;
1306 }
1307 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1308 {
1309 release_object( &request->hdr );
1310 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1311 return FALSE;
1312 }
1313 if (!supported || !first || !target)
1314 {
1315 release_object( &request->hdr );
1316 set_last_error( ERROR_INVALID_PARAMETER );
1317 return FALSE;
1318
1319 }
1320
1321 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
1322 {
1323 *target = WINHTTP_AUTH_TARGET_SERVER;
1324 ret = TRUE;
1325 }
1326 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
1327 {
1328 *target = WINHTTP_AUTH_TARGET_PROXY;
1329 ret = TRUE;
1330 }
1331
1332 release_object( &request->hdr );
1333 return ret;
1334 }
1335
1336 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
1337 {
1338 UINT n = 0, x;
1339 static const char base64enc[] =
1340 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1341
1342 while (len > 0)
1343 {
1344 /* first 6 bits, all from bin[0] */
1345 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
1346 x = (bin[0] & 3) << 4;
1347
1348 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1349 if (len == 1)
1350 {
1351 base64[n++] = base64enc[x];
1352 base64[n++] = '=';
1353 base64[n++] = '=';
1354 break;
1355 }
1356 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
1357 x = (bin[1] & 0x0f) << 2;
1358
1359 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1360 if (len == 2)
1361 {
1362 base64[n++] = base64enc[x];
1363 base64[n++] = '=';
1364 break;
1365 }
1366 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1367
1368 /* last 6 bits, all from bin [2] */
1369 base64[n++] = base64enc[bin[2] & 0x3f];
1370 bin += 3;
1371 len -= 3;
1372 }
1373 base64[n] = 0;
1374 return n;
1375 }
1376
1377 static inline char decode_char( WCHAR c )
1378 {
1379 if (c >= 'A' && c <= 'Z') return c - 'A';
1380 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1381 if (c >= '0' && c <= '9') return c - '0' + 52;
1382 if (c == '+') return 62;
1383 if (c == '/') return 63;
1384 return 64;
1385 }
1386
1387 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1388 {
1389 unsigned int i = 0;
1390 char c0, c1, c2, c3;
1391 const WCHAR *p = base64;
1392
1393 while (len >= 4)
1394 {
1395 if ((c0 = decode_char( p[0] )) > 63) return 0;
1396 if ((c1 = decode_char( p[1] )) > 63) return 0;
1397 if ((c2 = decode_char( p[2] )) > 63) return 0;
1398 if ((c3 = decode_char( p[3] )) > 63) return 0;
1399
1400 if (buf)
1401 {
1402 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1403 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1404 buf[i + 2] = (c2 << 6) | c3;
1405 }
1406 len -= 4;
1407 i += 3;
1408 p += 4;
1409 }
1410 if (p[2] == '=')
1411 {
1412 if ((c0 = decode_char( p[0] )) > 63) return 0;
1413 if ((c1 = decode_char( p[1] )) > 63) return 0;
1414
1415 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1416 i++;
1417 }
1418 else if (p[3] == '=')
1419 {
1420 if ((c0 = decode_char( p[0] )) > 63) return 0;
1421 if ((c1 = decode_char( p[1] )) > 63) return 0;
1422 if ((c2 = decode_char( p[2] )) > 63) return 0;
1423
1424 if (buf)
1425 {
1426 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1427 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1428 }
1429 i += 2;
1430 }
1431 return i;
1432 }
1433
1434 static struct authinfo *alloc_authinfo(void)
1435 {
1436 struct authinfo *ret;
1437
1438 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1439
1440 SecInvalidateHandle( &ret->cred );
1441 SecInvalidateHandle( &ret->ctx );
1442 memset( &ret->exp, 0, sizeof(ret->exp) );
1443 ret->scheme = 0;
1444 ret->attr = 0;
1445 ret->max_token = 0;
1446 ret->data = NULL;
1447 ret->data_len = 0;
1448 ret->finished = FALSE;
1449 return ret;
1450 }
1451
1452 void destroy_authinfo( struct authinfo *authinfo )
1453 {
1454 if (!authinfo) return;
1455
1456 if (SecIsValidHandle( &authinfo->ctx ))
1457 DeleteSecurityContext( &authinfo->ctx );
1458 if (SecIsValidHandle( &authinfo->cred ))
1459 FreeCredentialsHandle( &authinfo->cred );
1460
1461 heap_free( authinfo->data );
1462 heap_free( authinfo );
1463 }
1464
1465 static BOOL get_authvalue( request_t *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1466 {
1467 DWORD size, index = 0;
1468 for (;;)
1469 {
1470 size = len;
1471 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1472 if (auth_scheme_from_header( buffer ) == scheme) break;
1473 }
1474 return TRUE;
1475 }
1476
1477 static BOOL do_authorization( request_t *request, DWORD target, DWORD scheme_flag )
1478 {
1479 struct authinfo *authinfo, **auth_ptr;
1480 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1481 const WCHAR *auth_target, *username, *password;
1482 WCHAR auth_value[2048], *auth_reply;
1483 DWORD len = sizeof(auth_value), len_scheme, flags;
1484 BOOL ret;
1485
1486 if (scheme == SCHEME_INVALID) return FALSE;
1487
1488 switch (target)
1489 {
1490 case WINHTTP_AUTH_TARGET_SERVER:
1491 if (!get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len ))
1492 return FALSE;
1493 auth_ptr = &request->authinfo;
1494 auth_target = attr_authorization;
1495 username = request->connect->username;
1496 password = request->connect->password;
1497 break;
1498
1499 case WINHTTP_AUTH_TARGET_PROXY:
1500 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1501 return FALSE;
1502 auth_ptr = &request->proxy_authinfo;
1503 auth_target = attr_proxy_authorization;
1504 username = request->connect->session->proxy_username;
1505 password = request->connect->session->proxy_password;
1506 break;
1507
1508 default:
1509 WARN("unknown target %x\n", target);
1510 return FALSE;
1511 }
1512 authinfo = *auth_ptr;
1513
1514 switch (scheme)
1515 {
1516 case SCHEME_BASIC:
1517 {
1518 int userlen, passlen;
1519
1520 if (!username || !password) return FALSE;
1521 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1522
1523 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1524 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1525
1526 authinfo->data_len = userlen + 1 + passlen;
1527 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1528
1529 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1530 authinfo->data[userlen] = ':';
1531 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1532
1533 authinfo->scheme = SCHEME_BASIC;
1534 authinfo->finished = TRUE;
1535 break;
1536 }
1537 case SCHEME_NTLM:
1538 case SCHEME_NEGOTIATE:
1539 {
1540 SECURITY_STATUS status;
1541 SecBufferDesc out_desc, in_desc;
1542 SecBuffer out, in;
1543 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1544 const WCHAR *p;
1545 BOOL first = FALSE;
1546
1547 if (!authinfo)
1548 {
1549 TimeStamp exp;
1550 SEC_WINNT_AUTH_IDENTITY_W id;
1551 WCHAR *domain, *user;
1552
1553 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1554
1555 first = TRUE;
1556 domain = (WCHAR *)username;
1557 user = strchrW( username, '\\' );
1558
1559 if (user) user++;
1560 else
1561 {
1562 user = (WCHAR *)username;
1563 domain = NULL;
1564 }
1565 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1566 id.User = user;
1567 id.UserLength = strlenW( user );
1568 id.Domain = domain;
1569 id.DomainLength = domain ? user - domain - 1 : 0;
1570 id.Password = (WCHAR *)password;
1571 id.PasswordLength = strlenW( password );
1572
1573 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1574 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1575 &authinfo->cred, &exp );
1576 if (status == SEC_E_OK)
1577 {
1578 PSecPkgInfoW info;
1579 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1580 if (status == SEC_E_OK)
1581 {
1582 authinfo->max_token = info->cbMaxToken;
1583 FreeContextBuffer( info );
1584 }
1585 }
1586 if (status != SEC_E_OK)
1587 {
1588 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1589 debugstr_w(auth_schemes[scheme].str), status);
1590 heap_free( authinfo );
1591 return FALSE;
1592 }
1593 authinfo->scheme = scheme;
1594 }
1595 else if (authinfo->finished) return FALSE;
1596
1597 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1598 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1599 {
1600 ERR("authentication scheme changed from %s to %s\n",
1601 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1602 destroy_authinfo( authinfo );
1603 *auth_ptr = NULL;
1604 return FALSE;
1605 }
1606 in.BufferType = SECBUFFER_TOKEN;
1607 in.cbBuffer = 0;
1608 in.pvBuffer = NULL;
1609
1610 in_desc.ulVersion = 0;
1611 in_desc.cBuffers = 1;
1612 in_desc.pBuffers = &in;
1613
1614 p = auth_value + auth_schemes[scheme].len;
1615 if (*p == ' ')
1616 {
1617 int len = strlenW( ++p );
1618 in.cbBuffer = decode_base64( p, len, NULL );
1619 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) return FALSE;
1620 decode_base64( p, len, in.pvBuffer );
1621 }
1622 out.BufferType = SECBUFFER_TOKEN;
1623 out.cbBuffer = authinfo->max_token;
1624 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1625 {
1626 heap_free( in.pvBuffer );
1627 return FALSE;
1628 }
1629 out_desc.ulVersion = 0;
1630 out_desc.cBuffers = 1;
1631 out_desc.pBuffers = &out;
1632
1633 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1634 first ? request->connect->servername : NULL, flags, 0,
1635 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1636 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1637 heap_free( in.pvBuffer );
1638 if (status == SEC_E_OK)
1639 {
1640 heap_free( authinfo->data );
1641 authinfo->data = out.pvBuffer;
1642 authinfo->data_len = out.cbBuffer;
1643 authinfo->finished = TRUE;
1644 TRACE("sending last auth packet\n");
1645 }
1646 else if (status == SEC_I_CONTINUE_NEEDED)
1647 {
1648 heap_free( authinfo->data );
1649 authinfo->data = out.pvBuffer;
1650 authinfo->data_len = out.cbBuffer;
1651 TRACE("sending next auth packet\n");
1652 }
1653 else
1654 {
1655 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1656 heap_free( out.pvBuffer );
1657 destroy_authinfo( authinfo );
1658 *auth_ptr = NULL;
1659 return FALSE;
1660 }
1661 break;
1662 }
1663 default:
1664 ERR("invalid scheme %u\n", scheme);
1665 return FALSE;
1666 }
1667 *auth_ptr = authinfo;
1668
1669 len_scheme = auth_schemes[authinfo->scheme].len;
1670 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1671 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1672
1673 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1674 auth_reply[len_scheme] = ' ';
1675 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1676
1677 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1678 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1679 heap_free( auth_reply );
1680 return ret;
1681 }
1682
1683 static BOOL set_credentials( request_t *request, DWORD target, DWORD scheme, const WCHAR *username,
1684 const WCHAR *password )
1685 {
1686 if ((scheme == WINHTTP_AUTH_SCHEME_BASIC || scheme == WINHTTP_AUTH_SCHEME_DIGEST) &&
1687 (!username || !password))
1688 {
1689 set_last_error( ERROR_INVALID_PARAMETER );
1690 return FALSE;
1691 }
1692 switch (target)
1693 {
1694 case WINHTTP_AUTH_TARGET_SERVER:
1695 {
1696 heap_free( request->connect->username );
1697 if (!username) request->connect->username = NULL;
1698 else if (!(request->connect->username = strdupW( username ))) return FALSE;
1699
1700 heap_free( request->connect->password );
1701 if (!password) request->connect->password = NULL;
1702 else if (!(request->connect->password = strdupW( password ))) return FALSE;
1703 break;
1704 }
1705 case WINHTTP_AUTH_TARGET_PROXY:
1706 {
1707 heap_free( request->connect->session->proxy_username );
1708 if (!username) request->connect->session->proxy_username = NULL;
1709 else if (!(request->connect->session->proxy_username = strdupW( username ))) return FALSE;
1710
1711 heap_free( request->connect->session->proxy_password );
1712 if (!password) request->connect->session->proxy_password = NULL;
1713 else if (!(request->connect->session->proxy_password = strdupW( password ))) return FALSE;
1714 break;
1715 }
1716 default:
1717 WARN("unknown target %u\n", target);
1718 return FALSE;
1719 }
1720 return TRUE;
1721 }
1722
1723 /***********************************************************************
1724 * WinHttpSetCredentials (winhttp.@)
1725 */
1726 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
1727 LPCWSTR password, LPVOID params )
1728 {
1729 BOOL ret;
1730 request_t *request;
1731
1732 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
1733
1734 if (!(request = (request_t *)grab_object( hrequest )))
1735 {
1736 set_last_error( ERROR_INVALID_HANDLE );
1737 return FALSE;
1738 }
1739 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1740 {
1741 release_object( &request->hdr );
1742 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1743 return FALSE;
1744 }
1745
1746 ret = set_credentials( request, target, scheme, username, password );
1747
1748 release_object( &request->hdr );
1749 return ret;
1750 }
1751
1752 static BOOL handle_authorization( request_t *request, DWORD status )
1753 {
1754 DWORD i, schemes, first, level, target;
1755
1756 switch (status)
1757 {
1758 case HTTP_STATUS_DENIED:
1759 target = WINHTTP_AUTH_TARGET_SERVER;
1760 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
1761 break;
1762
1763 case HTTP_STATUS_PROXY_AUTH_REQ:
1764 target = WINHTTP_AUTH_TARGET_PROXY;
1765 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
1766 break;
1767
1768 default:
1769 WARN("unhandled status %u\n", status);
1770 return FALSE;
1771 }
1772
1773 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
1774 if (do_authorization( request, target, first )) return TRUE;
1775
1776 schemes &= ~first;
1777 for (i = 0; i < num_auth_schemes; i++)
1778 {
1779 if (!(schemes & auth_schemes[i].scheme)) continue;
1780 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
1781 }
1782 return FALSE;
1783 }
1784
1785 /* set the request content length based on the headers */
1786 static DWORD set_content_length( request_t *request )
1787 {
1788 WCHAR encoding[20];
1789 DWORD buflen;
1790
1791 buflen = sizeof(request->content_length);
1792 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
1793 NULL, &request->content_length, &buflen, NULL ))
1794 request->content_length = ~0u;
1795
1796 buflen = sizeof(encoding);
1797 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
1798 !strcmpiW( encoding, chunkedW ))
1799 {
1800 request->content_length = ~0u;
1801 request->read_chunked = TRUE;
1802 }
1803 request->content_read = 0;
1804 return request->content_length;
1805 }
1806
1807 /* read some more data into the read buffer */
1808 static BOOL read_more_data( request_t *request, int maxlen )
1809 {
1810 int len;
1811
1812 if (request->read_size && request->read_pos)
1813 {
1814 /* move existing data to the start of the buffer */
1815 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1816 request->read_pos = 0;
1817 }
1818 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1819 if (!netconn_recv( &request->netconn, request->read_buf + request->read_size,
1820 maxlen - request->read_size, 0, &len )) return FALSE;
1821 request->read_size += len;
1822 return TRUE;
1823 }
1824
1825 /* remove some amount of data from the read buffer */
1826 static void remove_data( request_t *request, int count )
1827 {
1828 if (!(request->read_size -= count)) request->read_pos = 0;
1829 else request->read_pos += count;
1830 }
1831
1832 static BOOL read_line( request_t *request, char *buffer, DWORD *len )
1833 {
1834 int count, bytes_read, pos = 0;
1835
1836 for (;;)
1837 {
1838 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1839 if (eol)
1840 {
1841 count = eol - (request->read_buf + request->read_pos);
1842 bytes_read = count + 1;
1843 }
1844 else count = bytes_read = request->read_size;
1845
1846 count = min( count, *len - pos );
1847 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
1848 pos += count;
1849 remove_data( request, bytes_read );
1850 if (eol) break;
1851
1852 if (!read_more_data( request, -1 )) return FALSE;
1853 if (!request->read_size)
1854 {
1855 *len = 0;
1856 TRACE("returning empty string\n");
1857 return FALSE;
1858 }
1859 }
1860 if (pos < *len)
1861 {
1862 if (pos && buffer[pos - 1] == '\r') pos--;
1863 *len = pos + 1;
1864 }
1865 buffer[*len - 1] = 0;
1866 TRACE("returning %s\n", debugstr_a(buffer));
1867 return TRUE;
1868 }
1869
1870 /* discard data contents until we reach end of line */
1871 static BOOL discard_eol( request_t *request )
1872 {
1873 do
1874 {
1875 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1876 if (eol)
1877 {
1878 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1879 break;
1880 }
1881 request->read_pos = request->read_size = 0; /* discard everything */
1882 if (!read_more_data( request, -1 )) return FALSE;
1883 } while (request->read_size);
1884 return TRUE;
1885 }
1886
1887 /* read the size of the next chunk */
1888 static BOOL start_next_chunk( request_t *request )
1889 {
1890 DWORD chunk_size = 0;
1891
1892 if (!request->content_length) return TRUE;
1893 if (request->content_length == request->content_read)
1894 {
1895 /* read terminator for the previous chunk */
1896 if (!discard_eol( request )) return FALSE;
1897 request->content_length = ~0u;
1898 request->content_read = 0;
1899 }
1900 for (;;)
1901 {
1902 while (request->read_size)
1903 {
1904 char ch = request->read_buf[request->read_pos];
1905 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1906 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1907 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1908 else if (ch == ';' || ch == '\r' || ch == '\n')
1909 {
1910 TRACE("reading %u byte chunk\n", chunk_size);
1911 request->content_length = chunk_size;
1912 request->content_read = 0;
1913 if (!discard_eol( request )) return FALSE;
1914 return TRUE;
1915 }
1916 remove_data( request, 1 );
1917 }
1918 if (!read_more_data( request, -1 )) return FALSE;
1919 if (!request->read_size)
1920 {
1921 request->content_length = request->content_read = 0;
1922 return TRUE;
1923 }
1924 }
1925 }
1926
1927 /* return the size of data available to be read immediately */
1928 static DWORD get_available_data( request_t *request )
1929 {
1930 if (request->read_chunked &&
1931 (request->content_length == ~0u || request->content_length == request->content_read))
1932 return 0;
1933 return min( request->read_size, request->content_length - request->content_read );
1934 }
1935
1936 /* check if we have reached the end of the data to read */
1937 static BOOL end_of_read_data( request_t *request )
1938 {
1939 if (request->read_chunked) return (request->content_length == 0);
1940 if (request->content_length == ~0u) return FALSE;
1941 return (request->content_length == request->content_read);
1942 }
1943
1944 static BOOL refill_buffer( request_t *request )
1945 {
1946 int len = sizeof(request->read_buf);
1947
1948 if (request->read_chunked &&
1949 (request->content_length == ~0u || request->content_length == request->content_read))
1950 {
1951 if (!start_next_chunk( request )) return FALSE;
1952 }
1953 if (request->content_length != ~0u) len = min( len, request->content_length - request->content_read );
1954 if (len <= request->read_size) return TRUE;
1955 if (!read_more_data( request, len )) return FALSE;
1956 if (!request->read_size) request->content_length = request->content_read = 0;
1957 return TRUE;
1958 }
1959
1960 #define MAX_REPLY_LEN 1460
1961 #define INITIAL_HEADER_BUFFER_LEN 512
1962
1963 static BOOL read_reply( request_t *request )
1964 {
1965 static const WCHAR crlf[] = {'\r','\n',0};
1966
1967 char buffer[MAX_REPLY_LEN];
1968 DWORD buflen, len, offset, received_len, crlf_len = 2; /* strlenW(crlf) */
1969 char *status_code, *status_text;
1970 WCHAR *versionW, *status_textW, *raw_headers;
1971 WCHAR status_codeW[4]; /* sizeof("nnn") */
1972
1973 if (!netconn_connected( &request->netconn )) return FALSE;
1974
1975 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1976
1977 received_len = 0;
1978 do
1979 {
1980 buflen = MAX_REPLY_LEN;
1981 if (!read_line( request, buffer, &buflen )) return FALSE;
1982 received_len += buflen;
1983
1984 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
1985 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
1986 status_code++;
1987 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
1988 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
1989 status_text++;
1990
1991 TRACE("version [%s] status code [%s] status text [%s]\n",
1992 debugstr_an(buffer, status_code - buffer - 1),
1993 debugstr_an(status_code, len),
1994 debugstr_a(status_text));
1995
1996 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
1997
1998 /* we rely on the fact that the protocol is ascii */
1999 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2000 status_codeW[len] = 0;
2001 if (!(process_header( request, attr_status, status_codeW, WINHTTP_ADDREQ_FLAG_REPLACE, FALSE ))) return FALSE;
2002
2003 len = status_code - buffer;
2004 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2005 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2006 versionW[len - 1] = 0;
2007
2008 heap_free( request->version );
2009 request->version = versionW;
2010
2011 len = buflen - (status_text - buffer);
2012 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2013 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2014
2015 heap_free( request->status_text );
2016 request->status_text = status_textW;
2017
2018 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2019 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2020 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2021 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2022
2023 heap_free( request->raw_headers );
2024 request->raw_headers = raw_headers;
2025
2026 offset = buflen + crlf_len - 1;
2027 for (;;)
2028 {
2029 header_t *header;
2030
2031 buflen = MAX_REPLY_LEN;
2032 if (!read_line( request, buffer, &buflen )) goto end;
2033 received_len += buflen;
2034 if (!*buffer) break;
2035
2036 while (len - offset < buflen + crlf_len)
2037 {
2038 WCHAR *tmp;
2039 len *= 2;
2040 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2041 request->raw_headers = raw_headers = tmp;
2042 }
2043 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2044
2045 if (!(header = parse_header( raw_headers + offset ))) break;
2046 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2047 {
2048 free_header( header );
2049 break;
2050 }
2051 free_header( header );
2052 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2053 offset += buflen + crlf_len - 1;
2054 }
2055
2056 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2057
2058 end:
2059 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &received_len, sizeof(DWORD) );
2060 return TRUE;
2061 }
2062
2063 static void finished_reading( request_t *request )
2064 {
2065 static const WCHAR closeW[] = {'c','l','o','s','e',0};
2066
2067 BOOL close = FALSE;
2068 WCHAR connection[20];
2069 DWORD size = sizeof(connection);
2070
2071 if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
2072 else if (query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
2073 query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
2074 {
2075 if (!strcmpiW( connection, closeW )) close = TRUE;
2076 }
2077 else if (!strcmpW( request->version, http1_0 )) close = TRUE;
2078 if (close) close_connection( request );
2079 }
2080
2081 static BOOL read_data( request_t *request, void *buffer, DWORD size, DWORD *read, BOOL async )
2082 {
2083 BOOL ret = TRUE;
2084 int len, bytes_read = 0;
2085
2086 if (request->read_chunked &&
2087 (request->content_length == ~0u || request->content_length == request->content_read))
2088 {
2089 if (!start_next_chunk( request )) goto done;
2090 }
2091 if (request->content_length != ~0u) size = min( size, request->content_length - request->content_read );
2092
2093 if (request->read_size)
2094 {
2095 bytes_read = min( request->read_size, size );
2096 memcpy( buffer, request->read_buf + request->read_pos, bytes_read );
2097 remove_data( request, bytes_read );
2098 }
2099 if (size > bytes_read && (!bytes_read || !async))
2100 {
2101 if ((ret = netconn_recv( &request->netconn, (char *)buffer + bytes_read, size - bytes_read,
2102 async ? 0 : MSG_WAITALL, &len )))
2103 bytes_read += len;
2104 }
2105
2106 done:
2107 request->content_read += bytes_read;
2108 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, request->content_read, request->content_length );
2109 if (async)
2110 {
2111 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
2112 else
2113 {
2114 WINHTTP_ASYNC_RESULT result;
2115 result.dwResult = API_READ_DATA;
2116 result.dwError = get_last_error();
2117 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2118 }
2119 }
2120 if (read) *read = bytes_read;
2121 if (!bytes_read && request->content_read == request->content_length) finished_reading( request );
2122 return ret;
2123 }
2124
2125 /* read any content returned by the server so that the connection can be reused */
2126 static void drain_content( request_t *request )
2127 {
2128 DWORD bytes_read;
2129 char buffer[2048];
2130
2131 if (request->content_length == ~0u)
2132 {
2133 finished_reading( request );
2134 return;
2135 }
2136 for (;;)
2137 {
2138 if (!read_data( request, buffer, sizeof(buffer), &bytes_read, FALSE ) || !bytes_read) return;
2139 }
2140 }
2141
2142 static void record_cookies( request_t *request )
2143 {
2144 unsigned int i;
2145
2146 for (i = 0; i < request->num_headers; i++)
2147 {
2148 header_t *set_cookie = &request->headers[i];
2149 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2150 {
2151 set_cookies( request, set_cookie->value );
2152 }
2153 }
2154 }
2155
2156 static WCHAR *get_redirect_url( request_t *request, DWORD *len )
2157 {
2158 DWORD size;
2159 WCHAR *ret;
2160
2161 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2162 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2163 if (!(ret = heap_alloc( size ))) return NULL;
2164 *len = size / sizeof(WCHAR);
2165 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2166 heap_free( ret );
2167 return NULL;
2168 }
2169
2170 static BOOL handle_redirect( request_t *request, DWORD status )
2171 {
2172 BOOL ret = FALSE;
2173 DWORD len, len_url;
2174 URL_COMPONENTS uc;
2175 connect_t *connect = request->connect;
2176 INTERNET_PORT port;
2177 WCHAR *hostname = NULL, *location;
2178 int index;
2179
2180 if (!(location = get_redirect_url( request, &len_url ))) return FALSE;
2181
2182 memset( &uc, 0, sizeof(uc) );
2183 uc.dwStructSize = sizeof(uc);
2184 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2185
2186 if (!WinHttpCrackUrl( location, len_url, 0, &uc )) /* assume relative redirect */
2187 {
2188 WCHAR *path, *p;
2189
2190 len = strlenW( location ) + 1;
2191 if (location[0] != '/') len++;
2192 if (!(p = path = heap_alloc( len * sizeof(WCHAR) ))) goto end;
2193
2194 if (location[0] != '/') *p++ = '/';
2195 strcpyW( p, location );
2196
2197 heap_free( request->path );
2198 request->path = path;
2199
2200 drain_content( request );
2201 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2202 }
2203 else
2204 {
2205 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2206 {
2207 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2208 TRACE("redirect from secure page to non-secure page\n");
2209 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2210 }
2211 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2212 {
2213 TRACE("redirect from non-secure page to secure page\n");
2214 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2215 }
2216
2217 drain_content( request );
2218 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2219
2220 len = uc.dwHostNameLength;
2221 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2222 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2223 hostname[len] = 0;
2224
2225 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2226 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2227 {
2228 heap_free( connect->hostname );
2229 connect->hostname = hostname;
2230 connect->hostport = port;
2231 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2232
2233 netconn_close( &request->netconn );
2234 if (!(ret = netconn_init( &request->netconn ))) goto end;
2235 request->read_pos = request->read_size = 0;
2236 request->read_chunked = FALSE;
2237 }
2238 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2239 if (!(ret = open_connection( request ))) goto end;
2240
2241 heap_free( request->path );
2242 request->path = NULL;
2243 if (uc.dwUrlPathLength)
2244 {
2245 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2246 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2247 strcpyW( request->path, uc.lpszUrlPath );
2248 }
2249 else request->path = strdupW( slashW );
2250 }
2251
2252 /* remove content-type/length headers */
2253 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2254 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2255
2256 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2257 {
2258 heap_free( request->verb );
2259 request->verb = strdupW( getW );
2260 request->optional = NULL;
2261 request->optional_len = 0;
2262 }
2263 ret = TRUE;
2264
2265 end:
2266 if (!ret) heap_free( hostname );
2267 heap_free( location );
2268 return ret;
2269 }
2270
2271 static BOOL receive_response( request_t *request, BOOL async )
2272 {
2273 BOOL ret;
2274 DWORD size, query, status;
2275
2276 for (;;)
2277 {
2278 if (!(ret = read_reply( request )))
2279 {
2280 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2281 break;
2282 }
2283 size = sizeof(DWORD);
2284 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2285 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2286
2287 set_content_length( request );
2288
2289 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2290
2291 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2292 {
2293 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2294 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2295
2296 if (!(ret = handle_redirect( request, status ))) break;
2297
2298 /* recurse synchronously */
2299 send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE );
2300 continue;
2301 }
2302 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2303 {
2304 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2305
2306 drain_content( request );
2307 if (!handle_authorization( request, status ))
2308 {
2309 ret = TRUE;
2310 break;
2311 }
2312 /* recurse synchronously */
2313 send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE );
2314 continue;
2315 }
2316 break;
2317 }
2318
2319 if (async)
2320 {
2321 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2322 else
2323 {
2324 WINHTTP_ASYNC_RESULT result;
2325 result.dwResult = API_RECEIVE_RESPONSE;
2326 result.dwError = get_last_error();
2327 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2328 }
2329 }
2330 return ret;
2331 }
2332
2333 static void task_receive_response( task_header_t *task )
2334 {
2335 receive_response_t *r = (receive_response_t *)task;
2336 receive_response( r->hdr.request, TRUE );
2337 }
2338
2339 /***********************************************************************
2340 * WinHttpReceiveResponse (winhttp.@)
2341 */
2342 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2343 {
2344 BOOL ret;
2345 request_t *request;
2346
2347 TRACE("%p, %p\n", hrequest, reserved);
2348
2349 if (!(request = (request_t *)grab_object( hrequest )))
2350 {
2351 set_last_error( ERROR_INVALID_HANDLE );
2352 return FALSE;
2353 }
2354 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2355 {
2356 release_object( &request->hdr );
2357 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2358 return FALSE;
2359 }
2360
2361 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2362 {
2363 receive_response_t *r;
2364
2365 if (!(r = heap_alloc( sizeof(receive_response_t) ))) return FALSE;
2366 r->hdr.request = request;
2367 r->hdr.proc = task_receive_response;
2368
2369 addref_object( &request->hdr );
2370 ret = queue_task( (task_header_t *)r );
2371 }
2372 else
2373 ret = receive_response( request, FALSE );
2374
2375 release_object( &request->hdr );
2376 return ret;
2377 }
2378
2379 static BOOL query_data_available( request_t *request, DWORD *available, BOOL async )
2380 {
2381 BOOL ret = TRUE;
2382 DWORD count;
2383
2384 if (!(count = get_available_data( request )))
2385 {
2386 if (end_of_read_data( request ))
2387 {
2388 if (available) *available = 0;
2389 return TRUE;
2390 }
2391 }
2392 refill_buffer( request );
2393 count = get_available_data( request );
2394
2395 if (count == sizeof(request->read_buf)) /* check if we have even more pending in the socket */
2396 {
2397 DWORD extra;
2398 if ((ret = netconn_query_data_available( &request->netconn, &extra )))
2399 {
2400 count = min( count + extra, request->content_length - request->content_read );
2401 }
2402 }
2403 if (async)
2404 {
2405 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2406 else
2407 {
2408 WINHTTP_ASYNC_RESULT result;
2409 result.dwResult = API_QUERY_DATA_AVAILABLE;
2410 result.dwError = get_last_error();
2411 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2412 }
2413 }
2414 if (ret)
2415 {
2416 TRACE("%u bytes available\n", count);
2417 if (available) *available = count;
2418 }
2419 return ret;
2420 }
2421
2422 static void task_query_data_available( task_header_t *task )
2423 {
2424 query_data_t *q = (query_data_t *)task;
2425 query_data_available( q->hdr.request, q->available, TRUE );
2426 }
2427
2428 /***********************************************************************
2429 * WinHttpQueryDataAvailable (winhttp.@)
2430 */
2431 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2432 {
2433 BOOL ret;
2434 request_t *request;
2435
2436 TRACE("%p, %p\n", hrequest, available);
2437
2438 if (!(request = (request_t *)grab_object( hrequest )))
2439 {
2440 set_last_error( ERROR_INVALID_HANDLE );
2441 return FALSE;
2442 }
2443 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2444 {
2445 release_object( &request->hdr );
2446 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2447 return FALSE;
2448 }
2449
2450 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2451 {
2452 query_data_t *q;
2453
2454 if (!(q = heap_alloc( sizeof(query_data_t) ))) return FALSE;
2455 q->hdr.request = request;
2456 q->hdr.proc = task_query_data_available;
2457 q->available = available;
2458
2459 addref_object( &request->hdr );
2460 ret = queue_task( (task_header_t *)q );
2461 }
2462 else
2463 ret = query_data_available( request, available, FALSE );
2464
2465 release_object( &request->hdr );
2466 return ret;
2467 }
2468
2469 static void task_read_data( task_header_t *task )
2470 {
2471 read_data_t *r = (read_data_t *)task;
2472 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2473 }
2474
2475 /***********************************************************************
2476 * WinHttpReadData (winhttp.@)
2477 */
2478 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2479 {
2480 BOOL ret;
2481 request_t *request;
2482
2483 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2484
2485 if (!(request = (request_t *)grab_object( hrequest )))
2486 {
2487 set_last_error( ERROR_INVALID_HANDLE );
2488 return FALSE;
2489 }
2490 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2491 {
2492 release_object( &request->hdr );
2493 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2494 return FALSE;
2495 }
2496
2497 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2498 {
2499 read_data_t *r;
2500
2501 if (!(r = heap_alloc( sizeof(read_data_t) ))) return FALSE;
2502 r->hdr.request = request;
2503 r->hdr.proc = task_read_data;
2504 r->buffer = buffer;
2505 r->to_read = to_read;
2506 r->read = read;
2507
2508 addref_object( &request->hdr );
2509 ret = queue_task( (task_header_t *)r );
2510 }
2511 else
2512 ret = read_data( request, buffer, to_read, read, FALSE );
2513
2514 release_object( &request->hdr );
2515 return ret;
2516 }
2517
2518 static BOOL write_data( request_t *request, LPCVOID buffer, DWORD to_write, LPDWORD written, BOOL async )
2519 {
2520 BOOL ret;
2521 int num_bytes;
2522
2523 ret = netconn_send( &request->netconn, buffer, to_write, &num_bytes );
2524
2525 if (async)
2526 {
2527 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(DWORD) );
2528 else
2529 {
2530 WINHTTP_ASYNC_RESULT result;
2531 result.dwResult = API_WRITE_DATA;
2532 result.dwError = get_last_error();
2533 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2534 }
2535 }
2536 if (ret && written) *written = num_bytes;
2537 return ret;
2538 }
2539
2540 static void task_write_data( task_header_t *task )
2541 {
2542 write_data_t *w = (write_data_t *)task;
2543 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
2544 }
2545
2546 /***********************************************************************
2547 * WinHttpWriteData (winhttp.@)
2548 */
2549 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
2550 {
2551 BOOL ret;
2552 request_t *request;
2553
2554 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
2555
2556 if (!(request = (request_t *)grab_object( hrequest )))
2557 {
2558 set_last_error( ERROR_INVALID_HANDLE );
2559 return FALSE;
2560 }
2561 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2562 {
2563 release_object( &request->hdr );
2564 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2565 return FALSE;
2566 }
2567
2568 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2569 {
2570 write_data_t *w;
2571
2572 if (!(w = heap_alloc( sizeof(write_data_t) ))) return FALSE;
2573 w->hdr.request = request;
2574 w->hdr.proc = task_write_data;
2575 w->buffer = buffer;
2576 w->to_write = to_write;
2577 w->written = written;
2578
2579 addref_object( &request->hdr );
2580 ret = queue_task( (task_header_t *)w );
2581 }
2582 else
2583 ret = write_data( request, buffer, to_write, written, FALSE );
2584
2585 release_object( &request->hdr );
2586 return ret;
2587 }
2588
2589 enum request_state
2590 {
2591 REQUEST_STATE_UNINITIALIZED,
2592 REQUEST_STATE_INITIALIZED,
2593 REQUEST_STATE_CANCELLED,
2594 REQUEST_STATE_OPEN,
2595 REQUEST_STATE_SENT,
2596 REQUEST_STATE_RESPONSE_RECEIVED
2597 };
2598
2599 struct winhttp_request
2600 {
2601 IWinHttpRequest IWinHttpRequest_iface;
2602 LONG refs;
2603 CRITICAL_SECTION cs;
2604 enum request_state state;
2605 HINTERNET hsession;
2606 HINTERNET hconnect;
2607 HINTERNET hrequest;
2608 VARIANT data;
2609 WCHAR *verb;
2610 HANDLE thread;
2611 HANDLE wait;
2612 HANDLE cancel;
2613 char *buffer;
2614 DWORD offset;
2615 DWORD bytes_available;
2616 DWORD bytes_read;
2617 DWORD error;
2618 DWORD logon_policy;
2619 DWORD disable_feature;
2620 LONG resolve_timeout;
2621 LONG connect_timeout;
2622 LONG send_timeout;
2623 LONG receive_timeout;
2624 WINHTTP_PROXY_INFO proxy;
2625 };
2626
2627 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
2628 {
2629 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
2630 }
2631
2632 static ULONG WINAPI winhttp_request_AddRef(
2633 IWinHttpRequest *iface )
2634 {
2635 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2636 return InterlockedIncrement( &request->refs );
2637 }
2638
2639 /* critical section must be held */
2640 static void cancel_request( struct winhttp_request *request )
2641 {
2642 if (request->state <= REQUEST_STATE_CANCELLED) return;
2643 if (request->thread) SetEvent( request->cancel );
2644 request->state = REQUEST_STATE_CANCELLED;
2645 }
2646
2647 /* critical section must be held */
2648 static void free_request( struct winhttp_request *request )
2649 {
2650 if (request->state < REQUEST_STATE_INITIALIZED) return;
2651 WinHttpCloseHandle( request->hrequest );
2652 WinHttpCloseHandle( request->hconnect );
2653 WinHttpCloseHandle( request->hsession );
2654 CloseHandle( request->thread );
2655 CloseHandle( request->wait );
2656 CloseHandle( request->cancel );
2657 heap_free( (WCHAR *)request->proxy.lpszProxy );
2658 heap_free( (WCHAR *)request->proxy.lpszProxyBypass );
2659 heap_free( request->buffer );
2660 heap_free( request->verb );
2661 VariantClear( &request->data );
2662 }
2663
2664 static ULONG WINAPI winhttp_request_Release(
2665 IWinHttpRequest *iface )
2666 {
2667 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2668 LONG refs = InterlockedDecrement( &request->refs );
2669 if (!refs)
2670 {
2671 TRACE("destroying %p\n", request);
2672
2673 EnterCriticalSection( &request->cs );
2674 cancel_request( request );
2675 free_request( request );
2676 LeaveCriticalSection( &request->cs );
2677 request->cs.DebugInfo->Spare[0] = 0;
2678 DeleteCriticalSection( &request->cs );
2679 heap_free( request );
2680 }
2681 return refs;
2682 }
2683
2684 static HRESULT WINAPI winhttp_request_QueryInterface(
2685 IWinHttpRequest *iface,
2686 REFIID riid,
2687 void **obj )
2688 {
2689 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2690
2691 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
2692
2693 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
2694 IsEqualGUID( riid, &IID_IDispatch ) ||
2695 IsEqualGUID( riid, &IID_IUnknown ))
2696 {
2697 *obj = iface;
2698 }
2699 else
2700 {
2701 FIXME("interface %s not implemented\n", debugstr_guid(riid));
2702 return E_NOINTERFACE;
2703 }
2704 IWinHttpRequest_AddRef( iface );
2705 return S_OK;
2706 }
2707
2708 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
2709 IWinHttpRequest *iface,
2710 UINT *count )
2711 {
2712 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2713
2714 TRACE("%p, %p\n", request, count);
2715 *count = 1;
2716 return S_OK;
2717 }
2718
2719 enum type_id
2720 {
2721 IWinHttpRequest_tid,
2722 last_tid
2723 };
2724
2725 static ITypeLib *winhttp_typelib;
2726 static ITypeInfo *winhttp_typeinfo[last_tid];
2727
2728 static REFIID winhttp_tid_id[] =
2729 {
2730 &IID_IWinHttpRequest
2731 };
2732
2733 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
2734 {
2735 HRESULT hr;
2736
2737 if (!winhttp_typelib)
2738 {
2739 ITypeLib *typelib;
2740
2741 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
2742 if (FAILED(hr))
2743 {
2744 ERR("LoadRegTypeLib failed: %08x\n", hr);
2745 return hr;
2746 }
2747 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
2748 ITypeLib_Release( typelib );
2749 }
2750 if (!winhttp_typeinfo[tid])
2751 {
2752 ITypeInfo *typeinfo;
2753
2754 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
2755 if (FAILED(hr))
2756 {
2757 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
2758 return hr;
2759 }
2760 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
2761 ITypeInfo_Release( typeinfo );
2762 }
2763 *ret = winhttp_typeinfo[tid];
2764 return S_OK;
2765 }
2766
2767 static HRESULT WINAPI winhttp_request_GetTypeInfo(
2768 IWinHttpRequest *iface,
2769 UINT index,
2770 LCID lcid,
2771 ITypeInfo **info )
2772 {
2773 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2774 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
2775
2776 return get_typeinfo( IWinHttpRequest_tid, info );
2777 }
2778
2779 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
2780 IWinHttpRequest *iface,
2781 REFIID riid,
2782 LPOLESTR *names,
2783 UINT count,
2784 LCID lcid,
2785 DISPID *dispid )
2786 {
2787 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2788 ITypeInfo *typeinfo;
2789 HRESULT hr;
2790
2791 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
2792
2793 if (!names || !count || !dispid) return E_INVALIDARG;
2794
2795 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2796 if (SUCCEEDED(hr))
2797 {
2798 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
2799 ITypeInfo_Release( typeinfo );
2800 }
2801 return hr;
2802 }
2803
2804 static HRESULT WINAPI winhttp_request_Invoke(
2805 IWinHttpRequest *iface,
2806 DISPID member,
2807 REFIID riid,
2808 LCID lcid,
2809 WORD flags,
2810 DISPPARAMS *params,
2811 VARIANT *result,
2812 EXCEPINFO *excep_info,
2813 UINT *arg_err )
2814 {
2815 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2816 ITypeInfo *typeinfo;
2817 HRESULT hr;
2818
2819 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
2820 lcid, flags, params, result, excep_info, arg_err);
2821
2822 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2823 if (SUCCEEDED(hr))
2824 {
2825 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
2826 params, result, excep_info, arg_err );
2827 ITypeInfo_Release( typeinfo );
2828 }
2829 return hr;
2830 }
2831
2832 static HRESULT WINAPI winhttp_request_SetProxy(
2833 IWinHttpRequest *iface,
2834 HTTPREQUEST_PROXY_SETTING proxy_setting,
2835 VARIANT proxy_server,
2836 VARIANT bypass_list )
2837 {
2838 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2839 DWORD err = ERROR_SUCCESS;
2840
2841 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
2842 debugstr_variant(&bypass_list));
2843
2844 EnterCriticalSection( &request->cs );
2845 switch (proxy_setting)
2846 {
2847 case HTTPREQUEST_PROXYSETTING_DEFAULT:
2848 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
2849 heap_free( (WCHAR *)request->proxy.lpszProxy );
2850 heap_free( (WCHAR *)request->proxy.lpszProxyBypass );
2851 request->proxy.lpszProxy = NULL;
2852 request->proxy.lpszProxyBypass = NULL;
2853 break;
2854
2855 case HTTPREQUEST_PROXYSETTING_DIRECT:
2856 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
2857 heap_free( (WCHAR *)request->proxy.lpszProxy );
2858 heap_free( (WCHAR *)request->proxy.lpszProxyBypass );
2859 request->proxy.lpszProxy = NULL;
2860 request->proxy.lpszProxyBypass = NULL;
2861 break;
2862
2863 case HTTPREQUEST_PROXYSETTING_PROXY:
2864 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
2865 if (V_VT( &proxy_server ) == VT_BSTR)
2866 {
2867 heap_free( (WCHAR *)request->proxy.lpszProxy );
2868 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
2869 }
2870 if (V_VT( &bypass_list ) == VT_BSTR)
2871 {
2872 heap_free( (WCHAR *)request->proxy.lpszProxyBypass );
2873 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
2874 }
2875 break;
2876
2877 default:
2878 err = ERROR_INVALID_PARAMETER;
2879 break;
2880 }
2881 LeaveCriticalSection( &request->cs );
2882 return HRESULT_FROM_WIN32( err );
2883 }
2884
2885 static HRESULT WINAPI winhttp_request_SetCredentials(
2886 IWinHttpRequest *iface,
2887 BSTR username,
2888 BSTR password,
2889 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
2890 {
2891 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2892 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
2893 DWORD err = ERROR_SUCCESS;
2894
2895 TRACE("%p, %s, %p\n", request, debugstr_w(username), password);
2896
2897 EnterCriticalSection( &request->cs );
2898 if (request->state < REQUEST_STATE_OPEN)
2899 {
2900 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
2901 goto done;
2902 }
2903 switch (flags)
2904 {
2905 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
2906 target = WINHTTP_AUTH_TARGET_SERVER;
2907 break;
2908 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
2909 target = WINHTTP_AUTH_TARGET_PROXY;
2910 break;
2911 default:
2912 err = ERROR_INVALID_PARAMETER;
2913 goto done;
2914 }
2915 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
2916 {
2917 err = get_last_error();
2918 }
2919 done:
2920 LeaveCriticalSection( &request->cs );
2921 return HRESULT_FROM_WIN32( err );
2922 }
2923
2924 static void initialize_request( struct winhttp_request *request )
2925 {
2926 request->hrequest = NULL;
2927 request->hconnect = NULL;
2928 request->hsession = NULL;
2929 request->thread = NULL;
2930 request->wait = NULL;
2931 request->cancel = NULL;
2932 request->buffer = NULL;
2933 request->verb = NULL;
2934 request->offset = 0;
2935 request->bytes_available = 0;
2936 request->bytes_read = 0;
2937 request->error = ERROR_SUCCESS;
2938 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
2939 request->disable_feature = WINHTTP_DISABLE_AUTHENTICATION;
2940 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
2941 request->proxy.lpszProxy = NULL;
2942 request->proxy.lpszProxyBypass = NULL;
2943 request->resolve_timeout = 0;
2944 request->connect_timeout = 60000;
2945 request->send_timeout = 30000;
2946 request->receive_timeout = 30000;
2947 VariantInit( &request->data );
2948 request->state = REQUEST_STATE_INITIALIZED;
2949 }
2950
2951 static HRESULT WINAPI winhttp_request_Open(
2952 IWinHttpRequest *iface,
2953 BSTR method,
2954 BSTR url,
2955 VARIANT async )
2956 {
2957 static const WCHAR typeW[] = {'*','/','*',0};
2958 static const WCHAR *acceptW[] = {typeW, NULL};
2959 static const WCHAR httpsW[] = {'h','t','t','p','s'};
2960 static const WCHAR user_agentW[] = {
2961 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
2962 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
2963 'R','e','q','u','e','s','t','.','5',')',0};
2964 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2965 HINTERNET hsession = NULL, hconnect = NULL, hrequest;
2966 URL_COMPONENTS uc;
2967 WCHAR *hostname, *path = NULL, *verb = NULL;
2968 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0, request_flags = 0;
2969
2970 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
2971 debugstr_variant(&async));
2972
2973 if (!method || !url) return E_INVALIDARG;
2974
2975 memset( &uc, 0, sizeof(uc) );
2976 uc.dwStructSize = sizeof(uc);
2977 uc.dwSchemeLength = ~0u;
2978 uc.dwHostNameLength = ~0u;
2979 uc.dwUrlPathLength = ~0u;
2980 uc.dwExtraInfoLength = ~0u;
2981 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( get_last_error() );
2982
2983 EnterCriticalSection( &request->cs );
2984 if (request->state != REQUEST_STATE_INITIALIZED)
2985 {
2986 cancel_request( request );
2987 free_request( request );
2988 initialize_request( request );
2989 }
2990 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
2991 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
2992 hostname[uc.dwHostNameLength] = 0;
2993
2994 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
2995 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
2996 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
2997
2998 if (!(verb = strdupW( method ))) goto error;
2999 if (V_BOOL( &async )) flags |= WINHTTP_FLAG_ASYNC;
3000 if (!(hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, flags )))
3001 {
3002 err = get_last_error();
3003 goto error;
3004 }
3005 if (!(hconnect = WinHttpConnect( hsession, hostname, uc.nPort, 0 )))
3006 {
3007 err = get_last_error();
3008 goto error;
3009 }
3010 len = sizeof(httpsW) / sizeof(WCHAR);
3011 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
3012 {
3013 request_flags |= WINHTTP_FLAG_SECURE;
3014 }
3015 if (!(hrequest = WinHttpOpenRequest( hconnect, method, path, NULL, NULL, acceptW, request_flags )))
3016 {
3017 err = get_last_error();
3018 goto error;
3019 }
3020 if (flags & WINHTTP_FLAG_ASYNC)
3021 {
3022 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3023 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3024 WinHttpSetOption( hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3025 }
3026 request->state = REQUEST_STATE_OPEN;
3027 request->hsession = hsession;
3028 request->hconnect = hconnect;
3029 request->hrequest = hrequest;
3030 request->verb = verb;
3031 heap_free( hostname );
3032 heap_free( path );
3033 LeaveCriticalSection( &request->cs );
3034 return S_OK;
3035
3036 error:
3037 WinHttpCloseHandle( hconnect );
3038 WinHttpCloseHandle( hsession );
3039 heap_free( hostname );
3040 heap_free( path );
3041 heap_free( verb );
3042 LeaveCriticalSection( &request->cs );
3043 return HRESULT_FROM_WIN32( err );
3044 }
3045
3046 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3047 IWinHttpRequest *iface,
3048 BSTR header,
3049 BSTR value )
3050 {
3051 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3052 static const WCHAR emptyW[] = {0};
3053 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3054 DWORD len, err = ERROR_SUCCESS;
3055 WCHAR *str;
3056
3057 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3058
3059 if (!header) return E_INVALIDARG;
3060
3061 EnterCriticalSection( &request->cs );
3062 if (request->state < REQUEST_STATE_OPEN)
3063 {
3064 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3065 goto done;
3066 }
3067 if (request->state >= REQUEST_STATE_SENT)
3068 {
3069 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3070 goto done;
3071 }
3072 len = strlenW( header ) + 4;
3073 if (value) len += strlenW( value );
3074 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3075 {
3076 err = ERROR_OUTOFMEMORY;
3077 goto done;
3078 }
3079 sprintfW( str, fmtW, header, value ? value : emptyW );
3080 if (!WinHttpAddRequestHeaders( request->hrequest, str, len, WINHTTP_ADDREQ_FLAG_REPLACE ))
3081 {
3082 err = get_last_error();
3083 }
3084 heap_free( str );
3085
3086 done:
3087 LeaveCriticalSection( &request->cs );
3088 return HRESULT_FROM_WIN32( err );
3089 }
3090
3091 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3092 IWinHttpRequest *iface,
3093 BSTR header,
3094 BSTR *value )
3095 {
3096 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3097 DWORD size, err = ERROR_SUCCESS;
3098
3099 TRACE("%p, %p\n", request, header);
3100
3101 EnterCriticalSection( &request->cs );
3102 if (request->state < REQUEST_STATE_SENT)
3103 {
3104 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3105 goto done;
3106 }
3107 if (!header || !value)
3108 {
3109 err = ERROR_INVALID_PARAMETER;
3110 goto done;
3111 }
3112 size = 0;
3113 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3114 {
3115 err = get_last_error();
3116 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3117 }
3118 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3119 {
3120 err = ERROR_OUTOFMEMORY;
3121 goto done;
3122 }
3123 err = ERROR_SUCCESS;
3124 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3125 {
3126 err = get_last_error();
3127 SysFreeString( *value );
3128 }
3129 done:
3130 LeaveCriticalSection( &request->cs );
3131 return HRESULT_FROM_WIN32( err );
3132 }
3133
3134 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3135 IWinHttpRequest *iface,
3136 BSTR *headers )
3137 {
3138 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3139 DWORD size, err = ERROR_SUCCESS;
3140
3141 TRACE("%p, %p\n", request, headers);
3142
3143 if (!headers) return E_INVALIDARG;
3144
3145 EnterCriticalSection( &request->cs );
3146 if (request->state < REQUEST_STATE_SENT)
3147 {
3148 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3149 goto done;
3150 }
3151 size = 0;
3152 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3153 {
3154 err = get_last_error();
3155 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3156 }
3157 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3158 {
3159 err = ERROR_OUTOFMEMORY;
3160 goto done;
3161 }
3162 err = ERROR_SUCCESS;
3163 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3164 {
3165 err = get_last_error();
3166 SysFreeString( *headers );
3167 }
3168 done:
3169 LeaveCriticalSection( &request->cs );
3170 return HRESULT_FROM_WIN32( err );
3171 }
3172
3173 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3174 {
3175 struct winhttp_request *request = (struct winhttp_request *)context;
3176
3177 switch (status)
3178 {
3179 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3180 request->bytes_available = *(DWORD *)buffer;
3181 request->error = ERROR_SUCCESS;
3182 break;
3183 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3184 request->bytes_read = size;
3185 request->error = ERROR_SUCCESS;
3186 break;
3187 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3188 {
3189 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3190 request->error = result->dwError;
3191 break;
3192 }
3193 default: break;
3194 }
3195 SetEvent( request->wait );
3196 }
3197
3198 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3199 {
3200 if (!request->wait) return;
3201 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3202 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3203 }
3204
3205 static DWORD wait_for_completion( struct winhttp_request *request )
3206 {
3207 HANDLE handles[2];
3208
3209 if (!request->wait)
3210 {
3211 request->error = ERROR_SUCCESS;
3212 return ERROR_SUCCESS;
3213 }
3214 handles[0] = request->wait;
3215 handles[1] = request->cancel;
3216 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3217 {
3218 case WAIT_OBJECT_0:
3219 break;
3220 case WAIT_OBJECT_0 + 1:
3221 request->error = ERROR_CANCELLED;
3222 break;
3223 default:
3224 request->error = get_last_error();
3225 break;
3226 }
3227 return request->error;
3228 }
3229
3230 static HRESULT request_receive( struct winhttp_request *request )
3231 {
3232 DWORD err, size, buflen = 4096;
3233
3234 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3235 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3236 {
3237 return HRESULT_FROM_WIN32( get_last_error() );
3238 }
3239 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3240 if (!strcmpW( request->verb, headW ))
3241 {
3242 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3243 return S_OK;
3244 }
3245 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3246 request->buffer[0] = 0;
3247 size = 0;
3248 do
3249 {
3250 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3251 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3252 {
3253 err = get_last_error();
3254 goto error;
3255 }
3256 if ((err = wait_for_completion( request ))) goto error;
3257 if (!request->bytes_available) break;
3258 size += request->bytes_available;
3259 if (buflen < size)
3260 {
3261 char *tmp;
3262 while (buflen < size) buflen *= 2;
3263 if (!(tmp = heap_realloc( request->buffer, buflen )))
3264 {
3265 err = ERROR_OUTOFMEMORY;
3266 goto error;
3267 }
3268 request->buffer = tmp;
3269 }
3270 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3271 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3272 request->bytes_available, &request->bytes_read ))
3273 {
3274 err = get_last_error();
3275 goto error;
3276 }
3277 if ((err = wait_for_completion( request ))) goto error;
3278 request->offset += request->bytes_read;
3279 } while (request->bytes_read);
3280
3281 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3282 return S_OK;
3283
3284 error:
3285 heap_free( request->buffer );
3286 request->buffer = NULL;
3287 return HRESULT_FROM_WIN32( err );
3288 }
3289
3290 static DWORD request_set_parameters( struct winhttp_request *request )
3291 {
3292 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3293 sizeof(request->proxy) )) return get_last_error();
3294
3295 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3296 sizeof(request->logon_policy) )) return get_last_error();
3297
3298 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3299 sizeof(request->disable_feature) )) return get_last_error();
3300
3301 if (!WinHttpSetTimeouts( request->hrequest,
3302 request->resolve_timeout,
3303 request->connect_timeout,
3304 request->send_timeout,
3305 request->receive_timeout )) return get_last_error();
3306 return ERROR_SUCCESS;
3307 }
3308
3309 static void request_set_utf8_content_type( struct winhttp_request *request )
3310 {
3311 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3312 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3313 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3314 WCHAR headerW[64];
3315 int len;
3316
3317 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3318 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3319 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3320 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3321 }
3322
3323 static HRESULT request_send( struct winhttp_request *request )
3324 {
3325 SAFEARRAY *sa = NULL;
3326 VARIANT data;
3327 char *ptr = NULL;
3328 LONG size = 0;
3329 HRESULT hr;
3330 DWORD err;
3331
3332 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3333 if (strcmpW( request->verb, getW ))
3334 {
3335 VariantInit( &data );
3336 if (V_VT( &request->data ) == VT_BSTR)
3337 {
3338 UINT cp = CP_ACP;
3339 const WCHAR *str = V_BSTR( &request->data );
3340 int i, len = strlenW( str );
3341
3342 for (i = 0; i < len; i++)
3343 {
3344 if (str[i] > 127)
3345 {
3346 cp = CP_UTF8;
3347 break;
3348 }
3349 }
3350 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3351 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3352 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3353 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3354 }
3355 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3356 {
3357 sa = V_ARRAY( &data );
3358 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3359 if ((hr = SafeArrayGetUBound( sa, 1, &size ) != S_OK))
3360 {
3361 SafeArrayUnaccessData( sa );
3362 return hr;
3363 }
3364 size++;
3365 }
3366 }
3367 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3368 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3369 {
3370 err = get_last_error();
3371 goto error;
3372 }
3373 if ((err = wait_for_completion( request ))) goto error;
3374 if (sa) SafeArrayUnaccessData( sa );
3375 else heap_free( ptr );
3376 request->state = REQUEST_STATE_SENT;
3377 return S_OK;
3378
3379 error:
3380 if (sa) SafeArrayUnaccessData( sa );
3381 else heap_free( ptr );
3382 return HRESULT_FROM_WIN32( err );
3383 }
3384
3385 static HRESULT request_send_and_receive( struct winhttp_request *request )
3386 {
3387 HRESULT hr = request_send( request );
3388 if (hr == S_OK) hr = request_receive( request );
3389 return hr;
3390 }
3391
3392 static DWORD CALLBACK send_and_receive_proc( void *arg )
3393 {
3394 struct winhttp_request *request = (struct winhttp_request *)arg;
3395 return request_send_and_receive( request );
3396 }
3397
3398 static HRESULT WINAPI winhttp_request_Send(
3399 IWinHttpRequest *iface,
3400 VARIANT body )
3401 {
3402 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3403 HRESULT hr;
3404
3405 TRACE("%p, %s\n", request, debugstr_variant(&body));
3406
3407 EnterCriticalSection( &request->cs );
3408 if (request->state < REQUEST_STATE_OPEN)
3409 {
3410 LeaveCriticalSection( &request->cs );
3411 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3412 }
3413 if (request->state >= REQUEST_STATE_SENT)
3414 {
3415 LeaveCriticalSection( &request->cs );
3416 return S_OK;
3417 }
3418 VariantClear( &request->data );
3419 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK) {
3420 LeaveCriticalSection( &request->cs );
3421 return hr;
3422 }
3423
3424 if (request->wait) /* async request */
3425 {
3426 if (!(request->thread = CreateThread( NULL, 0, send_and_receive_proc, request, 0, NULL )))
3427 {
3428 LeaveCriticalSection( &request->cs );
3429 return HRESULT_FROM_WIN32( get_last_error() );
3430 }
3431 }
3432 else hr = request_send_and_receive( request );
3433 LeaveCriticalSection( &request->cs );
3434 return hr;
3435 }
3436
3437 static HRESULT WINAPI winhttp_request_get_Status(
3438 IWinHttpRequest *iface,
3439 LONG *status )
3440 {
3441 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3442 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
3443
3444 TRACE("%p, %p\n", request, status);
3445
3446 if (!status) return E_INVALIDARG;
3447
3448 EnterCriticalSection( &request->cs );
3449 if (request->state < REQUEST_STATE_SENT)
3450 {
3451 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3452 goto done;
3453 }
3454 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
3455 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
3456 {
3457 err = get_last_error();
3458 goto done;
3459 }
3460 *status = status_code;
3461
3462 done:
3463 LeaveCriticalSection( &request->cs );
3464 return HRESULT_FROM_WIN32( err );
3465 }
3466
3467 static HRESULT WINAPI winhttp_request_get_StatusText(
3468 IWinHttpRequest *iface,
3469 BSTR *status )
3470 {
3471 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3472 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
3473
3474 TRACE("%p, %p\n", request, status);
3475
3476 if (!status) return E_INVALIDARG;
3477
3478 EnterCriticalSection( &request->cs );
3479 if (request->state < REQUEST_STATE_SENT)
3480 {
3481 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3482 goto done;
3483 }
3484 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
3485 {
3486 err = get_last_error();
3487 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3488 }
3489 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
3490 {
3491 err = ERROR_OUTOFMEMORY;
3492 goto done;
3493 }
3494 index = 0;
3495 err = ERROR_SUCCESS;
3496 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
3497 {
3498 err = get_last_error();
3499 SysFreeString( *status );
3500 }
3501 done:
3502 LeaveCriticalSection( &request->cs );
3503 return HRESULT_FROM_WIN32( err );
3504 }
3505
3506 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
3507 {
3508 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
3509 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
3510 WCHAR *buffer, *p;
3511 DWORD size;
3512
3513 *codepage = CP_ACP;
3514 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
3515 get_last_error() == ERROR_INSUFFICIENT_BUFFER)
3516 {
3517 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
3518 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
3519 {
3520 return get_last_error();
3521 }
3522 if ((p = strstrW( buffer, charsetW )))
3523 {
3524 p += strlenW( charsetW );
3525 while (*p == ' ') p++;
3526 if (*p++ == '=')
3527 {
3528 while (*p == ' ') p++;
3529 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
3530 }
3531 }
3532 heap_free( buffer );
3533 }
3534 return ERROR_SUCCESS;
3535 }
3536
3537 static HRESULT WINAPI winhttp_request_get_ResponseText(
3538 IWinHttpRequest *iface,
3539 BSTR *body )
3540 {
3541 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3542 UINT codepage;
3543 DWORD err = ERROR_SUCCESS;
3544 int len;
3545
3546 TRACE("%p, %p\n", request, body);
3547
3548 if (!body) return E_INVALIDARG;
3549
3550 EnterCriticalSection( &request->cs );
3551 if (request->state < REQUEST_STATE_SENT)
3552 {
3553 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3554 goto done;
3555 }
3556 if ((err = request_get_codepage( request, &codepage ))) goto done;
3557 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
3558 if (!(*body = SysAllocStringLen( NULL, len )))
3559 {
3560 err = ERROR_OUTOFMEMORY;
3561 goto done;
3562 }
3563 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
3564 (*body)[len] = 0;
3565
3566 done:
3567 LeaveCriticalSection( &request->cs );
3568 return HRESULT_FROM_WIN32( err );
3569 }
3570
3571 static HRESULT WINAPI winhttp_request_get_ResponseBody(
3572 IWinHttpRequest *iface,
3573 VARIANT *body )
3574 {
3575 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3576 SAFEARRAY *sa;
3577 HRESULT hr;
3578 DWORD err = ERROR_SUCCESS;
3579 char *ptr;
3580
3581 TRACE("%p, %p\n", request, body);
3582
3583 if (!body) return E_INVALIDARG;
3584
3585 EnterCriticalSection( &request->cs );
3586 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
3587 {
3588 err = ERROR_OUTOFMEMORY;
3589 goto done;
3590 }
3591 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
3592 {
3593 SafeArrayDestroy( sa );
3594 LeaveCriticalSection( &request->cs );
3595 return hr;
3596 }
3597 memcpy( ptr, request->buffer, request->offset );
3598 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
3599 {
3600 SafeArrayDestroy( sa );
3601 LeaveCriticalSection( &request->cs );
3602 return hr;
3603 }
3604 V_VT( body ) = VT_ARRAY|VT_UI1;
3605 V_ARRAY( body ) = sa;
3606
3607 done:
3608 LeaveCriticalSection( &request->cs );
3609 return HRESULT_FROM_WIN32( err );
3610 }
3611
3612 static HRESULT WINAPI winhttp_request_get_ResponseStream(
3613 IWinHttpRequest *iface,
3614 VARIANT *body )
3615 {
3616 FIXME("\n");
3617 return E_NOTIMPL;
3618 }
3619
3620 static HRESULT WINAPI winhttp_request_get_Option(
3621 IWinHttpRequest *iface,
3622 WinHttpRequestOption option,
3623 VARIANT *value )
3624 {
3625 FIXME("\n");
3626 return E_NOTIMPL;
3627 }
3628
3629 static HRESULT WINAPI winhttp_request_put_Option(
3630 IWinHttpRequest *iface,
3631 WinHttpRequestOption option,
3632 VARIANT value )
3633 {
3634 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3635 HRESULT hr = S_OK;
3636
3637 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
3638
3639 EnterCriticalSection( &request->cs );
3640 switch (option)
3641 {
3642 case WinHttpRequestOption_EnableRedirects:
3643 {
3644 if (V_BOOL( &value ))
3645 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
3646 else
3647 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
3648 break;
3649 }
3650 default:
3651 FIXME("unimplemented option %u\n", option);
3652 hr = E_NOTIMPL;
3653 break;
3654 }
3655 LeaveCriticalSection( &request->cs );
3656 return hr;
3657 }
3658
3659 /* critical section must be held */
3660 static DWORD wait_for_response( struct winhttp_request *request, DWORD timeout )
3661 {
3662 HANDLE thread = request->thread;
3663 DWORD err, ret;
3664
3665 LeaveCriticalSection( &request->cs );
3666 while ((err = MsgWaitForMultipleObjects( 1, &thread, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3667 {
3668 MSG msg;
3669 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3670 {
3671 TranslateMessage( &msg );
3672 DispatchMessageW( &msg );
3673 }
3674 }
3675 switch (err)
3676 {
3677 case WAIT_OBJECT_0:
3678 ret = ERROR_SUCCESS;
3679 break;
3680 case WAIT_TIMEOUT:
3681 ret = ERROR_TIMEOUT;
3682 break;
3683 case WAIT_FAILED:
3684 default:
3685 ret = get_last_error();
3686 break;
3687 }
3688 EnterCriticalSection( &request->cs );
3689 return ret;
3690 }
3691
3692 static HRESULT WINAPI winhttp_request_WaitForResponse(
3693 IWinHttpRequest *iface,
3694 VARIANT timeout,
3695 VARIANT_BOOL *succeeded )
3696 {
3697 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3698 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
3699
3700 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
3701
3702 EnterCriticalSection( &request->cs );
3703 if (!request->thread)
3704 {
3705 LeaveCriticalSection( &request->cs );
3706 return S_OK;
3707 }
3708 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
3709 {
3710 LeaveCriticalSection( &request->cs );
3711 return S_OK;
3712 }
3713 switch ((err = wait_for_response( request, msecs )))
3714 {
3715 case ERROR_TIMEOUT:
3716 if (succeeded) *succeeded = VARIANT_FALSE;
3717 err = ERROR_SUCCESS;
3718 break;
3719
3720 case ERROR_SUCCESS:
3721 if (succeeded) *succeeded = VARIANT_TRUE;
3722 break;
3723
3724 default: break;
3725 }
3726 LeaveCriticalSection( &request->cs );
3727 return HRESULT_FROM_WIN32( err );
3728 }
3729
3730 static HRESULT WINAPI winhttp_request_Abort(
3731 IWinHttpRequest *iface )
3732 {
3733 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3734
3735 TRACE("%p\n", request);
3736
3737 EnterCriticalSection( &request->cs );
3738 cancel_request( request );
3739 LeaveCriticalSection( &request->cs );
3740 return S_OK;
3741 }
3742
3743 static HRESULT WINAPI winhttp_request_SetTimeouts(
3744 IWinHttpRequest *iface,
3745 LONG resolve_timeout,
3746 LONG connect_timeout,
3747 LONG send_timeout,
3748 LONG receive_timeout )
3749 {
3750 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3751
3752 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
3753
3754 EnterCriticalSection( &request->cs );
3755 request->resolve_timeout = resolve_timeout;
3756 request->connect_timeout = connect_timeout;
3757 request->send_timeout = send_timeout;
3758 request->receive_timeout = receive_timeout;
3759 LeaveCriticalSection( &request->cs );
3760 return S_OK;
3761 }
3762
3763 static HRESULT WINAPI winhttp_request_SetClientCertificate(
3764 IWinHttpRequest *iface,
3765 BSTR certificate )
3766 {
3767 FIXME("\n");
3768 return E_NOTIMPL;
3769 }
3770
3771 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
3772 IWinHttpRequest *iface,
3773 WinHttpRequestAutoLogonPolicy policy )
3774 {
3775 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3776 HRESULT hr = S_OK;
3777
3778 TRACE("%p, %u\n", request, policy );
3779
3780 EnterCriticalSection( &request->cs );
3781 switch (policy)
3782 {
3783 case AutoLogonPolicy_Always:
3784 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
3785 break;
3786 case AutoLogonPolicy_OnlyIfBypassProxy:
3787 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
3788 break;
3789 case AutoLogonPolicy_Never:
3790 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
3791 break;
3792 default: hr = E_INVALIDARG;
3793 break;
3794 }
3795 LeaveCriticalSection( &request->cs );
3796 return hr;
3797 }
3798
3799 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
3800 {
3801 winhttp_request_QueryInterface,
3802 winhttp_request_AddRef,
3803 winhttp_request_Release,
3804 winhttp_request_GetTypeInfoCount,
3805 winhttp_request_GetTypeInfo,
3806 winhttp_request_GetIDsOfNames,
3807 winhttp_request_Invoke,
3808 winhttp_request_SetProxy,
3809 winhttp_request_SetCredentials,
3810 winhttp_request_Open,
3811 winhttp_request_SetRequestHeader,
3812 winhttp_request_GetResponseHeader,
3813 winhttp_request_GetAllResponseHeaders,
3814 winhttp_request_Send,
3815 winhttp_request_get_Status,
3816 winhttp_request_get_StatusText,
3817 winhttp_request_get_ResponseText,
3818 winhttp_request_get_ResponseBody,
3819 winhttp_request_get_ResponseStream,
3820 winhttp_request_get_Option,
3821 winhttp_request_put_Option,
3822 winhttp_request_WaitForResponse,
3823 winhttp_request_Abort,
3824 winhttp_request_SetTimeouts,
3825 winhttp_request_SetClientCertificate,
3826 winhttp_request_SetAutoLogonPolicy
3827 };
3828
3829 HRESULT WinHttpRequest_create( IUnknown *unknown, void **obj )
3830 {
3831 struct winhttp_request *request;
3832
3833 TRACE("%p, %p\n", unknown, obj);
3834
3835 if (!(request = heap_alloc( sizeof(*request) ))) return E_OUTOFMEMORY;
3836 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
3837 request->refs = 1;
3838 request->state = REQUEST_STATE_UNINITIALIZED;
3839 request->proxy.lpszProxy = NULL;
3840 request->proxy.lpszProxyBypass = NULL;
3841 InitializeCriticalSection( &request->cs );
3842 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
3843
3844 *obj = &request->IWinHttpRequest_iface;
3845 TRACE("returning iface %p\n", *obj);
3846 return S_OK;
3847 }