winhttp: Use the thread pool for COM object requests.
[wine.git] / dlls / winhttp / request.c
bloba081b608ab9a54048d58066eadfa7ab6dba9a83d
1 /*
2 * Copyright 2004 Mike McCormack for CodeWeavers
3 * Copyright 2006 Rob Shearman for CodeWeavers
4 * Copyright 2008, 2011 Hans Leidekker for CodeWeavers
5 * Copyright 2009 Juan Lang
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #define COBJMACROS
23 #include "config.h"
24 #include "ws2tcpip.h"
25 #include <stdarg.h>
26 #include <assert.h>
28 #include "windef.h"
29 #include "winbase.h"
30 #include "ole2.h"
31 #include "initguid.h"
32 #include "httprequest.h"
33 #include "httprequestid.h"
34 #include "schannel.h"
35 #include "winhttp.h"
37 #include "wine/debug.h"
38 #include "winhttp_private.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
42 #define DEFAULT_KEEP_ALIVE_TIMEOUT 30000
44 static const WCHAR attr_accept[] = {'A','c','c','e','p','t',0};
45 static const WCHAR attr_accept_charset[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
46 static const WCHAR attr_accept_encoding[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
47 static const WCHAR attr_accept_language[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
48 static const WCHAR attr_accept_ranges[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
49 static const WCHAR attr_age[] = {'A','g','e',0};
50 static const WCHAR attr_allow[] = {'A','l','l','o','w',0};
51 static const WCHAR attr_authorization[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
52 static const WCHAR attr_cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
53 static const WCHAR attr_connection[] = {'C','o','n','n','e','c','t','i','o','n',0};
54 static const WCHAR attr_content_base[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
55 static const WCHAR attr_content_encoding[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
56 static const WCHAR attr_content_id[] = {'C','o','n','t','e','n','t','-','I','D',0};
57 static const WCHAR attr_content_language[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
58 static const WCHAR attr_content_length[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
59 static const WCHAR attr_content_location[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
60 static const WCHAR attr_content_md5[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
61 static const WCHAR attr_content_range[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
62 static const WCHAR attr_content_transfer_encoding[] = {'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
63 static const WCHAR attr_content_type[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
64 static const WCHAR attr_cookie[] = {'C','o','o','k','i','e',0};
65 static const WCHAR attr_date[] = {'D','a','t','e',0};
66 static const WCHAR attr_from[] = {'F','r','o','m',0};
67 static const WCHAR attr_etag[] = {'E','T','a','g',0};
68 static const WCHAR attr_expect[] = {'E','x','p','e','c','t',0};
69 static const WCHAR attr_expires[] = {'E','x','p','i','r','e','s',0};
70 static const WCHAR attr_host[] = {'H','o','s','t',0};
71 static const WCHAR attr_if_match[] = {'I','f','-','M','a','t','c','h',0};
72 static const WCHAR attr_if_modified_since[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
73 static const WCHAR attr_if_none_match[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
74 static const WCHAR attr_if_range[] = {'I','f','-','R','a','n','g','e',0};
75 static const WCHAR attr_if_unmodified_since[] = {'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
76 static const WCHAR attr_last_modified[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
77 static const WCHAR attr_location[] = {'L','o','c','a','t','i','o','n',0};
78 static const WCHAR attr_max_forwards[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
79 static const WCHAR attr_mime_version[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
80 static const WCHAR attr_pragma[] = {'P','r','a','g','m','a',0};
81 static const WCHAR attr_proxy_authenticate[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
82 static const WCHAR attr_proxy_authorization[] = {'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0};
83 static const WCHAR attr_proxy_connection[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
84 static const WCHAR attr_public[] = {'P','u','b','l','i','c',0};
85 static const WCHAR attr_range[] = {'R','a','n','g','e',0};
86 static const WCHAR attr_referer[] = {'R','e','f','e','r','e','r',0};
87 static const WCHAR attr_retry_after[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
88 static const WCHAR attr_server[] = {'S','e','r','v','e','r',0};
89 static const WCHAR attr_set_cookie[] = {'S','e','t','-','C','o','o','k','i','e',0};
90 static const WCHAR attr_status[] = {'S','t','a','t','u','s',0};
91 static const WCHAR attr_transfer_encoding[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
92 static const WCHAR attr_unless_modified_since[] = {'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
93 static const WCHAR attr_upgrade[] = {'U','p','g','r','a','d','e',0};
94 static const WCHAR attr_uri[] = {'U','R','I',0};
95 static const WCHAR attr_user_agent[] = {'U','s','e','r','-','A','g','e','n','t',0};
96 static const WCHAR attr_vary[] = {'V','a','r','y',0};
97 static const WCHAR attr_via[] = {'V','i','a',0};
98 static const WCHAR attr_warning[] = {'W','a','r','n','i','n','g',0};
99 static const WCHAR attr_www_authenticate[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
101 static const WCHAR *attribute_table[] =
103 attr_mime_version, /* WINHTTP_QUERY_MIME_VERSION = 0 */
104 attr_content_type, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
105 attr_content_transfer_encoding, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
106 attr_content_id, /* WINHTTP_QUERY_CONTENT_ID = 3 */
107 NULL, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
108 attr_content_length, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
109 attr_content_language, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
110 attr_allow, /* WINHTTP_QUERY_ALLOW = 7 */
111 attr_public, /* WINHTTP_QUERY_PUBLIC = 8 */
112 attr_date, /* WINHTTP_QUERY_DATE = 9 */
113 attr_expires, /* WINHTTP_QUERY_EXPIRES = 10 */
114 attr_last_modified, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
115 NULL, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
116 attr_uri, /* WINHTTP_QUERY_URI = 13 */
117 attr_from, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
118 NULL, /* WINHTTP_QUERY_COST = 15 */
119 NULL, /* WINHTTP_QUERY_LINK = 16 */
120 attr_pragma, /* WINHTTP_QUERY_PRAGMA = 17 */
121 NULL, /* WINHTTP_QUERY_VERSION = 18 */
122 attr_status, /* WINHTTP_QUERY_STATUS_CODE = 19 */
123 NULL, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
124 NULL, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
125 NULL, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
126 attr_connection, /* WINHTTP_QUERY_CONNECTION = 23 */
127 attr_accept, /* WINHTTP_QUERY_ACCEPT = 24 */
128 attr_accept_charset, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
129 attr_accept_encoding, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
130 attr_accept_language, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
131 attr_authorization, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
132 attr_content_encoding, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
133 NULL, /* WINHTTP_QUERY_FORWARDED = 30 */
134 NULL, /* WINHTTP_QUERY_FROM = 31 */
135 attr_if_modified_since, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
136 attr_location, /* WINHTTP_QUERY_LOCATION = 33 */
137 NULL, /* WINHTTP_QUERY_ORIG_URI = 34 */
138 attr_referer, /* WINHTTP_QUERY_REFERER = 35 */
139 attr_retry_after, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
140 attr_server, /* WINHTTP_QUERY_SERVER = 37 */
141 NULL, /* WINHTTP_TITLE = 38 */
142 attr_user_agent, /* WINHTTP_QUERY_USER_AGENT = 39 */
143 attr_www_authenticate, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
144 attr_proxy_authenticate, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
145 attr_accept_ranges, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
146 attr_set_cookie, /* WINHTTP_QUERY_SET_COOKIE = 43 */
147 attr_cookie, /* WINHTTP_QUERY_COOKIE = 44 */
148 NULL, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
149 NULL, /* WINHTTP_QUERY_REFRESH = 46 */
150 NULL, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
151 attr_age, /* WINHTTP_QUERY_AGE = 48 */
152 attr_cache_control, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
153 attr_content_base, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
154 attr_content_location, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
155 attr_content_md5, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
156 attr_content_range, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
157 attr_etag, /* WINHTTP_QUERY_ETAG = 54 */
158 attr_host, /* WINHTTP_QUERY_HOST = 55 */
159 attr_if_match, /* WINHTTP_QUERY_IF_MATCH = 56 */
160 attr_if_none_match, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
161 attr_if_range, /* WINHTTP_QUERY_IF_RANGE = 58 */
162 attr_if_unmodified_since, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
163 attr_max_forwards, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
164 attr_proxy_authorization, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
165 attr_range, /* WINHTTP_QUERY_RANGE = 62 */
166 attr_transfer_encoding, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
167 attr_upgrade, /* WINHTTP_QUERY_UPGRADE = 64 */
168 attr_vary, /* WINHTTP_QUERY_VARY = 65 */
169 attr_via, /* WINHTTP_QUERY_VIA = 66 */
170 attr_warning, /* WINHTTP_QUERY_WARNING = 67 */
171 attr_expect, /* WINHTTP_QUERY_EXPECT = 68 */
172 attr_proxy_connection, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
173 attr_unless_modified_since, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
174 NULL, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
175 NULL, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
176 NULL, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
177 NULL /* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
180 static struct task_header *dequeue_task( struct request *request )
182 struct task_header *task;
184 EnterCriticalSection( &request->task_cs );
185 TRACE("%u tasks queued\n", list_count( &request->task_queue ));
186 task = LIST_ENTRY( list_head( &request->task_queue ), struct task_header, entry );
187 if (task) list_remove( &task->entry );
188 LeaveCriticalSection( &request->task_cs );
190 TRACE("returning task %p\n", task);
191 return task;
194 static void CALLBACK task_proc( TP_CALLBACK_INSTANCE *instance, void *ctx )
196 struct request *request = ctx;
197 HANDLE handles[2];
199 handles[0] = request->task_wait;
200 handles[1] = request->task_cancel;
201 for (;;)
203 DWORD err = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
204 switch (err)
206 case WAIT_OBJECT_0:
208 struct task_header *task;
209 while ((task = dequeue_task( request )))
211 task->proc( task );
212 release_object( &task->request->hdr );
213 heap_free( task );
215 break;
217 case WAIT_OBJECT_0 + 1:
218 TRACE("exiting\n");
219 CloseHandle( request->task_cancel );
220 CloseHandle( request->task_wait );
221 request->task_cs.DebugInfo->Spare[0] = 0;
222 DeleteCriticalSection( &request->task_cs );
223 request->hdr.vtbl->destroy( &request->hdr );
224 return;
226 default:
227 ERR("wait failed %u (%u)\n", err, GetLastError());
228 break;
233 static BOOL queue_task( struct task_header *task )
235 struct request *request = task->request;
237 if (!request->task_wait)
239 if (!(request->task_wait = CreateEventW( NULL, FALSE, FALSE, NULL ))) return FALSE;
240 if (!(request->task_cancel = CreateEventW( NULL, FALSE, FALSE, NULL )))
242 CloseHandle( request->task_wait );
243 request->task_wait = NULL;
244 return FALSE;
246 if (!TrySubmitThreadpoolCallback( task_proc, request, NULL ))
248 CloseHandle( request->task_wait );
249 request->task_wait = NULL;
250 CloseHandle( request->task_cancel );
251 request->task_cancel = NULL;
252 return FALSE;
254 request->task_proc_running = TRUE;
255 InitializeCriticalSection( &request->task_cs );
256 request->task_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": request.task_cs");
259 EnterCriticalSection( &request->task_cs );
260 TRACE("queueing task %p\n", task );
261 list_add_tail( &request->task_queue, &task->entry );
262 LeaveCriticalSection( &request->task_cs );
264 SetEvent( request->task_wait );
265 return TRUE;
268 static void free_header( struct header *header )
270 heap_free( header->field );
271 heap_free( header->value );
272 heap_free( header );
275 static BOOL valid_token_char( WCHAR c )
277 if (c < 32 || c == 127) return FALSE;
278 switch (c)
280 case '(': case ')':
281 case '<': case '>':
282 case '@': case ',':
283 case ';': case ':':
284 case '\\': case '\"':
285 case '/': case '[':
286 case ']': case '?':
287 case '=': case '{':
288 case '}': case ' ':
289 case '\t':
290 return FALSE;
291 default:
292 return TRUE;
296 static struct header *parse_header( const WCHAR *string )
298 const WCHAR *p, *q;
299 struct header *header;
300 int len;
302 p = string;
303 if (!(q = strchrW( p, ':' )))
305 WARN("no ':' in line %s\n", debugstr_w(string));
306 return NULL;
308 if (q == string)
310 WARN("empty field name in line %s\n", debugstr_w(string));
311 return NULL;
313 while (*p != ':')
315 if (!valid_token_char( *p ))
317 WARN("invalid character in field name %s\n", debugstr_w(string));
318 return NULL;
320 p++;
322 len = q - string;
323 if (!(header = heap_alloc_zero( sizeof(struct header) ))) return NULL;
324 if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
326 heap_free( header );
327 return NULL;
329 memcpy( header->field, string, len * sizeof(WCHAR) );
330 header->field[len] = 0;
332 q++; /* skip past colon */
333 while (*q == ' ') q++;
334 len = strlenW( q );
336 if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
338 free_header( header );
339 return NULL;
341 memcpy( header->value, q, len * sizeof(WCHAR) );
342 header->value[len] = 0;
344 return header;
347 static int get_header_index( struct request *request, const WCHAR *field, int requested_index, BOOL request_only )
349 int index;
351 TRACE("%s\n", debugstr_w(field));
353 for (index = 0; index < request->num_headers; index++)
355 if (strcmpiW( request->headers[index].field, field )) continue;
356 if (request_only && !request->headers[index].is_request) continue;
357 if (!request_only && request->headers[index].is_request) continue;
359 if (!requested_index) break;
360 requested_index--;
362 if (index >= request->num_headers) index = -1;
363 TRACE("returning %d\n", index);
364 return index;
367 static BOOL insert_header( struct request *request, struct header *header )
369 DWORD count = request->num_headers + 1;
370 struct header *hdrs;
372 if (request->headers)
373 hdrs = heap_realloc_zero( request->headers, sizeof(struct header) * count );
374 else
375 hdrs = heap_alloc_zero( sizeof(struct header) );
376 if (!hdrs) return FALSE;
378 request->headers = hdrs;
379 request->headers[count - 1].field = strdupW( header->field );
380 request->headers[count - 1].value = strdupW( header->value );
381 request->headers[count - 1].is_request = header->is_request;
382 request->num_headers = count;
383 return TRUE;
386 static BOOL delete_header( struct request *request, DWORD index )
388 if (!request->num_headers) return FALSE;
389 if (index >= request->num_headers) return FALSE;
390 request->num_headers--;
392 heap_free( request->headers[index].field );
393 heap_free( request->headers[index].value );
395 memmove( &request->headers[index], &request->headers[index + 1],
396 (request->num_headers - index) * sizeof(struct header) );
397 memset( &request->headers[request->num_headers], 0, sizeof(struct header) );
398 return TRUE;
401 static BOOL process_header( struct request *request, const WCHAR *field, const WCHAR *value, DWORD flags,
402 BOOL request_only )
404 int index;
405 struct header hdr;
407 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
409 if ((index = get_header_index( request, field, 0, request_only )) >= 0)
411 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
414 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
416 if (index >= 0)
418 delete_header( request, index );
419 if (!value || !value[0]) return TRUE;
421 else if (!(flags & WINHTTP_ADDREQ_FLAG_ADD))
423 SetLastError( ERROR_WINHTTP_HEADER_NOT_FOUND );
424 return FALSE;
427 hdr.field = (LPWSTR)field;
428 hdr.value = (LPWSTR)value;
429 hdr.is_request = request_only;
430 return insert_header( request, &hdr );
432 else if (value)
435 if ((flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON)) &&
436 index >= 0)
438 WCHAR *tmp;
439 int len, len_orig, len_value;
440 struct header *header = &request->headers[index];
442 len_orig = strlenW( header->value );
443 len_value = strlenW( value );
445 len = len_orig + len_value + 2;
446 if (!(tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) ))) return FALSE;
447 header->value = tmp;
448 header->value[len_orig++] = (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) ? ',' : ';';
449 header->value[len_orig++] = ' ';
451 memcpy( &header->value[len_orig], value, len_value * sizeof(WCHAR) );
452 header->value[len] = 0;
453 return TRUE;
455 else
457 hdr.field = (LPWSTR)field;
458 hdr.value = (LPWSTR)value;
459 hdr.is_request = request_only;
460 return insert_header( request, &hdr );
464 return TRUE;
467 BOOL add_request_headers( struct request *request, const WCHAR *headers, DWORD len, DWORD flags )
469 BOOL ret = FALSE;
470 WCHAR *buffer, *p, *q;
471 struct header *header;
473 if (len == ~0u) len = strlenW( headers );
474 if (!len) return TRUE;
475 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
476 memcpy( buffer, headers, len * sizeof(WCHAR) );
477 buffer[len] = 0;
479 p = buffer;
482 q = p;
483 while (*q)
485 if (q[0] == '\n' && q[1] == '\r')
487 q[0] = '\r';
488 q[1] = '\n';
490 if (q[0] == '\r' && q[1] == '\n') break;
491 q++;
493 if (!*p) break;
494 if (*q == '\r')
496 *q = 0;
497 q += 2; /* jump over \r\n */
499 if ((header = parse_header( p )))
501 ret = process_header( request, header->field, header->value, flags, TRUE );
502 free_header( header );
504 p = q;
505 } while (ret);
507 heap_free( buffer );
508 return ret;
511 /***********************************************************************
512 * WinHttpAddRequestHeaders (winhttp.@)
514 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
516 BOOL ret;
517 struct request *request;
519 TRACE("%p, %s, %u, 0x%08x\n", hrequest, debugstr_wn(headers, len), len, flags);
521 if (!headers || !len)
523 SetLastError( ERROR_INVALID_PARAMETER );
524 return FALSE;
526 if (!(request = (struct request *)grab_object( hrequest )))
528 SetLastError( ERROR_INVALID_HANDLE );
529 return FALSE;
531 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
533 release_object( &request->hdr );
534 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
535 return FALSE;
538 ret = add_request_headers( request, headers, len, flags );
540 release_object( &request->hdr );
541 if (ret) SetLastError( ERROR_SUCCESS );
542 return ret;
545 static WCHAR *build_absolute_request_path( struct request *request, const WCHAR **path )
547 static const WCHAR http[] = {'h','t','t','p',0};
548 static const WCHAR https[] = {'h','t','t','p','s',0};
549 static const WCHAR fmt[] = {'%','s',':','/','/','%','s',0};
550 const WCHAR *scheme;
551 WCHAR *ret;
552 int len;
554 scheme = (request->netconn ? request->netconn->secure : (request->hdr.flags & WINHTTP_FLAG_SECURE)) ? https : http;
556 len = strlenW( scheme ) + strlenW( request->connect->hostname ) + 4; /* '://' + nul */
557 if (request->connect->hostport) len += 6; /* ':' between host and port, up to 5 for port */
559 len += strlenW( request->path );
560 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
562 len = sprintfW( ret, fmt, scheme, request->connect->hostname );
563 if (request->connect->hostport)
565 static const WCHAR port_fmt[] = {':','%','u',0};
566 len += sprintfW( ret + len, port_fmt, request->connect->hostport );
568 strcpyW( ret + len, request->path );
569 if (path) *path = ret + len;
572 return ret;
575 static WCHAR *build_request_string( struct request *request )
577 static const WCHAR spaceW[] = {' ',0}, crlfW[] = {'\r','\n',0}, colonW[] = {':',' ',0};
578 static const WCHAR twocrlfW[] = {'\r','\n','\r','\n',0};
579 WCHAR *path, *ret;
580 unsigned int i, len;
582 if (!strcmpiW( request->connect->hostname, request->connect->servername )) path = request->path;
583 else if (!(path = build_absolute_request_path( request, NULL ))) return NULL;
585 len = strlenW( request->verb ) + 1 /* ' ' */;
586 len += strlenW( path ) + 1 /* ' ' */;
587 len += strlenW( request->version );
589 for (i = 0; i < request->num_headers; i++)
591 if (request->headers[i].is_request)
592 len += strlenW( request->headers[i].field ) + strlenW( request->headers[i].value ) + 4; /* '\r\n: ' */
594 len += 4; /* '\r\n\r\n' */
596 if ((ret = heap_alloc( (len + 1) * sizeof(WCHAR) )))
598 strcpyW( ret, request->verb );
599 strcatW( ret, spaceW );
600 strcatW( ret, path );
601 strcatW( ret, spaceW );
602 strcatW( ret, request->version );
604 for (i = 0; i < request->num_headers; i++)
606 if (request->headers[i].is_request)
608 strcatW( ret, crlfW );
609 strcatW( ret, request->headers[i].field );
610 strcatW( ret, colonW );
611 strcatW( ret, request->headers[i].value );
614 strcatW( ret, twocrlfW );
617 if (path != request->path) heap_free( path );
618 return ret;
621 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
623 static BOOL query_headers( struct request *request, DWORD level, const WCHAR *name, void *buffer, DWORD *buflen,
624 DWORD *index )
626 struct header *header = NULL;
627 BOOL request_only, ret = FALSE;
628 int requested_index, header_index = -1;
629 DWORD attr, len;
631 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
632 requested_index = index ? *index : 0;
634 attr = level & ~QUERY_MODIFIER_MASK;
635 switch (attr)
637 case WINHTTP_QUERY_CUSTOM:
639 header_index = get_header_index( request, name, requested_index, request_only );
640 break;
642 case WINHTTP_QUERY_RAW_HEADERS:
644 WCHAR *headers, *p, *q;
646 if (request_only)
647 headers = build_request_string( request );
648 else
649 headers = request->raw_headers;
651 if (!(p = headers)) return FALSE;
652 for (len = 0; *p; p++) if (*p != '\r') len++;
654 if (!buffer || len * sizeof(WCHAR) > *buflen)
655 SetLastError( ERROR_INSUFFICIENT_BUFFER );
656 else
658 for (p = headers, q = buffer; *p; p++, q++)
660 if (*p != '\r') *q = *p;
661 else
663 *q = 0;
664 p++; /* skip '\n' */
667 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
668 if (len) len--;
669 ret = TRUE;
671 *buflen = len * sizeof(WCHAR);
672 if (request_only) heap_free( headers );
673 return ret;
675 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
677 WCHAR *headers;
679 if (request_only)
680 headers = build_request_string( request );
681 else
682 headers = request->raw_headers;
684 if (!headers) return FALSE;
685 len = strlenW( headers ) * sizeof(WCHAR);
686 if (!buffer || len + sizeof(WCHAR) > *buflen)
688 len += sizeof(WCHAR);
689 SetLastError( ERROR_INSUFFICIENT_BUFFER );
691 else
693 memcpy( buffer, headers, len + sizeof(WCHAR) );
694 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
695 ret = TRUE;
697 *buflen = len;
698 if (request_only) heap_free( headers );
699 return ret;
701 case WINHTTP_QUERY_VERSION:
702 len = strlenW( request->version ) * sizeof(WCHAR);
703 if (!buffer || len + sizeof(WCHAR) > *buflen)
705 len += sizeof(WCHAR);
706 SetLastError( ERROR_INSUFFICIENT_BUFFER );
708 else
710 strcpyW( buffer, request->version );
711 TRACE("returning string: %s\n", debugstr_w(buffer));
712 ret = TRUE;
714 *buflen = len;
715 return ret;
717 case WINHTTP_QUERY_STATUS_TEXT:
718 len = strlenW( request->status_text ) * sizeof(WCHAR);
719 if (!buffer || len + sizeof(WCHAR) > *buflen)
721 len += sizeof(WCHAR);
722 SetLastError( ERROR_INSUFFICIENT_BUFFER );
724 else
726 strcpyW( buffer, request->status_text );
727 TRACE("returning string: %s\n", debugstr_w(buffer));
728 ret = TRUE;
730 *buflen = len;
731 return ret;
733 default:
734 if (attr >= ARRAY_SIZE(attribute_table) || !attribute_table[attr])
736 FIXME("attribute %u not implemented\n", attr);
737 return FALSE;
739 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
740 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
741 break;
744 if (header_index >= 0)
746 header = &request->headers[header_index];
748 if (!header || (request_only && !header->is_request))
750 SetLastError( ERROR_WINHTTP_HEADER_NOT_FOUND );
751 return FALSE;
753 if (level & WINHTTP_QUERY_FLAG_NUMBER)
755 if (!buffer || sizeof(int) > *buflen)
757 SetLastError( ERROR_INSUFFICIENT_BUFFER );
759 else
761 int *number = buffer;
762 *number = atoiW( header->value );
763 TRACE("returning number: %d\n", *number);
764 ret = TRUE;
766 *buflen = sizeof(int);
768 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
770 SYSTEMTIME *st = buffer;
771 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
773 SetLastError( ERROR_INSUFFICIENT_BUFFER );
775 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
777 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
778 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
779 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
781 *buflen = sizeof(SYSTEMTIME);
783 else if (header->value)
785 len = strlenW( header->value ) * sizeof(WCHAR);
786 if (!buffer || len + sizeof(WCHAR) > *buflen)
788 len += sizeof(WCHAR);
789 SetLastError( ERROR_INSUFFICIENT_BUFFER );
791 else
793 strcpyW( buffer, header->value );
794 TRACE("returning string: %s\n", debugstr_w(buffer));
795 ret = TRUE;
797 *buflen = len;
799 if (ret && index) *index += 1;
800 return ret;
803 /***********************************************************************
804 * WinHttpQueryHeaders (winhttp.@)
806 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
808 BOOL ret;
809 struct request *request;
811 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
813 if (!(request = (struct request *)grab_object( hrequest )))
815 SetLastError( ERROR_INVALID_HANDLE );
816 return FALSE;
818 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
820 release_object( &request->hdr );
821 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
822 return FALSE;
825 ret = query_headers( request, level, name, buffer, buflen, index );
827 release_object( &request->hdr );
828 if (ret) SetLastError( ERROR_SUCCESS );
829 return ret;
832 static const WCHAR basicW[] = {'B','a','s','i','c',0};
833 static const WCHAR ntlmW[] = {'N','T','L','M',0};
834 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
835 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
836 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
838 static const struct
840 const WCHAR *str;
841 unsigned int len;
842 DWORD scheme;
844 auth_schemes[] =
846 { basicW, ARRAY_SIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
847 { ntlmW, ARRAY_SIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
848 { passportW, ARRAY_SIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
849 { digestW, ARRAY_SIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
850 { negotiateW, ARRAY_SIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
853 static enum auth_scheme scheme_from_flag( DWORD flag )
855 int i;
857 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++) if (flag == auth_schemes[i].scheme) return i;
858 return SCHEME_INVALID;
861 static DWORD auth_scheme_from_header( WCHAR *header )
863 unsigned int i;
865 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++)
867 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
868 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
870 return 0;
873 static BOOL query_auth_schemes( struct request *request, DWORD level, DWORD *supported, DWORD *first )
875 DWORD index = 0, supported_schemes = 0, first_scheme = 0;
876 BOOL ret = FALSE;
878 for (;;)
880 WCHAR *buffer;
881 DWORD size, scheme;
883 size = 0;
884 query_headers( request, level, NULL, NULL, &size, &index );
885 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) break;
887 if (!(buffer = heap_alloc( size ))) return FALSE;
888 if (!query_headers( request, level, NULL, buffer, &size, &index ))
890 heap_free( buffer );
891 return FALSE;
893 scheme = auth_scheme_from_header( buffer );
894 heap_free( buffer );
895 if (!scheme) continue;
897 if (!first_scheme) first_scheme = scheme;
898 supported_schemes |= scheme;
900 ret = TRUE;
903 if (ret)
905 *supported = supported_schemes;
906 *first = first_scheme;
908 return ret;
911 /***********************************************************************
912 * WinHttpQueryAuthSchemes (winhttp.@)
914 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
916 BOOL ret = FALSE;
917 struct request *request;
919 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
921 if (!(request = (struct request *)grab_object( hrequest )))
923 SetLastError( ERROR_INVALID_HANDLE );
924 return FALSE;
926 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
928 release_object( &request->hdr );
929 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
930 return FALSE;
932 if (!supported || !first || !target)
934 release_object( &request->hdr );
935 SetLastError( ERROR_INVALID_PARAMETER );
936 return FALSE;
940 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
942 *target = WINHTTP_AUTH_TARGET_SERVER;
943 ret = TRUE;
945 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
947 *target = WINHTTP_AUTH_TARGET_PROXY;
948 ret = TRUE;
950 else SetLastError( ERROR_INVALID_OPERATION );
952 release_object( &request->hdr );
953 if (ret) SetLastError( ERROR_SUCCESS );
954 return ret;
957 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
959 UINT n = 0, x;
960 static const char base64enc[] =
961 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
963 while (len > 0)
965 /* first 6 bits, all from bin[0] */
966 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
967 x = (bin[0] & 3) << 4;
969 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
970 if (len == 1)
972 base64[n++] = base64enc[x];
973 base64[n++] = '=';
974 base64[n++] = '=';
975 break;
977 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
978 x = (bin[1] & 0x0f) << 2;
980 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
981 if (len == 2)
983 base64[n++] = base64enc[x];
984 base64[n++] = '=';
985 break;
987 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
989 /* last 6 bits, all from bin [2] */
990 base64[n++] = base64enc[bin[2] & 0x3f];
991 bin += 3;
992 len -= 3;
994 base64[n] = 0;
995 return n;
998 static inline char decode_char( WCHAR c )
1000 if (c >= 'A' && c <= 'Z') return c - 'A';
1001 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1002 if (c >= '0' && c <= '9') return c - '0' + 52;
1003 if (c == '+') return 62;
1004 if (c == '/') return 63;
1005 return 64;
1008 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1010 unsigned int i = 0;
1011 char c0, c1, c2, c3;
1012 const WCHAR *p = base64;
1014 while (len > 4)
1016 if ((c0 = decode_char( p[0] )) > 63) return 0;
1017 if ((c1 = decode_char( p[1] )) > 63) return 0;
1018 if ((c2 = decode_char( p[2] )) > 63) return 0;
1019 if ((c3 = decode_char( p[3] )) > 63) return 0;
1021 if (buf)
1023 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1024 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1025 buf[i + 2] = (c2 << 6) | c3;
1027 len -= 4;
1028 i += 3;
1029 p += 4;
1031 if (p[2] == '=')
1033 if ((c0 = decode_char( p[0] )) > 63) return 0;
1034 if ((c1 = decode_char( p[1] )) > 63) return 0;
1036 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1037 i++;
1039 else if (p[3] == '=')
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;
1045 if (buf)
1047 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1048 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1050 i += 2;
1052 else
1054 if ((c0 = decode_char( p[0] )) > 63) return 0;
1055 if ((c1 = decode_char( p[1] )) > 63) return 0;
1056 if ((c2 = decode_char( p[2] )) > 63) return 0;
1057 if ((c3 = decode_char( p[3] )) > 63) return 0;
1059 if (buf)
1061 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1062 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1063 buf[i + 2] = (c2 << 6) | c3;
1065 i += 3;
1067 return i;
1070 static struct authinfo *alloc_authinfo(void)
1072 struct authinfo *ret;
1074 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1076 SecInvalidateHandle( &ret->cred );
1077 SecInvalidateHandle( &ret->ctx );
1078 memset( &ret->exp, 0, sizeof(ret->exp) );
1079 ret->scheme = 0;
1080 ret->attr = 0;
1081 ret->max_token = 0;
1082 ret->data = NULL;
1083 ret->data_len = 0;
1084 ret->finished = FALSE;
1085 return ret;
1088 void destroy_authinfo( struct authinfo *authinfo )
1090 if (!authinfo) return;
1092 if (SecIsValidHandle( &authinfo->ctx ))
1093 DeleteSecurityContext( &authinfo->ctx );
1094 if (SecIsValidHandle( &authinfo->cred ))
1095 FreeCredentialsHandle( &authinfo->cred );
1097 heap_free( authinfo->data );
1098 heap_free( authinfo );
1101 static BOOL get_authvalue( struct request *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1103 DWORD size, index = 0;
1104 for (;;)
1106 size = len;
1107 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1108 if (auth_scheme_from_header( buffer ) == scheme) break;
1110 return TRUE;
1113 static BOOL do_authorization( struct request *request, DWORD target, DWORD scheme_flag )
1115 struct authinfo *authinfo, **auth_ptr;
1116 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1117 const WCHAR *auth_target, *username, *password;
1118 WCHAR auth_value[2048], *auth_reply;
1119 DWORD len = sizeof(auth_value), len_scheme, flags;
1120 BOOL ret, has_auth_value;
1122 if (scheme == SCHEME_INVALID) return FALSE;
1124 switch (target)
1126 case WINHTTP_AUTH_TARGET_SERVER:
1127 has_auth_value = get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len );
1128 auth_ptr = &request->authinfo;
1129 auth_target = attr_authorization;
1130 if (request->creds[TARGET_SERVER][scheme].username)
1132 if (scheme != SCHEME_BASIC && !has_auth_value) return FALSE;
1133 username = request->creds[TARGET_SERVER][scheme].username;
1134 password = request->creds[TARGET_SERVER][scheme].password;
1136 else
1138 if (!has_auth_value) return FALSE;
1139 username = request->connect->username;
1140 password = request->connect->password;
1142 break;
1144 case WINHTTP_AUTH_TARGET_PROXY:
1145 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1146 return FALSE;
1147 auth_ptr = &request->proxy_authinfo;
1148 auth_target = attr_proxy_authorization;
1149 if (request->creds[TARGET_PROXY][scheme].username)
1151 username = request->creds[TARGET_PROXY][scheme].username;
1152 password = request->creds[TARGET_PROXY][scheme].password;
1154 else
1156 username = request->connect->session->proxy_username;
1157 password = request->connect->session->proxy_password;
1159 break;
1161 default:
1162 WARN("unknown target %x\n", target);
1163 return FALSE;
1165 authinfo = *auth_ptr;
1167 switch (scheme)
1169 case SCHEME_BASIC:
1171 int userlen, passlen;
1173 if (!username || !password) return FALSE;
1174 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1176 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1177 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1179 authinfo->data_len = userlen + 1 + passlen;
1180 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1182 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1183 authinfo->data[userlen] = ':';
1184 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1186 authinfo->scheme = SCHEME_BASIC;
1187 authinfo->finished = TRUE;
1188 break;
1190 case SCHEME_NTLM:
1191 case SCHEME_NEGOTIATE:
1193 SECURITY_STATUS status;
1194 SecBufferDesc out_desc, in_desc;
1195 SecBuffer out, in;
1196 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1197 const WCHAR *p;
1198 BOOL first = FALSE;
1200 if (!authinfo)
1202 TimeStamp exp;
1203 SEC_WINNT_AUTH_IDENTITY_W id;
1204 WCHAR *domain, *user;
1206 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1208 first = TRUE;
1209 domain = (WCHAR *)username;
1210 user = strchrW( username, '\\' );
1212 if (user) user++;
1213 else
1215 user = (WCHAR *)username;
1216 domain = NULL;
1218 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1219 id.User = user;
1220 id.UserLength = strlenW( user );
1221 id.Domain = domain;
1222 id.DomainLength = domain ? user - domain - 1 : 0;
1223 id.Password = (WCHAR *)password;
1224 id.PasswordLength = strlenW( password );
1226 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1227 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1228 &authinfo->cred, &exp );
1229 if (status == SEC_E_OK)
1231 PSecPkgInfoW info;
1232 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1233 if (status == SEC_E_OK)
1235 authinfo->max_token = info->cbMaxToken;
1236 FreeContextBuffer( info );
1239 if (status != SEC_E_OK)
1241 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1242 debugstr_w(auth_schemes[scheme].str), status);
1243 heap_free( authinfo );
1244 return FALSE;
1246 authinfo->scheme = scheme;
1248 else if (authinfo->finished) return FALSE;
1250 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1251 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1253 ERR("authentication scheme changed from %s to %s\n",
1254 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1255 destroy_authinfo( authinfo );
1256 *auth_ptr = NULL;
1257 return FALSE;
1259 in.BufferType = SECBUFFER_TOKEN;
1260 in.cbBuffer = 0;
1261 in.pvBuffer = NULL;
1263 in_desc.ulVersion = 0;
1264 in_desc.cBuffers = 1;
1265 in_desc.pBuffers = &in;
1267 p = auth_value + auth_schemes[scheme].len;
1268 if (*p == ' ')
1270 int len = strlenW( ++p );
1271 in.cbBuffer = decode_base64( p, len, NULL );
1272 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) {
1273 destroy_authinfo( authinfo );
1274 *auth_ptr = NULL;
1275 return FALSE;
1277 decode_base64( p, len, in.pvBuffer );
1279 out.BufferType = SECBUFFER_TOKEN;
1280 out.cbBuffer = authinfo->max_token;
1281 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1283 heap_free( in.pvBuffer );
1284 destroy_authinfo( authinfo );
1285 *auth_ptr = NULL;
1286 return FALSE;
1288 out_desc.ulVersion = 0;
1289 out_desc.cBuffers = 1;
1290 out_desc.pBuffers = &out;
1292 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1293 first ? request->connect->servername : NULL, flags, 0,
1294 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1295 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1296 heap_free( in.pvBuffer );
1297 if (status == SEC_E_OK)
1299 heap_free( authinfo->data );
1300 authinfo->data = out.pvBuffer;
1301 authinfo->data_len = out.cbBuffer;
1302 authinfo->finished = TRUE;
1303 TRACE("sending last auth packet\n");
1305 else if (status == SEC_I_CONTINUE_NEEDED)
1307 heap_free( authinfo->data );
1308 authinfo->data = out.pvBuffer;
1309 authinfo->data_len = out.cbBuffer;
1310 TRACE("sending next auth packet\n");
1312 else
1314 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1315 heap_free( out.pvBuffer );
1316 destroy_authinfo( authinfo );
1317 *auth_ptr = NULL;
1318 return FALSE;
1320 break;
1322 default:
1323 ERR("invalid scheme %u\n", scheme);
1324 return FALSE;
1326 *auth_ptr = authinfo;
1328 len_scheme = auth_schemes[authinfo->scheme].len;
1329 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1330 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1332 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1333 auth_reply[len_scheme] = ' ';
1334 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1336 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1337 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1338 heap_free( auth_reply );
1339 return ret;
1342 static WCHAR *build_proxy_connect_string( struct request *request )
1344 static const WCHAR fmtW[] = {'%','s',':','%','u',0};
1345 static const WCHAR connectW[] = {'C','O','N','N','E','C','T', 0};
1346 static const WCHAR spaceW[] = {' ',0}, crlfW[] = {'\r','\n',0}, colonW[] = {':',' ',0};
1347 static const WCHAR twocrlfW[] = {'\r','\n','\r','\n',0};
1348 WCHAR *ret, *host;
1349 unsigned int i;
1350 int len;
1352 if (!(host = heap_alloc( (strlenW( request->connect->hostname ) + 7) * sizeof(WCHAR) ))) return NULL;
1353 len = sprintfW( host, fmtW, request->connect->hostname, request->connect->hostport );
1355 len += ARRAY_SIZE(connectW);
1356 len += ARRAY_SIZE(http1_1);
1358 for (i = 0; i < request->num_headers; i++)
1360 if (request->headers[i].is_request)
1361 len += strlenW( request->headers[i].field ) + strlenW( request->headers[i].value ) + 4; /* '\r\n: ' */
1363 len += 4; /* '\r\n\r\n' */
1365 if ((ret = heap_alloc( (len + 1) * sizeof(WCHAR) )))
1367 strcpyW( ret, connectW );
1368 strcatW( ret, spaceW );
1369 strcatW( ret, host );
1370 strcatW( ret, spaceW );
1371 strcatW( ret, http1_1 );
1373 for (i = 0; i < request->num_headers; i++)
1375 if (request->headers[i].is_request)
1377 strcatW( ret, crlfW );
1378 strcatW( ret, request->headers[i].field );
1379 strcatW( ret, colonW );
1380 strcatW( ret, request->headers[i].value );
1383 strcatW( ret, twocrlfW );
1386 heap_free( host );
1387 return ret;
1390 static BOOL read_reply( struct request *request );
1392 static BOOL secure_proxy_connect( struct request *request )
1394 WCHAR *str;
1395 char *strA;
1396 int len, bytes_sent;
1397 BOOL ret;
1399 if (!(str = build_proxy_connect_string( request ))) return FALSE;
1400 strA = strdupWA( str );
1401 heap_free( str );
1402 if (!strA) return FALSE;
1404 len = strlen( strA );
1405 ret = netconn_send( request->netconn, strA, len, &bytes_sent );
1406 heap_free( strA );
1407 if (ret) ret = read_reply( request );
1409 return ret;
1412 static WCHAR *addr_to_str( struct sockaddr_storage *addr )
1414 char buf[INET6_ADDRSTRLEN];
1415 void *src;
1417 switch (addr->ss_family)
1419 case AF_INET:
1420 src = &((struct sockaddr_in *)addr)->sin_addr;
1421 break;
1422 case AF_INET6:
1423 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
1424 break;
1425 default:
1426 WARN("unsupported address family %d\n", addr->ss_family);
1427 return NULL;
1429 if (!inet_ntop( addr->ss_family, src, buf, sizeof(buf) )) return NULL;
1430 return strdupAW( buf );
1433 static CRITICAL_SECTION connection_pool_cs;
1434 static CRITICAL_SECTION_DEBUG connection_pool_debug =
1436 0, 0, &connection_pool_cs,
1437 { &connection_pool_debug.ProcessLocksList, &connection_pool_debug.ProcessLocksList },
1438 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
1440 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
1442 static struct list connection_pool = LIST_INIT( connection_pool );
1444 void release_host( struct hostdata *host )
1446 LONG ref;
1448 EnterCriticalSection( &connection_pool_cs );
1449 if (!(ref = --host->ref)) list_remove( &host->entry );
1450 LeaveCriticalSection( &connection_pool_cs );
1451 if (ref) return;
1453 assert( list_empty( &host->connections ) );
1454 heap_free( host->hostname );
1455 heap_free( host );
1458 static BOOL connection_collector_running;
1460 static void CALLBACK connection_collector( TP_CALLBACK_INSTANCE *instance, void *ctx )
1462 unsigned int remaining_connections;
1463 struct netconn *netconn, *next_netconn;
1464 struct hostdata *host, *next_host;
1465 ULONGLONG now;
1469 /* FIXME: Use more sophisticated method */
1470 Sleep(5000);
1471 remaining_connections = 0;
1472 now = GetTickCount64();
1474 EnterCriticalSection(&connection_pool_cs);
1476 LIST_FOR_EACH_ENTRY_SAFE(host, next_host, &connection_pool, struct hostdata, entry)
1478 LIST_FOR_EACH_ENTRY_SAFE(netconn, next_netconn, &host->connections, struct netconn, entry)
1480 if (netconn->keep_until < now)
1482 TRACE("freeing %p\n", netconn);
1483 list_remove(&netconn->entry);
1484 netconn_close(netconn);
1486 else remaining_connections++;
1490 if (!remaining_connections) connection_collector_running = FALSE;
1492 LeaveCriticalSection(&connection_pool_cs);
1493 } while(remaining_connections);
1495 FreeLibraryWhenCallbackReturns( instance, winhttp_instance );
1498 static void cache_connection( struct netconn *netconn )
1500 TRACE( "caching connection %p\n", netconn );
1502 EnterCriticalSection( &connection_pool_cs );
1504 netconn->keep_until = GetTickCount64() + DEFAULT_KEEP_ALIVE_TIMEOUT;
1505 list_add_head( &netconn->host->connections, &netconn->entry );
1507 if (!connection_collector_running)
1509 HMODULE module;
1511 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR *)winhttp_instance, &module );
1513 if (TrySubmitThreadpoolCallback( connection_collector, NULL, NULL )) connection_collector_running = TRUE;
1514 else FreeLibrary( winhttp_instance );
1517 LeaveCriticalSection( &connection_pool_cs );
1520 static DWORD map_secure_protocols( DWORD mask )
1522 DWORD ret = 0;
1523 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL2) ret |= SP_PROT_SSL2_CLIENT;
1524 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL3) ret |= SP_PROT_SSL3_CLIENT;
1525 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1) ret |= SP_PROT_TLS1_CLIENT;
1526 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1) ret |= SP_PROT_TLS1_1_CLIENT;
1527 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2) ret |= SP_PROT_TLS1_2_CLIENT;
1528 return ret;
1531 static BOOL ensure_cred_handle( struct session *session )
1533 SECURITY_STATUS status = SEC_E_OK;
1535 if (session->cred_handle_initialized) return TRUE;
1537 EnterCriticalSection( &session->cs );
1538 if (!session->cred_handle_initialized)
1540 SCHANNEL_CRED cred;
1541 memset( &cred, 0, sizeof(cred) );
1542 cred.dwVersion = SCHANNEL_CRED_VERSION;
1543 cred.grbitEnabledProtocols = map_secure_protocols( session->secure_protocols );
1544 status = AcquireCredentialsHandleW( NULL, (WCHAR *)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL,
1545 &cred, NULL, NULL, &session->cred_handle, NULL );
1546 if (status == SEC_E_OK)
1547 session->cred_handle_initialized = TRUE;
1549 LeaveCriticalSection( &session->cs );
1551 if (status != SEC_E_OK)
1553 WARN( "AcquireCredentialsHandleW failed: 0x%08x\n", status );
1554 return FALSE;
1556 return TRUE;
1559 static BOOL open_connection( struct request *request )
1561 BOOL is_secure = request->hdr.flags & WINHTTP_FLAG_SECURE;
1562 struct hostdata *host = NULL, *iter;
1563 struct netconn *netconn = NULL;
1564 struct connect *connect;
1565 WCHAR *addressW = NULL;
1566 INTERNET_PORT port;
1567 DWORD len;
1569 if (request->netconn) goto done;
1571 connect = request->connect;
1572 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1574 EnterCriticalSection( &connection_pool_cs );
1576 LIST_FOR_EACH_ENTRY( iter, &connection_pool, struct hostdata, entry )
1578 if (iter->port == port && !strcmpW( connect->servername, iter->hostname ) && !is_secure == !iter->secure)
1580 host = iter;
1581 host->ref++;
1582 break;
1586 if (!host)
1588 if ((host = heap_alloc( sizeof(*host) )))
1590 host->ref = 1;
1591 host->secure = is_secure;
1592 host->port = port;
1593 list_init( &host->connections );
1594 if ((host->hostname = strdupW( connect->servername )))
1596 list_add_head( &connection_pool, &host->entry );
1598 else
1600 heap_free( host );
1601 host = NULL;
1606 LeaveCriticalSection( &connection_pool_cs );
1608 if (!host) return FALSE;
1610 for (;;)
1612 EnterCriticalSection( &connection_pool_cs );
1613 if (!list_empty( &host->connections ))
1615 netconn = LIST_ENTRY( list_head( &host->connections ), struct netconn, entry );
1616 list_remove( &netconn->entry );
1618 LeaveCriticalSection( &connection_pool_cs );
1619 if (!netconn) break;
1621 if (netconn_is_alive( netconn )) break;
1622 TRACE("connection %p no longer alive, closing\n", netconn);
1623 netconn_close( netconn );
1624 netconn = NULL;
1627 if (!connect->resolved && netconn)
1629 connect->sockaddr = netconn->sockaddr;
1630 connect->resolved = TRUE;
1633 if (!connect->resolved)
1635 len = strlenW( host->hostname ) + 1;
1636 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, host->hostname, len );
1638 if (!netconn_resolve( host->hostname, port, &connect->sockaddr, request->resolve_timeout ))
1640 release_host( host );
1641 return FALSE;
1643 connect->resolved = TRUE;
1645 if (!(addressW = addr_to_str( &connect->sockaddr )))
1647 release_host( host );
1648 return FALSE;
1650 len = strlenW( addressW ) + 1;
1651 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
1654 if (!netconn)
1656 if (!addressW && !(addressW = addr_to_str( &connect->sockaddr )))
1658 release_host( host );
1659 return FALSE;
1662 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
1664 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
1666 if (!(netconn = netconn_create( host, &connect->sockaddr, request->connect_timeout )))
1668 heap_free( addressW );
1669 release_host( host );
1670 return FALSE;
1672 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1673 netconn_set_timeout( netconn, FALSE, request->receive_response_timeout );
1674 if (is_secure)
1676 if (connect->session->proxy_server &&
1677 strcmpiW( connect->hostname, connect->servername ))
1679 if (!secure_proxy_connect( request ))
1681 heap_free( addressW );
1682 netconn_close( netconn );
1683 return FALSE;
1687 CertFreeCertificateContext( request->server_cert );
1688 request->server_cert = NULL;
1690 if (!ensure_cred_handle( connect->session ) ||
1691 !netconn_secure_connect( netconn, connect->hostname, request->security_flags,
1692 &connect->session->cred_handle, request->check_revocation ))
1694 heap_free( addressW );
1695 netconn_close( netconn );
1696 return FALSE;
1700 request->netconn = netconn;
1701 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
1703 else
1705 TRACE("using connection %p\n", netconn);
1707 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1708 netconn_set_timeout( netconn, FALSE, request->receive_response_timeout );
1709 request->netconn = netconn;
1712 if (netconn->secure && !(request->server_cert = netconn_get_certificate( netconn )))
1714 heap_free( addressW );
1715 netconn_close( netconn );
1716 return FALSE;
1719 done:
1720 request->read_pos = request->read_size = 0;
1721 request->read_chunked = FALSE;
1722 request->read_chunked_size = ~0u;
1723 request->read_chunked_eof = FALSE;
1724 heap_free( addressW );
1725 return TRUE;
1728 void close_connection( struct request *request )
1730 if (!request->netconn) return;
1732 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1733 netconn_close( request->netconn );
1734 request->netconn = NULL;
1735 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1738 static BOOL add_host_header( struct request *request, DWORD modifier )
1740 BOOL ret;
1741 DWORD len;
1742 WCHAR *host;
1743 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1744 struct connect *connect = request->connect;
1745 INTERNET_PORT port;
1747 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1749 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1751 return process_header( request, attr_host, connect->hostname, modifier, TRUE );
1753 len = strlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1754 if (!(host = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1755 sprintfW( host, fmt, connect->hostname, port );
1756 ret = process_header( request, attr_host, host, modifier, TRUE );
1757 heap_free( host );
1758 return ret;
1761 static void clear_response_headers( struct request *request )
1763 unsigned int i;
1765 for (i = 0; i < request->num_headers; i++)
1767 if (!request->headers[i].field) continue;
1768 if (!request->headers[i].value) continue;
1769 if (request->headers[i].is_request) continue;
1770 delete_header( request, i );
1771 i--;
1775 /* remove some amount of data from the read buffer */
1776 static void remove_data( struct request *request, int count )
1778 if (!(request->read_size -= count)) request->read_pos = 0;
1779 else request->read_pos += count;
1782 /* read some more data into the read buffer */
1783 static BOOL read_more_data( struct request *request, int maxlen, BOOL notify )
1785 int len;
1786 BOOL ret;
1788 if (request->read_chunked_eof) return FALSE;
1790 if (request->read_size && request->read_pos)
1792 /* move existing data to the start of the buffer */
1793 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1794 request->read_pos = 0;
1796 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1798 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1800 ret = netconn_recv( request->netconn, request->read_buf + request->read_size,
1801 maxlen - request->read_size, 0, &len );
1803 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &len, sizeof(len) );
1805 request->read_size += len;
1806 return ret;
1809 /* discard data contents until we reach end of line */
1810 static BOOL discard_eol( struct request *request, BOOL notify )
1814 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1815 if (eol)
1817 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1818 break;
1820 request->read_pos = request->read_size = 0; /* discard everything */
1821 if (!read_more_data( request, -1, notify )) return FALSE;
1822 } while (request->read_size);
1823 return TRUE;
1826 /* read the size of the next chunk */
1827 static BOOL start_next_chunk( struct request *request, BOOL notify )
1829 DWORD chunk_size = 0;
1831 assert(!request->read_chunked_size || request->read_chunked_size == ~0u);
1833 if (request->read_chunked_eof) return FALSE;
1835 /* read terminator for the previous chunk */
1836 if (!request->read_chunked_size && !discard_eol( request, notify )) return FALSE;
1838 for (;;)
1840 while (request->read_size)
1842 char ch = request->read_buf[request->read_pos];
1843 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1844 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1845 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1846 else if (ch == ';' || ch == '\r' || ch == '\n')
1848 TRACE("reading %u byte chunk\n", chunk_size);
1850 if (request->content_length == ~0u) request->content_length = chunk_size;
1851 else request->content_length += chunk_size;
1853 request->read_chunked_size = chunk_size;
1854 if (!chunk_size) request->read_chunked_eof = TRUE;
1856 return discard_eol( request, notify );
1858 remove_data( request, 1 );
1860 if (!read_more_data( request, -1, notify )) return FALSE;
1861 if (!request->read_size)
1863 request->content_length = request->content_read = 0;
1864 request->read_chunked_size = 0;
1865 return TRUE;
1870 static BOOL refill_buffer( struct request *request, BOOL notify )
1872 int len = sizeof(request->read_buf);
1874 if (request->read_chunked)
1876 if (request->read_chunked_eof) return FALSE;
1877 if (request->read_chunked_size == ~0u || !request->read_chunked_size)
1879 if (!start_next_chunk( request, notify )) return FALSE;
1881 len = min( len, request->read_chunked_size );
1883 else if (request->content_length != ~0u)
1885 len = min( len, request->content_length - request->content_read );
1888 if (len <= request->read_size) return TRUE;
1889 if (!read_more_data( request, len, notify )) return FALSE;
1890 if (!request->read_size) request->content_length = request->content_read = 0;
1891 return TRUE;
1894 static void finished_reading( struct request *request )
1896 static const WCHAR closeW[] = {'c','l','o','s','e',0};
1898 BOOL close = FALSE;
1899 WCHAR connection[20];
1900 DWORD size = sizeof(connection);
1902 if (!request->netconn) return;
1904 if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
1905 else if (query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
1906 query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
1908 if (!strcmpiW( connection, closeW )) close = TRUE;
1910 else if (!strcmpW( request->version, http1_0 )) close = TRUE;
1911 if (close)
1913 close_connection( request );
1914 return;
1917 cache_connection( request->netconn );
1918 request->netconn = NULL;
1921 /* return the size of data available to be read immediately */
1922 static DWORD get_available_data( struct request *request )
1924 if (request->read_chunked) return min( request->read_chunked_size, request->read_size );
1925 return request->read_size;
1928 /* check if we have reached the end of the data to read */
1929 static BOOL end_of_read_data( struct request *request )
1931 if (!request->content_length) return TRUE;
1932 if (request->read_chunked) return request->read_chunked_eof;
1933 if (request->content_length == ~0u) return FALSE;
1934 return (request->content_length == request->content_read);
1937 static BOOL read_data( struct request *request, void *buffer, DWORD size, DWORD *read, BOOL async )
1939 int count, bytes_read = 0;
1940 BOOL ret = TRUE;
1942 if (end_of_read_data( request )) goto done;
1944 while (size)
1946 if (!(count = get_available_data( request )))
1948 if (!(ret = refill_buffer( request, async ))) goto done;
1949 if (!(count = get_available_data( request ))) goto done;
1951 count = min( count, size );
1952 memcpy( (char *)buffer + bytes_read, request->read_buf + request->read_pos, count );
1953 remove_data( request, count );
1954 if (request->read_chunked) request->read_chunked_size -= count;
1955 size -= count;
1956 bytes_read += count;
1957 request->content_read += count;
1958 if (end_of_read_data( request )) goto done;
1960 if (request->read_chunked && !request->read_chunked_size) ret = refill_buffer( request, async );
1962 done:
1963 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, request->content_read, request->content_length );
1964 if (async)
1966 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
1967 else
1969 WINHTTP_ASYNC_RESULT result;
1970 result.dwResult = API_READ_DATA;
1971 result.dwError = GetLastError();
1972 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
1976 if (ret && read) *read = bytes_read;
1977 if (end_of_read_data( request )) finished_reading( request );
1978 return ret;
1981 /* read any content returned by the server so that the connection can be reused */
1982 static void drain_content( struct request *request )
1984 DWORD size, bytes_read, bytes_total = 0, bytes_left = request->content_length - request->content_read;
1985 char buffer[2048];
1987 refill_buffer( request, FALSE );
1988 for (;;)
1990 if (request->read_chunked) size = sizeof(buffer);
1991 else
1993 if (bytes_total >= bytes_left) return;
1994 size = min( sizeof(buffer), bytes_left - bytes_total );
1996 if (!read_data( request, buffer, size, &bytes_read, FALSE ) || !bytes_read) return;
1997 bytes_total += bytes_read;
2001 enum escape_flags
2003 ESCAPE_FLAG_NON_PRINTABLE = 0x01,
2004 ESCAPE_FLAG_SPACE = 0x02,
2005 ESCAPE_FLAG_PERCENT = 0x04,
2006 ESCAPE_FLAG_UNSAFE = 0x08,
2007 ESCAPE_FLAG_DEL = 0x10,
2008 ESCAPE_FLAG_8BIT = 0x20,
2009 ESCAPE_FLAG_STRIP_CRLF = 0x40,
2012 #define ESCAPE_MASK_DEFAULT (ESCAPE_FLAG_NON_PRINTABLE | ESCAPE_FLAG_SPACE | ESCAPE_FLAG_UNSAFE |\
2013 ESCAPE_FLAG_DEL | ESCAPE_FLAG_8BIT)
2014 #define ESCAPE_MASK_PERCENT (ESCAPE_FLAG_PERCENT | ESCAPE_MASK_DEFAULT)
2015 #define ESCAPE_MASK_DISABLE (ESCAPE_FLAG_SPACE | ESCAPE_FLAG_8BIT | ESCAPE_FLAG_STRIP_CRLF)
2017 static inline BOOL need_escape( char ch, enum escape_flags flags )
2019 static const char unsafe[] = "\"#<>[\\]^`{|}";
2020 const char *ptr = unsafe;
2022 if ((flags & ESCAPE_FLAG_SPACE) && ch == ' ') return TRUE;
2023 if ((flags & ESCAPE_FLAG_PERCENT) && ch == '%') return TRUE;
2024 if ((flags & ESCAPE_FLAG_NON_PRINTABLE) && ch < 0x20) return TRUE;
2025 if ((flags & ESCAPE_FLAG_DEL) && ch == 0x7f) return TRUE;
2026 if ((flags & ESCAPE_FLAG_8BIT) && (ch & 0x80)) return TRUE;
2027 if ((flags & ESCAPE_FLAG_UNSAFE)) while (*ptr) { if (ch == *ptr++) return TRUE; }
2028 return FALSE;
2031 static DWORD escape_string( const char *src, DWORD len, char *dst, enum escape_flags flags )
2033 static const char hex[] = "0123456789ABCDEF";
2034 DWORD i, ret = len;
2035 char *ptr = dst;
2037 for (i = 0; i < len; i++)
2039 if ((flags & ESCAPE_FLAG_STRIP_CRLF) && (src[i] == '\r' || src[i] == '\n'))
2041 ret--;
2042 continue;
2044 if (need_escape( src[i], flags ))
2046 if (dst)
2048 ptr[0] = '%';
2049 ptr[1] = hex[(src[i] >> 4) & 0xf];
2050 ptr[2] = hex[src[i] & 0xf];
2051 ptr += 3;
2053 ret += 2;
2055 else if (dst) *ptr++ = src[i];
2058 if (dst) dst[ret] = 0;
2059 return ret;
2062 static DWORD str_to_wire( const WCHAR *src, int src_len, char *dst, enum escape_flags flags )
2064 DWORD len;
2065 char *utf8;
2067 if (src_len < 0) src_len = strlenW( src );
2068 len = WideCharToMultiByte( CP_UTF8, 0, src, src_len, NULL, 0, NULL, NULL );
2069 if (!(utf8 = heap_alloc( len ))) return 0;
2071 WideCharToMultiByte( CP_UTF8, 0, src, -1, utf8, len, NULL, NULL );
2072 len = escape_string( utf8, len, dst, flags );
2073 heap_free( utf8 );
2075 return len;
2078 static char *build_wire_path( struct request *request, DWORD *ret_len )
2080 WCHAR *full_path;
2081 const WCHAR *start, *path, *query = NULL;
2082 DWORD len, len_path = 0, len_query = 0;
2083 enum escape_flags path_flags, query_flags;
2084 char *ret;
2086 if (!strcmpiW( request->connect->hostname, request->connect->servername )) start = full_path = request->path;
2087 else if (!(full_path = build_absolute_request_path( request, &start ))) return NULL;
2089 len = strlenW( full_path );
2090 if ((path = strchrW( start, '/' )))
2092 len_path = strlenW( path );
2093 if ((query = strchrW( path, '?' )))
2095 len_query = strlenW( query );
2096 len_path -= len_query;
2100 if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_DISABLE) path_flags = ESCAPE_MASK_DISABLE;
2101 else if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_PERCENT) path_flags = ESCAPE_MASK_PERCENT;
2102 else path_flags = ESCAPE_MASK_DEFAULT;
2104 if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_DISABLE_QUERY) query_flags = ESCAPE_MASK_DISABLE;
2105 else query_flags = path_flags;
2107 *ret_len = str_to_wire( full_path, len - len_path - len_query, NULL, 0 );
2108 if (path) *ret_len += str_to_wire( path, len_path, NULL, path_flags );
2109 if (query) *ret_len += str_to_wire( query, len_query, NULL, query_flags );
2111 if ((ret = heap_alloc( *ret_len + 1 )))
2113 len = str_to_wire( full_path, len - len_path - len_query, ret, 0 );
2114 if (path) len += str_to_wire( path, len_path, ret + len, path_flags );
2115 if (query) str_to_wire( query, len_query, ret + len, query_flags );
2118 if (full_path != request->path) heap_free( full_path );
2119 return ret;
2122 static char *build_wire_request( struct request *request, DWORD *len )
2124 char *path, *ptr, *ret;
2125 DWORD i, len_path;
2127 if (!(path = build_wire_path( request, &len_path ))) return NULL;
2129 *len = str_to_wire( request->verb, -1, NULL, 0 ) + 1; /* ' ' */
2130 *len += len_path + 1; /* ' ' */
2131 *len += str_to_wire( request->version, -1, NULL, 0 );
2133 for (i = 0; i < request->num_headers; i++)
2135 if (request->headers[i].is_request)
2137 *len += str_to_wire( request->headers[i].field, -1, NULL, 0 ) + 2; /* ': ' */
2138 *len += str_to_wire( request->headers[i].value, -1, NULL, 0 ) + 2; /* '\r\n' */
2141 *len += 4; /* '\r\n\r\n' */
2143 if ((ret = ptr = heap_alloc( *len + 1 )))
2145 ptr += str_to_wire( request->verb, -1, ptr, 0 );
2146 *ptr++ = ' ';
2147 memcpy( ptr, path, len_path );
2148 ptr += len_path;
2149 *ptr++ = ' ';
2150 ptr += str_to_wire( request->version, -1, ptr, 0 );
2152 for (i = 0; i < request->num_headers; i++)
2154 if (request->headers[i].is_request)
2156 *ptr++ = '\r';
2157 *ptr++ = '\n';
2158 ptr += str_to_wire( request->headers[i].field, -1, ptr, 0 );
2159 *ptr++ = ':';
2160 *ptr++ = ' ';
2161 ptr += str_to_wire( request->headers[i].value, -1, ptr, 0 );
2164 memcpy( ptr, "\r\n\r\n", sizeof("\r\n\r\n") );
2167 heap_free( path );
2168 return ret;
2171 static BOOL send_request( struct request *request, const WCHAR *headers, DWORD headers_len, void *optional,
2172 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
2174 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
2175 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
2176 static const WCHAR length_fmt[] = {'%','l','d',0};
2178 BOOL ret = FALSE;
2179 struct connect *connect = request->connect;
2180 struct session *session = connect->session;
2181 char *wire_req;
2182 int bytes_sent;
2183 DWORD len, i, flags;
2185 clear_response_headers( request );
2186 drain_content( request );
2188 flags = WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
2189 for (i = 0; i < request->num_accept_types; i++)
2191 process_header( request, attr_accept, request->accept_types[i], flags, TRUE );
2193 if (session->agent)
2194 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2196 if (connect->hostname)
2197 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
2199 if (request->creds[TARGET_SERVER][SCHEME_BASIC].username)
2200 do_authorization( request, WINHTTP_AUTH_TARGET_SERVER, WINHTTP_AUTH_SCHEME_BASIC );
2202 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
2204 WCHAR length[21]; /* decimal long int + null */
2205 sprintfW( length, length_fmt, total_len );
2206 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2208 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
2210 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2212 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
2214 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2215 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2217 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
2219 TRACE("failed to add request headers\n");
2220 return FALSE;
2222 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
2224 WARN("failed to add cookie headers\n");
2225 return FALSE;
2228 if (context) request->hdr.context = context;
2230 if (!(ret = open_connection( request ))) goto end;
2231 if (!(wire_req = build_wire_request( request, &len ))) goto end;
2232 TRACE("full request: %s\n", debugstr_a(wire_req));
2234 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
2236 ret = netconn_send( request->netconn, wire_req, len, &bytes_sent );
2237 heap_free( wire_req );
2238 if (!ret) goto end;
2240 if (optional_len)
2242 if (!netconn_send( request->netconn, optional, optional_len, &bytes_sent )) goto end;
2243 request->optional = optional;
2244 request->optional_len = optional_len;
2245 len += optional_len;
2247 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(len) );
2249 end:
2250 if (async)
2252 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
2253 else
2255 WINHTTP_ASYNC_RESULT result;
2256 result.dwResult = API_SEND_REQUEST;
2257 result.dwError = GetLastError();
2258 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2261 return ret;
2264 static void task_send_request( struct task_header *task )
2266 struct send_request *s = (struct send_request *)task;
2267 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
2268 heap_free( s->headers );
2271 /***********************************************************************
2272 * WinHttpSendRequest (winhttp.@)
2274 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
2275 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
2277 BOOL ret;
2278 struct request *request;
2280 TRACE("%p, %s, %u, %u, %u, %lx\n", hrequest, debugstr_wn(headers, headers_len), headers_len, optional_len,
2281 total_len, context);
2283 if (!(request = (struct request *)grab_object( hrequest )))
2285 SetLastError( ERROR_INVALID_HANDLE );
2286 return FALSE;
2288 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2290 release_object( &request->hdr );
2291 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2292 return FALSE;
2295 if (headers && !headers_len) headers_len = strlenW( headers );
2297 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2299 struct send_request *s;
2301 if (!(s = heap_alloc( sizeof(struct send_request) ))) return FALSE;
2302 s->hdr.request = request;
2303 s->hdr.proc = task_send_request;
2304 s->headers = strdupW( headers );
2305 s->headers_len = headers_len;
2306 s->optional = optional;
2307 s->optional_len = optional_len;
2308 s->total_len = total_len;
2309 s->context = context;
2311 addref_object( &request->hdr );
2312 ret = queue_task( (struct task_header *)s );
2314 else
2315 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
2317 release_object( &request->hdr );
2318 if (ret) SetLastError( ERROR_SUCCESS );
2319 return ret;
2322 static BOOL set_credentials( struct request *request, DWORD target, DWORD scheme_flag, const WCHAR *username,
2323 const WCHAR *password )
2325 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
2327 if (scheme == SCHEME_INVALID || ((scheme == SCHEME_BASIC || scheme == SCHEME_DIGEST) && (!username || !password)))
2329 SetLastError( ERROR_INVALID_PARAMETER );
2330 return FALSE;
2332 switch (target)
2334 case WINHTTP_AUTH_TARGET_SERVER:
2336 heap_free( request->creds[TARGET_SERVER][scheme].username );
2337 if (!username) request->creds[TARGET_SERVER][scheme].username = NULL;
2338 else if (!(request->creds[TARGET_SERVER][scheme].username = strdupW( username ))) return FALSE;
2340 heap_free( request->creds[TARGET_SERVER][scheme].password );
2341 if (!password) request->creds[TARGET_SERVER][scheme].password = NULL;
2342 else if (!(request->creds[TARGET_SERVER][scheme].password = strdupW( password ))) return FALSE;
2343 break;
2345 case WINHTTP_AUTH_TARGET_PROXY:
2347 heap_free( request->creds[TARGET_PROXY][scheme].username );
2348 if (!username) request->creds[TARGET_PROXY][scheme].username = NULL;
2349 else if (!(request->creds[TARGET_PROXY][scheme].username = strdupW( username ))) return FALSE;
2351 heap_free( request->creds[TARGET_PROXY][scheme].password );
2352 if (!password) request->creds[TARGET_PROXY][scheme].password = NULL;
2353 else if (!(request->creds[TARGET_PROXY][scheme].password = strdupW( password ))) return FALSE;
2354 break;
2356 default:
2357 WARN("unknown target %u\n", target);
2358 return FALSE;
2360 return TRUE;
2363 /***********************************************************************
2364 * WinHttpSetCredentials (winhttp.@)
2366 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
2367 LPCWSTR password, LPVOID params )
2369 BOOL ret;
2370 struct request *request;
2372 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
2374 if (!(request = (struct request *)grab_object( hrequest )))
2376 SetLastError( ERROR_INVALID_HANDLE );
2377 return FALSE;
2379 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2381 release_object( &request->hdr );
2382 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2383 return FALSE;
2386 ret = set_credentials( request, target, scheme, username, password );
2388 release_object( &request->hdr );
2389 if (ret) SetLastError( ERROR_SUCCESS );
2390 return ret;
2393 static BOOL handle_authorization( struct request *request, DWORD status )
2395 DWORD i, schemes, first, level, target;
2397 switch (status)
2399 case HTTP_STATUS_DENIED:
2400 target = WINHTTP_AUTH_TARGET_SERVER;
2401 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
2402 break;
2404 case HTTP_STATUS_PROXY_AUTH_REQ:
2405 target = WINHTTP_AUTH_TARGET_PROXY;
2406 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
2407 break;
2409 default:
2410 WARN("unhandled status %u\n", status);
2411 return FALSE;
2414 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
2415 if (do_authorization( request, target, first )) return TRUE;
2417 schemes &= ~first;
2418 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++)
2420 if (!(schemes & auth_schemes[i].scheme)) continue;
2421 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
2423 return FALSE;
2426 /* set the request content length based on the headers */
2427 static DWORD set_content_length( struct request *request, DWORD status )
2429 WCHAR encoding[20];
2430 DWORD buflen = sizeof(request->content_length);
2432 if (status == HTTP_STATUS_NO_CONTENT || status == HTTP_STATUS_NOT_MODIFIED || !strcmpW( request->verb, headW ))
2433 request->content_length = 0;
2434 else
2436 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
2437 NULL, &request->content_length, &buflen, NULL ))
2438 request->content_length = ~0u;
2440 buflen = sizeof(encoding);
2441 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
2442 !strcmpiW( encoding, chunkedW ))
2444 request->content_length = ~0u;
2445 request->read_chunked = TRUE;
2446 request->read_chunked_size = ~0u;
2447 request->read_chunked_eof = FALSE;
2450 request->content_read = 0;
2451 return request->content_length;
2454 static BOOL read_line( struct request *request, char *buffer, DWORD *len )
2456 int count, bytes_read, pos = 0;
2458 for (;;)
2460 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
2461 if (eol)
2463 count = eol - (request->read_buf + request->read_pos);
2464 bytes_read = count + 1;
2466 else count = bytes_read = request->read_size;
2468 count = min( count, *len - pos );
2469 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
2470 pos += count;
2471 remove_data( request, bytes_read );
2472 if (eol) break;
2474 if (!read_more_data( request, -1, TRUE )) return FALSE;
2475 if (!request->read_size)
2477 *len = 0;
2478 TRACE("returning empty string\n");
2479 return FALSE;
2482 if (pos < *len)
2484 if (pos && buffer[pos - 1] == '\r') pos--;
2485 *len = pos + 1;
2487 buffer[*len - 1] = 0;
2488 TRACE("returning %s\n", debugstr_a(buffer));
2489 return TRUE;
2492 #define MAX_REPLY_LEN 1460
2493 #define INITIAL_HEADER_BUFFER_LEN 512
2495 static BOOL read_reply( struct request *request )
2497 static const WCHAR crlf[] = {'\r','\n',0};
2499 char buffer[MAX_REPLY_LEN];
2500 DWORD buflen, len, offset, crlf_len = 2; /* strlenW(crlf) */
2501 char *status_code, *status_text;
2502 WCHAR *versionW, *status_textW, *raw_headers;
2503 WCHAR status_codeW[4]; /* sizeof("nnn") */
2505 if (!request->netconn) return FALSE;
2509 buflen = MAX_REPLY_LEN;
2510 if (!read_line( request, buffer, &buflen )) return FALSE;
2512 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2513 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
2514 status_code++;
2515 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
2516 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
2517 status_text++;
2519 TRACE("version [%s] status code [%s] status text [%s]\n",
2520 debugstr_an(buffer, status_code - buffer - 1),
2521 debugstr_an(status_code, len),
2522 debugstr_a(status_text));
2524 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
2526 /* we rely on the fact that the protocol is ascii */
2527 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2528 status_codeW[len] = 0;
2529 if (!(process_header( request, attr_status, status_codeW,
2530 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE, FALSE )))
2531 return FALSE;
2533 len = status_code - buffer;
2534 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2535 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2536 versionW[len - 1] = 0;
2538 heap_free( request->version );
2539 request->version = versionW;
2541 len = buflen - (status_text - buffer);
2542 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2543 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2545 heap_free( request->status_text );
2546 request->status_text = status_textW;
2548 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2549 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2550 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2551 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2553 heap_free( request->raw_headers );
2554 request->raw_headers = raw_headers;
2556 offset = buflen + crlf_len - 1;
2557 for (;;)
2559 struct header *header;
2561 buflen = MAX_REPLY_LEN;
2562 if (!read_line( request, buffer, &buflen )) return TRUE;
2563 if (!*buffer) buflen = 1;
2565 while (len - offset < buflen + crlf_len)
2567 WCHAR *tmp;
2568 len *= 2;
2569 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2570 request->raw_headers = raw_headers = tmp;
2572 if (!*buffer)
2574 memcpy( raw_headers + offset, crlf, sizeof(crlf) );
2575 break;
2577 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2579 if (!(header = parse_header( raw_headers + offset ))) break;
2580 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2582 free_header( header );
2583 break;
2585 free_header( header );
2586 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2587 offset += buflen + crlf_len - 1;
2590 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2591 return TRUE;
2594 static void record_cookies( struct request *request )
2596 unsigned int i;
2598 for (i = 0; i < request->num_headers; i++)
2600 struct header *set_cookie = &request->headers[i];
2601 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2603 set_cookies( request, set_cookie->value );
2608 static WCHAR *get_redirect_url( struct request *request, DWORD *len )
2610 DWORD size;
2611 WCHAR *ret;
2613 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2614 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2615 if (!(ret = heap_alloc( size ))) return NULL;
2616 *len = size / sizeof(WCHAR) - 1;
2617 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2618 heap_free( ret );
2619 return NULL;
2622 static BOOL handle_redirect( struct request *request, DWORD status )
2624 BOOL ret = FALSE;
2625 DWORD len, len_loc;
2626 URL_COMPONENTS uc;
2627 struct connect *connect = request->connect;
2628 INTERNET_PORT port;
2629 WCHAR *hostname = NULL, *location;
2630 int index;
2632 if (!(location = get_redirect_url( request, &len_loc ))) return FALSE;
2634 memset( &uc, 0, sizeof(uc) );
2635 uc.dwStructSize = sizeof(uc);
2636 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2638 if (!WinHttpCrackUrl( location, len_loc, 0, &uc )) /* assume relative redirect */
2640 WCHAR *path, *p;
2642 if (location[0] == '/')
2644 if (!(path = heap_alloc( (len_loc + 1) * sizeof(WCHAR) ))) goto end;
2645 memcpy( path, location, len_loc * sizeof(WCHAR) );
2646 path[len_loc] = 0;
2648 else
2650 if ((p = strrchrW( request->path, '/' ))) *p = 0;
2651 len = strlenW( request->path ) + 1 + len_loc;
2652 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2653 strcpyW( path, request->path );
2654 strcatW( path, slashW );
2655 memcpy( path + strlenW(path), location, len_loc * sizeof(WCHAR) );
2656 path[len_loc] = 0;
2658 heap_free( request->path );
2659 request->path = path;
2661 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_loc + 1 );
2663 else
2665 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2667 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2668 TRACE("redirect from secure page to non-secure page\n");
2669 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2671 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2673 TRACE("redirect from non-secure page to secure page\n");
2674 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2677 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_loc + 1 );
2679 len = uc.dwHostNameLength;
2680 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2681 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2682 hostname[len] = 0;
2684 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2685 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2687 heap_free( connect->hostname );
2688 connect->hostname = hostname;
2689 connect->hostport = port;
2690 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2692 netconn_close( request->netconn );
2693 request->netconn = NULL;
2694 request->content_length = request->content_read = 0;
2695 request->read_pos = request->read_size = 0;
2696 request->read_chunked = request->read_chunked_eof = FALSE;
2698 else heap_free( hostname );
2700 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2701 if (!(ret = open_connection( request ))) goto end;
2703 heap_free( request->path );
2704 request->path = NULL;
2705 if (uc.dwUrlPathLength)
2707 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2708 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2709 memcpy( request->path, uc.lpszUrlPath, (len + 1) * sizeof(WCHAR) );
2710 request->path[len] = 0;
2712 else request->path = strdupW( slashW );
2715 /* remove content-type/length headers */
2716 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2717 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2719 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2721 heap_free( request->verb );
2722 request->verb = strdupW( getW );
2723 request->optional = NULL;
2724 request->optional_len = 0;
2726 ret = TRUE;
2728 end:
2729 heap_free( location );
2730 return ret;
2733 static BOOL receive_response( struct request *request, BOOL async )
2735 BOOL ret;
2736 DWORD size, query, status;
2738 if (!request->netconn)
2740 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_STATE );
2741 return FALSE;
2744 netconn_set_timeout( request->netconn, FALSE, request->receive_response_timeout );
2745 for (;;)
2747 if (!(ret = read_reply( request )))
2749 SetLastError( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2750 break;
2752 size = sizeof(DWORD);
2753 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2754 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2756 set_content_length( request, status );
2758 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2760 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2762 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2763 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2765 if (!(ret = handle_redirect( request, status ))) break;
2767 /* recurse synchronously */
2768 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2770 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2772 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2774 if (!handle_authorization( request, status )) break;
2776 /* recurse synchronously */
2777 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2779 break;
2782 netconn_set_timeout( request->netconn, FALSE, request->receive_timeout );
2783 if (request->content_length) ret = refill_buffer( request, FALSE );
2785 if (async)
2787 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2788 else
2790 WINHTTP_ASYNC_RESULT result;
2791 result.dwResult = API_RECEIVE_RESPONSE;
2792 result.dwError = GetLastError();
2793 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2796 return ret;
2799 static void task_receive_response( struct task_header *task )
2801 struct receive_response *r = (struct receive_response *)task;
2802 receive_response( r->hdr.request, TRUE );
2805 /***********************************************************************
2806 * WinHttpReceiveResponse (winhttp.@)
2808 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2810 BOOL ret;
2811 struct request *request;
2813 TRACE("%p, %p\n", hrequest, reserved);
2815 if (!(request = (struct request *)grab_object( hrequest )))
2817 SetLastError( ERROR_INVALID_HANDLE );
2818 return FALSE;
2820 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2822 release_object( &request->hdr );
2823 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2824 return FALSE;
2827 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2829 struct receive_response *r;
2831 if (!(r = heap_alloc( sizeof(struct receive_response) ))) return FALSE;
2832 r->hdr.request = request;
2833 r->hdr.proc = task_receive_response;
2835 addref_object( &request->hdr );
2836 ret = queue_task( (struct task_header *)r );
2838 else
2839 ret = receive_response( request, FALSE );
2841 release_object( &request->hdr );
2842 if (ret) SetLastError( ERROR_SUCCESS );
2843 return ret;
2846 static BOOL query_data_available( struct request *request, DWORD *available, BOOL async )
2848 DWORD count = 0;
2849 BOOL ret = TRUE;
2851 if (end_of_read_data( request )) goto done;
2853 count = get_available_data( request );
2854 if (!request->read_chunked && request->netconn) count += netconn_query_data_available( request->netconn );
2855 if (!count)
2857 if (!(ret = refill_buffer( request, async ))) goto done;
2858 count = get_available_data( request );
2859 if (!request->read_chunked && request->netconn) count += netconn_query_data_available( request->netconn );
2862 done:
2863 TRACE("%u bytes available\n", count);
2864 if (async)
2866 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2867 else
2869 WINHTTP_ASYNC_RESULT result;
2870 result.dwResult = API_QUERY_DATA_AVAILABLE;
2871 result.dwError = GetLastError();
2872 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2876 if (ret && available) *available = count;
2877 return ret;
2880 static void task_query_data_available( struct task_header *task )
2882 struct query_data *q = (struct query_data *)task;
2883 query_data_available( q->hdr.request, q->available, TRUE );
2886 /***********************************************************************
2887 * WinHttpQueryDataAvailable (winhttp.@)
2889 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2891 BOOL ret;
2892 struct request *request;
2894 TRACE("%p, %p\n", hrequest, available);
2896 if (!(request = (struct request *)grab_object( hrequest )))
2898 SetLastError( ERROR_INVALID_HANDLE );
2899 return FALSE;
2901 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2903 release_object( &request->hdr );
2904 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2905 return FALSE;
2908 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2910 struct query_data *q;
2912 if (!(q = heap_alloc( sizeof(struct query_data) ))) return FALSE;
2913 q->hdr.request = request;
2914 q->hdr.proc = task_query_data_available;
2915 q->available = available;
2917 addref_object( &request->hdr );
2918 ret = queue_task( (struct task_header *)q );
2920 else
2921 ret = query_data_available( request, available, FALSE );
2923 release_object( &request->hdr );
2924 if (ret) SetLastError( ERROR_SUCCESS );
2925 return ret;
2928 static void task_read_data( struct task_header *task )
2930 struct read_data *r = (struct read_data *)task;
2931 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2934 /***********************************************************************
2935 * WinHttpReadData (winhttp.@)
2937 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2939 BOOL ret;
2940 struct request *request;
2942 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2944 if (!(request = (struct request *)grab_object( hrequest )))
2946 SetLastError( ERROR_INVALID_HANDLE );
2947 return FALSE;
2949 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2951 release_object( &request->hdr );
2952 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2953 return FALSE;
2956 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2958 struct read_data *r;
2960 if (!(r = heap_alloc( sizeof(struct read_data) ))) return FALSE;
2961 r->hdr.request = request;
2962 r->hdr.proc = task_read_data;
2963 r->buffer = buffer;
2964 r->to_read = to_read;
2965 r->read = read;
2967 addref_object( &request->hdr );
2968 ret = queue_task( (struct task_header *)r );
2970 else
2971 ret = read_data( request, buffer, to_read, read, FALSE );
2973 release_object( &request->hdr );
2974 if (ret) SetLastError( ERROR_SUCCESS );
2975 return ret;
2978 static BOOL write_data( struct request *request, const void *buffer, DWORD to_write, DWORD *written, BOOL async )
2980 BOOL ret;
2981 int num_bytes;
2983 ret = netconn_send( request->netconn, buffer, to_write, &num_bytes );
2985 if (async)
2987 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
2988 else
2990 WINHTTP_ASYNC_RESULT result;
2991 result.dwResult = API_WRITE_DATA;
2992 result.dwError = GetLastError();
2993 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2996 if (ret && written) *written = num_bytes;
2997 return ret;
3000 static void task_write_data( struct task_header *task )
3002 struct write_data *w = (struct write_data *)task;
3003 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
3006 /***********************************************************************
3007 * WinHttpWriteData (winhttp.@)
3009 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
3011 BOOL ret;
3012 struct request *request;
3014 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
3016 if (!(request = (struct request *)grab_object( hrequest )))
3018 SetLastError( ERROR_INVALID_HANDLE );
3019 return FALSE;
3021 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
3023 release_object( &request->hdr );
3024 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
3025 return FALSE;
3028 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
3030 struct write_data *w;
3032 if (!(w = heap_alloc( sizeof(struct write_data) ))) return FALSE;
3033 w->hdr.request = request;
3034 w->hdr.proc = task_write_data;
3035 w->buffer = buffer;
3036 w->to_write = to_write;
3037 w->written = written;
3039 addref_object( &request->hdr );
3040 ret = queue_task( (struct task_header *)w );
3042 else
3043 ret = write_data( request, buffer, to_write, written, FALSE );
3045 release_object( &request->hdr );
3046 if (ret) SetLastError( ERROR_SUCCESS );
3047 return ret;
3050 enum request_state
3052 REQUEST_STATE_INITIALIZED,
3053 REQUEST_STATE_CANCELLED,
3054 REQUEST_STATE_OPEN,
3055 REQUEST_STATE_SENT,
3056 REQUEST_STATE_RESPONSE_RECEIVED
3059 struct winhttp_request
3061 IWinHttpRequest IWinHttpRequest_iface;
3062 LONG refs;
3063 CRITICAL_SECTION cs;
3064 enum request_state state;
3065 HINTERNET hsession;
3066 HINTERNET hconnect;
3067 HINTERNET hrequest;
3068 VARIANT data;
3069 WCHAR *verb;
3070 HANDLE done;
3071 HANDLE wait;
3072 HANDLE cancel;
3073 BOOL proc_running;
3074 char *buffer;
3075 DWORD offset;
3076 DWORD bytes_available;
3077 DWORD bytes_read;
3078 DWORD error;
3079 DWORD logon_policy;
3080 DWORD disable_feature;
3081 LONG resolve_timeout;
3082 LONG connect_timeout;
3083 LONG send_timeout;
3084 LONG receive_timeout;
3085 WINHTTP_PROXY_INFO proxy;
3086 BOOL async;
3087 UINT url_codepage;
3090 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
3092 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
3095 static ULONG WINAPI winhttp_request_AddRef(
3096 IWinHttpRequest *iface )
3098 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3099 return InterlockedIncrement( &request->refs );
3102 /* critical section must be held */
3103 static void cancel_request( struct winhttp_request *request )
3105 if (request->state <= REQUEST_STATE_CANCELLED) return;
3107 if (request->proc_running)
3109 SetEvent( request->cancel );
3110 LeaveCriticalSection( &request->cs );
3112 WaitForSingleObject( request->done, INFINITE );
3114 EnterCriticalSection( &request->cs );
3116 request->state = REQUEST_STATE_CANCELLED;
3119 /* critical section must be held */
3120 static void free_request( struct winhttp_request *request )
3122 if (request->state < REQUEST_STATE_INITIALIZED) return;
3123 WinHttpCloseHandle( request->hrequest );
3124 WinHttpCloseHandle( request->hconnect );
3125 WinHttpCloseHandle( request->hsession );
3126 CloseHandle( request->done );
3127 CloseHandle( request->wait );
3128 CloseHandle( request->cancel );
3129 heap_free( request->proxy.lpszProxy );
3130 heap_free( request->proxy.lpszProxyBypass );
3131 heap_free( request->buffer );
3132 heap_free( request->verb );
3133 VariantClear( &request->data );
3136 static ULONG WINAPI winhttp_request_Release(
3137 IWinHttpRequest *iface )
3139 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3140 LONG refs = InterlockedDecrement( &request->refs );
3141 if (!refs)
3143 TRACE("destroying %p\n", request);
3145 EnterCriticalSection( &request->cs );
3146 cancel_request( request );
3147 free_request( request );
3148 LeaveCriticalSection( &request->cs );
3149 request->cs.DebugInfo->Spare[0] = 0;
3150 DeleteCriticalSection( &request->cs );
3151 heap_free( request );
3153 return refs;
3156 static HRESULT WINAPI winhttp_request_QueryInterface(
3157 IWinHttpRequest *iface,
3158 REFIID riid,
3159 void **obj )
3161 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3163 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
3165 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
3166 IsEqualGUID( riid, &IID_IDispatch ) ||
3167 IsEqualGUID( riid, &IID_IUnknown ))
3169 *obj = iface;
3171 else
3173 FIXME("interface %s not implemented\n", debugstr_guid(riid));
3174 return E_NOINTERFACE;
3176 IWinHttpRequest_AddRef( iface );
3177 return S_OK;
3180 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
3181 IWinHttpRequest *iface,
3182 UINT *count )
3184 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3186 TRACE("%p, %p\n", request, count);
3187 *count = 1;
3188 return S_OK;
3191 enum type_id
3193 IWinHttpRequest_tid,
3194 last_tid
3197 static ITypeLib *winhttp_typelib;
3198 static ITypeInfo *winhttp_typeinfo[last_tid];
3200 static REFIID winhttp_tid_id[] =
3202 &IID_IWinHttpRequest
3205 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
3207 HRESULT hr;
3209 if (!winhttp_typelib)
3211 ITypeLib *typelib;
3213 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
3214 if (FAILED(hr))
3216 ERR("LoadRegTypeLib failed: %08x\n", hr);
3217 return hr;
3219 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
3220 ITypeLib_Release( typelib );
3222 if (!winhttp_typeinfo[tid])
3224 ITypeInfo *typeinfo;
3226 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
3227 if (FAILED(hr))
3229 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
3230 return hr;
3232 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
3233 ITypeInfo_Release( typeinfo );
3235 *ret = winhttp_typeinfo[tid];
3236 ITypeInfo_AddRef(winhttp_typeinfo[tid]);
3237 return S_OK;
3240 void release_typelib(void)
3242 unsigned i;
3244 for (i = 0; i < ARRAY_SIZE(winhttp_typeinfo); i++)
3245 if (winhttp_typeinfo[i])
3246 ITypeInfo_Release(winhttp_typeinfo[i]);
3248 if (winhttp_typelib)
3249 ITypeLib_Release(winhttp_typelib);
3252 static HRESULT WINAPI winhttp_request_GetTypeInfo(
3253 IWinHttpRequest *iface,
3254 UINT index,
3255 LCID lcid,
3256 ITypeInfo **info )
3258 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3259 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
3261 return get_typeinfo( IWinHttpRequest_tid, info );
3264 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
3265 IWinHttpRequest *iface,
3266 REFIID riid,
3267 LPOLESTR *names,
3268 UINT count,
3269 LCID lcid,
3270 DISPID *dispid )
3272 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3273 ITypeInfo *typeinfo;
3274 HRESULT hr;
3276 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
3278 if (!names || !count || !dispid) return E_INVALIDARG;
3280 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
3281 if (SUCCEEDED(hr))
3283 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
3284 ITypeInfo_Release( typeinfo );
3286 return hr;
3289 static HRESULT WINAPI winhttp_request_Invoke(
3290 IWinHttpRequest *iface,
3291 DISPID member,
3292 REFIID riid,
3293 LCID lcid,
3294 WORD flags,
3295 DISPPARAMS *params,
3296 VARIANT *result,
3297 EXCEPINFO *excep_info,
3298 UINT *arg_err )
3300 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3301 ITypeInfo *typeinfo;
3302 HRESULT hr;
3304 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
3305 lcid, flags, params, result, excep_info, arg_err);
3307 if (!IsEqualIID( riid, &IID_NULL )) return DISP_E_UNKNOWNINTERFACE;
3309 if (member == DISPID_HTTPREQUEST_OPTION)
3311 VARIANT ret_value, option;
3312 UINT err_pos;
3314 if (!result) result = &ret_value;
3315 if (!arg_err) arg_err = &err_pos;
3317 VariantInit( &option );
3318 VariantInit( result );
3320 if (!flags) return S_OK;
3322 if (flags == DISPATCH_PROPERTYPUT)
3324 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
3325 if (FAILED(hr)) return hr;
3327 hr = IWinHttpRequest_put_Option( &request->IWinHttpRequest_iface, V_I4( &option ), params->rgvarg[0] );
3328 if (FAILED(hr))
3329 WARN("put_Option(%d) failed: %x\n", V_I4( &option ), hr);
3330 return hr;
3332 else if (flags & (DISPATCH_PROPERTYGET | DISPATCH_METHOD))
3334 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
3335 if (FAILED(hr)) return hr;
3337 hr = IWinHttpRequest_get_Option( &request->IWinHttpRequest_iface, V_I4( &option ), result );
3338 if (FAILED(hr))
3339 WARN("get_Option(%d) failed: %x\n", V_I4( &option ), hr);
3340 return hr;
3343 FIXME("unsupported flags %x\n", flags);
3344 return E_NOTIMPL;
3347 /* fallback to standard implementation */
3349 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
3350 if (SUCCEEDED(hr))
3352 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
3353 params, result, excep_info, arg_err );
3354 ITypeInfo_Release( typeinfo );
3356 return hr;
3359 static HRESULT WINAPI winhttp_request_SetProxy(
3360 IWinHttpRequest *iface,
3361 HTTPREQUEST_PROXY_SETTING proxy_setting,
3362 VARIANT proxy_server,
3363 VARIANT bypass_list )
3365 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3366 DWORD err = ERROR_SUCCESS;
3368 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
3369 debugstr_variant(&bypass_list));
3371 EnterCriticalSection( &request->cs );
3372 switch (proxy_setting)
3374 case HTTPREQUEST_PROXYSETTING_DEFAULT:
3375 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3376 heap_free( request->proxy.lpszProxy );
3377 heap_free( request->proxy.lpszProxyBypass );
3378 request->proxy.lpszProxy = NULL;
3379 request->proxy.lpszProxyBypass = NULL;
3380 break;
3382 case HTTPREQUEST_PROXYSETTING_DIRECT:
3383 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
3384 heap_free( request->proxy.lpszProxy );
3385 heap_free( request->proxy.lpszProxyBypass );
3386 request->proxy.lpszProxy = NULL;
3387 request->proxy.lpszProxyBypass = NULL;
3388 break;
3390 case HTTPREQUEST_PROXYSETTING_PROXY:
3391 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
3392 if (V_VT( &proxy_server ) == VT_BSTR)
3394 heap_free( request->proxy.lpszProxy );
3395 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
3397 if (V_VT( &bypass_list ) == VT_BSTR)
3399 heap_free( request->proxy.lpszProxyBypass );
3400 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
3402 break;
3404 default:
3405 err = ERROR_INVALID_PARAMETER;
3406 break;
3408 LeaveCriticalSection( &request->cs );
3409 return HRESULT_FROM_WIN32( err );
3412 static HRESULT WINAPI winhttp_request_SetCredentials(
3413 IWinHttpRequest *iface,
3414 BSTR username,
3415 BSTR password,
3416 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
3418 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3419 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
3420 DWORD err = ERROR_SUCCESS;
3422 TRACE("%p, %s, %p, 0x%08x\n", request, debugstr_w(username), password, flags);
3424 EnterCriticalSection( &request->cs );
3425 if (request->state < REQUEST_STATE_OPEN)
3427 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3428 goto done;
3430 switch (flags)
3432 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
3433 target = WINHTTP_AUTH_TARGET_SERVER;
3434 break;
3435 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
3436 target = WINHTTP_AUTH_TARGET_PROXY;
3437 break;
3438 default:
3439 err = ERROR_INVALID_PARAMETER;
3440 goto done;
3442 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
3444 err = GetLastError();
3446 done:
3447 LeaveCriticalSection( &request->cs );
3448 return HRESULT_FROM_WIN32( err );
3451 static void initialize_request( struct winhttp_request *request )
3453 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3454 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3455 request->done = CreateEventW( NULL, FALSE, FALSE, NULL );
3456 request->connect_timeout = 60000;
3457 request->send_timeout = 30000;
3458 request->receive_timeout = 30000;
3459 request->url_codepage = CP_UTF8;
3460 VariantInit( &request->data );
3461 request->state = REQUEST_STATE_INITIALIZED;
3464 static void reset_request( struct winhttp_request *request )
3466 cancel_request( request );
3467 WinHttpCloseHandle( request->hrequest );
3468 request->hrequest = NULL;
3469 WinHttpCloseHandle( request->hconnect );
3470 request->hconnect = NULL;
3471 heap_free( request->buffer );
3472 request->buffer = NULL;
3473 heap_free( request->verb );
3474 request->verb = NULL;
3475 request->offset = 0;
3476 request->bytes_available = 0;
3477 request->bytes_read = 0;
3478 request->error = ERROR_SUCCESS;
3479 request->logon_policy = 0;
3480 request->disable_feature = 0;
3481 request->async = FALSE;
3482 request->connect_timeout = 60000;
3483 request->send_timeout = 30000;
3484 request->receive_timeout = 30000;
3485 request->url_codepage = CP_UTF8;
3486 heap_free( request->proxy.lpszProxy );
3487 request->proxy.lpszProxy = NULL;
3488 heap_free( request->proxy.lpszProxyBypass );
3489 request->proxy.lpszProxyBypass = NULL;
3490 VariantClear( &request->data );
3491 request->state = REQUEST_STATE_INITIALIZED;
3494 static HRESULT WINAPI winhttp_request_Open(
3495 IWinHttpRequest *iface,
3496 BSTR method,
3497 BSTR url,
3498 VARIANT async )
3500 static const WCHAR typeW[] = {'*','/','*',0};
3501 static const WCHAR *acceptW[] = {typeW, NULL};
3502 static const WCHAR httpsW[] = {'h','t','t','p','s'};
3503 static const WCHAR user_agentW[] = {
3504 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
3505 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
3506 'R','e','q','u','e','s','t','.','5',')',0};
3507 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3508 URL_COMPONENTS uc;
3509 WCHAR *hostname, *path = NULL, *verb = NULL;
3510 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0;
3512 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
3513 debugstr_variant(&async));
3515 if (!method || !url) return E_INVALIDARG;
3517 memset( &uc, 0, sizeof(uc) );
3518 uc.dwStructSize = sizeof(uc);
3519 uc.dwSchemeLength = ~0u;
3520 uc.dwHostNameLength = ~0u;
3521 uc.dwUrlPathLength = ~0u;
3522 uc.dwExtraInfoLength = ~0u;
3523 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( GetLastError() );
3525 EnterCriticalSection( &request->cs );
3526 reset_request( request );
3528 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
3529 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
3530 hostname[uc.dwHostNameLength] = 0;
3532 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
3533 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
3534 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
3536 if (!(verb = strdupW( method ))) goto error;
3537 if (SUCCEEDED( VariantChangeType( &async, &async, 0, VT_BOOL )) && V_BOOL( &async )) request->async = TRUE;
3538 else request->async = FALSE;
3540 if (!request->hsession)
3542 if (!(request->hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL,
3543 WINHTTP_FLAG_ASYNC )))
3545 err = GetLastError();
3546 goto error;
3548 if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3550 WinHttpCloseHandle( request->hsession );
3551 request->hsession = NULL;
3552 err = GetLastError();
3553 goto error;
3556 else if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3558 err = GetLastError();
3559 goto error;
3562 len = ARRAY_SIZE( httpsW );
3563 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
3565 flags |= WINHTTP_FLAG_SECURE;
3567 if (!(request->hrequest = WinHttpOpenRequest( request->hconnect, method, path, NULL, NULL, acceptW, flags )))
3569 err = GetLastError();
3570 goto error;
3572 WinHttpSetOption( request->hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3574 request->state = REQUEST_STATE_OPEN;
3575 request->verb = verb;
3576 heap_free( hostname );
3577 heap_free( path );
3578 LeaveCriticalSection( &request->cs );
3579 return S_OK;
3581 error:
3582 WinHttpCloseHandle( request->hconnect );
3583 request->hconnect = NULL;
3584 heap_free( hostname );
3585 heap_free( path );
3586 heap_free( verb );
3587 LeaveCriticalSection( &request->cs );
3588 return HRESULT_FROM_WIN32( err );
3591 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3592 IWinHttpRequest *iface,
3593 BSTR header,
3594 BSTR value )
3596 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3597 static const WCHAR emptyW[] = {0};
3598 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3599 DWORD len, err = ERROR_SUCCESS;
3600 WCHAR *str;
3602 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3604 if (!header) return E_INVALIDARG;
3606 EnterCriticalSection( &request->cs );
3607 if (request->state < REQUEST_STATE_OPEN)
3609 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3610 goto done;
3612 if (request->state >= REQUEST_STATE_SENT)
3614 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3615 goto done;
3617 len = strlenW( header ) + 4;
3618 if (value) len += strlenW( value );
3619 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3621 err = ERROR_OUTOFMEMORY;
3622 goto done;
3624 sprintfW( str, fmtW, header, value ? value : emptyW );
3625 if (!WinHttpAddRequestHeaders( request->hrequest, str, len,
3626 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
3628 err = GetLastError();
3630 heap_free( str );
3632 done:
3633 LeaveCriticalSection( &request->cs );
3634 return HRESULT_FROM_WIN32( err );
3637 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3638 IWinHttpRequest *iface,
3639 BSTR header,
3640 BSTR *value )
3642 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3643 DWORD size, err = ERROR_SUCCESS;
3645 TRACE("%p, %p\n", request, header);
3647 EnterCriticalSection( &request->cs );
3648 if (request->state < REQUEST_STATE_SENT)
3650 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3651 goto done;
3653 if (!header || !value)
3655 err = ERROR_INVALID_PARAMETER;
3656 goto done;
3658 size = 0;
3659 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3661 err = GetLastError();
3662 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3664 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3666 err = ERROR_OUTOFMEMORY;
3667 goto done;
3669 err = ERROR_SUCCESS;
3670 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3672 err = GetLastError();
3673 SysFreeString( *value );
3675 done:
3676 LeaveCriticalSection( &request->cs );
3677 return HRESULT_FROM_WIN32( err );
3680 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3681 IWinHttpRequest *iface,
3682 BSTR *headers )
3684 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3685 DWORD size, err = ERROR_SUCCESS;
3687 TRACE("%p, %p\n", request, headers);
3689 if (!headers) return E_INVALIDARG;
3691 EnterCriticalSection( &request->cs );
3692 if (request->state < REQUEST_STATE_SENT)
3694 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3695 goto done;
3697 size = 0;
3698 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3700 err = GetLastError();
3701 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3703 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3705 err = ERROR_OUTOFMEMORY;
3706 goto done;
3708 err = ERROR_SUCCESS;
3709 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3711 err = GetLastError();
3712 SysFreeString( *headers );
3714 done:
3715 LeaveCriticalSection( &request->cs );
3716 return HRESULT_FROM_WIN32( err );
3719 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3721 struct winhttp_request *request = (struct winhttp_request *)context;
3723 switch (status)
3725 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3726 request->bytes_available = *(DWORD *)buffer;
3727 request->error = ERROR_SUCCESS;
3728 break;
3729 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3730 request->bytes_read = size;
3731 request->error = ERROR_SUCCESS;
3732 break;
3733 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3735 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3736 request->error = result->dwError;
3737 break;
3739 default: break;
3741 SetEvent( request->wait );
3744 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3746 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3747 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3750 static DWORD wait_for_completion( struct winhttp_request *request )
3752 HANDLE handles[2] = { request->wait, request->cancel };
3753 DWORD ret;
3755 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3757 case WAIT_OBJECT_0:
3758 ret = request->error;
3759 break;
3760 case WAIT_OBJECT_0 + 1:
3761 ret = request->error = ERROR_CANCELLED;
3762 SetEvent( request->done );
3763 break;
3764 default:
3765 ret = request->error = GetLastError();
3766 break;
3768 return ret;
3771 static HRESULT request_receive( struct winhttp_request *request )
3773 DWORD err, size, buflen = 4096;
3775 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3776 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3778 return HRESULT_FROM_WIN32( GetLastError() );
3780 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3781 if (!strcmpW( request->verb, headW ))
3783 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3784 return S_OK;
3786 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3787 request->buffer[0] = 0;
3788 size = 0;
3791 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3792 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3794 err = GetLastError();
3795 goto error;
3797 if ((err = wait_for_completion( request ))) goto error;
3798 if (!request->bytes_available) break;
3799 size += request->bytes_available;
3800 if (buflen < size)
3802 char *tmp;
3803 while (buflen < size) buflen *= 2;
3804 if (!(tmp = heap_realloc( request->buffer, buflen )))
3806 err = ERROR_OUTOFMEMORY;
3807 goto error;
3809 request->buffer = tmp;
3811 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3812 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3813 request->bytes_available, &request->bytes_read ))
3815 err = GetLastError();
3816 goto error;
3818 if ((err = wait_for_completion( request ))) goto error;
3819 request->offset += request->bytes_read;
3820 } while (request->bytes_read);
3822 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3823 return S_OK;
3825 error:
3826 heap_free( request->buffer );
3827 request->buffer = NULL;
3828 return HRESULT_FROM_WIN32( err );
3831 static DWORD request_set_parameters( struct winhttp_request *request )
3833 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3834 sizeof(request->proxy) )) return GetLastError();
3836 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3837 sizeof(request->logon_policy) )) return GetLastError();
3839 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3840 sizeof(request->disable_feature) )) return GetLastError();
3842 if (!WinHttpSetTimeouts( request->hrequest,
3843 request->resolve_timeout,
3844 request->connect_timeout,
3845 request->send_timeout,
3846 request->receive_timeout )) return GetLastError();
3847 return ERROR_SUCCESS;
3850 static void request_set_utf8_content_type( struct winhttp_request *request )
3852 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3853 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3854 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3855 WCHAR headerW[64];
3856 int len;
3858 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3859 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3860 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3861 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3864 static HRESULT request_send( struct winhttp_request *request )
3866 SAFEARRAY *sa = NULL;
3867 VARIANT data;
3868 char *ptr = NULL;
3869 LONG size = 0;
3870 HRESULT hr;
3871 DWORD err;
3873 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3874 if (strcmpW( request->verb, getW ))
3876 VariantInit( &data );
3877 if (V_VT( &request->data ) == VT_BSTR)
3879 UINT cp = CP_ACP;
3880 const WCHAR *str = V_BSTR( &request->data );
3881 int i, len = strlenW( str );
3883 for (i = 0; i < len; i++)
3885 if (str[i] > 127)
3887 cp = CP_UTF8;
3888 break;
3891 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3892 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3893 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3894 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3896 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3898 sa = V_ARRAY( &data );
3899 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3900 if ((hr = SafeArrayGetUBound( sa, 1, &size )) != S_OK)
3902 SafeArrayUnaccessData( sa );
3903 return hr;
3905 size++;
3908 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3909 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3911 err = GetLastError();
3912 goto error;
3914 if ((err = wait_for_completion( request ))) goto error;
3915 if (sa) SafeArrayUnaccessData( sa );
3916 else heap_free( ptr );
3917 request->state = REQUEST_STATE_SENT;
3918 return S_OK;
3920 error:
3921 if (sa) SafeArrayUnaccessData( sa );
3922 else heap_free( ptr );
3923 return HRESULT_FROM_WIN32( err );
3926 static void CALLBACK send_and_receive_proc( TP_CALLBACK_INSTANCE *instance, void *ctx )
3928 struct winhttp_request *request = (struct winhttp_request *)ctx;
3929 if (request_send( request ) == S_OK) request_receive( request );
3930 SetEvent( request->done );
3933 /* critical section must be held */
3934 static DWORD request_wait( struct winhttp_request *request, DWORD timeout )
3936 HANDLE done = request->done;
3937 DWORD err, ret;
3939 LeaveCriticalSection( &request->cs );
3940 while ((err = MsgWaitForMultipleObjects( 1, &done, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3942 MSG msg;
3943 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3945 TranslateMessage( &msg );
3946 DispatchMessageW( &msg );
3949 switch (err)
3951 case WAIT_OBJECT_0:
3952 ret = ERROR_SUCCESS;
3953 break;
3954 case WAIT_TIMEOUT:
3955 ret = ERROR_TIMEOUT;
3956 break;
3957 case WAIT_FAILED:
3958 default:
3959 ret = GetLastError();
3960 break;
3962 EnterCriticalSection( &request->cs );
3963 if (!ret) request->proc_running = FALSE;
3964 return ret;
3967 static HRESULT WINAPI winhttp_request_Send(
3968 IWinHttpRequest *iface,
3969 VARIANT body )
3971 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3972 HRESULT hr;
3974 TRACE("%p, %s\n", request, debugstr_variant(&body));
3976 EnterCriticalSection( &request->cs );
3977 if (request->state < REQUEST_STATE_OPEN)
3979 LeaveCriticalSection( &request->cs );
3980 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3982 if (request->state >= REQUEST_STATE_SENT)
3984 LeaveCriticalSection( &request->cs );
3985 return S_OK;
3987 VariantClear( &request->data );
3988 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK)
3990 LeaveCriticalSection( &request->cs );
3991 return hr;
3993 if (!TrySubmitThreadpoolCallback( send_and_receive_proc, request, NULL ))
3995 LeaveCriticalSection( &request->cs );
3996 return HRESULT_FROM_WIN32( GetLastError() );
3998 request->proc_running = TRUE;
3999 if (!request->async)
4001 hr = HRESULT_FROM_WIN32( request_wait( request, INFINITE ) );
4003 LeaveCriticalSection( &request->cs );
4004 return hr;
4007 static HRESULT WINAPI winhttp_request_get_Status(
4008 IWinHttpRequest *iface,
4009 LONG *status )
4011 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4012 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
4014 TRACE("%p, %p\n", request, status);
4016 if (!status) return E_INVALIDARG;
4018 EnterCriticalSection( &request->cs );
4019 if (request->state < REQUEST_STATE_SENT)
4021 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4022 goto done;
4024 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
4025 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
4027 err = GetLastError();
4028 goto done;
4030 *status = status_code;
4032 done:
4033 LeaveCriticalSection( &request->cs );
4034 return HRESULT_FROM_WIN32( err );
4037 static HRESULT WINAPI winhttp_request_get_StatusText(
4038 IWinHttpRequest *iface,
4039 BSTR *status )
4041 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4042 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
4044 TRACE("%p, %p\n", request, status);
4046 if (!status) return E_INVALIDARG;
4048 EnterCriticalSection( &request->cs );
4049 if (request->state < REQUEST_STATE_SENT)
4051 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4052 goto done;
4054 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
4056 err = GetLastError();
4057 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
4059 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
4061 err = ERROR_OUTOFMEMORY;
4062 goto done;
4064 index = 0;
4065 err = ERROR_SUCCESS;
4066 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
4068 err = GetLastError();
4069 SysFreeString( *status );
4071 done:
4072 LeaveCriticalSection( &request->cs );
4073 return HRESULT_FROM_WIN32( err );
4076 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
4078 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
4079 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
4080 WCHAR *buffer, *p;
4081 DWORD size;
4083 *codepage = CP_ACP;
4084 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
4085 GetLastError() == ERROR_INSUFFICIENT_BUFFER)
4087 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
4088 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
4090 return GetLastError();
4092 if ((p = strstrW( buffer, charsetW )))
4094 p += strlenW( charsetW );
4095 while (*p == ' ') p++;
4096 if (*p++ == '=')
4098 while (*p == ' ') p++;
4099 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
4102 heap_free( buffer );
4104 return ERROR_SUCCESS;
4107 static HRESULT WINAPI winhttp_request_get_ResponseText(
4108 IWinHttpRequest *iface,
4109 BSTR *body )
4111 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4112 UINT codepage;
4113 DWORD err = ERROR_SUCCESS;
4114 int len;
4116 TRACE("%p, %p\n", request, body);
4118 if (!body) return E_INVALIDARG;
4120 EnterCriticalSection( &request->cs );
4121 if (request->state < REQUEST_STATE_SENT)
4123 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4124 goto done;
4126 if ((err = request_get_codepage( request, &codepage ))) goto done;
4127 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
4128 if (!(*body = SysAllocStringLen( NULL, len )))
4130 err = ERROR_OUTOFMEMORY;
4131 goto done;
4133 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
4134 (*body)[len] = 0;
4136 done:
4137 LeaveCriticalSection( &request->cs );
4138 return HRESULT_FROM_WIN32( err );
4141 static HRESULT WINAPI winhttp_request_get_ResponseBody(
4142 IWinHttpRequest *iface,
4143 VARIANT *body )
4145 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4146 SAFEARRAY *sa;
4147 HRESULT hr;
4148 DWORD err = ERROR_SUCCESS;
4149 char *ptr;
4151 TRACE("%p, %p\n", request, body);
4153 if (!body) return E_INVALIDARG;
4155 EnterCriticalSection( &request->cs );
4156 if (request->state < REQUEST_STATE_SENT)
4158 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4159 goto done;
4161 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
4163 err = ERROR_OUTOFMEMORY;
4164 goto done;
4166 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
4168 SafeArrayDestroy( sa );
4169 LeaveCriticalSection( &request->cs );
4170 return hr;
4172 memcpy( ptr, request->buffer, request->offset );
4173 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
4175 SafeArrayDestroy( sa );
4176 LeaveCriticalSection( &request->cs );
4177 return hr;
4179 V_VT( body ) = VT_ARRAY|VT_UI1;
4180 V_ARRAY( body ) = sa;
4182 done:
4183 LeaveCriticalSection( &request->cs );
4184 return HRESULT_FROM_WIN32( err );
4187 struct stream
4189 IStream IStream_iface;
4190 LONG refs;
4191 char *data;
4192 ULARGE_INTEGER pos, size;
4195 static inline struct stream *impl_from_IStream( IStream *iface )
4197 return CONTAINING_RECORD( iface, struct stream, IStream_iface );
4200 static HRESULT WINAPI stream_QueryInterface( IStream *iface, REFIID riid, void **obj )
4202 struct stream *stream = impl_from_IStream( iface );
4204 TRACE("%p, %s, %p\n", stream, debugstr_guid(riid), obj);
4206 if (IsEqualGUID( riid, &IID_IStream ) || IsEqualGUID( riid, &IID_IUnknown ))
4208 *obj = iface;
4210 else
4212 FIXME("interface %s not implemented\n", debugstr_guid(riid));
4213 return E_NOINTERFACE;
4215 IStream_AddRef( iface );
4216 return S_OK;
4219 static ULONG WINAPI stream_AddRef( IStream *iface )
4221 struct stream *stream = impl_from_IStream( iface );
4222 return InterlockedIncrement( &stream->refs );
4225 static ULONG WINAPI stream_Release( IStream *iface )
4227 struct stream *stream = impl_from_IStream( iface );
4228 LONG refs = InterlockedDecrement( &stream->refs );
4229 if (!refs)
4231 heap_free( stream->data );
4232 heap_free( stream );
4234 return refs;
4237 static HRESULT WINAPI stream_Read( IStream *iface, void *buf, ULONG len, ULONG *read )
4239 struct stream *stream = impl_from_IStream( iface );
4240 ULONG size;
4242 if (stream->pos.QuadPart >= stream->size.QuadPart)
4244 *read = 0;
4245 return S_FALSE;
4248 size = min( stream->size.QuadPart - stream->pos.QuadPart, len );
4249 memcpy( buf, stream->data + stream->pos.QuadPart, size );
4250 stream->pos.QuadPart += size;
4251 *read = size;
4253 return S_OK;
4256 static HRESULT WINAPI stream_Write( IStream *iface, const void *buf, ULONG len, ULONG *written )
4258 FIXME("\n");
4259 return E_NOTIMPL;
4262 static HRESULT WINAPI stream_Seek( IStream *iface, LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *newpos )
4264 struct stream *stream = impl_from_IStream( iface );
4266 if (origin == STREAM_SEEK_SET)
4267 stream->pos.QuadPart = move.QuadPart;
4268 else if (origin == STREAM_SEEK_CUR)
4269 stream->pos.QuadPart += move.QuadPart;
4270 else if (origin == STREAM_SEEK_END)
4271 stream->pos.QuadPart = stream->size.QuadPart - move.QuadPart;
4273 if (newpos) newpos->QuadPart = stream->pos.QuadPart;
4274 return S_OK;
4277 static HRESULT WINAPI stream_SetSize( IStream *iface, ULARGE_INTEGER newsize )
4279 FIXME("\n");
4280 return E_NOTIMPL;
4283 static HRESULT WINAPI stream_CopyTo( IStream *iface, IStream *stream, ULARGE_INTEGER len, ULARGE_INTEGER *read,
4284 ULARGE_INTEGER *written )
4286 FIXME("\n");
4287 return E_NOTIMPL;
4290 static HRESULT WINAPI stream_Commit( IStream *iface, DWORD flags )
4292 FIXME("\n");
4293 return E_NOTIMPL;
4296 static HRESULT WINAPI stream_Revert( IStream *iface )
4298 FIXME("\n");
4299 return E_NOTIMPL;
4302 static HRESULT WINAPI stream_LockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
4304 FIXME("\n");
4305 return E_NOTIMPL;
4308 static HRESULT WINAPI stream_UnlockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
4310 FIXME("\n");
4311 return E_NOTIMPL;
4314 static HRESULT WINAPI stream_Stat( IStream *iface, STATSTG *stg, DWORD flag )
4316 FIXME("\n");
4317 return E_NOTIMPL;
4320 static HRESULT WINAPI stream_Clone( IStream *iface, IStream **stream )
4322 FIXME("\n");
4323 return E_NOTIMPL;
4326 static const IStreamVtbl stream_vtbl =
4328 stream_QueryInterface,
4329 stream_AddRef,
4330 stream_Release,
4331 stream_Read,
4332 stream_Write,
4333 stream_Seek,
4334 stream_SetSize,
4335 stream_CopyTo,
4336 stream_Commit,
4337 stream_Revert,
4338 stream_LockRegion,
4339 stream_UnlockRegion,
4340 stream_Stat,
4341 stream_Clone
4344 static HRESULT WINAPI winhttp_request_get_ResponseStream(
4345 IWinHttpRequest *iface,
4346 VARIANT *body )
4348 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4349 DWORD err = ERROR_SUCCESS;
4350 struct stream *stream;
4352 TRACE("%p, %p\n", request, body);
4354 if (!body) return E_INVALIDARG;
4356 EnterCriticalSection( &request->cs );
4357 if (request->state < REQUEST_STATE_SENT)
4359 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4360 goto done;
4362 if (!(stream = heap_alloc( sizeof(*stream) )))
4364 err = ERROR_OUTOFMEMORY;
4365 goto done;
4367 stream->IStream_iface.lpVtbl = &stream_vtbl;
4368 stream->refs = 1;
4369 if (!(stream->data = heap_alloc( request->offset )))
4371 heap_free( stream );
4372 err = ERROR_OUTOFMEMORY;
4373 goto done;
4375 memcpy( stream->data, request->buffer, request->offset );
4376 stream->pos.QuadPart = 0;
4377 stream->size.QuadPart = request->offset;
4378 V_VT( body ) = VT_UNKNOWN;
4379 V_UNKNOWN( body ) = (IUnknown *)&stream->IStream_iface;
4381 done:
4382 LeaveCriticalSection( &request->cs );
4383 return HRESULT_FROM_WIN32( err );
4386 static HRESULT WINAPI winhttp_request_get_Option(
4387 IWinHttpRequest *iface,
4388 WinHttpRequestOption option,
4389 VARIANT *value )
4391 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4392 HRESULT hr = S_OK;
4394 TRACE("%p, %u, %p\n", request, option, value);
4396 EnterCriticalSection( &request->cs );
4397 switch (option)
4399 case WinHttpRequestOption_URLCodePage:
4400 V_VT( value ) = VT_I4;
4401 V_I4( value ) = request->url_codepage;
4402 break;
4403 default:
4404 FIXME("unimplemented option %u\n", option);
4405 hr = E_NOTIMPL;
4406 break;
4408 LeaveCriticalSection( &request->cs );
4409 return hr;
4412 static HRESULT WINAPI winhttp_request_put_Option(
4413 IWinHttpRequest *iface,
4414 WinHttpRequestOption option,
4415 VARIANT value )
4417 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4418 HRESULT hr = S_OK;
4420 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
4422 EnterCriticalSection( &request->cs );
4423 switch (option)
4425 case WinHttpRequestOption_EnableRedirects:
4427 if (V_BOOL( &value ))
4428 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
4429 else
4430 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
4431 break;
4433 case WinHttpRequestOption_URLCodePage:
4435 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
4436 VARIANT cp;
4438 VariantInit( &cp );
4439 hr = VariantChangeType( &cp, &value, 0, VT_UI4 );
4440 if (SUCCEEDED( hr ))
4442 request->url_codepage = V_UI4( &cp );
4443 TRACE("URL codepage: %u\n", request->url_codepage);
4445 else if (V_VT( &value ) == VT_BSTR && !strcmpiW( V_BSTR( &value ), utf8W ))
4447 TRACE("URL codepage: UTF-8\n");
4448 request->url_codepage = CP_UTF8;
4449 hr = S_OK;
4451 else
4452 FIXME("URL codepage %s is not recognized\n", debugstr_variant( &value ));
4453 break;
4455 default:
4456 FIXME("unimplemented option %u\n", option);
4457 hr = E_NOTIMPL;
4458 break;
4460 LeaveCriticalSection( &request->cs );
4461 return hr;
4464 static HRESULT WINAPI winhttp_request_WaitForResponse(
4465 IWinHttpRequest *iface,
4466 VARIANT timeout,
4467 VARIANT_BOOL *succeeded )
4469 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4470 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
4472 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
4474 EnterCriticalSection( &request->cs );
4475 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
4477 LeaveCriticalSection( &request->cs );
4478 return S_OK;
4480 switch ((err = request_wait( request, msecs )))
4482 case ERROR_TIMEOUT:
4483 if (succeeded) *succeeded = VARIANT_FALSE;
4484 err = ERROR_SUCCESS;
4485 break;
4487 case ERROR_SUCCESS:
4488 if (succeeded) *succeeded = VARIANT_TRUE;
4489 break;
4491 default: break;
4493 LeaveCriticalSection( &request->cs );
4494 return HRESULT_FROM_WIN32( err );
4497 static HRESULT WINAPI winhttp_request_Abort(
4498 IWinHttpRequest *iface )
4500 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4502 TRACE("%p\n", request);
4504 EnterCriticalSection( &request->cs );
4505 cancel_request( request );
4506 LeaveCriticalSection( &request->cs );
4507 return S_OK;
4510 static HRESULT WINAPI winhttp_request_SetTimeouts(
4511 IWinHttpRequest *iface,
4512 LONG resolve_timeout,
4513 LONG connect_timeout,
4514 LONG send_timeout,
4515 LONG receive_timeout )
4517 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4519 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
4521 EnterCriticalSection( &request->cs );
4522 request->resolve_timeout = resolve_timeout;
4523 request->connect_timeout = connect_timeout;
4524 request->send_timeout = send_timeout;
4525 request->receive_timeout = receive_timeout;
4526 LeaveCriticalSection( &request->cs );
4527 return S_OK;
4530 static HRESULT WINAPI winhttp_request_SetClientCertificate(
4531 IWinHttpRequest *iface,
4532 BSTR certificate )
4534 FIXME("\n");
4535 return E_NOTIMPL;
4538 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
4539 IWinHttpRequest *iface,
4540 WinHttpRequestAutoLogonPolicy policy )
4542 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4543 HRESULT hr = S_OK;
4545 TRACE("%p, %u\n", request, policy );
4547 EnterCriticalSection( &request->cs );
4548 switch (policy)
4550 case AutoLogonPolicy_Always:
4551 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
4552 break;
4553 case AutoLogonPolicy_OnlyIfBypassProxy:
4554 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
4555 break;
4556 case AutoLogonPolicy_Never:
4557 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
4558 break;
4559 default: hr = E_INVALIDARG;
4560 break;
4562 LeaveCriticalSection( &request->cs );
4563 return hr;
4566 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
4568 winhttp_request_QueryInterface,
4569 winhttp_request_AddRef,
4570 winhttp_request_Release,
4571 winhttp_request_GetTypeInfoCount,
4572 winhttp_request_GetTypeInfo,
4573 winhttp_request_GetIDsOfNames,
4574 winhttp_request_Invoke,
4575 winhttp_request_SetProxy,
4576 winhttp_request_SetCredentials,
4577 winhttp_request_Open,
4578 winhttp_request_SetRequestHeader,
4579 winhttp_request_GetResponseHeader,
4580 winhttp_request_GetAllResponseHeaders,
4581 winhttp_request_Send,
4582 winhttp_request_get_Status,
4583 winhttp_request_get_StatusText,
4584 winhttp_request_get_ResponseText,
4585 winhttp_request_get_ResponseBody,
4586 winhttp_request_get_ResponseStream,
4587 winhttp_request_get_Option,
4588 winhttp_request_put_Option,
4589 winhttp_request_WaitForResponse,
4590 winhttp_request_Abort,
4591 winhttp_request_SetTimeouts,
4592 winhttp_request_SetClientCertificate,
4593 winhttp_request_SetAutoLogonPolicy
4596 HRESULT WinHttpRequest_create( void **obj )
4598 struct winhttp_request *request;
4600 TRACE("%p\n", obj);
4602 if (!(request = heap_alloc_zero( sizeof(*request) ))) return E_OUTOFMEMORY;
4603 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
4604 request->refs = 1;
4605 InitializeCriticalSection( &request->cs );
4606 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
4607 initialize_request( request );
4609 *obj = &request->IWinHttpRequest_iface;
4610 TRACE("returning iface %p\n", *obj);
4611 return S_OK;