Release 2.9.
[wine.git] / dlls / winhttp / request.c
blobdb6d12d0278e1c175a90c2fbcc82847414c050bf
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
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.
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.
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
22 #define COBJMACROS
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <assert.h>
28 #ifdef HAVE_ARPA_INET_H
29 # include <arpa/inet.h>
30 #endif
32 #include "windef.h"
33 #include "winbase.h"
34 #include "ole2.h"
35 #include "initguid.h"
36 #include "httprequest.h"
37 #include "httprequestid.h"
38 #include "winhttp.h"
40 #include "winhttp_private.h"
42 #include "wine/debug.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
46 static const WCHAR attr_accept[] = {'A','c','c','e','p','t',0};
47 static const WCHAR attr_accept_charset[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
48 static const WCHAR attr_accept_encoding[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
49 static const WCHAR attr_accept_language[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
50 static const WCHAR attr_accept_ranges[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
51 static const WCHAR attr_age[] = {'A','g','e',0};
52 static const WCHAR attr_allow[] = {'A','l','l','o','w',0};
53 static const WCHAR attr_authorization[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
54 static const WCHAR attr_cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
55 static const WCHAR attr_connection[] = {'C','o','n','n','e','c','t','i','o','n',0};
56 static const WCHAR attr_content_base[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
57 static const WCHAR attr_content_encoding[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
58 static const WCHAR attr_content_id[] = {'C','o','n','t','e','n','t','-','I','D',0};
59 static const WCHAR attr_content_language[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
60 static const WCHAR attr_content_length[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
61 static const WCHAR attr_content_location[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
62 static const WCHAR attr_content_md5[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
63 static const WCHAR attr_content_range[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
64 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};
65 static const WCHAR attr_content_type[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
66 static const WCHAR attr_cookie[] = {'C','o','o','k','i','e',0};
67 static const WCHAR attr_date[] = {'D','a','t','e',0};
68 static const WCHAR attr_from[] = {'F','r','o','m',0};
69 static const WCHAR attr_etag[] = {'E','T','a','g',0};
70 static const WCHAR attr_expect[] = {'E','x','p','e','c','t',0};
71 static const WCHAR attr_expires[] = {'E','x','p','i','r','e','s',0};
72 static const WCHAR attr_host[] = {'H','o','s','t',0};
73 static const WCHAR attr_if_match[] = {'I','f','-','M','a','t','c','h',0};
74 static const WCHAR attr_if_modified_since[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
75 static const WCHAR attr_if_none_match[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
76 static const WCHAR attr_if_range[] = {'I','f','-','R','a','n','g','e',0};
77 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};
78 static const WCHAR attr_last_modified[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
79 static const WCHAR attr_location[] = {'L','o','c','a','t','i','o','n',0};
80 static const WCHAR attr_max_forwards[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
81 static const WCHAR attr_mime_version[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
82 static const WCHAR attr_pragma[] = {'P','r','a','g','m','a',0};
83 static const WCHAR attr_proxy_authenticate[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
84 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};
85 static const WCHAR attr_proxy_connection[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
86 static const WCHAR attr_public[] = {'P','u','b','l','i','c',0};
87 static const WCHAR attr_range[] = {'R','a','n','g','e',0};
88 static const WCHAR attr_referer[] = {'R','e','f','e','r','e','r',0};
89 static const WCHAR attr_retry_after[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
90 static const WCHAR attr_server[] = {'S','e','r','v','e','r',0};
91 static const WCHAR attr_set_cookie[] = {'S','e','t','-','C','o','o','k','i','e',0};
92 static const WCHAR attr_status[] = {'S','t','a','t','u','s',0};
93 static const WCHAR attr_transfer_encoding[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
94 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};
95 static const WCHAR attr_upgrade[] = {'U','p','g','r','a','d','e',0};
96 static const WCHAR attr_uri[] = {'U','R','I',0};
97 static const WCHAR attr_user_agent[] = {'U','s','e','r','-','A','g','e','n','t',0};
98 static const WCHAR attr_vary[] = {'V','a','r','y',0};
99 static const WCHAR attr_via[] = {'V','i','a',0};
100 static const WCHAR attr_warning[] = {'W','a','r','n','i','n','g',0};
101 static const WCHAR attr_www_authenticate[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
103 static const WCHAR *attribute_table[] =
105 attr_mime_version, /* WINHTTP_QUERY_MIME_VERSION = 0 */
106 attr_content_type, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
107 attr_content_transfer_encoding, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
108 attr_content_id, /* WINHTTP_QUERY_CONTENT_ID = 3 */
109 NULL, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
110 attr_content_length, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
111 attr_content_language, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
112 attr_allow, /* WINHTTP_QUERY_ALLOW = 7 */
113 attr_public, /* WINHTTP_QUERY_PUBLIC = 8 */
114 attr_date, /* WINHTTP_QUERY_DATE = 9 */
115 attr_expires, /* WINHTTP_QUERY_EXPIRES = 10 */
116 attr_last_modified, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
117 NULL, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
118 attr_uri, /* WINHTTP_QUERY_URI = 13 */
119 attr_from, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
120 NULL, /* WINHTTP_QUERY_COST = 15 */
121 NULL, /* WINHTTP_QUERY_LINK = 16 */
122 attr_pragma, /* WINHTTP_QUERY_PRAGMA = 17 */
123 NULL, /* WINHTTP_QUERY_VERSION = 18 */
124 attr_status, /* WINHTTP_QUERY_STATUS_CODE = 19 */
125 NULL, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
126 NULL, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
127 NULL, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
128 attr_connection, /* WINHTTP_QUERY_CONNECTION = 23 */
129 attr_accept, /* WINHTTP_QUERY_ACCEPT = 24 */
130 attr_accept_charset, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
131 attr_accept_encoding, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
132 attr_accept_language, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
133 attr_authorization, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
134 attr_content_encoding, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
135 NULL, /* WINHTTP_QUERY_FORWARDED = 30 */
136 NULL, /* WINHTTP_QUERY_FROM = 31 */
137 attr_if_modified_since, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
138 attr_location, /* WINHTTP_QUERY_LOCATION = 33 */
139 NULL, /* WINHTTP_QUERY_ORIG_URI = 34 */
140 attr_referer, /* WINHTTP_QUERY_REFERER = 35 */
141 attr_retry_after, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
142 attr_server, /* WINHTTP_QUERY_SERVER = 37 */
143 NULL, /* WINHTTP_TITLE = 38 */
144 attr_user_agent, /* WINHTTP_QUERY_USER_AGENT = 39 */
145 attr_www_authenticate, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
146 attr_proxy_authenticate, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
147 attr_accept_ranges, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
148 attr_set_cookie, /* WINHTTP_QUERY_SET_COOKIE = 43 */
149 attr_cookie, /* WINHTTP_QUERY_COOKIE = 44 */
150 NULL, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
151 NULL, /* WINHTTP_QUERY_REFRESH = 46 */
152 NULL, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
153 attr_age, /* WINHTTP_QUERY_AGE = 48 */
154 attr_cache_control, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
155 attr_content_base, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
156 attr_content_location, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
157 attr_content_md5, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
158 attr_content_range, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
159 attr_etag, /* WINHTTP_QUERY_ETAG = 54 */
160 attr_host, /* WINHTTP_QUERY_HOST = 55 */
161 attr_if_match, /* WINHTTP_QUERY_IF_MATCH = 56 */
162 attr_if_none_match, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
163 attr_if_range, /* WINHTTP_QUERY_IF_RANGE = 58 */
164 attr_if_unmodified_since, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
165 attr_max_forwards, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
166 attr_proxy_authorization, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
167 attr_range, /* WINHTTP_QUERY_RANGE = 62 */
168 attr_transfer_encoding, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
169 attr_upgrade, /* WINHTTP_QUERY_UPGRADE = 64 */
170 attr_vary, /* WINHTTP_QUERY_VARY = 65 */
171 attr_via, /* WINHTTP_QUERY_VIA = 66 */
172 attr_warning, /* WINHTTP_QUERY_WARNING = 67 */
173 attr_expect, /* WINHTTP_QUERY_EXPECT = 68 */
174 attr_proxy_connection, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
175 attr_unless_modified_since, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
176 NULL, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
177 NULL, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
178 NULL, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
179 NULL /* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
182 static task_header_t *dequeue_task( request_t *request )
184 task_header_t *task;
186 EnterCriticalSection( &request->task_cs );
187 TRACE("%u tasks queued\n", list_count( &request->task_queue ));
188 task = LIST_ENTRY( list_head( &request->task_queue ), task_header_t, entry );
189 if (task) list_remove( &task->entry );
190 LeaveCriticalSection( &request->task_cs );
192 TRACE("returning task %p\n", task);
193 return task;
196 static DWORD CALLBACK task_proc( LPVOID param )
198 request_t *request = param;
199 HANDLE handles[2];
201 handles[0] = request->task_wait;
202 handles[1] = request->task_cancel;
203 for (;;)
205 DWORD err = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
206 switch (err)
208 case WAIT_OBJECT_0:
210 task_header_t *task;
211 while ((task = dequeue_task( request )))
213 task->proc( task );
214 release_object( &task->request->hdr );
215 heap_free( task );
217 break;
219 case WAIT_OBJECT_0 + 1:
220 TRACE("exiting\n");
221 CloseHandle( request->task_cancel );
222 CloseHandle( request->task_wait );
223 request->task_cs.DebugInfo->Spare[0] = 0;
224 DeleteCriticalSection( &request->task_cs );
225 request->hdr.vtbl->destroy( &request->hdr );
226 return 0;
228 default:
229 ERR("wait failed %u (%u)\n", err, GetLastError());
230 break;
233 return 0;
236 static BOOL queue_task( task_header_t *task )
238 request_t *request = task->request;
240 if (!request->task_thread)
242 if (!(request->task_wait = CreateEventW( NULL, FALSE, FALSE, NULL ))) return FALSE;
243 if (!(request->task_cancel = CreateEventW( NULL, FALSE, FALSE, NULL )))
245 CloseHandle( request->task_wait );
246 request->task_wait = NULL;
247 return FALSE;
249 if (!(request->task_thread = CreateThread( NULL, 0, task_proc, request, 0, NULL )))
251 CloseHandle( request->task_wait );
252 request->task_wait = NULL;
253 CloseHandle( request->task_cancel );
254 request->task_cancel = NULL;
255 return FALSE;
257 InitializeCriticalSection( &request->task_cs );
258 request->task_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": request.task_cs");
261 EnterCriticalSection( &request->task_cs );
262 TRACE("queueing task %p\n", task );
263 list_add_tail( &request->task_queue, &task->entry );
264 LeaveCriticalSection( &request->task_cs );
266 SetEvent( request->task_wait );
267 return TRUE;
270 static void free_header( header_t *header )
272 heap_free( header->field );
273 heap_free( header->value );
274 heap_free( header );
277 static BOOL valid_token_char( WCHAR c )
279 if (c < 32 || c == 127) return FALSE;
280 switch (c)
282 case '(': case ')':
283 case '<': case '>':
284 case '@': case ',':
285 case ';': case ':':
286 case '\\': case '\"':
287 case '/': case '[':
288 case ']': case '?':
289 case '=': case '{':
290 case '}': case ' ':
291 case '\t':
292 return FALSE;
293 default:
294 return TRUE;
298 static header_t *parse_header( LPCWSTR string )
300 const WCHAR *p, *q;
301 header_t *header;
302 int len;
304 p = string;
305 if (!(q = strchrW( p, ':' )))
307 WARN("no ':' in line %s\n", debugstr_w(string));
308 return NULL;
310 if (q == string)
312 WARN("empty field name in line %s\n", debugstr_w(string));
313 return NULL;
315 while (*p != ':')
317 if (!valid_token_char( *p ))
319 WARN("invalid character in field name %s\n", debugstr_w(string));
320 return NULL;
322 p++;
324 len = q - string;
325 if (!(header = heap_alloc_zero( sizeof(header_t) ))) return NULL;
326 if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
328 heap_free( header );
329 return NULL;
331 memcpy( header->field, string, len * sizeof(WCHAR) );
332 header->field[len] = 0;
334 q++; /* skip past colon */
335 while (*q == ' ') q++;
336 len = strlenW( q );
338 if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
340 free_header( header );
341 return NULL;
343 memcpy( header->value, q, len * sizeof(WCHAR) );
344 header->value[len] = 0;
346 return header;
349 static int get_header_index( request_t *request, LPCWSTR field, int requested_index, BOOL request_only )
351 int index;
353 TRACE("%s\n", debugstr_w(field));
355 for (index = 0; index < request->num_headers; index++)
357 if (strcmpiW( request->headers[index].field, field )) continue;
358 if (request_only && !request->headers[index].is_request) continue;
359 if (!request_only && request->headers[index].is_request) continue;
361 if (!requested_index) break;
362 requested_index--;
364 if (index >= request->num_headers) index = -1;
365 TRACE("returning %d\n", index);
366 return index;
369 static BOOL insert_header( request_t *request, header_t *header )
371 DWORD count = request->num_headers + 1;
372 header_t *hdrs;
374 if (request->headers)
375 hdrs = heap_realloc_zero( request->headers, sizeof(header_t) * count );
376 else
377 hdrs = heap_alloc_zero( sizeof(header_t) );
378 if (!hdrs) return FALSE;
380 request->headers = hdrs;
381 request->headers[count - 1].field = strdupW( header->field );
382 request->headers[count - 1].value = strdupW( header->value );
383 request->headers[count - 1].is_request = header->is_request;
384 request->num_headers = count;
385 return TRUE;
388 static BOOL delete_header( request_t *request, DWORD index )
390 if (!request->num_headers) return FALSE;
391 if (index >= request->num_headers) return FALSE;
392 request->num_headers--;
394 heap_free( request->headers[index].field );
395 heap_free( request->headers[index].value );
397 memmove( &request->headers[index], &request->headers[index + 1], (request->num_headers - index) * sizeof(header_t) );
398 memset( &request->headers[request->num_headers], 0, sizeof(header_t) );
399 return TRUE;
402 static BOOL process_header( request_t *request, LPCWSTR field, LPCWSTR value, DWORD flags, BOOL request_only )
404 int index;
405 header_t hdr;
407 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
409 if ((index = get_header_index( request, field, 0, request_only )) >= 0)
411 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
414 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
416 if (index >= 0)
418 delete_header( request, index );
419 if (!value || !value[0]) return TRUE;
421 else if (!(flags & WINHTTP_ADDREQ_FLAG_ADD))
423 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
424 return FALSE;
427 hdr.field = (LPWSTR)field;
428 hdr.value = (LPWSTR)value;
429 hdr.is_request = request_only;
430 return insert_header( request, &hdr );
432 else if (value)
435 if ((flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON)) &&
436 index >= 0)
438 WCHAR *tmp;
439 int len, len_orig, len_value;
440 header_t *header = &request->headers[index];
442 len_orig = strlenW( header->value );
443 len_value = strlenW( value );
445 len = len_orig + len_value + 2;
446 if (!(tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) ))) return FALSE;
447 header->value = tmp;
448 header->value[len_orig++] = (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) ? ',' : ';';
449 header->value[len_orig++] = ' ';
451 memcpy( &header->value[len_orig], value, len_value * sizeof(WCHAR) );
452 header->value[len] = 0;
453 return TRUE;
455 else
457 hdr.field = (LPWSTR)field;
458 hdr.value = (LPWSTR)value;
459 hdr.is_request = request_only;
460 return insert_header( request, &hdr );
464 return TRUE;
467 BOOL add_request_headers( request_t *request, LPCWSTR headers, DWORD len, DWORD flags )
469 BOOL ret = FALSE;
470 WCHAR *buffer, *p, *q;
471 header_t *header;
473 if (len == ~0u) len = strlenW( headers );
474 if (!len) return TRUE;
475 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
476 memcpy( buffer, headers, len * sizeof(WCHAR) );
477 buffer[len] = 0;
479 p = buffer;
482 q = p;
483 while (*q)
485 if (q[0] == '\n' && q[1] == '\r')
487 q[0] = '\r';
488 q[1] = '\n';
490 if (q[0] == '\r' && q[1] == '\n') break;
491 q++;
493 if (!*p) break;
494 if (*q == '\r')
496 *q = 0;
497 q += 2; /* jump over \r\n */
499 if ((header = parse_header( p )))
501 ret = process_header( request, header->field, header->value, flags, TRUE );
502 free_header( header );
504 p = q;
505 } while (ret);
507 heap_free( buffer );
508 return ret;
511 /***********************************************************************
512 * WinHttpAddRequestHeaders (winhttp.@)
514 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
516 BOOL ret;
517 request_t *request;
519 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest, debugstr_w(headers), len, flags);
521 if (!headers || !len)
523 set_last_error( ERROR_INVALID_PARAMETER );
524 return FALSE;
526 if (!(request = (request_t *)grab_object( hrequest )))
528 set_last_error( ERROR_INVALID_HANDLE );
529 return FALSE;
531 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
533 release_object( &request->hdr );
534 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
535 return FALSE;
538 ret = add_request_headers( request, headers, len, flags );
540 release_object( &request->hdr );
541 if (ret) set_last_error( ERROR_SUCCESS );
542 return ret;
545 static WCHAR *build_request_path( request_t *request )
547 WCHAR *ret;
549 if (strcmpiW( request->connect->hostname, request->connect->servername ))
551 static const WCHAR http[] = { 'h','t','t','p',0 };
552 static const WCHAR https[] = { 'h','t','t','p','s',0 };
553 static const WCHAR fmt[] = { '%','s',':','/','/','%','s',0 };
554 LPCWSTR scheme = request->netconn.secure ? https : http;
555 int len;
557 len = strlenW( scheme ) + strlenW( request->connect->hostname );
558 /* 3 characters for '://', 1 for NUL. */
559 len += 4;
560 if (request->connect->hostport)
562 /* 1 for ':' between host and port, up to 5 for port */
563 len += 6;
565 if (request->path)
566 len += strlenW( request->path );
567 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
569 sprintfW( ret, fmt, scheme, request->connect->hostname );
570 if (request->connect->hostport)
572 static const WCHAR colonFmt[] = { ':','%','u',0 };
574 sprintfW( ret + strlenW( ret ), colonFmt,
575 request->connect->hostport );
577 if (request->path)
578 strcatW( ret, request->path );
581 else
582 ret = request->path;
583 return ret;
586 static WCHAR *build_request_string( request_t *request )
588 static const WCHAR space[] = {' ',0};
589 static const WCHAR crlf[] = {'\r','\n',0};
590 static const WCHAR colon[] = {':',' ',0};
591 static const WCHAR twocrlf[] = {'\r','\n','\r','\n',0};
593 WCHAR *path, *ret;
594 const WCHAR **headers, **p;
595 unsigned int len, i = 0, j;
597 /* allocate space for an array of all the string pointers to be added */
598 len = request->num_headers * 4 + 7;
599 if (!(headers = heap_alloc( len * sizeof(LPCWSTR) ))) return NULL;
601 path = build_request_path( request );
602 headers[i++] = request->verb;
603 headers[i++] = space;
604 headers[i++] = path;
605 headers[i++] = space;
606 headers[i++] = request->version;
608 for (j = 0; j < request->num_headers; j++)
610 if (request->headers[j].is_request)
612 headers[i++] = crlf;
613 headers[i++] = request->headers[j].field;
614 headers[i++] = colon;
615 headers[i++] = request->headers[j].value;
617 TRACE("adding header %s (%s)\n", debugstr_w(request->headers[j].field),
618 debugstr_w(request->headers[j].value));
621 headers[i++] = twocrlf;
622 headers[i] = NULL;
624 len = 0;
625 for (p = headers; *p; p++) len += strlenW( *p );
626 len++;
628 if (!(ret = heap_alloc( len * sizeof(WCHAR) )))
629 goto out;
630 *ret = 0;
631 for (p = headers; *p; p++) strcatW( ret, *p );
633 out:
634 if (path != request->path)
635 heap_free( path );
636 heap_free( headers );
637 return ret;
640 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
642 static BOOL query_headers( request_t *request, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
644 header_t *header = NULL;
645 BOOL request_only, ret = FALSE;
646 int requested_index, header_index = -1;
647 DWORD attr, len;
649 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
650 requested_index = index ? *index : 0;
652 attr = level & ~QUERY_MODIFIER_MASK;
653 switch (attr)
655 case WINHTTP_QUERY_CUSTOM:
657 header_index = get_header_index( request, name, requested_index, request_only );
658 break;
660 case WINHTTP_QUERY_RAW_HEADERS:
662 WCHAR *headers, *p, *q;
664 if (request_only)
665 headers = build_request_string( request );
666 else
667 headers = request->raw_headers;
669 if (!(p = headers)) return FALSE;
670 for (len = 0; *p; p++) if (*p != '\r') len++;
672 if (!buffer || len * sizeof(WCHAR) > *buflen)
673 set_last_error( ERROR_INSUFFICIENT_BUFFER );
674 else
676 for (p = headers, q = buffer; *p; p++, q++)
678 if (*p != '\r') *q = *p;
679 else
681 *q = 0;
682 p++; /* skip '\n' */
685 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
686 if (len) len--;
687 ret = TRUE;
689 *buflen = len * sizeof(WCHAR);
690 if (request_only) heap_free( headers );
691 return ret;
693 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
695 WCHAR *headers;
697 if (request_only)
698 headers = build_request_string( request );
699 else
700 headers = request->raw_headers;
702 if (!headers) return FALSE;
703 len = strlenW( headers ) * sizeof(WCHAR);
704 if (!buffer || len + sizeof(WCHAR) > *buflen)
706 len += sizeof(WCHAR);
707 set_last_error( ERROR_INSUFFICIENT_BUFFER );
709 else
711 memcpy( buffer, headers, len + sizeof(WCHAR) );
712 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
713 ret = TRUE;
715 *buflen = len;
716 if (request_only) heap_free( headers );
717 return ret;
719 case WINHTTP_QUERY_VERSION:
720 len = strlenW( request->version ) * sizeof(WCHAR);
721 if (!buffer || len + sizeof(WCHAR) > *buflen)
723 len += sizeof(WCHAR);
724 set_last_error( ERROR_INSUFFICIENT_BUFFER );
726 else
728 strcpyW( buffer, request->version );
729 TRACE("returning string: %s\n", debugstr_w(buffer));
730 ret = TRUE;
732 *buflen = len;
733 return ret;
735 case WINHTTP_QUERY_STATUS_TEXT:
736 len = strlenW( request->status_text ) * sizeof(WCHAR);
737 if (!buffer || len + sizeof(WCHAR) > *buflen)
739 len += sizeof(WCHAR);
740 set_last_error( ERROR_INSUFFICIENT_BUFFER );
742 else
744 strcpyW( buffer, request->status_text );
745 TRACE("returning string: %s\n", debugstr_w(buffer));
746 ret = TRUE;
748 *buflen = len;
749 return ret;
751 default:
752 if (attr >= sizeof(attribute_table)/sizeof(attribute_table[0]) || !attribute_table[attr])
754 FIXME("attribute %u not implemented\n", attr);
755 return FALSE;
757 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
758 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
759 break;
762 if (header_index >= 0)
764 header = &request->headers[header_index];
766 if (!header || (request_only && !header->is_request))
768 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
769 return FALSE;
771 if (index) *index += 1;
772 if (level & WINHTTP_QUERY_FLAG_NUMBER)
774 if (!buffer || sizeof(int) > *buflen)
776 set_last_error( ERROR_INSUFFICIENT_BUFFER );
778 else
780 int *number = buffer;
781 *number = atoiW( header->value );
782 TRACE("returning number: %d\n", *number);
783 ret = TRUE;
785 *buflen = sizeof(int);
787 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
789 SYSTEMTIME *st = buffer;
790 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
792 set_last_error( ERROR_INSUFFICIENT_BUFFER );
794 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
796 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
797 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
798 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
800 *buflen = sizeof(SYSTEMTIME);
802 else if (header->value)
804 len = strlenW( header->value ) * sizeof(WCHAR);
805 if (!buffer || len + sizeof(WCHAR) > *buflen)
807 len += sizeof(WCHAR);
808 set_last_error( ERROR_INSUFFICIENT_BUFFER );
810 else
812 strcpyW( buffer, header->value );
813 TRACE("returning string: %s\n", debugstr_w(buffer));
814 ret = TRUE;
816 *buflen = len;
818 return ret;
821 /***********************************************************************
822 * WinHttpQueryHeaders (winhttp.@)
824 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
826 BOOL ret;
827 request_t *request;
829 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
831 if (!(request = (request_t *)grab_object( hrequest )))
833 set_last_error( ERROR_INVALID_HANDLE );
834 return FALSE;
836 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
838 release_object( &request->hdr );
839 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
840 return FALSE;
843 ret = query_headers( request, level, name, buffer, buflen, index );
845 release_object( &request->hdr );
846 if (ret) set_last_error( ERROR_SUCCESS );
847 return ret;
850 static LPWSTR concatenate_string_list( LPCWSTR *list, int len )
852 LPCWSTR *t;
853 LPWSTR str;
855 for( t = list; *t ; t++ )
856 len += strlenW( *t );
857 len++;
859 str = heap_alloc( len * sizeof(WCHAR) );
860 if (!str) return NULL;
861 *str = 0;
863 for( t = list; *t ; t++ )
864 strcatW( str, *t );
866 return str;
869 static LPWSTR build_header_request_string( request_t *request, LPCWSTR verb,
870 LPCWSTR path, LPCWSTR version )
872 static const WCHAR crlf[] = {'\r','\n',0};
873 static const WCHAR space[] = { ' ',0 };
874 static const WCHAR colon[] = { ':',' ',0 };
875 static const WCHAR twocrlf[] = {'\r','\n','\r','\n', 0};
876 LPWSTR requestString;
877 DWORD len, n;
878 LPCWSTR *req;
879 UINT i;
880 LPWSTR p;
882 /* allocate space for an array of all the string pointers to be added */
883 len = (request->num_headers) * 4 + 10;
884 req = heap_alloc( len * sizeof(LPCWSTR) );
885 if (!req) return NULL;
887 /* add the verb, path and HTTP version string */
888 n = 0;
889 req[n++] = verb;
890 req[n++] = space;
891 req[n++] = path;
892 req[n++] = space;
893 req[n++] = version;
895 /* Append custom request headers */
896 for (i = 0; i < request->num_headers; i++)
898 if (request->headers[i].is_request)
900 req[n++] = crlf;
901 req[n++] = request->headers[i].field;
902 req[n++] = colon;
903 req[n++] = request->headers[i].value;
905 TRACE("Adding custom header %s (%s)\n",
906 debugstr_w(request->headers[i].field),
907 debugstr_w(request->headers[i].value));
911 if( n >= len )
912 ERR("oops. buffer overrun\n");
914 req[n] = NULL;
915 requestString = concatenate_string_list( req, 4 );
916 heap_free( req );
917 if (!requestString) return NULL;
920 * Set (header) termination string for request
921 * Make sure there are exactly two new lines at the end of the request
923 p = &requestString[strlenW(requestString)-1];
924 while ( (*p == '\n') || (*p == '\r') )
925 p--;
926 strcpyW( p+1, twocrlf );
928 return requestString;
931 static BOOL read_reply( request_t *request );
933 static BOOL secure_proxy_connect( request_t *request )
935 static const WCHAR verbConnect[] = {'C','O','N','N','E','C','T',0};
936 static const WCHAR fmt[] = {'%','s',':','%','u',0};
937 BOOL ret = FALSE;
938 LPWSTR path;
939 connect_t *connect = request->connect;
941 path = heap_alloc( (strlenW( connect->hostname ) + 13) * sizeof(WCHAR) );
942 if (path)
944 LPWSTR requestString;
946 sprintfW( path, fmt, connect->hostname, connect->hostport );
947 requestString = build_header_request_string( request, verbConnect,
948 path, http1_1 );
949 heap_free( path );
950 if (requestString)
952 LPSTR req_ascii = strdupWA( requestString );
954 heap_free( requestString );
955 if (req_ascii)
957 int len = strlen( req_ascii ), bytes_sent;
959 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
960 heap_free( req_ascii );
961 if (ret)
962 ret = read_reply( request );
966 return ret;
969 #ifndef INET6_ADDRSTRLEN
970 #define INET6_ADDRSTRLEN 46
971 #endif
973 static WCHAR *addr_to_str( struct sockaddr *addr )
975 char buf[INET6_ADDRSTRLEN];
976 void *src;
978 switch (addr->sa_family)
980 case AF_INET:
981 src = &((struct sockaddr_in *)addr)->sin_addr;
982 break;
983 case AF_INET6:
984 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
985 break;
986 default:
987 WARN("unsupported address family %d\n", addr->sa_family);
988 return NULL;
990 if (!inet_ntop( addr->sa_family, src, buf, sizeof(buf) )) return NULL;
991 return strdupAW( buf );
994 static BOOL open_connection( request_t *request )
996 connect_t *connect;
997 WCHAR *addressW = NULL;
998 INTERNET_PORT port;
999 socklen_t slen;
1000 struct sockaddr *saddr;
1001 DWORD len;
1003 if (netconn_connected( &request->netconn )) goto done;
1005 connect = request->connect;
1006 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1007 saddr = (struct sockaddr *)&connect->sockaddr;
1008 slen = sizeof(struct sockaddr);
1010 if (!connect->resolved)
1012 len = strlenW( connect->servername ) + 1;
1013 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, connect->servername, len );
1015 if (!netconn_resolve( connect->servername, port, saddr, &slen, request->resolve_timeout )) return FALSE;
1016 connect->resolved = TRUE;
1018 if (!(addressW = addr_to_str( saddr ))) return FALSE;
1019 len = strlenW( addressW ) + 1;
1020 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
1022 if (!addressW && !(addressW = addr_to_str( saddr ))) return FALSE;
1023 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
1025 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
1027 if (!netconn_create( &request->netconn, saddr->sa_family, SOCK_STREAM, 0 ))
1029 heap_free( addressW );
1030 return FALSE;
1032 netconn_set_timeout( &request->netconn, TRUE, request->send_timeout );
1033 netconn_set_timeout( &request->netconn, FALSE, request->recv_timeout );
1034 if (!netconn_connect( &request->netconn, saddr, slen, request->connect_timeout ))
1036 netconn_close( &request->netconn );
1037 heap_free( addressW );
1038 return FALSE;
1040 if (request->hdr.flags & WINHTTP_FLAG_SECURE)
1042 if (connect->session->proxy_server &&
1043 strcmpiW( connect->hostname, connect->servername ))
1045 if (!secure_proxy_connect( request ))
1047 heap_free( addressW );
1048 return FALSE;
1051 if (!netconn_secure_connect( &request->netconn, connect->hostname ))
1053 netconn_close( &request->netconn );
1054 heap_free( addressW );
1055 return FALSE;
1059 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
1061 done:
1062 request->read_pos = request->read_size = 0;
1063 request->read_chunked = FALSE;
1064 request->read_chunked_size = ~0u;
1065 request->read_chunked_eof = FALSE;
1066 heap_free( addressW );
1067 return TRUE;
1070 void close_connection( request_t *request )
1072 if (!netconn_connected( &request->netconn )) return;
1074 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1075 netconn_close( &request->netconn );
1076 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1079 static BOOL add_host_header( request_t *request, DWORD modifier )
1081 BOOL ret;
1082 DWORD len;
1083 WCHAR *host;
1084 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1085 connect_t *connect = request->connect;
1086 INTERNET_PORT port;
1088 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1090 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1092 return process_header( request, attr_host, connect->hostname, modifier, TRUE );
1094 len = strlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1095 if (!(host = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1096 sprintfW( host, fmt, connect->hostname, port );
1097 ret = process_header( request, attr_host, host, modifier, TRUE );
1098 heap_free( host );
1099 return ret;
1102 static void clear_response_headers( request_t *request )
1104 unsigned int i;
1106 for (i = 0; i < request->num_headers; i++)
1108 if (!request->headers[i].field) continue;
1109 if (!request->headers[i].value) continue;
1110 if (request->headers[i].is_request) continue;
1111 delete_header( request, i );
1112 i--;
1116 /* remove some amount of data from the read buffer */
1117 static void remove_data( request_t *request, int count )
1119 if (!(request->read_size -= count)) request->read_pos = 0;
1120 else request->read_pos += count;
1123 /* read some more data into the read buffer */
1124 static BOOL read_more_data( request_t *request, int maxlen, BOOL notify )
1126 int len;
1127 BOOL ret;
1129 if (request->read_chunked_eof) return FALSE;
1131 if (request->read_size && request->read_pos)
1133 /* move existing data to the start of the buffer */
1134 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1135 request->read_pos = 0;
1137 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1139 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1141 ret = netconn_recv( &request->netconn, request->read_buf + request->read_size,
1142 maxlen - request->read_size, 0, &len );
1144 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &len, sizeof(len) );
1146 request->read_size += len;
1147 return ret;
1150 /* discard data contents until we reach end of line */
1151 static BOOL discard_eol( request_t *request, BOOL notify )
1155 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1156 if (eol)
1158 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1159 break;
1161 request->read_pos = request->read_size = 0; /* discard everything */
1162 if (!read_more_data( request, -1, notify )) return FALSE;
1163 } while (request->read_size);
1164 return TRUE;
1167 /* read the size of the next chunk */
1168 static BOOL start_next_chunk( request_t *request, BOOL notify )
1170 DWORD chunk_size = 0;
1172 assert(!request->read_chunked_size || request->read_chunked_size == ~0u);
1174 if (request->read_chunked_eof) return FALSE;
1176 /* read terminator for the previous chunk */
1177 if (!request->read_chunked_size && !discard_eol( request, notify )) return FALSE;
1179 for (;;)
1181 while (request->read_size)
1183 char ch = request->read_buf[request->read_pos];
1184 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1185 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1186 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1187 else if (ch == ';' || ch == '\r' || ch == '\n')
1189 TRACE("reading %u byte chunk\n", chunk_size);
1191 if (request->content_length == ~0u) request->content_length = chunk_size;
1192 else request->content_length += chunk_size;
1194 request->read_chunked_size = chunk_size;
1195 if (!chunk_size) request->read_chunked_eof = TRUE;
1197 return discard_eol( request, notify );
1199 remove_data( request, 1 );
1201 if (!read_more_data( request, -1, notify )) return FALSE;
1202 if (!request->read_size)
1204 request->content_length = request->content_read = 0;
1205 request->read_chunked_size = 0;
1206 return TRUE;
1211 static BOOL refill_buffer( request_t *request, BOOL notify )
1213 int len = sizeof(request->read_buf);
1215 if (request->read_chunked)
1217 if (request->read_chunked_eof) return FALSE;
1218 if (request->read_chunked_size == ~0u || !request->read_chunked_size)
1220 if (!start_next_chunk( request, notify )) return FALSE;
1222 len = min( len, request->read_chunked_size );
1224 else if (request->content_length != ~0u)
1226 len = min( len, request->content_length - request->content_read );
1229 if (len <= request->read_size) return TRUE;
1230 if (!read_more_data( request, len, notify )) return FALSE;
1231 if (!request->read_size) request->content_length = request->content_read = 0;
1232 return TRUE;
1235 static void finished_reading( request_t *request )
1237 static const WCHAR closeW[] = {'c','l','o','s','e',0};
1239 BOOL close = FALSE;
1240 WCHAR connection[20];
1241 DWORD size = sizeof(connection);
1243 if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
1244 else if (query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
1245 query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
1247 if (!strcmpiW( connection, closeW )) close = TRUE;
1249 else if (!strcmpW( request->version, http1_0 )) close = TRUE;
1250 if (close) close_connection( request );
1253 /* return the size of data available to be read immediately */
1254 static DWORD get_available_data( request_t *request )
1256 if (request->read_chunked) return min( request->read_chunked_size, request->read_size );
1257 return request->read_size;
1260 /* check if we have reached the end of the data to read */
1261 static BOOL end_of_read_data( request_t *request )
1263 if (!request->content_length) return TRUE;
1264 if (request->read_chunked) return request->read_chunked_eof;
1265 if (request->content_length == ~0u) return FALSE;
1266 return (request->content_length == request->content_read);
1269 static BOOL read_data( request_t *request, void *buffer, DWORD size, DWORD *read, BOOL async )
1271 int count, bytes_read = 0;
1273 if (end_of_read_data( request )) goto done;
1275 while (size)
1277 if (!(count = get_available_data( request )))
1279 if (!refill_buffer( request, async )) goto done;
1280 if (!(count = get_available_data( request ))) goto done;
1282 count = min( count, size );
1283 memcpy( (char *)buffer + bytes_read, request->read_buf + request->read_pos, count );
1284 remove_data( request, count );
1285 if (request->read_chunked) request->read_chunked_size -= count;
1286 size -= count;
1287 bytes_read += count;
1288 request->content_read += count;
1289 if (end_of_read_data( request )) goto done;
1291 if (request->read_chunked && !request->read_chunked_size) refill_buffer( request, async );
1293 done:
1294 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, request->content_read, request->content_length );
1296 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
1297 if (read) *read = bytes_read;
1298 if (end_of_read_data( request )) finished_reading( request );
1299 return TRUE;
1302 /* read any content returned by the server so that the connection can be reused */
1303 static void drain_content( request_t *request )
1305 DWORD bytes_read;
1306 char buffer[2048];
1308 refill_buffer( request, FALSE );
1309 for (;;)
1311 if (!read_data( request, buffer, sizeof(buffer), &bytes_read, FALSE ) || !bytes_read) return;
1315 static BOOL send_request( request_t *request, LPCWSTR headers, DWORD headers_len, LPVOID optional,
1316 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
1318 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
1319 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
1320 static const WCHAR length_fmt[] = {'%','l','d',0};
1322 BOOL ret = FALSE;
1323 connect_t *connect = request->connect;
1324 session_t *session = connect->session;
1325 WCHAR *req = NULL;
1326 char *req_ascii;
1327 int bytes_sent;
1328 DWORD len, i, flags;
1330 clear_response_headers( request );
1331 drain_content( request );
1333 flags = WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
1334 for (i = 0; i < request->num_accept_types; i++)
1336 process_header( request, attr_accept, request->accept_types[i], flags, TRUE );
1338 if (session->agent)
1339 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1341 if (connect->hostname)
1342 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
1344 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
1346 WCHAR length[21]; /* decimal long int + null */
1347 sprintfW( length, length_fmt, total_len );
1348 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1350 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
1352 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1354 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
1356 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1357 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1359 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
1361 TRACE("failed to add request headers\n");
1362 return FALSE;
1364 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
1366 WARN("failed to add cookie headers\n");
1367 return FALSE;
1370 if (context) request->hdr.context = context;
1372 if (!(ret = open_connection( request ))) goto end;
1373 if (!(req = build_request_string( request ))) goto end;
1375 if (!(req_ascii = strdupWA( req ))) goto end;
1376 TRACE("full request: %s\n", debugstr_a(req_ascii));
1377 len = strlen(req_ascii);
1379 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
1381 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
1382 heap_free( req_ascii );
1383 if (!ret) goto end;
1385 if (optional_len)
1387 if (!netconn_send( &request->netconn, optional, optional_len, &bytes_sent )) goto end;
1388 request->optional = optional;
1389 request->optional_len = optional_len;
1390 len += optional_len;
1392 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(len) );
1394 end:
1395 if (async)
1397 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
1398 else
1400 WINHTTP_ASYNC_RESULT result;
1401 result.dwResult = API_SEND_REQUEST;
1402 result.dwError = get_last_error();
1403 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
1406 heap_free( req );
1407 return ret;
1410 static void task_send_request( task_header_t *task )
1412 send_request_t *s = (send_request_t *)task;
1413 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
1414 heap_free( s->headers );
1417 /***********************************************************************
1418 * WinHttpSendRequest (winhttp.@)
1420 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
1421 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
1423 BOOL ret;
1424 request_t *request;
1426 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1427 hrequest, debugstr_w(headers), headers_len, optional_len, total_len, context);
1429 if (!(request = (request_t *)grab_object( hrequest )))
1431 set_last_error( ERROR_INVALID_HANDLE );
1432 return FALSE;
1434 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1436 release_object( &request->hdr );
1437 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1438 return FALSE;
1441 if (headers && !headers_len) headers_len = strlenW( headers );
1443 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
1445 send_request_t *s;
1447 if (!(s = heap_alloc( sizeof(send_request_t) ))) return FALSE;
1448 s->hdr.request = request;
1449 s->hdr.proc = task_send_request;
1450 s->headers = strdupW( headers );
1451 s->headers_len = headers_len;
1452 s->optional = optional;
1453 s->optional_len = optional_len;
1454 s->total_len = total_len;
1455 s->context = context;
1457 addref_object( &request->hdr );
1458 ret = queue_task( (task_header_t *)s );
1460 else
1461 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
1463 release_object( &request->hdr );
1464 if (ret) set_last_error( ERROR_SUCCESS );
1465 return ret;
1468 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1470 static const WCHAR basicW[] = {'B','a','s','i','c',0};
1471 static const WCHAR ntlmW[] = {'N','T','L','M',0};
1472 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
1473 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
1474 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
1476 static const struct
1478 const WCHAR *str;
1479 unsigned int len;
1480 DWORD scheme;
1482 auth_schemes[] =
1484 { basicW, ARRAYSIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
1485 { ntlmW, ARRAYSIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
1486 { passportW, ARRAYSIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
1487 { digestW, ARRAYSIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
1488 { negotiateW, ARRAYSIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
1490 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
1492 static enum auth_scheme scheme_from_flag( DWORD flag )
1494 int i;
1496 for (i = 0; i < num_auth_schemes; i++) if (flag == auth_schemes[i].scheme) return i;
1497 return SCHEME_INVALID;
1500 static DWORD auth_scheme_from_header( WCHAR *header )
1502 unsigned int i;
1504 for (i = 0; i < num_auth_schemes; i++)
1506 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
1507 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
1509 return 0;
1512 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
1514 DWORD index = 0, supported_schemes = 0, first_scheme = 0;
1515 BOOL ret = FALSE;
1517 for (;;)
1519 WCHAR *buffer;
1520 DWORD size, scheme;
1522 size = 0;
1523 query_headers( request, level, NULL, NULL, &size, &index );
1524 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) break;
1526 index--;
1527 if (!(buffer = heap_alloc( size ))) return FALSE;
1528 if (!query_headers( request, level, NULL, buffer, &size, &index ))
1530 heap_free( buffer );
1531 return FALSE;
1533 scheme = auth_scheme_from_header( buffer );
1534 heap_free( buffer );
1535 if (!scheme) continue;
1537 if (!first_scheme) first_scheme = scheme;
1538 supported_schemes |= scheme;
1540 ret = TRUE;
1543 if (ret)
1545 *supported = supported_schemes;
1546 *first = first_scheme;
1548 return ret;
1551 /***********************************************************************
1552 * WinHttpQueryAuthSchemes (winhttp.@)
1554 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
1556 BOOL ret = FALSE;
1557 request_t *request;
1559 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
1561 if (!(request = (request_t *)grab_object( hrequest )))
1563 set_last_error( ERROR_INVALID_HANDLE );
1564 return FALSE;
1566 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1568 release_object( &request->hdr );
1569 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1570 return FALSE;
1572 if (!supported || !first || !target)
1574 release_object( &request->hdr );
1575 set_last_error( ERROR_INVALID_PARAMETER );
1576 return FALSE;
1580 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
1582 *target = WINHTTP_AUTH_TARGET_SERVER;
1583 ret = TRUE;
1585 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
1587 *target = WINHTTP_AUTH_TARGET_PROXY;
1588 ret = TRUE;
1591 release_object( &request->hdr );
1592 if (ret) set_last_error( ERROR_SUCCESS );
1593 return ret;
1596 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
1598 UINT n = 0, x;
1599 static const char base64enc[] =
1600 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1602 while (len > 0)
1604 /* first 6 bits, all from bin[0] */
1605 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
1606 x = (bin[0] & 3) << 4;
1608 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1609 if (len == 1)
1611 base64[n++] = base64enc[x];
1612 base64[n++] = '=';
1613 base64[n++] = '=';
1614 break;
1616 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
1617 x = (bin[1] & 0x0f) << 2;
1619 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1620 if (len == 2)
1622 base64[n++] = base64enc[x];
1623 base64[n++] = '=';
1624 break;
1626 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1628 /* last 6 bits, all from bin [2] */
1629 base64[n++] = base64enc[bin[2] & 0x3f];
1630 bin += 3;
1631 len -= 3;
1633 base64[n] = 0;
1634 return n;
1637 static inline char decode_char( WCHAR c )
1639 if (c >= 'A' && c <= 'Z') return c - 'A';
1640 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1641 if (c >= '0' && c <= '9') return c - '0' + 52;
1642 if (c == '+') return 62;
1643 if (c == '/') return 63;
1644 return 64;
1647 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1649 unsigned int i = 0;
1650 char c0, c1, c2, c3;
1651 const WCHAR *p = base64;
1653 while (len > 4)
1655 if ((c0 = decode_char( p[0] )) > 63) return 0;
1656 if ((c1 = decode_char( p[1] )) > 63) return 0;
1657 if ((c2 = decode_char( p[2] )) > 63) return 0;
1658 if ((c3 = decode_char( p[3] )) > 63) return 0;
1660 if (buf)
1662 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1663 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1664 buf[i + 2] = (c2 << 6) | c3;
1666 len -= 4;
1667 i += 3;
1668 p += 4;
1670 if (p[2] == '=')
1672 if ((c0 = decode_char( p[0] )) > 63) return 0;
1673 if ((c1 = decode_char( p[1] )) > 63) return 0;
1675 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1676 i++;
1678 else if (p[3] == '=')
1680 if ((c0 = decode_char( p[0] )) > 63) return 0;
1681 if ((c1 = decode_char( p[1] )) > 63) return 0;
1682 if ((c2 = decode_char( p[2] )) > 63) return 0;
1684 if (buf)
1686 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1687 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1689 i += 2;
1691 else
1693 if ((c0 = decode_char( p[0] )) > 63) return 0;
1694 if ((c1 = decode_char( p[1] )) > 63) return 0;
1695 if ((c2 = decode_char( p[2] )) > 63) return 0;
1696 if ((c3 = decode_char( p[3] )) > 63) return 0;
1698 if (buf)
1700 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1701 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1702 buf[i + 2] = (c2 << 6) | c3;
1704 i += 3;
1706 return i;
1709 static struct authinfo *alloc_authinfo(void)
1711 struct authinfo *ret;
1713 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1715 SecInvalidateHandle( &ret->cred );
1716 SecInvalidateHandle( &ret->ctx );
1717 memset( &ret->exp, 0, sizeof(ret->exp) );
1718 ret->scheme = 0;
1719 ret->attr = 0;
1720 ret->max_token = 0;
1721 ret->data = NULL;
1722 ret->data_len = 0;
1723 ret->finished = FALSE;
1724 return ret;
1727 void destroy_authinfo( struct authinfo *authinfo )
1729 if (!authinfo) return;
1731 if (SecIsValidHandle( &authinfo->ctx ))
1732 DeleteSecurityContext( &authinfo->ctx );
1733 if (SecIsValidHandle( &authinfo->cred ))
1734 FreeCredentialsHandle( &authinfo->cred );
1736 heap_free( authinfo->data );
1737 heap_free( authinfo );
1740 static BOOL get_authvalue( request_t *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1742 DWORD size, index = 0;
1743 for (;;)
1745 size = len;
1746 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1747 if (auth_scheme_from_header( buffer ) == scheme) break;
1749 return TRUE;
1752 static BOOL do_authorization( request_t *request, DWORD target, DWORD scheme_flag )
1754 struct authinfo *authinfo, **auth_ptr;
1755 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1756 const WCHAR *auth_target, *username, *password;
1757 WCHAR auth_value[2048], *auth_reply;
1758 DWORD len = sizeof(auth_value), len_scheme, flags;
1759 BOOL ret;
1761 if (scheme == SCHEME_INVALID) return FALSE;
1763 switch (target)
1765 case WINHTTP_AUTH_TARGET_SERVER:
1766 if (!get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len ))
1767 return FALSE;
1768 auth_ptr = &request->authinfo;
1769 auth_target = attr_authorization;
1770 if (request->creds[TARGET_SERVER][scheme].username)
1772 username = request->creds[TARGET_SERVER][scheme].username;
1773 password = request->creds[TARGET_SERVER][scheme].password;
1775 else
1777 username = request->connect->username;
1778 password = request->connect->password;
1780 break;
1782 case WINHTTP_AUTH_TARGET_PROXY:
1783 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1784 return FALSE;
1785 auth_ptr = &request->proxy_authinfo;
1786 auth_target = attr_proxy_authorization;
1787 if (request->creds[TARGET_PROXY][scheme].username)
1789 username = request->creds[TARGET_PROXY][scheme].username;
1790 password = request->creds[TARGET_PROXY][scheme].password;
1792 else
1794 username = request->connect->session->proxy_username;
1795 password = request->connect->session->proxy_password;
1797 break;
1799 default:
1800 WARN("unknown target %x\n", target);
1801 return FALSE;
1803 authinfo = *auth_ptr;
1805 switch (scheme)
1807 case SCHEME_BASIC:
1809 int userlen, passlen;
1811 if (!username || !password) return FALSE;
1812 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1814 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1815 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1817 authinfo->data_len = userlen + 1 + passlen;
1818 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1820 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1821 authinfo->data[userlen] = ':';
1822 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1824 authinfo->scheme = SCHEME_BASIC;
1825 authinfo->finished = TRUE;
1826 break;
1828 case SCHEME_NTLM:
1829 case SCHEME_NEGOTIATE:
1831 SECURITY_STATUS status;
1832 SecBufferDesc out_desc, in_desc;
1833 SecBuffer out, in;
1834 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1835 const WCHAR *p;
1836 BOOL first = FALSE;
1838 if (!authinfo)
1840 TimeStamp exp;
1841 SEC_WINNT_AUTH_IDENTITY_W id;
1842 WCHAR *domain, *user;
1844 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1846 first = TRUE;
1847 domain = (WCHAR *)username;
1848 user = strchrW( username, '\\' );
1850 if (user) user++;
1851 else
1853 user = (WCHAR *)username;
1854 domain = NULL;
1856 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1857 id.User = user;
1858 id.UserLength = strlenW( user );
1859 id.Domain = domain;
1860 id.DomainLength = domain ? user - domain - 1 : 0;
1861 id.Password = (WCHAR *)password;
1862 id.PasswordLength = strlenW( password );
1864 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1865 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1866 &authinfo->cred, &exp );
1867 if (status == SEC_E_OK)
1869 PSecPkgInfoW info;
1870 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1871 if (status == SEC_E_OK)
1873 authinfo->max_token = info->cbMaxToken;
1874 FreeContextBuffer( info );
1877 if (status != SEC_E_OK)
1879 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1880 debugstr_w(auth_schemes[scheme].str), status);
1881 heap_free( authinfo );
1882 return FALSE;
1884 authinfo->scheme = scheme;
1886 else if (authinfo->finished) return FALSE;
1888 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1889 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1891 ERR("authentication scheme changed from %s to %s\n",
1892 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1893 destroy_authinfo( authinfo );
1894 *auth_ptr = NULL;
1895 return FALSE;
1897 in.BufferType = SECBUFFER_TOKEN;
1898 in.cbBuffer = 0;
1899 in.pvBuffer = NULL;
1901 in_desc.ulVersion = 0;
1902 in_desc.cBuffers = 1;
1903 in_desc.pBuffers = &in;
1905 p = auth_value + auth_schemes[scheme].len;
1906 if (*p == ' ')
1908 int len = strlenW( ++p );
1909 in.cbBuffer = decode_base64( p, len, NULL );
1910 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) {
1911 destroy_authinfo( authinfo );
1912 *auth_ptr = NULL;
1913 return FALSE;
1915 decode_base64( p, len, in.pvBuffer );
1917 out.BufferType = SECBUFFER_TOKEN;
1918 out.cbBuffer = authinfo->max_token;
1919 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1921 heap_free( in.pvBuffer );
1922 destroy_authinfo( authinfo );
1923 *auth_ptr = NULL;
1924 return FALSE;
1926 out_desc.ulVersion = 0;
1927 out_desc.cBuffers = 1;
1928 out_desc.pBuffers = &out;
1930 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1931 first ? request->connect->servername : NULL, flags, 0,
1932 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1933 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1934 heap_free( in.pvBuffer );
1935 if (status == SEC_E_OK)
1937 heap_free( authinfo->data );
1938 authinfo->data = out.pvBuffer;
1939 authinfo->data_len = out.cbBuffer;
1940 authinfo->finished = TRUE;
1941 TRACE("sending last auth packet\n");
1943 else if (status == SEC_I_CONTINUE_NEEDED)
1945 heap_free( authinfo->data );
1946 authinfo->data = out.pvBuffer;
1947 authinfo->data_len = out.cbBuffer;
1948 TRACE("sending next auth packet\n");
1950 else
1952 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1953 heap_free( out.pvBuffer );
1954 destroy_authinfo( authinfo );
1955 *auth_ptr = NULL;
1956 return FALSE;
1958 break;
1960 default:
1961 ERR("invalid scheme %u\n", scheme);
1962 return FALSE;
1964 *auth_ptr = authinfo;
1966 len_scheme = auth_schemes[authinfo->scheme].len;
1967 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1968 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1970 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1971 auth_reply[len_scheme] = ' ';
1972 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1974 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1975 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1976 heap_free( auth_reply );
1977 return ret;
1980 static BOOL set_credentials( request_t *request, DWORD target, DWORD scheme_flag, const WCHAR *username,
1981 const WCHAR *password )
1983 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1985 if (scheme == SCHEME_INVALID || ((scheme == SCHEME_BASIC || scheme == SCHEME_DIGEST) && (!username || !password)))
1987 set_last_error( ERROR_INVALID_PARAMETER );
1988 return FALSE;
1990 switch (target)
1992 case WINHTTP_AUTH_TARGET_SERVER:
1994 heap_free( request->creds[TARGET_SERVER][scheme].username );
1995 if (!username) request->creds[TARGET_SERVER][scheme].username = NULL;
1996 else if (!(request->creds[TARGET_SERVER][scheme].username = strdupW( username ))) return FALSE;
1998 heap_free( request->creds[TARGET_SERVER][scheme].password );
1999 if (!password) request->creds[TARGET_SERVER][scheme].password = NULL;
2000 else if (!(request->creds[TARGET_SERVER][scheme].password = strdupW( password ))) return FALSE;
2001 break;
2003 case WINHTTP_AUTH_TARGET_PROXY:
2005 heap_free( request->creds[TARGET_PROXY][scheme].username );
2006 if (!username) request->creds[TARGET_PROXY][scheme].username = NULL;
2007 else if (!(request->creds[TARGET_PROXY][scheme].username = strdupW( username ))) return FALSE;
2009 heap_free( request->creds[TARGET_PROXY][scheme].password );
2010 if (!password) request->creds[TARGET_PROXY][scheme].password = NULL;
2011 else if (!(request->creds[TARGET_PROXY][scheme].password = strdupW( password ))) return FALSE;
2012 break;
2014 default:
2015 WARN("unknown target %u\n", target);
2016 return FALSE;
2018 return TRUE;
2021 /***********************************************************************
2022 * WinHttpSetCredentials (winhttp.@)
2024 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
2025 LPCWSTR password, LPVOID params )
2027 BOOL ret;
2028 request_t *request;
2030 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
2032 if (!(request = (request_t *)grab_object( hrequest )))
2034 set_last_error( ERROR_INVALID_HANDLE );
2035 return FALSE;
2037 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2039 release_object( &request->hdr );
2040 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2041 return FALSE;
2044 ret = set_credentials( request, target, scheme, username, password );
2046 release_object( &request->hdr );
2047 if (ret) set_last_error( ERROR_SUCCESS );
2048 return ret;
2051 static BOOL handle_authorization( request_t *request, DWORD status )
2053 DWORD i, schemes, first, level, target;
2055 switch (status)
2057 case HTTP_STATUS_DENIED:
2058 target = WINHTTP_AUTH_TARGET_SERVER;
2059 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
2060 break;
2062 case HTTP_STATUS_PROXY_AUTH_REQ:
2063 target = WINHTTP_AUTH_TARGET_PROXY;
2064 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
2065 break;
2067 default:
2068 WARN("unhandled status %u\n", status);
2069 return FALSE;
2072 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
2073 if (do_authorization( request, target, first )) return TRUE;
2075 schemes &= ~first;
2076 for (i = 0; i < num_auth_schemes; i++)
2078 if (!(schemes & auth_schemes[i].scheme)) continue;
2079 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
2081 return FALSE;
2084 /* set the request content length based on the headers */
2085 static DWORD set_content_length( request_t *request, DWORD status )
2087 WCHAR encoding[20];
2088 DWORD buflen = sizeof(request->content_length);
2090 if (status == HTTP_STATUS_NO_CONTENT || status == HTTP_STATUS_NOT_MODIFIED || !strcmpW( request->verb, headW ))
2091 request->content_length = 0;
2092 else
2094 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
2095 NULL, &request->content_length, &buflen, NULL ))
2096 request->content_length = ~0u;
2098 buflen = sizeof(encoding);
2099 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
2100 !strcmpiW( encoding, chunkedW ))
2102 request->content_length = ~0u;
2103 request->read_chunked = TRUE;
2104 request->read_chunked_size = ~0u;
2105 request->read_chunked_eof = FALSE;
2108 request->content_read = 0;
2109 return request->content_length;
2112 static BOOL read_line( request_t *request, char *buffer, DWORD *len )
2114 int count, bytes_read, pos = 0;
2116 for (;;)
2118 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
2119 if (eol)
2121 count = eol - (request->read_buf + request->read_pos);
2122 bytes_read = count + 1;
2124 else count = bytes_read = request->read_size;
2126 count = min( count, *len - pos );
2127 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
2128 pos += count;
2129 remove_data( request, bytes_read );
2130 if (eol) break;
2132 if (!read_more_data( request, -1, TRUE )) return FALSE;
2133 if (!request->read_size)
2135 *len = 0;
2136 TRACE("returning empty string\n");
2137 return FALSE;
2140 if (pos < *len)
2142 if (pos && buffer[pos - 1] == '\r') pos--;
2143 *len = pos + 1;
2145 buffer[*len - 1] = 0;
2146 TRACE("returning %s\n", debugstr_a(buffer));
2147 return TRUE;
2150 #define MAX_REPLY_LEN 1460
2151 #define INITIAL_HEADER_BUFFER_LEN 512
2153 static BOOL read_reply( request_t *request )
2155 static const WCHAR crlf[] = {'\r','\n',0};
2157 char buffer[MAX_REPLY_LEN];
2158 DWORD buflen, len, offset, crlf_len = 2; /* strlenW(crlf) */
2159 char *status_code, *status_text;
2160 WCHAR *versionW, *status_textW, *raw_headers;
2161 WCHAR status_codeW[4]; /* sizeof("nnn") */
2163 if (!netconn_connected( &request->netconn )) return FALSE;
2167 buflen = MAX_REPLY_LEN;
2168 if (!read_line( request, buffer, &buflen )) return FALSE;
2170 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2171 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
2172 status_code++;
2173 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
2174 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
2175 status_text++;
2177 TRACE("version [%s] status code [%s] status text [%s]\n",
2178 debugstr_an(buffer, status_code - buffer - 1),
2179 debugstr_an(status_code, len),
2180 debugstr_a(status_text));
2182 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
2184 /* we rely on the fact that the protocol is ascii */
2185 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2186 status_codeW[len] = 0;
2187 if (!(process_header( request, attr_status, status_codeW,
2188 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE, FALSE )))
2189 return FALSE;
2191 len = status_code - buffer;
2192 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2193 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2194 versionW[len - 1] = 0;
2196 heap_free( request->version );
2197 request->version = versionW;
2199 len = buflen - (status_text - buffer);
2200 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2201 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2203 heap_free( request->status_text );
2204 request->status_text = status_textW;
2206 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2207 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2208 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2209 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2211 heap_free( request->raw_headers );
2212 request->raw_headers = raw_headers;
2214 offset = buflen + crlf_len - 1;
2215 for (;;)
2217 header_t *header;
2219 buflen = MAX_REPLY_LEN;
2220 if (!read_line( request, buffer, &buflen )) return TRUE;
2221 if (!*buffer) buflen = 1;
2223 while (len - offset < buflen + crlf_len)
2225 WCHAR *tmp;
2226 len *= 2;
2227 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2228 request->raw_headers = raw_headers = tmp;
2230 if (!*buffer)
2232 memcpy( raw_headers + offset, crlf, sizeof(crlf) );
2233 break;
2235 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2237 if (!(header = parse_header( raw_headers + offset ))) break;
2238 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2240 free_header( header );
2241 break;
2243 free_header( header );
2244 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2245 offset += buflen + crlf_len - 1;
2248 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2249 return TRUE;
2252 static void record_cookies( request_t *request )
2254 unsigned int i;
2256 for (i = 0; i < request->num_headers; i++)
2258 header_t *set_cookie = &request->headers[i];
2259 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2261 set_cookies( request, set_cookie->value );
2266 static WCHAR *get_redirect_url( request_t *request, DWORD *len )
2268 DWORD size;
2269 WCHAR *ret;
2271 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2272 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2273 if (!(ret = heap_alloc( size ))) return NULL;
2274 *len = size / sizeof(WCHAR);
2275 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2276 heap_free( ret );
2277 return NULL;
2280 static BOOL handle_redirect( request_t *request, DWORD status )
2282 BOOL ret = FALSE;
2283 DWORD len, len_url;
2284 URL_COMPONENTS uc;
2285 connect_t *connect = request->connect;
2286 INTERNET_PORT port;
2287 WCHAR *hostname = NULL, *location;
2288 int index;
2290 if (!(location = get_redirect_url( request, &len_url ))) return FALSE;
2292 memset( &uc, 0, sizeof(uc) );
2293 uc.dwStructSize = sizeof(uc);
2294 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2296 if (!WinHttpCrackUrl( location, len_url, 0, &uc )) /* assume relative redirect */
2298 WCHAR *path, *p;
2300 if (location[0] == '/')
2302 len = strlenW( location );
2303 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2304 strcpyW( path, location );
2306 else
2308 if ((p = strrchrW( request->path, '/' ))) *p = 0;
2309 len = strlenW( request->path ) + 1 + strlenW( location );
2310 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2311 strcpyW( path, request->path );
2312 strcatW( path, slashW );
2313 strcatW( path, location );
2315 heap_free( request->path );
2316 request->path = path;
2318 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2320 else
2322 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2324 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2325 TRACE("redirect from secure page to non-secure page\n");
2326 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2328 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2330 TRACE("redirect from non-secure page to secure page\n");
2331 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2334 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2336 len = uc.dwHostNameLength;
2337 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2338 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2339 hostname[len] = 0;
2341 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2342 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2344 heap_free( connect->hostname );
2345 connect->hostname = hostname;
2346 connect->hostport = port;
2347 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2349 netconn_close( &request->netconn );
2350 if (!(ret = netconn_init( &request->netconn ))) goto end;
2351 request->read_pos = request->read_size = 0;
2352 request->read_chunked = FALSE;
2353 request->read_chunked_eof = FALSE;
2355 else heap_free( hostname );
2357 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2358 if (!(ret = open_connection( request ))) goto end;
2360 heap_free( request->path );
2361 request->path = NULL;
2362 if (uc.dwUrlPathLength)
2364 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2365 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2366 strcpyW( request->path, uc.lpszUrlPath );
2368 else request->path = strdupW( slashW );
2371 /* remove content-type/length headers */
2372 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2373 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2375 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2377 heap_free( request->verb );
2378 request->verb = strdupW( getW );
2379 request->optional = NULL;
2380 request->optional_len = 0;
2382 ret = TRUE;
2384 end:
2385 heap_free( location );
2386 return ret;
2389 static BOOL receive_response( request_t *request, BOOL async )
2391 BOOL ret;
2392 DWORD size, query, status;
2394 for (;;)
2396 if (!(ret = read_reply( request )))
2398 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2399 break;
2401 size = sizeof(DWORD);
2402 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2403 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2405 set_content_length( request, status );
2407 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2409 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2411 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2412 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2414 if (!(ret = handle_redirect( request, status ))) break;
2416 /* recurse synchronously */
2417 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2419 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2421 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2423 if (!handle_authorization( request, status )) break;
2425 /* recurse synchronously */
2426 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2428 break;
2431 if (request->content_length) refill_buffer( request, FALSE );
2433 if (async)
2435 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2436 else
2438 WINHTTP_ASYNC_RESULT result;
2439 result.dwResult = API_RECEIVE_RESPONSE;
2440 result.dwError = get_last_error();
2441 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2444 return ret;
2447 static void task_receive_response( task_header_t *task )
2449 receive_response_t *r = (receive_response_t *)task;
2450 receive_response( r->hdr.request, TRUE );
2453 /***********************************************************************
2454 * WinHttpReceiveResponse (winhttp.@)
2456 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2458 BOOL ret;
2459 request_t *request;
2461 TRACE("%p, %p\n", hrequest, reserved);
2463 if (!(request = (request_t *)grab_object( hrequest )))
2465 set_last_error( ERROR_INVALID_HANDLE );
2466 return FALSE;
2468 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2470 release_object( &request->hdr );
2471 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2472 return FALSE;
2475 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2477 receive_response_t *r;
2479 if (!(r = heap_alloc( sizeof(receive_response_t) ))) return FALSE;
2480 r->hdr.request = request;
2481 r->hdr.proc = task_receive_response;
2483 addref_object( &request->hdr );
2484 ret = queue_task( (task_header_t *)r );
2486 else
2487 ret = receive_response( request, FALSE );
2489 release_object( &request->hdr );
2490 if (ret) set_last_error( ERROR_SUCCESS );
2491 return ret;
2494 static BOOL query_data_available( request_t *request, DWORD *available, BOOL async )
2496 DWORD count = 0;
2498 if (end_of_read_data( request )) goto done;
2500 count = get_available_data( request );
2501 if (!request->read_chunked)
2502 count += netconn_query_data_available( &request->netconn );
2503 if (!count)
2505 refill_buffer( request, async );
2506 count = get_available_data( request );
2507 if (!request->read_chunked)
2508 count += netconn_query_data_available( &request->netconn );
2511 done:
2512 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2513 TRACE("%u bytes available\n", count);
2514 if (available) *available = count;
2515 return TRUE;
2518 static void task_query_data_available( task_header_t *task )
2520 query_data_t *q = (query_data_t *)task;
2521 query_data_available( q->hdr.request, q->available, TRUE );
2524 /***********************************************************************
2525 * WinHttpQueryDataAvailable (winhttp.@)
2527 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2529 BOOL ret;
2530 request_t *request;
2532 TRACE("%p, %p\n", hrequest, available);
2534 if (!(request = (request_t *)grab_object( hrequest )))
2536 set_last_error( ERROR_INVALID_HANDLE );
2537 return FALSE;
2539 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2541 release_object( &request->hdr );
2542 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2543 return FALSE;
2546 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2548 query_data_t *q;
2550 if (!(q = heap_alloc( sizeof(query_data_t) ))) return FALSE;
2551 q->hdr.request = request;
2552 q->hdr.proc = task_query_data_available;
2553 q->available = available;
2555 addref_object( &request->hdr );
2556 ret = queue_task( (task_header_t *)q );
2558 else
2559 ret = query_data_available( request, available, FALSE );
2561 release_object( &request->hdr );
2562 if (ret) set_last_error( ERROR_SUCCESS );
2563 return ret;
2566 static void task_read_data( task_header_t *task )
2568 read_data_t *r = (read_data_t *)task;
2569 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2572 /***********************************************************************
2573 * WinHttpReadData (winhttp.@)
2575 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2577 BOOL ret;
2578 request_t *request;
2580 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2582 if (!(request = (request_t *)grab_object( hrequest )))
2584 set_last_error( ERROR_INVALID_HANDLE );
2585 return FALSE;
2587 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2589 release_object( &request->hdr );
2590 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2591 return FALSE;
2594 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2596 read_data_t *r;
2598 if (!(r = heap_alloc( sizeof(read_data_t) ))) return FALSE;
2599 r->hdr.request = request;
2600 r->hdr.proc = task_read_data;
2601 r->buffer = buffer;
2602 r->to_read = to_read;
2603 r->read = read;
2605 addref_object( &request->hdr );
2606 ret = queue_task( (task_header_t *)r );
2608 else
2609 ret = read_data( request, buffer, to_read, read, FALSE );
2611 release_object( &request->hdr );
2612 if (ret) set_last_error( ERROR_SUCCESS );
2613 return ret;
2616 static BOOL write_data( request_t *request, LPCVOID buffer, DWORD to_write, LPDWORD written, BOOL async )
2618 BOOL ret;
2619 int num_bytes;
2621 ret = netconn_send( &request->netconn, buffer, to_write, &num_bytes );
2623 if (async)
2625 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
2626 else
2628 WINHTTP_ASYNC_RESULT result;
2629 result.dwResult = API_WRITE_DATA;
2630 result.dwError = get_last_error();
2631 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2634 if (ret && written) *written = num_bytes;
2635 return ret;
2638 static void task_write_data( task_header_t *task )
2640 write_data_t *w = (write_data_t *)task;
2641 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
2644 /***********************************************************************
2645 * WinHttpWriteData (winhttp.@)
2647 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
2649 BOOL ret;
2650 request_t *request;
2652 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
2654 if (!(request = (request_t *)grab_object( hrequest )))
2656 set_last_error( ERROR_INVALID_HANDLE );
2657 return FALSE;
2659 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2661 release_object( &request->hdr );
2662 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2663 return FALSE;
2666 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2668 write_data_t *w;
2670 if (!(w = heap_alloc( sizeof(write_data_t) ))) return FALSE;
2671 w->hdr.request = request;
2672 w->hdr.proc = task_write_data;
2673 w->buffer = buffer;
2674 w->to_write = to_write;
2675 w->written = written;
2677 addref_object( &request->hdr );
2678 ret = queue_task( (task_header_t *)w );
2680 else
2681 ret = write_data( request, buffer, to_write, written, FALSE );
2683 release_object( &request->hdr );
2684 if (ret) set_last_error( ERROR_SUCCESS );
2685 return ret;
2688 enum request_state
2690 REQUEST_STATE_UNINITIALIZED,
2691 REQUEST_STATE_INITIALIZED,
2692 REQUEST_STATE_CANCELLED,
2693 REQUEST_STATE_OPEN,
2694 REQUEST_STATE_SENT,
2695 REQUEST_STATE_RESPONSE_RECEIVED
2698 struct winhttp_request
2700 IWinHttpRequest IWinHttpRequest_iface;
2701 LONG refs;
2702 CRITICAL_SECTION cs;
2703 enum request_state state;
2704 HINTERNET hsession;
2705 HINTERNET hconnect;
2706 HINTERNET hrequest;
2707 VARIANT data;
2708 WCHAR *verb;
2709 HANDLE thread;
2710 HANDLE wait;
2711 HANDLE cancel;
2712 char *buffer;
2713 DWORD offset;
2714 DWORD bytes_available;
2715 DWORD bytes_read;
2716 DWORD error;
2717 DWORD logon_policy;
2718 DWORD disable_feature;
2719 LONG resolve_timeout;
2720 LONG connect_timeout;
2721 LONG send_timeout;
2722 LONG receive_timeout;
2723 WINHTTP_PROXY_INFO proxy;
2724 BOOL async;
2725 UINT url_codepage;
2728 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
2730 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
2733 static ULONG WINAPI winhttp_request_AddRef(
2734 IWinHttpRequest *iface )
2736 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2737 return InterlockedIncrement( &request->refs );
2740 /* critical section must be held */
2741 static void cancel_request( struct winhttp_request *request )
2743 if (request->state <= REQUEST_STATE_CANCELLED) return;
2745 SetEvent( request->cancel );
2746 LeaveCriticalSection( &request->cs );
2747 WaitForSingleObject( request->thread, INFINITE );
2748 EnterCriticalSection( &request->cs );
2750 request->state = REQUEST_STATE_CANCELLED;
2752 CloseHandle( request->thread );
2753 request->thread = NULL;
2754 CloseHandle( request->wait );
2755 request->wait = NULL;
2756 CloseHandle( request->cancel );
2757 request->cancel = NULL;
2760 /* critical section must be held */
2761 static void free_request( struct winhttp_request *request )
2763 if (request->state < REQUEST_STATE_INITIALIZED) return;
2764 WinHttpCloseHandle( request->hrequest );
2765 WinHttpCloseHandle( request->hconnect );
2766 WinHttpCloseHandle( request->hsession );
2767 CloseHandle( request->thread );
2768 CloseHandle( request->wait );
2769 CloseHandle( request->cancel );
2770 heap_free( request->proxy.lpszProxy );
2771 heap_free( request->proxy.lpszProxyBypass );
2772 heap_free( request->buffer );
2773 heap_free( request->verb );
2774 VariantClear( &request->data );
2777 static ULONG WINAPI winhttp_request_Release(
2778 IWinHttpRequest *iface )
2780 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2781 LONG refs = InterlockedDecrement( &request->refs );
2782 if (!refs)
2784 TRACE("destroying %p\n", request);
2786 EnterCriticalSection( &request->cs );
2787 cancel_request( request );
2788 free_request( request );
2789 LeaveCriticalSection( &request->cs );
2790 request->cs.DebugInfo->Spare[0] = 0;
2791 DeleteCriticalSection( &request->cs );
2792 heap_free( request );
2794 return refs;
2797 static HRESULT WINAPI winhttp_request_QueryInterface(
2798 IWinHttpRequest *iface,
2799 REFIID riid,
2800 void **obj )
2802 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2804 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
2806 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
2807 IsEqualGUID( riid, &IID_IDispatch ) ||
2808 IsEqualGUID( riid, &IID_IUnknown ))
2810 *obj = iface;
2812 else
2814 FIXME("interface %s not implemented\n", debugstr_guid(riid));
2815 return E_NOINTERFACE;
2817 IWinHttpRequest_AddRef( iface );
2818 return S_OK;
2821 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
2822 IWinHttpRequest *iface,
2823 UINT *count )
2825 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2827 TRACE("%p, %p\n", request, count);
2828 *count = 1;
2829 return S_OK;
2832 enum type_id
2834 IWinHttpRequest_tid,
2835 last_tid
2838 static ITypeLib *winhttp_typelib;
2839 static ITypeInfo *winhttp_typeinfo[last_tid];
2841 static REFIID winhttp_tid_id[] =
2843 &IID_IWinHttpRequest
2846 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
2848 HRESULT hr;
2850 if (!winhttp_typelib)
2852 ITypeLib *typelib;
2854 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
2855 if (FAILED(hr))
2857 ERR("LoadRegTypeLib failed: %08x\n", hr);
2858 return hr;
2860 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
2861 ITypeLib_Release( typelib );
2863 if (!winhttp_typeinfo[tid])
2865 ITypeInfo *typeinfo;
2867 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
2868 if (FAILED(hr))
2870 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
2871 return hr;
2873 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
2874 ITypeInfo_Release( typeinfo );
2876 *ret = winhttp_typeinfo[tid];
2877 ITypeInfo_AddRef(winhttp_typeinfo[tid]);
2878 return S_OK;
2881 void release_typelib(void)
2883 unsigned i;
2885 for (i = 0; i < sizeof(winhttp_typeinfo)/sizeof(*winhttp_typeinfo); i++)
2886 if (winhttp_typeinfo[i])
2887 ITypeInfo_Release(winhttp_typeinfo[i]);
2889 if (winhttp_typelib)
2890 ITypeLib_Release(winhttp_typelib);
2893 static HRESULT WINAPI winhttp_request_GetTypeInfo(
2894 IWinHttpRequest *iface,
2895 UINT index,
2896 LCID lcid,
2897 ITypeInfo **info )
2899 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2900 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
2902 return get_typeinfo( IWinHttpRequest_tid, info );
2905 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
2906 IWinHttpRequest *iface,
2907 REFIID riid,
2908 LPOLESTR *names,
2909 UINT count,
2910 LCID lcid,
2911 DISPID *dispid )
2913 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2914 ITypeInfo *typeinfo;
2915 HRESULT hr;
2917 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
2919 if (!names || !count || !dispid) return E_INVALIDARG;
2921 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2922 if (SUCCEEDED(hr))
2924 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
2925 ITypeInfo_Release( typeinfo );
2927 return hr;
2930 static HRESULT WINAPI winhttp_request_Invoke(
2931 IWinHttpRequest *iface,
2932 DISPID member,
2933 REFIID riid,
2934 LCID lcid,
2935 WORD flags,
2936 DISPPARAMS *params,
2937 VARIANT *result,
2938 EXCEPINFO *excep_info,
2939 UINT *arg_err )
2941 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2942 ITypeInfo *typeinfo;
2943 HRESULT hr;
2945 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
2946 lcid, flags, params, result, excep_info, arg_err);
2948 if (!IsEqualIID( riid, &IID_NULL )) return DISP_E_UNKNOWNINTERFACE;
2950 if (member == DISPID_HTTPREQUEST_OPTION)
2952 VARIANT ret_value, option;
2953 UINT err_pos;
2955 if (!result) result = &ret_value;
2956 if (!arg_err) arg_err = &err_pos;
2958 VariantInit( &option );
2959 VariantInit( result );
2961 if (!flags) return S_OK;
2963 if (flags == DISPATCH_PROPERTYPUT)
2965 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
2966 if (FAILED(hr)) return hr;
2968 hr = IWinHttpRequest_put_Option( &request->IWinHttpRequest_iface, V_I4( &option ), params->rgvarg[0] );
2969 if (FAILED(hr))
2970 WARN("put_Option(%d) failed: %x\n", V_I4( &option ), hr);
2971 return hr;
2973 else if (flags & (DISPATCH_PROPERTYGET | DISPATCH_METHOD))
2975 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
2976 if (FAILED(hr)) return hr;
2978 hr = IWinHttpRequest_get_Option( &request->IWinHttpRequest_iface, V_I4( &option ), result );
2979 if (FAILED(hr))
2980 WARN("get_Option(%d) failed: %x\n", V_I4( &option ), hr);
2981 return hr;
2984 FIXME("unsupported flags %x\n", flags);
2985 return E_NOTIMPL;
2988 /* fallback to standard implementation */
2990 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2991 if (SUCCEEDED(hr))
2993 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
2994 params, result, excep_info, arg_err );
2995 ITypeInfo_Release( typeinfo );
2997 return hr;
3000 static HRESULT WINAPI winhttp_request_SetProxy(
3001 IWinHttpRequest *iface,
3002 HTTPREQUEST_PROXY_SETTING proxy_setting,
3003 VARIANT proxy_server,
3004 VARIANT bypass_list )
3006 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3007 DWORD err = ERROR_SUCCESS;
3009 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
3010 debugstr_variant(&bypass_list));
3012 EnterCriticalSection( &request->cs );
3013 switch (proxy_setting)
3015 case HTTPREQUEST_PROXYSETTING_DEFAULT:
3016 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3017 heap_free( request->proxy.lpszProxy );
3018 heap_free( request->proxy.lpszProxyBypass );
3019 request->proxy.lpszProxy = NULL;
3020 request->proxy.lpszProxyBypass = NULL;
3021 break;
3023 case HTTPREQUEST_PROXYSETTING_DIRECT:
3024 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
3025 heap_free( request->proxy.lpszProxy );
3026 heap_free( request->proxy.lpszProxyBypass );
3027 request->proxy.lpszProxy = NULL;
3028 request->proxy.lpszProxyBypass = NULL;
3029 break;
3031 case HTTPREQUEST_PROXYSETTING_PROXY:
3032 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
3033 if (V_VT( &proxy_server ) == VT_BSTR)
3035 heap_free( request->proxy.lpszProxy );
3036 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
3038 if (V_VT( &bypass_list ) == VT_BSTR)
3040 heap_free( request->proxy.lpszProxyBypass );
3041 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
3043 break;
3045 default:
3046 err = ERROR_INVALID_PARAMETER;
3047 break;
3049 LeaveCriticalSection( &request->cs );
3050 return HRESULT_FROM_WIN32( err );
3053 static HRESULT WINAPI winhttp_request_SetCredentials(
3054 IWinHttpRequest *iface,
3055 BSTR username,
3056 BSTR password,
3057 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
3059 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3060 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
3061 DWORD err = ERROR_SUCCESS;
3063 TRACE("%p, %s, %p, 0x%08x\n", request, debugstr_w(username), password, flags);
3065 EnterCriticalSection( &request->cs );
3066 if (request->state < REQUEST_STATE_OPEN)
3068 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3069 goto done;
3071 switch (flags)
3073 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
3074 target = WINHTTP_AUTH_TARGET_SERVER;
3075 break;
3076 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
3077 target = WINHTTP_AUTH_TARGET_PROXY;
3078 break;
3079 default:
3080 err = ERROR_INVALID_PARAMETER;
3081 goto done;
3083 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
3085 err = get_last_error();
3087 done:
3088 LeaveCriticalSection( &request->cs );
3089 return HRESULT_FROM_WIN32( err );
3092 static void initialize_request( struct winhttp_request *request )
3094 request->hrequest = NULL;
3095 request->hconnect = NULL;
3096 request->hsession = NULL;
3097 request->thread = NULL;
3098 request->wait = NULL;
3099 request->cancel = NULL;
3100 request->buffer = NULL;
3101 request->verb = NULL;
3102 request->offset = 0;
3103 request->bytes_available = 0;
3104 request->bytes_read = 0;
3105 request->error = ERROR_SUCCESS;
3106 request->async = FALSE;
3107 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
3108 request->disable_feature = 0;
3109 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3110 request->proxy.lpszProxy = NULL;
3111 request->proxy.lpszProxyBypass = NULL;
3112 request->resolve_timeout = 0;
3113 request->connect_timeout = 60000;
3114 request->send_timeout = 30000;
3115 request->receive_timeout = 30000;
3116 request->url_codepage = CP_UTF8;
3117 VariantInit( &request->data );
3118 request->state = REQUEST_STATE_INITIALIZED;
3121 static void reset_request( struct winhttp_request *request )
3123 cancel_request( request );
3124 WinHttpCloseHandle( request->hrequest );
3125 request->hrequest = NULL;
3126 WinHttpCloseHandle( request->hconnect );
3127 request->hconnect = NULL;
3128 heap_free( request->buffer );
3129 request->buffer = NULL;
3130 heap_free( request->verb );
3131 request->verb = NULL;
3132 request->offset = 0;
3133 request->bytes_available = 0;
3134 request->bytes_read = 0;
3135 request->error = ERROR_SUCCESS;
3136 request->async = FALSE;
3137 request->url_codepage = CP_UTF8;
3138 VariantClear( &request->data );
3139 request->state = REQUEST_STATE_INITIALIZED;
3142 static HRESULT WINAPI winhttp_request_Open(
3143 IWinHttpRequest *iface,
3144 BSTR method,
3145 BSTR url,
3146 VARIANT async )
3148 static const WCHAR typeW[] = {'*','/','*',0};
3149 static const WCHAR *acceptW[] = {typeW, NULL};
3150 static const WCHAR httpsW[] = {'h','t','t','p','s'};
3151 static const WCHAR user_agentW[] = {
3152 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
3153 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
3154 'R','e','q','u','e','s','t','.','5',')',0};
3155 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3156 URL_COMPONENTS uc;
3157 WCHAR *hostname, *path = NULL, *verb = NULL;
3158 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0;
3160 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
3161 debugstr_variant(&async));
3163 if (!method || !url) return E_INVALIDARG;
3165 memset( &uc, 0, sizeof(uc) );
3166 uc.dwStructSize = sizeof(uc);
3167 uc.dwSchemeLength = ~0u;
3168 uc.dwHostNameLength = ~0u;
3169 uc.dwUrlPathLength = ~0u;
3170 uc.dwExtraInfoLength = ~0u;
3171 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( get_last_error() );
3173 EnterCriticalSection( &request->cs );
3174 if (request->state < REQUEST_STATE_INITIALIZED) initialize_request( request );
3175 else reset_request( request );
3177 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
3178 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
3179 hostname[uc.dwHostNameLength] = 0;
3181 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
3182 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
3183 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
3185 if (!(verb = strdupW( method ))) goto error;
3186 if (SUCCEEDED( VariantChangeType( &async, &async, 0, VT_BOOL )) && V_BOOL( &async )) request->async = TRUE;
3187 else request->async = FALSE;
3189 if (!request->hsession)
3191 if (!(request->hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL,
3192 WINHTTP_FLAG_ASYNC )))
3194 err = get_last_error();
3195 goto error;
3197 if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3199 WinHttpCloseHandle( request->hsession );
3200 request->hsession = NULL;
3201 err = get_last_error();
3202 goto error;
3205 else if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3207 err = get_last_error();
3208 goto error;
3211 len = sizeof(httpsW) / sizeof(WCHAR);
3212 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
3214 flags |= WINHTTP_FLAG_SECURE;
3216 if (!(request->hrequest = WinHttpOpenRequest( request->hconnect, method, path, NULL, NULL, acceptW, flags )))
3218 err = get_last_error();
3219 goto error;
3221 WinHttpSetOption( request->hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3223 request->state = REQUEST_STATE_OPEN;
3224 request->verb = verb;
3225 heap_free( hostname );
3226 heap_free( path );
3227 LeaveCriticalSection( &request->cs );
3228 return S_OK;
3230 error:
3231 WinHttpCloseHandle( request->hconnect );
3232 request->hconnect = NULL;
3233 heap_free( hostname );
3234 heap_free( path );
3235 heap_free( verb );
3236 LeaveCriticalSection( &request->cs );
3237 return HRESULT_FROM_WIN32( err );
3240 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3241 IWinHttpRequest *iface,
3242 BSTR header,
3243 BSTR value )
3245 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3246 static const WCHAR emptyW[] = {0};
3247 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3248 DWORD len, err = ERROR_SUCCESS;
3249 WCHAR *str;
3251 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3253 if (!header) return E_INVALIDARG;
3255 EnterCriticalSection( &request->cs );
3256 if (request->state < REQUEST_STATE_OPEN)
3258 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3259 goto done;
3261 if (request->state >= REQUEST_STATE_SENT)
3263 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3264 goto done;
3266 len = strlenW( header ) + 4;
3267 if (value) len += strlenW( value );
3268 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3270 err = ERROR_OUTOFMEMORY;
3271 goto done;
3273 sprintfW( str, fmtW, header, value ? value : emptyW );
3274 if (!WinHttpAddRequestHeaders( request->hrequest, str, len,
3275 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
3277 err = get_last_error();
3279 heap_free( str );
3281 done:
3282 LeaveCriticalSection( &request->cs );
3283 return HRESULT_FROM_WIN32( err );
3286 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3287 IWinHttpRequest *iface,
3288 BSTR header,
3289 BSTR *value )
3291 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3292 DWORD size, err = ERROR_SUCCESS;
3294 TRACE("%p, %p\n", request, header);
3296 EnterCriticalSection( &request->cs );
3297 if (request->state < REQUEST_STATE_SENT)
3299 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3300 goto done;
3302 if (!header || !value)
3304 err = ERROR_INVALID_PARAMETER;
3305 goto done;
3307 size = 0;
3308 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3310 err = get_last_error();
3311 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3313 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3315 err = ERROR_OUTOFMEMORY;
3316 goto done;
3318 err = ERROR_SUCCESS;
3319 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3321 err = get_last_error();
3322 SysFreeString( *value );
3324 done:
3325 LeaveCriticalSection( &request->cs );
3326 return HRESULT_FROM_WIN32( err );
3329 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3330 IWinHttpRequest *iface,
3331 BSTR *headers )
3333 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3334 DWORD size, err = ERROR_SUCCESS;
3336 TRACE("%p, %p\n", request, headers);
3338 if (!headers) return E_INVALIDARG;
3340 EnterCriticalSection( &request->cs );
3341 if (request->state < REQUEST_STATE_SENT)
3343 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3344 goto done;
3346 size = 0;
3347 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3349 err = get_last_error();
3350 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3352 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3354 err = ERROR_OUTOFMEMORY;
3355 goto done;
3357 err = ERROR_SUCCESS;
3358 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3360 err = get_last_error();
3361 SysFreeString( *headers );
3363 done:
3364 LeaveCriticalSection( &request->cs );
3365 return HRESULT_FROM_WIN32( err );
3368 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3370 struct winhttp_request *request = (struct winhttp_request *)context;
3372 switch (status)
3374 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3375 request->bytes_available = *(DWORD *)buffer;
3376 request->error = ERROR_SUCCESS;
3377 break;
3378 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3379 request->bytes_read = size;
3380 request->error = ERROR_SUCCESS;
3381 break;
3382 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3384 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3385 request->error = result->dwError;
3386 break;
3388 default: break;
3390 SetEvent( request->wait );
3393 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3395 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3396 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3399 static DWORD wait_for_completion( struct winhttp_request *request )
3401 HANDLE handles[2] = { request->wait, request->cancel };
3403 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3405 case WAIT_OBJECT_0:
3406 break;
3407 case WAIT_OBJECT_0 + 1:
3408 request->error = ERROR_CANCELLED;
3409 break;
3410 default:
3411 request->error = get_last_error();
3412 break;
3414 return request->error;
3417 static HRESULT request_receive( struct winhttp_request *request )
3419 DWORD err, size, buflen = 4096;
3421 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3422 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3424 return HRESULT_FROM_WIN32( get_last_error() );
3426 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3427 if (!strcmpW( request->verb, headW ))
3429 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3430 return S_OK;
3432 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3433 request->buffer[0] = 0;
3434 size = 0;
3437 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3438 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3440 err = get_last_error();
3441 goto error;
3443 if ((err = wait_for_completion( request ))) goto error;
3444 if (!request->bytes_available) break;
3445 size += request->bytes_available;
3446 if (buflen < size)
3448 char *tmp;
3449 while (buflen < size) buflen *= 2;
3450 if (!(tmp = heap_realloc( request->buffer, buflen )))
3452 err = ERROR_OUTOFMEMORY;
3453 goto error;
3455 request->buffer = tmp;
3457 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3458 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3459 request->bytes_available, &request->bytes_read ))
3461 err = get_last_error();
3462 goto error;
3464 if ((err = wait_for_completion( request ))) goto error;
3465 request->offset += request->bytes_read;
3466 } while (request->bytes_read);
3468 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3469 return S_OK;
3471 error:
3472 heap_free( request->buffer );
3473 request->buffer = NULL;
3474 return HRESULT_FROM_WIN32( err );
3477 static DWORD request_set_parameters( struct winhttp_request *request )
3479 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3480 sizeof(request->proxy) )) return get_last_error();
3482 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3483 sizeof(request->logon_policy) )) return get_last_error();
3485 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3486 sizeof(request->disable_feature) )) return get_last_error();
3488 if (!WinHttpSetTimeouts( request->hrequest,
3489 request->resolve_timeout,
3490 request->connect_timeout,
3491 request->send_timeout,
3492 request->receive_timeout )) return get_last_error();
3493 return ERROR_SUCCESS;
3496 static void request_set_utf8_content_type( struct winhttp_request *request )
3498 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3499 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3500 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3501 WCHAR headerW[64];
3502 int len;
3504 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3505 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3506 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3507 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3510 static HRESULT request_send( struct winhttp_request *request )
3512 SAFEARRAY *sa = NULL;
3513 VARIANT data;
3514 char *ptr = NULL;
3515 LONG size = 0;
3516 HRESULT hr;
3517 DWORD err;
3519 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3520 if (strcmpW( request->verb, getW ))
3522 VariantInit( &data );
3523 if (V_VT( &request->data ) == VT_BSTR)
3525 UINT cp = CP_ACP;
3526 const WCHAR *str = V_BSTR( &request->data );
3527 int i, len = strlenW( str );
3529 for (i = 0; i < len; i++)
3531 if (str[i] > 127)
3533 cp = CP_UTF8;
3534 break;
3537 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3538 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3539 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3540 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3542 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3544 sa = V_ARRAY( &data );
3545 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3546 if ((hr = SafeArrayGetUBound( sa, 1, &size )) != S_OK)
3548 SafeArrayUnaccessData( sa );
3549 return hr;
3551 size++;
3554 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3555 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3557 err = get_last_error();
3558 goto error;
3560 if ((err = wait_for_completion( request ))) goto error;
3561 if (sa) SafeArrayUnaccessData( sa );
3562 else heap_free( ptr );
3563 request->state = REQUEST_STATE_SENT;
3564 return S_OK;
3566 error:
3567 if (sa) SafeArrayUnaccessData( sa );
3568 else heap_free( ptr );
3569 return HRESULT_FROM_WIN32( err );
3572 static HRESULT request_send_and_receive( struct winhttp_request *request )
3574 HRESULT hr = request_send( request );
3575 if (hr == S_OK) hr = request_receive( request );
3576 return hr;
3579 static DWORD CALLBACK send_and_receive_proc( void *arg )
3581 struct winhttp_request *request = (struct winhttp_request *)arg;
3582 return request_send_and_receive( request );
3585 /* critical section must be held */
3586 static DWORD request_wait( struct winhttp_request *request, DWORD timeout )
3588 HANDLE thread = request->thread;
3589 DWORD err, ret;
3591 LeaveCriticalSection( &request->cs );
3592 while ((err = MsgWaitForMultipleObjects( 1, &thread, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3594 MSG msg;
3595 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3597 TranslateMessage( &msg );
3598 DispatchMessageW( &msg );
3601 switch (err)
3603 case WAIT_OBJECT_0:
3604 ret = ERROR_SUCCESS;
3605 break;
3606 case WAIT_TIMEOUT:
3607 ret = ERROR_TIMEOUT;
3608 break;
3609 case WAIT_FAILED:
3610 default:
3611 ret = get_last_error();
3612 break;
3614 EnterCriticalSection( &request->cs );
3615 return ret;
3618 static HRESULT WINAPI winhttp_request_Send(
3619 IWinHttpRequest *iface,
3620 VARIANT body )
3622 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3623 HRESULT hr;
3625 TRACE("%p, %s\n", request, debugstr_variant(&body));
3627 EnterCriticalSection( &request->cs );
3628 if (request->state < REQUEST_STATE_OPEN)
3630 LeaveCriticalSection( &request->cs );
3631 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3633 if (request->state >= REQUEST_STATE_SENT)
3635 LeaveCriticalSection( &request->cs );
3636 return S_OK;
3638 VariantClear( &request->data );
3639 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK)
3641 LeaveCriticalSection( &request->cs );
3642 return hr;
3644 if (!(request->thread = CreateThread( NULL, 0, send_and_receive_proc, request, 0, NULL )))
3646 LeaveCriticalSection( &request->cs );
3647 return HRESULT_FROM_WIN32( get_last_error() );
3649 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3650 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3651 if (!request->async)
3653 hr = HRESULT_FROM_WIN32( request_wait( request, INFINITE ) );
3655 LeaveCriticalSection( &request->cs );
3656 return hr;
3659 static HRESULT WINAPI winhttp_request_get_Status(
3660 IWinHttpRequest *iface,
3661 LONG *status )
3663 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3664 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
3666 TRACE("%p, %p\n", request, status);
3668 if (!status) return E_INVALIDARG;
3670 EnterCriticalSection( &request->cs );
3671 if (request->state < REQUEST_STATE_SENT)
3673 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3674 goto done;
3676 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
3677 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
3679 err = get_last_error();
3680 goto done;
3682 *status = status_code;
3684 done:
3685 LeaveCriticalSection( &request->cs );
3686 return HRESULT_FROM_WIN32( err );
3689 static HRESULT WINAPI winhttp_request_get_StatusText(
3690 IWinHttpRequest *iface,
3691 BSTR *status )
3693 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3694 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
3696 TRACE("%p, %p\n", request, status);
3698 if (!status) return E_INVALIDARG;
3700 EnterCriticalSection( &request->cs );
3701 if (request->state < REQUEST_STATE_SENT)
3703 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3704 goto done;
3706 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
3708 err = get_last_error();
3709 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3711 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
3713 err = ERROR_OUTOFMEMORY;
3714 goto done;
3716 index = 0;
3717 err = ERROR_SUCCESS;
3718 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
3720 err = get_last_error();
3721 SysFreeString( *status );
3723 done:
3724 LeaveCriticalSection( &request->cs );
3725 return HRESULT_FROM_WIN32( err );
3728 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
3730 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
3731 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
3732 WCHAR *buffer, *p;
3733 DWORD size;
3735 *codepage = CP_ACP;
3736 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
3737 get_last_error() == ERROR_INSUFFICIENT_BUFFER)
3739 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
3740 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
3742 return get_last_error();
3744 if ((p = strstrW( buffer, charsetW )))
3746 p += strlenW( charsetW );
3747 while (*p == ' ') p++;
3748 if (*p++ == '=')
3750 while (*p == ' ') p++;
3751 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
3754 heap_free( buffer );
3756 return ERROR_SUCCESS;
3759 static HRESULT WINAPI winhttp_request_get_ResponseText(
3760 IWinHttpRequest *iface,
3761 BSTR *body )
3763 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3764 UINT codepage;
3765 DWORD err = ERROR_SUCCESS;
3766 int len;
3768 TRACE("%p, %p\n", request, body);
3770 if (!body) return E_INVALIDARG;
3772 EnterCriticalSection( &request->cs );
3773 if (request->state < REQUEST_STATE_SENT)
3775 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3776 goto done;
3778 if ((err = request_get_codepage( request, &codepage ))) goto done;
3779 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
3780 if (!(*body = SysAllocStringLen( NULL, len )))
3782 err = ERROR_OUTOFMEMORY;
3783 goto done;
3785 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
3786 (*body)[len] = 0;
3788 done:
3789 LeaveCriticalSection( &request->cs );
3790 return HRESULT_FROM_WIN32( err );
3793 static HRESULT WINAPI winhttp_request_get_ResponseBody(
3794 IWinHttpRequest *iface,
3795 VARIANT *body )
3797 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3798 SAFEARRAY *sa;
3799 HRESULT hr;
3800 DWORD err = ERROR_SUCCESS;
3801 char *ptr;
3803 TRACE("%p, %p\n", request, body);
3805 if (!body) return E_INVALIDARG;
3807 EnterCriticalSection( &request->cs );
3808 if (request->state < REQUEST_STATE_SENT)
3810 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3811 goto done;
3813 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
3815 err = ERROR_OUTOFMEMORY;
3816 goto done;
3818 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
3820 SafeArrayDestroy( sa );
3821 LeaveCriticalSection( &request->cs );
3822 return hr;
3824 memcpy( ptr, request->buffer, request->offset );
3825 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
3827 SafeArrayDestroy( sa );
3828 LeaveCriticalSection( &request->cs );
3829 return hr;
3831 V_VT( body ) = VT_ARRAY|VT_UI1;
3832 V_ARRAY( body ) = sa;
3834 done:
3835 LeaveCriticalSection( &request->cs );
3836 return HRESULT_FROM_WIN32( err );
3839 struct stream
3841 IStream IStream_iface;
3842 LONG refs;
3843 char *data;
3844 ULARGE_INTEGER pos, size;
3847 static inline struct stream *impl_from_IStream( IStream *iface )
3849 return CONTAINING_RECORD( iface, struct stream, IStream_iface );
3852 static HRESULT WINAPI stream_QueryInterface( IStream *iface, REFIID riid, void **obj )
3854 struct stream *stream = impl_from_IStream( iface );
3856 TRACE("%p, %s, %p\n", stream, debugstr_guid(riid), obj);
3858 if (IsEqualGUID( riid, &IID_IStream ) || IsEqualGUID( riid, &IID_IUnknown ))
3860 *obj = iface;
3862 else
3864 FIXME("interface %s not implemented\n", debugstr_guid(riid));
3865 return E_NOINTERFACE;
3867 IStream_AddRef( iface );
3868 return S_OK;
3871 static ULONG WINAPI stream_AddRef( IStream *iface )
3873 struct stream *stream = impl_from_IStream( iface );
3874 return InterlockedIncrement( &stream->refs );
3877 static ULONG WINAPI stream_Release( IStream *iface )
3879 struct stream *stream = impl_from_IStream( iface );
3880 LONG refs = InterlockedDecrement( &stream->refs );
3881 if (!refs)
3883 heap_free( stream->data );
3884 heap_free( stream );
3886 return refs;
3889 static HRESULT WINAPI stream_Read( IStream *iface, void *buf, ULONG len, ULONG *read )
3891 struct stream *stream = impl_from_IStream( iface );
3892 ULONG size;
3894 if (stream->pos.QuadPart >= stream->size.QuadPart)
3896 *read = 0;
3897 return S_FALSE;
3900 size = min( stream->size.QuadPart - stream->pos.QuadPart, len );
3901 memcpy( buf, stream->data + stream->pos.QuadPart, size );
3902 stream->pos.QuadPart += size;
3903 *read = size;
3905 return S_OK;
3908 static HRESULT WINAPI stream_Write( IStream *iface, const void *buf, ULONG len, ULONG *written )
3910 FIXME("\n");
3911 return E_NOTIMPL;
3914 static HRESULT WINAPI stream_Seek( IStream *iface, LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *newpos )
3916 struct stream *stream = impl_from_IStream( iface );
3918 if (origin == STREAM_SEEK_SET)
3919 stream->pos.QuadPart = move.QuadPart;
3920 else if (origin == STREAM_SEEK_CUR)
3921 stream->pos.QuadPart += move.QuadPart;
3922 else if (origin == STREAM_SEEK_END)
3923 stream->pos.QuadPart = stream->size.QuadPart - move.QuadPart;
3925 if (newpos) newpos->QuadPart = stream->pos.QuadPart;
3926 return S_OK;
3929 static HRESULT WINAPI stream_SetSize( IStream *iface, ULARGE_INTEGER newsize )
3931 FIXME("\n");
3932 return E_NOTIMPL;
3935 static HRESULT WINAPI stream_CopyTo( IStream *iface, IStream *stream, ULARGE_INTEGER len, ULARGE_INTEGER *read,
3936 ULARGE_INTEGER *written )
3938 FIXME("\n");
3939 return E_NOTIMPL;
3942 static HRESULT WINAPI stream_Commit( IStream *iface, DWORD flags )
3944 FIXME("\n");
3945 return E_NOTIMPL;
3948 static HRESULT WINAPI stream_Revert( IStream *iface )
3950 FIXME("\n");
3951 return E_NOTIMPL;
3954 static HRESULT WINAPI stream_LockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
3956 FIXME("\n");
3957 return E_NOTIMPL;
3960 static HRESULT WINAPI stream_UnlockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
3962 FIXME("\n");
3963 return E_NOTIMPL;
3966 static HRESULT WINAPI stream_Stat( IStream *iface, STATSTG *stg, DWORD flag )
3968 FIXME("\n");
3969 return E_NOTIMPL;
3972 static HRESULT WINAPI stream_Clone( IStream *iface, IStream **stream )
3974 FIXME("\n");
3975 return E_NOTIMPL;
3978 static const IStreamVtbl stream_vtbl =
3980 stream_QueryInterface,
3981 stream_AddRef,
3982 stream_Release,
3983 stream_Read,
3984 stream_Write,
3985 stream_Seek,
3986 stream_SetSize,
3987 stream_CopyTo,
3988 stream_Commit,
3989 stream_Revert,
3990 stream_LockRegion,
3991 stream_UnlockRegion,
3992 stream_Stat,
3993 stream_Clone
3996 static HRESULT WINAPI winhttp_request_get_ResponseStream(
3997 IWinHttpRequest *iface,
3998 VARIANT *body )
4000 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4001 DWORD err = ERROR_SUCCESS;
4002 struct stream *stream;
4004 TRACE("%p, %p\n", request, body);
4006 if (!body) return E_INVALIDARG;
4008 EnterCriticalSection( &request->cs );
4009 if (request->state < REQUEST_STATE_SENT)
4011 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4012 goto done;
4014 if (!(stream = heap_alloc( sizeof(*stream) )))
4016 err = ERROR_OUTOFMEMORY;
4017 goto done;
4019 stream->IStream_iface.lpVtbl = &stream_vtbl;
4020 stream->refs = 1;
4021 if (!(stream->data = heap_alloc( request->offset )))
4023 heap_free( stream );
4024 err = ERROR_OUTOFMEMORY;
4025 goto done;
4027 memcpy( stream->data, request->buffer, request->offset );
4028 stream->pos.QuadPart = 0;
4029 stream->size.QuadPart = request->offset;
4030 V_VT( body ) = VT_UNKNOWN;
4031 V_UNKNOWN( body ) = (IUnknown *)&stream->IStream_iface;
4033 done:
4034 LeaveCriticalSection( &request->cs );
4035 return HRESULT_FROM_WIN32( err );
4038 static HRESULT WINAPI winhttp_request_get_Option(
4039 IWinHttpRequest *iface,
4040 WinHttpRequestOption option,
4041 VARIANT *value )
4043 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4044 HRESULT hr = S_OK;
4046 TRACE("%p, %u, %p\n", request, option, value);
4048 EnterCriticalSection( &request->cs );
4049 switch (option)
4051 case WinHttpRequestOption_URLCodePage:
4052 V_VT( value ) = VT_I4;
4053 V_I4( value ) = request->url_codepage;
4054 break;
4055 default:
4056 FIXME("unimplemented option %u\n", option);
4057 hr = E_NOTIMPL;
4058 break;
4060 LeaveCriticalSection( &request->cs );
4061 return hr;
4064 static HRESULT WINAPI winhttp_request_put_Option(
4065 IWinHttpRequest *iface,
4066 WinHttpRequestOption option,
4067 VARIANT value )
4069 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4070 HRESULT hr = S_OK;
4072 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
4074 EnterCriticalSection( &request->cs );
4075 switch (option)
4077 case WinHttpRequestOption_EnableRedirects:
4079 if (V_BOOL( &value ))
4080 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
4081 else
4082 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
4083 break;
4085 case WinHttpRequestOption_URLCodePage:
4087 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
4088 VARIANT cp;
4090 VariantInit( &cp );
4091 hr = VariantChangeType( &cp, &value, 0, VT_UI4 );
4092 if (SUCCEEDED( hr ))
4094 request->url_codepage = V_UI4( &cp );
4095 TRACE("URL codepage: %u\n", request->url_codepage);
4097 else if (V_VT( &value ) == VT_BSTR && !strcmpiW( V_BSTR( &value ), utf8W ))
4099 TRACE("URL codepage: UTF-8\n");
4100 request->url_codepage = CP_UTF8;
4101 hr = S_OK;
4103 else
4104 FIXME("URL codepage %s is not recognized\n", debugstr_variant( &value ));
4105 break;
4107 default:
4108 FIXME("unimplemented option %u\n", option);
4109 hr = E_NOTIMPL;
4110 break;
4112 LeaveCriticalSection( &request->cs );
4113 return hr;
4116 static HRESULT WINAPI winhttp_request_WaitForResponse(
4117 IWinHttpRequest *iface,
4118 VARIANT timeout,
4119 VARIANT_BOOL *succeeded )
4121 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4122 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
4124 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
4126 EnterCriticalSection( &request->cs );
4127 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
4129 LeaveCriticalSection( &request->cs );
4130 return S_OK;
4132 switch ((err = request_wait( request, msecs )))
4134 case ERROR_TIMEOUT:
4135 if (succeeded) *succeeded = VARIANT_FALSE;
4136 err = ERROR_SUCCESS;
4137 break;
4139 case ERROR_SUCCESS:
4140 if (succeeded) *succeeded = VARIANT_TRUE;
4141 break;
4143 default: break;
4145 LeaveCriticalSection( &request->cs );
4146 return HRESULT_FROM_WIN32( err );
4149 static HRESULT WINAPI winhttp_request_Abort(
4150 IWinHttpRequest *iface )
4152 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4154 TRACE("%p\n", request);
4156 EnterCriticalSection( &request->cs );
4157 cancel_request( request );
4158 LeaveCriticalSection( &request->cs );
4159 return S_OK;
4162 static HRESULT WINAPI winhttp_request_SetTimeouts(
4163 IWinHttpRequest *iface,
4164 LONG resolve_timeout,
4165 LONG connect_timeout,
4166 LONG send_timeout,
4167 LONG receive_timeout )
4169 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4171 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
4173 EnterCriticalSection( &request->cs );
4174 request->resolve_timeout = resolve_timeout;
4175 request->connect_timeout = connect_timeout;
4176 request->send_timeout = send_timeout;
4177 request->receive_timeout = receive_timeout;
4178 LeaveCriticalSection( &request->cs );
4179 return S_OK;
4182 static HRESULT WINAPI winhttp_request_SetClientCertificate(
4183 IWinHttpRequest *iface,
4184 BSTR certificate )
4186 FIXME("\n");
4187 return E_NOTIMPL;
4190 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
4191 IWinHttpRequest *iface,
4192 WinHttpRequestAutoLogonPolicy policy )
4194 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4195 HRESULT hr = S_OK;
4197 TRACE("%p, %u\n", request, policy );
4199 EnterCriticalSection( &request->cs );
4200 switch (policy)
4202 case AutoLogonPolicy_Always:
4203 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
4204 break;
4205 case AutoLogonPolicy_OnlyIfBypassProxy:
4206 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
4207 break;
4208 case AutoLogonPolicy_Never:
4209 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
4210 break;
4211 default: hr = E_INVALIDARG;
4212 break;
4214 LeaveCriticalSection( &request->cs );
4215 return hr;
4218 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
4220 winhttp_request_QueryInterface,
4221 winhttp_request_AddRef,
4222 winhttp_request_Release,
4223 winhttp_request_GetTypeInfoCount,
4224 winhttp_request_GetTypeInfo,
4225 winhttp_request_GetIDsOfNames,
4226 winhttp_request_Invoke,
4227 winhttp_request_SetProxy,
4228 winhttp_request_SetCredentials,
4229 winhttp_request_Open,
4230 winhttp_request_SetRequestHeader,
4231 winhttp_request_GetResponseHeader,
4232 winhttp_request_GetAllResponseHeaders,
4233 winhttp_request_Send,
4234 winhttp_request_get_Status,
4235 winhttp_request_get_StatusText,
4236 winhttp_request_get_ResponseText,
4237 winhttp_request_get_ResponseBody,
4238 winhttp_request_get_ResponseStream,
4239 winhttp_request_get_Option,
4240 winhttp_request_put_Option,
4241 winhttp_request_WaitForResponse,
4242 winhttp_request_Abort,
4243 winhttp_request_SetTimeouts,
4244 winhttp_request_SetClientCertificate,
4245 winhttp_request_SetAutoLogonPolicy
4248 HRESULT WinHttpRequest_create( void **obj )
4250 struct winhttp_request *request;
4252 TRACE("%p\n", obj);
4254 if (!(request = heap_alloc( sizeof(*request) ))) return E_OUTOFMEMORY;
4255 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
4256 request->refs = 1;
4257 request->state = REQUEST_STATE_UNINITIALIZED;
4258 request->proxy.lpszProxy = NULL;
4259 request->proxy.lpszProxyBypass = NULL;
4260 request->url_codepage = CP_UTF8;
4261 InitializeCriticalSection( &request->cs );
4262 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
4264 *obj = &request->IWinHttpRequest_iface;
4265 TRACE("returning iface %p\n", *obj);
4266 return S_OK;