include: Use the hard-float calling convention for Windows APIs on ARM
[wine.git] / dlls / winhttp / request.c
blob96a2c91de55903080a516cb6915ae2cee9888098
1 /*
2 * Copyright 2004 Mike McCormack for CodeWeavers
3 * Copyright 2006 Rob Shearman for CodeWeavers
4 * Copyright 2008, 2011 Hans Leidekker for CodeWeavers
5 * Copyright 2009 Juan Lang
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #define COBJMACROS
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <assert.h>
28 #ifdef HAVE_ARPA_INET_H
29 # include <arpa/inet.h>
30 #endif
32 #include "windef.h"
33 #include "winbase.h"
34 #include "ole2.h"
35 #include "initguid.h"
36 #include "httprequest.h"
37 #include "httprequestid.h"
38 #include "schannel.h"
39 #include "winhttp.h"
41 #include "winhttp_private.h"
43 #include "wine/debug.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
47 #define DEFAULT_KEEP_ALIVE_TIMEOUT 30000
49 static const WCHAR attr_accept[] = {'A','c','c','e','p','t',0};
50 static const WCHAR attr_accept_charset[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
51 static const WCHAR attr_accept_encoding[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
52 static const WCHAR attr_accept_language[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
53 static const WCHAR attr_accept_ranges[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
54 static const WCHAR attr_age[] = {'A','g','e',0};
55 static const WCHAR attr_allow[] = {'A','l','l','o','w',0};
56 static const WCHAR attr_authorization[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
57 static const WCHAR attr_cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
58 static const WCHAR attr_connection[] = {'C','o','n','n','e','c','t','i','o','n',0};
59 static const WCHAR attr_content_base[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
60 static const WCHAR attr_content_encoding[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
61 static const WCHAR attr_content_id[] = {'C','o','n','t','e','n','t','-','I','D',0};
62 static const WCHAR attr_content_language[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
63 static const WCHAR attr_content_length[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
64 static const WCHAR attr_content_location[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
65 static const WCHAR attr_content_md5[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
66 static const WCHAR attr_content_range[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
67 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};
68 static const WCHAR attr_content_type[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
69 static const WCHAR attr_cookie[] = {'C','o','o','k','i','e',0};
70 static const WCHAR attr_date[] = {'D','a','t','e',0};
71 static const WCHAR attr_from[] = {'F','r','o','m',0};
72 static const WCHAR attr_etag[] = {'E','T','a','g',0};
73 static const WCHAR attr_expect[] = {'E','x','p','e','c','t',0};
74 static const WCHAR attr_expires[] = {'E','x','p','i','r','e','s',0};
75 static const WCHAR attr_host[] = {'H','o','s','t',0};
76 static const WCHAR attr_if_match[] = {'I','f','-','M','a','t','c','h',0};
77 static const WCHAR attr_if_modified_since[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
78 static const WCHAR attr_if_none_match[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
79 static const WCHAR attr_if_range[] = {'I','f','-','R','a','n','g','e',0};
80 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};
81 static const WCHAR attr_last_modified[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
82 static const WCHAR attr_location[] = {'L','o','c','a','t','i','o','n',0};
83 static const WCHAR attr_max_forwards[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
84 static const WCHAR attr_mime_version[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
85 static const WCHAR attr_pragma[] = {'P','r','a','g','m','a',0};
86 static const WCHAR attr_proxy_authenticate[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
87 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};
88 static const WCHAR attr_proxy_connection[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
89 static const WCHAR attr_public[] = {'P','u','b','l','i','c',0};
90 static const WCHAR attr_range[] = {'R','a','n','g','e',0};
91 static const WCHAR attr_referer[] = {'R','e','f','e','r','e','r',0};
92 static const WCHAR attr_retry_after[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
93 static const WCHAR attr_server[] = {'S','e','r','v','e','r',0};
94 static const WCHAR attr_set_cookie[] = {'S','e','t','-','C','o','o','k','i','e',0};
95 static const WCHAR attr_status[] = {'S','t','a','t','u','s',0};
96 static const WCHAR attr_transfer_encoding[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
97 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};
98 static const WCHAR attr_upgrade[] = {'U','p','g','r','a','d','e',0};
99 static const WCHAR attr_uri[] = {'U','R','I',0};
100 static const WCHAR attr_user_agent[] = {'U','s','e','r','-','A','g','e','n','t',0};
101 static const WCHAR attr_vary[] = {'V','a','r','y',0};
102 static const WCHAR attr_via[] = {'V','i','a',0};
103 static const WCHAR attr_warning[] = {'W','a','r','n','i','n','g',0};
104 static const WCHAR attr_www_authenticate[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
106 static const WCHAR *attribute_table[] =
108 attr_mime_version, /* WINHTTP_QUERY_MIME_VERSION = 0 */
109 attr_content_type, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
110 attr_content_transfer_encoding, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
111 attr_content_id, /* WINHTTP_QUERY_CONTENT_ID = 3 */
112 NULL, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
113 attr_content_length, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
114 attr_content_language, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
115 attr_allow, /* WINHTTP_QUERY_ALLOW = 7 */
116 attr_public, /* WINHTTP_QUERY_PUBLIC = 8 */
117 attr_date, /* WINHTTP_QUERY_DATE = 9 */
118 attr_expires, /* WINHTTP_QUERY_EXPIRES = 10 */
119 attr_last_modified, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
120 NULL, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
121 attr_uri, /* WINHTTP_QUERY_URI = 13 */
122 attr_from, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
123 NULL, /* WINHTTP_QUERY_COST = 15 */
124 NULL, /* WINHTTP_QUERY_LINK = 16 */
125 attr_pragma, /* WINHTTP_QUERY_PRAGMA = 17 */
126 NULL, /* WINHTTP_QUERY_VERSION = 18 */
127 attr_status, /* WINHTTP_QUERY_STATUS_CODE = 19 */
128 NULL, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
129 NULL, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
130 NULL, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
131 attr_connection, /* WINHTTP_QUERY_CONNECTION = 23 */
132 attr_accept, /* WINHTTP_QUERY_ACCEPT = 24 */
133 attr_accept_charset, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
134 attr_accept_encoding, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
135 attr_accept_language, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
136 attr_authorization, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
137 attr_content_encoding, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
138 NULL, /* WINHTTP_QUERY_FORWARDED = 30 */
139 NULL, /* WINHTTP_QUERY_FROM = 31 */
140 attr_if_modified_since, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
141 attr_location, /* WINHTTP_QUERY_LOCATION = 33 */
142 NULL, /* WINHTTP_QUERY_ORIG_URI = 34 */
143 attr_referer, /* WINHTTP_QUERY_REFERER = 35 */
144 attr_retry_after, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
145 attr_server, /* WINHTTP_QUERY_SERVER = 37 */
146 NULL, /* WINHTTP_TITLE = 38 */
147 attr_user_agent, /* WINHTTP_QUERY_USER_AGENT = 39 */
148 attr_www_authenticate, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
149 attr_proxy_authenticate, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
150 attr_accept_ranges, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
151 attr_set_cookie, /* WINHTTP_QUERY_SET_COOKIE = 43 */
152 attr_cookie, /* WINHTTP_QUERY_COOKIE = 44 */
153 NULL, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
154 NULL, /* WINHTTP_QUERY_REFRESH = 46 */
155 NULL, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
156 attr_age, /* WINHTTP_QUERY_AGE = 48 */
157 attr_cache_control, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
158 attr_content_base, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
159 attr_content_location, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
160 attr_content_md5, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
161 attr_content_range, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
162 attr_etag, /* WINHTTP_QUERY_ETAG = 54 */
163 attr_host, /* WINHTTP_QUERY_HOST = 55 */
164 attr_if_match, /* WINHTTP_QUERY_IF_MATCH = 56 */
165 attr_if_none_match, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
166 attr_if_range, /* WINHTTP_QUERY_IF_RANGE = 58 */
167 attr_if_unmodified_since, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
168 attr_max_forwards, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
169 attr_proxy_authorization, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
170 attr_range, /* WINHTTP_QUERY_RANGE = 62 */
171 attr_transfer_encoding, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
172 attr_upgrade, /* WINHTTP_QUERY_UPGRADE = 64 */
173 attr_vary, /* WINHTTP_QUERY_VARY = 65 */
174 attr_via, /* WINHTTP_QUERY_VIA = 66 */
175 attr_warning, /* WINHTTP_QUERY_WARNING = 67 */
176 attr_expect, /* WINHTTP_QUERY_EXPECT = 68 */
177 attr_proxy_connection, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
178 attr_unless_modified_since, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
179 NULL, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
180 NULL, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
181 NULL, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
182 NULL /* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
185 static task_header_t *dequeue_task( request_t *request )
187 task_header_t *task;
189 EnterCriticalSection( &request->task_cs );
190 TRACE("%u tasks queued\n", list_count( &request->task_queue ));
191 task = LIST_ENTRY( list_head( &request->task_queue ), task_header_t, entry );
192 if (task) list_remove( &task->entry );
193 LeaveCriticalSection( &request->task_cs );
195 TRACE("returning task %p\n", task);
196 return task;
199 static DWORD CALLBACK task_proc( LPVOID param )
201 request_t *request = param;
202 HANDLE handles[2];
204 handles[0] = request->task_wait;
205 handles[1] = request->task_cancel;
206 for (;;)
208 DWORD err = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
209 switch (err)
211 case WAIT_OBJECT_0:
213 task_header_t *task;
214 while ((task = dequeue_task( request )))
216 task->proc( task );
217 release_object( &task->request->hdr );
218 heap_free( task );
220 break;
222 case WAIT_OBJECT_0 + 1:
223 TRACE("exiting\n");
224 CloseHandle( request->task_cancel );
225 CloseHandle( request->task_wait );
226 request->task_cs.DebugInfo->Spare[0] = 0;
227 DeleteCriticalSection( &request->task_cs );
228 request->hdr.vtbl->destroy( &request->hdr );
229 return 0;
231 default:
232 ERR("wait failed %u (%u)\n", err, GetLastError());
233 break;
236 return 0;
239 static BOOL queue_task( task_header_t *task )
241 request_t *request = task->request;
243 if (!request->task_thread)
245 if (!(request->task_wait = CreateEventW( NULL, FALSE, FALSE, NULL ))) return FALSE;
246 if (!(request->task_cancel = CreateEventW( NULL, FALSE, FALSE, NULL )))
248 CloseHandle( request->task_wait );
249 request->task_wait = NULL;
250 return FALSE;
252 if (!(request->task_thread = CreateThread( NULL, 0, task_proc, request, 0, NULL )))
254 CloseHandle( request->task_wait );
255 request->task_wait = NULL;
256 CloseHandle( request->task_cancel );
257 request->task_cancel = NULL;
258 return FALSE;
260 InitializeCriticalSection( &request->task_cs );
261 request->task_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": request.task_cs");
264 EnterCriticalSection( &request->task_cs );
265 TRACE("queueing task %p\n", task );
266 list_add_tail( &request->task_queue, &task->entry );
267 LeaveCriticalSection( &request->task_cs );
269 SetEvent( request->task_wait );
270 return TRUE;
273 static void free_header( header_t *header )
275 heap_free( header->field );
276 heap_free( header->value );
277 heap_free( header );
280 static BOOL valid_token_char( WCHAR c )
282 if (c < 32 || c == 127) return FALSE;
283 switch (c)
285 case '(': case ')':
286 case '<': case '>':
287 case '@': case ',':
288 case ';': case ':':
289 case '\\': case '\"':
290 case '/': case '[':
291 case ']': case '?':
292 case '=': case '{':
293 case '}': case ' ':
294 case '\t':
295 return FALSE;
296 default:
297 return TRUE;
301 static header_t *parse_header( LPCWSTR string )
303 const WCHAR *p, *q;
304 header_t *header;
305 int len;
307 p = string;
308 if (!(q = strchrW( p, ':' )))
310 WARN("no ':' in line %s\n", debugstr_w(string));
311 return NULL;
313 if (q == string)
315 WARN("empty field name in line %s\n", debugstr_w(string));
316 return NULL;
318 while (*p != ':')
320 if (!valid_token_char( *p ))
322 WARN("invalid character in field name %s\n", debugstr_w(string));
323 return NULL;
325 p++;
327 len = q - string;
328 if (!(header = heap_alloc_zero( sizeof(header_t) ))) return NULL;
329 if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
331 heap_free( header );
332 return NULL;
334 memcpy( header->field, string, len * sizeof(WCHAR) );
335 header->field[len] = 0;
337 q++; /* skip past colon */
338 while (*q == ' ') q++;
339 len = strlenW( q );
341 if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
343 free_header( header );
344 return NULL;
346 memcpy( header->value, q, len * sizeof(WCHAR) );
347 header->value[len] = 0;
349 return header;
352 static int get_header_index( request_t *request, LPCWSTR field, int requested_index, BOOL request_only )
354 int index;
356 TRACE("%s\n", debugstr_w(field));
358 for (index = 0; index < request->num_headers; index++)
360 if (strcmpiW( request->headers[index].field, field )) continue;
361 if (request_only && !request->headers[index].is_request) continue;
362 if (!request_only && request->headers[index].is_request) continue;
364 if (!requested_index) break;
365 requested_index--;
367 if (index >= request->num_headers) index = -1;
368 TRACE("returning %d\n", index);
369 return index;
372 static BOOL insert_header( request_t *request, header_t *header )
374 DWORD count = request->num_headers + 1;
375 header_t *hdrs;
377 if (request->headers)
378 hdrs = heap_realloc_zero( request->headers, sizeof(header_t) * count );
379 else
380 hdrs = heap_alloc_zero( sizeof(header_t) );
381 if (!hdrs) return FALSE;
383 request->headers = hdrs;
384 request->headers[count - 1].field = strdupW( header->field );
385 request->headers[count - 1].value = strdupW( header->value );
386 request->headers[count - 1].is_request = header->is_request;
387 request->num_headers = count;
388 return TRUE;
391 static BOOL delete_header( request_t *request, DWORD index )
393 if (!request->num_headers) return FALSE;
394 if (index >= request->num_headers) return FALSE;
395 request->num_headers--;
397 heap_free( request->headers[index].field );
398 heap_free( request->headers[index].value );
400 memmove( &request->headers[index], &request->headers[index + 1], (request->num_headers - index) * sizeof(header_t) );
401 memset( &request->headers[request->num_headers], 0, sizeof(header_t) );
402 return TRUE;
405 static BOOL process_header( request_t *request, LPCWSTR field, LPCWSTR value, DWORD flags, BOOL request_only )
407 int index;
408 header_t hdr;
410 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
412 if ((index = get_header_index( request, field, 0, request_only )) >= 0)
414 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
417 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
419 if (index >= 0)
421 delete_header( request, index );
422 if (!value || !value[0]) return TRUE;
424 else if (!(flags & WINHTTP_ADDREQ_FLAG_ADD))
426 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
427 return FALSE;
430 hdr.field = (LPWSTR)field;
431 hdr.value = (LPWSTR)value;
432 hdr.is_request = request_only;
433 return insert_header( request, &hdr );
435 else if (value)
438 if ((flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON)) &&
439 index >= 0)
441 WCHAR *tmp;
442 int len, len_orig, len_value;
443 header_t *header = &request->headers[index];
445 len_orig = strlenW( header->value );
446 len_value = strlenW( value );
448 len = len_orig + len_value + 2;
449 if (!(tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) ))) return FALSE;
450 header->value = tmp;
451 header->value[len_orig++] = (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) ? ',' : ';';
452 header->value[len_orig++] = ' ';
454 memcpy( &header->value[len_orig], value, len_value * sizeof(WCHAR) );
455 header->value[len] = 0;
456 return TRUE;
458 else
460 hdr.field = (LPWSTR)field;
461 hdr.value = (LPWSTR)value;
462 hdr.is_request = request_only;
463 return insert_header( request, &hdr );
467 return TRUE;
470 BOOL add_request_headers( request_t *request, LPCWSTR headers, DWORD len, DWORD flags )
472 BOOL ret = FALSE;
473 WCHAR *buffer, *p, *q;
474 header_t *header;
476 if (len == ~0u) len = strlenW( headers );
477 if (!len) return TRUE;
478 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
479 memcpy( buffer, headers, len * sizeof(WCHAR) );
480 buffer[len] = 0;
482 p = buffer;
485 q = p;
486 while (*q)
488 if (q[0] == '\n' && q[1] == '\r')
490 q[0] = '\r';
491 q[1] = '\n';
493 if (q[0] == '\r' && q[1] == '\n') break;
494 q++;
496 if (!*p) break;
497 if (*q == '\r')
499 *q = 0;
500 q += 2; /* jump over \r\n */
502 if ((header = parse_header( p )))
504 ret = process_header( request, header->field, header->value, flags, TRUE );
505 free_header( header );
507 p = q;
508 } while (ret);
510 heap_free( buffer );
511 return ret;
514 /***********************************************************************
515 * WinHttpAddRequestHeaders (winhttp.@)
517 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
519 BOOL ret;
520 request_t *request;
522 TRACE("%p, %s, %u, 0x%08x\n", hrequest, debugstr_wn(headers, len), len, flags);
524 if (!headers || !len)
526 set_last_error( ERROR_INVALID_PARAMETER );
527 return FALSE;
529 if (!(request = (request_t *)grab_object( hrequest )))
531 set_last_error( ERROR_INVALID_HANDLE );
532 return FALSE;
534 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
536 release_object( &request->hdr );
537 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
538 return FALSE;
541 ret = add_request_headers( request, headers, len, flags );
543 release_object( &request->hdr );
544 if (ret) set_last_error( ERROR_SUCCESS );
545 return ret;
548 static WCHAR *build_request_path( request_t *request )
550 WCHAR *ret;
552 if (strcmpiW( request->connect->hostname, request->connect->servername ))
554 static const WCHAR http[] = { 'h','t','t','p',0 };
555 static const WCHAR https[] = { 'h','t','t','p','s',0 };
556 static const WCHAR fmt[] = { '%','s',':','/','/','%','s',0 };
557 LPCWSTR scheme = (request->netconn ? request->netconn->secure : (request->hdr.flags & WINHTTP_FLAG_SECURE)) ? https : http;
558 int len;
560 len = strlenW( scheme ) + strlenW( request->connect->hostname );
561 /* 3 characters for '://', 1 for NUL. */
562 len += 4;
563 if (request->connect->hostport)
565 /* 1 for ':' between host and port, up to 5 for port */
566 len += 6;
568 if (request->path)
569 len += strlenW( request->path );
570 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
572 sprintfW( ret, fmt, scheme, request->connect->hostname );
573 if (request->connect->hostport)
575 static const WCHAR colonFmt[] = { ':','%','u',0 };
577 sprintfW( ret + strlenW( ret ), colonFmt,
578 request->connect->hostport );
580 if (request->path)
581 strcatW( ret, request->path );
584 else
585 ret = request->path;
586 return ret;
589 static WCHAR *build_request_string( request_t *request )
591 static const WCHAR space[] = {' ',0};
592 static const WCHAR crlf[] = {'\r','\n',0};
593 static const WCHAR colon[] = {':',' ',0};
594 static const WCHAR twocrlf[] = {'\r','\n','\r','\n',0};
596 WCHAR *path, *ret;
597 const WCHAR **headers, **p;
598 unsigned int len, i = 0, j;
600 /* allocate space for an array of all the string pointers to be added */
601 len = request->num_headers * 4 + 7;
602 if (!(headers = heap_alloc( len * sizeof(LPCWSTR) ))) return NULL;
604 path = build_request_path( request );
605 headers[i++] = request->verb;
606 headers[i++] = space;
607 headers[i++] = path;
608 headers[i++] = space;
609 headers[i++] = request->version;
611 for (j = 0; j < request->num_headers; j++)
613 if (request->headers[j].is_request)
615 headers[i++] = crlf;
616 headers[i++] = request->headers[j].field;
617 headers[i++] = colon;
618 headers[i++] = request->headers[j].value;
620 TRACE("adding header %s (%s)\n", debugstr_w(request->headers[j].field),
621 debugstr_w(request->headers[j].value));
624 headers[i++] = twocrlf;
625 headers[i] = NULL;
627 len = 0;
628 for (p = headers; *p; p++) len += strlenW( *p );
629 len++;
631 if (!(ret = heap_alloc( len * sizeof(WCHAR) )))
632 goto out;
633 *ret = 0;
634 for (p = headers; *p; p++) strcatW( ret, *p );
636 out:
637 if (path != request->path)
638 heap_free( path );
639 heap_free( headers );
640 return ret;
643 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
645 static BOOL query_headers( request_t *request, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
647 header_t *header = NULL;
648 BOOL request_only, ret = FALSE;
649 int requested_index, header_index = -1;
650 DWORD attr, len;
652 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
653 requested_index = index ? *index : 0;
655 attr = level & ~QUERY_MODIFIER_MASK;
656 switch (attr)
658 case WINHTTP_QUERY_CUSTOM:
660 header_index = get_header_index( request, name, requested_index, request_only );
661 break;
663 case WINHTTP_QUERY_RAW_HEADERS:
665 WCHAR *headers, *p, *q;
667 if (request_only)
668 headers = build_request_string( request );
669 else
670 headers = request->raw_headers;
672 if (!(p = headers)) return FALSE;
673 for (len = 0; *p; p++) if (*p != '\r') len++;
675 if (!buffer || len * sizeof(WCHAR) > *buflen)
676 set_last_error( ERROR_INSUFFICIENT_BUFFER );
677 else
679 for (p = headers, q = buffer; *p; p++, q++)
681 if (*p != '\r') *q = *p;
682 else
684 *q = 0;
685 p++; /* skip '\n' */
688 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
689 if (len) len--;
690 ret = TRUE;
692 *buflen = len * sizeof(WCHAR);
693 if (request_only) heap_free( headers );
694 return ret;
696 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
698 WCHAR *headers;
700 if (request_only)
701 headers = build_request_string( request );
702 else
703 headers = request->raw_headers;
705 if (!headers) return FALSE;
706 len = strlenW( headers ) * sizeof(WCHAR);
707 if (!buffer || len + sizeof(WCHAR) > *buflen)
709 len += sizeof(WCHAR);
710 set_last_error( ERROR_INSUFFICIENT_BUFFER );
712 else
714 memcpy( buffer, headers, len + sizeof(WCHAR) );
715 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
716 ret = TRUE;
718 *buflen = len;
719 if (request_only) heap_free( headers );
720 return ret;
722 case WINHTTP_QUERY_VERSION:
723 len = strlenW( request->version ) * sizeof(WCHAR);
724 if (!buffer || len + sizeof(WCHAR) > *buflen)
726 len += sizeof(WCHAR);
727 set_last_error( ERROR_INSUFFICIENT_BUFFER );
729 else
731 strcpyW( buffer, request->version );
732 TRACE("returning string: %s\n", debugstr_w(buffer));
733 ret = TRUE;
735 *buflen = len;
736 return ret;
738 case WINHTTP_QUERY_STATUS_TEXT:
739 len = strlenW( request->status_text ) * sizeof(WCHAR);
740 if (!buffer || len + sizeof(WCHAR) > *buflen)
742 len += sizeof(WCHAR);
743 set_last_error( ERROR_INSUFFICIENT_BUFFER );
745 else
747 strcpyW( buffer, request->status_text );
748 TRACE("returning string: %s\n", debugstr_w(buffer));
749 ret = TRUE;
751 *buflen = len;
752 return ret;
754 default:
755 if (attr >= sizeof(attribute_table)/sizeof(attribute_table[0]) || !attribute_table[attr])
757 FIXME("attribute %u not implemented\n", attr);
758 return FALSE;
760 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
761 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
762 break;
765 if (header_index >= 0)
767 header = &request->headers[header_index];
769 if (!header || (request_only && !header->is_request))
771 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
772 return FALSE;
774 if (index) *index += 1;
775 if (level & WINHTTP_QUERY_FLAG_NUMBER)
777 if (!buffer || sizeof(int) > *buflen)
779 set_last_error( ERROR_INSUFFICIENT_BUFFER );
781 else
783 int *number = buffer;
784 *number = atoiW( header->value );
785 TRACE("returning number: %d\n", *number);
786 ret = TRUE;
788 *buflen = sizeof(int);
790 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
792 SYSTEMTIME *st = buffer;
793 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
795 set_last_error( ERROR_INSUFFICIENT_BUFFER );
797 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
799 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
800 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
801 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
803 *buflen = sizeof(SYSTEMTIME);
805 else if (header->value)
807 len = strlenW( header->value ) * sizeof(WCHAR);
808 if (!buffer || len + sizeof(WCHAR) > *buflen)
810 len += sizeof(WCHAR);
811 set_last_error( ERROR_INSUFFICIENT_BUFFER );
813 else
815 strcpyW( buffer, header->value );
816 TRACE("returning string: %s\n", debugstr_w(buffer));
817 ret = TRUE;
819 *buflen = len;
821 return ret;
824 /***********************************************************************
825 * WinHttpQueryHeaders (winhttp.@)
827 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
829 BOOL ret;
830 request_t *request;
832 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
834 if (!(request = (request_t *)grab_object( hrequest )))
836 set_last_error( ERROR_INVALID_HANDLE );
837 return FALSE;
839 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
841 release_object( &request->hdr );
842 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
843 return FALSE;
846 ret = query_headers( request, level, name, buffer, buflen, index );
848 release_object( &request->hdr );
849 if (ret) set_last_error( ERROR_SUCCESS );
850 return ret;
854 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
856 static const WCHAR basicW[] = {'B','a','s','i','c',0};
857 static const WCHAR ntlmW[] = {'N','T','L','M',0};
858 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
859 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
860 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
862 static const struct
864 const WCHAR *str;
865 unsigned int len;
866 DWORD scheme;
868 auth_schemes[] =
870 { basicW, ARRAYSIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
871 { ntlmW, ARRAYSIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
872 { passportW, ARRAYSIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
873 { digestW, ARRAYSIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
874 { negotiateW, ARRAYSIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
876 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
878 static enum auth_scheme scheme_from_flag( DWORD flag )
880 int i;
882 for (i = 0; i < num_auth_schemes; i++) if (flag == auth_schemes[i].scheme) return i;
883 return SCHEME_INVALID;
886 static DWORD auth_scheme_from_header( WCHAR *header )
888 unsigned int i;
890 for (i = 0; i < num_auth_schemes; i++)
892 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
893 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
895 return 0;
898 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
900 DWORD index = 0, supported_schemes = 0, first_scheme = 0;
901 BOOL ret = FALSE;
903 for (;;)
905 WCHAR *buffer;
906 DWORD size, scheme;
908 size = 0;
909 query_headers( request, level, NULL, NULL, &size, &index );
910 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) break;
912 index--;
913 if (!(buffer = heap_alloc( size ))) return FALSE;
914 if (!query_headers( request, level, NULL, buffer, &size, &index ))
916 heap_free( buffer );
917 return FALSE;
919 scheme = auth_scheme_from_header( buffer );
920 heap_free( buffer );
921 if (!scheme) continue;
923 if (!first_scheme) first_scheme = scheme;
924 supported_schemes |= scheme;
926 ret = TRUE;
929 if (ret)
931 *supported = supported_schemes;
932 *first = first_scheme;
934 return ret;
937 /***********************************************************************
938 * WinHttpQueryAuthSchemes (winhttp.@)
940 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
942 BOOL ret = FALSE;
943 request_t *request;
945 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
947 if (!(request = (request_t *)grab_object( hrequest )))
949 set_last_error( ERROR_INVALID_HANDLE );
950 return FALSE;
952 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
954 release_object( &request->hdr );
955 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
956 return FALSE;
958 if (!supported || !first || !target)
960 release_object( &request->hdr );
961 set_last_error( ERROR_INVALID_PARAMETER );
962 return FALSE;
966 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
968 *target = WINHTTP_AUTH_TARGET_SERVER;
969 ret = TRUE;
971 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
973 *target = WINHTTP_AUTH_TARGET_PROXY;
974 ret = TRUE;
977 release_object( &request->hdr );
978 if (ret) set_last_error( ERROR_SUCCESS );
979 return ret;
982 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
984 UINT n = 0, x;
985 static const char base64enc[] =
986 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
988 while (len > 0)
990 /* first 6 bits, all from bin[0] */
991 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
992 x = (bin[0] & 3) << 4;
994 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
995 if (len == 1)
997 base64[n++] = base64enc[x];
998 base64[n++] = '=';
999 base64[n++] = '=';
1000 break;
1002 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
1003 x = (bin[1] & 0x0f) << 2;
1005 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1006 if (len == 2)
1008 base64[n++] = base64enc[x];
1009 base64[n++] = '=';
1010 break;
1012 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1014 /* last 6 bits, all from bin [2] */
1015 base64[n++] = base64enc[bin[2] & 0x3f];
1016 bin += 3;
1017 len -= 3;
1019 base64[n] = 0;
1020 return n;
1023 static inline char decode_char( WCHAR c )
1025 if (c >= 'A' && c <= 'Z') return c - 'A';
1026 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1027 if (c >= '0' && c <= '9') return c - '0' + 52;
1028 if (c == '+') return 62;
1029 if (c == '/') return 63;
1030 return 64;
1033 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1035 unsigned int i = 0;
1036 char c0, c1, c2, c3;
1037 const WCHAR *p = base64;
1039 while (len > 4)
1041 if ((c0 = decode_char( p[0] )) > 63) return 0;
1042 if ((c1 = decode_char( p[1] )) > 63) return 0;
1043 if ((c2 = decode_char( p[2] )) > 63) return 0;
1044 if ((c3 = decode_char( p[3] )) > 63) return 0;
1046 if (buf)
1048 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1049 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1050 buf[i + 2] = (c2 << 6) | c3;
1052 len -= 4;
1053 i += 3;
1054 p += 4;
1056 if (p[2] == '=')
1058 if ((c0 = decode_char( p[0] )) > 63) return 0;
1059 if ((c1 = decode_char( p[1] )) > 63) return 0;
1061 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1062 i++;
1064 else if (p[3] == '=')
1066 if ((c0 = decode_char( p[0] )) > 63) return 0;
1067 if ((c1 = decode_char( p[1] )) > 63) return 0;
1068 if ((c2 = decode_char( p[2] )) > 63) return 0;
1070 if (buf)
1072 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1073 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1075 i += 2;
1077 else
1079 if ((c0 = decode_char( p[0] )) > 63) return 0;
1080 if ((c1 = decode_char( p[1] )) > 63) return 0;
1081 if ((c2 = decode_char( p[2] )) > 63) return 0;
1082 if ((c3 = decode_char( p[3] )) > 63) return 0;
1084 if (buf)
1086 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1087 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1088 buf[i + 2] = (c2 << 6) | c3;
1090 i += 3;
1092 return i;
1095 static struct authinfo *alloc_authinfo(void)
1097 struct authinfo *ret;
1099 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1101 SecInvalidateHandle( &ret->cred );
1102 SecInvalidateHandle( &ret->ctx );
1103 memset( &ret->exp, 0, sizeof(ret->exp) );
1104 ret->scheme = 0;
1105 ret->attr = 0;
1106 ret->max_token = 0;
1107 ret->data = NULL;
1108 ret->data_len = 0;
1109 ret->finished = FALSE;
1110 return ret;
1113 void destroy_authinfo( struct authinfo *authinfo )
1115 if (!authinfo) return;
1117 if (SecIsValidHandle( &authinfo->ctx ))
1118 DeleteSecurityContext( &authinfo->ctx );
1119 if (SecIsValidHandle( &authinfo->cred ))
1120 FreeCredentialsHandle( &authinfo->cred );
1122 heap_free( authinfo->data );
1123 heap_free( authinfo );
1126 static BOOL get_authvalue( request_t *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1128 DWORD size, index = 0;
1129 for (;;)
1131 size = len;
1132 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1133 if (auth_scheme_from_header( buffer ) == scheme) break;
1135 return TRUE;
1138 static BOOL do_authorization( request_t *request, DWORD target, DWORD scheme_flag )
1140 struct authinfo *authinfo, **auth_ptr;
1141 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1142 const WCHAR *auth_target, *username, *password;
1143 WCHAR auth_value[2048], *auth_reply;
1144 DWORD len = sizeof(auth_value), len_scheme, flags;
1145 BOOL ret, has_auth_value;
1147 if (scheme == SCHEME_INVALID) return FALSE;
1149 switch (target)
1151 case WINHTTP_AUTH_TARGET_SERVER:
1152 has_auth_value = get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len );
1153 auth_ptr = &request->authinfo;
1154 auth_target = attr_authorization;
1155 if (request->creds[TARGET_SERVER][scheme].username)
1157 if (scheme != SCHEME_BASIC && !has_auth_value) return FALSE;
1158 username = request->creds[TARGET_SERVER][scheme].username;
1159 password = request->creds[TARGET_SERVER][scheme].password;
1161 else
1163 if (!has_auth_value) return FALSE;
1164 username = request->connect->username;
1165 password = request->connect->password;
1167 break;
1169 case WINHTTP_AUTH_TARGET_PROXY:
1170 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1171 return FALSE;
1172 auth_ptr = &request->proxy_authinfo;
1173 auth_target = attr_proxy_authorization;
1174 if (request->creds[TARGET_PROXY][scheme].username)
1176 username = request->creds[TARGET_PROXY][scheme].username;
1177 password = request->creds[TARGET_PROXY][scheme].password;
1179 else
1181 username = request->connect->session->proxy_username;
1182 password = request->connect->session->proxy_password;
1184 break;
1186 default:
1187 WARN("unknown target %x\n", target);
1188 return FALSE;
1190 authinfo = *auth_ptr;
1192 switch (scheme)
1194 case SCHEME_BASIC:
1196 int userlen, passlen;
1198 if (!username || !password) return FALSE;
1199 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1201 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1202 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1204 authinfo->data_len = userlen + 1 + passlen;
1205 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1207 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1208 authinfo->data[userlen] = ':';
1209 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1211 authinfo->scheme = SCHEME_BASIC;
1212 authinfo->finished = TRUE;
1213 break;
1215 case SCHEME_NTLM:
1216 case SCHEME_NEGOTIATE:
1218 SECURITY_STATUS status;
1219 SecBufferDesc out_desc, in_desc;
1220 SecBuffer out, in;
1221 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1222 const WCHAR *p;
1223 BOOL first = FALSE;
1225 if (!authinfo)
1227 TimeStamp exp;
1228 SEC_WINNT_AUTH_IDENTITY_W id;
1229 WCHAR *domain, *user;
1231 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1233 first = TRUE;
1234 domain = (WCHAR *)username;
1235 user = strchrW( username, '\\' );
1237 if (user) user++;
1238 else
1240 user = (WCHAR *)username;
1241 domain = NULL;
1243 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1244 id.User = user;
1245 id.UserLength = strlenW( user );
1246 id.Domain = domain;
1247 id.DomainLength = domain ? user - domain - 1 : 0;
1248 id.Password = (WCHAR *)password;
1249 id.PasswordLength = strlenW( password );
1251 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1252 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1253 &authinfo->cred, &exp );
1254 if (status == SEC_E_OK)
1256 PSecPkgInfoW info;
1257 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1258 if (status == SEC_E_OK)
1260 authinfo->max_token = info->cbMaxToken;
1261 FreeContextBuffer( info );
1264 if (status != SEC_E_OK)
1266 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1267 debugstr_w(auth_schemes[scheme].str), status);
1268 heap_free( authinfo );
1269 return FALSE;
1271 authinfo->scheme = scheme;
1273 else if (authinfo->finished) return FALSE;
1275 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1276 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1278 ERR("authentication scheme changed from %s to %s\n",
1279 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1280 destroy_authinfo( authinfo );
1281 *auth_ptr = NULL;
1282 return FALSE;
1284 in.BufferType = SECBUFFER_TOKEN;
1285 in.cbBuffer = 0;
1286 in.pvBuffer = NULL;
1288 in_desc.ulVersion = 0;
1289 in_desc.cBuffers = 1;
1290 in_desc.pBuffers = &in;
1292 p = auth_value + auth_schemes[scheme].len;
1293 if (*p == ' ')
1295 int len = strlenW( ++p );
1296 in.cbBuffer = decode_base64( p, len, NULL );
1297 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) {
1298 destroy_authinfo( authinfo );
1299 *auth_ptr = NULL;
1300 return FALSE;
1302 decode_base64( p, len, in.pvBuffer );
1304 out.BufferType = SECBUFFER_TOKEN;
1305 out.cbBuffer = authinfo->max_token;
1306 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1308 heap_free( in.pvBuffer );
1309 destroy_authinfo( authinfo );
1310 *auth_ptr = NULL;
1311 return FALSE;
1313 out_desc.ulVersion = 0;
1314 out_desc.cBuffers = 1;
1315 out_desc.pBuffers = &out;
1317 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1318 first ? request->connect->servername : NULL, flags, 0,
1319 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1320 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1321 heap_free( in.pvBuffer );
1322 if (status == SEC_E_OK)
1324 heap_free( authinfo->data );
1325 authinfo->data = out.pvBuffer;
1326 authinfo->data_len = out.cbBuffer;
1327 authinfo->finished = TRUE;
1328 TRACE("sending last auth packet\n");
1330 else if (status == SEC_I_CONTINUE_NEEDED)
1332 heap_free( authinfo->data );
1333 authinfo->data = out.pvBuffer;
1334 authinfo->data_len = out.cbBuffer;
1335 TRACE("sending next auth packet\n");
1337 else
1339 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1340 heap_free( out.pvBuffer );
1341 destroy_authinfo( authinfo );
1342 *auth_ptr = NULL;
1343 return FALSE;
1345 break;
1347 default:
1348 ERR("invalid scheme %u\n", scheme);
1349 return FALSE;
1351 *auth_ptr = authinfo;
1353 len_scheme = auth_schemes[authinfo->scheme].len;
1354 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1355 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1357 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1358 auth_reply[len_scheme] = ' ';
1359 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1361 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1362 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1363 heap_free( auth_reply );
1364 return ret;
1367 static LPWSTR concatenate_string_list( LPCWSTR *list, int len )
1369 LPCWSTR *t;
1370 LPWSTR str;
1372 for( t = list; *t ; t++ )
1373 len += strlenW( *t );
1374 len++;
1376 str = heap_alloc( len * sizeof(WCHAR) );
1377 if (!str) return NULL;
1378 *str = 0;
1380 for( t = list; *t ; t++ )
1381 strcatW( str, *t );
1383 return str;
1386 static LPWSTR build_header_request_string( request_t *request, LPCWSTR verb,
1387 LPCWSTR path, LPCWSTR version )
1389 static const WCHAR crlf[] = {'\r','\n',0};
1390 static const WCHAR space[] = { ' ',0 };
1391 static const WCHAR colon[] = { ':',' ',0 };
1392 static const WCHAR twocrlf[] = {'\r','\n','\r','\n', 0};
1393 LPWSTR requestString;
1394 DWORD len, n;
1395 LPCWSTR *req;
1396 UINT i;
1397 LPWSTR p;
1399 /* allocate space for an array of all the string pointers to be added */
1400 len = (request->num_headers) * 4 + 10;
1401 req = heap_alloc( len * sizeof(LPCWSTR) );
1402 if (!req) return NULL;
1404 /* add the verb, path and HTTP version string */
1405 n = 0;
1406 req[n++] = verb;
1407 req[n++] = space;
1408 req[n++] = path;
1409 req[n++] = space;
1410 req[n++] = version;
1412 /* Append custom request headers */
1413 for (i = 0; i < request->num_headers; i++)
1415 if (request->headers[i].is_request)
1417 req[n++] = crlf;
1418 req[n++] = request->headers[i].field;
1419 req[n++] = colon;
1420 req[n++] = request->headers[i].value;
1422 TRACE("Adding custom header %s (%s)\n",
1423 debugstr_w(request->headers[i].field),
1424 debugstr_w(request->headers[i].value));
1428 if( n >= len )
1429 ERR("oops. buffer overrun\n");
1431 req[n] = NULL;
1432 requestString = concatenate_string_list( req, 4 );
1433 heap_free( req );
1434 if (!requestString) return NULL;
1437 * Set (header) termination string for request
1438 * Make sure there are exactly two new lines at the end of the request
1440 p = &requestString[strlenW(requestString)-1];
1441 while ( (*p == '\n') || (*p == '\r') )
1442 p--;
1443 strcpyW( p+1, twocrlf );
1445 return requestString;
1448 static BOOL read_reply( request_t *request );
1450 static BOOL secure_proxy_connect( request_t *request )
1452 static const WCHAR verbConnect[] = {'C','O','N','N','E','C','T',0};
1453 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1454 BOOL ret = FALSE;
1455 LPWSTR path;
1456 connect_t *connect = request->connect;
1458 path = heap_alloc( (strlenW( connect->hostname ) + 13) * sizeof(WCHAR) );
1459 if (path)
1461 LPWSTR requestString;
1463 sprintfW( path, fmt, connect->hostname, connect->hostport );
1464 requestString = build_header_request_string( request, verbConnect,
1465 path, http1_1 );
1466 heap_free( path );
1467 if (requestString)
1469 LPSTR req_ascii = strdupWA( requestString );
1471 heap_free( requestString );
1472 if (req_ascii)
1474 int len = strlen( req_ascii ), bytes_sent;
1476 ret = netconn_send( request->netconn, req_ascii, len, &bytes_sent );
1477 heap_free( req_ascii );
1478 if (ret)
1479 ret = read_reply( request );
1483 return ret;
1486 #ifndef INET6_ADDRSTRLEN
1487 #define INET6_ADDRSTRLEN 46
1488 #endif
1490 static WCHAR *addr_to_str( struct sockaddr_storage *addr )
1492 char buf[INET6_ADDRSTRLEN];
1493 void *src;
1495 switch (addr->ss_family)
1497 case AF_INET:
1498 src = &((struct sockaddr_in *)addr)->sin_addr;
1499 break;
1500 case AF_INET6:
1501 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
1502 break;
1503 default:
1504 WARN("unsupported address family %d\n", addr->ss_family);
1505 return NULL;
1507 if (!inet_ntop( addr->ss_family, src, buf, sizeof(buf) )) return NULL;
1508 return strdupAW( buf );
1511 static CRITICAL_SECTION connection_pool_cs;
1512 static CRITICAL_SECTION_DEBUG connection_pool_debug =
1514 0, 0, &connection_pool_cs,
1515 { &connection_pool_debug.ProcessLocksList, &connection_pool_debug.ProcessLocksList },
1516 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
1518 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
1520 static struct list connection_pool = LIST_INIT( connection_pool );
1522 void release_host( hostdata_t *host )
1524 LONG ref;
1526 EnterCriticalSection( &connection_pool_cs );
1527 if (!(ref = --host->ref)) list_remove( &host->entry );
1528 LeaveCriticalSection( &connection_pool_cs );
1529 if (ref) return;
1531 assert( list_empty( &host->connections ) );
1532 heap_free( host->hostname );
1533 heap_free( host );
1536 static BOOL connection_collector_running;
1538 static DWORD WINAPI connection_collector(void *arg)
1540 unsigned int remaining_connections;
1541 netconn_t *netconn, *next_netconn;
1542 hostdata_t *host, *next_host;
1543 ULONGLONG now;
1547 /* FIXME: Use more sophisticated method */
1548 Sleep(5000);
1549 remaining_connections = 0;
1550 now = GetTickCount64();
1552 EnterCriticalSection(&connection_pool_cs);
1554 LIST_FOR_EACH_ENTRY_SAFE(host, next_host, &connection_pool, hostdata_t, entry)
1556 LIST_FOR_EACH_ENTRY_SAFE(netconn, next_netconn, &host->connections, netconn_t, entry)
1558 if (netconn->keep_until < now)
1560 TRACE("freeing %p\n", netconn);
1561 list_remove(&netconn->entry);
1562 netconn_close(netconn);
1564 else
1566 remaining_connections++;
1571 if (!remaining_connections) connection_collector_running = FALSE;
1573 LeaveCriticalSection(&connection_pool_cs);
1574 } while(remaining_connections);
1576 FreeLibraryAndExitThread( winhttp_instance, 0 );
1579 static void cache_connection( netconn_t *netconn )
1581 TRACE( "caching connection %p\n", netconn );
1583 EnterCriticalSection( &connection_pool_cs );
1585 netconn->keep_until = GetTickCount64() + DEFAULT_KEEP_ALIVE_TIMEOUT;
1586 list_add_head( &netconn->host->connections, &netconn->entry );
1588 if (!connection_collector_running)
1590 HMODULE module;
1591 HANDLE thread;
1593 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)winhttp_instance, &module );
1595 thread = CreateThread(NULL, 0, connection_collector, NULL, 0, NULL);
1596 if (thread)
1598 CloseHandle( thread );
1599 connection_collector_running = TRUE;
1601 else
1603 FreeLibrary( winhttp_instance );
1607 LeaveCriticalSection( &connection_pool_cs );
1610 static DWORD map_secure_protocols( DWORD mask )
1612 DWORD ret = 0;
1613 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL2) ret |= SP_PROT_SSL2_CLIENT;
1614 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL3) ret |= SP_PROT_SSL3_CLIENT;
1615 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1) ret |= SP_PROT_TLS1_CLIENT;
1616 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1) ret |= SP_PROT_TLS1_1_CLIENT;
1617 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2) ret |= SP_PROT_TLS1_2_CLIENT;
1618 return ret;
1621 static BOOL ensure_cred_handle( session_t *session )
1623 SCHANNEL_CRED cred;
1624 SECURITY_STATUS status;
1626 if (session->cred_handle_initialized) return TRUE;
1628 memset( &cred, 0, sizeof(cred) );
1629 cred.dwVersion = SCHANNEL_CRED_VERSION;
1630 cred.grbitEnabledProtocols = map_secure_protocols( session->secure_protocols );
1631 if ((status = AcquireCredentialsHandleW( NULL, (WCHAR *)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
1632 NULL, NULL, &session->cred_handle, NULL )) != SEC_E_OK)
1634 WARN( "AcquireCredentialsHandleW failed: 0x%08x\n", status );
1635 return FALSE;
1637 session->cred_handle_initialized = TRUE;
1638 return TRUE;
1641 static BOOL open_connection( request_t *request )
1643 BOOL is_secure = request->hdr.flags & WINHTTP_FLAG_SECURE;
1644 hostdata_t *host = NULL, *iter;
1645 netconn_t *netconn = NULL;
1646 connect_t *connect;
1647 WCHAR *addressW = NULL;
1648 INTERNET_PORT port;
1649 DWORD len;
1651 if (request->netconn) goto done;
1653 connect = request->connect;
1654 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1656 EnterCriticalSection( &connection_pool_cs );
1658 LIST_FOR_EACH_ENTRY( iter, &connection_pool, hostdata_t, entry )
1660 if (iter->port == port && !strcmpW( connect->servername, iter->hostname ) && !is_secure == !iter->secure)
1662 host = iter;
1663 host->ref++;
1664 break;
1668 if (!host)
1670 if ((host = heap_alloc( sizeof(*host) )))
1672 host->ref = 1;
1673 host->secure = is_secure;
1674 host->port = port;
1675 list_init( &host->connections );
1676 if ((host->hostname = strdupW( connect->servername )))
1678 list_add_head( &connection_pool, &host->entry );
1680 else
1682 heap_free( host );
1683 host = NULL;
1688 LeaveCriticalSection( &connection_pool_cs );
1690 if (!host) return FALSE;
1692 for (;;)
1694 EnterCriticalSection( &connection_pool_cs );
1695 if (!list_empty( &host->connections ))
1697 netconn = LIST_ENTRY( list_head( &host->connections ), netconn_t, entry );
1698 list_remove( &netconn->entry );
1700 LeaveCriticalSection( &connection_pool_cs );
1701 if (!netconn) break;
1703 if (netconn_is_alive( netconn )) break;
1704 TRACE("connection %p no longer alive, closing\n", netconn);
1705 netconn_close( netconn );
1706 netconn = NULL;
1709 if (!connect->resolved && netconn)
1711 connect->sockaddr = netconn->sockaddr;
1712 connect->resolved = TRUE;
1715 if (!connect->resolved)
1717 len = strlenW( host->hostname ) + 1;
1718 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, host->hostname, len );
1720 if (!netconn_resolve( host->hostname, port, &connect->sockaddr, request->resolve_timeout ))
1722 release_host( host );
1723 return FALSE;
1725 connect->resolved = TRUE;
1727 if (!(addressW = addr_to_str( &connect->sockaddr )))
1729 release_host( host );
1730 return FALSE;
1732 len = strlenW( addressW ) + 1;
1733 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
1736 if (!netconn)
1738 if (!addressW && !(addressW = addr_to_str( &connect->sockaddr )))
1740 release_host( host );
1741 return FALSE;
1744 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
1746 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
1748 if (!(netconn = netconn_create( host, &connect->sockaddr, request->connect_timeout )))
1750 heap_free( addressW );
1751 release_host( host );
1752 return FALSE;
1754 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1755 netconn_set_timeout( netconn, FALSE, request->recv_timeout );
1756 if (is_secure)
1758 if (connect->session->proxy_server &&
1759 strcmpiW( connect->hostname, connect->servername ))
1761 if (!secure_proxy_connect( request ))
1763 heap_free( addressW );
1764 netconn_close( netconn );
1765 return FALSE;
1768 if (!ensure_cred_handle( connect->session ) ||
1769 !netconn_secure_connect( netconn, connect->hostname, request->security_flags,
1770 &connect->session->cred_handle ))
1772 heap_free( addressW );
1773 netconn_close( netconn );
1774 return FALSE;
1778 request->netconn = netconn;
1779 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
1781 else
1783 TRACE("using connection %p\n", netconn);
1785 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1786 netconn_set_timeout( netconn, FALSE, request->recv_timeout );
1787 request->netconn = netconn;
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);
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_url;
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_url ))) 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_url, 0, &uc )) /* assume relative redirect */
2535 WCHAR *path, *p;
2537 if (location[0] == '/')
2539 len = strlenW( location );
2540 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2541 strcpyW( path, location );
2543 else
2545 if ((p = strrchrW( request->path, '/' ))) *p = 0;
2546 len = strlenW( request->path ) + 1 + strlenW( location );
2547 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2548 strcpyW( path, request->path );
2549 strcatW( path, slashW );
2550 strcatW( path, location );
2552 heap_free( request->path );
2553 request->path = path;
2555 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 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_url + 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 = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2602 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2603 strcpyW( request->path, uc.lpszUrlPath );
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;