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