winhttp: Only read as much data as advertized when draining content.
[wine.git] / dlls / winhttp / request.c
blobf35d73b7780205e66c15e11c550afc147a66d71c
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 size, bytes_read, bytes_total = 0, bytes_left = request->content_length - request->content_read;
1306 char buffer[2048];
1308 refill_buffer( request, FALSE );
1309 for (;;)
1311 if (request->read_chunked) size = sizeof(buffer);
1312 else
1314 if (bytes_total >= bytes_left) return;
1315 size = min( sizeof(buffer), bytes_left - bytes_total );
1317 if (!read_data( request, buffer, size, &bytes_read, FALSE ) || !bytes_read) return;
1318 bytes_total += bytes_read;
1322 static BOOL send_request( request_t *request, LPCWSTR headers, DWORD headers_len, LPVOID optional,
1323 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
1325 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
1326 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
1327 static const WCHAR length_fmt[] = {'%','l','d',0};
1329 BOOL ret = FALSE;
1330 connect_t *connect = request->connect;
1331 session_t *session = connect->session;
1332 WCHAR *req = NULL;
1333 char *req_ascii;
1334 int bytes_sent;
1335 DWORD len, i, flags;
1337 clear_response_headers( request );
1338 drain_content( request );
1340 flags = WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
1341 for (i = 0; i < request->num_accept_types; i++)
1343 process_header( request, attr_accept, request->accept_types[i], flags, TRUE );
1345 if (session->agent)
1346 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1348 if (connect->hostname)
1349 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
1351 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
1353 WCHAR length[21]; /* decimal long int + null */
1354 sprintfW( length, length_fmt, total_len );
1355 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1357 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
1359 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1361 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
1363 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1364 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1366 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
1368 TRACE("failed to add request headers\n");
1369 return FALSE;
1371 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
1373 WARN("failed to add cookie headers\n");
1374 return FALSE;
1377 if (context) request->hdr.context = context;
1379 if (!(ret = open_connection( request ))) goto end;
1380 if (!(req = build_request_string( request ))) goto end;
1382 if (!(req_ascii = strdupWA( req ))) goto end;
1383 TRACE("full request: %s\n", debugstr_a(req_ascii));
1384 len = strlen(req_ascii);
1386 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
1388 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
1389 heap_free( req_ascii );
1390 if (!ret) goto end;
1392 if (optional_len)
1394 if (!netconn_send( &request->netconn, optional, optional_len, &bytes_sent )) goto end;
1395 request->optional = optional;
1396 request->optional_len = optional_len;
1397 len += optional_len;
1399 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(len) );
1401 end:
1402 if (async)
1404 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
1405 else
1407 WINHTTP_ASYNC_RESULT result;
1408 result.dwResult = API_SEND_REQUEST;
1409 result.dwError = get_last_error();
1410 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
1413 heap_free( req );
1414 return ret;
1417 static void task_send_request( task_header_t *task )
1419 send_request_t *s = (send_request_t *)task;
1420 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
1421 heap_free( s->headers );
1424 /***********************************************************************
1425 * WinHttpSendRequest (winhttp.@)
1427 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
1428 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
1430 BOOL ret;
1431 request_t *request;
1433 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1434 hrequest, debugstr_w(headers), headers_len, optional_len, total_len, context);
1436 if (!(request = (request_t *)grab_object( hrequest )))
1438 set_last_error( ERROR_INVALID_HANDLE );
1439 return FALSE;
1441 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1443 release_object( &request->hdr );
1444 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1445 return FALSE;
1448 if (headers && !headers_len) headers_len = strlenW( headers );
1450 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
1452 send_request_t *s;
1454 if (!(s = heap_alloc( sizeof(send_request_t) ))) return FALSE;
1455 s->hdr.request = request;
1456 s->hdr.proc = task_send_request;
1457 s->headers = strdupW( headers );
1458 s->headers_len = headers_len;
1459 s->optional = optional;
1460 s->optional_len = optional_len;
1461 s->total_len = total_len;
1462 s->context = context;
1464 addref_object( &request->hdr );
1465 ret = queue_task( (task_header_t *)s );
1467 else
1468 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
1470 release_object( &request->hdr );
1471 if (ret) set_last_error( ERROR_SUCCESS );
1472 return ret;
1475 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1477 static const WCHAR basicW[] = {'B','a','s','i','c',0};
1478 static const WCHAR ntlmW[] = {'N','T','L','M',0};
1479 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
1480 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
1481 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
1483 static const struct
1485 const WCHAR *str;
1486 unsigned int len;
1487 DWORD scheme;
1489 auth_schemes[] =
1491 { basicW, ARRAYSIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
1492 { ntlmW, ARRAYSIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
1493 { passportW, ARRAYSIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
1494 { digestW, ARRAYSIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
1495 { negotiateW, ARRAYSIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
1497 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
1499 static enum auth_scheme scheme_from_flag( DWORD flag )
1501 int i;
1503 for (i = 0; i < num_auth_schemes; i++) if (flag == auth_schemes[i].scheme) return i;
1504 return SCHEME_INVALID;
1507 static DWORD auth_scheme_from_header( WCHAR *header )
1509 unsigned int i;
1511 for (i = 0; i < num_auth_schemes; i++)
1513 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
1514 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
1516 return 0;
1519 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
1521 DWORD index = 0, supported_schemes = 0, first_scheme = 0;
1522 BOOL ret = FALSE;
1524 for (;;)
1526 WCHAR *buffer;
1527 DWORD size, scheme;
1529 size = 0;
1530 query_headers( request, level, NULL, NULL, &size, &index );
1531 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) break;
1533 index--;
1534 if (!(buffer = heap_alloc( size ))) return FALSE;
1535 if (!query_headers( request, level, NULL, buffer, &size, &index ))
1537 heap_free( buffer );
1538 return FALSE;
1540 scheme = auth_scheme_from_header( buffer );
1541 heap_free( buffer );
1542 if (!scheme) continue;
1544 if (!first_scheme) first_scheme = scheme;
1545 supported_schemes |= scheme;
1547 ret = TRUE;
1550 if (ret)
1552 *supported = supported_schemes;
1553 *first = first_scheme;
1555 return ret;
1558 /***********************************************************************
1559 * WinHttpQueryAuthSchemes (winhttp.@)
1561 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
1563 BOOL ret = FALSE;
1564 request_t *request;
1566 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
1568 if (!(request = (request_t *)grab_object( hrequest )))
1570 set_last_error( ERROR_INVALID_HANDLE );
1571 return FALSE;
1573 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1575 release_object( &request->hdr );
1576 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1577 return FALSE;
1579 if (!supported || !first || !target)
1581 release_object( &request->hdr );
1582 set_last_error( ERROR_INVALID_PARAMETER );
1583 return FALSE;
1587 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
1589 *target = WINHTTP_AUTH_TARGET_SERVER;
1590 ret = TRUE;
1592 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
1594 *target = WINHTTP_AUTH_TARGET_PROXY;
1595 ret = TRUE;
1598 release_object( &request->hdr );
1599 if (ret) set_last_error( ERROR_SUCCESS );
1600 return ret;
1603 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
1605 UINT n = 0, x;
1606 static const char base64enc[] =
1607 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1609 while (len > 0)
1611 /* first 6 bits, all from bin[0] */
1612 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
1613 x = (bin[0] & 3) << 4;
1615 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1616 if (len == 1)
1618 base64[n++] = base64enc[x];
1619 base64[n++] = '=';
1620 base64[n++] = '=';
1621 break;
1623 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
1624 x = (bin[1] & 0x0f) << 2;
1626 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1627 if (len == 2)
1629 base64[n++] = base64enc[x];
1630 base64[n++] = '=';
1631 break;
1633 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1635 /* last 6 bits, all from bin [2] */
1636 base64[n++] = base64enc[bin[2] & 0x3f];
1637 bin += 3;
1638 len -= 3;
1640 base64[n] = 0;
1641 return n;
1644 static inline char decode_char( WCHAR c )
1646 if (c >= 'A' && c <= 'Z') return c - 'A';
1647 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1648 if (c >= '0' && c <= '9') return c - '0' + 52;
1649 if (c == '+') return 62;
1650 if (c == '/') return 63;
1651 return 64;
1654 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1656 unsigned int i = 0;
1657 char c0, c1, c2, c3;
1658 const WCHAR *p = base64;
1660 while (len > 4)
1662 if ((c0 = decode_char( p[0] )) > 63) return 0;
1663 if ((c1 = decode_char( p[1] )) > 63) return 0;
1664 if ((c2 = decode_char( p[2] )) > 63) return 0;
1665 if ((c3 = decode_char( p[3] )) > 63) return 0;
1667 if (buf)
1669 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1670 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1671 buf[i + 2] = (c2 << 6) | c3;
1673 len -= 4;
1674 i += 3;
1675 p += 4;
1677 if (p[2] == '=')
1679 if ((c0 = decode_char( p[0] )) > 63) return 0;
1680 if ((c1 = decode_char( p[1] )) > 63) return 0;
1682 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1683 i++;
1685 else if (p[3] == '=')
1687 if ((c0 = decode_char( p[0] )) > 63) return 0;
1688 if ((c1 = decode_char( p[1] )) > 63) return 0;
1689 if ((c2 = decode_char( p[2] )) > 63) return 0;
1691 if (buf)
1693 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1694 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1696 i += 2;
1698 else
1700 if ((c0 = decode_char( p[0] )) > 63) return 0;
1701 if ((c1 = decode_char( p[1] )) > 63) return 0;
1702 if ((c2 = decode_char( p[2] )) > 63) return 0;
1703 if ((c3 = decode_char( p[3] )) > 63) return 0;
1705 if (buf)
1707 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1708 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1709 buf[i + 2] = (c2 << 6) | c3;
1711 i += 3;
1713 return i;
1716 static struct authinfo *alloc_authinfo(void)
1718 struct authinfo *ret;
1720 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1722 SecInvalidateHandle( &ret->cred );
1723 SecInvalidateHandle( &ret->ctx );
1724 memset( &ret->exp, 0, sizeof(ret->exp) );
1725 ret->scheme = 0;
1726 ret->attr = 0;
1727 ret->max_token = 0;
1728 ret->data = NULL;
1729 ret->data_len = 0;
1730 ret->finished = FALSE;
1731 return ret;
1734 void destroy_authinfo( struct authinfo *authinfo )
1736 if (!authinfo) return;
1738 if (SecIsValidHandle( &authinfo->ctx ))
1739 DeleteSecurityContext( &authinfo->ctx );
1740 if (SecIsValidHandle( &authinfo->cred ))
1741 FreeCredentialsHandle( &authinfo->cred );
1743 heap_free( authinfo->data );
1744 heap_free( authinfo );
1747 static BOOL get_authvalue( request_t *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1749 DWORD size, index = 0;
1750 for (;;)
1752 size = len;
1753 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1754 if (auth_scheme_from_header( buffer ) == scheme) break;
1756 return TRUE;
1759 static BOOL do_authorization( request_t *request, DWORD target, DWORD scheme_flag )
1761 struct authinfo *authinfo, **auth_ptr;
1762 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1763 const WCHAR *auth_target, *username, *password;
1764 WCHAR auth_value[2048], *auth_reply;
1765 DWORD len = sizeof(auth_value), len_scheme, flags;
1766 BOOL ret;
1768 if (scheme == SCHEME_INVALID) return FALSE;
1770 switch (target)
1772 case WINHTTP_AUTH_TARGET_SERVER:
1773 if (!get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len ))
1774 return FALSE;
1775 auth_ptr = &request->authinfo;
1776 auth_target = attr_authorization;
1777 if (request->creds[TARGET_SERVER][scheme].username)
1779 username = request->creds[TARGET_SERVER][scheme].username;
1780 password = request->creds[TARGET_SERVER][scheme].password;
1782 else
1784 username = request->connect->username;
1785 password = request->connect->password;
1787 break;
1789 case WINHTTP_AUTH_TARGET_PROXY:
1790 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1791 return FALSE;
1792 auth_ptr = &request->proxy_authinfo;
1793 auth_target = attr_proxy_authorization;
1794 if (request->creds[TARGET_PROXY][scheme].username)
1796 username = request->creds[TARGET_PROXY][scheme].username;
1797 password = request->creds[TARGET_PROXY][scheme].password;
1799 else
1801 username = request->connect->session->proxy_username;
1802 password = request->connect->session->proxy_password;
1804 break;
1806 default:
1807 WARN("unknown target %x\n", target);
1808 return FALSE;
1810 authinfo = *auth_ptr;
1812 switch (scheme)
1814 case SCHEME_BASIC:
1816 int userlen, passlen;
1818 if (!username || !password) return FALSE;
1819 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1821 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1822 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1824 authinfo->data_len = userlen + 1 + passlen;
1825 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1827 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1828 authinfo->data[userlen] = ':';
1829 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1831 authinfo->scheme = SCHEME_BASIC;
1832 authinfo->finished = TRUE;
1833 break;
1835 case SCHEME_NTLM:
1836 case SCHEME_NEGOTIATE:
1838 SECURITY_STATUS status;
1839 SecBufferDesc out_desc, in_desc;
1840 SecBuffer out, in;
1841 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1842 const WCHAR *p;
1843 BOOL first = FALSE;
1845 if (!authinfo)
1847 TimeStamp exp;
1848 SEC_WINNT_AUTH_IDENTITY_W id;
1849 WCHAR *domain, *user;
1851 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1853 first = TRUE;
1854 domain = (WCHAR *)username;
1855 user = strchrW( username, '\\' );
1857 if (user) user++;
1858 else
1860 user = (WCHAR *)username;
1861 domain = NULL;
1863 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1864 id.User = user;
1865 id.UserLength = strlenW( user );
1866 id.Domain = domain;
1867 id.DomainLength = domain ? user - domain - 1 : 0;
1868 id.Password = (WCHAR *)password;
1869 id.PasswordLength = strlenW( password );
1871 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1872 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1873 &authinfo->cred, &exp );
1874 if (status == SEC_E_OK)
1876 PSecPkgInfoW info;
1877 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1878 if (status == SEC_E_OK)
1880 authinfo->max_token = info->cbMaxToken;
1881 FreeContextBuffer( info );
1884 if (status != SEC_E_OK)
1886 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1887 debugstr_w(auth_schemes[scheme].str), status);
1888 heap_free( authinfo );
1889 return FALSE;
1891 authinfo->scheme = scheme;
1893 else if (authinfo->finished) return FALSE;
1895 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1896 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1898 ERR("authentication scheme changed from %s to %s\n",
1899 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1900 destroy_authinfo( authinfo );
1901 *auth_ptr = NULL;
1902 return FALSE;
1904 in.BufferType = SECBUFFER_TOKEN;
1905 in.cbBuffer = 0;
1906 in.pvBuffer = NULL;
1908 in_desc.ulVersion = 0;
1909 in_desc.cBuffers = 1;
1910 in_desc.pBuffers = &in;
1912 p = auth_value + auth_schemes[scheme].len;
1913 if (*p == ' ')
1915 int len = strlenW( ++p );
1916 in.cbBuffer = decode_base64( p, len, NULL );
1917 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) {
1918 destroy_authinfo( authinfo );
1919 *auth_ptr = NULL;
1920 return FALSE;
1922 decode_base64( p, len, in.pvBuffer );
1924 out.BufferType = SECBUFFER_TOKEN;
1925 out.cbBuffer = authinfo->max_token;
1926 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1928 heap_free( in.pvBuffer );
1929 destroy_authinfo( authinfo );
1930 *auth_ptr = NULL;
1931 return FALSE;
1933 out_desc.ulVersion = 0;
1934 out_desc.cBuffers = 1;
1935 out_desc.pBuffers = &out;
1937 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1938 first ? request->connect->servername : NULL, flags, 0,
1939 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1940 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1941 heap_free( in.pvBuffer );
1942 if (status == SEC_E_OK)
1944 heap_free( authinfo->data );
1945 authinfo->data = out.pvBuffer;
1946 authinfo->data_len = out.cbBuffer;
1947 authinfo->finished = TRUE;
1948 TRACE("sending last auth packet\n");
1950 else if (status == SEC_I_CONTINUE_NEEDED)
1952 heap_free( authinfo->data );
1953 authinfo->data = out.pvBuffer;
1954 authinfo->data_len = out.cbBuffer;
1955 TRACE("sending next auth packet\n");
1957 else
1959 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1960 heap_free( out.pvBuffer );
1961 destroy_authinfo( authinfo );
1962 *auth_ptr = NULL;
1963 return FALSE;
1965 break;
1967 default:
1968 ERR("invalid scheme %u\n", scheme);
1969 return FALSE;
1971 *auth_ptr = authinfo;
1973 len_scheme = auth_schemes[authinfo->scheme].len;
1974 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1975 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1977 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1978 auth_reply[len_scheme] = ' ';
1979 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1981 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1982 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1983 heap_free( auth_reply );
1984 return ret;
1987 static BOOL set_credentials( request_t *request, DWORD target, DWORD scheme_flag, const WCHAR *username,
1988 const WCHAR *password )
1990 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1992 if (scheme == SCHEME_INVALID || ((scheme == SCHEME_BASIC || scheme == SCHEME_DIGEST) && (!username || !password)))
1994 set_last_error( ERROR_INVALID_PARAMETER );
1995 return FALSE;
1997 switch (target)
1999 case WINHTTP_AUTH_TARGET_SERVER:
2001 heap_free( request->creds[TARGET_SERVER][scheme].username );
2002 if (!username) request->creds[TARGET_SERVER][scheme].username = NULL;
2003 else if (!(request->creds[TARGET_SERVER][scheme].username = strdupW( username ))) return FALSE;
2005 heap_free( request->creds[TARGET_SERVER][scheme].password );
2006 if (!password) request->creds[TARGET_SERVER][scheme].password = NULL;
2007 else if (!(request->creds[TARGET_SERVER][scheme].password = strdupW( password ))) return FALSE;
2008 break;
2010 case WINHTTP_AUTH_TARGET_PROXY:
2012 heap_free( request->creds[TARGET_PROXY][scheme].username );
2013 if (!username) request->creds[TARGET_PROXY][scheme].username = NULL;
2014 else if (!(request->creds[TARGET_PROXY][scheme].username = strdupW( username ))) return FALSE;
2016 heap_free( request->creds[TARGET_PROXY][scheme].password );
2017 if (!password) request->creds[TARGET_PROXY][scheme].password = NULL;
2018 else if (!(request->creds[TARGET_PROXY][scheme].password = strdupW( password ))) return FALSE;
2019 break;
2021 default:
2022 WARN("unknown target %u\n", target);
2023 return FALSE;
2025 return TRUE;
2028 /***********************************************************************
2029 * WinHttpSetCredentials (winhttp.@)
2031 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
2032 LPCWSTR password, LPVOID params )
2034 BOOL ret;
2035 request_t *request;
2037 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
2039 if (!(request = (request_t *)grab_object( hrequest )))
2041 set_last_error( ERROR_INVALID_HANDLE );
2042 return FALSE;
2044 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2046 release_object( &request->hdr );
2047 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2048 return FALSE;
2051 ret = set_credentials( request, target, scheme, username, password );
2053 release_object( &request->hdr );
2054 if (ret) set_last_error( ERROR_SUCCESS );
2055 return ret;
2058 static BOOL handle_authorization( request_t *request, DWORD status )
2060 DWORD i, schemes, first, level, target;
2062 switch (status)
2064 case HTTP_STATUS_DENIED:
2065 target = WINHTTP_AUTH_TARGET_SERVER;
2066 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
2067 break;
2069 case HTTP_STATUS_PROXY_AUTH_REQ:
2070 target = WINHTTP_AUTH_TARGET_PROXY;
2071 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
2072 break;
2074 default:
2075 WARN("unhandled status %u\n", status);
2076 return FALSE;
2079 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
2080 if (do_authorization( request, target, first )) return TRUE;
2082 schemes &= ~first;
2083 for (i = 0; i < num_auth_schemes; i++)
2085 if (!(schemes & auth_schemes[i].scheme)) continue;
2086 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
2088 return FALSE;
2091 /* set the request content length based on the headers */
2092 static DWORD set_content_length( request_t *request, DWORD status )
2094 WCHAR encoding[20];
2095 DWORD buflen = sizeof(request->content_length);
2097 if (status == HTTP_STATUS_NO_CONTENT || status == HTTP_STATUS_NOT_MODIFIED || !strcmpW( request->verb, headW ))
2098 request->content_length = 0;
2099 else
2101 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
2102 NULL, &request->content_length, &buflen, NULL ))
2103 request->content_length = ~0u;
2105 buflen = sizeof(encoding);
2106 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
2107 !strcmpiW( encoding, chunkedW ))
2109 request->content_length = ~0u;
2110 request->read_chunked = TRUE;
2111 request->read_chunked_size = ~0u;
2112 request->read_chunked_eof = FALSE;
2115 request->content_read = 0;
2116 return request->content_length;
2119 static BOOL read_line( request_t *request, char *buffer, DWORD *len )
2121 int count, bytes_read, pos = 0;
2123 for (;;)
2125 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
2126 if (eol)
2128 count = eol - (request->read_buf + request->read_pos);
2129 bytes_read = count + 1;
2131 else count = bytes_read = request->read_size;
2133 count = min( count, *len - pos );
2134 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
2135 pos += count;
2136 remove_data( request, bytes_read );
2137 if (eol) break;
2139 if (!read_more_data( request, -1, TRUE )) return FALSE;
2140 if (!request->read_size)
2142 *len = 0;
2143 TRACE("returning empty string\n");
2144 return FALSE;
2147 if (pos < *len)
2149 if (pos && buffer[pos - 1] == '\r') pos--;
2150 *len = pos + 1;
2152 buffer[*len - 1] = 0;
2153 TRACE("returning %s\n", debugstr_a(buffer));
2154 return TRUE;
2157 #define MAX_REPLY_LEN 1460
2158 #define INITIAL_HEADER_BUFFER_LEN 512
2160 static BOOL read_reply( request_t *request )
2162 static const WCHAR crlf[] = {'\r','\n',0};
2164 char buffer[MAX_REPLY_LEN];
2165 DWORD buflen, len, offset, crlf_len = 2; /* strlenW(crlf) */
2166 char *status_code, *status_text;
2167 WCHAR *versionW, *status_textW, *raw_headers;
2168 WCHAR status_codeW[4]; /* sizeof("nnn") */
2170 if (!netconn_connected( &request->netconn )) return FALSE;
2174 buflen = MAX_REPLY_LEN;
2175 if (!read_line( request, buffer, &buflen )) return FALSE;
2177 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2178 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
2179 status_code++;
2180 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
2181 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
2182 status_text++;
2184 TRACE("version [%s] status code [%s] status text [%s]\n",
2185 debugstr_an(buffer, status_code - buffer - 1),
2186 debugstr_an(status_code, len),
2187 debugstr_a(status_text));
2189 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
2191 /* we rely on the fact that the protocol is ascii */
2192 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2193 status_codeW[len] = 0;
2194 if (!(process_header( request, attr_status, status_codeW,
2195 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE, FALSE )))
2196 return FALSE;
2198 len = status_code - buffer;
2199 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2200 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2201 versionW[len - 1] = 0;
2203 heap_free( request->version );
2204 request->version = versionW;
2206 len = buflen - (status_text - buffer);
2207 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2208 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2210 heap_free( request->status_text );
2211 request->status_text = status_textW;
2213 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2214 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2215 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2216 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2218 heap_free( request->raw_headers );
2219 request->raw_headers = raw_headers;
2221 offset = buflen + crlf_len - 1;
2222 for (;;)
2224 header_t *header;
2226 buflen = MAX_REPLY_LEN;
2227 if (!read_line( request, buffer, &buflen )) return TRUE;
2228 if (!*buffer) buflen = 1;
2230 while (len - offset < buflen + crlf_len)
2232 WCHAR *tmp;
2233 len *= 2;
2234 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2235 request->raw_headers = raw_headers = tmp;
2237 if (!*buffer)
2239 memcpy( raw_headers + offset, crlf, sizeof(crlf) );
2240 break;
2242 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2244 if (!(header = parse_header( raw_headers + offset ))) break;
2245 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2247 free_header( header );
2248 break;
2250 free_header( header );
2251 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2252 offset += buflen + crlf_len - 1;
2255 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2256 return TRUE;
2259 static void record_cookies( request_t *request )
2261 unsigned int i;
2263 for (i = 0; i < request->num_headers; i++)
2265 header_t *set_cookie = &request->headers[i];
2266 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2268 set_cookies( request, set_cookie->value );
2273 static WCHAR *get_redirect_url( request_t *request, DWORD *len )
2275 DWORD size;
2276 WCHAR *ret;
2278 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2279 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2280 if (!(ret = heap_alloc( size ))) return NULL;
2281 *len = size / sizeof(WCHAR);
2282 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2283 heap_free( ret );
2284 return NULL;
2287 static BOOL handle_redirect( request_t *request, DWORD status )
2289 BOOL ret = FALSE;
2290 DWORD len, len_url;
2291 URL_COMPONENTS uc;
2292 connect_t *connect = request->connect;
2293 INTERNET_PORT port;
2294 WCHAR *hostname = NULL, *location;
2295 int index;
2297 if (!(location = get_redirect_url( request, &len_url ))) return FALSE;
2299 memset( &uc, 0, sizeof(uc) );
2300 uc.dwStructSize = sizeof(uc);
2301 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2303 if (!WinHttpCrackUrl( location, len_url, 0, &uc )) /* assume relative redirect */
2305 WCHAR *path, *p;
2307 if (location[0] == '/')
2309 len = strlenW( location );
2310 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2311 strcpyW( path, location );
2313 else
2315 if ((p = strrchrW( request->path, '/' ))) *p = 0;
2316 len = strlenW( request->path ) + 1 + strlenW( location );
2317 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2318 strcpyW( path, request->path );
2319 strcatW( path, slashW );
2320 strcatW( path, location );
2322 heap_free( request->path );
2323 request->path = path;
2325 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2327 else
2329 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2331 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2332 TRACE("redirect from secure page to non-secure page\n");
2333 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2335 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2337 TRACE("redirect from non-secure page to secure page\n");
2338 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2341 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2343 len = uc.dwHostNameLength;
2344 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2345 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2346 hostname[len] = 0;
2348 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2349 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2351 heap_free( connect->hostname );
2352 connect->hostname = hostname;
2353 connect->hostport = port;
2354 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2356 netconn_close( &request->netconn );
2357 if (!(ret = netconn_init( &request->netconn ))) goto end;
2358 request->read_pos = request->read_size = 0;
2359 request->read_chunked = FALSE;
2360 request->read_chunked_eof = FALSE;
2362 else heap_free( hostname );
2364 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2365 if (!(ret = open_connection( request ))) goto end;
2367 heap_free( request->path );
2368 request->path = NULL;
2369 if (uc.dwUrlPathLength)
2371 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2372 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2373 strcpyW( request->path, uc.lpszUrlPath );
2375 else request->path = strdupW( slashW );
2378 /* remove content-type/length headers */
2379 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2380 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2382 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2384 heap_free( request->verb );
2385 request->verb = strdupW( getW );
2386 request->optional = NULL;
2387 request->optional_len = 0;
2389 ret = TRUE;
2391 end:
2392 heap_free( location );
2393 return ret;
2396 static BOOL receive_response( request_t *request, BOOL async )
2398 BOOL ret;
2399 DWORD size, query, status;
2401 for (;;)
2403 if (!(ret = read_reply( request )))
2405 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2406 break;
2408 size = sizeof(DWORD);
2409 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2410 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2412 set_content_length( request, status );
2414 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2416 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2418 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2419 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2421 if (!(ret = handle_redirect( request, status ))) break;
2423 /* recurse synchronously */
2424 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2426 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2428 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2430 if (!handle_authorization( request, status )) break;
2432 /* recurse synchronously */
2433 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2435 break;
2438 if (request->content_length) refill_buffer( request, FALSE );
2440 if (async)
2442 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2443 else
2445 WINHTTP_ASYNC_RESULT result;
2446 result.dwResult = API_RECEIVE_RESPONSE;
2447 result.dwError = get_last_error();
2448 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2451 return ret;
2454 static void task_receive_response( task_header_t *task )
2456 receive_response_t *r = (receive_response_t *)task;
2457 receive_response( r->hdr.request, TRUE );
2460 /***********************************************************************
2461 * WinHttpReceiveResponse (winhttp.@)
2463 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2465 BOOL ret;
2466 request_t *request;
2468 TRACE("%p, %p\n", hrequest, reserved);
2470 if (!(request = (request_t *)grab_object( hrequest )))
2472 set_last_error( ERROR_INVALID_HANDLE );
2473 return FALSE;
2475 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2477 release_object( &request->hdr );
2478 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2479 return FALSE;
2482 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2484 receive_response_t *r;
2486 if (!(r = heap_alloc( sizeof(receive_response_t) ))) return FALSE;
2487 r->hdr.request = request;
2488 r->hdr.proc = task_receive_response;
2490 addref_object( &request->hdr );
2491 ret = queue_task( (task_header_t *)r );
2493 else
2494 ret = receive_response( request, FALSE );
2496 release_object( &request->hdr );
2497 if (ret) set_last_error( ERROR_SUCCESS );
2498 return ret;
2501 static BOOL query_data_available( request_t *request, DWORD *available, BOOL async )
2503 DWORD count = 0;
2505 if (end_of_read_data( request )) goto done;
2507 count = get_available_data( request );
2508 if (!request->read_chunked)
2509 count += netconn_query_data_available( &request->netconn );
2510 if (!count)
2512 refill_buffer( request, async );
2513 count = get_available_data( request );
2514 if (!request->read_chunked)
2515 count += netconn_query_data_available( &request->netconn );
2518 done:
2519 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2520 TRACE("%u bytes available\n", count);
2521 if (available) *available = count;
2522 return TRUE;
2525 static void task_query_data_available( task_header_t *task )
2527 query_data_t *q = (query_data_t *)task;
2528 query_data_available( q->hdr.request, q->available, TRUE );
2531 /***********************************************************************
2532 * WinHttpQueryDataAvailable (winhttp.@)
2534 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2536 BOOL ret;
2537 request_t *request;
2539 TRACE("%p, %p\n", hrequest, available);
2541 if (!(request = (request_t *)grab_object( hrequest )))
2543 set_last_error( ERROR_INVALID_HANDLE );
2544 return FALSE;
2546 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2548 release_object( &request->hdr );
2549 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2550 return FALSE;
2553 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2555 query_data_t *q;
2557 if (!(q = heap_alloc( sizeof(query_data_t) ))) return FALSE;
2558 q->hdr.request = request;
2559 q->hdr.proc = task_query_data_available;
2560 q->available = available;
2562 addref_object( &request->hdr );
2563 ret = queue_task( (task_header_t *)q );
2565 else
2566 ret = query_data_available( request, available, FALSE );
2568 release_object( &request->hdr );
2569 if (ret) set_last_error( ERROR_SUCCESS );
2570 return ret;
2573 static void task_read_data( task_header_t *task )
2575 read_data_t *r = (read_data_t *)task;
2576 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2579 /***********************************************************************
2580 * WinHttpReadData (winhttp.@)
2582 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2584 BOOL ret;
2585 request_t *request;
2587 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2589 if (!(request = (request_t *)grab_object( hrequest )))
2591 set_last_error( ERROR_INVALID_HANDLE );
2592 return FALSE;
2594 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2596 release_object( &request->hdr );
2597 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2598 return FALSE;
2601 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2603 read_data_t *r;
2605 if (!(r = heap_alloc( sizeof(read_data_t) ))) return FALSE;
2606 r->hdr.request = request;
2607 r->hdr.proc = task_read_data;
2608 r->buffer = buffer;
2609 r->to_read = to_read;
2610 r->read = read;
2612 addref_object( &request->hdr );
2613 ret = queue_task( (task_header_t *)r );
2615 else
2616 ret = read_data( request, buffer, to_read, read, FALSE );
2618 release_object( &request->hdr );
2619 if (ret) set_last_error( ERROR_SUCCESS );
2620 return ret;
2623 static BOOL write_data( request_t *request, LPCVOID buffer, DWORD to_write, LPDWORD written, BOOL async )
2625 BOOL ret;
2626 int num_bytes;
2628 ret = netconn_send( &request->netconn, buffer, to_write, &num_bytes );
2630 if (async)
2632 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
2633 else
2635 WINHTTP_ASYNC_RESULT result;
2636 result.dwResult = API_WRITE_DATA;
2637 result.dwError = get_last_error();
2638 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2641 if (ret && written) *written = num_bytes;
2642 return ret;
2645 static void task_write_data( task_header_t *task )
2647 write_data_t *w = (write_data_t *)task;
2648 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
2651 /***********************************************************************
2652 * WinHttpWriteData (winhttp.@)
2654 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
2656 BOOL ret;
2657 request_t *request;
2659 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
2661 if (!(request = (request_t *)grab_object( hrequest )))
2663 set_last_error( ERROR_INVALID_HANDLE );
2664 return FALSE;
2666 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2668 release_object( &request->hdr );
2669 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2670 return FALSE;
2673 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2675 write_data_t *w;
2677 if (!(w = heap_alloc( sizeof(write_data_t) ))) return FALSE;
2678 w->hdr.request = request;
2679 w->hdr.proc = task_write_data;
2680 w->buffer = buffer;
2681 w->to_write = to_write;
2682 w->written = written;
2684 addref_object( &request->hdr );
2685 ret = queue_task( (task_header_t *)w );
2687 else
2688 ret = write_data( request, buffer, to_write, written, FALSE );
2690 release_object( &request->hdr );
2691 if (ret) set_last_error( ERROR_SUCCESS );
2692 return ret;
2695 enum request_state
2697 REQUEST_STATE_UNINITIALIZED,
2698 REQUEST_STATE_INITIALIZED,
2699 REQUEST_STATE_CANCELLED,
2700 REQUEST_STATE_OPEN,
2701 REQUEST_STATE_SENT,
2702 REQUEST_STATE_RESPONSE_RECEIVED
2705 struct winhttp_request
2707 IWinHttpRequest IWinHttpRequest_iface;
2708 LONG refs;
2709 CRITICAL_SECTION cs;
2710 enum request_state state;
2711 HINTERNET hsession;
2712 HINTERNET hconnect;
2713 HINTERNET hrequest;
2714 VARIANT data;
2715 WCHAR *verb;
2716 HANDLE thread;
2717 HANDLE wait;
2718 HANDLE cancel;
2719 char *buffer;
2720 DWORD offset;
2721 DWORD bytes_available;
2722 DWORD bytes_read;
2723 DWORD error;
2724 DWORD logon_policy;
2725 DWORD disable_feature;
2726 LONG resolve_timeout;
2727 LONG connect_timeout;
2728 LONG send_timeout;
2729 LONG receive_timeout;
2730 WINHTTP_PROXY_INFO proxy;
2731 BOOL async;
2732 UINT url_codepage;
2735 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
2737 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
2740 static ULONG WINAPI winhttp_request_AddRef(
2741 IWinHttpRequest *iface )
2743 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2744 return InterlockedIncrement( &request->refs );
2747 /* critical section must be held */
2748 static void cancel_request( struct winhttp_request *request )
2750 if (request->state <= REQUEST_STATE_CANCELLED) return;
2752 SetEvent( request->cancel );
2753 LeaveCriticalSection( &request->cs );
2754 WaitForSingleObject( request->thread, INFINITE );
2755 EnterCriticalSection( &request->cs );
2757 request->state = REQUEST_STATE_CANCELLED;
2759 CloseHandle( request->thread );
2760 request->thread = NULL;
2761 CloseHandle( request->wait );
2762 request->wait = NULL;
2763 CloseHandle( request->cancel );
2764 request->cancel = NULL;
2767 /* critical section must be held */
2768 static void free_request( struct winhttp_request *request )
2770 if (request->state < REQUEST_STATE_INITIALIZED) return;
2771 WinHttpCloseHandle( request->hrequest );
2772 WinHttpCloseHandle( request->hconnect );
2773 WinHttpCloseHandle( request->hsession );
2774 CloseHandle( request->thread );
2775 CloseHandle( request->wait );
2776 CloseHandle( request->cancel );
2777 heap_free( request->proxy.lpszProxy );
2778 heap_free( request->proxy.lpszProxyBypass );
2779 heap_free( request->buffer );
2780 heap_free( request->verb );
2781 VariantClear( &request->data );
2784 static ULONG WINAPI winhttp_request_Release(
2785 IWinHttpRequest *iface )
2787 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2788 LONG refs = InterlockedDecrement( &request->refs );
2789 if (!refs)
2791 TRACE("destroying %p\n", request);
2793 EnterCriticalSection( &request->cs );
2794 cancel_request( request );
2795 free_request( request );
2796 LeaveCriticalSection( &request->cs );
2797 request->cs.DebugInfo->Spare[0] = 0;
2798 DeleteCriticalSection( &request->cs );
2799 heap_free( request );
2801 return refs;
2804 static HRESULT WINAPI winhttp_request_QueryInterface(
2805 IWinHttpRequest *iface,
2806 REFIID riid,
2807 void **obj )
2809 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2811 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
2813 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
2814 IsEqualGUID( riid, &IID_IDispatch ) ||
2815 IsEqualGUID( riid, &IID_IUnknown ))
2817 *obj = iface;
2819 else
2821 FIXME("interface %s not implemented\n", debugstr_guid(riid));
2822 return E_NOINTERFACE;
2824 IWinHttpRequest_AddRef( iface );
2825 return S_OK;
2828 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
2829 IWinHttpRequest *iface,
2830 UINT *count )
2832 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2834 TRACE("%p, %p\n", request, count);
2835 *count = 1;
2836 return S_OK;
2839 enum type_id
2841 IWinHttpRequest_tid,
2842 last_tid
2845 static ITypeLib *winhttp_typelib;
2846 static ITypeInfo *winhttp_typeinfo[last_tid];
2848 static REFIID winhttp_tid_id[] =
2850 &IID_IWinHttpRequest
2853 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
2855 HRESULT hr;
2857 if (!winhttp_typelib)
2859 ITypeLib *typelib;
2861 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
2862 if (FAILED(hr))
2864 ERR("LoadRegTypeLib failed: %08x\n", hr);
2865 return hr;
2867 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
2868 ITypeLib_Release( typelib );
2870 if (!winhttp_typeinfo[tid])
2872 ITypeInfo *typeinfo;
2874 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
2875 if (FAILED(hr))
2877 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
2878 return hr;
2880 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
2881 ITypeInfo_Release( typeinfo );
2883 *ret = winhttp_typeinfo[tid];
2884 ITypeInfo_AddRef(winhttp_typeinfo[tid]);
2885 return S_OK;
2888 void release_typelib(void)
2890 unsigned i;
2892 for (i = 0; i < sizeof(winhttp_typeinfo)/sizeof(*winhttp_typeinfo); i++)
2893 if (winhttp_typeinfo[i])
2894 ITypeInfo_Release(winhttp_typeinfo[i]);
2896 if (winhttp_typelib)
2897 ITypeLib_Release(winhttp_typelib);
2900 static HRESULT WINAPI winhttp_request_GetTypeInfo(
2901 IWinHttpRequest *iface,
2902 UINT index,
2903 LCID lcid,
2904 ITypeInfo **info )
2906 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2907 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
2909 return get_typeinfo( IWinHttpRequest_tid, info );
2912 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
2913 IWinHttpRequest *iface,
2914 REFIID riid,
2915 LPOLESTR *names,
2916 UINT count,
2917 LCID lcid,
2918 DISPID *dispid )
2920 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2921 ITypeInfo *typeinfo;
2922 HRESULT hr;
2924 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
2926 if (!names || !count || !dispid) return E_INVALIDARG;
2928 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2929 if (SUCCEEDED(hr))
2931 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
2932 ITypeInfo_Release( typeinfo );
2934 return hr;
2937 static HRESULT WINAPI winhttp_request_Invoke(
2938 IWinHttpRequest *iface,
2939 DISPID member,
2940 REFIID riid,
2941 LCID lcid,
2942 WORD flags,
2943 DISPPARAMS *params,
2944 VARIANT *result,
2945 EXCEPINFO *excep_info,
2946 UINT *arg_err )
2948 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2949 ITypeInfo *typeinfo;
2950 HRESULT hr;
2952 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
2953 lcid, flags, params, result, excep_info, arg_err);
2955 if (!IsEqualIID( riid, &IID_NULL )) return DISP_E_UNKNOWNINTERFACE;
2957 if (member == DISPID_HTTPREQUEST_OPTION)
2959 VARIANT ret_value, option;
2960 UINT err_pos;
2962 if (!result) result = &ret_value;
2963 if (!arg_err) arg_err = &err_pos;
2965 VariantInit( &option );
2966 VariantInit( result );
2968 if (!flags) return S_OK;
2970 if (flags == DISPATCH_PROPERTYPUT)
2972 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
2973 if (FAILED(hr)) return hr;
2975 hr = IWinHttpRequest_put_Option( &request->IWinHttpRequest_iface, V_I4( &option ), params->rgvarg[0] );
2976 if (FAILED(hr))
2977 WARN("put_Option(%d) failed: %x\n", V_I4( &option ), hr);
2978 return hr;
2980 else if (flags & (DISPATCH_PROPERTYGET | DISPATCH_METHOD))
2982 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
2983 if (FAILED(hr)) return hr;
2985 hr = IWinHttpRequest_get_Option( &request->IWinHttpRequest_iface, V_I4( &option ), result );
2986 if (FAILED(hr))
2987 WARN("get_Option(%d) failed: %x\n", V_I4( &option ), hr);
2988 return hr;
2991 FIXME("unsupported flags %x\n", flags);
2992 return E_NOTIMPL;
2995 /* fallback to standard implementation */
2997 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2998 if (SUCCEEDED(hr))
3000 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
3001 params, result, excep_info, arg_err );
3002 ITypeInfo_Release( typeinfo );
3004 return hr;
3007 static HRESULT WINAPI winhttp_request_SetProxy(
3008 IWinHttpRequest *iface,
3009 HTTPREQUEST_PROXY_SETTING proxy_setting,
3010 VARIANT proxy_server,
3011 VARIANT bypass_list )
3013 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3014 DWORD err = ERROR_SUCCESS;
3016 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
3017 debugstr_variant(&bypass_list));
3019 EnterCriticalSection( &request->cs );
3020 switch (proxy_setting)
3022 case HTTPREQUEST_PROXYSETTING_DEFAULT:
3023 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3024 heap_free( request->proxy.lpszProxy );
3025 heap_free( request->proxy.lpszProxyBypass );
3026 request->proxy.lpszProxy = NULL;
3027 request->proxy.lpszProxyBypass = NULL;
3028 break;
3030 case HTTPREQUEST_PROXYSETTING_DIRECT:
3031 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
3032 heap_free( request->proxy.lpszProxy );
3033 heap_free( request->proxy.lpszProxyBypass );
3034 request->proxy.lpszProxy = NULL;
3035 request->proxy.lpszProxyBypass = NULL;
3036 break;
3038 case HTTPREQUEST_PROXYSETTING_PROXY:
3039 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
3040 if (V_VT( &proxy_server ) == VT_BSTR)
3042 heap_free( request->proxy.lpszProxy );
3043 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
3045 if (V_VT( &bypass_list ) == VT_BSTR)
3047 heap_free( request->proxy.lpszProxyBypass );
3048 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
3050 break;
3052 default:
3053 err = ERROR_INVALID_PARAMETER;
3054 break;
3056 LeaveCriticalSection( &request->cs );
3057 return HRESULT_FROM_WIN32( err );
3060 static HRESULT WINAPI winhttp_request_SetCredentials(
3061 IWinHttpRequest *iface,
3062 BSTR username,
3063 BSTR password,
3064 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
3066 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3067 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
3068 DWORD err = ERROR_SUCCESS;
3070 TRACE("%p, %s, %p, 0x%08x\n", request, debugstr_w(username), password, flags);
3072 EnterCriticalSection( &request->cs );
3073 if (request->state < REQUEST_STATE_OPEN)
3075 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3076 goto done;
3078 switch (flags)
3080 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
3081 target = WINHTTP_AUTH_TARGET_SERVER;
3082 break;
3083 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
3084 target = WINHTTP_AUTH_TARGET_PROXY;
3085 break;
3086 default:
3087 err = ERROR_INVALID_PARAMETER;
3088 goto done;
3090 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
3092 err = get_last_error();
3094 done:
3095 LeaveCriticalSection( &request->cs );
3096 return HRESULT_FROM_WIN32( err );
3099 static void initialize_request( struct winhttp_request *request )
3101 request->hrequest = NULL;
3102 request->hconnect = NULL;
3103 request->hsession = NULL;
3104 request->thread = NULL;
3105 request->wait = NULL;
3106 request->cancel = NULL;
3107 request->buffer = NULL;
3108 request->verb = NULL;
3109 request->offset = 0;
3110 request->bytes_available = 0;
3111 request->bytes_read = 0;
3112 request->error = ERROR_SUCCESS;
3113 request->async = FALSE;
3114 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
3115 request->disable_feature = 0;
3116 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3117 request->proxy.lpszProxy = NULL;
3118 request->proxy.lpszProxyBypass = NULL;
3119 request->resolve_timeout = 0;
3120 request->connect_timeout = 60000;
3121 request->send_timeout = 30000;
3122 request->receive_timeout = 30000;
3123 request->url_codepage = CP_UTF8;
3124 VariantInit( &request->data );
3125 request->state = REQUEST_STATE_INITIALIZED;
3128 static void reset_request( struct winhttp_request *request )
3130 cancel_request( request );
3131 WinHttpCloseHandle( request->hrequest );
3132 request->hrequest = NULL;
3133 WinHttpCloseHandle( request->hconnect );
3134 request->hconnect = NULL;
3135 heap_free( request->buffer );
3136 request->buffer = NULL;
3137 heap_free( request->verb );
3138 request->verb = NULL;
3139 request->offset = 0;
3140 request->bytes_available = 0;
3141 request->bytes_read = 0;
3142 request->error = ERROR_SUCCESS;
3143 request->async = FALSE;
3144 request->url_codepage = CP_UTF8;
3145 VariantClear( &request->data );
3146 request->state = REQUEST_STATE_INITIALIZED;
3149 static HRESULT WINAPI winhttp_request_Open(
3150 IWinHttpRequest *iface,
3151 BSTR method,
3152 BSTR url,
3153 VARIANT async )
3155 static const WCHAR typeW[] = {'*','/','*',0};
3156 static const WCHAR *acceptW[] = {typeW, NULL};
3157 static const WCHAR httpsW[] = {'h','t','t','p','s'};
3158 static const WCHAR user_agentW[] = {
3159 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
3160 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
3161 'R','e','q','u','e','s','t','.','5',')',0};
3162 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3163 URL_COMPONENTS uc;
3164 WCHAR *hostname, *path = NULL, *verb = NULL;
3165 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0;
3167 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
3168 debugstr_variant(&async));
3170 if (!method || !url) return E_INVALIDARG;
3172 memset( &uc, 0, sizeof(uc) );
3173 uc.dwStructSize = sizeof(uc);
3174 uc.dwSchemeLength = ~0u;
3175 uc.dwHostNameLength = ~0u;
3176 uc.dwUrlPathLength = ~0u;
3177 uc.dwExtraInfoLength = ~0u;
3178 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( get_last_error() );
3180 EnterCriticalSection( &request->cs );
3181 if (request->state < REQUEST_STATE_INITIALIZED) initialize_request( request );
3182 else reset_request( request );
3184 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
3185 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
3186 hostname[uc.dwHostNameLength] = 0;
3188 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
3189 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
3190 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
3192 if (!(verb = strdupW( method ))) goto error;
3193 if (SUCCEEDED( VariantChangeType( &async, &async, 0, VT_BOOL )) && V_BOOL( &async )) request->async = TRUE;
3194 else request->async = FALSE;
3196 if (!request->hsession)
3198 if (!(request->hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL,
3199 WINHTTP_FLAG_ASYNC )))
3201 err = get_last_error();
3202 goto error;
3204 if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3206 WinHttpCloseHandle( request->hsession );
3207 request->hsession = NULL;
3208 err = get_last_error();
3209 goto error;
3212 else if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3214 err = get_last_error();
3215 goto error;
3218 len = sizeof(httpsW) / sizeof(WCHAR);
3219 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
3221 flags |= WINHTTP_FLAG_SECURE;
3223 if (!(request->hrequest = WinHttpOpenRequest( request->hconnect, method, path, NULL, NULL, acceptW, flags )))
3225 err = get_last_error();
3226 goto error;
3228 WinHttpSetOption( request->hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3230 request->state = REQUEST_STATE_OPEN;
3231 request->verb = verb;
3232 heap_free( hostname );
3233 heap_free( path );
3234 LeaveCriticalSection( &request->cs );
3235 return S_OK;
3237 error:
3238 WinHttpCloseHandle( request->hconnect );
3239 request->hconnect = NULL;
3240 heap_free( hostname );
3241 heap_free( path );
3242 heap_free( verb );
3243 LeaveCriticalSection( &request->cs );
3244 return HRESULT_FROM_WIN32( err );
3247 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3248 IWinHttpRequest *iface,
3249 BSTR header,
3250 BSTR value )
3252 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3253 static const WCHAR emptyW[] = {0};
3254 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3255 DWORD len, err = ERROR_SUCCESS;
3256 WCHAR *str;
3258 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3260 if (!header) return E_INVALIDARG;
3262 EnterCriticalSection( &request->cs );
3263 if (request->state < REQUEST_STATE_OPEN)
3265 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3266 goto done;
3268 if (request->state >= REQUEST_STATE_SENT)
3270 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3271 goto done;
3273 len = strlenW( header ) + 4;
3274 if (value) len += strlenW( value );
3275 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3277 err = ERROR_OUTOFMEMORY;
3278 goto done;
3280 sprintfW( str, fmtW, header, value ? value : emptyW );
3281 if (!WinHttpAddRequestHeaders( request->hrequest, str, len,
3282 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
3284 err = get_last_error();
3286 heap_free( str );
3288 done:
3289 LeaveCriticalSection( &request->cs );
3290 return HRESULT_FROM_WIN32( err );
3293 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3294 IWinHttpRequest *iface,
3295 BSTR header,
3296 BSTR *value )
3298 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3299 DWORD size, err = ERROR_SUCCESS;
3301 TRACE("%p, %p\n", request, header);
3303 EnterCriticalSection( &request->cs );
3304 if (request->state < REQUEST_STATE_SENT)
3306 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3307 goto done;
3309 if (!header || !value)
3311 err = ERROR_INVALID_PARAMETER;
3312 goto done;
3314 size = 0;
3315 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3317 err = get_last_error();
3318 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3320 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3322 err = ERROR_OUTOFMEMORY;
3323 goto done;
3325 err = ERROR_SUCCESS;
3326 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3328 err = get_last_error();
3329 SysFreeString( *value );
3331 done:
3332 LeaveCriticalSection( &request->cs );
3333 return HRESULT_FROM_WIN32( err );
3336 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3337 IWinHttpRequest *iface,
3338 BSTR *headers )
3340 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3341 DWORD size, err = ERROR_SUCCESS;
3343 TRACE("%p, %p\n", request, headers);
3345 if (!headers) return E_INVALIDARG;
3347 EnterCriticalSection( &request->cs );
3348 if (request->state < REQUEST_STATE_SENT)
3350 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3351 goto done;
3353 size = 0;
3354 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3356 err = get_last_error();
3357 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3359 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3361 err = ERROR_OUTOFMEMORY;
3362 goto done;
3364 err = ERROR_SUCCESS;
3365 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3367 err = get_last_error();
3368 SysFreeString( *headers );
3370 done:
3371 LeaveCriticalSection( &request->cs );
3372 return HRESULT_FROM_WIN32( err );
3375 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3377 struct winhttp_request *request = (struct winhttp_request *)context;
3379 switch (status)
3381 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3382 request->bytes_available = *(DWORD *)buffer;
3383 request->error = ERROR_SUCCESS;
3384 break;
3385 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3386 request->bytes_read = size;
3387 request->error = ERROR_SUCCESS;
3388 break;
3389 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3391 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3392 request->error = result->dwError;
3393 break;
3395 default: break;
3397 SetEvent( request->wait );
3400 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3402 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3403 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3406 static DWORD wait_for_completion( struct winhttp_request *request )
3408 HANDLE handles[2] = { request->wait, request->cancel };
3410 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3412 case WAIT_OBJECT_0:
3413 break;
3414 case WAIT_OBJECT_0 + 1:
3415 request->error = ERROR_CANCELLED;
3416 break;
3417 default:
3418 request->error = get_last_error();
3419 break;
3421 return request->error;
3424 static HRESULT request_receive( struct winhttp_request *request )
3426 DWORD err, size, buflen = 4096;
3428 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3429 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3431 return HRESULT_FROM_WIN32( get_last_error() );
3433 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3434 if (!strcmpW( request->verb, headW ))
3436 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3437 return S_OK;
3439 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3440 request->buffer[0] = 0;
3441 size = 0;
3444 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3445 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3447 err = get_last_error();
3448 goto error;
3450 if ((err = wait_for_completion( request ))) goto error;
3451 if (!request->bytes_available) break;
3452 size += request->bytes_available;
3453 if (buflen < size)
3455 char *tmp;
3456 while (buflen < size) buflen *= 2;
3457 if (!(tmp = heap_realloc( request->buffer, buflen )))
3459 err = ERROR_OUTOFMEMORY;
3460 goto error;
3462 request->buffer = tmp;
3464 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3465 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3466 request->bytes_available, &request->bytes_read ))
3468 err = get_last_error();
3469 goto error;
3471 if ((err = wait_for_completion( request ))) goto error;
3472 request->offset += request->bytes_read;
3473 } while (request->bytes_read);
3475 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3476 return S_OK;
3478 error:
3479 heap_free( request->buffer );
3480 request->buffer = NULL;
3481 return HRESULT_FROM_WIN32( err );
3484 static DWORD request_set_parameters( struct winhttp_request *request )
3486 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3487 sizeof(request->proxy) )) return get_last_error();
3489 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3490 sizeof(request->logon_policy) )) return get_last_error();
3492 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3493 sizeof(request->disable_feature) )) return get_last_error();
3495 if (!WinHttpSetTimeouts( request->hrequest,
3496 request->resolve_timeout,
3497 request->connect_timeout,
3498 request->send_timeout,
3499 request->receive_timeout )) return get_last_error();
3500 return ERROR_SUCCESS;
3503 static void request_set_utf8_content_type( struct winhttp_request *request )
3505 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3506 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3507 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3508 WCHAR headerW[64];
3509 int len;
3511 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3512 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3513 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3514 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3517 static HRESULT request_send( struct winhttp_request *request )
3519 SAFEARRAY *sa = NULL;
3520 VARIANT data;
3521 char *ptr = NULL;
3522 LONG size = 0;
3523 HRESULT hr;
3524 DWORD err;
3526 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3527 if (strcmpW( request->verb, getW ))
3529 VariantInit( &data );
3530 if (V_VT( &request->data ) == VT_BSTR)
3532 UINT cp = CP_ACP;
3533 const WCHAR *str = V_BSTR( &request->data );
3534 int i, len = strlenW( str );
3536 for (i = 0; i < len; i++)
3538 if (str[i] > 127)
3540 cp = CP_UTF8;
3541 break;
3544 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3545 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3546 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3547 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3549 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3551 sa = V_ARRAY( &data );
3552 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3553 if ((hr = SafeArrayGetUBound( sa, 1, &size )) != S_OK)
3555 SafeArrayUnaccessData( sa );
3556 return hr;
3558 size++;
3561 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3562 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3564 err = get_last_error();
3565 goto error;
3567 if ((err = wait_for_completion( request ))) goto error;
3568 if (sa) SafeArrayUnaccessData( sa );
3569 else heap_free( ptr );
3570 request->state = REQUEST_STATE_SENT;
3571 return S_OK;
3573 error:
3574 if (sa) SafeArrayUnaccessData( sa );
3575 else heap_free( ptr );
3576 return HRESULT_FROM_WIN32( err );
3579 static HRESULT request_send_and_receive( struct winhttp_request *request )
3581 HRESULT hr = request_send( request );
3582 if (hr == S_OK) hr = request_receive( request );
3583 return hr;
3586 static DWORD CALLBACK send_and_receive_proc( void *arg )
3588 struct winhttp_request *request = (struct winhttp_request *)arg;
3589 return request_send_and_receive( request );
3592 /* critical section must be held */
3593 static DWORD request_wait( struct winhttp_request *request, DWORD timeout )
3595 HANDLE thread = request->thread;
3596 DWORD err, ret;
3598 LeaveCriticalSection( &request->cs );
3599 while ((err = MsgWaitForMultipleObjects( 1, &thread, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3601 MSG msg;
3602 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3604 TranslateMessage( &msg );
3605 DispatchMessageW( &msg );
3608 switch (err)
3610 case WAIT_OBJECT_0:
3611 ret = ERROR_SUCCESS;
3612 break;
3613 case WAIT_TIMEOUT:
3614 ret = ERROR_TIMEOUT;
3615 break;
3616 case WAIT_FAILED:
3617 default:
3618 ret = get_last_error();
3619 break;
3621 EnterCriticalSection( &request->cs );
3622 return ret;
3625 static HRESULT WINAPI winhttp_request_Send(
3626 IWinHttpRequest *iface,
3627 VARIANT body )
3629 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3630 HRESULT hr;
3632 TRACE("%p, %s\n", request, debugstr_variant(&body));
3634 EnterCriticalSection( &request->cs );
3635 if (request->state < REQUEST_STATE_OPEN)
3637 LeaveCriticalSection( &request->cs );
3638 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3640 if (request->state >= REQUEST_STATE_SENT)
3642 LeaveCriticalSection( &request->cs );
3643 return S_OK;
3645 VariantClear( &request->data );
3646 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK)
3648 LeaveCriticalSection( &request->cs );
3649 return hr;
3651 if (!(request->thread = CreateThread( NULL, 0, send_and_receive_proc, request, 0, NULL )))
3653 LeaveCriticalSection( &request->cs );
3654 return HRESULT_FROM_WIN32( get_last_error() );
3656 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3657 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3658 if (!request->async)
3660 hr = HRESULT_FROM_WIN32( request_wait( request, INFINITE ) );
3662 LeaveCriticalSection( &request->cs );
3663 return hr;
3666 static HRESULT WINAPI winhttp_request_get_Status(
3667 IWinHttpRequest *iface,
3668 LONG *status )
3670 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3671 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
3673 TRACE("%p, %p\n", request, status);
3675 if (!status) return E_INVALIDARG;
3677 EnterCriticalSection( &request->cs );
3678 if (request->state < REQUEST_STATE_SENT)
3680 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3681 goto done;
3683 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
3684 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
3686 err = get_last_error();
3687 goto done;
3689 *status = status_code;
3691 done:
3692 LeaveCriticalSection( &request->cs );
3693 return HRESULT_FROM_WIN32( err );
3696 static HRESULT WINAPI winhttp_request_get_StatusText(
3697 IWinHttpRequest *iface,
3698 BSTR *status )
3700 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3701 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
3703 TRACE("%p, %p\n", request, status);
3705 if (!status) return E_INVALIDARG;
3707 EnterCriticalSection( &request->cs );
3708 if (request->state < REQUEST_STATE_SENT)
3710 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3711 goto done;
3713 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
3715 err = get_last_error();
3716 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3718 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
3720 err = ERROR_OUTOFMEMORY;
3721 goto done;
3723 index = 0;
3724 err = ERROR_SUCCESS;
3725 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
3727 err = get_last_error();
3728 SysFreeString( *status );
3730 done:
3731 LeaveCriticalSection( &request->cs );
3732 return HRESULT_FROM_WIN32( err );
3735 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
3737 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
3738 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
3739 WCHAR *buffer, *p;
3740 DWORD size;
3742 *codepage = CP_ACP;
3743 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
3744 get_last_error() == ERROR_INSUFFICIENT_BUFFER)
3746 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
3747 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
3749 return get_last_error();
3751 if ((p = strstrW( buffer, charsetW )))
3753 p += strlenW( charsetW );
3754 while (*p == ' ') p++;
3755 if (*p++ == '=')
3757 while (*p == ' ') p++;
3758 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
3761 heap_free( buffer );
3763 return ERROR_SUCCESS;
3766 static HRESULT WINAPI winhttp_request_get_ResponseText(
3767 IWinHttpRequest *iface,
3768 BSTR *body )
3770 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3771 UINT codepage;
3772 DWORD err = ERROR_SUCCESS;
3773 int len;
3775 TRACE("%p, %p\n", request, body);
3777 if (!body) return E_INVALIDARG;
3779 EnterCriticalSection( &request->cs );
3780 if (request->state < REQUEST_STATE_SENT)
3782 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3783 goto done;
3785 if ((err = request_get_codepage( request, &codepage ))) goto done;
3786 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
3787 if (!(*body = SysAllocStringLen( NULL, len )))
3789 err = ERROR_OUTOFMEMORY;
3790 goto done;
3792 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
3793 (*body)[len] = 0;
3795 done:
3796 LeaveCriticalSection( &request->cs );
3797 return HRESULT_FROM_WIN32( err );
3800 static HRESULT WINAPI winhttp_request_get_ResponseBody(
3801 IWinHttpRequest *iface,
3802 VARIANT *body )
3804 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3805 SAFEARRAY *sa;
3806 HRESULT hr;
3807 DWORD err = ERROR_SUCCESS;
3808 char *ptr;
3810 TRACE("%p, %p\n", request, body);
3812 if (!body) return E_INVALIDARG;
3814 EnterCriticalSection( &request->cs );
3815 if (request->state < REQUEST_STATE_SENT)
3817 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3818 goto done;
3820 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
3822 err = ERROR_OUTOFMEMORY;
3823 goto done;
3825 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
3827 SafeArrayDestroy( sa );
3828 LeaveCriticalSection( &request->cs );
3829 return hr;
3831 memcpy( ptr, request->buffer, request->offset );
3832 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
3834 SafeArrayDestroy( sa );
3835 LeaveCriticalSection( &request->cs );
3836 return hr;
3838 V_VT( body ) = VT_ARRAY|VT_UI1;
3839 V_ARRAY( body ) = sa;
3841 done:
3842 LeaveCriticalSection( &request->cs );
3843 return HRESULT_FROM_WIN32( err );
3846 struct stream
3848 IStream IStream_iface;
3849 LONG refs;
3850 char *data;
3851 ULARGE_INTEGER pos, size;
3854 static inline struct stream *impl_from_IStream( IStream *iface )
3856 return CONTAINING_RECORD( iface, struct stream, IStream_iface );
3859 static HRESULT WINAPI stream_QueryInterface( IStream *iface, REFIID riid, void **obj )
3861 struct stream *stream = impl_from_IStream( iface );
3863 TRACE("%p, %s, %p\n", stream, debugstr_guid(riid), obj);
3865 if (IsEqualGUID( riid, &IID_IStream ) || IsEqualGUID( riid, &IID_IUnknown ))
3867 *obj = iface;
3869 else
3871 FIXME("interface %s not implemented\n", debugstr_guid(riid));
3872 return E_NOINTERFACE;
3874 IStream_AddRef( iface );
3875 return S_OK;
3878 static ULONG WINAPI stream_AddRef( IStream *iface )
3880 struct stream *stream = impl_from_IStream( iface );
3881 return InterlockedIncrement( &stream->refs );
3884 static ULONG WINAPI stream_Release( IStream *iface )
3886 struct stream *stream = impl_from_IStream( iface );
3887 LONG refs = InterlockedDecrement( &stream->refs );
3888 if (!refs)
3890 heap_free( stream->data );
3891 heap_free( stream );
3893 return refs;
3896 static HRESULT WINAPI stream_Read( IStream *iface, void *buf, ULONG len, ULONG *read )
3898 struct stream *stream = impl_from_IStream( iface );
3899 ULONG size;
3901 if (stream->pos.QuadPart >= stream->size.QuadPart)
3903 *read = 0;
3904 return S_FALSE;
3907 size = min( stream->size.QuadPart - stream->pos.QuadPart, len );
3908 memcpy( buf, stream->data + stream->pos.QuadPart, size );
3909 stream->pos.QuadPart += size;
3910 *read = size;
3912 return S_OK;
3915 static HRESULT WINAPI stream_Write( IStream *iface, const void *buf, ULONG len, ULONG *written )
3917 FIXME("\n");
3918 return E_NOTIMPL;
3921 static HRESULT WINAPI stream_Seek( IStream *iface, LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *newpos )
3923 struct stream *stream = impl_from_IStream( iface );
3925 if (origin == STREAM_SEEK_SET)
3926 stream->pos.QuadPart = move.QuadPart;
3927 else if (origin == STREAM_SEEK_CUR)
3928 stream->pos.QuadPart += move.QuadPart;
3929 else if (origin == STREAM_SEEK_END)
3930 stream->pos.QuadPart = stream->size.QuadPart - move.QuadPart;
3932 if (newpos) newpos->QuadPart = stream->pos.QuadPart;
3933 return S_OK;
3936 static HRESULT WINAPI stream_SetSize( IStream *iface, ULARGE_INTEGER newsize )
3938 FIXME("\n");
3939 return E_NOTIMPL;
3942 static HRESULT WINAPI stream_CopyTo( IStream *iface, IStream *stream, ULARGE_INTEGER len, ULARGE_INTEGER *read,
3943 ULARGE_INTEGER *written )
3945 FIXME("\n");
3946 return E_NOTIMPL;
3949 static HRESULT WINAPI stream_Commit( IStream *iface, DWORD flags )
3951 FIXME("\n");
3952 return E_NOTIMPL;
3955 static HRESULT WINAPI stream_Revert( IStream *iface )
3957 FIXME("\n");
3958 return E_NOTIMPL;
3961 static HRESULT WINAPI stream_LockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
3963 FIXME("\n");
3964 return E_NOTIMPL;
3967 static HRESULT WINAPI stream_UnlockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
3969 FIXME("\n");
3970 return E_NOTIMPL;
3973 static HRESULT WINAPI stream_Stat( IStream *iface, STATSTG *stg, DWORD flag )
3975 FIXME("\n");
3976 return E_NOTIMPL;
3979 static HRESULT WINAPI stream_Clone( IStream *iface, IStream **stream )
3981 FIXME("\n");
3982 return E_NOTIMPL;
3985 static const IStreamVtbl stream_vtbl =
3987 stream_QueryInterface,
3988 stream_AddRef,
3989 stream_Release,
3990 stream_Read,
3991 stream_Write,
3992 stream_Seek,
3993 stream_SetSize,
3994 stream_CopyTo,
3995 stream_Commit,
3996 stream_Revert,
3997 stream_LockRegion,
3998 stream_UnlockRegion,
3999 stream_Stat,
4000 stream_Clone
4003 static HRESULT WINAPI winhttp_request_get_ResponseStream(
4004 IWinHttpRequest *iface,
4005 VARIANT *body )
4007 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4008 DWORD err = ERROR_SUCCESS;
4009 struct stream *stream;
4011 TRACE("%p, %p\n", request, body);
4013 if (!body) return E_INVALIDARG;
4015 EnterCriticalSection( &request->cs );
4016 if (request->state < REQUEST_STATE_SENT)
4018 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4019 goto done;
4021 if (!(stream = heap_alloc( sizeof(*stream) )))
4023 err = ERROR_OUTOFMEMORY;
4024 goto done;
4026 stream->IStream_iface.lpVtbl = &stream_vtbl;
4027 stream->refs = 1;
4028 if (!(stream->data = heap_alloc( request->offset )))
4030 heap_free( stream );
4031 err = ERROR_OUTOFMEMORY;
4032 goto done;
4034 memcpy( stream->data, request->buffer, request->offset );
4035 stream->pos.QuadPart = 0;
4036 stream->size.QuadPart = request->offset;
4037 V_VT( body ) = VT_UNKNOWN;
4038 V_UNKNOWN( body ) = (IUnknown *)&stream->IStream_iface;
4040 done:
4041 LeaveCriticalSection( &request->cs );
4042 return HRESULT_FROM_WIN32( err );
4045 static HRESULT WINAPI winhttp_request_get_Option(
4046 IWinHttpRequest *iface,
4047 WinHttpRequestOption option,
4048 VARIANT *value )
4050 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4051 HRESULT hr = S_OK;
4053 TRACE("%p, %u, %p\n", request, option, value);
4055 EnterCriticalSection( &request->cs );
4056 switch (option)
4058 case WinHttpRequestOption_URLCodePage:
4059 V_VT( value ) = VT_I4;
4060 V_I4( value ) = request->url_codepage;
4061 break;
4062 default:
4063 FIXME("unimplemented option %u\n", option);
4064 hr = E_NOTIMPL;
4065 break;
4067 LeaveCriticalSection( &request->cs );
4068 return hr;
4071 static HRESULT WINAPI winhttp_request_put_Option(
4072 IWinHttpRequest *iface,
4073 WinHttpRequestOption option,
4074 VARIANT value )
4076 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4077 HRESULT hr = S_OK;
4079 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
4081 EnterCriticalSection( &request->cs );
4082 switch (option)
4084 case WinHttpRequestOption_EnableRedirects:
4086 if (V_BOOL( &value ))
4087 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
4088 else
4089 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
4090 break;
4092 case WinHttpRequestOption_URLCodePage:
4094 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
4095 VARIANT cp;
4097 VariantInit( &cp );
4098 hr = VariantChangeType( &cp, &value, 0, VT_UI4 );
4099 if (SUCCEEDED( hr ))
4101 request->url_codepage = V_UI4( &cp );
4102 TRACE("URL codepage: %u\n", request->url_codepage);
4104 else if (V_VT( &value ) == VT_BSTR && !strcmpiW( V_BSTR( &value ), utf8W ))
4106 TRACE("URL codepage: UTF-8\n");
4107 request->url_codepage = CP_UTF8;
4108 hr = S_OK;
4110 else
4111 FIXME("URL codepage %s is not recognized\n", debugstr_variant( &value ));
4112 break;
4114 default:
4115 FIXME("unimplemented option %u\n", option);
4116 hr = E_NOTIMPL;
4117 break;
4119 LeaveCriticalSection( &request->cs );
4120 return hr;
4123 static HRESULT WINAPI winhttp_request_WaitForResponse(
4124 IWinHttpRequest *iface,
4125 VARIANT timeout,
4126 VARIANT_BOOL *succeeded )
4128 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4129 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
4131 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
4133 EnterCriticalSection( &request->cs );
4134 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
4136 LeaveCriticalSection( &request->cs );
4137 return S_OK;
4139 switch ((err = request_wait( request, msecs )))
4141 case ERROR_TIMEOUT:
4142 if (succeeded) *succeeded = VARIANT_FALSE;
4143 err = ERROR_SUCCESS;
4144 break;
4146 case ERROR_SUCCESS:
4147 if (succeeded) *succeeded = VARIANT_TRUE;
4148 break;
4150 default: break;
4152 LeaveCriticalSection( &request->cs );
4153 return HRESULT_FROM_WIN32( err );
4156 static HRESULT WINAPI winhttp_request_Abort(
4157 IWinHttpRequest *iface )
4159 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4161 TRACE("%p\n", request);
4163 EnterCriticalSection( &request->cs );
4164 cancel_request( request );
4165 LeaveCriticalSection( &request->cs );
4166 return S_OK;
4169 static HRESULT WINAPI winhttp_request_SetTimeouts(
4170 IWinHttpRequest *iface,
4171 LONG resolve_timeout,
4172 LONG connect_timeout,
4173 LONG send_timeout,
4174 LONG receive_timeout )
4176 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4178 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
4180 EnterCriticalSection( &request->cs );
4181 request->resolve_timeout = resolve_timeout;
4182 request->connect_timeout = connect_timeout;
4183 request->send_timeout = send_timeout;
4184 request->receive_timeout = receive_timeout;
4185 LeaveCriticalSection( &request->cs );
4186 return S_OK;
4189 static HRESULT WINAPI winhttp_request_SetClientCertificate(
4190 IWinHttpRequest *iface,
4191 BSTR certificate )
4193 FIXME("\n");
4194 return E_NOTIMPL;
4197 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
4198 IWinHttpRequest *iface,
4199 WinHttpRequestAutoLogonPolicy policy )
4201 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4202 HRESULT hr = S_OK;
4204 TRACE("%p, %u\n", request, policy );
4206 EnterCriticalSection( &request->cs );
4207 switch (policy)
4209 case AutoLogonPolicy_Always:
4210 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
4211 break;
4212 case AutoLogonPolicy_OnlyIfBypassProxy:
4213 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
4214 break;
4215 case AutoLogonPolicy_Never:
4216 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
4217 break;
4218 default: hr = E_INVALIDARG;
4219 break;
4221 LeaveCriticalSection( &request->cs );
4222 return hr;
4225 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
4227 winhttp_request_QueryInterface,
4228 winhttp_request_AddRef,
4229 winhttp_request_Release,
4230 winhttp_request_GetTypeInfoCount,
4231 winhttp_request_GetTypeInfo,
4232 winhttp_request_GetIDsOfNames,
4233 winhttp_request_Invoke,
4234 winhttp_request_SetProxy,
4235 winhttp_request_SetCredentials,
4236 winhttp_request_Open,
4237 winhttp_request_SetRequestHeader,
4238 winhttp_request_GetResponseHeader,
4239 winhttp_request_GetAllResponseHeaders,
4240 winhttp_request_Send,
4241 winhttp_request_get_Status,
4242 winhttp_request_get_StatusText,
4243 winhttp_request_get_ResponseText,
4244 winhttp_request_get_ResponseBody,
4245 winhttp_request_get_ResponseStream,
4246 winhttp_request_get_Option,
4247 winhttp_request_put_Option,
4248 winhttp_request_WaitForResponse,
4249 winhttp_request_Abort,
4250 winhttp_request_SetTimeouts,
4251 winhttp_request_SetClientCertificate,
4252 winhttp_request_SetAutoLogonPolicy
4255 HRESULT WinHttpRequest_create( void **obj )
4257 struct winhttp_request *request;
4259 TRACE("%p\n", obj);
4261 if (!(request = heap_alloc( sizeof(*request) ))) return E_OUTOFMEMORY;
4262 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
4263 request->refs = 1;
4264 request->state = REQUEST_STATE_UNINITIALIZED;
4265 request->proxy.lpszProxy = NULL;
4266 request->proxy.lpszProxyBypass = NULL;
4267 request->url_codepage = CP_UTF8;
4268 InitializeCriticalSection( &request->cs );
4269 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
4271 *obj = &request->IWinHttpRequest_iface;
4272 TRACE("returning iface %p\n", *obj);
4273 return S_OK;