user32: Ignore application-specified DPI awareness when DPI scaling is disabled.
[wine.git] / dlls / winhttp / request.c
blob3e6d2af396aabb684fb14ccbb1c084df9f3d6c82
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 "ws2tcpip.h"
25 #include <stdarg.h>
26 #include <assert.h>
28 #include "windef.h"
29 #include "winbase.h"
30 #include "ole2.h"
31 #include "initguid.h"
32 #include "httprequest.h"
33 #include "httprequestid.h"
34 #include "schannel.h"
35 #include "winhttp.h"
37 #include "wine/debug.h"
38 #include "winhttp_private.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
42 #define DEFAULT_KEEP_ALIVE_TIMEOUT 30000
44 static const WCHAR attr_accept[] = {'A','c','c','e','p','t',0};
45 static const WCHAR attr_accept_charset[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
46 static const WCHAR attr_accept_encoding[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
47 static const WCHAR attr_accept_language[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
48 static const WCHAR attr_accept_ranges[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
49 static const WCHAR attr_age[] = {'A','g','e',0};
50 static const WCHAR attr_allow[] = {'A','l','l','o','w',0};
51 static const WCHAR attr_authorization[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
52 static const WCHAR attr_cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
53 static const WCHAR attr_connection[] = {'C','o','n','n','e','c','t','i','o','n',0};
54 static const WCHAR attr_content_base[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
55 static const WCHAR attr_content_encoding[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
56 static const WCHAR attr_content_id[] = {'C','o','n','t','e','n','t','-','I','D',0};
57 static const WCHAR attr_content_language[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
58 static const WCHAR attr_content_length[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
59 static const WCHAR attr_content_location[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
60 static const WCHAR attr_content_md5[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
61 static const WCHAR attr_content_range[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
62 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};
63 static const WCHAR attr_content_type[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
64 static const WCHAR attr_cookie[] = {'C','o','o','k','i','e',0};
65 static const WCHAR attr_date[] = {'D','a','t','e',0};
66 static const WCHAR attr_from[] = {'F','r','o','m',0};
67 static const WCHAR attr_etag[] = {'E','T','a','g',0};
68 static const WCHAR attr_expect[] = {'E','x','p','e','c','t',0};
69 static const WCHAR attr_expires[] = {'E','x','p','i','r','e','s',0};
70 static const WCHAR attr_host[] = {'H','o','s','t',0};
71 static const WCHAR attr_if_match[] = {'I','f','-','M','a','t','c','h',0};
72 static const WCHAR attr_if_modified_since[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
73 static const WCHAR attr_if_none_match[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
74 static const WCHAR attr_if_range[] = {'I','f','-','R','a','n','g','e',0};
75 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};
76 static const WCHAR attr_last_modified[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
77 static const WCHAR attr_location[] = {'L','o','c','a','t','i','o','n',0};
78 static const WCHAR attr_max_forwards[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
79 static const WCHAR attr_mime_version[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
80 static const WCHAR attr_pragma[] = {'P','r','a','g','m','a',0};
81 static const WCHAR attr_proxy_authenticate[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
82 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};
83 static const WCHAR attr_proxy_connection[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
84 static const WCHAR attr_public[] = {'P','u','b','l','i','c',0};
85 static const WCHAR attr_range[] = {'R','a','n','g','e',0};
86 static const WCHAR attr_referer[] = {'R','e','f','e','r','e','r',0};
87 static const WCHAR attr_retry_after[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
88 static const WCHAR attr_server[] = {'S','e','r','v','e','r',0};
89 static const WCHAR attr_set_cookie[] = {'S','e','t','-','C','o','o','k','i','e',0};
90 static const WCHAR attr_status[] = {'S','t','a','t','u','s',0};
91 static const WCHAR attr_transfer_encoding[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
92 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};
93 static const WCHAR attr_upgrade[] = {'U','p','g','r','a','d','e',0};
94 static const WCHAR attr_uri[] = {'U','R','I',0};
95 static const WCHAR attr_user_agent[] = {'U','s','e','r','-','A','g','e','n','t',0};
96 static const WCHAR attr_vary[] = {'V','a','r','y',0};
97 static const WCHAR attr_via[] = {'V','i','a',0};
98 static const WCHAR attr_warning[] = {'W','a','r','n','i','n','g',0};
99 static const WCHAR attr_www_authenticate[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
101 static const WCHAR *attribute_table[] =
103 attr_mime_version, /* WINHTTP_QUERY_MIME_VERSION = 0 */
104 attr_content_type, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
105 attr_content_transfer_encoding, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
106 attr_content_id, /* WINHTTP_QUERY_CONTENT_ID = 3 */
107 NULL, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
108 attr_content_length, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
109 attr_content_language, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
110 attr_allow, /* WINHTTP_QUERY_ALLOW = 7 */
111 attr_public, /* WINHTTP_QUERY_PUBLIC = 8 */
112 attr_date, /* WINHTTP_QUERY_DATE = 9 */
113 attr_expires, /* WINHTTP_QUERY_EXPIRES = 10 */
114 attr_last_modified, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
115 NULL, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
116 attr_uri, /* WINHTTP_QUERY_URI = 13 */
117 attr_from, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
118 NULL, /* WINHTTP_QUERY_COST = 15 */
119 NULL, /* WINHTTP_QUERY_LINK = 16 */
120 attr_pragma, /* WINHTTP_QUERY_PRAGMA = 17 */
121 NULL, /* WINHTTP_QUERY_VERSION = 18 */
122 attr_status, /* WINHTTP_QUERY_STATUS_CODE = 19 */
123 NULL, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
124 NULL, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
125 NULL, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
126 attr_connection, /* WINHTTP_QUERY_CONNECTION = 23 */
127 attr_accept, /* WINHTTP_QUERY_ACCEPT = 24 */
128 attr_accept_charset, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
129 attr_accept_encoding, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
130 attr_accept_language, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
131 attr_authorization, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
132 attr_content_encoding, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
133 NULL, /* WINHTTP_QUERY_FORWARDED = 30 */
134 NULL, /* WINHTTP_QUERY_FROM = 31 */
135 attr_if_modified_since, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
136 attr_location, /* WINHTTP_QUERY_LOCATION = 33 */
137 NULL, /* WINHTTP_QUERY_ORIG_URI = 34 */
138 attr_referer, /* WINHTTP_QUERY_REFERER = 35 */
139 attr_retry_after, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
140 attr_server, /* WINHTTP_QUERY_SERVER = 37 */
141 NULL, /* WINHTTP_TITLE = 38 */
142 attr_user_agent, /* WINHTTP_QUERY_USER_AGENT = 39 */
143 attr_www_authenticate, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
144 attr_proxy_authenticate, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
145 attr_accept_ranges, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
146 attr_set_cookie, /* WINHTTP_QUERY_SET_COOKIE = 43 */
147 attr_cookie, /* WINHTTP_QUERY_COOKIE = 44 */
148 NULL, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
149 NULL, /* WINHTTP_QUERY_REFRESH = 46 */
150 NULL, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
151 attr_age, /* WINHTTP_QUERY_AGE = 48 */
152 attr_cache_control, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
153 attr_content_base, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
154 attr_content_location, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
155 attr_content_md5, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
156 attr_content_range, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
157 attr_etag, /* WINHTTP_QUERY_ETAG = 54 */
158 attr_host, /* WINHTTP_QUERY_HOST = 55 */
159 attr_if_match, /* WINHTTP_QUERY_IF_MATCH = 56 */
160 attr_if_none_match, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
161 attr_if_range, /* WINHTTP_QUERY_IF_RANGE = 58 */
162 attr_if_unmodified_since, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
163 attr_max_forwards, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
164 attr_proxy_authorization, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
165 attr_range, /* WINHTTP_QUERY_RANGE = 62 */
166 attr_transfer_encoding, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
167 attr_upgrade, /* WINHTTP_QUERY_UPGRADE = 64 */
168 attr_vary, /* WINHTTP_QUERY_VARY = 65 */
169 attr_via, /* WINHTTP_QUERY_VIA = 66 */
170 attr_warning, /* WINHTTP_QUERY_WARNING = 67 */
171 attr_expect, /* WINHTTP_QUERY_EXPECT = 68 */
172 attr_proxy_connection, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
173 attr_unless_modified_since, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
174 NULL, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
175 NULL, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
176 NULL, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
177 NULL /* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
180 static task_header_t *dequeue_task( request_t *request )
182 task_header_t *task;
184 EnterCriticalSection( &request->task_cs );
185 TRACE("%u tasks queued\n", list_count( &request->task_queue ));
186 task = LIST_ENTRY( list_head( &request->task_queue ), task_header_t, entry );
187 if (task) list_remove( &task->entry );
188 LeaveCriticalSection( &request->task_cs );
190 TRACE("returning task %p\n", task);
191 return task;
194 static DWORD CALLBACK task_proc( LPVOID param )
196 request_t *request = param;
197 HANDLE handles[2];
199 handles[0] = request->task_wait;
200 handles[1] = request->task_cancel;
201 for (;;)
203 DWORD err = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
204 switch (err)
206 case WAIT_OBJECT_0:
208 task_header_t *task;
209 while ((task = dequeue_task( request )))
211 task->proc( task );
212 release_object( &task->request->hdr );
213 heap_free( task );
215 break;
217 case WAIT_OBJECT_0 + 1:
218 TRACE("exiting\n");
219 CloseHandle( request->task_cancel );
220 CloseHandle( request->task_wait );
221 request->task_cs.DebugInfo->Spare[0] = 0;
222 DeleteCriticalSection( &request->task_cs );
223 request->hdr.vtbl->destroy( &request->hdr );
224 return 0;
226 default:
227 ERR("wait failed %u (%u)\n", err, GetLastError());
228 break;
231 return 0;
234 static BOOL queue_task( task_header_t *task )
236 request_t *request = task->request;
238 if (!request->task_thread)
240 if (!(request->task_wait = CreateEventW( NULL, FALSE, FALSE, NULL ))) return FALSE;
241 if (!(request->task_cancel = CreateEventW( NULL, FALSE, FALSE, NULL )))
243 CloseHandle( request->task_wait );
244 request->task_wait = NULL;
245 return FALSE;
247 if (!(request->task_thread = CreateThread( NULL, 0, task_proc, request, 0, NULL )))
249 CloseHandle( request->task_wait );
250 request->task_wait = NULL;
251 CloseHandle( request->task_cancel );
252 request->task_cancel = NULL;
253 return FALSE;
255 InitializeCriticalSection( &request->task_cs );
256 request->task_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": request.task_cs");
259 EnterCriticalSection( &request->task_cs );
260 TRACE("queueing task %p\n", task );
261 list_add_tail( &request->task_queue, &task->entry );
262 LeaveCriticalSection( &request->task_cs );
264 SetEvent( request->task_wait );
265 return TRUE;
268 static void free_header( header_t *header )
270 heap_free( header->field );
271 heap_free( header->value );
272 heap_free( header );
275 static BOOL valid_token_char( WCHAR c )
277 if (c < 32 || c == 127) return FALSE;
278 switch (c)
280 case '(': case ')':
281 case '<': case '>':
282 case '@': case ',':
283 case ';': case ':':
284 case '\\': case '\"':
285 case '/': case '[':
286 case ']': case '?':
287 case '=': case '{':
288 case '}': case ' ':
289 case '\t':
290 return FALSE;
291 default:
292 return TRUE;
296 static header_t *parse_header( LPCWSTR string )
298 const WCHAR *p, *q;
299 header_t *header;
300 int len;
302 p = string;
303 if (!(q = strchrW( p, ':' )))
305 WARN("no ':' in line %s\n", debugstr_w(string));
306 return NULL;
308 if (q == string)
310 WARN("empty field name in line %s\n", debugstr_w(string));
311 return NULL;
313 while (*p != ':')
315 if (!valid_token_char( *p ))
317 WARN("invalid character in field name %s\n", debugstr_w(string));
318 return NULL;
320 p++;
322 len = q - string;
323 if (!(header = heap_alloc_zero( sizeof(header_t) ))) return NULL;
324 if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
326 heap_free( header );
327 return NULL;
329 memcpy( header->field, string, len * sizeof(WCHAR) );
330 header->field[len] = 0;
332 q++; /* skip past colon */
333 while (*q == ' ') q++;
334 len = strlenW( q );
336 if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
338 free_header( header );
339 return NULL;
341 memcpy( header->value, q, len * sizeof(WCHAR) );
342 header->value[len] = 0;
344 return header;
347 static int get_header_index( request_t *request, LPCWSTR field, int requested_index, BOOL request_only )
349 int index;
351 TRACE("%s\n", debugstr_w(field));
353 for (index = 0; index < request->num_headers; index++)
355 if (strcmpiW( request->headers[index].field, field )) continue;
356 if (request_only && !request->headers[index].is_request) continue;
357 if (!request_only && request->headers[index].is_request) continue;
359 if (!requested_index) break;
360 requested_index--;
362 if (index >= request->num_headers) index = -1;
363 TRACE("returning %d\n", index);
364 return index;
367 static BOOL insert_header( request_t *request, header_t *header )
369 DWORD count = request->num_headers + 1;
370 header_t *hdrs;
372 if (request->headers)
373 hdrs = heap_realloc_zero( request->headers, sizeof(header_t) * count );
374 else
375 hdrs = heap_alloc_zero( sizeof(header_t) );
376 if (!hdrs) return FALSE;
378 request->headers = hdrs;
379 request->headers[count - 1].field = strdupW( header->field );
380 request->headers[count - 1].value = strdupW( header->value );
381 request->headers[count - 1].is_request = header->is_request;
382 request->num_headers = count;
383 return TRUE;
386 static BOOL delete_header( request_t *request, DWORD index )
388 if (!request->num_headers) return FALSE;
389 if (index >= request->num_headers) return FALSE;
390 request->num_headers--;
392 heap_free( request->headers[index].field );
393 heap_free( request->headers[index].value );
395 memmove( &request->headers[index], &request->headers[index + 1], (request->num_headers - index) * sizeof(header_t) );
396 memset( &request->headers[request->num_headers], 0, sizeof(header_t) );
397 return TRUE;
400 static BOOL process_header( request_t *request, LPCWSTR field, LPCWSTR value, DWORD flags, BOOL request_only )
402 int index;
403 header_t hdr;
405 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
407 if ((index = get_header_index( request, field, 0, request_only )) >= 0)
409 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
412 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
414 if (index >= 0)
416 delete_header( request, index );
417 if (!value || !value[0]) return TRUE;
419 else if (!(flags & WINHTTP_ADDREQ_FLAG_ADD))
421 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
422 return FALSE;
425 hdr.field = (LPWSTR)field;
426 hdr.value = (LPWSTR)value;
427 hdr.is_request = request_only;
428 return insert_header( request, &hdr );
430 else if (value)
433 if ((flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON)) &&
434 index >= 0)
436 WCHAR *tmp;
437 int len, len_orig, len_value;
438 header_t *header = &request->headers[index];
440 len_orig = strlenW( header->value );
441 len_value = strlenW( value );
443 len = len_orig + len_value + 2;
444 if (!(tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) ))) return FALSE;
445 header->value = tmp;
446 header->value[len_orig++] = (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) ? ',' : ';';
447 header->value[len_orig++] = ' ';
449 memcpy( &header->value[len_orig], value, len_value * sizeof(WCHAR) );
450 header->value[len] = 0;
451 return TRUE;
453 else
455 hdr.field = (LPWSTR)field;
456 hdr.value = (LPWSTR)value;
457 hdr.is_request = request_only;
458 return insert_header( request, &hdr );
462 return TRUE;
465 BOOL add_request_headers( request_t *request, LPCWSTR headers, DWORD len, DWORD flags )
467 BOOL ret = FALSE;
468 WCHAR *buffer, *p, *q;
469 header_t *header;
471 if (len == ~0u) len = strlenW( headers );
472 if (!len) return TRUE;
473 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
474 memcpy( buffer, headers, len * sizeof(WCHAR) );
475 buffer[len] = 0;
477 p = buffer;
480 q = p;
481 while (*q)
483 if (q[0] == '\n' && q[1] == '\r')
485 q[0] = '\r';
486 q[1] = '\n';
488 if (q[0] == '\r' && q[1] == '\n') break;
489 q++;
491 if (!*p) break;
492 if (*q == '\r')
494 *q = 0;
495 q += 2; /* jump over \r\n */
497 if ((header = parse_header( p )))
499 ret = process_header( request, header->field, header->value, flags, TRUE );
500 free_header( header );
502 p = q;
503 } while (ret);
505 heap_free( buffer );
506 return ret;
509 /***********************************************************************
510 * WinHttpAddRequestHeaders (winhttp.@)
512 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
514 BOOL ret;
515 request_t *request;
517 TRACE("%p, %s, %u, 0x%08x\n", hrequest, debugstr_wn(headers, len), len, flags);
519 if (!headers || !len)
521 set_last_error( ERROR_INVALID_PARAMETER );
522 return FALSE;
524 if (!(request = (request_t *)grab_object( hrequest )))
526 set_last_error( ERROR_INVALID_HANDLE );
527 return FALSE;
529 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
531 release_object( &request->hdr );
532 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
533 return FALSE;
536 ret = add_request_headers( request, headers, len, flags );
538 release_object( &request->hdr );
539 if (ret) set_last_error( ERROR_SUCCESS );
540 return ret;
543 static WCHAR *build_request_path( request_t *request )
545 WCHAR *ret;
547 if (strcmpiW( request->connect->hostname, request->connect->servername ))
549 static const WCHAR http[] = { 'h','t','t','p',0 };
550 static const WCHAR https[] = { 'h','t','t','p','s',0 };
551 static const WCHAR fmt[] = { '%','s',':','/','/','%','s',0 };
552 LPCWSTR scheme = (request->netconn ? request->netconn->secure : (request->hdr.flags & WINHTTP_FLAG_SECURE)) ? https : http;
553 int len;
555 len = strlenW( scheme ) + strlenW( request->connect->hostname );
556 /* 3 characters for '://', 1 for NUL. */
557 len += 4;
558 if (request->connect->hostport)
560 /* 1 for ':' between host and port, up to 5 for port */
561 len += 6;
563 if (request->path)
564 len += strlenW( request->path );
565 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
567 sprintfW( ret, fmt, scheme, request->connect->hostname );
568 if (request->connect->hostport)
570 static const WCHAR colonFmt[] = { ':','%','u',0 };
572 sprintfW( ret + strlenW( ret ), colonFmt,
573 request->connect->hostport );
575 if (request->path)
576 strcatW( ret, request->path );
579 else
580 ret = request->path;
581 return ret;
584 static WCHAR *build_request_string( request_t *request )
586 static const WCHAR space[] = {' ',0};
587 static const WCHAR crlf[] = {'\r','\n',0};
588 static const WCHAR colon[] = {':',' ',0};
589 static const WCHAR twocrlf[] = {'\r','\n','\r','\n',0};
591 WCHAR *path, *ret;
592 const WCHAR **headers, **p;
593 unsigned int len, i = 0, j;
595 /* allocate space for an array of all the string pointers to be added */
596 len = request->num_headers * 4 + 7;
597 if (!(headers = heap_alloc( len * sizeof(LPCWSTR) ))) return NULL;
599 path = build_request_path( request );
600 headers[i++] = request->verb;
601 headers[i++] = space;
602 headers[i++] = path;
603 headers[i++] = space;
604 headers[i++] = request->version;
606 for (j = 0; j < request->num_headers; j++)
608 if (request->headers[j].is_request)
610 headers[i++] = crlf;
611 headers[i++] = request->headers[j].field;
612 headers[i++] = colon;
613 headers[i++] = request->headers[j].value;
615 TRACE("adding header %s (%s)\n", debugstr_w(request->headers[j].field),
616 debugstr_w(request->headers[j].value));
619 headers[i++] = twocrlf;
620 headers[i] = NULL;
622 len = 0;
623 for (p = headers; *p; p++) len += strlenW( *p );
624 len++;
626 if (!(ret = heap_alloc( len * sizeof(WCHAR) )))
627 goto out;
628 *ret = 0;
629 for (p = headers; *p; p++) strcatW( ret, *p );
631 out:
632 if (path != request->path)
633 heap_free( path );
634 heap_free( headers );
635 return ret;
638 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
640 static BOOL query_headers( request_t *request, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
642 header_t *header = NULL;
643 BOOL request_only, ret = FALSE;
644 int requested_index, header_index = -1;
645 DWORD attr, len;
647 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
648 requested_index = index ? *index : 0;
650 attr = level & ~QUERY_MODIFIER_MASK;
651 switch (attr)
653 case WINHTTP_QUERY_CUSTOM:
655 header_index = get_header_index( request, name, requested_index, request_only );
656 break;
658 case WINHTTP_QUERY_RAW_HEADERS:
660 WCHAR *headers, *p, *q;
662 if (request_only)
663 headers = build_request_string( request );
664 else
665 headers = request->raw_headers;
667 if (!(p = headers)) return FALSE;
668 for (len = 0; *p; p++) if (*p != '\r') len++;
670 if (!buffer || len * sizeof(WCHAR) > *buflen)
671 set_last_error( ERROR_INSUFFICIENT_BUFFER );
672 else
674 for (p = headers, q = buffer; *p; p++, q++)
676 if (*p != '\r') *q = *p;
677 else
679 *q = 0;
680 p++; /* skip '\n' */
683 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
684 if (len) len--;
685 ret = TRUE;
687 *buflen = len * sizeof(WCHAR);
688 if (request_only) heap_free( headers );
689 return ret;
691 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
693 WCHAR *headers;
695 if (request_only)
696 headers = build_request_string( request );
697 else
698 headers = request->raw_headers;
700 if (!headers) return FALSE;
701 len = strlenW( headers ) * sizeof(WCHAR);
702 if (!buffer || len + sizeof(WCHAR) > *buflen)
704 len += sizeof(WCHAR);
705 set_last_error( ERROR_INSUFFICIENT_BUFFER );
707 else
709 memcpy( buffer, headers, len + sizeof(WCHAR) );
710 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
711 ret = TRUE;
713 *buflen = len;
714 if (request_only) heap_free( headers );
715 return ret;
717 case WINHTTP_QUERY_VERSION:
718 len = strlenW( request->version ) * sizeof(WCHAR);
719 if (!buffer || len + sizeof(WCHAR) > *buflen)
721 len += sizeof(WCHAR);
722 set_last_error( ERROR_INSUFFICIENT_BUFFER );
724 else
726 strcpyW( buffer, request->version );
727 TRACE("returning string: %s\n", debugstr_w(buffer));
728 ret = TRUE;
730 *buflen = len;
731 return ret;
733 case WINHTTP_QUERY_STATUS_TEXT:
734 len = strlenW( request->status_text ) * sizeof(WCHAR);
735 if (!buffer || len + sizeof(WCHAR) > *buflen)
737 len += sizeof(WCHAR);
738 set_last_error( ERROR_INSUFFICIENT_BUFFER );
740 else
742 strcpyW( buffer, request->status_text );
743 TRACE("returning string: %s\n", debugstr_w(buffer));
744 ret = TRUE;
746 *buflen = len;
747 return ret;
749 default:
750 if (attr >= sizeof(attribute_table)/sizeof(attribute_table[0]) || !attribute_table[attr])
752 FIXME("attribute %u not implemented\n", attr);
753 return FALSE;
755 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
756 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
757 break;
760 if (header_index >= 0)
762 header = &request->headers[header_index];
764 if (!header || (request_only && !header->is_request))
766 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
767 return FALSE;
769 if (index) *index += 1;
770 if (level & WINHTTP_QUERY_FLAG_NUMBER)
772 if (!buffer || sizeof(int) > *buflen)
774 set_last_error( ERROR_INSUFFICIENT_BUFFER );
776 else
778 int *number = buffer;
779 *number = atoiW( header->value );
780 TRACE("returning number: %d\n", *number);
781 ret = TRUE;
783 *buflen = sizeof(int);
785 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
787 SYSTEMTIME *st = buffer;
788 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
790 set_last_error( ERROR_INSUFFICIENT_BUFFER );
792 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
794 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
795 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
796 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
798 *buflen = sizeof(SYSTEMTIME);
800 else if (header->value)
802 len = strlenW( header->value ) * sizeof(WCHAR);
803 if (!buffer || len + sizeof(WCHAR) > *buflen)
805 len += sizeof(WCHAR);
806 set_last_error( ERROR_INSUFFICIENT_BUFFER );
808 else
810 strcpyW( buffer, header->value );
811 TRACE("returning string: %s\n", debugstr_w(buffer));
812 ret = TRUE;
814 *buflen = len;
816 return ret;
819 /***********************************************************************
820 * WinHttpQueryHeaders (winhttp.@)
822 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
824 BOOL ret;
825 request_t *request;
827 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
829 if (!(request = (request_t *)grab_object( hrequest )))
831 set_last_error( ERROR_INVALID_HANDLE );
832 return FALSE;
834 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
836 release_object( &request->hdr );
837 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
838 return FALSE;
841 ret = query_headers( request, level, name, buffer, buflen, index );
843 release_object( &request->hdr );
844 if (ret) set_last_error( ERROR_SUCCESS );
845 return ret;
849 static const WCHAR basicW[] = {'B','a','s','i','c',0};
850 static const WCHAR ntlmW[] = {'N','T','L','M',0};
851 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
852 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
853 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
855 static const struct
857 const WCHAR *str;
858 unsigned int len;
859 DWORD scheme;
861 auth_schemes[] =
863 { basicW, ARRAY_SIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
864 { ntlmW, ARRAY_SIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
865 { passportW, ARRAY_SIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
866 { digestW, ARRAY_SIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
867 { negotiateW, ARRAY_SIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
869 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
871 static enum auth_scheme scheme_from_flag( DWORD flag )
873 int i;
875 for (i = 0; i < num_auth_schemes; i++) if (flag == auth_schemes[i].scheme) return i;
876 return SCHEME_INVALID;
879 static DWORD auth_scheme_from_header( WCHAR *header )
881 unsigned int i;
883 for (i = 0; i < num_auth_schemes; i++)
885 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
886 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
888 return 0;
891 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
893 DWORD index = 0, supported_schemes = 0, first_scheme = 0;
894 BOOL ret = FALSE;
896 for (;;)
898 WCHAR *buffer;
899 DWORD size, scheme;
901 size = 0;
902 query_headers( request, level, NULL, NULL, &size, &index );
903 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) break;
905 index--;
906 if (!(buffer = heap_alloc( size ))) return FALSE;
907 if (!query_headers( request, level, NULL, buffer, &size, &index ))
909 heap_free( buffer );
910 return FALSE;
912 scheme = auth_scheme_from_header( buffer );
913 heap_free( buffer );
914 if (!scheme) continue;
916 if (!first_scheme) first_scheme = scheme;
917 supported_schemes |= scheme;
919 ret = TRUE;
922 if (ret)
924 *supported = supported_schemes;
925 *first = first_scheme;
927 return ret;
930 /***********************************************************************
931 * WinHttpQueryAuthSchemes (winhttp.@)
933 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
935 BOOL ret = FALSE;
936 request_t *request;
938 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
940 if (!(request = (request_t *)grab_object( hrequest )))
942 set_last_error( ERROR_INVALID_HANDLE );
943 return FALSE;
945 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
947 release_object( &request->hdr );
948 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
949 return FALSE;
951 if (!supported || !first || !target)
953 release_object( &request->hdr );
954 set_last_error( ERROR_INVALID_PARAMETER );
955 return FALSE;
959 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
961 *target = WINHTTP_AUTH_TARGET_SERVER;
962 ret = TRUE;
964 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
966 *target = WINHTTP_AUTH_TARGET_PROXY;
967 ret = TRUE;
970 release_object( &request->hdr );
971 if (ret) set_last_error( ERROR_SUCCESS );
972 return ret;
975 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
977 UINT n = 0, x;
978 static const char base64enc[] =
979 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
981 while (len > 0)
983 /* first 6 bits, all from bin[0] */
984 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
985 x = (bin[0] & 3) << 4;
987 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
988 if (len == 1)
990 base64[n++] = base64enc[x];
991 base64[n++] = '=';
992 base64[n++] = '=';
993 break;
995 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
996 x = (bin[1] & 0x0f) << 2;
998 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
999 if (len == 2)
1001 base64[n++] = base64enc[x];
1002 base64[n++] = '=';
1003 break;
1005 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1007 /* last 6 bits, all from bin [2] */
1008 base64[n++] = base64enc[bin[2] & 0x3f];
1009 bin += 3;
1010 len -= 3;
1012 base64[n] = 0;
1013 return n;
1016 static inline char decode_char( WCHAR c )
1018 if (c >= 'A' && c <= 'Z') return c - 'A';
1019 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1020 if (c >= '0' && c <= '9') return c - '0' + 52;
1021 if (c == '+') return 62;
1022 if (c == '/') return 63;
1023 return 64;
1026 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1028 unsigned int i = 0;
1029 char c0, c1, c2, c3;
1030 const WCHAR *p = base64;
1032 while (len > 4)
1034 if ((c0 = decode_char( p[0] )) > 63) return 0;
1035 if ((c1 = decode_char( p[1] )) > 63) return 0;
1036 if ((c2 = decode_char( p[2] )) > 63) return 0;
1037 if ((c3 = decode_char( p[3] )) > 63) return 0;
1039 if (buf)
1041 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1042 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1043 buf[i + 2] = (c2 << 6) | c3;
1045 len -= 4;
1046 i += 3;
1047 p += 4;
1049 if (p[2] == '=')
1051 if ((c0 = decode_char( p[0] )) > 63) return 0;
1052 if ((c1 = decode_char( p[1] )) > 63) return 0;
1054 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1055 i++;
1057 else if (p[3] == '=')
1059 if ((c0 = decode_char( p[0] )) > 63) return 0;
1060 if ((c1 = decode_char( p[1] )) > 63) return 0;
1061 if ((c2 = decode_char( p[2] )) > 63) return 0;
1063 if (buf)
1065 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1066 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1068 i += 2;
1070 else
1072 if ((c0 = decode_char( p[0] )) > 63) return 0;
1073 if ((c1 = decode_char( p[1] )) > 63) return 0;
1074 if ((c2 = decode_char( p[2] )) > 63) return 0;
1075 if ((c3 = decode_char( p[3] )) > 63) return 0;
1077 if (buf)
1079 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1080 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1081 buf[i + 2] = (c2 << 6) | c3;
1083 i += 3;
1085 return i;
1088 static struct authinfo *alloc_authinfo(void)
1090 struct authinfo *ret;
1092 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1094 SecInvalidateHandle( &ret->cred );
1095 SecInvalidateHandle( &ret->ctx );
1096 memset( &ret->exp, 0, sizeof(ret->exp) );
1097 ret->scheme = 0;
1098 ret->attr = 0;
1099 ret->max_token = 0;
1100 ret->data = NULL;
1101 ret->data_len = 0;
1102 ret->finished = FALSE;
1103 return ret;
1106 void destroy_authinfo( struct authinfo *authinfo )
1108 if (!authinfo) return;
1110 if (SecIsValidHandle( &authinfo->ctx ))
1111 DeleteSecurityContext( &authinfo->ctx );
1112 if (SecIsValidHandle( &authinfo->cred ))
1113 FreeCredentialsHandle( &authinfo->cred );
1115 heap_free( authinfo->data );
1116 heap_free( authinfo );
1119 static BOOL get_authvalue( request_t *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1121 DWORD size, index = 0;
1122 for (;;)
1124 size = len;
1125 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1126 if (auth_scheme_from_header( buffer ) == scheme) break;
1128 return TRUE;
1131 static BOOL do_authorization( request_t *request, DWORD target, DWORD scheme_flag )
1133 struct authinfo *authinfo, **auth_ptr;
1134 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1135 const WCHAR *auth_target, *username, *password;
1136 WCHAR auth_value[2048], *auth_reply;
1137 DWORD len = sizeof(auth_value), len_scheme, flags;
1138 BOOL ret, has_auth_value;
1140 if (scheme == SCHEME_INVALID) return FALSE;
1142 switch (target)
1144 case WINHTTP_AUTH_TARGET_SERVER:
1145 has_auth_value = get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len );
1146 auth_ptr = &request->authinfo;
1147 auth_target = attr_authorization;
1148 if (request->creds[TARGET_SERVER][scheme].username)
1150 if (scheme != SCHEME_BASIC && !has_auth_value) return FALSE;
1151 username = request->creds[TARGET_SERVER][scheme].username;
1152 password = request->creds[TARGET_SERVER][scheme].password;
1154 else
1156 if (!has_auth_value) return FALSE;
1157 username = request->connect->username;
1158 password = request->connect->password;
1160 break;
1162 case WINHTTP_AUTH_TARGET_PROXY:
1163 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1164 return FALSE;
1165 auth_ptr = &request->proxy_authinfo;
1166 auth_target = attr_proxy_authorization;
1167 if (request->creds[TARGET_PROXY][scheme].username)
1169 username = request->creds[TARGET_PROXY][scheme].username;
1170 password = request->creds[TARGET_PROXY][scheme].password;
1172 else
1174 username = request->connect->session->proxy_username;
1175 password = request->connect->session->proxy_password;
1177 break;
1179 default:
1180 WARN("unknown target %x\n", target);
1181 return FALSE;
1183 authinfo = *auth_ptr;
1185 switch (scheme)
1187 case SCHEME_BASIC:
1189 int userlen, passlen;
1191 if (!username || !password) return FALSE;
1192 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1194 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1195 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1197 authinfo->data_len = userlen + 1 + passlen;
1198 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1200 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1201 authinfo->data[userlen] = ':';
1202 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1204 authinfo->scheme = SCHEME_BASIC;
1205 authinfo->finished = TRUE;
1206 break;
1208 case SCHEME_NTLM:
1209 case SCHEME_NEGOTIATE:
1211 SECURITY_STATUS status;
1212 SecBufferDesc out_desc, in_desc;
1213 SecBuffer out, in;
1214 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1215 const WCHAR *p;
1216 BOOL first = FALSE;
1218 if (!authinfo)
1220 TimeStamp exp;
1221 SEC_WINNT_AUTH_IDENTITY_W id;
1222 WCHAR *domain, *user;
1224 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1226 first = TRUE;
1227 domain = (WCHAR *)username;
1228 user = strchrW( username, '\\' );
1230 if (user) user++;
1231 else
1233 user = (WCHAR *)username;
1234 domain = NULL;
1236 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1237 id.User = user;
1238 id.UserLength = strlenW( user );
1239 id.Domain = domain;
1240 id.DomainLength = domain ? user - domain - 1 : 0;
1241 id.Password = (WCHAR *)password;
1242 id.PasswordLength = strlenW( password );
1244 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1245 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1246 &authinfo->cred, &exp );
1247 if (status == SEC_E_OK)
1249 PSecPkgInfoW info;
1250 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1251 if (status == SEC_E_OK)
1253 authinfo->max_token = info->cbMaxToken;
1254 FreeContextBuffer( info );
1257 if (status != SEC_E_OK)
1259 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1260 debugstr_w(auth_schemes[scheme].str), status);
1261 heap_free( authinfo );
1262 return FALSE;
1264 authinfo->scheme = scheme;
1266 else if (authinfo->finished) return FALSE;
1268 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1269 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1271 ERR("authentication scheme changed from %s to %s\n",
1272 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1273 destroy_authinfo( authinfo );
1274 *auth_ptr = NULL;
1275 return FALSE;
1277 in.BufferType = SECBUFFER_TOKEN;
1278 in.cbBuffer = 0;
1279 in.pvBuffer = NULL;
1281 in_desc.ulVersion = 0;
1282 in_desc.cBuffers = 1;
1283 in_desc.pBuffers = &in;
1285 p = auth_value + auth_schemes[scheme].len;
1286 if (*p == ' ')
1288 int len = strlenW( ++p );
1289 in.cbBuffer = decode_base64( p, len, NULL );
1290 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) {
1291 destroy_authinfo( authinfo );
1292 *auth_ptr = NULL;
1293 return FALSE;
1295 decode_base64( p, len, in.pvBuffer );
1297 out.BufferType = SECBUFFER_TOKEN;
1298 out.cbBuffer = authinfo->max_token;
1299 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1301 heap_free( in.pvBuffer );
1302 destroy_authinfo( authinfo );
1303 *auth_ptr = NULL;
1304 return FALSE;
1306 out_desc.ulVersion = 0;
1307 out_desc.cBuffers = 1;
1308 out_desc.pBuffers = &out;
1310 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1311 first ? request->connect->servername : NULL, flags, 0,
1312 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1313 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1314 heap_free( in.pvBuffer );
1315 if (status == SEC_E_OK)
1317 heap_free( authinfo->data );
1318 authinfo->data = out.pvBuffer;
1319 authinfo->data_len = out.cbBuffer;
1320 authinfo->finished = TRUE;
1321 TRACE("sending last auth packet\n");
1323 else if (status == SEC_I_CONTINUE_NEEDED)
1325 heap_free( authinfo->data );
1326 authinfo->data = out.pvBuffer;
1327 authinfo->data_len = out.cbBuffer;
1328 TRACE("sending next auth packet\n");
1330 else
1332 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1333 heap_free( out.pvBuffer );
1334 destroy_authinfo( authinfo );
1335 *auth_ptr = NULL;
1336 return FALSE;
1338 break;
1340 default:
1341 ERR("invalid scheme %u\n", scheme);
1342 return FALSE;
1344 *auth_ptr = authinfo;
1346 len_scheme = auth_schemes[authinfo->scheme].len;
1347 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1348 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1350 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1351 auth_reply[len_scheme] = ' ';
1352 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1354 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1355 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1356 heap_free( auth_reply );
1357 return ret;
1360 static LPWSTR concatenate_string_list( LPCWSTR *list, int len )
1362 LPCWSTR *t;
1363 LPWSTR str;
1365 for( t = list; *t ; t++ )
1366 len += strlenW( *t );
1367 len++;
1369 str = heap_alloc( len * sizeof(WCHAR) );
1370 if (!str) return NULL;
1371 *str = 0;
1373 for( t = list; *t ; t++ )
1374 strcatW( str, *t );
1376 return str;
1379 static LPWSTR build_header_request_string( request_t *request, LPCWSTR verb,
1380 LPCWSTR path, LPCWSTR version )
1382 static const WCHAR crlf[] = {'\r','\n',0};
1383 static const WCHAR space[] = { ' ',0 };
1384 static const WCHAR colon[] = { ':',' ',0 };
1385 static const WCHAR twocrlf[] = {'\r','\n','\r','\n', 0};
1386 LPWSTR requestString;
1387 DWORD len, n;
1388 LPCWSTR *req;
1389 UINT i;
1390 LPWSTR p;
1392 /* allocate space for an array of all the string pointers to be added */
1393 len = (request->num_headers) * 4 + 10;
1394 req = heap_alloc( len * sizeof(LPCWSTR) );
1395 if (!req) return NULL;
1397 /* add the verb, path and HTTP version string */
1398 n = 0;
1399 req[n++] = verb;
1400 req[n++] = space;
1401 req[n++] = path;
1402 req[n++] = space;
1403 req[n++] = version;
1405 /* Append custom request headers */
1406 for (i = 0; i < request->num_headers; i++)
1408 if (request->headers[i].is_request)
1410 req[n++] = crlf;
1411 req[n++] = request->headers[i].field;
1412 req[n++] = colon;
1413 req[n++] = request->headers[i].value;
1415 TRACE("Adding custom header %s (%s)\n",
1416 debugstr_w(request->headers[i].field),
1417 debugstr_w(request->headers[i].value));
1421 if( n >= len )
1422 ERR("oops. buffer overrun\n");
1424 req[n] = NULL;
1425 requestString = concatenate_string_list( req, 4 );
1426 heap_free( req );
1427 if (!requestString) return NULL;
1430 * Set (header) termination string for request
1431 * Make sure there are exactly two new lines at the end of the request
1433 p = &requestString[strlenW(requestString)-1];
1434 while ( (*p == '\n') || (*p == '\r') )
1435 p--;
1436 strcpyW( p+1, twocrlf );
1438 return requestString;
1441 static BOOL read_reply( request_t *request );
1443 static BOOL secure_proxy_connect( request_t *request )
1445 static const WCHAR verbConnect[] = {'C','O','N','N','E','C','T',0};
1446 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1447 BOOL ret = FALSE;
1448 LPWSTR path;
1449 connect_t *connect = request->connect;
1451 path = heap_alloc( (strlenW( connect->hostname ) + 13) * sizeof(WCHAR) );
1452 if (path)
1454 LPWSTR requestString;
1456 sprintfW( path, fmt, connect->hostname, connect->hostport );
1457 requestString = build_header_request_string( request, verbConnect,
1458 path, http1_1 );
1459 heap_free( path );
1460 if (requestString)
1462 LPSTR req_ascii = strdupWA( requestString );
1464 heap_free( requestString );
1465 if (req_ascii)
1467 int len = strlen( req_ascii ), bytes_sent;
1469 ret = netconn_send( request->netconn, req_ascii, len, &bytes_sent );
1470 heap_free( req_ascii );
1471 if (ret)
1472 ret = read_reply( request );
1476 return ret;
1479 static WCHAR *addr_to_str( struct sockaddr_storage *addr )
1481 char buf[INET6_ADDRSTRLEN];
1482 void *src;
1484 switch (addr->ss_family)
1486 case AF_INET:
1487 src = &((struct sockaddr_in *)addr)->sin_addr;
1488 break;
1489 case AF_INET6:
1490 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
1491 break;
1492 default:
1493 WARN("unsupported address family %d\n", addr->ss_family);
1494 return NULL;
1496 if (!inet_ntop( addr->ss_family, src, buf, sizeof(buf) )) return NULL;
1497 return strdupAW( buf );
1500 static CRITICAL_SECTION connection_pool_cs;
1501 static CRITICAL_SECTION_DEBUG connection_pool_debug =
1503 0, 0, &connection_pool_cs,
1504 { &connection_pool_debug.ProcessLocksList, &connection_pool_debug.ProcessLocksList },
1505 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
1507 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
1509 static struct list connection_pool = LIST_INIT( connection_pool );
1511 void release_host( hostdata_t *host )
1513 LONG ref;
1515 EnterCriticalSection( &connection_pool_cs );
1516 if (!(ref = --host->ref)) list_remove( &host->entry );
1517 LeaveCriticalSection( &connection_pool_cs );
1518 if (ref) return;
1520 assert( list_empty( &host->connections ) );
1521 heap_free( host->hostname );
1522 heap_free( host );
1525 static BOOL connection_collector_running;
1527 static DWORD WINAPI connection_collector(void *arg)
1529 unsigned int remaining_connections;
1530 netconn_t *netconn, *next_netconn;
1531 hostdata_t *host, *next_host;
1532 ULONGLONG now;
1536 /* FIXME: Use more sophisticated method */
1537 Sleep(5000);
1538 remaining_connections = 0;
1539 now = GetTickCount64();
1541 EnterCriticalSection(&connection_pool_cs);
1543 LIST_FOR_EACH_ENTRY_SAFE(host, next_host, &connection_pool, hostdata_t, entry)
1545 LIST_FOR_EACH_ENTRY_SAFE(netconn, next_netconn, &host->connections, netconn_t, entry)
1547 if (netconn->keep_until < now)
1549 TRACE("freeing %p\n", netconn);
1550 list_remove(&netconn->entry);
1551 netconn_close(netconn);
1553 else
1555 remaining_connections++;
1560 if (!remaining_connections) connection_collector_running = FALSE;
1562 LeaveCriticalSection(&connection_pool_cs);
1563 } while(remaining_connections);
1565 FreeLibraryAndExitThread( winhttp_instance, 0 );
1568 static void cache_connection( netconn_t *netconn )
1570 TRACE( "caching connection %p\n", netconn );
1572 EnterCriticalSection( &connection_pool_cs );
1574 netconn->keep_until = GetTickCount64() + DEFAULT_KEEP_ALIVE_TIMEOUT;
1575 list_add_head( &netconn->host->connections, &netconn->entry );
1577 if (!connection_collector_running)
1579 HMODULE module;
1580 HANDLE thread;
1582 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)winhttp_instance, &module );
1584 thread = CreateThread(NULL, 0, connection_collector, NULL, 0, NULL);
1585 if (thread)
1587 CloseHandle( thread );
1588 connection_collector_running = TRUE;
1590 else
1592 FreeLibrary( winhttp_instance );
1596 LeaveCriticalSection( &connection_pool_cs );
1599 static DWORD map_secure_protocols( DWORD mask )
1601 DWORD ret = 0;
1602 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL2) ret |= SP_PROT_SSL2_CLIENT;
1603 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL3) ret |= SP_PROT_SSL3_CLIENT;
1604 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1) ret |= SP_PROT_TLS1_CLIENT;
1605 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1) ret |= SP_PROT_TLS1_1_CLIENT;
1606 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2) ret |= SP_PROT_TLS1_2_CLIENT;
1607 return ret;
1610 static BOOL ensure_cred_handle( session_t *session )
1612 SCHANNEL_CRED cred;
1613 SECURITY_STATUS status;
1615 if (session->cred_handle_initialized) return TRUE;
1617 memset( &cred, 0, sizeof(cred) );
1618 cred.dwVersion = SCHANNEL_CRED_VERSION;
1619 cred.grbitEnabledProtocols = map_secure_protocols( session->secure_protocols );
1620 if ((status = AcquireCredentialsHandleW( NULL, (WCHAR *)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
1621 NULL, NULL, &session->cred_handle, NULL )) != SEC_E_OK)
1623 WARN( "AcquireCredentialsHandleW failed: 0x%08x\n", status );
1624 return FALSE;
1626 session->cred_handle_initialized = TRUE;
1627 return TRUE;
1630 static BOOL open_connection( request_t *request )
1632 BOOL is_secure = request->hdr.flags & WINHTTP_FLAG_SECURE;
1633 hostdata_t *host = NULL, *iter;
1634 netconn_t *netconn = NULL;
1635 connect_t *connect;
1636 WCHAR *addressW = NULL;
1637 INTERNET_PORT port;
1638 DWORD len;
1640 if (request->netconn) goto done;
1642 connect = request->connect;
1643 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1645 EnterCriticalSection( &connection_pool_cs );
1647 LIST_FOR_EACH_ENTRY( iter, &connection_pool, hostdata_t, entry )
1649 if (iter->port == port && !strcmpW( connect->servername, iter->hostname ) && !is_secure == !iter->secure)
1651 host = iter;
1652 host->ref++;
1653 break;
1657 if (!host)
1659 if ((host = heap_alloc( sizeof(*host) )))
1661 host->ref = 1;
1662 host->secure = is_secure;
1663 host->port = port;
1664 list_init( &host->connections );
1665 if ((host->hostname = strdupW( connect->servername )))
1667 list_add_head( &connection_pool, &host->entry );
1669 else
1671 heap_free( host );
1672 host = NULL;
1677 LeaveCriticalSection( &connection_pool_cs );
1679 if (!host) return FALSE;
1681 for (;;)
1683 EnterCriticalSection( &connection_pool_cs );
1684 if (!list_empty( &host->connections ))
1686 netconn = LIST_ENTRY( list_head( &host->connections ), netconn_t, entry );
1687 list_remove( &netconn->entry );
1689 LeaveCriticalSection( &connection_pool_cs );
1690 if (!netconn) break;
1692 if (netconn_is_alive( netconn )) break;
1693 TRACE("connection %p no longer alive, closing\n", netconn);
1694 netconn_close( netconn );
1695 netconn = NULL;
1698 if (!connect->resolved && netconn)
1700 connect->sockaddr = netconn->sockaddr;
1701 connect->resolved = TRUE;
1704 if (!connect->resolved)
1706 len = strlenW( host->hostname ) + 1;
1707 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, host->hostname, len );
1709 if (!netconn_resolve( host->hostname, port, &connect->sockaddr, request->resolve_timeout ))
1711 release_host( host );
1712 return FALSE;
1714 connect->resolved = TRUE;
1716 if (!(addressW = addr_to_str( &connect->sockaddr )))
1718 release_host( host );
1719 return FALSE;
1721 len = strlenW( addressW ) + 1;
1722 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
1725 if (!netconn)
1727 if (!addressW && !(addressW = addr_to_str( &connect->sockaddr )))
1729 release_host( host );
1730 return FALSE;
1733 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
1735 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
1737 if (!(netconn = netconn_create( host, &connect->sockaddr, request->connect_timeout )))
1739 heap_free( addressW );
1740 release_host( host );
1741 return FALSE;
1743 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1744 netconn_set_timeout( netconn, FALSE, request->recv_timeout );
1745 if (is_secure)
1747 if (connect->session->proxy_server &&
1748 strcmpiW( connect->hostname, connect->servername ))
1750 if (!secure_proxy_connect( request ))
1752 heap_free( addressW );
1753 netconn_close( netconn );
1754 return FALSE;
1758 CertFreeCertificateContext( request->server_cert );
1759 request->server_cert = NULL;
1761 if (!ensure_cred_handle( connect->session ) ||
1762 !netconn_secure_connect( netconn, connect->hostname, request->security_flags,
1763 &connect->session->cred_handle, request->check_revocation ))
1765 heap_free( addressW );
1766 netconn_close( netconn );
1767 return FALSE;
1771 request->netconn = netconn;
1772 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
1774 else
1776 TRACE("using connection %p\n", netconn);
1778 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1779 netconn_set_timeout( netconn, FALSE, request->recv_timeout );
1780 request->netconn = netconn;
1783 if (netconn->secure && !(request->server_cert = netconn_get_certificate( netconn )))
1785 heap_free( addressW );
1786 netconn_close( netconn );
1787 return FALSE;
1790 done:
1791 request->read_pos = request->read_size = 0;
1792 request->read_chunked = FALSE;
1793 request->read_chunked_size = ~0u;
1794 request->read_chunked_eof = FALSE;
1795 heap_free( addressW );
1796 return TRUE;
1799 void close_connection( request_t *request )
1801 if (!request->netconn) return;
1803 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1804 netconn_close( request->netconn );
1805 request->netconn = NULL;
1806 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1809 static BOOL add_host_header( request_t *request, DWORD modifier )
1811 BOOL ret;
1812 DWORD len;
1813 WCHAR *host;
1814 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1815 connect_t *connect = request->connect;
1816 INTERNET_PORT port;
1818 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1820 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1822 return process_header( request, attr_host, connect->hostname, modifier, TRUE );
1824 len = strlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1825 if (!(host = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1826 sprintfW( host, fmt, connect->hostname, port );
1827 ret = process_header( request, attr_host, host, modifier, TRUE );
1828 heap_free( host );
1829 return ret;
1832 static void clear_response_headers( request_t *request )
1834 unsigned int i;
1836 for (i = 0; i < request->num_headers; i++)
1838 if (!request->headers[i].field) continue;
1839 if (!request->headers[i].value) continue;
1840 if (request->headers[i].is_request) continue;
1841 delete_header( request, i );
1842 i--;
1846 /* remove some amount of data from the read buffer */
1847 static void remove_data( request_t *request, int count )
1849 if (!(request->read_size -= count)) request->read_pos = 0;
1850 else request->read_pos += count;
1853 /* read some more data into the read buffer */
1854 static BOOL read_more_data( request_t *request, int maxlen, BOOL notify )
1856 int len;
1857 BOOL ret;
1859 if (request->read_chunked_eof) return FALSE;
1861 if (request->read_size && request->read_pos)
1863 /* move existing data to the start of the buffer */
1864 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1865 request->read_pos = 0;
1867 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1869 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1871 ret = netconn_recv( request->netconn, request->read_buf + request->read_size,
1872 maxlen - request->read_size, 0, &len );
1874 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &len, sizeof(len) );
1876 request->read_size += len;
1877 return ret;
1880 /* discard data contents until we reach end of line */
1881 static BOOL discard_eol( request_t *request, BOOL notify )
1885 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1886 if (eol)
1888 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1889 break;
1891 request->read_pos = request->read_size = 0; /* discard everything */
1892 if (!read_more_data( request, -1, notify )) return FALSE;
1893 } while (request->read_size);
1894 return TRUE;
1897 /* read the size of the next chunk */
1898 static BOOL start_next_chunk( request_t *request, BOOL notify )
1900 DWORD chunk_size = 0;
1902 assert(!request->read_chunked_size || request->read_chunked_size == ~0u);
1904 if (request->read_chunked_eof) return FALSE;
1906 /* read terminator for the previous chunk */
1907 if (!request->read_chunked_size && !discard_eol( request, notify )) return FALSE;
1909 for (;;)
1911 while (request->read_size)
1913 char ch = request->read_buf[request->read_pos];
1914 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1915 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1916 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1917 else if (ch == ';' || ch == '\r' || ch == '\n')
1919 TRACE("reading %u byte chunk\n", chunk_size);
1921 if (request->content_length == ~0u) request->content_length = chunk_size;
1922 else request->content_length += chunk_size;
1924 request->read_chunked_size = chunk_size;
1925 if (!chunk_size) request->read_chunked_eof = TRUE;
1927 return discard_eol( request, notify );
1929 remove_data( request, 1 );
1931 if (!read_more_data( request, -1, notify )) return FALSE;
1932 if (!request->read_size)
1934 request->content_length = request->content_read = 0;
1935 request->read_chunked_size = 0;
1936 return TRUE;
1941 static BOOL refill_buffer( request_t *request, BOOL notify )
1943 int len = sizeof(request->read_buf);
1945 if (request->read_chunked)
1947 if (request->read_chunked_eof) return FALSE;
1948 if (request->read_chunked_size == ~0u || !request->read_chunked_size)
1950 if (!start_next_chunk( request, notify )) return FALSE;
1952 len = min( len, request->read_chunked_size );
1954 else if (request->content_length != ~0u)
1956 len = min( len, request->content_length - request->content_read );
1959 if (len <= request->read_size) return TRUE;
1960 if (!read_more_data( request, len, notify )) return FALSE;
1961 if (!request->read_size) request->content_length = request->content_read = 0;
1962 return TRUE;
1965 static void finished_reading( request_t *request )
1967 static const WCHAR closeW[] = {'c','l','o','s','e',0};
1969 BOOL close = FALSE;
1970 WCHAR connection[20];
1971 DWORD size = sizeof(connection);
1973 if (!request->netconn) return;
1975 if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
1976 else if (query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
1977 query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
1979 if (!strcmpiW( connection, closeW )) close = TRUE;
1981 else if (!strcmpW( request->version, http1_0 )) close = TRUE;
1982 if (close)
1984 close_connection( request );
1985 return;
1988 cache_connection( request->netconn );
1989 request->netconn = NULL;
1992 /* return the size of data available to be read immediately */
1993 static DWORD get_available_data( request_t *request )
1995 if (request->read_chunked) return min( request->read_chunked_size, request->read_size );
1996 return request->read_size;
1999 /* check if we have reached the end of the data to read */
2000 static BOOL end_of_read_data( request_t *request )
2002 if (!request->content_length) return TRUE;
2003 if (request->read_chunked) return request->read_chunked_eof;
2004 if (request->content_length == ~0u) return FALSE;
2005 return (request->content_length == request->content_read);
2008 static BOOL read_data( request_t *request, void *buffer, DWORD size, DWORD *read, BOOL async )
2010 int count, bytes_read = 0;
2012 if (end_of_read_data( request )) goto done;
2014 while (size)
2016 if (!(count = get_available_data( request )))
2018 if (!refill_buffer( request, async )) goto done;
2019 if (!(count = get_available_data( request ))) goto done;
2021 count = min( count, size );
2022 memcpy( (char *)buffer + bytes_read, request->read_buf + request->read_pos, count );
2023 remove_data( request, count );
2024 if (request->read_chunked) request->read_chunked_size -= count;
2025 size -= count;
2026 bytes_read += count;
2027 request->content_read += count;
2028 if (end_of_read_data( request )) goto done;
2030 if (request->read_chunked && !request->read_chunked_size) refill_buffer( request, async );
2032 done:
2033 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, request->content_read, request->content_length );
2035 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
2036 if (read) *read = bytes_read;
2037 if (end_of_read_data( request )) finished_reading( request );
2038 return TRUE;
2041 /* read any content returned by the server so that the connection can be reused */
2042 static void drain_content( request_t *request )
2044 DWORD size, bytes_read, bytes_total = 0, bytes_left = request->content_length - request->content_read;
2045 char buffer[2048];
2047 refill_buffer( request, FALSE );
2048 for (;;)
2050 if (request->read_chunked) size = sizeof(buffer);
2051 else
2053 if (bytes_total >= bytes_left) return;
2054 size = min( sizeof(buffer), bytes_left - bytes_total );
2056 if (!read_data( request, buffer, size, &bytes_read, FALSE ) || !bytes_read) return;
2057 bytes_total += bytes_read;
2061 static BOOL send_request( request_t *request, LPCWSTR headers, DWORD headers_len, LPVOID optional,
2062 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
2064 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
2065 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
2066 static const WCHAR length_fmt[] = {'%','l','d',0};
2068 BOOL ret = FALSE;
2069 connect_t *connect = request->connect;
2070 session_t *session = connect->session;
2071 WCHAR *req = NULL;
2072 char *req_ascii;
2073 int bytes_sent;
2074 DWORD len, i, flags;
2076 clear_response_headers( request );
2077 drain_content( request );
2079 flags = WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
2080 for (i = 0; i < request->num_accept_types; i++)
2082 process_header( request, attr_accept, request->accept_types[i], flags, TRUE );
2084 if (session->agent)
2085 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2087 if (connect->hostname)
2088 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
2090 if (request->creds[TARGET_SERVER][SCHEME_BASIC].username)
2091 do_authorization( request, WINHTTP_AUTH_TARGET_SERVER, WINHTTP_AUTH_SCHEME_BASIC );
2093 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
2095 WCHAR length[21]; /* decimal long int + null */
2096 sprintfW( length, length_fmt, total_len );
2097 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2099 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
2101 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2103 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
2105 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2106 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2108 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
2110 TRACE("failed to add request headers\n");
2111 return FALSE;
2113 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
2115 WARN("failed to add cookie headers\n");
2116 return FALSE;
2119 if (context) request->hdr.context = context;
2121 if (!(ret = open_connection( request ))) goto end;
2122 if (!(req = build_request_string( request ))) goto end;
2124 if (!(req_ascii = strdupWA( req ))) goto end;
2125 TRACE("full request: %s\n", debugstr_a(req_ascii));
2126 len = strlen(req_ascii);
2128 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
2130 ret = netconn_send( request->netconn, req_ascii, len, &bytes_sent );
2131 heap_free( req_ascii );
2132 if (!ret) goto end;
2134 if (optional_len)
2136 if (!netconn_send( request->netconn, optional, optional_len, &bytes_sent )) goto end;
2137 request->optional = optional;
2138 request->optional_len = optional_len;
2139 len += optional_len;
2141 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(len) );
2143 end:
2144 if (async)
2146 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
2147 else
2149 WINHTTP_ASYNC_RESULT result;
2150 result.dwResult = API_SEND_REQUEST;
2151 result.dwError = get_last_error();
2152 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2155 heap_free( req );
2156 return ret;
2159 static void task_send_request( task_header_t *task )
2161 send_request_t *s = (send_request_t *)task;
2162 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
2163 heap_free( s->headers );
2166 /***********************************************************************
2167 * WinHttpSendRequest (winhttp.@)
2169 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
2170 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
2172 BOOL ret;
2173 request_t *request;
2175 TRACE("%p, %s, %u, %u, %u, %lx\n", hrequest, debugstr_wn(headers, headers_len), headers_len, optional_len,
2176 total_len, context);
2178 if (!(request = (request_t *)grab_object( hrequest )))
2180 set_last_error( ERROR_INVALID_HANDLE );
2181 return FALSE;
2183 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2185 release_object( &request->hdr );
2186 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2187 return FALSE;
2190 if (headers && !headers_len) headers_len = strlenW( headers );
2192 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2194 send_request_t *s;
2196 if (!(s = heap_alloc( sizeof(send_request_t) ))) return FALSE;
2197 s->hdr.request = request;
2198 s->hdr.proc = task_send_request;
2199 s->headers = strdupW( headers );
2200 s->headers_len = headers_len;
2201 s->optional = optional;
2202 s->optional_len = optional_len;
2203 s->total_len = total_len;
2204 s->context = context;
2206 addref_object( &request->hdr );
2207 ret = queue_task( (task_header_t *)s );
2209 else
2210 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
2212 release_object( &request->hdr );
2213 if (ret) set_last_error( ERROR_SUCCESS );
2214 return ret;
2217 static BOOL set_credentials( request_t *request, DWORD target, DWORD scheme_flag, const WCHAR *username,
2218 const WCHAR *password )
2220 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
2222 if (scheme == SCHEME_INVALID || ((scheme == SCHEME_BASIC || scheme == SCHEME_DIGEST) && (!username || !password)))
2224 set_last_error( ERROR_INVALID_PARAMETER );
2225 return FALSE;
2227 switch (target)
2229 case WINHTTP_AUTH_TARGET_SERVER:
2231 heap_free( request->creds[TARGET_SERVER][scheme].username );
2232 if (!username) request->creds[TARGET_SERVER][scheme].username = NULL;
2233 else if (!(request->creds[TARGET_SERVER][scheme].username = strdupW( username ))) return FALSE;
2235 heap_free( request->creds[TARGET_SERVER][scheme].password );
2236 if (!password) request->creds[TARGET_SERVER][scheme].password = NULL;
2237 else if (!(request->creds[TARGET_SERVER][scheme].password = strdupW( password ))) return FALSE;
2238 break;
2240 case WINHTTP_AUTH_TARGET_PROXY:
2242 heap_free( request->creds[TARGET_PROXY][scheme].username );
2243 if (!username) request->creds[TARGET_PROXY][scheme].username = NULL;
2244 else if (!(request->creds[TARGET_PROXY][scheme].username = strdupW( username ))) return FALSE;
2246 heap_free( request->creds[TARGET_PROXY][scheme].password );
2247 if (!password) request->creds[TARGET_PROXY][scheme].password = NULL;
2248 else if (!(request->creds[TARGET_PROXY][scheme].password = strdupW( password ))) return FALSE;
2249 break;
2251 default:
2252 WARN("unknown target %u\n", target);
2253 return FALSE;
2255 return TRUE;
2258 /***********************************************************************
2259 * WinHttpSetCredentials (winhttp.@)
2261 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
2262 LPCWSTR password, LPVOID params )
2264 BOOL ret;
2265 request_t *request;
2267 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
2269 if (!(request = (request_t *)grab_object( hrequest )))
2271 set_last_error( ERROR_INVALID_HANDLE );
2272 return FALSE;
2274 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2276 release_object( &request->hdr );
2277 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2278 return FALSE;
2281 ret = set_credentials( request, target, scheme, username, password );
2283 release_object( &request->hdr );
2284 if (ret) set_last_error( ERROR_SUCCESS );
2285 return ret;
2288 static BOOL handle_authorization( request_t *request, DWORD status )
2290 DWORD i, schemes, first, level, target;
2292 switch (status)
2294 case HTTP_STATUS_DENIED:
2295 target = WINHTTP_AUTH_TARGET_SERVER;
2296 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
2297 break;
2299 case HTTP_STATUS_PROXY_AUTH_REQ:
2300 target = WINHTTP_AUTH_TARGET_PROXY;
2301 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
2302 break;
2304 default:
2305 WARN("unhandled status %u\n", status);
2306 return FALSE;
2309 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
2310 if (do_authorization( request, target, first )) return TRUE;
2312 schemes &= ~first;
2313 for (i = 0; i < num_auth_schemes; i++)
2315 if (!(schemes & auth_schemes[i].scheme)) continue;
2316 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
2318 return FALSE;
2321 /* set the request content length based on the headers */
2322 static DWORD set_content_length( request_t *request, DWORD status )
2324 WCHAR encoding[20];
2325 DWORD buflen = sizeof(request->content_length);
2327 if (status == HTTP_STATUS_NO_CONTENT || status == HTTP_STATUS_NOT_MODIFIED || !strcmpW( request->verb, headW ))
2328 request->content_length = 0;
2329 else
2331 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
2332 NULL, &request->content_length, &buflen, NULL ))
2333 request->content_length = ~0u;
2335 buflen = sizeof(encoding);
2336 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
2337 !strcmpiW( encoding, chunkedW ))
2339 request->content_length = ~0u;
2340 request->read_chunked = TRUE;
2341 request->read_chunked_size = ~0u;
2342 request->read_chunked_eof = FALSE;
2345 request->content_read = 0;
2346 return request->content_length;
2349 static BOOL read_line( request_t *request, char *buffer, DWORD *len )
2351 int count, bytes_read, pos = 0;
2353 for (;;)
2355 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
2356 if (eol)
2358 count = eol - (request->read_buf + request->read_pos);
2359 bytes_read = count + 1;
2361 else count = bytes_read = request->read_size;
2363 count = min( count, *len - pos );
2364 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
2365 pos += count;
2366 remove_data( request, bytes_read );
2367 if (eol) break;
2369 if (!read_more_data( request, -1, TRUE )) return FALSE;
2370 if (!request->read_size)
2372 *len = 0;
2373 TRACE("returning empty string\n");
2374 return FALSE;
2377 if (pos < *len)
2379 if (pos && buffer[pos - 1] == '\r') pos--;
2380 *len = pos + 1;
2382 buffer[*len - 1] = 0;
2383 TRACE("returning %s\n", debugstr_a(buffer));
2384 return TRUE;
2387 #define MAX_REPLY_LEN 1460
2388 #define INITIAL_HEADER_BUFFER_LEN 512
2390 static BOOL read_reply( request_t *request )
2392 static const WCHAR crlf[] = {'\r','\n',0};
2394 char buffer[MAX_REPLY_LEN];
2395 DWORD buflen, len, offset, crlf_len = 2; /* strlenW(crlf) */
2396 char *status_code, *status_text;
2397 WCHAR *versionW, *status_textW, *raw_headers;
2398 WCHAR status_codeW[4]; /* sizeof("nnn") */
2400 if (!request->netconn) return FALSE;
2404 buflen = MAX_REPLY_LEN;
2405 if (!read_line( request, buffer, &buflen )) return FALSE;
2407 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2408 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
2409 status_code++;
2410 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
2411 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
2412 status_text++;
2414 TRACE("version [%s] status code [%s] status text [%s]\n",
2415 debugstr_an(buffer, status_code - buffer - 1),
2416 debugstr_an(status_code, len),
2417 debugstr_a(status_text));
2419 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
2421 /* we rely on the fact that the protocol is ascii */
2422 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2423 status_codeW[len] = 0;
2424 if (!(process_header( request, attr_status, status_codeW,
2425 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE, FALSE )))
2426 return FALSE;
2428 len = status_code - buffer;
2429 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2430 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2431 versionW[len - 1] = 0;
2433 heap_free( request->version );
2434 request->version = versionW;
2436 len = buflen - (status_text - buffer);
2437 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2438 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2440 heap_free( request->status_text );
2441 request->status_text = status_textW;
2443 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2444 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2445 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2446 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2448 heap_free( request->raw_headers );
2449 request->raw_headers = raw_headers;
2451 offset = buflen + crlf_len - 1;
2452 for (;;)
2454 header_t *header;
2456 buflen = MAX_REPLY_LEN;
2457 if (!read_line( request, buffer, &buflen )) return TRUE;
2458 if (!*buffer) buflen = 1;
2460 while (len - offset < buflen + crlf_len)
2462 WCHAR *tmp;
2463 len *= 2;
2464 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2465 request->raw_headers = raw_headers = tmp;
2467 if (!*buffer)
2469 memcpy( raw_headers + offset, crlf, sizeof(crlf) );
2470 break;
2472 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2474 if (!(header = parse_header( raw_headers + offset ))) break;
2475 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2477 free_header( header );
2478 break;
2480 free_header( header );
2481 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2482 offset += buflen + crlf_len - 1;
2485 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2486 return TRUE;
2489 static void record_cookies( request_t *request )
2491 unsigned int i;
2493 for (i = 0; i < request->num_headers; i++)
2495 header_t *set_cookie = &request->headers[i];
2496 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2498 set_cookies( request, set_cookie->value );
2503 static WCHAR *get_redirect_url( request_t *request, DWORD *len )
2505 DWORD size;
2506 WCHAR *ret;
2508 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2509 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2510 if (!(ret = heap_alloc( size ))) return NULL;
2511 *len = size / sizeof(WCHAR) - 1;
2512 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2513 heap_free( ret );
2514 return NULL;
2517 static BOOL handle_redirect( request_t *request, DWORD status )
2519 BOOL ret = FALSE;
2520 DWORD len, len_loc;
2521 URL_COMPONENTS uc;
2522 connect_t *connect = request->connect;
2523 INTERNET_PORT port;
2524 WCHAR *hostname = NULL, *location;
2525 int index;
2527 if (!(location = get_redirect_url( request, &len_loc ))) return FALSE;
2529 memset( &uc, 0, sizeof(uc) );
2530 uc.dwStructSize = sizeof(uc);
2531 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2533 if (!WinHttpCrackUrl( location, len_loc, 0, &uc )) /* assume relative redirect */
2535 WCHAR *path, *p;
2537 if (location[0] == '/')
2539 len = escape_string( NULL, location, len_loc );
2540 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2541 escape_string( path, location, len_loc );
2543 else
2545 if ((p = strrchrW( request->path, '/' ))) *p = 0;
2546 len = strlenW( request->path ) + 1 + escape_string( NULL, location, len_loc );
2547 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2548 strcpyW( path, request->path );
2549 strcatW( path, slashW );
2550 escape_string( path + strlenW(path), location, len_loc );
2552 heap_free( request->path );
2553 request->path = path;
2555 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_loc + 1 );
2557 else
2559 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2561 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2562 TRACE("redirect from secure page to non-secure page\n");
2563 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2565 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2567 TRACE("redirect from non-secure page to secure page\n");
2568 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2571 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_loc + 1 );
2573 len = uc.dwHostNameLength;
2574 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2575 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2576 hostname[len] = 0;
2578 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2579 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2581 heap_free( connect->hostname );
2582 connect->hostname = hostname;
2583 connect->hostport = port;
2584 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2586 netconn_close( request->netconn );
2587 request->netconn = NULL;
2588 request->content_length = request->content_read = 0;
2589 request->read_pos = request->read_size = 0;
2590 request->read_chunked = request->read_chunked_eof = FALSE;
2592 else heap_free( hostname );
2594 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2595 if (!(ret = open_connection( request ))) goto end;
2597 heap_free( request->path );
2598 request->path = NULL;
2599 if (uc.dwUrlPathLength)
2601 len = escape_string( NULL, uc.lpszUrlPath, uc.dwUrlPathLength + uc.dwExtraInfoLength );
2602 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2603 escape_string( request->path, uc.lpszUrlPath, uc.dwUrlPathLength + uc.dwExtraInfoLength );
2605 else request->path = strdupW( slashW );
2608 /* remove content-type/length headers */
2609 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2610 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2612 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2614 heap_free( request->verb );
2615 request->verb = strdupW( getW );
2616 request->optional = NULL;
2617 request->optional_len = 0;
2619 ret = TRUE;
2621 end:
2622 heap_free( location );
2623 return ret;
2626 static BOOL receive_response( request_t *request, BOOL async )
2628 BOOL ret;
2629 DWORD size, query, status;
2631 for (;;)
2633 if (!(ret = read_reply( request )))
2635 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2636 break;
2638 size = sizeof(DWORD);
2639 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2640 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2642 set_content_length( request, status );
2644 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2646 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2648 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2649 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2651 if (!(ret = handle_redirect( request, status ))) break;
2653 /* recurse synchronously */
2654 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2656 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2658 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2660 if (!handle_authorization( request, status )) break;
2662 /* recurse synchronously */
2663 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2665 break;
2668 if (request->content_length) refill_buffer( request, FALSE );
2670 if (async)
2672 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2673 else
2675 WINHTTP_ASYNC_RESULT result;
2676 result.dwResult = API_RECEIVE_RESPONSE;
2677 result.dwError = get_last_error();
2678 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2681 return ret;
2684 static void task_receive_response( task_header_t *task )
2686 receive_response_t *r = (receive_response_t *)task;
2687 receive_response( r->hdr.request, TRUE );
2690 /***********************************************************************
2691 * WinHttpReceiveResponse (winhttp.@)
2693 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2695 BOOL ret;
2696 request_t *request;
2698 TRACE("%p, %p\n", hrequest, reserved);
2700 if (!(request = (request_t *)grab_object( hrequest )))
2702 set_last_error( ERROR_INVALID_HANDLE );
2703 return FALSE;
2705 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2707 release_object( &request->hdr );
2708 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2709 return FALSE;
2712 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2714 receive_response_t *r;
2716 if (!(r = heap_alloc( sizeof(receive_response_t) ))) return FALSE;
2717 r->hdr.request = request;
2718 r->hdr.proc = task_receive_response;
2720 addref_object( &request->hdr );
2721 ret = queue_task( (task_header_t *)r );
2723 else
2724 ret = receive_response( request, FALSE );
2726 release_object( &request->hdr );
2727 if (ret) set_last_error( ERROR_SUCCESS );
2728 return ret;
2731 static BOOL query_data_available( request_t *request, DWORD *available, BOOL async )
2733 DWORD count = 0;
2735 if (end_of_read_data( request )) goto done;
2737 count = get_available_data( request );
2738 if (!request->read_chunked && request->netconn)
2739 count += netconn_query_data_available( request->netconn );
2740 if (!count)
2742 refill_buffer( request, async );
2743 count = get_available_data( request );
2744 if (!request->read_chunked && request->netconn)
2745 count += netconn_query_data_available( request->netconn );
2748 done:
2749 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2750 TRACE("%u bytes available\n", count);
2751 if (available) *available = count;
2752 return TRUE;
2755 static void task_query_data_available( task_header_t *task )
2757 query_data_t *q = (query_data_t *)task;
2758 query_data_available( q->hdr.request, q->available, TRUE );
2761 /***********************************************************************
2762 * WinHttpQueryDataAvailable (winhttp.@)
2764 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2766 BOOL ret;
2767 request_t *request;
2769 TRACE("%p, %p\n", hrequest, available);
2771 if (!(request = (request_t *)grab_object( hrequest )))
2773 set_last_error( ERROR_INVALID_HANDLE );
2774 return FALSE;
2776 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2778 release_object( &request->hdr );
2779 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2780 return FALSE;
2783 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2785 query_data_t *q;
2787 if (!(q = heap_alloc( sizeof(query_data_t) ))) return FALSE;
2788 q->hdr.request = request;
2789 q->hdr.proc = task_query_data_available;
2790 q->available = available;
2792 addref_object( &request->hdr );
2793 ret = queue_task( (task_header_t *)q );
2795 else
2796 ret = query_data_available( request, available, FALSE );
2798 release_object( &request->hdr );
2799 if (ret) set_last_error( ERROR_SUCCESS );
2800 return ret;
2803 static void task_read_data( task_header_t *task )
2805 read_data_t *r = (read_data_t *)task;
2806 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2809 /***********************************************************************
2810 * WinHttpReadData (winhttp.@)
2812 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2814 BOOL ret;
2815 request_t *request;
2817 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2819 if (!(request = (request_t *)grab_object( hrequest )))
2821 set_last_error( ERROR_INVALID_HANDLE );
2822 return FALSE;
2824 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2826 release_object( &request->hdr );
2827 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2828 return FALSE;
2831 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2833 read_data_t *r;
2835 if (!(r = heap_alloc( sizeof(read_data_t) ))) return FALSE;
2836 r->hdr.request = request;
2837 r->hdr.proc = task_read_data;
2838 r->buffer = buffer;
2839 r->to_read = to_read;
2840 r->read = read;
2842 addref_object( &request->hdr );
2843 ret = queue_task( (task_header_t *)r );
2845 else
2846 ret = read_data( request, buffer, to_read, read, FALSE );
2848 release_object( &request->hdr );
2849 if (ret) set_last_error( ERROR_SUCCESS );
2850 return ret;
2853 static BOOL write_data( request_t *request, LPCVOID buffer, DWORD to_write, LPDWORD written, BOOL async )
2855 BOOL ret;
2856 int num_bytes;
2858 ret = netconn_send( request->netconn, buffer, to_write, &num_bytes );
2860 if (async)
2862 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
2863 else
2865 WINHTTP_ASYNC_RESULT result;
2866 result.dwResult = API_WRITE_DATA;
2867 result.dwError = get_last_error();
2868 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2871 if (ret && written) *written = num_bytes;
2872 return ret;
2875 static void task_write_data( task_header_t *task )
2877 write_data_t *w = (write_data_t *)task;
2878 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
2881 /***********************************************************************
2882 * WinHttpWriteData (winhttp.@)
2884 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
2886 BOOL ret;
2887 request_t *request;
2889 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
2891 if (!(request = (request_t *)grab_object( hrequest )))
2893 set_last_error( ERROR_INVALID_HANDLE );
2894 return FALSE;
2896 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2898 release_object( &request->hdr );
2899 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2900 return FALSE;
2903 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2905 write_data_t *w;
2907 if (!(w = heap_alloc( sizeof(write_data_t) ))) return FALSE;
2908 w->hdr.request = request;
2909 w->hdr.proc = task_write_data;
2910 w->buffer = buffer;
2911 w->to_write = to_write;
2912 w->written = written;
2914 addref_object( &request->hdr );
2915 ret = queue_task( (task_header_t *)w );
2917 else
2918 ret = write_data( request, buffer, to_write, written, FALSE );
2920 release_object( &request->hdr );
2921 if (ret) set_last_error( ERROR_SUCCESS );
2922 return ret;
2925 enum request_state
2927 REQUEST_STATE_UNINITIALIZED,
2928 REQUEST_STATE_INITIALIZED,
2929 REQUEST_STATE_CANCELLED,
2930 REQUEST_STATE_OPEN,
2931 REQUEST_STATE_SENT,
2932 REQUEST_STATE_RESPONSE_RECEIVED
2935 struct winhttp_request
2937 IWinHttpRequest IWinHttpRequest_iface;
2938 LONG refs;
2939 CRITICAL_SECTION cs;
2940 enum request_state state;
2941 HINTERNET hsession;
2942 HINTERNET hconnect;
2943 HINTERNET hrequest;
2944 VARIANT data;
2945 WCHAR *verb;
2946 HANDLE thread;
2947 HANDLE wait;
2948 HANDLE cancel;
2949 char *buffer;
2950 DWORD offset;
2951 DWORD bytes_available;
2952 DWORD bytes_read;
2953 DWORD error;
2954 DWORD logon_policy;
2955 DWORD disable_feature;
2956 LONG resolve_timeout;
2957 LONG connect_timeout;
2958 LONG send_timeout;
2959 LONG receive_timeout;
2960 WINHTTP_PROXY_INFO proxy;
2961 BOOL async;
2962 UINT url_codepage;
2965 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
2967 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
2970 static ULONG WINAPI winhttp_request_AddRef(
2971 IWinHttpRequest *iface )
2973 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2974 return InterlockedIncrement( &request->refs );
2977 /* critical section must be held */
2978 static void cancel_request( struct winhttp_request *request )
2980 if (request->state <= REQUEST_STATE_CANCELLED) return;
2982 SetEvent( request->cancel );
2983 LeaveCriticalSection( &request->cs );
2984 WaitForSingleObject( request->thread, INFINITE );
2985 EnterCriticalSection( &request->cs );
2987 request->state = REQUEST_STATE_CANCELLED;
2989 CloseHandle( request->thread );
2990 request->thread = NULL;
2991 CloseHandle( request->wait );
2992 request->wait = NULL;
2993 CloseHandle( request->cancel );
2994 request->cancel = NULL;
2997 /* critical section must be held */
2998 static void free_request( struct winhttp_request *request )
3000 if (request->state < REQUEST_STATE_INITIALIZED) return;
3001 WinHttpCloseHandle( request->hrequest );
3002 WinHttpCloseHandle( request->hconnect );
3003 WinHttpCloseHandle( request->hsession );
3004 CloseHandle( request->thread );
3005 CloseHandle( request->wait );
3006 CloseHandle( request->cancel );
3007 heap_free( request->proxy.lpszProxy );
3008 heap_free( request->proxy.lpszProxyBypass );
3009 heap_free( request->buffer );
3010 heap_free( request->verb );
3011 VariantClear( &request->data );
3014 static ULONG WINAPI winhttp_request_Release(
3015 IWinHttpRequest *iface )
3017 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3018 LONG refs = InterlockedDecrement( &request->refs );
3019 if (!refs)
3021 TRACE("destroying %p\n", request);
3023 EnterCriticalSection( &request->cs );
3024 cancel_request( request );
3025 free_request( request );
3026 LeaveCriticalSection( &request->cs );
3027 request->cs.DebugInfo->Spare[0] = 0;
3028 DeleteCriticalSection( &request->cs );
3029 heap_free( request );
3031 return refs;
3034 static HRESULT WINAPI winhttp_request_QueryInterface(
3035 IWinHttpRequest *iface,
3036 REFIID riid,
3037 void **obj )
3039 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3041 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
3043 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
3044 IsEqualGUID( riid, &IID_IDispatch ) ||
3045 IsEqualGUID( riid, &IID_IUnknown ))
3047 *obj = iface;
3049 else
3051 FIXME("interface %s not implemented\n", debugstr_guid(riid));
3052 return E_NOINTERFACE;
3054 IWinHttpRequest_AddRef( iface );
3055 return S_OK;
3058 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
3059 IWinHttpRequest *iface,
3060 UINT *count )
3062 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3064 TRACE("%p, %p\n", request, count);
3065 *count = 1;
3066 return S_OK;
3069 enum type_id
3071 IWinHttpRequest_tid,
3072 last_tid
3075 static ITypeLib *winhttp_typelib;
3076 static ITypeInfo *winhttp_typeinfo[last_tid];
3078 static REFIID winhttp_tid_id[] =
3080 &IID_IWinHttpRequest
3083 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
3085 HRESULT hr;
3087 if (!winhttp_typelib)
3089 ITypeLib *typelib;
3091 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
3092 if (FAILED(hr))
3094 ERR("LoadRegTypeLib failed: %08x\n", hr);
3095 return hr;
3097 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
3098 ITypeLib_Release( typelib );
3100 if (!winhttp_typeinfo[tid])
3102 ITypeInfo *typeinfo;
3104 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
3105 if (FAILED(hr))
3107 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
3108 return hr;
3110 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
3111 ITypeInfo_Release( typeinfo );
3113 *ret = winhttp_typeinfo[tid];
3114 ITypeInfo_AddRef(winhttp_typeinfo[tid]);
3115 return S_OK;
3118 void release_typelib(void)
3120 unsigned i;
3122 for (i = 0; i < sizeof(winhttp_typeinfo)/sizeof(*winhttp_typeinfo); i++)
3123 if (winhttp_typeinfo[i])
3124 ITypeInfo_Release(winhttp_typeinfo[i]);
3126 if (winhttp_typelib)
3127 ITypeLib_Release(winhttp_typelib);
3130 static HRESULT WINAPI winhttp_request_GetTypeInfo(
3131 IWinHttpRequest *iface,
3132 UINT index,
3133 LCID lcid,
3134 ITypeInfo **info )
3136 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3137 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
3139 return get_typeinfo( IWinHttpRequest_tid, info );
3142 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
3143 IWinHttpRequest *iface,
3144 REFIID riid,
3145 LPOLESTR *names,
3146 UINT count,
3147 LCID lcid,
3148 DISPID *dispid )
3150 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3151 ITypeInfo *typeinfo;
3152 HRESULT hr;
3154 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
3156 if (!names || !count || !dispid) return E_INVALIDARG;
3158 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
3159 if (SUCCEEDED(hr))
3161 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
3162 ITypeInfo_Release( typeinfo );
3164 return hr;
3167 static HRESULT WINAPI winhttp_request_Invoke(
3168 IWinHttpRequest *iface,
3169 DISPID member,
3170 REFIID riid,
3171 LCID lcid,
3172 WORD flags,
3173 DISPPARAMS *params,
3174 VARIANT *result,
3175 EXCEPINFO *excep_info,
3176 UINT *arg_err )
3178 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3179 ITypeInfo *typeinfo;
3180 HRESULT hr;
3182 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
3183 lcid, flags, params, result, excep_info, arg_err);
3185 if (!IsEqualIID( riid, &IID_NULL )) return DISP_E_UNKNOWNINTERFACE;
3187 if (member == DISPID_HTTPREQUEST_OPTION)
3189 VARIANT ret_value, option;
3190 UINT err_pos;
3192 if (!result) result = &ret_value;
3193 if (!arg_err) arg_err = &err_pos;
3195 VariantInit( &option );
3196 VariantInit( result );
3198 if (!flags) return S_OK;
3200 if (flags == DISPATCH_PROPERTYPUT)
3202 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
3203 if (FAILED(hr)) return hr;
3205 hr = IWinHttpRequest_put_Option( &request->IWinHttpRequest_iface, V_I4( &option ), params->rgvarg[0] );
3206 if (FAILED(hr))
3207 WARN("put_Option(%d) failed: %x\n", V_I4( &option ), hr);
3208 return hr;
3210 else if (flags & (DISPATCH_PROPERTYGET | DISPATCH_METHOD))
3212 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
3213 if (FAILED(hr)) return hr;
3215 hr = IWinHttpRequest_get_Option( &request->IWinHttpRequest_iface, V_I4( &option ), result );
3216 if (FAILED(hr))
3217 WARN("get_Option(%d) failed: %x\n", V_I4( &option ), hr);
3218 return hr;
3221 FIXME("unsupported flags %x\n", flags);
3222 return E_NOTIMPL;
3225 /* fallback to standard implementation */
3227 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
3228 if (SUCCEEDED(hr))
3230 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
3231 params, result, excep_info, arg_err );
3232 ITypeInfo_Release( typeinfo );
3234 return hr;
3237 static HRESULT WINAPI winhttp_request_SetProxy(
3238 IWinHttpRequest *iface,
3239 HTTPREQUEST_PROXY_SETTING proxy_setting,
3240 VARIANT proxy_server,
3241 VARIANT bypass_list )
3243 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3244 DWORD err = ERROR_SUCCESS;
3246 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
3247 debugstr_variant(&bypass_list));
3249 EnterCriticalSection( &request->cs );
3250 switch (proxy_setting)
3252 case HTTPREQUEST_PROXYSETTING_DEFAULT:
3253 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3254 heap_free( request->proxy.lpszProxy );
3255 heap_free( request->proxy.lpszProxyBypass );
3256 request->proxy.lpszProxy = NULL;
3257 request->proxy.lpszProxyBypass = NULL;
3258 break;
3260 case HTTPREQUEST_PROXYSETTING_DIRECT:
3261 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
3262 heap_free( request->proxy.lpszProxy );
3263 heap_free( request->proxy.lpszProxyBypass );
3264 request->proxy.lpszProxy = NULL;
3265 request->proxy.lpszProxyBypass = NULL;
3266 break;
3268 case HTTPREQUEST_PROXYSETTING_PROXY:
3269 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
3270 if (V_VT( &proxy_server ) == VT_BSTR)
3272 heap_free( request->proxy.lpszProxy );
3273 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
3275 if (V_VT( &bypass_list ) == VT_BSTR)
3277 heap_free( request->proxy.lpszProxyBypass );
3278 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
3280 break;
3282 default:
3283 err = ERROR_INVALID_PARAMETER;
3284 break;
3286 LeaveCriticalSection( &request->cs );
3287 return HRESULT_FROM_WIN32( err );
3290 static HRESULT WINAPI winhttp_request_SetCredentials(
3291 IWinHttpRequest *iface,
3292 BSTR username,
3293 BSTR password,
3294 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
3296 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3297 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
3298 DWORD err = ERROR_SUCCESS;
3300 TRACE("%p, %s, %p, 0x%08x\n", request, debugstr_w(username), password, flags);
3302 EnterCriticalSection( &request->cs );
3303 if (request->state < REQUEST_STATE_OPEN)
3305 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3306 goto done;
3308 switch (flags)
3310 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
3311 target = WINHTTP_AUTH_TARGET_SERVER;
3312 break;
3313 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
3314 target = WINHTTP_AUTH_TARGET_PROXY;
3315 break;
3316 default:
3317 err = ERROR_INVALID_PARAMETER;
3318 goto done;
3320 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
3322 err = get_last_error();
3324 done:
3325 LeaveCriticalSection( &request->cs );
3326 return HRESULT_FROM_WIN32( err );
3329 static void initialize_request( struct winhttp_request *request )
3331 request->hrequest = NULL;
3332 request->hconnect = NULL;
3333 request->hsession = NULL;
3334 request->thread = NULL;
3335 request->wait = NULL;
3336 request->cancel = NULL;
3337 request->buffer = NULL;
3338 request->verb = NULL;
3339 request->offset = 0;
3340 request->bytes_available = 0;
3341 request->bytes_read = 0;
3342 request->error = ERROR_SUCCESS;
3343 request->async = FALSE;
3344 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
3345 request->disable_feature = 0;
3346 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3347 request->proxy.lpszProxy = NULL;
3348 request->proxy.lpszProxyBypass = NULL;
3349 request->resolve_timeout = 0;
3350 request->connect_timeout = 60000;
3351 request->send_timeout = 30000;
3352 request->receive_timeout = 30000;
3353 request->url_codepage = CP_UTF8;
3354 VariantInit( &request->data );
3355 request->state = REQUEST_STATE_INITIALIZED;
3358 static void reset_request( struct winhttp_request *request )
3360 cancel_request( request );
3361 WinHttpCloseHandle( request->hrequest );
3362 request->hrequest = NULL;
3363 WinHttpCloseHandle( request->hconnect );
3364 request->hconnect = NULL;
3365 heap_free( request->buffer );
3366 request->buffer = NULL;
3367 heap_free( request->verb );
3368 request->verb = NULL;
3369 request->offset = 0;
3370 request->bytes_available = 0;
3371 request->bytes_read = 0;
3372 request->error = ERROR_SUCCESS;
3373 request->async = FALSE;
3374 request->url_codepage = CP_UTF8;
3375 VariantClear( &request->data );
3376 request->state = REQUEST_STATE_INITIALIZED;
3379 static HRESULT WINAPI winhttp_request_Open(
3380 IWinHttpRequest *iface,
3381 BSTR method,
3382 BSTR url,
3383 VARIANT async )
3385 static const WCHAR typeW[] = {'*','/','*',0};
3386 static const WCHAR *acceptW[] = {typeW, NULL};
3387 static const WCHAR httpsW[] = {'h','t','t','p','s'};
3388 static const WCHAR user_agentW[] = {
3389 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
3390 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
3391 'R','e','q','u','e','s','t','.','5',')',0};
3392 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3393 URL_COMPONENTS uc;
3394 WCHAR *hostname, *path = NULL, *verb = NULL;
3395 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0;
3397 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
3398 debugstr_variant(&async));
3400 if (!method || !url) return E_INVALIDARG;
3402 memset( &uc, 0, sizeof(uc) );
3403 uc.dwStructSize = sizeof(uc);
3404 uc.dwSchemeLength = ~0u;
3405 uc.dwHostNameLength = ~0u;
3406 uc.dwUrlPathLength = ~0u;
3407 uc.dwExtraInfoLength = ~0u;
3408 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( get_last_error() );
3410 EnterCriticalSection( &request->cs );
3411 if (request->state < REQUEST_STATE_INITIALIZED) initialize_request( request );
3412 else reset_request( request );
3414 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
3415 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
3416 hostname[uc.dwHostNameLength] = 0;
3418 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
3419 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
3420 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
3422 if (!(verb = strdupW( method ))) goto error;
3423 if (SUCCEEDED( VariantChangeType( &async, &async, 0, VT_BOOL )) && V_BOOL( &async )) request->async = TRUE;
3424 else request->async = FALSE;
3426 if (!request->hsession)
3428 if (!(request->hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL,
3429 WINHTTP_FLAG_ASYNC )))
3431 err = get_last_error();
3432 goto error;
3434 if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3436 WinHttpCloseHandle( request->hsession );
3437 request->hsession = NULL;
3438 err = get_last_error();
3439 goto error;
3442 else if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3444 err = get_last_error();
3445 goto error;
3448 len = sizeof(httpsW) / sizeof(WCHAR);
3449 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
3451 flags |= WINHTTP_FLAG_SECURE;
3453 if (!(request->hrequest = WinHttpOpenRequest( request->hconnect, method, path, NULL, NULL, acceptW, flags )))
3455 err = get_last_error();
3456 goto error;
3458 WinHttpSetOption( request->hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3460 request->state = REQUEST_STATE_OPEN;
3461 request->verb = verb;
3462 heap_free( hostname );
3463 heap_free( path );
3464 LeaveCriticalSection( &request->cs );
3465 return S_OK;
3467 error:
3468 WinHttpCloseHandle( request->hconnect );
3469 request->hconnect = NULL;
3470 heap_free( hostname );
3471 heap_free( path );
3472 heap_free( verb );
3473 LeaveCriticalSection( &request->cs );
3474 return HRESULT_FROM_WIN32( err );
3477 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3478 IWinHttpRequest *iface,
3479 BSTR header,
3480 BSTR value )
3482 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3483 static const WCHAR emptyW[] = {0};
3484 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3485 DWORD len, err = ERROR_SUCCESS;
3486 WCHAR *str;
3488 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3490 if (!header) return E_INVALIDARG;
3492 EnterCriticalSection( &request->cs );
3493 if (request->state < REQUEST_STATE_OPEN)
3495 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3496 goto done;
3498 if (request->state >= REQUEST_STATE_SENT)
3500 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3501 goto done;
3503 len = strlenW( header ) + 4;
3504 if (value) len += strlenW( value );
3505 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3507 err = ERROR_OUTOFMEMORY;
3508 goto done;
3510 sprintfW( str, fmtW, header, value ? value : emptyW );
3511 if (!WinHttpAddRequestHeaders( request->hrequest, str, len,
3512 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
3514 err = get_last_error();
3516 heap_free( str );
3518 done:
3519 LeaveCriticalSection( &request->cs );
3520 return HRESULT_FROM_WIN32( err );
3523 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3524 IWinHttpRequest *iface,
3525 BSTR header,
3526 BSTR *value )
3528 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3529 DWORD size, err = ERROR_SUCCESS;
3531 TRACE("%p, %p\n", request, header);
3533 EnterCriticalSection( &request->cs );
3534 if (request->state < REQUEST_STATE_SENT)
3536 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3537 goto done;
3539 if (!header || !value)
3541 err = ERROR_INVALID_PARAMETER;
3542 goto done;
3544 size = 0;
3545 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3547 err = get_last_error();
3548 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3550 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3552 err = ERROR_OUTOFMEMORY;
3553 goto done;
3555 err = ERROR_SUCCESS;
3556 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3558 err = get_last_error();
3559 SysFreeString( *value );
3561 done:
3562 LeaveCriticalSection( &request->cs );
3563 return HRESULT_FROM_WIN32( err );
3566 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3567 IWinHttpRequest *iface,
3568 BSTR *headers )
3570 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3571 DWORD size, err = ERROR_SUCCESS;
3573 TRACE("%p, %p\n", request, headers);
3575 if (!headers) return E_INVALIDARG;
3577 EnterCriticalSection( &request->cs );
3578 if (request->state < REQUEST_STATE_SENT)
3580 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3581 goto done;
3583 size = 0;
3584 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3586 err = get_last_error();
3587 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3589 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3591 err = ERROR_OUTOFMEMORY;
3592 goto done;
3594 err = ERROR_SUCCESS;
3595 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3597 err = get_last_error();
3598 SysFreeString( *headers );
3600 done:
3601 LeaveCriticalSection( &request->cs );
3602 return HRESULT_FROM_WIN32( err );
3605 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3607 struct winhttp_request *request = (struct winhttp_request *)context;
3609 switch (status)
3611 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3612 request->bytes_available = *(DWORD *)buffer;
3613 request->error = ERROR_SUCCESS;
3614 break;
3615 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3616 request->bytes_read = size;
3617 request->error = ERROR_SUCCESS;
3618 break;
3619 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3621 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3622 request->error = result->dwError;
3623 break;
3625 default: break;
3627 SetEvent( request->wait );
3630 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3632 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3633 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3636 static DWORD wait_for_completion( struct winhttp_request *request )
3638 HANDLE handles[2] = { request->wait, request->cancel };
3640 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3642 case WAIT_OBJECT_0:
3643 break;
3644 case WAIT_OBJECT_0 + 1:
3645 request->error = ERROR_CANCELLED;
3646 break;
3647 default:
3648 request->error = get_last_error();
3649 break;
3651 return request->error;
3654 static HRESULT request_receive( struct winhttp_request *request )
3656 DWORD err, size, buflen = 4096;
3658 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3659 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3661 return HRESULT_FROM_WIN32( get_last_error() );
3663 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3664 if (!strcmpW( request->verb, headW ))
3666 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3667 return S_OK;
3669 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3670 request->buffer[0] = 0;
3671 size = 0;
3674 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3675 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3677 err = get_last_error();
3678 goto error;
3680 if ((err = wait_for_completion( request ))) goto error;
3681 if (!request->bytes_available) break;
3682 size += request->bytes_available;
3683 if (buflen < size)
3685 char *tmp;
3686 while (buflen < size) buflen *= 2;
3687 if (!(tmp = heap_realloc( request->buffer, buflen )))
3689 err = ERROR_OUTOFMEMORY;
3690 goto error;
3692 request->buffer = tmp;
3694 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3695 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3696 request->bytes_available, &request->bytes_read ))
3698 err = get_last_error();
3699 goto error;
3701 if ((err = wait_for_completion( request ))) goto error;
3702 request->offset += request->bytes_read;
3703 } while (request->bytes_read);
3705 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3706 return S_OK;
3708 error:
3709 heap_free( request->buffer );
3710 request->buffer = NULL;
3711 return HRESULT_FROM_WIN32( err );
3714 static DWORD request_set_parameters( struct winhttp_request *request )
3716 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3717 sizeof(request->proxy) )) return get_last_error();
3719 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3720 sizeof(request->logon_policy) )) return get_last_error();
3722 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3723 sizeof(request->disable_feature) )) return get_last_error();
3725 if (!WinHttpSetTimeouts( request->hrequest,
3726 request->resolve_timeout,
3727 request->connect_timeout,
3728 request->send_timeout,
3729 request->receive_timeout )) return get_last_error();
3730 return ERROR_SUCCESS;
3733 static void request_set_utf8_content_type( struct winhttp_request *request )
3735 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3736 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3737 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3738 WCHAR headerW[64];
3739 int len;
3741 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3742 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3743 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3744 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3747 static HRESULT request_send( struct winhttp_request *request )
3749 SAFEARRAY *sa = NULL;
3750 VARIANT data;
3751 char *ptr = NULL;
3752 LONG size = 0;
3753 HRESULT hr;
3754 DWORD err;
3756 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3757 if (strcmpW( request->verb, getW ))
3759 VariantInit( &data );
3760 if (V_VT( &request->data ) == VT_BSTR)
3762 UINT cp = CP_ACP;
3763 const WCHAR *str = V_BSTR( &request->data );
3764 int i, len = strlenW( str );
3766 for (i = 0; i < len; i++)
3768 if (str[i] > 127)
3770 cp = CP_UTF8;
3771 break;
3774 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3775 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3776 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3777 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3779 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3781 sa = V_ARRAY( &data );
3782 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3783 if ((hr = SafeArrayGetUBound( sa, 1, &size )) != S_OK)
3785 SafeArrayUnaccessData( sa );
3786 return hr;
3788 size++;
3791 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3792 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3794 err = get_last_error();
3795 goto error;
3797 if ((err = wait_for_completion( request ))) goto error;
3798 if (sa) SafeArrayUnaccessData( sa );
3799 else heap_free( ptr );
3800 request->state = REQUEST_STATE_SENT;
3801 return S_OK;
3803 error:
3804 if (sa) SafeArrayUnaccessData( sa );
3805 else heap_free( ptr );
3806 return HRESULT_FROM_WIN32( err );
3809 static HRESULT request_send_and_receive( struct winhttp_request *request )
3811 HRESULT hr = request_send( request );
3812 if (hr == S_OK) hr = request_receive( request );
3813 return hr;
3816 static DWORD CALLBACK send_and_receive_proc( void *arg )
3818 struct winhttp_request *request = (struct winhttp_request *)arg;
3819 return request_send_and_receive( request );
3822 /* critical section must be held */
3823 static DWORD request_wait( struct winhttp_request *request, DWORD timeout )
3825 HANDLE thread = request->thread;
3826 DWORD err, ret;
3828 LeaveCriticalSection( &request->cs );
3829 while ((err = MsgWaitForMultipleObjects( 1, &thread, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3831 MSG msg;
3832 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3834 TranslateMessage( &msg );
3835 DispatchMessageW( &msg );
3838 switch (err)
3840 case WAIT_OBJECT_0:
3841 ret = ERROR_SUCCESS;
3842 break;
3843 case WAIT_TIMEOUT:
3844 ret = ERROR_TIMEOUT;
3845 break;
3846 case WAIT_FAILED:
3847 default:
3848 ret = get_last_error();
3849 break;
3851 EnterCriticalSection( &request->cs );
3852 return ret;
3855 static HRESULT WINAPI winhttp_request_Send(
3856 IWinHttpRequest *iface,
3857 VARIANT body )
3859 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3860 HRESULT hr;
3862 TRACE("%p, %s\n", request, debugstr_variant(&body));
3864 EnterCriticalSection( &request->cs );
3865 if (request->state < REQUEST_STATE_OPEN)
3867 LeaveCriticalSection( &request->cs );
3868 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3870 if (request->state >= REQUEST_STATE_SENT)
3872 LeaveCriticalSection( &request->cs );
3873 return S_OK;
3875 VariantClear( &request->data );
3876 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK)
3878 LeaveCriticalSection( &request->cs );
3879 return hr;
3881 if (!(request->thread = CreateThread( NULL, 0, send_and_receive_proc, request, 0, NULL )))
3883 LeaveCriticalSection( &request->cs );
3884 return HRESULT_FROM_WIN32( get_last_error() );
3886 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3887 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3888 if (!request->async)
3890 hr = HRESULT_FROM_WIN32( request_wait( request, INFINITE ) );
3892 LeaveCriticalSection( &request->cs );
3893 return hr;
3896 static HRESULT WINAPI winhttp_request_get_Status(
3897 IWinHttpRequest *iface,
3898 LONG *status )
3900 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3901 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
3903 TRACE("%p, %p\n", request, status);
3905 if (!status) return E_INVALIDARG;
3907 EnterCriticalSection( &request->cs );
3908 if (request->state < REQUEST_STATE_SENT)
3910 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3911 goto done;
3913 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
3914 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
3916 err = get_last_error();
3917 goto done;
3919 *status = status_code;
3921 done:
3922 LeaveCriticalSection( &request->cs );
3923 return HRESULT_FROM_WIN32( err );
3926 static HRESULT WINAPI winhttp_request_get_StatusText(
3927 IWinHttpRequest *iface,
3928 BSTR *status )
3930 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3931 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
3933 TRACE("%p, %p\n", request, status);
3935 if (!status) return E_INVALIDARG;
3937 EnterCriticalSection( &request->cs );
3938 if (request->state < REQUEST_STATE_SENT)
3940 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3941 goto done;
3943 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
3945 err = get_last_error();
3946 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3948 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
3950 err = ERROR_OUTOFMEMORY;
3951 goto done;
3953 index = 0;
3954 err = ERROR_SUCCESS;
3955 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
3957 err = get_last_error();
3958 SysFreeString( *status );
3960 done:
3961 LeaveCriticalSection( &request->cs );
3962 return HRESULT_FROM_WIN32( err );
3965 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
3967 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
3968 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
3969 WCHAR *buffer, *p;
3970 DWORD size;
3972 *codepage = CP_ACP;
3973 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
3974 get_last_error() == ERROR_INSUFFICIENT_BUFFER)
3976 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
3977 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
3979 return get_last_error();
3981 if ((p = strstrW( buffer, charsetW )))
3983 p += strlenW( charsetW );
3984 while (*p == ' ') p++;
3985 if (*p++ == '=')
3987 while (*p == ' ') p++;
3988 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
3991 heap_free( buffer );
3993 return ERROR_SUCCESS;
3996 static HRESULT WINAPI winhttp_request_get_ResponseText(
3997 IWinHttpRequest *iface,
3998 BSTR *body )
4000 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4001 UINT codepage;
4002 DWORD err = ERROR_SUCCESS;
4003 int len;
4005 TRACE("%p, %p\n", request, body);
4007 if (!body) return E_INVALIDARG;
4009 EnterCriticalSection( &request->cs );
4010 if (request->state < REQUEST_STATE_SENT)
4012 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4013 goto done;
4015 if ((err = request_get_codepage( request, &codepage ))) goto done;
4016 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
4017 if (!(*body = SysAllocStringLen( NULL, len )))
4019 err = ERROR_OUTOFMEMORY;
4020 goto done;
4022 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
4023 (*body)[len] = 0;
4025 done:
4026 LeaveCriticalSection( &request->cs );
4027 return HRESULT_FROM_WIN32( err );
4030 static HRESULT WINAPI winhttp_request_get_ResponseBody(
4031 IWinHttpRequest *iface,
4032 VARIANT *body )
4034 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4035 SAFEARRAY *sa;
4036 HRESULT hr;
4037 DWORD err = ERROR_SUCCESS;
4038 char *ptr;
4040 TRACE("%p, %p\n", request, body);
4042 if (!body) return E_INVALIDARG;
4044 EnterCriticalSection( &request->cs );
4045 if (request->state < REQUEST_STATE_SENT)
4047 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4048 goto done;
4050 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
4052 err = ERROR_OUTOFMEMORY;
4053 goto done;
4055 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
4057 SafeArrayDestroy( sa );
4058 LeaveCriticalSection( &request->cs );
4059 return hr;
4061 memcpy( ptr, request->buffer, request->offset );
4062 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
4064 SafeArrayDestroy( sa );
4065 LeaveCriticalSection( &request->cs );
4066 return hr;
4068 V_VT( body ) = VT_ARRAY|VT_UI1;
4069 V_ARRAY( body ) = sa;
4071 done:
4072 LeaveCriticalSection( &request->cs );
4073 return HRESULT_FROM_WIN32( err );
4076 struct stream
4078 IStream IStream_iface;
4079 LONG refs;
4080 char *data;
4081 ULARGE_INTEGER pos, size;
4084 static inline struct stream *impl_from_IStream( IStream *iface )
4086 return CONTAINING_RECORD( iface, struct stream, IStream_iface );
4089 static HRESULT WINAPI stream_QueryInterface( IStream *iface, REFIID riid, void **obj )
4091 struct stream *stream = impl_from_IStream( iface );
4093 TRACE("%p, %s, %p\n", stream, debugstr_guid(riid), obj);
4095 if (IsEqualGUID( riid, &IID_IStream ) || IsEqualGUID( riid, &IID_IUnknown ))
4097 *obj = iface;
4099 else
4101 FIXME("interface %s not implemented\n", debugstr_guid(riid));
4102 return E_NOINTERFACE;
4104 IStream_AddRef( iface );
4105 return S_OK;
4108 static ULONG WINAPI stream_AddRef( IStream *iface )
4110 struct stream *stream = impl_from_IStream( iface );
4111 return InterlockedIncrement( &stream->refs );
4114 static ULONG WINAPI stream_Release( IStream *iface )
4116 struct stream *stream = impl_from_IStream( iface );
4117 LONG refs = InterlockedDecrement( &stream->refs );
4118 if (!refs)
4120 heap_free( stream->data );
4121 heap_free( stream );
4123 return refs;
4126 static HRESULT WINAPI stream_Read( IStream *iface, void *buf, ULONG len, ULONG *read )
4128 struct stream *stream = impl_from_IStream( iface );
4129 ULONG size;
4131 if (stream->pos.QuadPart >= stream->size.QuadPart)
4133 *read = 0;
4134 return S_FALSE;
4137 size = min( stream->size.QuadPart - stream->pos.QuadPart, len );
4138 memcpy( buf, stream->data + stream->pos.QuadPart, size );
4139 stream->pos.QuadPart += size;
4140 *read = size;
4142 return S_OK;
4145 static HRESULT WINAPI stream_Write( IStream *iface, const void *buf, ULONG len, ULONG *written )
4147 FIXME("\n");
4148 return E_NOTIMPL;
4151 static HRESULT WINAPI stream_Seek( IStream *iface, LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *newpos )
4153 struct stream *stream = impl_from_IStream( iface );
4155 if (origin == STREAM_SEEK_SET)
4156 stream->pos.QuadPart = move.QuadPart;
4157 else if (origin == STREAM_SEEK_CUR)
4158 stream->pos.QuadPart += move.QuadPart;
4159 else if (origin == STREAM_SEEK_END)
4160 stream->pos.QuadPart = stream->size.QuadPart - move.QuadPart;
4162 if (newpos) newpos->QuadPart = stream->pos.QuadPart;
4163 return S_OK;
4166 static HRESULT WINAPI stream_SetSize( IStream *iface, ULARGE_INTEGER newsize )
4168 FIXME("\n");
4169 return E_NOTIMPL;
4172 static HRESULT WINAPI stream_CopyTo( IStream *iface, IStream *stream, ULARGE_INTEGER len, ULARGE_INTEGER *read,
4173 ULARGE_INTEGER *written )
4175 FIXME("\n");
4176 return E_NOTIMPL;
4179 static HRESULT WINAPI stream_Commit( IStream *iface, DWORD flags )
4181 FIXME("\n");
4182 return E_NOTIMPL;
4185 static HRESULT WINAPI stream_Revert( IStream *iface )
4187 FIXME("\n");
4188 return E_NOTIMPL;
4191 static HRESULT WINAPI stream_LockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
4193 FIXME("\n");
4194 return E_NOTIMPL;
4197 static HRESULT WINAPI stream_UnlockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
4199 FIXME("\n");
4200 return E_NOTIMPL;
4203 static HRESULT WINAPI stream_Stat( IStream *iface, STATSTG *stg, DWORD flag )
4205 FIXME("\n");
4206 return E_NOTIMPL;
4209 static HRESULT WINAPI stream_Clone( IStream *iface, IStream **stream )
4211 FIXME("\n");
4212 return E_NOTIMPL;
4215 static const IStreamVtbl stream_vtbl =
4217 stream_QueryInterface,
4218 stream_AddRef,
4219 stream_Release,
4220 stream_Read,
4221 stream_Write,
4222 stream_Seek,
4223 stream_SetSize,
4224 stream_CopyTo,
4225 stream_Commit,
4226 stream_Revert,
4227 stream_LockRegion,
4228 stream_UnlockRegion,
4229 stream_Stat,
4230 stream_Clone
4233 static HRESULT WINAPI winhttp_request_get_ResponseStream(
4234 IWinHttpRequest *iface,
4235 VARIANT *body )
4237 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4238 DWORD err = ERROR_SUCCESS;
4239 struct stream *stream;
4241 TRACE("%p, %p\n", request, body);
4243 if (!body) return E_INVALIDARG;
4245 EnterCriticalSection( &request->cs );
4246 if (request->state < REQUEST_STATE_SENT)
4248 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4249 goto done;
4251 if (!(stream = heap_alloc( sizeof(*stream) )))
4253 err = ERROR_OUTOFMEMORY;
4254 goto done;
4256 stream->IStream_iface.lpVtbl = &stream_vtbl;
4257 stream->refs = 1;
4258 if (!(stream->data = heap_alloc( request->offset )))
4260 heap_free( stream );
4261 err = ERROR_OUTOFMEMORY;
4262 goto done;
4264 memcpy( stream->data, request->buffer, request->offset );
4265 stream->pos.QuadPart = 0;
4266 stream->size.QuadPart = request->offset;
4267 V_VT( body ) = VT_UNKNOWN;
4268 V_UNKNOWN( body ) = (IUnknown *)&stream->IStream_iface;
4270 done:
4271 LeaveCriticalSection( &request->cs );
4272 return HRESULT_FROM_WIN32( err );
4275 static HRESULT WINAPI winhttp_request_get_Option(
4276 IWinHttpRequest *iface,
4277 WinHttpRequestOption option,
4278 VARIANT *value )
4280 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4281 HRESULT hr = S_OK;
4283 TRACE("%p, %u, %p\n", request, option, value);
4285 EnterCriticalSection( &request->cs );
4286 switch (option)
4288 case WinHttpRequestOption_URLCodePage:
4289 V_VT( value ) = VT_I4;
4290 V_I4( value ) = request->url_codepage;
4291 break;
4292 default:
4293 FIXME("unimplemented option %u\n", option);
4294 hr = E_NOTIMPL;
4295 break;
4297 LeaveCriticalSection( &request->cs );
4298 return hr;
4301 static HRESULT WINAPI winhttp_request_put_Option(
4302 IWinHttpRequest *iface,
4303 WinHttpRequestOption option,
4304 VARIANT value )
4306 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4307 HRESULT hr = S_OK;
4309 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
4311 EnterCriticalSection( &request->cs );
4312 switch (option)
4314 case WinHttpRequestOption_EnableRedirects:
4316 if (V_BOOL( &value ))
4317 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
4318 else
4319 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
4320 break;
4322 case WinHttpRequestOption_URLCodePage:
4324 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
4325 VARIANT cp;
4327 VariantInit( &cp );
4328 hr = VariantChangeType( &cp, &value, 0, VT_UI4 );
4329 if (SUCCEEDED( hr ))
4331 request->url_codepage = V_UI4( &cp );
4332 TRACE("URL codepage: %u\n", request->url_codepage);
4334 else if (V_VT( &value ) == VT_BSTR && !strcmpiW( V_BSTR( &value ), utf8W ))
4336 TRACE("URL codepage: UTF-8\n");
4337 request->url_codepage = CP_UTF8;
4338 hr = S_OK;
4340 else
4341 FIXME("URL codepage %s is not recognized\n", debugstr_variant( &value ));
4342 break;
4344 default:
4345 FIXME("unimplemented option %u\n", option);
4346 hr = E_NOTIMPL;
4347 break;
4349 LeaveCriticalSection( &request->cs );
4350 return hr;
4353 static HRESULT WINAPI winhttp_request_WaitForResponse(
4354 IWinHttpRequest *iface,
4355 VARIANT timeout,
4356 VARIANT_BOOL *succeeded )
4358 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4359 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
4361 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
4363 EnterCriticalSection( &request->cs );
4364 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
4366 LeaveCriticalSection( &request->cs );
4367 return S_OK;
4369 switch ((err = request_wait( request, msecs )))
4371 case ERROR_TIMEOUT:
4372 if (succeeded) *succeeded = VARIANT_FALSE;
4373 err = ERROR_SUCCESS;
4374 break;
4376 case ERROR_SUCCESS:
4377 if (succeeded) *succeeded = VARIANT_TRUE;
4378 break;
4380 default: break;
4382 LeaveCriticalSection( &request->cs );
4383 return HRESULT_FROM_WIN32( err );
4386 static HRESULT WINAPI winhttp_request_Abort(
4387 IWinHttpRequest *iface )
4389 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4391 TRACE("%p\n", request);
4393 EnterCriticalSection( &request->cs );
4394 cancel_request( request );
4395 LeaveCriticalSection( &request->cs );
4396 return S_OK;
4399 static HRESULT WINAPI winhttp_request_SetTimeouts(
4400 IWinHttpRequest *iface,
4401 LONG resolve_timeout,
4402 LONG connect_timeout,
4403 LONG send_timeout,
4404 LONG receive_timeout )
4406 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4408 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
4410 EnterCriticalSection( &request->cs );
4411 request->resolve_timeout = resolve_timeout;
4412 request->connect_timeout = connect_timeout;
4413 request->send_timeout = send_timeout;
4414 request->receive_timeout = receive_timeout;
4415 LeaveCriticalSection( &request->cs );
4416 return S_OK;
4419 static HRESULT WINAPI winhttp_request_SetClientCertificate(
4420 IWinHttpRequest *iface,
4421 BSTR certificate )
4423 FIXME("\n");
4424 return E_NOTIMPL;
4427 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
4428 IWinHttpRequest *iface,
4429 WinHttpRequestAutoLogonPolicy policy )
4431 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4432 HRESULT hr = S_OK;
4434 TRACE("%p, %u\n", request, policy );
4436 EnterCriticalSection( &request->cs );
4437 switch (policy)
4439 case AutoLogonPolicy_Always:
4440 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
4441 break;
4442 case AutoLogonPolicy_OnlyIfBypassProxy:
4443 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
4444 break;
4445 case AutoLogonPolicy_Never:
4446 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
4447 break;
4448 default: hr = E_INVALIDARG;
4449 break;
4451 LeaveCriticalSection( &request->cs );
4452 return hr;
4455 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
4457 winhttp_request_QueryInterface,
4458 winhttp_request_AddRef,
4459 winhttp_request_Release,
4460 winhttp_request_GetTypeInfoCount,
4461 winhttp_request_GetTypeInfo,
4462 winhttp_request_GetIDsOfNames,
4463 winhttp_request_Invoke,
4464 winhttp_request_SetProxy,
4465 winhttp_request_SetCredentials,
4466 winhttp_request_Open,
4467 winhttp_request_SetRequestHeader,
4468 winhttp_request_GetResponseHeader,
4469 winhttp_request_GetAllResponseHeaders,
4470 winhttp_request_Send,
4471 winhttp_request_get_Status,
4472 winhttp_request_get_StatusText,
4473 winhttp_request_get_ResponseText,
4474 winhttp_request_get_ResponseBody,
4475 winhttp_request_get_ResponseStream,
4476 winhttp_request_get_Option,
4477 winhttp_request_put_Option,
4478 winhttp_request_WaitForResponse,
4479 winhttp_request_Abort,
4480 winhttp_request_SetTimeouts,
4481 winhttp_request_SetClientCertificate,
4482 winhttp_request_SetAutoLogonPolicy
4485 HRESULT WinHttpRequest_create( void **obj )
4487 struct winhttp_request *request;
4489 TRACE("%p\n", obj);
4491 if (!(request = heap_alloc( sizeof(*request) ))) return E_OUTOFMEMORY;
4492 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
4493 request->refs = 1;
4494 request->state = REQUEST_STATE_UNINITIALIZED;
4495 request->proxy.lpszProxy = NULL;
4496 request->proxy.lpszProxyBypass = NULL;
4497 request->url_codepage = CP_UTF8;
4498 InitializeCriticalSection( &request->cs );
4499 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
4501 *obj = &request->IWinHttpRequest_iface;
4502 TRACE("returning iface %p\n", *obj);
4503 return S_OK;