[rshell]
[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 <winuser.h>
29 #include <httprequest.h>
30
31 #include "inet_ntop.c"
32
33 static const WCHAR attr_accept[] = {'A','c','c','e','p','t',0};
34 static const WCHAR attr_accept_charset[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
35 static const WCHAR attr_accept_encoding[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
36 static const WCHAR attr_accept_language[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
37 static const WCHAR attr_accept_ranges[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
38 static const WCHAR attr_age[] = {'A','g','e',0};
39 static const WCHAR attr_allow[] = {'A','l','l','o','w',0};
40 static const WCHAR attr_authorization[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
41 static const WCHAR attr_cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
42 static const WCHAR attr_connection[] = {'C','o','n','n','e','c','t','i','o','n',0};
43 static const WCHAR attr_content_base[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
44 static const WCHAR attr_content_encoding[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
45 static const WCHAR attr_content_id[] = {'C','o','n','t','e','n','t','-','I','D',0};
46 static const WCHAR attr_content_language[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
47 static const WCHAR attr_content_length[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
48 static const WCHAR attr_content_location[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
49 static const WCHAR attr_content_md5[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
50 static const WCHAR attr_content_range[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
51 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};
52 static const WCHAR attr_content_type[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
53 static const WCHAR attr_cookie[] = {'C','o','o','k','i','e',0};
54 static const WCHAR attr_date[] = {'D','a','t','e',0};
55 static const WCHAR attr_from[] = {'F','r','o','m',0};
56 static const WCHAR attr_etag[] = {'E','T','a','g',0};
57 static const WCHAR attr_expect[] = {'E','x','p','e','c','t',0};
58 static const WCHAR attr_expires[] = {'E','x','p','i','r','e','s',0};
59 static const WCHAR attr_host[] = {'H','o','s','t',0};
60 static const WCHAR attr_if_match[] = {'I','f','-','M','a','t','c','h',0};
61 static const WCHAR attr_if_modified_since[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
62 static const WCHAR attr_if_none_match[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
63 static const WCHAR attr_if_range[] = {'I','f','-','R','a','n','g','e',0};
64 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};
65 static const WCHAR attr_last_modified[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
66 static const WCHAR attr_location[] = {'L','o','c','a','t','i','o','n',0};
67 static const WCHAR attr_max_forwards[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
68 static const WCHAR attr_mime_version[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
69 static const WCHAR attr_pragma[] = {'P','r','a','g','m','a',0};
70 static const WCHAR attr_proxy_authenticate[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
71 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};
72 static const WCHAR attr_proxy_connection[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
73 static const WCHAR attr_public[] = {'P','u','b','l','i','c',0};
74 static const WCHAR attr_range[] = {'R','a','n','g','e',0};
75 static const WCHAR attr_referer[] = {'R','e','f','e','r','e','r',0};
76 static const WCHAR attr_retry_after[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
77 static const WCHAR attr_server[] = {'S','e','r','v','e','r',0};
78 static const WCHAR attr_set_cookie[] = {'S','e','t','-','C','o','o','k','i','e',0};
79 static const WCHAR attr_status[] = {'S','t','a','t','u','s',0};
80 static const WCHAR attr_transfer_encoding[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
81 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};
82 static const WCHAR attr_upgrade[] = {'U','p','g','r','a','d','e',0};
83 static const WCHAR attr_uri[] = {'U','R','I',0};
84 static const WCHAR attr_user_agent[] = {'U','s','e','r','-','A','g','e','n','t',0};
85 static const WCHAR attr_vary[] = {'V','a','r','y',0};
86 static const WCHAR attr_via[] = {'V','i','a',0};
87 static const WCHAR attr_warning[] = {'W','a','r','n','i','n','g',0};
88 static const WCHAR attr_www_authenticate[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
89
90 static const WCHAR *attribute_table[] =
91 {
92 attr_mime_version, /* WINHTTP_QUERY_MIME_VERSION = 0 */
93 attr_content_type, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
94 attr_content_transfer_encoding, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
95 attr_content_id, /* WINHTTP_QUERY_CONTENT_ID = 3 */
96 NULL, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
97 attr_content_length, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
98 attr_content_language, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
99 attr_allow, /* WINHTTP_QUERY_ALLOW = 7 */
100 attr_public, /* WINHTTP_QUERY_PUBLIC = 8 */
101 attr_date, /* WINHTTP_QUERY_DATE = 9 */
102 attr_expires, /* WINHTTP_QUERY_EXPIRES = 10 */
103 attr_last_modified, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
104 NULL, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
105 attr_uri, /* WINHTTP_QUERY_URI = 13 */
106 attr_from, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
107 NULL, /* WINHTTP_QUERY_COST = 15 */
108 NULL, /* WINHTTP_QUERY_LINK = 16 */
109 attr_pragma, /* WINHTTP_QUERY_PRAGMA = 17 */
110 NULL, /* WINHTTP_QUERY_VERSION = 18 */
111 attr_status, /* WINHTTP_QUERY_STATUS_CODE = 19 */
112 NULL, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
113 NULL, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
114 NULL, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
115 attr_connection, /* WINHTTP_QUERY_CONNECTION = 23 */
116 attr_accept, /* WINHTTP_QUERY_ACCEPT = 24 */
117 attr_accept_charset, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
118 attr_accept_encoding, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
119 attr_accept_language, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
120 attr_authorization, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
121 attr_content_encoding, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
122 NULL, /* WINHTTP_QUERY_FORWARDED = 30 */
123 NULL, /* WINHTTP_QUERY_FROM = 31 */
124 attr_if_modified_since, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
125 attr_location, /* WINHTTP_QUERY_LOCATION = 33 */
126 NULL, /* WINHTTP_QUERY_ORIG_URI = 34 */
127 attr_referer, /* WINHTTP_QUERY_REFERER = 35 */
128 attr_retry_after, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
129 attr_server, /* WINHTTP_QUERY_SERVER = 37 */
130 NULL, /* WINHTTP_TITLE = 38 */
131 attr_user_agent, /* WINHTTP_QUERY_USER_AGENT = 39 */
132 attr_www_authenticate, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
133 attr_proxy_authenticate, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
134 attr_accept_ranges, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
135 attr_set_cookie, /* WINHTTP_QUERY_SET_COOKIE = 43 */
136 attr_cookie, /* WINHTTP_QUERY_COOKIE = 44 */
137 NULL, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
138 NULL, /* WINHTTP_QUERY_REFRESH = 46 */
139 NULL, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
140 attr_age, /* WINHTTP_QUERY_AGE = 48 */
141 attr_cache_control, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
142 attr_content_base, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
143 attr_content_location, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
144 attr_content_md5, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
145 attr_content_range, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
146 attr_etag, /* WINHTTP_QUERY_ETAG = 54 */
147 attr_host, /* WINHTTP_QUERY_HOST = 55 */
148 attr_if_match, /* WINHTTP_QUERY_IF_MATCH = 56 */
149 attr_if_none_match, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
150 attr_if_range, /* WINHTTP_QUERY_IF_RANGE = 58 */
151 attr_if_unmodified_since, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
152 attr_max_forwards, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
153 attr_proxy_authorization, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
154 attr_range, /* WINHTTP_QUERY_RANGE = 62 */
155 attr_transfer_encoding, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
156 attr_upgrade, /* WINHTTP_QUERY_UPGRADE = 64 */
157 attr_vary, /* WINHTTP_QUERY_VARY = 65 */
158 attr_via, /* WINHTTP_QUERY_VIA = 66 */
159 attr_warning, /* WINHTTP_QUERY_WARNING = 67 */
160 attr_expect, /* WINHTTP_QUERY_EXPECT = 68 */
161 attr_proxy_connection, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
162 attr_unless_modified_since, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
163 NULL, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
164 NULL, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
165 NULL, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
166 NULL /* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
167 };
168
169 static DWORD CALLBACK task_thread( LPVOID param )
170 {
171 task_header_t *task = param;
172
173 task->proc( task );
174
175 release_object( &task->request->hdr );
176 heap_free( task );
177 return ERROR_SUCCESS;
178 }
179
180 static BOOL queue_task( task_header_t *task )
181 {
182 return QueueUserWorkItem( task_thread, task, WT_EXECUTELONGFUNCTION );
183 }
184
185 static void free_header( header_t *header )
186 {
187 heap_free( header->field );
188 heap_free( header->value );
189 heap_free( header );
190 }
191
192 static BOOL valid_token_char( WCHAR c )
193 {
194 if (c < 32 || c == 127) return FALSE;
195 switch (c)
196 {
197 case '(': case ')':
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 '\t':
207 return FALSE;
208 default:
209 return TRUE;
210 }
211 }
212
213 static header_t *parse_header( LPCWSTR string )
214 {
215 const WCHAR *p, *q;
216 header_t *header;
217 int len;
218
219 p = string;
220 if (!(q = strchrW( p, ':' )))
221 {
222 WARN("no ':' in line %s\n", debugstr_w(string));
223 return NULL;
224 }
225 if (q == string)
226 {
227 WARN("empty field name in line %s\n", debugstr_w(string));
228 return NULL;
229 }
230 while (*p != ':')
231 {
232 if (!valid_token_char( *p ))
233 {
234 WARN("invalid character in field name %s\n", debugstr_w(string));
235 return NULL;
236 }
237 p++;
238 }
239 len = q - string;
240 if (!(header = heap_alloc_zero( sizeof(header_t) ))) return NULL;
241 if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
242 {
243 heap_free( header );
244 return NULL;
245 }
246 memcpy( header->field, string, len * sizeof(WCHAR) );
247 header->field[len] = 0;
248
249 q++; /* skip past colon */
250 while (*q == ' ') q++;
251 if (!*q)
252 {
253 WARN("no value in line %s\n", debugstr_w(string));
254 return header;
255 }
256 len = strlenW( q );
257 if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
258 {
259 free_header( header );
260 return NULL;
261 }
262 memcpy( header->value, q, len * sizeof(WCHAR) );
263 header->value[len] = 0;
264
265 return header;
266 }
267
268 static int get_header_index( request_t *request, LPCWSTR field, int requested_index, BOOL request_only )
269 {
270 int index;
271
272 TRACE("%s\n", debugstr_w(field));
273
274 for (index = 0; index < request->num_headers; index++)
275 {
276 if (strcmpiW( request->headers[index].field, field )) continue;
277 if (request_only && !request->headers[index].is_request) continue;
278 if (!request_only && request->headers[index].is_request) continue;
279
280 if (!requested_index) break;
281 requested_index--;
282 }
283 if (index >= request->num_headers) index = -1;
284 TRACE("returning %d\n", index);
285 return index;
286 }
287
288 static BOOL insert_header( request_t *request, header_t *header )
289 {
290 DWORD count;
291 header_t *hdrs;
292
293 count = request->num_headers + 1;
294 if (count > 1)
295 hdrs = heap_realloc_zero( request->headers, sizeof(header_t) * count );
296 else
297 hdrs = heap_alloc_zero( sizeof(header_t) * count );
298
299 if (hdrs)
300 {
301 request->headers = hdrs;
302 request->headers[count - 1].field = strdupW( header->field );
303 request->headers[count - 1].value = strdupW( header->value );
304 request->headers[count - 1].is_request = header->is_request;
305 request->num_headers++;
306 return TRUE;
307 }
308 return FALSE;
309 }
310
311 static BOOL delete_header( request_t *request, DWORD index )
312 {
313 if (!request->num_headers) return FALSE;
314 if (index >= request->num_headers) return FALSE;
315 request->num_headers--;
316
317 heap_free( request->headers[index].field );
318 heap_free( request->headers[index].value );
319
320 memmove( &request->headers[index], &request->headers[index + 1], (request->num_headers - index) * sizeof(header_t) );
321 memset( &request->headers[request->num_headers], 0, sizeof(header_t) );
322 return TRUE;
323 }
324
325 static BOOL process_header( request_t *request, LPCWSTR field, LPCWSTR value, DWORD flags, BOOL request_only )
326 {
327 int index;
328 header_t *header;
329
330 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
331
332 /* replace wins out over add */
333 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE) flags &= ~WINHTTP_ADDREQ_FLAG_ADD;
334
335 if (flags & WINHTTP_ADDREQ_FLAG_ADD) index = -1;
336 else
337 index = get_header_index( request, field, 0, request_only );
338
339 if (index >= 0)
340 {
341 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
342 header = &request->headers[index];
343 }
344 else if (value)
345 {
346 header_t hdr;
347
348 hdr.field = (LPWSTR)field;
349 hdr.value = (LPWSTR)value;
350 hdr.is_request = request_only;
351
352 return insert_header( request, &hdr );
353 }
354 /* no value to delete */
355 else return TRUE;
356
357 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
358 {
359 delete_header( request, index );
360 if (value)
361 {
362 header_t hdr;
363
364 hdr.field = (LPWSTR)field;
365 hdr.value = (LPWSTR)value;
366 hdr.is_request = request_only;
367
368 return insert_header( request, &hdr );
369 }
370 return TRUE;
371 }
372 else if (flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON))
373 {
374 WCHAR sep, *tmp;
375 int len, orig_len, value_len;
376
377 orig_len = strlenW( header->value );
378 value_len = strlenW( value );
379
380 if (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) sep = ',';
381 else sep = ';';
382
383 len = orig_len + value_len + 2;
384 if ((tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) )))
385 {
386 header->value = tmp;
387
388 header->value[orig_len] = sep;
389 orig_len++;
390 header->value[orig_len] = ' ';
391 orig_len++;
392
393 memcpy( &header->value[orig_len], value, value_len * sizeof(WCHAR) );
394 header->value[len] = 0;
395 return TRUE;
396 }
397 }
398 return TRUE;
399 }
400
401 BOOL add_request_headers( request_t *request, LPCWSTR headers, DWORD len, DWORD flags )
402 {
403 BOOL ret = FALSE;
404 WCHAR *buffer, *p, *q;
405 header_t *header;
406
407 if (len == ~0u) len = strlenW( headers );
408 if (!len) return TRUE;
409 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
410 strcpyW( buffer, headers );
411
412 p = buffer;
413 do
414 {
415 q = p;
416 while (*q)
417 {
418 if (q[0] == '\n' && q[1] == '\r')
419 {
420 q[0] = '\r';
421 q[1] = '\n';
422 }
423 if (q[0] == '\r' && q[1] == '\n') break;
424 q++;
425 }
426 if (!*p) break;
427 if (*q == '\r')
428 {
429 *q = 0;
430 q += 2; /* jump over \r\n */
431 }
432 if ((header = parse_header( p )))
433 {
434 ret = process_header( request, header->field, header->value, flags, TRUE );
435 free_header( header );
436 }
437 p = q;
438 } while (ret);
439
440 heap_free( buffer );
441 return ret;
442 }
443
444 /***********************************************************************
445 * WinHttpAddRequestHeaders (winhttp.@)
446 */
447 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
448 {
449 BOOL ret;
450 request_t *request;
451
452 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest, debugstr_w(headers), len, flags);
453
454 if (!headers)
455 {
456 set_last_error( ERROR_INVALID_PARAMETER );
457 return FALSE;
458 }
459 if (!(request = (request_t *)grab_object( hrequest )))
460 {
461 set_last_error( ERROR_INVALID_HANDLE );
462 return FALSE;
463 }
464 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
465 {
466 release_object( &request->hdr );
467 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
468 return FALSE;
469 }
470
471 ret = add_request_headers( request, headers, len, flags );
472
473 release_object( &request->hdr );
474 return ret;
475 }
476
477 static WCHAR *build_request_path( request_t *request )
478 {
479 WCHAR *ret;
480
481 if (strcmpiW( request->connect->hostname, request->connect->servername ))
482 {
483 static const WCHAR http[] = { 'h','t','t','p',0 };
484 static const WCHAR https[] = { 'h','t','t','p','s',0 };
485 static const WCHAR fmt[] = { '%','s',':','/','/','%','s',0 };
486 LPCWSTR scheme = request->netconn.secure ? https : http;
487 int len;
488
489 len = strlenW( scheme ) + strlenW( request->connect->hostname );
490 /* 3 characters for '://', 1 for NUL. */
491 len += 4;
492 if (request->connect->hostport)
493 {
494 /* 1 for ':' between host and port, up to 5 for port */
495 len += 6;
496 }
497 if (request->path)
498 len += strlenW( request->path );
499 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
500 {
501 sprintfW( ret, fmt, scheme, request->connect->hostname );
502 if (request->connect->hostport)
503 {
504 static const WCHAR colonFmt[] = { ':','%','u',0 };
505
506 sprintfW( ret + strlenW( ret ), colonFmt,
507 request->connect->hostport );
508 }
509 if (request->path)
510 strcatW( ret, request->path );
511 }
512 }
513 else
514 ret = request->path;
515 return ret;
516 }
517
518 static WCHAR *build_request_string( request_t *request )
519 {
520 static const WCHAR space[] = {' ',0};
521 static const WCHAR crlf[] = {'\r','\n',0};
522 static const WCHAR colon[] = {':',' ',0};
523 static const WCHAR twocrlf[] = {'\r','\n','\r','\n',0};
524
525 WCHAR *path, *ret;
526 const WCHAR **headers, **p;
527 unsigned int len, i = 0, j;
528
529 /* allocate space for an array of all the string pointers to be added */
530 len = request->num_headers * 4 + 7;
531 if (!(headers = heap_alloc( len * sizeof(LPCWSTR) ))) return NULL;
532
533 path = build_request_path( request );
534 headers[i++] = request->verb;
535 headers[i++] = space;
536 headers[i++] = path;
537 headers[i++] = space;
538 headers[i++] = request->version;
539
540 for (j = 0; j < request->num_headers; j++)
541 {
542 if (request->headers[j].is_request)
543 {
544 headers[i++] = crlf;
545 headers[i++] = request->headers[j].field;
546 headers[i++] = colon;
547 headers[i++] = request->headers[j].value;
548
549 TRACE("adding header %s (%s)\n", debugstr_w(request->headers[j].field),
550 debugstr_w(request->headers[j].value));
551 }
552 }
553 headers[i++] = twocrlf;
554 headers[i] = NULL;
555
556 len = 0;
557 for (p = headers; *p; p++) len += strlenW( *p );
558 len++;
559
560 if (!(ret = heap_alloc( len * sizeof(WCHAR) )))
561 goto out;
562 *ret = 0;
563 for (p = headers; *p; p++) strcatW( ret, *p );
564
565 out:
566 if (path != request->path)
567 heap_free( path );
568 heap_free( headers );
569 return ret;
570 }
571
572 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
573
574 static BOOL query_headers( request_t *request, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
575 {
576 header_t *header = NULL;
577 BOOL request_only, ret = FALSE;
578 int requested_index, header_index = -1;
579 DWORD attr, len;
580
581 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
582 requested_index = index ? *index : 0;
583
584 attr = level & ~QUERY_MODIFIER_MASK;
585 switch (attr)
586 {
587 case WINHTTP_QUERY_CUSTOM:
588 {
589 header_index = get_header_index( request, name, requested_index, request_only );
590 break;
591 }
592 case WINHTTP_QUERY_RAW_HEADERS:
593 {
594 WCHAR *headers, *p, *q;
595
596 if (request_only)
597 headers = build_request_string( request );
598 else
599 headers = request->raw_headers;
600
601 if (!(p = headers)) return FALSE;
602 for (len = 0; *p; p++) if (*p != '\r') len++;
603
604 if (!buffer || (len + 1) * sizeof(WCHAR) > *buflen)
605 {
606 len++;
607 set_last_error( ERROR_INSUFFICIENT_BUFFER );
608 }
609 else
610 {
611 for (p = headers, q = buffer; *p; p++, q++)
612 {
613 if (*p != '\r') *q = *p;
614 else
615 {
616 *q = 0;
617 p++; /* skip '\n' */
618 }
619 }
620 *q = 0;
621 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
622 ret = TRUE;
623 }
624 *buflen = len * sizeof(WCHAR);
625 if (request_only) heap_free( headers );
626 return ret;
627 }
628 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
629 {
630 WCHAR *headers;
631
632 if (request_only)
633 headers = build_request_string( request );
634 else
635 headers = request->raw_headers;
636
637 if (!headers) return FALSE;
638 len = strlenW( headers ) * sizeof(WCHAR);
639 if (!buffer || len + sizeof(WCHAR) > *buflen)
640 {
641 len += sizeof(WCHAR);
642 set_last_error( ERROR_INSUFFICIENT_BUFFER );
643 }
644 else
645 {
646 memcpy( buffer, headers, len + sizeof(WCHAR) );
647 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
648 ret = TRUE;
649 }
650 *buflen = len;
651 if (request_only) heap_free( headers );
652 return ret;
653 }
654 case WINHTTP_QUERY_VERSION:
655 len = strlenW( request->version ) * sizeof(WCHAR);
656 if (!buffer || len + sizeof(WCHAR) > *buflen)
657 {
658 len += sizeof(WCHAR);
659 set_last_error( ERROR_INSUFFICIENT_BUFFER );
660 }
661 else
662 {
663 strcpyW( buffer, request->version );
664 TRACE("returning string: %s\n", debugstr_w(buffer));
665 ret = TRUE;
666 }
667 *buflen = len;
668 return ret;
669
670 case WINHTTP_QUERY_STATUS_TEXT:
671 len = strlenW( request->status_text ) * sizeof(WCHAR);
672 if (!buffer || len + sizeof(WCHAR) > *buflen)
673 {
674 len += sizeof(WCHAR);
675 set_last_error( ERROR_INSUFFICIENT_BUFFER );
676 }
677 else
678 {
679 strcpyW( buffer, request->status_text );
680 TRACE("returning string: %s\n", debugstr_w(buffer));
681 ret = TRUE;
682 }
683 *buflen = len;
684 return ret;
685
686 default:
687 if (attr >= sizeof(attribute_table)/sizeof(attribute_table[0]) || !attribute_table[attr])
688 {
689 FIXME("attribute %u not implemented\n", attr);
690 return FALSE;
691 }
692 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
693 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
694 break;
695 }
696
697 if (header_index >= 0)
698 {
699 header = &request->headers[header_index];
700 }
701 if (!header || (request_only && !header->is_request))
702 {
703 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
704 return FALSE;
705 }
706 if (index) *index += 1;
707 if (level & WINHTTP_QUERY_FLAG_NUMBER)
708 {
709 if (!buffer || sizeof(int) > *buflen)
710 {
711 set_last_error( ERROR_INSUFFICIENT_BUFFER );
712 }
713 else
714 {
715 int *number = buffer;
716 *number = atoiW( header->value );
717 TRACE("returning number: %d\n", *number);
718 ret = TRUE;
719 }
720 *buflen = sizeof(int);
721 }
722 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
723 {
724 SYSTEMTIME *st = buffer;
725 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
726 {
727 set_last_error( ERROR_INSUFFICIENT_BUFFER );
728 }
729 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
730 {
731 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
732 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
733 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
734 }
735 *buflen = sizeof(SYSTEMTIME);
736 }
737 else if (header->value)
738 {
739 len = strlenW( header->value ) * sizeof(WCHAR);
740 if (!buffer || len + sizeof(WCHAR) > *buflen)
741 {
742 len += sizeof(WCHAR);
743 set_last_error( ERROR_INSUFFICIENT_BUFFER );
744 }
745 else
746 {
747 strcpyW( buffer, header->value );
748 TRACE("returning string: %s\n", debugstr_w(buffer));
749 ret = TRUE;
750 }
751 *buflen = len;
752 }
753 return ret;
754 }
755
756 /***********************************************************************
757 * WinHttpQueryHeaders (winhttp.@)
758 */
759 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
760 {
761 BOOL ret;
762 request_t *request;
763
764 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
765
766 if (!(request = (request_t *)grab_object( hrequest )))
767 {
768 set_last_error( ERROR_INVALID_HANDLE );
769 return FALSE;
770 }
771 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
772 {
773 release_object( &request->hdr );
774 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
775 return FALSE;
776 }
777
778 ret = query_headers( request, level, name, buffer, buflen, index );
779
780 release_object( &request->hdr );
781 return ret;
782 }
783
784 static LPWSTR concatenate_string_list( LPCWSTR *list, int len )
785 {
786 LPCWSTR *t;
787 LPWSTR str;
788
789 for( t = list; *t ; t++ )
790 len += strlenW( *t );
791 len++;
792
793 str = heap_alloc( len * sizeof(WCHAR) );
794 if (!str) return NULL;
795 *str = 0;
796
797 for( t = list; *t ; t++ )
798 strcatW( str, *t );
799
800 return str;
801 }
802
803 static LPWSTR build_header_request_string( request_t *request, LPCWSTR verb,
804 LPCWSTR path, LPCWSTR version )
805 {
806 static const WCHAR crlf[] = {'\r','\n',0};
807 static const WCHAR space[] = { ' ',0 };
808 static const WCHAR colon[] = { ':',' ',0 };
809 static const WCHAR twocrlf[] = {'\r','\n','\r','\n', 0};
810 LPWSTR requestString;
811 DWORD len, n;
812 LPCWSTR *req;
813 UINT i;
814 LPWSTR p;
815
816 /* allocate space for an array of all the string pointers to be added */
817 len = (request->num_headers) * 4 + 10;
818 req = heap_alloc( len * sizeof(LPCWSTR) );
819 if (!req) return NULL;
820
821 /* add the verb, path and HTTP version string */
822 n = 0;
823 req[n++] = verb;
824 req[n++] = space;
825 req[n++] = path;
826 req[n++] = space;
827 req[n++] = version;
828
829 /* Append custom request headers */
830 for (i = 0; i < request->num_headers; i++)
831 {
832 if (request->headers[i].is_request)
833 {
834 req[n++] = crlf;
835 req[n++] = request->headers[i].field;
836 req[n++] = colon;
837 req[n++] = request->headers[i].value;
838
839 TRACE("Adding custom header %s (%s)\n",
840 debugstr_w(request->headers[i].field),
841 debugstr_w(request->headers[i].value));
842 }
843 }
844
845 if( n >= len )
846 ERR("oops. buffer overrun\n");
847
848 req[n] = NULL;
849 requestString = concatenate_string_list( req, 4 );
850 heap_free( req );
851 if (!requestString) return NULL;
852
853 /*
854 * Set (header) termination string for request
855 * Make sure there's exactly two new lines at the end of the request
856 */
857 p = &requestString[strlenW(requestString)-1];
858 while ( (*p == '\n') || (*p == '\r') )
859 p--;
860 strcpyW( p+1, twocrlf );
861
862 return requestString;
863 }
864
865 static BOOL read_reply( request_t *request );
866
867 static BOOL secure_proxy_connect( request_t *request )
868 {
869 static const WCHAR verbConnect[] = {'C','O','N','N','E','C','T',0};
870 static const WCHAR fmt[] = {'%','s',':','%','u',0};
871 BOOL ret = FALSE;
872 LPWSTR path;
873 connect_t *connect = request->connect;
874
875 path = heap_alloc( (strlenW( connect->hostname ) + 13) * sizeof(WCHAR) );
876 if (path)
877 {
878 LPWSTR requestString;
879
880 sprintfW( path, fmt, connect->hostname, connect->hostport );
881 requestString = build_header_request_string( request, verbConnect,
882 path, http1_1 );
883 heap_free( path );
884 if (requestString)
885 {
886 LPSTR req_ascii = strdupWA( requestString );
887
888 heap_free( requestString );
889 if (req_ascii)
890 {
891 int len = strlen( req_ascii ), bytes_sent;
892
893 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
894 heap_free( req_ascii );
895 if (ret)
896 ret = read_reply( request );
897 }
898 }
899 }
900 return ret;
901 }
902
903 #ifndef INET6_ADDRSTRLEN
904 #define INET6_ADDRSTRLEN 46
905 #endif
906
907 static WCHAR *addr_to_str( const struct sockaddr *addr )
908 {
909 char buf[INET6_ADDRSTRLEN];
910 const void *src;
911
912 switch (addr->sa_family)
913 {
914 case AF_INET:
915 src = &((struct sockaddr_in *)addr)->sin_addr;
916 break;
917 case AF_INET6:
918 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
919 break;
920 default:
921 WARN("unsupported address family %d\n", addr->sa_family);
922 return NULL;
923 }
924 if (!inet_ntop( addr->sa_family, src, buf, sizeof(buf) )) return NULL;
925 return strdupAW( buf );
926 }
927
928 static BOOL open_connection( request_t *request )
929 {
930 connect_t *connect;
931 WCHAR *addressW = NULL;
932 INTERNET_PORT port;
933 socklen_t slen;
934 struct sockaddr *saddr;
935 DWORD len;
936
937 if (netconn_connected( &request->netconn )) goto done;
938
939 connect = request->connect;
940 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
941 saddr = (struct sockaddr *)&connect->sockaddr;
942 slen = sizeof(struct sockaddr);
943
944 if (!connect->resolved)
945 {
946 len = strlenW( connect->servername ) + 1;
947 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, connect->servername, len );
948
949 if (!netconn_resolve( connect->servername, port, saddr, &slen, request->resolve_timeout )) return FALSE;
950 connect->resolved = TRUE;
951
952 if (!(addressW = addr_to_str( saddr ))) return FALSE;
953 len = strlenW( addressW ) + 1;
954 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
955 }
956 if (!addressW && !(addressW = addr_to_str( saddr ))) return FALSE;
957 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
958
959 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
960
961 if (!netconn_create( &request->netconn, saddr->sa_family, SOCK_STREAM, 0 ))
962 {
963 heap_free( addressW );
964 return FALSE;
965 }
966 netconn_set_timeout( &request->netconn, TRUE, request->send_timeout );
967 netconn_set_timeout( &request->netconn, FALSE, request->recv_timeout );
968 if (!netconn_connect( &request->netconn, saddr, slen, request->connect_timeout ))
969 {
970 netconn_close( &request->netconn );
971 heap_free( addressW );
972 return FALSE;
973 }
974 if (request->hdr.flags & WINHTTP_FLAG_SECURE)
975 {
976 if (connect->session->proxy_server &&
977 strcmpiW( connect->hostname, connect->servername ))
978 {
979 if (!secure_proxy_connect( request ))
980 {
981 heap_free( addressW );
982 return FALSE;
983 }
984 }
985 if (!netconn_secure_connect( &request->netconn, connect->servername ))
986 {
987 netconn_close( &request->netconn );
988 heap_free( addressW );
989 return FALSE;
990 }
991 }
992
993 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
994
995 done:
996 request->read_pos = request->read_size = 0;
997 request->read_chunked = FALSE;
998 heap_free( addressW );
999 return TRUE;
1000 }
1001
1002 void close_connection( request_t *request )
1003 {
1004 if (!netconn_connected( &request->netconn )) return;
1005
1006 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1007 netconn_close( &request->netconn );
1008 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1009 }
1010
1011 static BOOL add_host_header( request_t *request, DWORD modifier )
1012 {
1013 BOOL ret;
1014 DWORD len;
1015 WCHAR *host;
1016 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1017 connect_t *connect = request->connect;
1018 INTERNET_PORT port;
1019
1020 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1021
1022 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1023 {
1024 return process_header( request, attr_host, connect->hostname, modifier, TRUE );
1025 }
1026 len = strlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1027 if (!(host = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1028 sprintfW( host, fmt, connect->hostname, port );
1029 ret = process_header( request, attr_host, host, modifier, TRUE );
1030 heap_free( host );
1031 return ret;
1032 }
1033
1034 static void clear_response_headers( request_t *request )
1035 {
1036 unsigned int i;
1037
1038 for (i = 0; i < request->num_headers; i++)
1039 {
1040 if (!request->headers[i].field) continue;
1041 if (!request->headers[i].value) continue;
1042 if (request->headers[i].is_request) continue;
1043 delete_header( request, i );
1044 i--;
1045 }
1046 }
1047
1048 static BOOL send_request( request_t *request, LPCWSTR headers, DWORD headers_len, LPVOID optional,
1049 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
1050 {
1051 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
1052 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
1053 static const WCHAR length_fmt[] = {'%','l','d',0};
1054
1055 BOOL ret = FALSE;
1056 connect_t *connect = request->connect;
1057 session_t *session = connect->session;
1058 WCHAR *req = NULL;
1059 char *req_ascii;
1060 int bytes_sent;
1061 DWORD len, i, flags;
1062
1063 clear_response_headers( request );
1064
1065 flags = WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
1066 for (i = 0; i < request->num_accept_types; i++)
1067 {
1068 process_header( request, attr_accept, request->accept_types[i], flags, TRUE );
1069 }
1070 if (session->agent)
1071 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1072
1073 if (connect->hostname)
1074 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
1075
1076 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
1077 {
1078 WCHAR length[21]; /* decimal long int + null */
1079 sprintfW( length, length_fmt, total_len );
1080 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1081 }
1082 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
1083 {
1084 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1085 }
1086 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
1087 {
1088 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1089 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1090 }
1091 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
1092 {
1093 TRACE("failed to add request headers\n");
1094 return FALSE;
1095 }
1096 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
1097 {
1098 WARN("failed to add cookie headers\n");
1099 return FALSE;
1100 }
1101
1102 if (context) request->hdr.context = context;
1103
1104 if (!(ret = open_connection( request ))) goto end;
1105 if (!(req = build_request_string( request ))) goto end;
1106
1107 if (!(req_ascii = strdupWA( req ))) goto end;
1108 TRACE("full request: %s\n", debugstr_a(req_ascii));
1109 len = strlen(req_ascii);
1110
1111 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
1112
1113 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
1114 heap_free( req_ascii );
1115 if (!ret) goto end;
1116
1117 if (optional_len)
1118 {
1119 if (!netconn_send( &request->netconn, optional, optional_len, &bytes_sent )) goto end;
1120 request->optional = optional;
1121 request->optional_len = optional_len;
1122 len += optional_len;
1123 }
1124 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(DWORD) );
1125
1126 end:
1127 if (async)
1128 {
1129 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
1130 else
1131 {
1132 WINHTTP_ASYNC_RESULT result;
1133 result.dwResult = API_SEND_REQUEST;
1134 result.dwError = get_last_error();
1135 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
1136 }
1137 }
1138 heap_free( req );
1139 return ret;
1140 }
1141
1142 static void task_send_request( task_header_t *task )
1143 {
1144 send_request_t *s = (send_request_t *)task;
1145 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
1146 heap_free( s->headers );
1147 }
1148
1149 /***********************************************************************
1150 * WinHttpSendRequest (winhttp.@)
1151 */
1152 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
1153 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
1154 {
1155 BOOL ret;
1156 request_t *request;
1157
1158 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1159 hrequest, debugstr_w(headers), headers_len, optional_len, total_len, context);
1160
1161 if (!(request = (request_t *)grab_object( hrequest )))
1162 {
1163 set_last_error( ERROR_INVALID_HANDLE );
1164 return FALSE;
1165 }
1166 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1167 {
1168 release_object( &request->hdr );
1169 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1170 return FALSE;
1171 }
1172
1173 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
1174 {
1175 send_request_t *s;
1176
1177 if (!(s = heap_alloc( sizeof(send_request_t) ))) return FALSE;
1178 s->hdr.request = request;
1179 s->hdr.proc = task_send_request;
1180 s->headers = strdupW( headers );
1181 s->headers_len = headers_len;
1182 s->optional = optional;
1183 s->optional_len = optional_len;
1184 s->total_len = total_len;
1185 s->context = context;
1186
1187 addref_object( &request->hdr );
1188 ret = queue_task( (task_header_t *)s );
1189 }
1190 else
1191 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
1192
1193 release_object( &request->hdr );
1194 return ret;
1195 }
1196
1197 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1198
1199 static const WCHAR basicW[] = {'B','a','s','i','c',0};
1200 static const WCHAR ntlmW[] = {'N','T','L','M',0};
1201 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
1202 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
1203 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
1204
1205 static const struct
1206 {
1207 const WCHAR *str;
1208 unsigned int len;
1209 DWORD scheme;
1210 }
1211 auth_schemes[] =
1212 {
1213 { basicW, ARRAYSIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
1214 { ntlmW, ARRAYSIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
1215 { passportW, ARRAYSIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
1216 { digestW, ARRAYSIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
1217 { negotiateW, ARRAYSIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
1218 };
1219 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
1220
1221 static enum auth_scheme scheme_from_flag( DWORD flag )
1222 {
1223 int i;
1224
1225 for (i = 0; i < num_auth_schemes; i++) if (flag == auth_schemes[i].scheme) return i;
1226 return SCHEME_INVALID;
1227 }
1228
1229 static DWORD auth_scheme_from_header( WCHAR *header )
1230 {
1231 unsigned int i;
1232
1233 for (i = 0; i < num_auth_schemes; i++)
1234 {
1235 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
1236 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
1237 }
1238 return 0;
1239 }
1240
1241 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
1242 {
1243 DWORD index = 0;
1244 BOOL ret = FALSE;
1245
1246 for (;;)
1247 {
1248 WCHAR *buffer;
1249 DWORD size, scheme;
1250
1251 size = 0;
1252 query_headers( request, level, NULL, NULL, &size, &index );
1253 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) break;
1254
1255 index--;
1256 if (!(buffer = heap_alloc( size ))) return FALSE;
1257 if (!query_headers( request, level, NULL, buffer, &size, &index ))
1258 {
1259 heap_free( buffer );
1260 return FALSE;
1261 }
1262 scheme = auth_scheme_from_header( buffer );
1263 heap_free( buffer );
1264 if (!scheme) break;
1265
1266 if (first && index == 1)
1267 *first = *supported = scheme;
1268 else
1269 *supported |= scheme;
1270
1271 ret = TRUE;
1272 }
1273 return ret;
1274 }
1275
1276 /***********************************************************************
1277 * WinHttpQueryAuthSchemes (winhttp.@)
1278 */
1279 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
1280 {
1281 BOOL ret = FALSE;
1282 request_t *request;
1283
1284 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
1285
1286 if (!(request = (request_t *)grab_object( hrequest )))
1287 {
1288 set_last_error( ERROR_INVALID_HANDLE );
1289 return FALSE;
1290 }
1291 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1292 {
1293 release_object( &request->hdr );
1294 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1295 return FALSE;
1296 }
1297 if (!supported || !first || !target)
1298 {
1299 release_object( &request->hdr );
1300 set_last_error( ERROR_INVALID_PARAMETER );
1301 return FALSE;
1302
1303 }
1304
1305 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
1306 {
1307 *target = WINHTTP_AUTH_TARGET_SERVER;
1308 ret = TRUE;
1309 }
1310 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
1311 {
1312 *target = WINHTTP_AUTH_TARGET_PROXY;
1313 ret = TRUE;
1314 }
1315
1316 release_object( &request->hdr );
1317 return ret;
1318 }
1319
1320 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
1321 {
1322 UINT n = 0, x;
1323 static const char base64enc[] =
1324 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1325
1326 while (len > 0)
1327 {
1328 /* first 6 bits, all from bin[0] */
1329 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
1330 x = (bin[0] & 3) << 4;
1331
1332 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1333 if (len == 1)
1334 {
1335 base64[n++] = base64enc[x];
1336 base64[n++] = '=';
1337 base64[n++] = '=';
1338 break;
1339 }
1340 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
1341 x = (bin[1] & 0x0f) << 2;
1342
1343 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1344 if (len == 2)
1345 {
1346 base64[n++] = base64enc[x];
1347 base64[n++] = '=';
1348 break;
1349 }
1350 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1351
1352 /* last 6 bits, all from bin [2] */
1353 base64[n++] = base64enc[bin[2] & 0x3f];
1354 bin += 3;
1355 len -= 3;
1356 }
1357 base64[n] = 0;
1358 return n;
1359 }
1360
1361 static inline char decode_char( WCHAR c )
1362 {
1363 if (c >= 'A' && c <= 'Z') return c - 'A';
1364 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1365 if (c >= '0' && c <= '9') return c - '0' + 52;
1366 if (c == '+') return 62;
1367 if (c == '/') return 63;
1368 return 64;
1369 }
1370
1371 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1372 {
1373 unsigned int i = 0;
1374 char c0, c1, c2, c3;
1375 const WCHAR *p = base64;
1376
1377 while (len >= 4)
1378 {
1379 if ((c0 = decode_char( p[0] )) > 63) return 0;
1380 if ((c1 = decode_char( p[1] )) > 63) return 0;
1381 if ((c2 = decode_char( p[2] )) > 63) return 0;
1382 if ((c3 = decode_char( p[3] )) > 63) return 0;
1383
1384 if (buf)
1385 {
1386 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1387 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1388 buf[i + 2] = (c2 << 6) | c3;
1389 }
1390 len -= 4;
1391 i += 3;
1392 p += 4;
1393 }
1394 if (p[2] == '=')
1395 {
1396 if ((c0 = decode_char( p[0] )) > 63) return 0;
1397 if ((c1 = decode_char( p[1] )) > 63) return 0;
1398
1399 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1400 i++;
1401 }
1402 else if (p[3] == '=')
1403 {
1404 if ((c0 = decode_char( p[0] )) > 63) return 0;
1405 if ((c1 = decode_char( p[1] )) > 63) return 0;
1406 if ((c2 = decode_char( p[2] )) > 63) return 0;
1407
1408 if (buf)
1409 {
1410 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1411 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1412 }
1413 i += 2;
1414 }
1415 return i;
1416 }
1417
1418 static struct authinfo *alloc_authinfo(void)
1419 {
1420 struct authinfo *ret;
1421
1422 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1423
1424 SecInvalidateHandle( &ret->cred );
1425 SecInvalidateHandle( &ret->ctx );
1426 memset( &ret->exp, 0, sizeof(ret->exp) );
1427 ret->scheme = 0;
1428 ret->attr = 0;
1429 ret->max_token = 0;
1430 ret->data = NULL;
1431 ret->data_len = 0;
1432 ret->finished = FALSE;
1433 return ret;
1434 }
1435
1436 void destroy_authinfo( struct authinfo *authinfo )
1437 {
1438 if (!authinfo) return;
1439
1440 if (SecIsValidHandle( &authinfo->ctx ))
1441 DeleteSecurityContext( &authinfo->ctx );
1442 if (SecIsValidHandle( &authinfo->cred ))
1443 FreeCredentialsHandle( &authinfo->cred );
1444
1445 heap_free( authinfo->data );
1446 heap_free( authinfo );
1447 }
1448
1449 static BOOL get_authvalue( request_t *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1450 {
1451 DWORD size, index = 0;
1452 for (;;)
1453 {
1454 size = len;
1455 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1456 if (auth_scheme_from_header( buffer ) == scheme) break;
1457 }
1458 return TRUE;
1459 }
1460
1461 static BOOL do_authorization( request_t *request, DWORD target, DWORD scheme_flag )
1462 {
1463 struct authinfo *authinfo, **auth_ptr;
1464 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1465 const WCHAR *auth_target, *username, *password;
1466 WCHAR auth_value[2048], *auth_reply;
1467 DWORD len = sizeof(auth_value), len_scheme, flags;
1468 BOOL ret;
1469
1470 if (scheme == SCHEME_INVALID) return FALSE;
1471
1472 switch (target)
1473 {
1474 case WINHTTP_AUTH_TARGET_SERVER:
1475 if (!get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len ))
1476 return FALSE;
1477 auth_ptr = &request->authinfo;
1478 auth_target = attr_authorization;
1479 username = request->connect->username;
1480 password = request->connect->password;
1481 break;
1482
1483 case WINHTTP_AUTH_TARGET_PROXY:
1484 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1485 return FALSE;
1486 auth_ptr = &request->proxy_authinfo;
1487 auth_target = attr_proxy_authorization;
1488 username = request->connect->session->proxy_username;
1489 password = request->connect->session->proxy_password;
1490 break;
1491
1492 default:
1493 WARN("unknown target %x\n", target);
1494 return FALSE;
1495 }
1496 authinfo = *auth_ptr;
1497
1498 switch (scheme)
1499 {
1500 case SCHEME_BASIC:
1501 {
1502 int userlen, passlen;
1503
1504 if (!username || !password) return FALSE;
1505 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1506
1507 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1508 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1509
1510 authinfo->data_len = userlen + 1 + passlen;
1511 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1512
1513 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1514 authinfo->data[userlen] = ':';
1515 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1516
1517 authinfo->scheme = SCHEME_BASIC;
1518 authinfo->finished = TRUE;
1519 break;
1520 }
1521 case SCHEME_NTLM:
1522 case SCHEME_NEGOTIATE:
1523 {
1524 SECURITY_STATUS status;
1525 SecBufferDesc out_desc, in_desc;
1526 SecBuffer out, in;
1527 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1528 const WCHAR *p;
1529 BOOL first = FALSE;
1530
1531 if (!authinfo)
1532 {
1533 TimeStamp exp;
1534 SEC_WINNT_AUTH_IDENTITY_W id;
1535 WCHAR *domain, *user;
1536
1537 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1538
1539 first = TRUE;
1540 domain = (WCHAR *)username;
1541 user = strchrW( username, '\\' );
1542
1543 if (user) user++;
1544 else
1545 {
1546 user = (WCHAR *)username;
1547 domain = NULL;
1548 }
1549 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1550 id.User = user;
1551 id.UserLength = strlenW( user );
1552 id.Domain = domain;
1553 id.DomainLength = domain ? user - domain - 1 : 0;
1554 id.Password = (WCHAR *)password;
1555 id.PasswordLength = strlenW( password );
1556
1557 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1558 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1559 &authinfo->cred, &exp );
1560 if (status == SEC_E_OK)
1561 {
1562 PSecPkgInfoW info;
1563 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1564 if (status == SEC_E_OK)
1565 {
1566 authinfo->max_token = info->cbMaxToken;
1567 FreeContextBuffer( info );
1568 }
1569 }
1570 if (status != SEC_E_OK)
1571 {
1572 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1573 debugstr_w(auth_schemes[scheme].str), status);
1574 heap_free( authinfo );
1575 return FALSE;
1576 }
1577 authinfo->scheme = scheme;
1578 }
1579 else if (authinfo->finished) return FALSE;
1580
1581 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1582 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1583 {
1584 ERR("authentication scheme changed from %s to %s\n",
1585 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1586 destroy_authinfo( authinfo );
1587 *auth_ptr = NULL;
1588 return FALSE;
1589 }
1590 in.BufferType = SECBUFFER_TOKEN;
1591 in.cbBuffer = 0;
1592 in.pvBuffer = NULL;
1593
1594 in_desc.ulVersion = 0;
1595 in_desc.cBuffers = 1;
1596 in_desc.pBuffers = &in;
1597
1598 p = auth_value + auth_schemes[scheme].len;
1599 if (*p == ' ')
1600 {
1601 int len = strlenW( ++p );
1602 in.cbBuffer = decode_base64( p, len, NULL );
1603 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) return FALSE;
1604 decode_base64( p, len, in.pvBuffer );
1605 }
1606 out.BufferType = SECBUFFER_TOKEN;
1607 out.cbBuffer = authinfo->max_token;
1608 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1609 {
1610 heap_free( in.pvBuffer );
1611 return FALSE;
1612 }
1613 out_desc.ulVersion = 0;
1614 out_desc.cBuffers = 1;
1615 out_desc.pBuffers = &out;
1616
1617 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1618 first ? request->connect->servername : NULL, flags, 0,
1619 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1620 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1621 heap_free( in.pvBuffer );
1622 if (status == SEC_E_OK)
1623 {
1624 heap_free( authinfo->data );
1625 authinfo->data = out.pvBuffer;
1626 authinfo->data_len = out.cbBuffer;
1627 authinfo->finished = TRUE;
1628 TRACE("sending last auth packet\n");
1629 }
1630 else if (status == SEC_I_CONTINUE_NEEDED)
1631 {
1632 heap_free( authinfo->data );
1633 authinfo->data = out.pvBuffer;
1634 authinfo->data_len = out.cbBuffer;
1635 TRACE("sending next auth packet\n");
1636 }
1637 else
1638 {
1639 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1640 heap_free( out.pvBuffer );
1641 destroy_authinfo( authinfo );
1642 *auth_ptr = NULL;
1643 return FALSE;
1644 }
1645 break;
1646 }
1647 default:
1648 ERR("invalid scheme %u\n", scheme);
1649 return FALSE;
1650 }
1651 *auth_ptr = authinfo;
1652
1653 len_scheme = auth_schemes[authinfo->scheme].len;
1654 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1655 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1656
1657 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1658 auth_reply[len_scheme] = ' ';
1659 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1660
1661 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1662 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1663 heap_free( auth_reply );
1664 return ret;
1665 }
1666
1667 static BOOL set_credentials( request_t *request, DWORD target, DWORD scheme, const WCHAR *username,
1668 const WCHAR *password )
1669 {
1670 if ((scheme == WINHTTP_AUTH_SCHEME_BASIC || scheme == WINHTTP_AUTH_SCHEME_DIGEST) &&
1671 (!username || !password))
1672 {
1673 set_last_error( ERROR_INVALID_PARAMETER );
1674 return FALSE;
1675 }
1676 switch (target)
1677 {
1678 case WINHTTP_AUTH_TARGET_SERVER:
1679 {
1680 heap_free( request->connect->username );
1681 if (!username) request->connect->username = NULL;
1682 else if (!(request->connect->username = strdupW( username ))) return FALSE;
1683
1684 heap_free( request->connect->password );
1685 if (!password) request->connect->password = NULL;
1686 else if (!(request->connect->password = strdupW( password ))) return FALSE;
1687 break;
1688 }
1689 case WINHTTP_AUTH_TARGET_PROXY:
1690 {
1691 heap_free( request->connect->session->proxy_username );
1692 if (!username) request->connect->session->proxy_username = NULL;
1693 else if (!(request->connect->session->proxy_username = strdupW( username ))) return FALSE;
1694
1695 heap_free( request->connect->session->proxy_password );
1696 if (!password) request->connect->session->proxy_password = NULL;
1697 else if (!(request->connect->session->proxy_password = strdupW( password ))) return FALSE;
1698 break;
1699 }
1700 default:
1701 WARN("unknown target %u\n", target);
1702 return FALSE;
1703 }
1704 return TRUE;
1705 }
1706
1707 /***********************************************************************
1708 * WinHttpSetCredentials (winhttp.@)
1709 */
1710 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
1711 LPCWSTR password, LPVOID params )
1712 {
1713 BOOL ret;
1714 request_t *request;
1715
1716 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
1717
1718 if (!(request = (request_t *)grab_object( hrequest )))
1719 {
1720 set_last_error( ERROR_INVALID_HANDLE );
1721 return FALSE;
1722 }
1723 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1724 {
1725 release_object( &request->hdr );
1726 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1727 return FALSE;
1728 }
1729
1730 ret = set_credentials( request, target, scheme, username, password );
1731
1732 release_object( &request->hdr );
1733 return ret;
1734 }
1735
1736 static BOOL handle_authorization( request_t *request, DWORD status )
1737 {
1738 DWORD i, schemes, first, level, target;
1739
1740 switch (status)
1741 {
1742 case HTTP_STATUS_DENIED:
1743 target = WINHTTP_AUTH_TARGET_SERVER;
1744 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
1745 break;
1746
1747 case HTTP_STATUS_PROXY_AUTH_REQ:
1748 target = WINHTTP_AUTH_TARGET_PROXY;
1749 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
1750 break;
1751
1752 default:
1753 WARN("unhandled status %u\n", status);
1754 return FALSE;
1755 }
1756
1757 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
1758 if (do_authorization( request, target, first )) return TRUE;
1759
1760 schemes &= ~first;
1761 for (i = 0; i < num_auth_schemes; i++)
1762 {
1763 if (!(schemes & auth_schemes[i].scheme)) continue;
1764 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
1765 }
1766 return FALSE;
1767 }
1768
1769 /* set the request content length based on the headers */
1770 static DWORD set_content_length( request_t *request )
1771 {
1772 WCHAR encoding[20];
1773 DWORD buflen;
1774
1775 buflen = sizeof(request->content_length);
1776 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
1777 NULL, &request->content_length, &buflen, NULL ))
1778 request->content_length = ~0u;
1779
1780 buflen = sizeof(encoding);
1781 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
1782 !strcmpiW( encoding, chunkedW ))
1783 {
1784 request->content_length = ~0u;
1785 request->read_chunked = TRUE;
1786 }
1787 request->content_read = 0;
1788 return request->content_length;
1789 }
1790
1791 /* read some more data into the read buffer */
1792 static BOOL read_more_data( request_t *request, int maxlen )
1793 {
1794 int len;
1795
1796 if (request->read_size && request->read_pos)
1797 {
1798 /* move existing data to the start of the buffer */
1799 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1800 request->read_pos = 0;
1801 }
1802 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1803 if (!netconn_recv( &request->netconn, request->read_buf + request->read_size,
1804 maxlen - request->read_size, 0, &len )) return FALSE;
1805 request->read_size += len;
1806 return TRUE;
1807 }
1808
1809 /* remove some amount of data from the read buffer */
1810 static void remove_data( request_t *request, int count )
1811 {
1812 if (!(request->read_size -= count)) request->read_pos = 0;
1813 else request->read_pos += count;
1814 }
1815
1816 static BOOL read_line( request_t *request, char *buffer, DWORD *len )
1817 {
1818 int count, bytes_read, pos = 0;
1819
1820 for (;;)
1821 {
1822 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1823 if (eol)
1824 {
1825 count = eol - (request->read_buf + request->read_pos);
1826 bytes_read = count + 1;
1827 }
1828 else count = bytes_read = request->read_size;
1829
1830 count = min( count, *len - pos );
1831 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
1832 pos += count;
1833 remove_data( request, bytes_read );
1834 if (eol) break;
1835
1836 if (!read_more_data( request, -1 )) return FALSE;
1837 if (!request->read_size)
1838 {
1839 *len = 0;
1840 TRACE("returning empty string\n");
1841 return FALSE;
1842 }
1843 }
1844 if (pos < *len)
1845 {
1846 if (pos && buffer[pos - 1] == '\r') pos--;
1847 *len = pos + 1;
1848 }
1849 buffer[*len - 1] = 0;
1850 TRACE("returning %s\n", debugstr_a(buffer));
1851 return TRUE;
1852 }
1853
1854 /* discard data contents until we reach end of line */
1855 static BOOL discard_eol( request_t *request )
1856 {
1857 do
1858 {
1859 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1860 if (eol)
1861 {
1862 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1863 break;
1864 }
1865 request->read_pos = request->read_size = 0; /* discard everything */
1866 if (!read_more_data( request, -1 )) return FALSE;
1867 } while (request->read_size);
1868 return TRUE;
1869 }
1870
1871 /* read the size of the next chunk */
1872 static BOOL start_next_chunk( request_t *request )
1873 {
1874 DWORD chunk_size = 0;
1875
1876 if (!request->content_length) return TRUE;
1877 if (request->content_length == request->content_read)
1878 {
1879 /* read terminator for the previous chunk */
1880 if (!discard_eol( request )) return FALSE;
1881 request->content_length = ~0u;
1882 request->content_read = 0;
1883 }
1884 for (;;)
1885 {
1886 while (request->read_size)
1887 {
1888 char ch = request->read_buf[request->read_pos];
1889 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1890 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1891 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1892 else if (ch == ';' || ch == '\r' || ch == '\n')
1893 {
1894 TRACE("reading %u byte chunk\n", chunk_size);
1895 request->content_length = chunk_size;
1896 request->content_read = 0;
1897 if (!discard_eol( request )) return FALSE;
1898 return TRUE;
1899 }
1900 remove_data( request, 1 );
1901 }
1902 if (!read_more_data( request, -1 )) return FALSE;
1903 if (!request->read_size)
1904 {
1905 request->content_length = request->content_read = 0;
1906 return TRUE;
1907 }
1908 }
1909 }
1910
1911 /* return the size of data available to be read immediately */
1912 static DWORD get_available_data( request_t *request )
1913 {
1914 if (request->read_chunked &&
1915 (request->content_length == ~0u || request->content_length == request->content_read))
1916 return 0;
1917 return min( request->read_size, request->content_length - request->content_read );
1918 }
1919
1920 /* check if we have reached the end of the data to read */
1921 static BOOL end_of_read_data( request_t *request )
1922 {
1923 if (request->read_chunked) return (request->content_length == 0);
1924 if (request->content_length == ~0u) return FALSE;
1925 return (request->content_length == request->content_read);
1926 }
1927
1928 static BOOL refill_buffer( request_t *request )
1929 {
1930 int len = sizeof(request->read_buf);
1931
1932 if (request->read_chunked &&
1933 (request->content_length == ~0u || request->content_length == request->content_read))
1934 {
1935 if (!start_next_chunk( request )) return FALSE;
1936 }
1937 if (request->content_length != ~0u) len = min( len, request->content_length - request->content_read );
1938 if (len <= request->read_size) return TRUE;
1939 if (!read_more_data( request, len )) return FALSE;
1940 if (!request->read_size) request->content_length = request->content_read = 0;
1941 return TRUE;
1942 }
1943
1944 #define MAX_REPLY_LEN 1460
1945 #define INITIAL_HEADER_BUFFER_LEN 512
1946
1947 static BOOL read_reply( request_t *request )
1948 {
1949 static const WCHAR crlf[] = {'\r','\n',0};
1950
1951 char buffer[MAX_REPLY_LEN];
1952 DWORD buflen, len, offset, received_len, crlf_len = 2; /* strlenW(crlf) */
1953 char *status_code, *status_text;
1954 WCHAR *versionW, *status_textW, *raw_headers;
1955 WCHAR status_codeW[4]; /* sizeof("nnn") */
1956
1957 if (!netconn_connected( &request->netconn )) return FALSE;
1958
1959 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1960
1961 received_len = 0;
1962 do
1963 {
1964 buflen = MAX_REPLY_LEN;
1965 if (!read_line( request, buffer, &buflen )) return FALSE;
1966 received_len += buflen;
1967
1968 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
1969 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
1970 status_code++;
1971 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
1972 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
1973 status_text++;
1974
1975 TRACE("version [%s] status code [%s] status text [%s]\n",
1976 debugstr_an(buffer, status_code - buffer - 1),
1977 debugstr_an(status_code, len),
1978 debugstr_a(status_text));
1979
1980 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
1981
1982 /* we rely on the fact that the protocol is ascii */
1983 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
1984 status_codeW[len] = 0;
1985 if (!(process_header( request, attr_status, status_codeW, WINHTTP_ADDREQ_FLAG_REPLACE, FALSE ))) return FALSE;
1986
1987 len = status_code - buffer;
1988 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1989 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
1990 versionW[len - 1] = 0;
1991
1992 heap_free( request->version );
1993 request->version = versionW;
1994
1995 len = buflen - (status_text - buffer);
1996 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1997 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
1998
1999 heap_free( request->status_text );
2000 request->status_text = status_textW;
2001
2002 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2003 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2004 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2005 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2006
2007 heap_free( request->raw_headers );
2008 request->raw_headers = raw_headers;
2009
2010 offset = buflen + crlf_len - 1;
2011 for (;;)
2012 {
2013 header_t *header;
2014
2015 buflen = MAX_REPLY_LEN;
2016 if (!read_line( request, buffer, &buflen )) goto end;
2017 received_len += buflen;
2018 if (!*buffer) break;
2019
2020 while (len - offset < buflen + crlf_len)
2021 {
2022 WCHAR *tmp;
2023 len *= 2;
2024 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2025 request->raw_headers = raw_headers = tmp;
2026 }
2027 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2028
2029 if (!(header = parse_header( raw_headers + offset ))) break;
2030 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2031 {
2032 free_header( header );
2033 break;
2034 }
2035 free_header( header );
2036 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2037 offset += buflen + crlf_len - 1;
2038 }
2039
2040 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2041
2042 end:
2043 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &received_len, sizeof(DWORD) );
2044 return TRUE;
2045 }
2046
2047 static void finished_reading( request_t *request )
2048 {
2049 static const WCHAR closeW[] = {'c','l','o','s','e',0};
2050
2051 BOOL close = FALSE;
2052 WCHAR connection[20];
2053 DWORD size = sizeof(connection);
2054
2055 if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
2056 else if (query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
2057 query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
2058 {
2059 if (!strcmpiW( connection, closeW )) close = TRUE;
2060 }
2061 else if (!strcmpW( request->version, http1_0 )) close = TRUE;
2062 if (close) close_connection( request );
2063 }
2064
2065 static BOOL read_data( request_t *request, void *buffer, DWORD size, DWORD *read, BOOL async )
2066 {
2067 BOOL ret = TRUE;
2068 int len, bytes_read = 0;
2069
2070 if (request->read_chunked &&
2071 (request->content_length == ~0u || request->content_length == request->content_read))
2072 {
2073 if (!start_next_chunk( request )) goto done;
2074 }
2075 if (request->content_length != ~0u) size = min( size, request->content_length - request->content_read );
2076
2077 if (request->read_size)
2078 {
2079 bytes_read = min( request->read_size, size );
2080 memcpy( buffer, request->read_buf + request->read_pos, bytes_read );
2081 remove_data( request, bytes_read );
2082 }
2083 if (size > bytes_read && (!bytes_read || !async))
2084 {
2085 if ((ret = netconn_recv( &request->netconn, (char *)buffer + bytes_read, size - bytes_read,
2086 async ? 0 : MSG_WAITALL, &len )))
2087 bytes_read += len;
2088 }
2089
2090 done:
2091 request->content_read += bytes_read;
2092 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, request->content_read, request->content_length );
2093 if (async)
2094 {
2095 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
2096 else
2097 {
2098 WINHTTP_ASYNC_RESULT result;
2099 result.dwResult = API_READ_DATA;
2100 result.dwError = get_last_error();
2101 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2102 }
2103 }
2104 if (read) *read = bytes_read;
2105 if (!bytes_read && request->content_read == request->content_length) finished_reading( request );
2106 return ret;
2107 }
2108
2109 /* read any content returned by the server so that the connection can be reused */
2110 static void drain_content( request_t *request )
2111 {
2112 DWORD bytes_read;
2113 char buffer[2048];
2114
2115 if (request->content_length == ~0u)
2116 {
2117 finished_reading( request );
2118 return;
2119 }
2120 for (;;)
2121 {
2122 if (!read_data( request, buffer, sizeof(buffer), &bytes_read, FALSE ) || !bytes_read) return;
2123 }
2124 }
2125
2126 static void record_cookies( request_t *request )
2127 {
2128 unsigned int i;
2129
2130 for (i = 0; i < request->num_headers; i++)
2131 {
2132 header_t *set_cookie = &request->headers[i];
2133 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2134 {
2135 set_cookies( request, set_cookie->value );
2136 }
2137 }
2138 }
2139
2140 static WCHAR *get_redirect_url( request_t *request, DWORD *len )
2141 {
2142 DWORD size;
2143 WCHAR *ret;
2144
2145 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2146 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2147 if (!(ret = heap_alloc( size ))) return NULL;
2148 *len = size / sizeof(WCHAR);
2149 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2150 heap_free( ret );
2151 return NULL;
2152 }
2153
2154 static BOOL handle_redirect( request_t *request, DWORD status )
2155 {
2156 BOOL ret = FALSE;
2157 DWORD len, len_url;
2158 URL_COMPONENTS uc;
2159 connect_t *connect = request->connect;
2160 INTERNET_PORT port;
2161 WCHAR *hostname = NULL, *location;
2162 int index;
2163
2164 if (!(location = get_redirect_url( request, &len_url ))) return FALSE;
2165
2166 memset( &uc, 0, sizeof(uc) );
2167 uc.dwStructSize = sizeof(uc);
2168 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2169
2170 if (!WinHttpCrackUrl( location, len_url, 0, &uc )) /* assume relative redirect */
2171 {
2172 WCHAR *path, *p;
2173
2174 len = strlenW( location ) + 1;
2175 if (location[0] != '/') len++;
2176 if (!(p = path = heap_alloc( len * sizeof(WCHAR) ))) goto end;
2177
2178 if (location[0] != '/') *p++ = '/';
2179 strcpyW( p, location );
2180
2181 heap_free( request->path );
2182 request->path = path;
2183
2184 drain_content( request );
2185 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2186 }
2187 else
2188 {
2189 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2190 {
2191 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2192 TRACE("redirect from secure page to non-secure page\n");
2193 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2194 }
2195 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2196 {
2197 TRACE("redirect from non-secure page to secure page\n");
2198 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2199 }
2200
2201 drain_content( request );
2202 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2203
2204 len = uc.dwHostNameLength;
2205 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2206 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2207 hostname[len] = 0;
2208
2209 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2210 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2211 {
2212 heap_free( connect->hostname );
2213 connect->hostname = hostname;
2214 connect->hostport = port;
2215 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2216
2217 netconn_close( &request->netconn );
2218 if (!(ret = netconn_init( &request->netconn ))) goto end;
2219 request->read_pos = request->read_size = 0;
2220 request->read_chunked = FALSE;
2221 }
2222 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2223 if (!(ret = open_connection( request ))) goto end;
2224
2225 heap_free( request->path );
2226 request->path = NULL;
2227 if (uc.dwUrlPathLength)
2228 {
2229 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2230 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2231 strcpyW( request->path, uc.lpszUrlPath );
2232 }
2233 else request->path = strdupW( slashW );
2234 }
2235
2236 /* remove content-type/length headers */
2237 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2238 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2239
2240 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2241 {
2242 heap_free( request->verb );
2243 request->verb = strdupW( getW );
2244 request->optional = NULL;
2245 request->optional_len = 0;
2246 }
2247 ret = TRUE;
2248
2249 end:
2250 if (!ret) heap_free( hostname );
2251 heap_free( location );
2252 return ret;
2253 }
2254
2255 static BOOL receive_response( request_t *request, BOOL async )
2256 {
2257 BOOL ret;
2258 DWORD size, query, status;
2259
2260 for (;;)
2261 {
2262 if (!(ret = read_reply( request )))
2263 {
2264 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2265 break;
2266 }
2267 size = sizeof(DWORD);
2268 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2269 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2270
2271 set_content_length( request );
2272
2273 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2274
2275 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2276 {
2277 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2278 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2279
2280 if (!(ret = handle_redirect( request, status ))) break;
2281
2282 /* recurse synchronously */
2283 send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE );
2284 continue;
2285 }
2286 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2287 {
2288 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2289
2290 drain_content( request );
2291 if (!handle_authorization( request, status ))
2292 {
2293 ret = TRUE;
2294 break;
2295 }
2296 /* recurse synchronously */
2297 send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE );
2298 continue;
2299 }
2300 break;
2301 }
2302
2303 if (async)
2304 {
2305 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2306 else
2307 {
2308 WINHTTP_ASYNC_RESULT result;
2309 result.dwResult = API_RECEIVE_RESPONSE;
2310 result.dwError = get_last_error();
2311 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2312 }
2313 }
2314 return ret;
2315 }
2316
2317 static void task_receive_response( task_header_t *task )
2318 {
2319 receive_response_t *r = (receive_response_t *)task;
2320 receive_response( r->hdr.request, TRUE );
2321 }
2322
2323 /***********************************************************************
2324 * WinHttpReceiveResponse (winhttp.@)
2325 */
2326 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2327 {
2328 BOOL ret;
2329 request_t *request;
2330
2331 TRACE("%p, %p\n", hrequest, reserved);
2332
2333 if (!(request = (request_t *)grab_object( hrequest )))
2334 {
2335 set_last_error( ERROR_INVALID_HANDLE );
2336 return FALSE;
2337 }
2338 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2339 {
2340 release_object( &request->hdr );
2341 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2342 return FALSE;
2343 }
2344
2345 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2346 {
2347 receive_response_t *r;
2348
2349 if (!(r = heap_alloc( sizeof(receive_response_t) ))) return FALSE;
2350 r->hdr.request = request;
2351 r->hdr.proc = task_receive_response;
2352
2353 addref_object( &request->hdr );
2354 ret = queue_task( (task_header_t *)r );
2355 }
2356 else
2357 ret = receive_response( request, FALSE );
2358
2359 release_object( &request->hdr );
2360 return ret;
2361 }
2362
2363 static BOOL query_data_available( request_t *request, DWORD *available, BOOL async )
2364 {
2365 BOOL ret = TRUE;
2366 DWORD count;
2367
2368 if (!(count = get_available_data( request )))
2369 {
2370 if (end_of_read_data( request ))
2371 {
2372 if (available) *available = 0;
2373 return TRUE;
2374 }
2375 }
2376 refill_buffer( request );
2377 count = get_available_data( request );
2378
2379 if (count == sizeof(request->read_buf)) /* check if we have even more pending in the socket */
2380 {
2381 DWORD extra;
2382 if ((ret = netconn_query_data_available( &request->netconn, &extra )))
2383 {
2384 count = min( count + extra, request->content_length - request->content_read );
2385 }
2386 }
2387 if (async)
2388 {
2389 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2390 else
2391 {
2392 WINHTTP_ASYNC_RESULT result;
2393 result.dwResult = API_QUERY_DATA_AVAILABLE;
2394 result.dwError = get_last_error();
2395 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2396 }
2397 }
2398 if (ret)
2399 {
2400 TRACE("%u bytes available\n", count);
2401 if (available) *available = count;
2402 }
2403 return ret;
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(DWORD) );
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( IUnknown *unknown, void **obj )
3814 {
3815 struct winhttp_request *request;
3816
3817 TRACE("%p, %p\n", unknown, 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 }