0a75894136c81fc5d324858219d0e4f8f5ab27be
[reactos.git] / reactos / dll / win32 / winhttp / request.c
1 /*
2 * Copyright 2004 Mike McCormack for CodeWeavers
3 * Copyright 2006 Rob Shearman for CodeWeavers
4 * Copyright 2008, 2011 Hans Leidekker for CodeWeavers
5 * Copyright 2009 Juan Lang
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 */
21
22 #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 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2245 if (!(ret = open_connection( request ))) goto end;
2246
2247 heap_free( request->path );
2248 request->path = NULL;
2249 if (uc.dwUrlPathLength)
2250 {
2251 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2252 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2253 strcpyW( request->path, uc.lpszUrlPath );
2254 }
2255 else request->path = strdupW( slashW );
2256 }
2257
2258 /* remove content-type/length headers */
2259 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2260 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2261
2262 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2263 {
2264 heap_free( request->verb );
2265 request->verb = strdupW( getW );
2266 request->optional = NULL;
2267 request->optional_len = 0;
2268 }
2269 ret = TRUE;
2270
2271 end:
2272 if (!ret) heap_free( hostname );
2273 heap_free( location );
2274 return ret;
2275 }
2276
2277 static BOOL receive_response( request_t *request, BOOL async )
2278 {
2279 BOOL ret;
2280 DWORD size, query, status;
2281
2282 for (;;)
2283 {
2284 if (!(ret = read_reply( request )))
2285 {
2286 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2287 break;
2288 }
2289 size = sizeof(DWORD);
2290 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2291 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2292
2293 set_content_length( request );
2294
2295 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2296
2297 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2298 {
2299 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2300 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2301
2302 if (!(ret = handle_redirect( request, status ))) break;
2303
2304 /* recurse synchronously */
2305 send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE );
2306 continue;
2307 }
2308 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2309 {
2310 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2311
2312 drain_content( request );
2313 if (!handle_authorization( request, status ))
2314 {
2315 ret = TRUE;
2316 break;
2317 }
2318 /* recurse synchronously */
2319 send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE );
2320 continue;
2321 }
2322 break;
2323 }
2324
2325 if (ret) refill_buffer( request, FALSE );
2326
2327 if (async)
2328 {
2329 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2330 else
2331 {
2332 WINHTTP_ASYNC_RESULT result;
2333 result.dwResult = API_RECEIVE_RESPONSE;
2334 result.dwError = get_last_error();
2335 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2336 }
2337 }
2338 return ret;
2339 }
2340
2341 static void task_receive_response( task_header_t *task )
2342 {
2343 receive_response_t *r = (receive_response_t *)task;
2344 receive_response( r->hdr.request, TRUE );
2345 }
2346
2347 /***********************************************************************
2348 * WinHttpReceiveResponse (winhttp.@)
2349 */
2350 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2351 {
2352 BOOL ret;
2353 request_t *request;
2354
2355 TRACE("%p, %p\n", hrequest, reserved);
2356
2357 if (!(request = (request_t *)grab_object( hrequest )))
2358 {
2359 set_last_error( ERROR_INVALID_HANDLE );
2360 return FALSE;
2361 }
2362 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2363 {
2364 release_object( &request->hdr );
2365 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2366 return FALSE;
2367 }
2368
2369 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2370 {
2371 receive_response_t *r;
2372
2373 if (!(r = heap_alloc( sizeof(receive_response_t) ))) return FALSE;
2374 r->hdr.request = request;
2375 r->hdr.proc = task_receive_response;
2376
2377 addref_object( &request->hdr );
2378 ret = queue_task( (task_header_t *)r );
2379 }
2380 else
2381 ret = receive_response( request, FALSE );
2382
2383 release_object( &request->hdr );
2384 return ret;
2385 }
2386
2387 static BOOL query_data_available( request_t *request, DWORD *available, BOOL async )
2388 {
2389 DWORD count = get_available_data( request );
2390
2391 if (!request->read_chunked)
2392 count += netconn_query_data_available( &request->netconn );
2393 if (!count)
2394 {
2395 refill_buffer( request, async );
2396 count = get_available_data( request );
2397 if (!request->read_chunked)
2398 count += netconn_query_data_available( &request->netconn );
2399 }
2400
2401 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2402 TRACE("%u bytes available\n", count);
2403 if (available) *available = count;
2404 return TRUE;
2405 }
2406
2407 static void task_query_data_available( task_header_t *task )
2408 {
2409 query_data_t *q = (query_data_t *)task;
2410 query_data_available( q->hdr.request, q->available, TRUE );
2411 }
2412
2413 /***********************************************************************
2414 * WinHttpQueryDataAvailable (winhttp.@)
2415 */
2416 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2417 {
2418 BOOL ret;
2419 request_t *request;
2420
2421 TRACE("%p, %p\n", hrequest, available);
2422
2423 if (!(request = (request_t *)grab_object( hrequest )))
2424 {
2425 set_last_error( ERROR_INVALID_HANDLE );
2426 return FALSE;
2427 }
2428 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2429 {
2430 release_object( &request->hdr );
2431 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2432 return FALSE;
2433 }
2434
2435 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2436 {
2437 query_data_t *q;
2438
2439 if (!(q = heap_alloc( sizeof(query_data_t) ))) return FALSE;
2440 q->hdr.request = request;
2441 q->hdr.proc = task_query_data_available;
2442 q->available = available;
2443
2444 addref_object( &request->hdr );
2445 ret = queue_task( (task_header_t *)q );
2446 }
2447 else
2448 ret = query_data_available( request, available, FALSE );
2449
2450 release_object( &request->hdr );
2451 return ret;
2452 }
2453
2454 static void task_read_data( task_header_t *task )
2455 {
2456 read_data_t *r = (read_data_t *)task;
2457 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2458 }
2459
2460 /***********************************************************************
2461 * WinHttpReadData (winhttp.@)
2462 */
2463 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2464 {
2465 BOOL ret;
2466 request_t *request;
2467
2468 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2469
2470 if (!(request = (request_t *)grab_object( hrequest )))
2471 {
2472 set_last_error( ERROR_INVALID_HANDLE );
2473 return FALSE;
2474 }
2475 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2476 {
2477 release_object( &request->hdr );
2478 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2479 return FALSE;
2480 }
2481
2482 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2483 {
2484 read_data_t *r;
2485
2486 if (!(r = heap_alloc( sizeof(read_data_t) ))) return FALSE;
2487 r->hdr.request = request;
2488 r->hdr.proc = task_read_data;
2489 r->buffer = buffer;
2490 r->to_read = to_read;
2491 r->read = read;
2492
2493 addref_object( &request->hdr );
2494 ret = queue_task( (task_header_t *)r );
2495 }
2496 else
2497 ret = read_data( request, buffer, to_read, read, FALSE );
2498
2499 release_object( &request->hdr );
2500 return ret;
2501 }
2502
2503 static BOOL write_data( request_t *request, LPCVOID buffer, DWORD to_write, LPDWORD written, BOOL async )
2504 {
2505 BOOL ret;
2506 int num_bytes;
2507
2508 ret = netconn_send( &request->netconn, buffer, to_write, &num_bytes );
2509
2510 if (async)
2511 {
2512 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
2513 else
2514 {
2515 WINHTTP_ASYNC_RESULT result;
2516 result.dwResult = API_WRITE_DATA;
2517 result.dwError = get_last_error();
2518 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2519 }
2520 }
2521 if (ret && written) *written = num_bytes;
2522 return ret;
2523 }
2524
2525 static void task_write_data( task_header_t *task )
2526 {
2527 write_data_t *w = (write_data_t *)task;
2528 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
2529 }
2530
2531 /***********************************************************************
2532 * WinHttpWriteData (winhttp.@)
2533 */
2534 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
2535 {
2536 BOOL ret;
2537 request_t *request;
2538
2539 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
2540
2541 if (!(request = (request_t *)grab_object( hrequest )))
2542 {
2543 set_last_error( ERROR_INVALID_HANDLE );
2544 return FALSE;
2545 }
2546 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2547 {
2548 release_object( &request->hdr );
2549 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2550 return FALSE;
2551 }
2552
2553 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2554 {
2555 write_data_t *w;
2556
2557 if (!(w = heap_alloc( sizeof(write_data_t) ))) return FALSE;
2558 w->hdr.request = request;
2559 w->hdr.proc = task_write_data;
2560 w->buffer = buffer;
2561 w->to_write = to_write;
2562 w->written = written;
2563
2564 addref_object( &request->hdr );
2565 ret = queue_task( (task_header_t *)w );
2566 }
2567 else
2568 ret = write_data( request, buffer, to_write, written, FALSE );
2569
2570 release_object( &request->hdr );
2571 return ret;
2572 }
2573
2574 enum request_state
2575 {
2576 REQUEST_STATE_UNINITIALIZED,
2577 REQUEST_STATE_INITIALIZED,
2578 REQUEST_STATE_CANCELLED,
2579 REQUEST_STATE_OPEN,
2580 REQUEST_STATE_SENT,
2581 REQUEST_STATE_RESPONSE_RECEIVED
2582 };
2583
2584 struct winhttp_request
2585 {
2586 IWinHttpRequest IWinHttpRequest_iface;
2587 LONG refs;
2588 CRITICAL_SECTION cs;
2589 enum request_state state;
2590 HINTERNET hsession;
2591 HINTERNET hconnect;
2592 HINTERNET hrequest;
2593 VARIANT data;
2594 WCHAR *verb;
2595 HANDLE thread;
2596 HANDLE wait;
2597 HANDLE cancel;
2598 char *buffer;
2599 DWORD offset;
2600 DWORD bytes_available;
2601 DWORD bytes_read;
2602 DWORD error;
2603 DWORD logon_policy;
2604 DWORD disable_feature;
2605 LONG resolve_timeout;
2606 LONG connect_timeout;
2607 LONG send_timeout;
2608 LONG receive_timeout;
2609 WINHTTP_PROXY_INFO proxy;
2610 };
2611
2612 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
2613 {
2614 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
2615 }
2616
2617 static ULONG WINAPI winhttp_request_AddRef(
2618 IWinHttpRequest *iface )
2619 {
2620 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2621 return InterlockedIncrement( &request->refs );
2622 }
2623
2624 /* critical section must be held */
2625 static void cancel_request( struct winhttp_request *request )
2626 {
2627 if (request->state <= REQUEST_STATE_CANCELLED) return;
2628 if (request->thread) SetEvent( request->cancel );
2629 request->state = REQUEST_STATE_CANCELLED;
2630 }
2631
2632 /* critical section must be held */
2633 static void free_request( struct winhttp_request *request )
2634 {
2635 if (request->state < REQUEST_STATE_INITIALIZED) return;
2636 WinHttpCloseHandle( request->hrequest );
2637 WinHttpCloseHandle( request->hconnect );
2638 WinHttpCloseHandle( request->hsession );
2639 CloseHandle( request->thread );
2640 CloseHandle( request->wait );
2641 CloseHandle( request->cancel );
2642 heap_free( (WCHAR *)request->proxy.lpszProxy );
2643 heap_free( (WCHAR *)request->proxy.lpszProxyBypass );
2644 heap_free( request->buffer );
2645 heap_free( request->verb );
2646 VariantClear( &request->data );
2647 }
2648
2649 static ULONG WINAPI winhttp_request_Release(
2650 IWinHttpRequest *iface )
2651 {
2652 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2653 LONG refs = InterlockedDecrement( &request->refs );
2654 if (!refs)
2655 {
2656 TRACE("destroying %p\n", request);
2657
2658 EnterCriticalSection( &request->cs );
2659 cancel_request( request );
2660 free_request( request );
2661 LeaveCriticalSection( &request->cs );
2662 request->cs.DebugInfo->Spare[0] = 0;
2663 DeleteCriticalSection( &request->cs );
2664 heap_free( request );
2665 }
2666 return refs;
2667 }
2668
2669 static HRESULT WINAPI winhttp_request_QueryInterface(
2670 IWinHttpRequest *iface,
2671 REFIID riid,
2672 void **obj )
2673 {
2674 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2675
2676 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
2677
2678 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
2679 IsEqualGUID( riid, &IID_IDispatch ) ||
2680 IsEqualGUID( riid, &IID_IUnknown ))
2681 {
2682 *obj = iface;
2683 }
2684 else
2685 {
2686 FIXME("interface %s not implemented\n", debugstr_guid(riid));
2687 return E_NOINTERFACE;
2688 }
2689 IWinHttpRequest_AddRef( iface );
2690 return S_OK;
2691 }
2692
2693 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
2694 IWinHttpRequest *iface,
2695 UINT *count )
2696 {
2697 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2698
2699 TRACE("%p, %p\n", request, count);
2700 *count = 1;
2701 return S_OK;
2702 }
2703
2704 enum type_id
2705 {
2706 IWinHttpRequest_tid,
2707 last_tid
2708 };
2709
2710 static ITypeLib *winhttp_typelib;
2711 static ITypeInfo *winhttp_typeinfo[last_tid];
2712
2713 static REFIID winhttp_tid_id[] =
2714 {
2715 &IID_IWinHttpRequest
2716 };
2717
2718 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
2719 {
2720 HRESULT hr;
2721
2722 if (!winhttp_typelib)
2723 {
2724 ITypeLib *typelib;
2725
2726 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
2727 if (FAILED(hr))
2728 {
2729 ERR("LoadRegTypeLib failed: %08x\n", hr);
2730 return hr;
2731 }
2732 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
2733 ITypeLib_Release( typelib );
2734 }
2735 if (!winhttp_typeinfo[tid])
2736 {
2737 ITypeInfo *typeinfo;
2738
2739 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
2740 if (FAILED(hr))
2741 {
2742 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
2743 return hr;
2744 }
2745 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
2746 ITypeInfo_Release( typeinfo );
2747 }
2748 *ret = winhttp_typeinfo[tid];
2749 return S_OK;
2750 }
2751
2752 static HRESULT WINAPI winhttp_request_GetTypeInfo(
2753 IWinHttpRequest *iface,
2754 UINT index,
2755 LCID lcid,
2756 ITypeInfo **info )
2757 {
2758 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2759 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
2760
2761 return get_typeinfo( IWinHttpRequest_tid, info );
2762 }
2763
2764 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
2765 IWinHttpRequest *iface,
2766 REFIID riid,
2767 LPOLESTR *names,
2768 UINT count,
2769 LCID lcid,
2770 DISPID *dispid )
2771 {
2772 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2773 ITypeInfo *typeinfo;
2774 HRESULT hr;
2775
2776 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
2777
2778 if (!names || !count || !dispid) return E_INVALIDARG;
2779
2780 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2781 if (SUCCEEDED(hr))
2782 {
2783 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
2784 ITypeInfo_Release( typeinfo );
2785 }
2786 return hr;
2787 }
2788
2789 static HRESULT WINAPI winhttp_request_Invoke(
2790 IWinHttpRequest *iface,
2791 DISPID member,
2792 REFIID riid,
2793 LCID lcid,
2794 WORD flags,
2795 DISPPARAMS *params,
2796 VARIANT *result,
2797 EXCEPINFO *excep_info,
2798 UINT *arg_err )
2799 {
2800 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2801 ITypeInfo *typeinfo;
2802 HRESULT hr;
2803
2804 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
2805 lcid, flags, params, result, excep_info, arg_err);
2806
2807 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2808 if (SUCCEEDED(hr))
2809 {
2810 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
2811 params, result, excep_info, arg_err );
2812 ITypeInfo_Release( typeinfo );
2813 }
2814 return hr;
2815 }
2816
2817 static HRESULT WINAPI winhttp_request_SetProxy(
2818 IWinHttpRequest *iface,
2819 HTTPREQUEST_PROXY_SETTING proxy_setting,
2820 VARIANT proxy_server,
2821 VARIANT bypass_list )
2822 {
2823 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2824 DWORD err = ERROR_SUCCESS;
2825
2826 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
2827 debugstr_variant(&bypass_list));
2828
2829 EnterCriticalSection( &request->cs );
2830 switch (proxy_setting)
2831 {
2832 case HTTPREQUEST_PROXYSETTING_DEFAULT:
2833 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
2834 heap_free( (WCHAR *)request->proxy.lpszProxy );
2835 heap_free( (WCHAR *)request->proxy.lpszProxyBypass );
2836 request->proxy.lpszProxy = NULL;
2837 request->proxy.lpszProxyBypass = NULL;
2838 break;
2839
2840 case HTTPREQUEST_PROXYSETTING_DIRECT:
2841 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
2842 heap_free( (WCHAR *)request->proxy.lpszProxy );
2843 heap_free( (WCHAR *)request->proxy.lpszProxyBypass );
2844 request->proxy.lpszProxy = NULL;
2845 request->proxy.lpszProxyBypass = NULL;
2846 break;
2847
2848 case HTTPREQUEST_PROXYSETTING_PROXY:
2849 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
2850 if (V_VT( &proxy_server ) == VT_BSTR)
2851 {
2852 heap_free( (WCHAR *)request->proxy.lpszProxy );
2853 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
2854 }
2855 if (V_VT( &bypass_list ) == VT_BSTR)
2856 {
2857 heap_free( (WCHAR *)request->proxy.lpszProxyBypass );
2858 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
2859 }
2860 break;
2861
2862 default:
2863 err = ERROR_INVALID_PARAMETER;
2864 break;
2865 }
2866 LeaveCriticalSection( &request->cs );
2867 return HRESULT_FROM_WIN32( err );
2868 }
2869
2870 static HRESULT WINAPI winhttp_request_SetCredentials(
2871 IWinHttpRequest *iface,
2872 BSTR username,
2873 BSTR password,
2874 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
2875 {
2876 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2877 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
2878 DWORD err = ERROR_SUCCESS;
2879
2880 TRACE("%p, %s, %p\n", request, debugstr_w(username), password);
2881
2882 EnterCriticalSection( &request->cs );
2883 if (request->state < REQUEST_STATE_OPEN)
2884 {
2885 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
2886 goto done;
2887 }
2888 switch (flags)
2889 {
2890 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
2891 target = WINHTTP_AUTH_TARGET_SERVER;
2892 break;
2893 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
2894 target = WINHTTP_AUTH_TARGET_PROXY;
2895 break;
2896 default:
2897 err = ERROR_INVALID_PARAMETER;
2898 goto done;
2899 }
2900 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
2901 {
2902 err = get_last_error();
2903 }
2904 done:
2905 LeaveCriticalSection( &request->cs );
2906 return HRESULT_FROM_WIN32( err );
2907 }
2908
2909 static void initialize_request( struct winhttp_request *request )
2910 {
2911 request->hrequest = NULL;
2912 request->hconnect = NULL;
2913 request->hsession = NULL;
2914 request->thread = NULL;
2915 request->wait = NULL;
2916 request->cancel = NULL;
2917 request->buffer = NULL;
2918 request->verb = NULL;
2919 request->offset = 0;
2920 request->bytes_available = 0;
2921 request->bytes_read = 0;
2922 request->error = ERROR_SUCCESS;
2923 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
2924 request->disable_feature = WINHTTP_DISABLE_AUTHENTICATION;
2925 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
2926 request->proxy.lpszProxy = NULL;
2927 request->proxy.lpszProxyBypass = NULL;
2928 request->resolve_timeout = 0;
2929 request->connect_timeout = 60000;
2930 request->send_timeout = 30000;
2931 request->receive_timeout = 30000;
2932 VariantInit( &request->data );
2933 request->state = REQUEST_STATE_INITIALIZED;
2934 }
2935
2936 static HRESULT WINAPI winhttp_request_Open(
2937 IWinHttpRequest *iface,
2938 BSTR method,
2939 BSTR url,
2940 VARIANT async )
2941 {
2942 static const WCHAR typeW[] = {'*','/','*',0};
2943 static const WCHAR *acceptW[] = {typeW, NULL};
2944 static const WCHAR httpsW[] = {'h','t','t','p','s'};
2945 static const WCHAR user_agentW[] = {
2946 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
2947 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
2948 'R','e','q','u','e','s','t','.','5',')',0};
2949 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2950 HINTERNET hsession = NULL, hconnect = NULL, hrequest;
2951 URL_COMPONENTS uc;
2952 WCHAR *hostname, *path = NULL, *verb = NULL;
2953 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0, request_flags = 0;
2954
2955 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
2956 debugstr_variant(&async));
2957
2958 if (!method || !url) return E_INVALIDARG;
2959
2960 memset( &uc, 0, sizeof(uc) );
2961 uc.dwStructSize = sizeof(uc);
2962 uc.dwSchemeLength = ~0u;
2963 uc.dwHostNameLength = ~0u;
2964 uc.dwUrlPathLength = ~0u;
2965 uc.dwExtraInfoLength = ~0u;
2966 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( get_last_error() );
2967
2968 EnterCriticalSection( &request->cs );
2969 if (request->state != REQUEST_STATE_INITIALIZED)
2970 {
2971 cancel_request( request );
2972 free_request( request );
2973 initialize_request( request );
2974 }
2975 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
2976 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
2977 hostname[uc.dwHostNameLength] = 0;
2978
2979 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
2980 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
2981 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
2982
2983 if (!(verb = strdupW( method ))) goto error;
2984 if (V_BOOL( &async )) flags |= WINHTTP_FLAG_ASYNC;
2985 if (!(hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, flags )))
2986 {
2987 err = get_last_error();
2988 goto error;
2989 }
2990 if (!(hconnect = WinHttpConnect( hsession, hostname, uc.nPort, 0 )))
2991 {
2992 err = get_last_error();
2993 goto error;
2994 }
2995 len = sizeof(httpsW) / sizeof(WCHAR);
2996 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
2997 {
2998 request_flags |= WINHTTP_FLAG_SECURE;
2999 }
3000 if (!(hrequest = WinHttpOpenRequest( hconnect, method, path, NULL, NULL, acceptW, request_flags )))
3001 {
3002 err = get_last_error();
3003 goto error;
3004 }
3005 if (flags & WINHTTP_FLAG_ASYNC)
3006 {
3007 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3008 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3009 WinHttpSetOption( hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3010 }
3011 request->state = REQUEST_STATE_OPEN;
3012 request->hsession = hsession;
3013 request->hconnect = hconnect;
3014 request->hrequest = hrequest;
3015 request->verb = verb;
3016 heap_free( hostname );
3017 heap_free( path );
3018 LeaveCriticalSection( &request->cs );
3019 return S_OK;
3020
3021 error:
3022 WinHttpCloseHandle( hconnect );
3023 WinHttpCloseHandle( hsession );
3024 heap_free( hostname );
3025 heap_free( path );
3026 heap_free( verb );
3027 LeaveCriticalSection( &request->cs );
3028 return HRESULT_FROM_WIN32( err );
3029 }
3030
3031 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3032 IWinHttpRequest *iface,
3033 BSTR header,
3034 BSTR value )
3035 {
3036 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3037 static const WCHAR emptyW[] = {0};
3038 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3039 DWORD len, err = ERROR_SUCCESS;
3040 WCHAR *str;
3041
3042 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3043
3044 if (!header) return E_INVALIDARG;
3045
3046 EnterCriticalSection( &request->cs );
3047 if (request->state < REQUEST_STATE_OPEN)
3048 {
3049 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3050 goto done;
3051 }
3052 if (request->state >= REQUEST_STATE_SENT)
3053 {
3054 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3055 goto done;
3056 }
3057 len = strlenW( header ) + 4;
3058 if (value) len += strlenW( value );
3059 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3060 {
3061 err = ERROR_OUTOFMEMORY;
3062 goto done;
3063 }
3064 sprintfW( str, fmtW, header, value ? value : emptyW );
3065 if (!WinHttpAddRequestHeaders( request->hrequest, str, len, WINHTTP_ADDREQ_FLAG_REPLACE ))
3066 {
3067 err = get_last_error();
3068 }
3069 heap_free( str );
3070
3071 done:
3072 LeaveCriticalSection( &request->cs );
3073 return HRESULT_FROM_WIN32( err );
3074 }
3075
3076 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3077 IWinHttpRequest *iface,
3078 BSTR header,
3079 BSTR *value )
3080 {
3081 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3082 DWORD size, err = ERROR_SUCCESS;
3083
3084 TRACE("%p, %p\n", request, header);
3085
3086 EnterCriticalSection( &request->cs );
3087 if (request->state < REQUEST_STATE_SENT)
3088 {
3089 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3090 goto done;
3091 }
3092 if (!header || !value)
3093 {
3094 err = ERROR_INVALID_PARAMETER;
3095 goto done;
3096 }
3097 size = 0;
3098 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3099 {
3100 err = get_last_error();
3101 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3102 }
3103 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3104 {
3105 err = ERROR_OUTOFMEMORY;
3106 goto done;
3107 }
3108 err = ERROR_SUCCESS;
3109 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3110 {
3111 err = get_last_error();
3112 SysFreeString( *value );
3113 }
3114 done:
3115 LeaveCriticalSection( &request->cs );
3116 return HRESULT_FROM_WIN32( err );
3117 }
3118
3119 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3120 IWinHttpRequest *iface,
3121 BSTR *headers )
3122 {
3123 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3124 DWORD size, err = ERROR_SUCCESS;
3125
3126 TRACE("%p, %p\n", request, headers);
3127
3128 if (!headers) return E_INVALIDARG;
3129
3130 EnterCriticalSection( &request->cs );
3131 if (request->state < REQUEST_STATE_SENT)
3132 {
3133 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3134 goto done;
3135 }
3136 size = 0;
3137 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3138 {
3139 err = get_last_error();
3140 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3141 }
3142 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3143 {
3144 err = ERROR_OUTOFMEMORY;
3145 goto done;
3146 }
3147 err = ERROR_SUCCESS;
3148 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3149 {
3150 err = get_last_error();
3151 SysFreeString( *headers );
3152 }
3153 done:
3154 LeaveCriticalSection( &request->cs );
3155 return HRESULT_FROM_WIN32( err );
3156 }
3157
3158 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3159 {
3160 struct winhttp_request *request = (struct winhttp_request *)context;
3161
3162 switch (status)
3163 {
3164 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3165 request->bytes_available = *(DWORD *)buffer;
3166 request->error = ERROR_SUCCESS;
3167 break;
3168 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3169 request->bytes_read = size;
3170 request->error = ERROR_SUCCESS;
3171 break;
3172 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3173 {
3174 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3175 request->error = result->dwError;
3176 break;
3177 }
3178 default: break;
3179 }
3180 SetEvent( request->wait );
3181 }
3182
3183 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3184 {
3185 if (!request->wait) return;
3186 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3187 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3188 }
3189
3190 static DWORD wait_for_completion( struct winhttp_request *request )
3191 {
3192 HANDLE handles[2];
3193
3194 if (!request->wait)
3195 {
3196 request->error = ERROR_SUCCESS;
3197 return ERROR_SUCCESS;
3198 }
3199 handles[0] = request->wait;
3200 handles[1] = request->cancel;
3201 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3202 {
3203 case WAIT_OBJECT_0:
3204 break;
3205 case WAIT_OBJECT_0 + 1:
3206 request->error = ERROR_CANCELLED;
3207 break;
3208 default:
3209 request->error = get_last_error();
3210 break;
3211 }
3212 return request->error;
3213 }
3214
3215 static HRESULT request_receive( struct winhttp_request *request )
3216 {
3217 DWORD err, size, buflen = 4096;
3218
3219 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3220 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3221 {
3222 return HRESULT_FROM_WIN32( get_last_error() );
3223 }
3224 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3225 if (!strcmpW( request->verb, headW ))
3226 {
3227 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3228 return S_OK;
3229 }
3230 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3231 request->buffer[0] = 0;
3232 size = 0;
3233 do
3234 {
3235 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3236 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3237 {
3238 err = get_last_error();
3239 goto error;
3240 }
3241 if ((err = wait_for_completion( request ))) goto error;
3242 if (!request->bytes_available) break;
3243 size += request->bytes_available;
3244 if (buflen < size)
3245 {
3246 char *tmp;
3247 while (buflen < size) buflen *= 2;
3248 if (!(tmp = heap_realloc( request->buffer, buflen )))
3249 {
3250 err = ERROR_OUTOFMEMORY;
3251 goto error;
3252 }
3253 request->buffer = tmp;
3254 }
3255 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3256 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3257 request->bytes_available, &request->bytes_read ))
3258 {
3259 err = get_last_error();
3260 goto error;
3261 }
3262 if ((err = wait_for_completion( request ))) goto error;
3263 request->offset += request->bytes_read;
3264 } while (request->bytes_read);
3265
3266 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3267 return S_OK;
3268
3269 error:
3270 heap_free( request->buffer );
3271 request->buffer = NULL;
3272 return HRESULT_FROM_WIN32( err );
3273 }
3274
3275 static DWORD request_set_parameters( struct winhttp_request *request )
3276 {
3277 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3278 sizeof(request->proxy) )) return get_last_error();
3279
3280 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3281 sizeof(request->logon_policy) )) return get_last_error();
3282
3283 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3284 sizeof(request->disable_feature) )) return get_last_error();
3285
3286 if (!WinHttpSetTimeouts( request->hrequest,
3287 request->resolve_timeout,
3288 request->connect_timeout,
3289 request->send_timeout,
3290 request->receive_timeout )) return get_last_error();
3291 return ERROR_SUCCESS;
3292 }
3293
3294 static void request_set_utf8_content_type( struct winhttp_request *request )
3295 {
3296 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3297 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3298 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3299 WCHAR headerW[64];
3300 int len;
3301
3302 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3303 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3304 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3305 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3306 }
3307
3308 static HRESULT request_send( struct winhttp_request *request )
3309 {
3310 SAFEARRAY *sa = NULL;
3311 VARIANT data;
3312 char *ptr = NULL;
3313 LONG size = 0;
3314 HRESULT hr;
3315 DWORD err;
3316
3317 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3318 if (strcmpW( request->verb, getW ))
3319 {
3320 VariantInit( &data );
3321 if (V_VT( &request->data ) == VT_BSTR)
3322 {
3323 UINT cp = CP_ACP;
3324 const WCHAR *str = V_BSTR( &request->data );
3325 int i, len = strlenW( str );
3326
3327 for (i = 0; i < len; i++)
3328 {
3329 if (str[i] > 127)
3330 {
3331 cp = CP_UTF8;
3332 break;
3333 }
3334 }
3335 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3336 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3337 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3338 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3339 }
3340 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3341 {
3342 sa = V_ARRAY( &data );
3343 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3344 if ((hr = SafeArrayGetUBound( sa, 1, &size ) != S_OK))
3345 {
3346 SafeArrayUnaccessData( sa );
3347 return hr;
3348 }
3349 size++;
3350 }
3351 }
3352 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3353 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3354 {
3355 err = get_last_error();
3356 goto error;
3357 }
3358 if ((err = wait_for_completion( request ))) goto error;
3359 if (sa) SafeArrayUnaccessData( sa );
3360 else heap_free( ptr );
3361 request->state = REQUEST_STATE_SENT;
3362 return S_OK;
3363
3364 error:
3365 if (sa) SafeArrayUnaccessData( sa );
3366 else heap_free( ptr );
3367 return HRESULT_FROM_WIN32( err );
3368 }
3369
3370 static HRESULT request_send_and_receive( struct winhttp_request *request )
3371 {
3372 HRESULT hr = request_send( request );
3373 if (hr == S_OK) hr = request_receive( request );
3374 return hr;
3375 }
3376
3377 static DWORD CALLBACK send_and_receive_proc( void *arg )
3378 {
3379 struct winhttp_request *request = (struct winhttp_request *)arg;
3380 return request_send_and_receive( request );
3381 }
3382
3383 static HRESULT WINAPI winhttp_request_Send(
3384 IWinHttpRequest *iface,
3385 VARIANT body )
3386 {
3387 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3388 HRESULT hr;
3389
3390 TRACE("%p, %s\n", request, debugstr_variant(&body));
3391
3392 EnterCriticalSection( &request->cs );
3393 if (request->state < REQUEST_STATE_OPEN)
3394 {
3395 LeaveCriticalSection( &request->cs );
3396 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3397 }
3398 if (request->state >= REQUEST_STATE_SENT)
3399 {
3400 LeaveCriticalSection( &request->cs );
3401 return S_OK;
3402 }
3403 VariantClear( &request->data );
3404 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK) {
3405 LeaveCriticalSection( &request->cs );
3406 return hr;
3407 }
3408
3409 if (request->wait) /* async request */
3410 {
3411 if (!(request->thread = CreateThread( NULL, 0, send_and_receive_proc, request, 0, NULL )))
3412 {
3413 LeaveCriticalSection( &request->cs );
3414 return HRESULT_FROM_WIN32( get_last_error() );
3415 }
3416 }
3417 else hr = request_send_and_receive( request );
3418 LeaveCriticalSection( &request->cs );
3419 return hr;
3420 }
3421
3422 static HRESULT WINAPI winhttp_request_get_Status(
3423 IWinHttpRequest *iface,
3424 LONG *status )
3425 {
3426 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3427 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
3428
3429 TRACE("%p, %p\n", request, status);
3430
3431 if (!status) return E_INVALIDARG;
3432
3433 EnterCriticalSection( &request->cs );
3434 if (request->state < REQUEST_STATE_SENT)
3435 {
3436 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3437 goto done;
3438 }
3439 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
3440 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
3441 {
3442 err = get_last_error();
3443 goto done;
3444 }
3445 *status = status_code;
3446
3447 done:
3448 LeaveCriticalSection( &request->cs );
3449 return HRESULT_FROM_WIN32( err );
3450 }
3451
3452 static HRESULT WINAPI winhttp_request_get_StatusText(
3453 IWinHttpRequest *iface,
3454 BSTR *status )
3455 {
3456 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3457 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
3458
3459 TRACE("%p, %p\n", request, status);
3460
3461 if (!status) return E_INVALIDARG;
3462
3463 EnterCriticalSection( &request->cs );
3464 if (request->state < REQUEST_STATE_SENT)
3465 {
3466 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3467 goto done;
3468 }
3469 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
3470 {
3471 err = get_last_error();
3472 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3473 }
3474 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
3475 {
3476 err = ERROR_OUTOFMEMORY;
3477 goto done;
3478 }
3479 index = 0;
3480 err = ERROR_SUCCESS;
3481 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
3482 {
3483 err = get_last_error();
3484 SysFreeString( *status );
3485 }
3486 done:
3487 LeaveCriticalSection( &request->cs );
3488 return HRESULT_FROM_WIN32( err );
3489 }
3490
3491 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
3492 {
3493 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
3494 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
3495 WCHAR *buffer, *p;
3496 DWORD size;
3497
3498 *codepage = CP_ACP;
3499 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
3500 get_last_error() == ERROR_INSUFFICIENT_BUFFER)
3501 {
3502 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
3503 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
3504 {
3505 return get_last_error();
3506 }
3507 if ((p = strstrW( buffer, charsetW )))
3508 {
3509 p += strlenW( charsetW );
3510 while (*p == ' ') p++;
3511 if (*p++ == '=')
3512 {
3513 while (*p == ' ') p++;
3514 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
3515 }
3516 }
3517 heap_free( buffer );
3518 }
3519 return ERROR_SUCCESS;
3520 }
3521
3522 static HRESULT WINAPI winhttp_request_get_ResponseText(
3523 IWinHttpRequest *iface,
3524 BSTR *body )
3525 {
3526 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3527 UINT codepage;
3528 DWORD err = ERROR_SUCCESS;
3529 int len;
3530
3531 TRACE("%p, %p\n", request, body);
3532
3533 if (!body) return E_INVALIDARG;
3534
3535 EnterCriticalSection( &request->cs );
3536 if (request->state < REQUEST_STATE_SENT)
3537 {
3538 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3539 goto done;
3540 }
3541 if ((err = request_get_codepage( request, &codepage ))) goto done;
3542 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
3543 if (!(*body = SysAllocStringLen( NULL, len )))
3544 {
3545 err = ERROR_OUTOFMEMORY;
3546 goto done;
3547 }
3548 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
3549 (*body)[len] = 0;
3550
3551 done:
3552 LeaveCriticalSection( &request->cs );
3553 return HRESULT_FROM_WIN32( err );
3554 }
3555
3556 static HRESULT WINAPI winhttp_request_get_ResponseBody(
3557 IWinHttpRequest *iface,
3558 VARIANT *body )
3559 {
3560 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3561 SAFEARRAY *sa;
3562 HRESULT hr;
3563 DWORD err = ERROR_SUCCESS;
3564 char *ptr;
3565
3566 TRACE("%p, %p\n", request, body);
3567
3568 if (!body) return E_INVALIDARG;
3569
3570 EnterCriticalSection( &request->cs );
3571 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
3572 {
3573 err = ERROR_OUTOFMEMORY;
3574 goto done;
3575 }
3576 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
3577 {
3578 SafeArrayDestroy( sa );
3579 LeaveCriticalSection( &request->cs );
3580 return hr;
3581 }
3582 memcpy( ptr, request->buffer, request->offset );
3583 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
3584 {
3585 SafeArrayDestroy( sa );
3586 LeaveCriticalSection( &request->cs );
3587 return hr;
3588 }
3589 V_VT( body ) = VT_ARRAY|VT_UI1;
3590 V_ARRAY( body ) = sa;
3591
3592 done:
3593 LeaveCriticalSection( &request->cs );
3594 return HRESULT_FROM_WIN32( err );
3595 }
3596
3597 static HRESULT WINAPI winhttp_request_get_ResponseStream(
3598 IWinHttpRequest *iface,
3599 VARIANT *body )
3600 {
3601 FIXME("\n");
3602 return E_NOTIMPL;
3603 }
3604
3605 static HRESULT WINAPI winhttp_request_get_Option(
3606 IWinHttpRequest *iface,
3607 WinHttpRequestOption option,
3608 VARIANT *value )
3609 {
3610 FIXME("\n");
3611 return E_NOTIMPL;
3612 }
3613
3614 static HRESULT WINAPI winhttp_request_put_Option(
3615 IWinHttpRequest *iface,
3616 WinHttpRequestOption option,
3617 VARIANT value )
3618 {
3619 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3620 HRESULT hr = S_OK;
3621
3622 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
3623
3624 EnterCriticalSection( &request->cs );
3625 switch (option)
3626 {
3627 case WinHttpRequestOption_EnableRedirects:
3628 {
3629 if (V_BOOL( &value ))
3630 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
3631 else
3632 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
3633 break;
3634 }
3635 default:
3636 FIXME("unimplemented option %u\n", option);
3637 hr = E_NOTIMPL;
3638 break;
3639 }
3640 LeaveCriticalSection( &request->cs );
3641 return hr;
3642 }
3643
3644 /* critical section must be held */
3645 static DWORD wait_for_response( struct winhttp_request *request, DWORD timeout )
3646 {
3647 HANDLE thread = request->thread;
3648 DWORD err, ret;
3649
3650 LeaveCriticalSection( &request->cs );
3651 while ((err = MsgWaitForMultipleObjects( 1, &thread, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3652 {
3653 MSG msg;
3654 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3655 {
3656 TranslateMessage( &msg );
3657 DispatchMessageW( &msg );
3658 }
3659 }
3660 switch (err)
3661 {
3662 case WAIT_OBJECT_0:
3663 ret = ERROR_SUCCESS;
3664 break;
3665 case WAIT_TIMEOUT:
3666 ret = ERROR_TIMEOUT;
3667 break;
3668 case WAIT_FAILED:
3669 default:
3670 ret = get_last_error();
3671 break;
3672 }
3673 EnterCriticalSection( &request->cs );
3674 return ret;
3675 }
3676
3677 static HRESULT WINAPI winhttp_request_WaitForResponse(
3678 IWinHttpRequest *iface,
3679 VARIANT timeout,
3680 VARIANT_BOOL *succeeded )
3681 {
3682 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3683 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
3684
3685 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
3686
3687 EnterCriticalSection( &request->cs );
3688 if (!request->thread)
3689 {
3690 LeaveCriticalSection( &request->cs );
3691 return S_OK;
3692 }
3693 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
3694 {
3695 LeaveCriticalSection( &request->cs );
3696 return S_OK;
3697 }
3698 switch ((err = wait_for_response( request, msecs )))
3699 {
3700 case ERROR_TIMEOUT:
3701 if (succeeded) *succeeded = VARIANT_FALSE;
3702 err = ERROR_SUCCESS;
3703 break;
3704
3705 case ERROR_SUCCESS:
3706 if (succeeded) *succeeded = VARIANT_TRUE;
3707 break;
3708
3709 default: break;
3710 }
3711 LeaveCriticalSection( &request->cs );
3712 return HRESULT_FROM_WIN32( err );
3713 }
3714
3715 static HRESULT WINAPI winhttp_request_Abort(
3716 IWinHttpRequest *iface )
3717 {
3718 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3719
3720 TRACE("%p\n", request);
3721
3722 EnterCriticalSection( &request->cs );
3723 cancel_request( request );
3724 LeaveCriticalSection( &request->cs );
3725 return S_OK;
3726 }
3727
3728 static HRESULT WINAPI winhttp_request_SetTimeouts(
3729 IWinHttpRequest *iface,
3730 LONG resolve_timeout,
3731 LONG connect_timeout,
3732 LONG send_timeout,
3733 LONG receive_timeout )
3734 {
3735 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3736
3737 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
3738
3739 EnterCriticalSection( &request->cs );
3740 request->resolve_timeout = resolve_timeout;
3741 request->connect_timeout = connect_timeout;
3742 request->send_timeout = send_timeout;
3743 request->receive_timeout = receive_timeout;
3744 LeaveCriticalSection( &request->cs );
3745 return S_OK;
3746 }
3747
3748 static HRESULT WINAPI winhttp_request_SetClientCertificate(
3749 IWinHttpRequest *iface,
3750 BSTR certificate )
3751 {
3752 FIXME("\n");
3753 return E_NOTIMPL;
3754 }
3755
3756 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
3757 IWinHttpRequest *iface,
3758 WinHttpRequestAutoLogonPolicy policy )
3759 {
3760 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3761 HRESULT hr = S_OK;
3762
3763 TRACE("%p, %u\n", request, policy );
3764
3765 EnterCriticalSection( &request->cs );
3766 switch (policy)
3767 {
3768 case AutoLogonPolicy_Always:
3769 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
3770 break;
3771 case AutoLogonPolicy_OnlyIfBypassProxy:
3772 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
3773 break;
3774 case AutoLogonPolicy_Never:
3775 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
3776 break;
3777 default: hr = E_INVALIDARG;
3778 break;
3779 }
3780 LeaveCriticalSection( &request->cs );
3781 return hr;
3782 }
3783
3784 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
3785 {
3786 winhttp_request_QueryInterface,
3787 winhttp_request_AddRef,
3788 winhttp_request_Release,
3789 winhttp_request_GetTypeInfoCount,
3790 winhttp_request_GetTypeInfo,
3791 winhttp_request_GetIDsOfNames,
3792 winhttp_request_Invoke,
3793 winhttp_request_SetProxy,
3794 winhttp_request_SetCredentials,
3795 winhttp_request_Open,
3796 winhttp_request_SetRequestHeader,
3797 winhttp_request_GetResponseHeader,
3798 winhttp_request_GetAllResponseHeaders,
3799 winhttp_request_Send,
3800 winhttp_request_get_Status,
3801 winhttp_request_get_StatusText,
3802 winhttp_request_get_ResponseText,
3803 winhttp_request_get_ResponseBody,
3804 winhttp_request_get_ResponseStream,
3805 winhttp_request_get_Option,
3806 winhttp_request_put_Option,
3807 winhttp_request_WaitForResponse,
3808 winhttp_request_Abort,
3809 winhttp_request_SetTimeouts,
3810 winhttp_request_SetClientCertificate,
3811 winhttp_request_SetAutoLogonPolicy
3812 };
3813
3814 HRESULT WinHttpRequest_create( void **obj )
3815 {
3816 struct winhttp_request *request;
3817
3818 TRACE("%p\n", obj);
3819
3820 if (!(request = heap_alloc( sizeof(*request) ))) return E_OUTOFMEMORY;
3821 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
3822 request->refs = 1;
3823 request->state = REQUEST_STATE_UNINITIALIZED;
3824 request->proxy.lpszProxy = NULL;
3825 request->proxy.lpszProxyBypass = NULL;
3826 InitializeCriticalSection( &request->cs );
3827 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
3828
3829 *obj = &request->IWinHttpRequest_iface;
3830 TRACE("returning iface %p\n", *obj);
3831 return S_OK;
3832 }