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