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