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