libwine: Do not restrict base address of main thread on 64 bit mac os.
[wine.git] / dlls / winhttp / request.c
blob5525c1c0bbe14e5894482180b5f510f9d50b6761
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 BOOL process_header( struct request *request, const WCHAR *field, const WCHAR *value, DWORD flags, BOOL request_only )
403 int index;
404 struct header hdr;
406 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
408 if ((index = get_header_index( request, field, 0, request_only )) >= 0)
410 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
413 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
415 if (index >= 0)
417 delete_header( request, index );
418 if (!value || !value[0]) return TRUE;
420 else if (!(flags & WINHTTP_ADDREQ_FLAG_ADD))
422 SetLastError( ERROR_WINHTTP_HEADER_NOT_FOUND );
423 return FALSE;
426 hdr.field = (LPWSTR)field;
427 hdr.value = (LPWSTR)value;
428 hdr.is_request = request_only;
429 return insert_header( request, &hdr );
431 else if (value)
434 if ((flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON)) &&
435 index >= 0)
437 WCHAR *tmp;
438 int len, len_orig, len_value;
439 struct header *header = &request->headers[index];
441 len_orig = strlenW( header->value );
442 len_value = strlenW( value );
444 len = len_orig + len_value + 2;
445 if (!(tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) ))) return FALSE;
446 header->value = tmp;
447 header->value[len_orig++] = (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) ? ',' : ';';
448 header->value[len_orig++] = ' ';
450 memcpy( &header->value[len_orig], value, len_value * sizeof(WCHAR) );
451 header->value[len] = 0;
452 return TRUE;
454 else
456 hdr.field = (LPWSTR)field;
457 hdr.value = (LPWSTR)value;
458 hdr.is_request = request_only;
459 return insert_header( request, &hdr );
463 return TRUE;
466 BOOL add_request_headers( struct request *request, const WCHAR *headers, DWORD len, DWORD flags )
468 BOOL ret = FALSE;
469 WCHAR *buffer, *p, *q;
470 struct header *header;
472 if (len == ~0u) len = strlenW( headers );
473 if (!len) return TRUE;
474 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
475 memcpy( buffer, headers, len * sizeof(WCHAR) );
476 buffer[len] = 0;
478 p = buffer;
481 q = p;
482 while (*q)
484 if (q[0] == '\n' && q[1] == '\r')
486 q[0] = '\r';
487 q[1] = '\n';
489 if (q[0] == '\r' && q[1] == '\n') break;
490 q++;
492 if (!*p) break;
493 if (*q == '\r')
495 *q = 0;
496 q += 2; /* jump over \r\n */
498 if ((header = parse_header( p )))
500 ret = process_header( request, header->field, header->value, flags, TRUE );
501 free_header( header );
503 p = q;
504 } while (ret);
506 heap_free( buffer );
507 return ret;
510 /***********************************************************************
511 * WinHttpAddRequestHeaders (winhttp.@)
513 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
515 BOOL ret;
516 struct request *request;
518 TRACE("%p, %s, %u, 0x%08x\n", hrequest, debugstr_wn(headers, len), len, flags);
520 if (!headers || !len)
522 SetLastError( ERROR_INVALID_PARAMETER );
523 return FALSE;
525 if (!(request = (struct request *)grab_object( hrequest )))
527 SetLastError( ERROR_INVALID_HANDLE );
528 return FALSE;
530 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
532 release_object( &request->hdr );
533 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
534 return FALSE;
537 ret = add_request_headers( request, headers, len, flags );
539 release_object( &request->hdr );
540 if (ret) SetLastError( ERROR_SUCCESS );
541 return ret;
544 static WCHAR *build_absolute_request_path( struct request *request, const WCHAR **path )
546 static const WCHAR http[] = {'h','t','t','p',0};
547 static const WCHAR https[] = {'h','t','t','p','s',0};
548 static const WCHAR fmt[] = {'%','s',':','/','/','%','s',0};
549 const WCHAR *scheme;
550 WCHAR *ret;
551 int len;
553 scheme = (request->netconn ? request->netconn->secure : (request->hdr.flags & WINHTTP_FLAG_SECURE)) ? https : http;
555 len = strlenW( scheme ) + strlenW( request->connect->hostname ) + 4; /* '://' + nul */
556 if (request->connect->hostport) len += 6; /* ':' between host and port, up to 5 for port */
558 len += strlenW( request->path );
559 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
561 len = sprintfW( ret, fmt, scheme, request->connect->hostname );
562 if (request->connect->hostport)
564 static const WCHAR port_fmt[] = {':','%','u',0};
565 len += sprintfW( ret + len, port_fmt, request->connect->hostport );
567 strcpyW( ret + len, request->path );
568 if (path) *path = ret + len;
571 return ret;
574 static WCHAR *build_request_string( struct request *request )
576 static const WCHAR spaceW[] = {' ',0}, crlfW[] = {'\r','\n',0}, colonW[] = {':',' ',0};
577 static const WCHAR twocrlfW[] = {'\r','\n','\r','\n',0};
578 WCHAR *path, *ret;
579 unsigned int i, len;
581 if (!strcmpiW( request->connect->hostname, request->connect->servername )) path = request->path;
582 else if (!(path = build_absolute_request_path( request, NULL ))) return NULL;
584 len = strlenW( request->verb ) + 1 /* ' ' */;
585 len += strlenW( path ) + 1 /* ' ' */;
586 len += strlenW( request->version );
588 for (i = 0; i < request->num_headers; i++)
590 if (request->headers[i].is_request)
591 len += strlenW( request->headers[i].field ) + strlenW( request->headers[i].value ) + 4; /* '\r\n: ' */
593 len += 4; /* '\r\n\r\n' */
595 if ((ret = heap_alloc( (len + 1) * sizeof(WCHAR) )))
597 strcpyW( ret, request->verb );
598 strcatW( ret, spaceW );
599 strcatW( ret, path );
600 strcatW( ret, spaceW );
601 strcatW( ret, request->version );
603 for (i = 0; i < request->num_headers; i++)
605 if (request->headers[i].is_request)
607 strcatW( ret, crlfW );
608 strcatW( ret, request->headers[i].field );
609 strcatW( ret, colonW );
610 strcatW( ret, request->headers[i].value );
613 strcatW( ret, twocrlfW );
616 if (path != request->path) heap_free( path );
617 return ret;
620 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
622 static BOOL query_headers( struct request *request, DWORD level, const WCHAR *name, void *buffer, DWORD *buflen,
623 DWORD *index )
625 struct header *header = NULL;
626 BOOL request_only, ret = FALSE;
627 int requested_index, header_index = -1;
628 DWORD attr, len;
630 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
631 requested_index = index ? *index : 0;
633 attr = level & ~QUERY_MODIFIER_MASK;
634 switch (attr)
636 case WINHTTP_QUERY_CUSTOM:
638 header_index = get_header_index( request, name, requested_index, request_only );
639 break;
641 case WINHTTP_QUERY_RAW_HEADERS:
643 WCHAR *headers, *p, *q;
645 if (request_only)
646 headers = build_request_string( request );
647 else
648 headers = request->raw_headers;
650 if (!(p = headers)) return FALSE;
651 for (len = 0; *p; p++) if (*p != '\r') len++;
653 if (!buffer || len * sizeof(WCHAR) > *buflen)
654 SetLastError( ERROR_INSUFFICIENT_BUFFER );
655 else
657 for (p = headers, q = buffer; *p; p++, q++)
659 if (*p != '\r') *q = *p;
660 else
662 *q = 0;
663 p++; /* skip '\n' */
666 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
667 if (len) len--;
668 ret = TRUE;
670 *buflen = len * sizeof(WCHAR);
671 if (request_only) heap_free( headers );
672 return ret;
674 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
676 WCHAR *headers;
678 if (request_only)
679 headers = build_request_string( request );
680 else
681 headers = request->raw_headers;
683 if (!headers) return FALSE;
684 len = strlenW( headers ) * sizeof(WCHAR);
685 if (!buffer || len + sizeof(WCHAR) > *buflen)
687 len += sizeof(WCHAR);
688 SetLastError( ERROR_INSUFFICIENT_BUFFER );
690 else
692 memcpy( buffer, headers, len + sizeof(WCHAR) );
693 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
694 ret = TRUE;
696 *buflen = len;
697 if (request_only) heap_free( headers );
698 return ret;
700 case WINHTTP_QUERY_VERSION:
701 len = strlenW( request->version ) * sizeof(WCHAR);
702 if (!buffer || len + sizeof(WCHAR) > *buflen)
704 len += sizeof(WCHAR);
705 SetLastError( ERROR_INSUFFICIENT_BUFFER );
707 else
709 strcpyW( buffer, request->version );
710 TRACE("returning string: %s\n", debugstr_w(buffer));
711 ret = TRUE;
713 *buflen = len;
714 return ret;
716 case WINHTTP_QUERY_STATUS_TEXT:
717 len = strlenW( request->status_text ) * sizeof(WCHAR);
718 if (!buffer || len + sizeof(WCHAR) > *buflen)
720 len += sizeof(WCHAR);
721 SetLastError( ERROR_INSUFFICIENT_BUFFER );
723 else
725 strcpyW( buffer, request->status_text );
726 TRACE("returning string: %s\n", debugstr_w(buffer));
727 ret = TRUE;
729 *buflen = len;
730 return ret;
732 default:
733 if (attr >= ARRAY_SIZE(attribute_table) || !attribute_table[attr])
735 FIXME("attribute %u not implemented\n", attr);
736 return FALSE;
738 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
739 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
740 break;
743 if (header_index >= 0)
745 header = &request->headers[header_index];
747 if (!header || (request_only && !header->is_request))
749 SetLastError( ERROR_WINHTTP_HEADER_NOT_FOUND );
750 return FALSE;
752 if (level & WINHTTP_QUERY_FLAG_NUMBER)
754 if (!buffer || sizeof(int) > *buflen)
756 SetLastError( ERROR_INSUFFICIENT_BUFFER );
758 else
760 int *number = buffer;
761 *number = atoiW( header->value );
762 TRACE("returning number: %d\n", *number);
763 ret = TRUE;
765 *buflen = sizeof(int);
767 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
769 SYSTEMTIME *st = buffer;
770 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
772 SetLastError( ERROR_INSUFFICIENT_BUFFER );
774 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
776 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
777 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
778 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
780 *buflen = sizeof(SYSTEMTIME);
782 else if (header->value)
784 len = strlenW( header->value ) * sizeof(WCHAR);
785 if (!buffer || len + sizeof(WCHAR) > *buflen)
787 len += sizeof(WCHAR);
788 SetLastError( ERROR_INSUFFICIENT_BUFFER );
790 else
792 strcpyW( buffer, header->value );
793 TRACE("returning string: %s\n", debugstr_w(buffer));
794 ret = TRUE;
796 *buflen = len;
798 if (ret && index) *index += 1;
799 return ret;
802 /***********************************************************************
803 * WinHttpQueryHeaders (winhttp.@)
805 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
807 BOOL ret;
808 struct request *request;
810 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
812 if (!(request = (struct request *)grab_object( hrequest )))
814 SetLastError( ERROR_INVALID_HANDLE );
815 return FALSE;
817 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
819 release_object( &request->hdr );
820 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
821 return FALSE;
824 ret = query_headers( request, level, name, buffer, buflen, index );
826 release_object( &request->hdr );
827 if (ret) SetLastError( ERROR_SUCCESS );
828 return ret;
831 static const WCHAR basicW[] = {'B','a','s','i','c',0};
832 static const WCHAR ntlmW[] = {'N','T','L','M',0};
833 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
834 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
835 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
837 static const struct
839 const WCHAR *str;
840 unsigned int len;
841 DWORD scheme;
843 auth_schemes[] =
845 { basicW, ARRAY_SIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
846 { ntlmW, ARRAY_SIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
847 { passportW, ARRAY_SIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
848 { digestW, ARRAY_SIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
849 { negotiateW, ARRAY_SIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
852 static enum auth_scheme scheme_from_flag( DWORD flag )
854 int i;
856 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++) if (flag == auth_schemes[i].scheme) return i;
857 return SCHEME_INVALID;
860 static DWORD auth_scheme_from_header( WCHAR *header )
862 unsigned int i;
864 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++)
866 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
867 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
869 return 0;
872 static BOOL query_auth_schemes( struct request *request, DWORD level, DWORD *supported, DWORD *first )
874 DWORD index = 0, supported_schemes = 0, first_scheme = 0;
875 BOOL ret = FALSE;
877 for (;;)
879 WCHAR *buffer;
880 DWORD size, scheme;
882 size = 0;
883 query_headers( request, level, NULL, NULL, &size, &index );
884 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) break;
886 if (!(buffer = heap_alloc( size ))) return FALSE;
887 if (!query_headers( request, level, NULL, buffer, &size, &index ))
889 heap_free( buffer );
890 return FALSE;
892 scheme = auth_scheme_from_header( buffer );
893 heap_free( buffer );
894 if (!scheme) continue;
896 if (!first_scheme) first_scheme = scheme;
897 supported_schemes |= scheme;
899 ret = TRUE;
902 if (ret)
904 *supported = supported_schemes;
905 *first = first_scheme;
907 return ret;
910 /***********************************************************************
911 * WinHttpQueryAuthSchemes (winhttp.@)
913 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
915 BOOL ret = FALSE;
916 struct request *request;
918 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
920 if (!(request = (struct request *)grab_object( hrequest )))
922 SetLastError( ERROR_INVALID_HANDLE );
923 return FALSE;
925 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
927 release_object( &request->hdr );
928 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
929 return FALSE;
931 if (!supported || !first || !target)
933 release_object( &request->hdr );
934 SetLastError( ERROR_INVALID_PARAMETER );
935 return FALSE;
939 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
941 *target = WINHTTP_AUTH_TARGET_SERVER;
942 ret = TRUE;
944 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
946 *target = WINHTTP_AUTH_TARGET_PROXY;
947 ret = TRUE;
949 else SetLastError( ERROR_INVALID_OPERATION );
951 release_object( &request->hdr );
952 if (ret) SetLastError( ERROR_SUCCESS );
953 return ret;
956 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
958 UINT n = 0, x;
959 static const char base64enc[] =
960 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
962 while (len > 0)
964 /* first 6 bits, all from bin[0] */
965 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
966 x = (bin[0] & 3) << 4;
968 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
969 if (len == 1)
971 base64[n++] = base64enc[x];
972 base64[n++] = '=';
973 base64[n++] = '=';
974 break;
976 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
977 x = (bin[1] & 0x0f) << 2;
979 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
980 if (len == 2)
982 base64[n++] = base64enc[x];
983 base64[n++] = '=';
984 break;
986 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
988 /* last 6 bits, all from bin [2] */
989 base64[n++] = base64enc[bin[2] & 0x3f];
990 bin += 3;
991 len -= 3;
993 base64[n] = 0;
994 return n;
997 static inline char decode_char( WCHAR c )
999 if (c >= 'A' && c <= 'Z') return c - 'A';
1000 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1001 if (c >= '0' && c <= '9') return c - '0' + 52;
1002 if (c == '+') return 62;
1003 if (c == '/') return 63;
1004 return 64;
1007 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1009 unsigned int i = 0;
1010 char c0, c1, c2, c3;
1011 const WCHAR *p = base64;
1013 while (len > 4)
1015 if ((c0 = decode_char( p[0] )) > 63) return 0;
1016 if ((c1 = decode_char( p[1] )) > 63) return 0;
1017 if ((c2 = decode_char( p[2] )) > 63) return 0;
1018 if ((c3 = decode_char( p[3] )) > 63) return 0;
1020 if (buf)
1022 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1023 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1024 buf[i + 2] = (c2 << 6) | c3;
1026 len -= 4;
1027 i += 3;
1028 p += 4;
1030 if (p[2] == '=')
1032 if ((c0 = decode_char( p[0] )) > 63) return 0;
1033 if ((c1 = decode_char( p[1] )) > 63) return 0;
1035 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1036 i++;
1038 else if (p[3] == '=')
1040 if ((c0 = decode_char( p[0] )) > 63) return 0;
1041 if ((c1 = decode_char( p[1] )) > 63) return 0;
1042 if ((c2 = decode_char( p[2] )) > 63) return 0;
1044 if (buf)
1046 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1047 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1049 i += 2;
1051 else
1053 if ((c0 = decode_char( p[0] )) > 63) return 0;
1054 if ((c1 = decode_char( p[1] )) > 63) return 0;
1055 if ((c2 = decode_char( p[2] )) > 63) return 0;
1056 if ((c3 = decode_char( p[3] )) > 63) return 0;
1058 if (buf)
1060 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1061 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1062 buf[i + 2] = (c2 << 6) | c3;
1064 i += 3;
1066 return i;
1069 static struct authinfo *alloc_authinfo(void)
1071 struct authinfo *ret;
1073 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1075 SecInvalidateHandle( &ret->cred );
1076 SecInvalidateHandle( &ret->ctx );
1077 memset( &ret->exp, 0, sizeof(ret->exp) );
1078 ret->scheme = 0;
1079 ret->attr = 0;
1080 ret->max_token = 0;
1081 ret->data = NULL;
1082 ret->data_len = 0;
1083 ret->finished = FALSE;
1084 return ret;
1087 void destroy_authinfo( struct authinfo *authinfo )
1089 if (!authinfo) return;
1091 if (SecIsValidHandle( &authinfo->ctx ))
1092 DeleteSecurityContext( &authinfo->ctx );
1093 if (SecIsValidHandle( &authinfo->cred ))
1094 FreeCredentialsHandle( &authinfo->cred );
1096 heap_free( authinfo->data );
1097 heap_free( authinfo );
1100 static BOOL get_authvalue( struct request *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1102 DWORD size, index = 0;
1103 for (;;)
1105 size = len;
1106 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1107 if (auth_scheme_from_header( buffer ) == scheme) break;
1109 return TRUE;
1112 static BOOL do_authorization( struct request *request, DWORD target, DWORD scheme_flag )
1114 struct authinfo *authinfo, **auth_ptr;
1115 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1116 const WCHAR *auth_target, *username, *password;
1117 WCHAR auth_value[2048], *auth_reply;
1118 DWORD len = sizeof(auth_value), len_scheme, flags;
1119 BOOL ret, has_auth_value;
1121 if (scheme == SCHEME_INVALID) return FALSE;
1123 switch (target)
1125 case WINHTTP_AUTH_TARGET_SERVER:
1126 has_auth_value = get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len );
1127 auth_ptr = &request->authinfo;
1128 auth_target = attr_authorization;
1129 if (request->creds[TARGET_SERVER][scheme].username)
1131 if (scheme != SCHEME_BASIC && !has_auth_value) return FALSE;
1132 username = request->creds[TARGET_SERVER][scheme].username;
1133 password = request->creds[TARGET_SERVER][scheme].password;
1135 else
1137 if (!has_auth_value) return FALSE;
1138 username = request->connect->username;
1139 password = request->connect->password;
1141 break;
1143 case WINHTTP_AUTH_TARGET_PROXY:
1144 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1145 return FALSE;
1146 auth_ptr = &request->proxy_authinfo;
1147 auth_target = attr_proxy_authorization;
1148 if (request->creds[TARGET_PROXY][scheme].username)
1150 username = request->creds[TARGET_PROXY][scheme].username;
1151 password = request->creds[TARGET_PROXY][scheme].password;
1153 else
1155 username = request->connect->session->proxy_username;
1156 password = request->connect->session->proxy_password;
1158 break;
1160 default:
1161 WARN("unknown target %x\n", target);
1162 return FALSE;
1164 authinfo = *auth_ptr;
1166 switch (scheme)
1168 case SCHEME_BASIC:
1170 int userlen, passlen;
1172 if (!username || !password) return FALSE;
1173 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1175 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1176 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1178 authinfo->data_len = userlen + 1 + passlen;
1179 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1181 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1182 authinfo->data[userlen] = ':';
1183 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1185 authinfo->scheme = SCHEME_BASIC;
1186 authinfo->finished = TRUE;
1187 break;
1189 case SCHEME_NTLM:
1190 case SCHEME_NEGOTIATE:
1192 SECURITY_STATUS status;
1193 SecBufferDesc out_desc, in_desc;
1194 SecBuffer out, in;
1195 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1196 const WCHAR *p;
1197 BOOL first = FALSE;
1199 if (!authinfo)
1201 TimeStamp exp;
1202 SEC_WINNT_AUTH_IDENTITY_W id;
1203 WCHAR *domain, *user;
1205 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1207 first = TRUE;
1208 domain = (WCHAR *)username;
1209 user = strchrW( username, '\\' );
1211 if (user) user++;
1212 else
1214 user = (WCHAR *)username;
1215 domain = NULL;
1217 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1218 id.User = user;
1219 id.UserLength = strlenW( user );
1220 id.Domain = domain;
1221 id.DomainLength = domain ? user - domain - 1 : 0;
1222 id.Password = (WCHAR *)password;
1223 id.PasswordLength = strlenW( password );
1225 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1226 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1227 &authinfo->cred, &exp );
1228 if (status == SEC_E_OK)
1230 PSecPkgInfoW info;
1231 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1232 if (status == SEC_E_OK)
1234 authinfo->max_token = info->cbMaxToken;
1235 FreeContextBuffer( info );
1238 if (status != SEC_E_OK)
1240 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1241 debugstr_w(auth_schemes[scheme].str), status);
1242 heap_free( authinfo );
1243 return FALSE;
1245 authinfo->scheme = scheme;
1247 else if (authinfo->finished) return FALSE;
1249 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1250 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1252 ERR("authentication scheme changed from %s to %s\n",
1253 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1254 destroy_authinfo( authinfo );
1255 *auth_ptr = NULL;
1256 return FALSE;
1258 in.BufferType = SECBUFFER_TOKEN;
1259 in.cbBuffer = 0;
1260 in.pvBuffer = NULL;
1262 in_desc.ulVersion = 0;
1263 in_desc.cBuffers = 1;
1264 in_desc.pBuffers = &in;
1266 p = auth_value + auth_schemes[scheme].len;
1267 if (*p == ' ')
1269 int len = strlenW( ++p );
1270 in.cbBuffer = decode_base64( p, len, NULL );
1271 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) {
1272 destroy_authinfo( authinfo );
1273 *auth_ptr = NULL;
1274 return FALSE;
1276 decode_base64( p, len, in.pvBuffer );
1278 out.BufferType = SECBUFFER_TOKEN;
1279 out.cbBuffer = authinfo->max_token;
1280 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1282 heap_free( in.pvBuffer );
1283 destroy_authinfo( authinfo );
1284 *auth_ptr = NULL;
1285 return FALSE;
1287 out_desc.ulVersion = 0;
1288 out_desc.cBuffers = 1;
1289 out_desc.pBuffers = &out;
1291 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1292 first ? request->connect->servername : NULL, flags, 0,
1293 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1294 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1295 heap_free( in.pvBuffer );
1296 if (status == SEC_E_OK)
1298 heap_free( authinfo->data );
1299 authinfo->data = out.pvBuffer;
1300 authinfo->data_len = out.cbBuffer;
1301 authinfo->finished = TRUE;
1302 TRACE("sending last auth packet\n");
1304 else if (status == SEC_I_CONTINUE_NEEDED)
1306 heap_free( authinfo->data );
1307 authinfo->data = out.pvBuffer;
1308 authinfo->data_len = out.cbBuffer;
1309 TRACE("sending next auth packet\n");
1311 else
1313 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1314 heap_free( out.pvBuffer );
1315 destroy_authinfo( authinfo );
1316 *auth_ptr = NULL;
1317 return FALSE;
1319 break;
1321 default:
1322 ERR("invalid scheme %u\n", scheme);
1323 return FALSE;
1325 *auth_ptr = authinfo;
1327 len_scheme = auth_schemes[authinfo->scheme].len;
1328 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1329 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1331 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1332 auth_reply[len_scheme] = ' ';
1333 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1335 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1336 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1337 heap_free( auth_reply );
1338 return ret;
1341 static WCHAR *build_proxy_connect_string( struct request *request )
1343 static const WCHAR fmtW[] = {'%','s',':','%','u',0};
1344 static const WCHAR connectW[] = {'C','O','N','N','E','C','T', 0};
1345 static const WCHAR spaceW[] = {' ',0}, crlfW[] = {'\r','\n',0}, colonW[] = {':',' ',0};
1346 static const WCHAR twocrlfW[] = {'\r','\n','\r','\n',0};
1347 WCHAR *ret, *host;
1348 unsigned int i;
1349 int len;
1351 if (!(host = heap_alloc( (strlenW( request->connect->hostname ) + 7) * sizeof(WCHAR) ))) return NULL;
1352 len = sprintfW( host, fmtW, request->connect->hostname, request->connect->hostport );
1354 len += ARRAY_SIZE(connectW);
1355 len += ARRAY_SIZE(http1_1);
1357 for (i = 0; i < request->num_headers; i++)
1359 if (request->headers[i].is_request)
1360 len += strlenW( request->headers[i].field ) + strlenW( request->headers[i].value ) + 4; /* '\r\n: ' */
1362 len += 4; /* '\r\n\r\n' */
1364 if ((ret = heap_alloc( (len + 1) * sizeof(WCHAR) )))
1366 strcpyW( ret, connectW );
1367 strcatW( ret, spaceW );
1368 strcatW( ret, host );
1369 strcatW( ret, spaceW );
1370 strcatW( ret, http1_1 );
1372 for (i = 0; i < request->num_headers; i++)
1374 if (request->headers[i].is_request)
1376 strcatW( ret, crlfW );
1377 strcatW( ret, request->headers[i].field );
1378 strcatW( ret, colonW );
1379 strcatW( ret, request->headers[i].value );
1382 strcatW( ret, twocrlfW );
1385 heap_free( host );
1386 return ret;
1389 static BOOL read_reply( struct request *request );
1391 static BOOL secure_proxy_connect( struct request *request )
1393 WCHAR *str;
1394 char *strA;
1395 int len, bytes_sent;
1396 BOOL ret;
1398 if (!(str = build_proxy_connect_string( request ))) return FALSE;
1399 strA = strdupWA( str );
1400 heap_free( str );
1401 if (!strA) return FALSE;
1403 len = strlen( strA );
1404 ret = netconn_send( request->netconn, strA, len, &bytes_sent );
1405 heap_free( strA );
1406 if (ret) ret = read_reply( request );
1408 return ret;
1411 static WCHAR *addr_to_str( struct sockaddr_storage *addr )
1413 char buf[INET6_ADDRSTRLEN];
1414 void *src;
1416 switch (addr->ss_family)
1418 case AF_INET:
1419 src = &((struct sockaddr_in *)addr)->sin_addr;
1420 break;
1421 case AF_INET6:
1422 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
1423 break;
1424 default:
1425 WARN("unsupported address family %d\n", addr->ss_family);
1426 return NULL;
1428 if (!inet_ntop( addr->ss_family, src, buf, sizeof(buf) )) return NULL;
1429 return strdupAW( buf );
1432 static CRITICAL_SECTION connection_pool_cs;
1433 static CRITICAL_SECTION_DEBUG connection_pool_debug =
1435 0, 0, &connection_pool_cs,
1436 { &connection_pool_debug.ProcessLocksList, &connection_pool_debug.ProcessLocksList },
1437 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
1439 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
1441 static struct list connection_pool = LIST_INIT( connection_pool );
1443 void release_host( struct hostdata *host )
1445 LONG ref;
1447 EnterCriticalSection( &connection_pool_cs );
1448 if (!(ref = --host->ref)) list_remove( &host->entry );
1449 LeaveCriticalSection( &connection_pool_cs );
1450 if (ref) return;
1452 assert( list_empty( &host->connections ) );
1453 heap_free( host->hostname );
1454 heap_free( host );
1457 static BOOL connection_collector_running;
1459 static void CALLBACK connection_collector( TP_CALLBACK_INSTANCE *instance, void *ctx )
1461 unsigned int remaining_connections;
1462 struct netconn *netconn, *next_netconn;
1463 struct hostdata *host, *next_host;
1464 ULONGLONG now;
1468 /* FIXME: Use more sophisticated method */
1469 Sleep(5000);
1470 remaining_connections = 0;
1471 now = GetTickCount64();
1473 EnterCriticalSection(&connection_pool_cs);
1475 LIST_FOR_EACH_ENTRY_SAFE(host, next_host, &connection_pool, struct hostdata, entry)
1477 LIST_FOR_EACH_ENTRY_SAFE(netconn, next_netconn, &host->connections, struct netconn, entry)
1479 if (netconn->keep_until < now)
1481 TRACE("freeing %p\n", netconn);
1482 list_remove(&netconn->entry);
1483 netconn_close(netconn);
1485 else remaining_connections++;
1489 if (!remaining_connections) connection_collector_running = FALSE;
1491 LeaveCriticalSection(&connection_pool_cs);
1492 } while(remaining_connections);
1494 FreeLibraryWhenCallbackReturns( instance, winhttp_instance );
1497 static void cache_connection( struct netconn *netconn )
1499 TRACE( "caching connection %p\n", netconn );
1501 EnterCriticalSection( &connection_pool_cs );
1503 netconn->keep_until = GetTickCount64() + DEFAULT_KEEP_ALIVE_TIMEOUT;
1504 list_add_head( &netconn->host->connections, &netconn->entry );
1506 if (!connection_collector_running)
1508 HMODULE module;
1510 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR *)winhttp_instance, &module );
1512 if (TrySubmitThreadpoolCallback( connection_collector, NULL, NULL )) connection_collector_running = TRUE;
1513 else FreeLibrary( winhttp_instance );
1516 LeaveCriticalSection( &connection_pool_cs );
1519 static DWORD map_secure_protocols( DWORD mask )
1521 DWORD ret = 0;
1522 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL2) ret |= SP_PROT_SSL2_CLIENT;
1523 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL3) ret |= SP_PROT_SSL3_CLIENT;
1524 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1) ret |= SP_PROT_TLS1_CLIENT;
1525 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1) ret |= SP_PROT_TLS1_1_CLIENT;
1526 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2) ret |= SP_PROT_TLS1_2_CLIENT;
1527 return ret;
1530 static BOOL ensure_cred_handle( struct session *session )
1532 SECURITY_STATUS status = SEC_E_OK;
1534 if (session->cred_handle_initialized) return TRUE;
1536 EnterCriticalSection( &session->cs );
1537 if (!session->cred_handle_initialized)
1539 SCHANNEL_CRED cred;
1540 memset( &cred, 0, sizeof(cred) );
1541 cred.dwVersion = SCHANNEL_CRED_VERSION;
1542 cred.grbitEnabledProtocols = map_secure_protocols( session->secure_protocols );
1543 status = AcquireCredentialsHandleW( NULL, (WCHAR *)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL,
1544 &cred, NULL, NULL, &session->cred_handle, NULL );
1545 if (status == SEC_E_OK)
1546 session->cred_handle_initialized = TRUE;
1548 LeaveCriticalSection( &session->cs );
1550 if (status != SEC_E_OK)
1552 WARN( "AcquireCredentialsHandleW failed: 0x%08x\n", status );
1553 return FALSE;
1555 return TRUE;
1558 static BOOL open_connection( struct request *request )
1560 BOOL is_secure = request->hdr.flags & WINHTTP_FLAG_SECURE;
1561 struct hostdata *host = NULL, *iter;
1562 struct netconn *netconn = NULL;
1563 struct connect *connect;
1564 WCHAR *addressW = NULL;
1565 INTERNET_PORT port;
1566 DWORD len;
1568 if (request->netconn) goto done;
1570 connect = request->connect;
1571 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1573 EnterCriticalSection( &connection_pool_cs );
1575 LIST_FOR_EACH_ENTRY( iter, &connection_pool, struct hostdata, entry )
1577 if (iter->port == port && !strcmpW( connect->servername, iter->hostname ) && !is_secure == !iter->secure)
1579 host = iter;
1580 host->ref++;
1581 break;
1585 if (!host)
1587 if ((host = heap_alloc( sizeof(*host) )))
1589 host->ref = 1;
1590 host->secure = is_secure;
1591 host->port = port;
1592 list_init( &host->connections );
1593 if ((host->hostname = strdupW( connect->servername )))
1595 list_add_head( &connection_pool, &host->entry );
1597 else
1599 heap_free( host );
1600 host = NULL;
1605 LeaveCriticalSection( &connection_pool_cs );
1607 if (!host) return FALSE;
1609 for (;;)
1611 EnterCriticalSection( &connection_pool_cs );
1612 if (!list_empty( &host->connections ))
1614 netconn = LIST_ENTRY( list_head( &host->connections ), struct netconn, entry );
1615 list_remove( &netconn->entry );
1617 LeaveCriticalSection( &connection_pool_cs );
1618 if (!netconn) break;
1620 if (netconn_is_alive( netconn )) break;
1621 TRACE("connection %p no longer alive, closing\n", netconn);
1622 netconn_close( netconn );
1623 netconn = NULL;
1626 if (!connect->resolved && netconn)
1628 connect->sockaddr = netconn->sockaddr;
1629 connect->resolved = TRUE;
1632 if (!connect->resolved)
1634 len = strlenW( host->hostname ) + 1;
1635 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, host->hostname, len );
1637 if (!netconn_resolve( host->hostname, port, &connect->sockaddr, request->resolve_timeout ))
1639 release_host( host );
1640 return FALSE;
1642 connect->resolved = TRUE;
1644 if (!(addressW = addr_to_str( &connect->sockaddr )))
1646 release_host( host );
1647 return FALSE;
1649 len = strlenW( addressW ) + 1;
1650 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
1653 if (!netconn)
1655 if (!addressW && !(addressW = addr_to_str( &connect->sockaddr )))
1657 release_host( host );
1658 return FALSE;
1661 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
1663 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
1665 if (!(netconn = netconn_create( host, &connect->sockaddr, request->connect_timeout )))
1667 heap_free( addressW );
1668 release_host( host );
1669 return FALSE;
1671 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1672 netconn_set_timeout( netconn, FALSE, request->receive_response_timeout );
1673 if (is_secure)
1675 if (connect->session->proxy_server &&
1676 strcmpiW( connect->hostname, connect->servername ))
1678 if (!secure_proxy_connect( request ))
1680 heap_free( addressW );
1681 netconn_close( netconn );
1682 return FALSE;
1686 CertFreeCertificateContext( request->server_cert );
1687 request->server_cert = NULL;
1689 if (!ensure_cred_handle( connect->session ) ||
1690 !netconn_secure_connect( netconn, connect->hostname, request->security_flags,
1691 &connect->session->cred_handle, request->check_revocation ))
1693 heap_free( addressW );
1694 netconn_close( netconn );
1695 return FALSE;
1699 request->netconn = netconn;
1700 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
1702 else
1704 TRACE("using connection %p\n", netconn);
1706 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1707 netconn_set_timeout( netconn, FALSE, request->receive_response_timeout );
1708 request->netconn = netconn;
1711 if (netconn->secure && !(request->server_cert = netconn_get_certificate( netconn )))
1713 heap_free( addressW );
1714 netconn_close( netconn );
1715 return FALSE;
1718 done:
1719 request->read_pos = request->read_size = 0;
1720 request->read_chunked = FALSE;
1721 request->read_chunked_size = ~0u;
1722 request->read_chunked_eof = FALSE;
1723 heap_free( addressW );
1724 return TRUE;
1727 void close_connection( struct request *request )
1729 if (!request->netconn) return;
1731 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1732 netconn_close( request->netconn );
1733 request->netconn = NULL;
1734 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1737 static BOOL add_host_header( struct request *request, DWORD modifier )
1739 BOOL ret;
1740 DWORD len;
1741 WCHAR *host;
1742 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1743 struct connect *connect = request->connect;
1744 INTERNET_PORT port;
1746 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1748 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1750 return process_header( request, attr_host, connect->hostname, modifier, TRUE );
1752 len = strlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1753 if (!(host = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1754 sprintfW( host, fmt, connect->hostname, port );
1755 ret = process_header( request, attr_host, host, modifier, TRUE );
1756 heap_free( host );
1757 return ret;
1760 static void clear_response_headers( struct request *request )
1762 unsigned int i;
1764 for (i = 0; i < request->num_headers; i++)
1766 if (!request->headers[i].field) continue;
1767 if (!request->headers[i].value) continue;
1768 if (request->headers[i].is_request) continue;
1769 delete_header( request, i );
1770 i--;
1774 /* remove some amount of data from the read buffer */
1775 static void remove_data( struct request *request, int count )
1777 if (!(request->read_size -= count)) request->read_pos = 0;
1778 else request->read_pos += count;
1781 /* read some more data into the read buffer */
1782 static BOOL read_more_data( struct request *request, int maxlen, BOOL notify )
1784 int len;
1785 BOOL ret;
1787 if (request->read_chunked_eof) return FALSE;
1789 if (request->read_size && request->read_pos)
1791 /* move existing data to the start of the buffer */
1792 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1793 request->read_pos = 0;
1795 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1797 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1799 ret = netconn_recv( request->netconn, request->read_buf + request->read_size,
1800 maxlen - request->read_size, 0, &len );
1802 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &len, sizeof(len) );
1804 request->read_size += len;
1805 return ret;
1808 /* discard data contents until we reach end of line */
1809 static BOOL discard_eol( struct request *request, BOOL notify )
1813 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1814 if (eol)
1816 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1817 break;
1819 request->read_pos = request->read_size = 0; /* discard everything */
1820 if (!read_more_data( request, -1, notify )) return FALSE;
1821 } while (request->read_size);
1822 return TRUE;
1825 /* read the size of the next chunk */
1826 static BOOL start_next_chunk( struct request *request, BOOL notify )
1828 DWORD chunk_size = 0;
1830 assert(!request->read_chunked_size || request->read_chunked_size == ~0u);
1832 if (request->read_chunked_eof) return FALSE;
1834 /* read terminator for the previous chunk */
1835 if (!request->read_chunked_size && !discard_eol( request, notify )) return FALSE;
1837 for (;;)
1839 while (request->read_size)
1841 char ch = request->read_buf[request->read_pos];
1842 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1843 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1844 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1845 else if (ch == ';' || ch == '\r' || ch == '\n')
1847 TRACE("reading %u byte chunk\n", chunk_size);
1849 if (request->content_length == ~0u) request->content_length = chunk_size;
1850 else request->content_length += chunk_size;
1852 request->read_chunked_size = chunk_size;
1853 if (!chunk_size) request->read_chunked_eof = TRUE;
1855 return discard_eol( request, notify );
1857 remove_data( request, 1 );
1859 if (!read_more_data( request, -1, notify )) return FALSE;
1860 if (!request->read_size)
1862 request->content_length = request->content_read = 0;
1863 request->read_chunked_size = 0;
1864 return TRUE;
1869 static BOOL refill_buffer( struct request *request, BOOL notify )
1871 int len = sizeof(request->read_buf);
1873 if (request->read_chunked)
1875 if (request->read_chunked_eof) return FALSE;
1876 if (request->read_chunked_size == ~0u || !request->read_chunked_size)
1878 if (!start_next_chunk( request, notify )) return FALSE;
1880 len = min( len, request->read_chunked_size );
1882 else if (request->content_length != ~0u)
1884 len = min( len, request->content_length - request->content_read );
1887 if (len <= request->read_size) return TRUE;
1888 if (!read_more_data( request, len, notify )) return FALSE;
1889 if (!request->read_size) request->content_length = request->content_read = 0;
1890 return TRUE;
1893 static void finished_reading( struct request *request )
1895 static const WCHAR closeW[] = {'c','l','o','s','e',0};
1897 BOOL close = FALSE;
1898 WCHAR connection[20];
1899 DWORD size = sizeof(connection);
1901 if (!request->netconn) return;
1903 if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
1904 else if (query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
1905 query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
1907 if (!strcmpiW( connection, closeW )) close = TRUE;
1909 else if (!strcmpW( request->version, http1_0 )) close = TRUE;
1910 if (close)
1912 close_connection( request );
1913 return;
1916 cache_connection( request->netconn );
1917 request->netconn = NULL;
1920 /* return the size of data available to be read immediately */
1921 static DWORD get_available_data( struct request *request )
1923 if (request->read_chunked) return min( request->read_chunked_size, request->read_size );
1924 return request->read_size;
1927 /* check if we have reached the end of the data to read */
1928 static BOOL end_of_read_data( struct request *request )
1930 if (!request->content_length) return TRUE;
1931 if (request->read_chunked) return request->read_chunked_eof;
1932 if (request->content_length == ~0u) return FALSE;
1933 return (request->content_length == request->content_read);
1936 static BOOL read_data( struct request *request, void *buffer, DWORD size, DWORD *read, BOOL async )
1938 int count, bytes_read = 0;
1939 BOOL ret = TRUE;
1941 if (end_of_read_data( request )) goto done;
1943 while (size)
1945 if (!(count = get_available_data( request )))
1947 if (!(ret = refill_buffer( request, async ))) goto done;
1948 if (!(count = get_available_data( request ))) goto done;
1950 count = min( count, size );
1951 memcpy( (char *)buffer + bytes_read, request->read_buf + request->read_pos, count );
1952 remove_data( request, count );
1953 if (request->read_chunked) request->read_chunked_size -= count;
1954 size -= count;
1955 bytes_read += count;
1956 request->content_read += count;
1957 if (end_of_read_data( request )) goto done;
1959 if (request->read_chunked && !request->read_chunked_size) ret = refill_buffer( request, async );
1961 done:
1962 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, request->content_read, request->content_length );
1963 if (async)
1965 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
1966 else
1968 WINHTTP_ASYNC_RESULT result;
1969 result.dwResult = API_READ_DATA;
1970 result.dwError = GetLastError();
1971 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
1975 if (ret && read) *read = bytes_read;
1976 if (end_of_read_data( request )) finished_reading( request );
1977 return ret;
1980 /* read any content returned by the server so that the connection can be reused */
1981 static void drain_content( struct request *request )
1983 DWORD size, bytes_read, bytes_total = 0, bytes_left = request->content_length - request->content_read;
1984 char buffer[2048];
1986 refill_buffer( request, FALSE );
1987 for (;;)
1989 if (request->read_chunked) size = sizeof(buffer);
1990 else
1992 if (bytes_total >= bytes_left) return;
1993 size = min( sizeof(buffer), bytes_left - bytes_total );
1995 if (!read_data( request, buffer, size, &bytes_read, FALSE ) || !bytes_read) return;
1996 bytes_total += bytes_read;
2000 enum escape_flags
2002 ESCAPE_FLAG_NON_PRINTABLE = 0x01,
2003 ESCAPE_FLAG_SPACE = 0x02,
2004 ESCAPE_FLAG_PERCENT = 0x04,
2005 ESCAPE_FLAG_UNSAFE = 0x08,
2006 ESCAPE_FLAG_DEL = 0x10,
2007 ESCAPE_FLAG_8BIT = 0x20,
2008 ESCAPE_FLAG_STRIP_CRLF = 0x40,
2011 #define ESCAPE_MASK_DEFAULT (ESCAPE_FLAG_NON_PRINTABLE | ESCAPE_FLAG_SPACE | ESCAPE_FLAG_UNSAFE |\
2012 ESCAPE_FLAG_DEL | ESCAPE_FLAG_8BIT)
2013 #define ESCAPE_MASK_PERCENT (ESCAPE_FLAG_PERCENT | ESCAPE_MASK_DEFAULT)
2014 #define ESCAPE_MASK_DISABLE (ESCAPE_FLAG_SPACE | ESCAPE_FLAG_8BIT | ESCAPE_FLAG_STRIP_CRLF)
2016 static inline BOOL need_escape( char ch, enum escape_flags flags )
2018 static const char unsafe[] = "\"#<>[\\]^`{|}";
2019 const char *ptr = unsafe;
2021 if ((flags & ESCAPE_FLAG_SPACE) && ch == ' ') return TRUE;
2022 if ((flags & ESCAPE_FLAG_PERCENT) && ch == '%') return TRUE;
2023 if ((flags & ESCAPE_FLAG_NON_PRINTABLE) && ch < 0x20) return TRUE;
2024 if ((flags & ESCAPE_FLAG_DEL) && ch == 0x7f) return TRUE;
2025 if ((flags & ESCAPE_FLAG_8BIT) && (ch & 0x80)) return TRUE;
2026 if ((flags & ESCAPE_FLAG_UNSAFE)) while (*ptr) { if (ch == *ptr++) return TRUE; }
2027 return FALSE;
2030 static DWORD escape_string( const char *src, DWORD len, char *dst, enum escape_flags flags )
2032 static const char hex[] = "0123456789ABCDEF";
2033 DWORD i, ret = len;
2034 char *ptr = dst;
2036 for (i = 0; i < len; i++)
2038 if ((flags & ESCAPE_FLAG_STRIP_CRLF) && (src[i] == '\r' || src[i] == '\n'))
2040 ret--;
2041 continue;
2043 if (need_escape( src[i], flags ))
2045 if (dst)
2047 ptr[0] = '%';
2048 ptr[1] = hex[(src[i] >> 4) & 0xf];
2049 ptr[2] = hex[src[i] & 0xf];
2050 ptr += 3;
2052 ret += 2;
2054 else if (dst) *ptr++ = src[i];
2057 if (dst) dst[ret] = 0;
2058 return ret;
2061 static DWORD str_to_wire( const WCHAR *src, int src_len, char *dst, enum escape_flags flags )
2063 DWORD len;
2064 char *utf8;
2066 if (src_len < 0) src_len = strlenW( src );
2067 len = WideCharToMultiByte( CP_UTF8, 0, src, src_len, NULL, 0, NULL, NULL );
2068 if (!(utf8 = heap_alloc( len ))) return 0;
2070 WideCharToMultiByte( CP_UTF8, 0, src, -1, utf8, len, NULL, NULL );
2071 len = escape_string( utf8, len, dst, flags );
2072 heap_free( utf8 );
2074 return len;
2077 static char *build_wire_path( struct request *request, DWORD *ret_len )
2079 WCHAR *full_path;
2080 const WCHAR *start, *path, *query = NULL;
2081 DWORD len, len_path = 0, len_query = 0;
2082 enum escape_flags path_flags, query_flags;
2083 char *ret;
2085 if (!strcmpiW( request->connect->hostname, request->connect->servername )) start = full_path = request->path;
2086 else if (!(full_path = build_absolute_request_path( request, &start ))) return NULL;
2088 len = strlenW( full_path );
2089 if ((path = strchrW( start, '/' )))
2091 len_path = strlenW( path );
2092 if ((query = strchrW( path, '?' )))
2094 len_query = strlenW( query );
2095 len_path -= len_query;
2099 if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_DISABLE) path_flags = ESCAPE_MASK_DISABLE;
2100 else if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_PERCENT) path_flags = ESCAPE_MASK_PERCENT;
2101 else path_flags = ESCAPE_MASK_DEFAULT;
2103 if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_DISABLE_QUERY) query_flags = ESCAPE_MASK_DISABLE;
2104 else query_flags = path_flags;
2106 *ret_len = str_to_wire( full_path, len - len_path - len_query, NULL, 0 );
2107 if (path) *ret_len += str_to_wire( path, len_path, NULL, path_flags );
2108 if (query) *ret_len += str_to_wire( query, len_query, NULL, query_flags );
2110 if ((ret = heap_alloc( *ret_len + 1 )))
2112 len = str_to_wire( full_path, len - len_path - len_query, ret, 0 );
2113 if (path) len += str_to_wire( path, len_path, ret + len, path_flags );
2114 if (query) str_to_wire( query, len_query, ret + len, query_flags );
2117 if (full_path != request->path) heap_free( full_path );
2118 return ret;
2121 static char *build_wire_request( struct request *request, DWORD *len )
2123 char *path, *ptr, *ret;
2124 DWORD i, len_path;
2126 if (!(path = build_wire_path( request, &len_path ))) return NULL;
2128 *len = str_to_wire( request->verb, -1, NULL, 0 ) + 1; /* ' ' */
2129 *len += len_path + 1; /* ' ' */
2130 *len += str_to_wire( request->version, -1, NULL, 0 );
2132 for (i = 0; i < request->num_headers; i++)
2134 if (request->headers[i].is_request)
2136 *len += str_to_wire( request->headers[i].field, -1, NULL, 0 ) + 2; /* ': ' */
2137 *len += str_to_wire( request->headers[i].value, -1, NULL, 0 ) + 2; /* '\r\n' */
2140 *len += 4; /* '\r\n\r\n' */
2142 if ((ret = ptr = heap_alloc( *len + 1 )))
2144 ptr += str_to_wire( request->verb, -1, ptr, 0 );
2145 *ptr++ = ' ';
2146 memcpy( ptr, path, len_path );
2147 ptr += len_path;
2148 *ptr++ = ' ';
2149 ptr += str_to_wire( request->version, -1, ptr, 0 );
2151 for (i = 0; i < request->num_headers; i++)
2153 if (request->headers[i].is_request)
2155 *ptr++ = '\r';
2156 *ptr++ = '\n';
2157 ptr += str_to_wire( request->headers[i].field, -1, ptr, 0 );
2158 *ptr++ = ':';
2159 *ptr++ = ' ';
2160 ptr += str_to_wire( request->headers[i].value, -1, ptr, 0 );
2163 memcpy( ptr, "\r\n\r\n", sizeof("\r\n\r\n") );
2166 heap_free( path );
2167 return ret;
2170 static BOOL send_request( struct request *request, const WCHAR *headers, DWORD headers_len, void *optional,
2171 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
2173 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
2174 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
2175 static const WCHAR length_fmt[] = {'%','l','d',0};
2177 BOOL ret = FALSE;
2178 struct connect *connect = request->connect;
2179 struct session *session = connect->session;
2180 char *wire_req;
2181 int bytes_sent;
2182 DWORD len;
2184 clear_response_headers( request );
2185 drain_content( request );
2187 if (session->agent)
2188 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2190 if (connect->hostname)
2191 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
2193 if (request->creds[TARGET_SERVER][SCHEME_BASIC].username)
2194 do_authorization( request, WINHTTP_AUTH_TARGET_SERVER, WINHTTP_AUTH_SCHEME_BASIC );
2196 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
2198 WCHAR length[21]; /* decimal long int + null */
2199 sprintfW( length, length_fmt, total_len );
2200 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2202 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
2204 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2206 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
2208 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2209 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2211 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
2213 TRACE("failed to add request headers\n");
2214 return FALSE;
2216 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
2218 WARN("failed to add cookie headers\n");
2219 return FALSE;
2222 if (context) request->hdr.context = context;
2224 if (!(ret = open_connection( request ))) goto end;
2225 if (!(wire_req = build_wire_request( request, &len ))) goto end;
2226 TRACE("full request: %s\n", debugstr_a(wire_req));
2228 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
2230 ret = netconn_send( request->netconn, wire_req, len, &bytes_sent );
2231 heap_free( wire_req );
2232 if (!ret) goto end;
2234 if (optional_len)
2236 if (!netconn_send( request->netconn, optional, optional_len, &bytes_sent )) goto end;
2237 request->optional = optional;
2238 request->optional_len = optional_len;
2239 len += optional_len;
2241 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(len) );
2243 end:
2244 if (async)
2246 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
2247 else
2249 WINHTTP_ASYNC_RESULT result;
2250 result.dwResult = API_SEND_REQUEST;
2251 result.dwError = GetLastError();
2252 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2255 return ret;
2258 static void task_send_request( struct task_header *task )
2260 struct send_request *s = (struct send_request *)task;
2261 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
2262 heap_free( s->headers );
2265 /***********************************************************************
2266 * WinHttpSendRequest (winhttp.@)
2268 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
2269 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
2271 BOOL ret;
2272 struct request *request;
2274 TRACE("%p, %s, %u, %u, %u, %lx\n", hrequest, debugstr_wn(headers, headers_len), headers_len, optional_len,
2275 total_len, context);
2277 if (!(request = (struct request *)grab_object( hrequest )))
2279 SetLastError( ERROR_INVALID_HANDLE );
2280 return FALSE;
2282 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2284 release_object( &request->hdr );
2285 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2286 return FALSE;
2289 if (headers && !headers_len) headers_len = strlenW( headers );
2291 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2293 struct send_request *s;
2295 if (!(s = heap_alloc( sizeof(struct send_request) ))) return FALSE;
2296 s->hdr.request = request;
2297 s->hdr.proc = task_send_request;
2298 s->headers = strdupW( headers );
2299 s->headers_len = headers_len;
2300 s->optional = optional;
2301 s->optional_len = optional_len;
2302 s->total_len = total_len;
2303 s->context = context;
2305 addref_object( &request->hdr );
2306 ret = queue_task( (struct task_header *)s );
2308 else
2309 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
2311 release_object( &request->hdr );
2312 if (ret) SetLastError( ERROR_SUCCESS );
2313 return ret;
2316 static BOOL set_credentials( struct request *request, DWORD target, DWORD scheme_flag, const WCHAR *username,
2317 const WCHAR *password )
2319 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
2321 if (scheme == SCHEME_INVALID || ((scheme == SCHEME_BASIC || scheme == SCHEME_DIGEST) && (!username || !password)))
2323 SetLastError( ERROR_INVALID_PARAMETER );
2324 return FALSE;
2326 switch (target)
2328 case WINHTTP_AUTH_TARGET_SERVER:
2330 heap_free( request->creds[TARGET_SERVER][scheme].username );
2331 if (!username) request->creds[TARGET_SERVER][scheme].username = NULL;
2332 else if (!(request->creds[TARGET_SERVER][scheme].username = strdupW( username ))) return FALSE;
2334 heap_free( request->creds[TARGET_SERVER][scheme].password );
2335 if (!password) request->creds[TARGET_SERVER][scheme].password = NULL;
2336 else if (!(request->creds[TARGET_SERVER][scheme].password = strdupW( password ))) return FALSE;
2337 break;
2339 case WINHTTP_AUTH_TARGET_PROXY:
2341 heap_free( request->creds[TARGET_PROXY][scheme].username );
2342 if (!username) request->creds[TARGET_PROXY][scheme].username = NULL;
2343 else if (!(request->creds[TARGET_PROXY][scheme].username = strdupW( username ))) return FALSE;
2345 heap_free( request->creds[TARGET_PROXY][scheme].password );
2346 if (!password) request->creds[TARGET_PROXY][scheme].password = NULL;
2347 else if (!(request->creds[TARGET_PROXY][scheme].password = strdupW( password ))) return FALSE;
2348 break;
2350 default:
2351 WARN("unknown target %u\n", target);
2352 return FALSE;
2354 return TRUE;
2357 /***********************************************************************
2358 * WinHttpSetCredentials (winhttp.@)
2360 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
2361 LPCWSTR password, LPVOID params )
2363 BOOL ret;
2364 struct request *request;
2366 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
2368 if (!(request = (struct request *)grab_object( hrequest )))
2370 SetLastError( ERROR_INVALID_HANDLE );
2371 return FALSE;
2373 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2375 release_object( &request->hdr );
2376 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2377 return FALSE;
2380 ret = set_credentials( request, target, scheme, username, password );
2382 release_object( &request->hdr );
2383 if (ret) SetLastError( ERROR_SUCCESS );
2384 return ret;
2387 static BOOL handle_authorization( struct request *request, DWORD status )
2389 DWORD i, schemes, first, level, target;
2391 switch (status)
2393 case HTTP_STATUS_DENIED:
2394 target = WINHTTP_AUTH_TARGET_SERVER;
2395 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
2396 break;
2398 case HTTP_STATUS_PROXY_AUTH_REQ:
2399 target = WINHTTP_AUTH_TARGET_PROXY;
2400 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
2401 break;
2403 default:
2404 WARN("unhandled status %u\n", status);
2405 return FALSE;
2408 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
2409 if (do_authorization( request, target, first )) return TRUE;
2411 schemes &= ~first;
2412 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++)
2414 if (!(schemes & auth_schemes[i].scheme)) continue;
2415 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
2417 return FALSE;
2420 /* set the request content length based on the headers */
2421 static DWORD set_content_length( struct request *request, DWORD status )
2423 WCHAR encoding[20];
2424 DWORD buflen = sizeof(request->content_length);
2426 if (status == HTTP_STATUS_NO_CONTENT || status == HTTP_STATUS_NOT_MODIFIED || !strcmpW( request->verb, headW ))
2427 request->content_length = 0;
2428 else
2430 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
2431 NULL, &request->content_length, &buflen, NULL ))
2432 request->content_length = ~0u;
2434 buflen = sizeof(encoding);
2435 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
2436 !strcmpiW( encoding, chunkedW ))
2438 request->content_length = ~0u;
2439 request->read_chunked = TRUE;
2440 request->read_chunked_size = ~0u;
2441 request->read_chunked_eof = FALSE;
2444 request->content_read = 0;
2445 return request->content_length;
2448 static BOOL read_line( struct request *request, char *buffer, DWORD *len )
2450 int count, bytes_read, pos = 0;
2452 for (;;)
2454 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
2455 if (eol)
2457 count = eol - (request->read_buf + request->read_pos);
2458 bytes_read = count + 1;
2460 else count = bytes_read = request->read_size;
2462 count = min( count, *len - pos );
2463 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
2464 pos += count;
2465 remove_data( request, bytes_read );
2466 if (eol) break;
2468 if (!read_more_data( request, -1, TRUE )) return FALSE;
2469 if (!request->read_size)
2471 *len = 0;
2472 TRACE("returning empty string\n");
2473 return FALSE;
2476 if (pos < *len)
2478 if (pos && buffer[pos - 1] == '\r') pos--;
2479 *len = pos + 1;
2481 buffer[*len - 1] = 0;
2482 TRACE("returning %s\n", debugstr_a(buffer));
2483 return TRUE;
2486 #define MAX_REPLY_LEN 1460
2487 #define INITIAL_HEADER_BUFFER_LEN 512
2489 static BOOL read_reply( struct request *request )
2491 static const WCHAR crlf[] = {'\r','\n',0};
2493 char buffer[MAX_REPLY_LEN];
2494 DWORD buflen, len, offset, crlf_len = 2; /* strlenW(crlf) */
2495 char *status_code, *status_text;
2496 WCHAR *versionW, *status_textW, *raw_headers;
2497 WCHAR status_codeW[4]; /* sizeof("nnn") */
2499 if (!request->netconn) return FALSE;
2503 buflen = MAX_REPLY_LEN;
2504 if (!read_line( request, buffer, &buflen )) return FALSE;
2506 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2507 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
2508 status_code++;
2509 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
2510 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
2511 status_text++;
2513 TRACE("version [%s] status code [%s] status text [%s]\n",
2514 debugstr_an(buffer, status_code - buffer - 1),
2515 debugstr_an(status_code, len),
2516 debugstr_a(status_text));
2518 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
2520 /* we rely on the fact that the protocol is ascii */
2521 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2522 status_codeW[len] = 0;
2523 if (!(process_header( request, attr_status, status_codeW,
2524 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE, FALSE )))
2525 return FALSE;
2527 len = status_code - buffer;
2528 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2529 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2530 versionW[len - 1] = 0;
2532 heap_free( request->version );
2533 request->version = versionW;
2535 len = buflen - (status_text - buffer);
2536 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2537 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2539 heap_free( request->status_text );
2540 request->status_text = status_textW;
2542 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2543 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2544 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2545 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2547 heap_free( request->raw_headers );
2548 request->raw_headers = raw_headers;
2550 offset = buflen + crlf_len - 1;
2551 for (;;)
2553 struct header *header;
2555 buflen = MAX_REPLY_LEN;
2556 if (!read_line( request, buffer, &buflen )) return TRUE;
2557 if (!*buffer) buflen = 1;
2559 while (len - offset < buflen + crlf_len)
2561 WCHAR *tmp;
2562 len *= 2;
2563 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2564 request->raw_headers = raw_headers = tmp;
2566 if (!*buffer)
2568 memcpy( raw_headers + offset, crlf, sizeof(crlf) );
2569 break;
2571 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2573 if (!(header = parse_header( raw_headers + offset ))) break;
2574 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2576 free_header( header );
2577 break;
2579 free_header( header );
2580 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2581 offset += buflen + crlf_len - 1;
2584 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2585 return TRUE;
2588 static void record_cookies( struct request *request )
2590 unsigned int i;
2592 for (i = 0; i < request->num_headers; i++)
2594 struct header *set_cookie = &request->headers[i];
2595 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2597 set_cookies( request, set_cookie->value );
2602 static WCHAR *get_redirect_url( struct request *request, DWORD *len )
2604 DWORD size;
2605 WCHAR *ret;
2607 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2608 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2609 if (!(ret = heap_alloc( size ))) return NULL;
2610 *len = size / sizeof(WCHAR) - 1;
2611 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2612 heap_free( ret );
2613 return NULL;
2616 static BOOL handle_redirect( struct request *request, DWORD status )
2618 BOOL ret = FALSE;
2619 DWORD len, len_loc;
2620 URL_COMPONENTS uc;
2621 struct connect *connect = request->connect;
2622 INTERNET_PORT port;
2623 WCHAR *hostname = NULL, *location;
2624 int index;
2626 if (!(location = get_redirect_url( request, &len_loc ))) return FALSE;
2628 memset( &uc, 0, sizeof(uc) );
2629 uc.dwStructSize = sizeof(uc);
2630 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2632 if (!WinHttpCrackUrl( location, len_loc, 0, &uc )) /* assume relative redirect */
2634 WCHAR *path, *p;
2636 if (location[0] == '/')
2638 if (!(path = heap_alloc( (len_loc + 1) * sizeof(WCHAR) ))) goto end;
2639 memcpy( path, location, len_loc * sizeof(WCHAR) );
2640 path[len_loc] = 0;
2642 else
2644 if ((p = strrchrW( request->path, '/' ))) *p = 0;
2645 len = strlenW( request->path ) + 1 + len_loc;
2646 if (!(path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2647 strcpyW( path, request->path );
2648 strcatW( path, slashW );
2649 memcpy( path + strlenW(path), location, len_loc * sizeof(WCHAR) );
2650 path[len_loc] = 0;
2652 heap_free( request->path );
2653 request->path = path;
2655 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_loc + 1 );
2657 else
2659 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2661 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2662 TRACE("redirect from secure page to non-secure page\n");
2663 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2665 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2667 TRACE("redirect from non-secure page to secure page\n");
2668 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2671 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_loc + 1 );
2673 len = uc.dwHostNameLength;
2674 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2675 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2676 hostname[len] = 0;
2678 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2679 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2681 heap_free( connect->hostname );
2682 connect->hostname = hostname;
2683 connect->hostport = port;
2684 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2686 netconn_close( request->netconn );
2687 request->netconn = NULL;
2688 request->content_length = request->content_read = 0;
2689 request->read_pos = request->read_size = 0;
2690 request->read_chunked = request->read_chunked_eof = FALSE;
2692 else heap_free( hostname );
2694 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2695 if (!(ret = open_connection( request ))) goto end;
2697 heap_free( request->path );
2698 request->path = NULL;
2699 if (uc.dwUrlPathLength)
2701 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2702 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2703 memcpy( request->path, uc.lpszUrlPath, (len + 1) * sizeof(WCHAR) );
2704 request->path[len] = 0;
2706 else request->path = strdupW( slashW );
2709 /* remove content-type/length headers */
2710 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2711 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2713 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2715 heap_free( request->verb );
2716 request->verb = strdupW( getW );
2717 request->optional = NULL;
2718 request->optional_len = 0;
2720 ret = TRUE;
2722 end:
2723 heap_free( location );
2724 return ret;
2727 static BOOL receive_response( struct request *request, BOOL async )
2729 BOOL ret;
2730 DWORD size, query, status;
2732 if (!request->netconn)
2734 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_STATE );
2735 return FALSE;
2738 netconn_set_timeout( request->netconn, FALSE, request->receive_response_timeout );
2739 for (;;)
2741 if (!(ret = read_reply( request )))
2743 SetLastError( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2744 break;
2746 size = sizeof(DWORD);
2747 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2748 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2750 set_content_length( request, status );
2752 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2754 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2756 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2757 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2759 if (!(ret = handle_redirect( request, status ))) break;
2761 /* recurse synchronously */
2762 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2764 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2766 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2768 if (!handle_authorization( request, status )) break;
2770 /* recurse synchronously */
2771 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2773 break;
2776 netconn_set_timeout( request->netconn, FALSE, request->receive_timeout );
2777 if (request->content_length) ret = refill_buffer( request, FALSE );
2779 if (async)
2781 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2782 else
2784 WINHTTP_ASYNC_RESULT result;
2785 result.dwResult = API_RECEIVE_RESPONSE;
2786 result.dwError = GetLastError();
2787 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2790 return ret;
2793 static void task_receive_response( struct task_header *task )
2795 struct receive_response *r = (struct receive_response *)task;
2796 receive_response( r->hdr.request, TRUE );
2799 /***********************************************************************
2800 * WinHttpReceiveResponse (winhttp.@)
2802 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2804 BOOL ret;
2805 struct request *request;
2807 TRACE("%p, %p\n", hrequest, reserved);
2809 if (!(request = (struct request *)grab_object( hrequest )))
2811 SetLastError( ERROR_INVALID_HANDLE );
2812 return FALSE;
2814 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2816 release_object( &request->hdr );
2817 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2818 return FALSE;
2821 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2823 struct receive_response *r;
2825 if (!(r = heap_alloc( sizeof(struct receive_response) ))) return FALSE;
2826 r->hdr.request = request;
2827 r->hdr.proc = task_receive_response;
2829 addref_object( &request->hdr );
2830 ret = queue_task( (struct task_header *)r );
2832 else
2833 ret = receive_response( request, FALSE );
2835 release_object( &request->hdr );
2836 if (ret) SetLastError( ERROR_SUCCESS );
2837 return ret;
2840 static BOOL query_data_available( struct request *request, DWORD *available, BOOL async )
2842 DWORD count = 0;
2843 BOOL ret = TRUE;
2845 if (end_of_read_data( request )) goto done;
2847 count = get_available_data( request );
2848 if (!request->read_chunked && request->netconn) count += netconn_query_data_available( request->netconn );
2849 if (!count)
2851 if (!(ret = refill_buffer( request, async ))) goto done;
2852 count = get_available_data( request );
2853 if (!request->read_chunked && request->netconn) count += netconn_query_data_available( request->netconn );
2856 done:
2857 TRACE("%u bytes available\n", count);
2858 if (async)
2860 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2861 else
2863 WINHTTP_ASYNC_RESULT result;
2864 result.dwResult = API_QUERY_DATA_AVAILABLE;
2865 result.dwError = GetLastError();
2866 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2870 if (ret && available) *available = count;
2871 return ret;
2874 static void task_query_data_available( struct task_header *task )
2876 struct query_data *q = (struct query_data *)task;
2877 query_data_available( q->hdr.request, q->available, TRUE );
2880 /***********************************************************************
2881 * WinHttpQueryDataAvailable (winhttp.@)
2883 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2885 BOOL ret;
2886 struct request *request;
2888 TRACE("%p, %p\n", hrequest, available);
2890 if (!(request = (struct request *)grab_object( hrequest )))
2892 SetLastError( ERROR_INVALID_HANDLE );
2893 return FALSE;
2895 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2897 release_object( &request->hdr );
2898 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2899 return FALSE;
2902 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2904 struct query_data *q;
2906 if (!(q = heap_alloc( sizeof(struct query_data) ))) return FALSE;
2907 q->hdr.request = request;
2908 q->hdr.proc = task_query_data_available;
2909 q->available = available;
2911 addref_object( &request->hdr );
2912 ret = queue_task( (struct task_header *)q );
2914 else
2915 ret = query_data_available( request, available, FALSE );
2917 release_object( &request->hdr );
2918 if (ret) SetLastError( ERROR_SUCCESS );
2919 return ret;
2922 static void task_read_data( struct task_header *task )
2924 struct read_data *r = (struct read_data *)task;
2925 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2928 /***********************************************************************
2929 * WinHttpReadData (winhttp.@)
2931 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2933 BOOL ret;
2934 struct request *request;
2936 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2938 if (!(request = (struct request *)grab_object( hrequest )))
2940 SetLastError( ERROR_INVALID_HANDLE );
2941 return FALSE;
2943 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2945 release_object( &request->hdr );
2946 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2947 return FALSE;
2950 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2952 struct read_data *r;
2954 if (!(r = heap_alloc( sizeof(struct read_data) ))) return FALSE;
2955 r->hdr.request = request;
2956 r->hdr.proc = task_read_data;
2957 r->buffer = buffer;
2958 r->to_read = to_read;
2959 r->read = read;
2961 addref_object( &request->hdr );
2962 ret = queue_task( (struct task_header *)r );
2964 else
2965 ret = read_data( request, buffer, to_read, read, FALSE );
2967 release_object( &request->hdr );
2968 if (ret) SetLastError( ERROR_SUCCESS );
2969 return ret;
2972 static BOOL write_data( struct request *request, const void *buffer, DWORD to_write, DWORD *written, BOOL async )
2974 BOOL ret;
2975 int num_bytes;
2977 ret = netconn_send( request->netconn, buffer, to_write, &num_bytes );
2979 if (async)
2981 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
2982 else
2984 WINHTTP_ASYNC_RESULT result;
2985 result.dwResult = API_WRITE_DATA;
2986 result.dwError = GetLastError();
2987 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2990 if (ret && written) *written = num_bytes;
2991 return ret;
2994 static void task_write_data( struct task_header *task )
2996 struct write_data *w = (struct write_data *)task;
2997 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
3000 /***********************************************************************
3001 * WinHttpWriteData (winhttp.@)
3003 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
3005 BOOL ret;
3006 struct request *request;
3008 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
3010 if (!(request = (struct request *)grab_object( hrequest )))
3012 SetLastError( ERROR_INVALID_HANDLE );
3013 return FALSE;
3015 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
3017 release_object( &request->hdr );
3018 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
3019 return FALSE;
3022 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
3024 struct write_data *w;
3026 if (!(w = heap_alloc( sizeof(struct write_data) ))) return FALSE;
3027 w->hdr.request = request;
3028 w->hdr.proc = task_write_data;
3029 w->buffer = buffer;
3030 w->to_write = to_write;
3031 w->written = written;
3033 addref_object( &request->hdr );
3034 ret = queue_task( (struct task_header *)w );
3036 else
3037 ret = write_data( request, buffer, to_write, written, FALSE );
3039 release_object( &request->hdr );
3040 if (ret) SetLastError( ERROR_SUCCESS );
3041 return ret;
3044 enum request_state
3046 REQUEST_STATE_INITIALIZED,
3047 REQUEST_STATE_CANCELLED,
3048 REQUEST_STATE_OPEN,
3049 REQUEST_STATE_SENT,
3050 REQUEST_STATE_RESPONSE_RECEIVED
3053 struct winhttp_request
3055 IWinHttpRequest IWinHttpRequest_iface;
3056 LONG refs;
3057 CRITICAL_SECTION cs;
3058 enum request_state state;
3059 HINTERNET hsession;
3060 HINTERNET hconnect;
3061 HINTERNET hrequest;
3062 VARIANT data;
3063 WCHAR *verb;
3064 HANDLE done;
3065 HANDLE wait;
3066 HANDLE cancel;
3067 BOOL proc_running;
3068 char *buffer;
3069 DWORD offset;
3070 DWORD bytes_available;
3071 DWORD bytes_read;
3072 DWORD error;
3073 DWORD logon_policy;
3074 DWORD disable_feature;
3075 LONG resolve_timeout;
3076 LONG connect_timeout;
3077 LONG send_timeout;
3078 LONG receive_timeout;
3079 WINHTTP_PROXY_INFO proxy;
3080 BOOL async;
3081 UINT url_codepage;
3084 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
3086 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
3089 static ULONG WINAPI winhttp_request_AddRef(
3090 IWinHttpRequest *iface )
3092 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3093 return InterlockedIncrement( &request->refs );
3096 /* critical section must be held */
3097 static void cancel_request( struct winhttp_request *request )
3099 if (request->state <= REQUEST_STATE_CANCELLED) return;
3101 if (request->proc_running)
3103 SetEvent( request->cancel );
3104 LeaveCriticalSection( &request->cs );
3106 WaitForSingleObject( request->done, INFINITE );
3108 EnterCriticalSection( &request->cs );
3110 request->state = REQUEST_STATE_CANCELLED;
3113 /* critical section must be held */
3114 static void free_request( struct winhttp_request *request )
3116 if (request->state < REQUEST_STATE_INITIALIZED) return;
3117 WinHttpCloseHandle( request->hrequest );
3118 WinHttpCloseHandle( request->hconnect );
3119 WinHttpCloseHandle( request->hsession );
3120 CloseHandle( request->done );
3121 CloseHandle( request->wait );
3122 CloseHandle( request->cancel );
3123 heap_free( request->proxy.lpszProxy );
3124 heap_free( request->proxy.lpszProxyBypass );
3125 heap_free( request->buffer );
3126 heap_free( request->verb );
3127 VariantClear( &request->data );
3130 static ULONG WINAPI winhttp_request_Release(
3131 IWinHttpRequest *iface )
3133 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3134 LONG refs = InterlockedDecrement( &request->refs );
3135 if (!refs)
3137 TRACE("destroying %p\n", request);
3139 EnterCriticalSection( &request->cs );
3140 cancel_request( request );
3141 free_request( request );
3142 LeaveCriticalSection( &request->cs );
3143 request->cs.DebugInfo->Spare[0] = 0;
3144 DeleteCriticalSection( &request->cs );
3145 heap_free( request );
3147 return refs;
3150 static HRESULT WINAPI winhttp_request_QueryInterface(
3151 IWinHttpRequest *iface,
3152 REFIID riid,
3153 void **obj )
3155 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3157 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
3159 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
3160 IsEqualGUID( riid, &IID_IDispatch ) ||
3161 IsEqualGUID( riid, &IID_IUnknown ))
3163 *obj = iface;
3165 else
3167 FIXME("interface %s not implemented\n", debugstr_guid(riid));
3168 return E_NOINTERFACE;
3170 IWinHttpRequest_AddRef( iface );
3171 return S_OK;
3174 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
3175 IWinHttpRequest *iface,
3176 UINT *count )
3178 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3180 TRACE("%p, %p\n", request, count);
3181 *count = 1;
3182 return S_OK;
3185 enum type_id
3187 IWinHttpRequest_tid,
3188 last_tid
3191 static ITypeLib *winhttp_typelib;
3192 static ITypeInfo *winhttp_typeinfo[last_tid];
3194 static REFIID winhttp_tid_id[] =
3196 &IID_IWinHttpRequest
3199 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
3201 HRESULT hr;
3203 if (!winhttp_typelib)
3205 ITypeLib *typelib;
3207 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
3208 if (FAILED(hr))
3210 ERR("LoadRegTypeLib failed: %08x\n", hr);
3211 return hr;
3213 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
3214 ITypeLib_Release( typelib );
3216 if (!winhttp_typeinfo[tid])
3218 ITypeInfo *typeinfo;
3220 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
3221 if (FAILED(hr))
3223 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
3224 return hr;
3226 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
3227 ITypeInfo_Release( typeinfo );
3229 *ret = winhttp_typeinfo[tid];
3230 ITypeInfo_AddRef(winhttp_typeinfo[tid]);
3231 return S_OK;
3234 void release_typelib(void)
3236 unsigned i;
3238 for (i = 0; i < ARRAY_SIZE(winhttp_typeinfo); i++)
3239 if (winhttp_typeinfo[i])
3240 ITypeInfo_Release(winhttp_typeinfo[i]);
3242 if (winhttp_typelib)
3243 ITypeLib_Release(winhttp_typelib);
3246 static HRESULT WINAPI winhttp_request_GetTypeInfo(
3247 IWinHttpRequest *iface,
3248 UINT index,
3249 LCID lcid,
3250 ITypeInfo **info )
3252 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3253 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
3255 return get_typeinfo( IWinHttpRequest_tid, info );
3258 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
3259 IWinHttpRequest *iface,
3260 REFIID riid,
3261 LPOLESTR *names,
3262 UINT count,
3263 LCID lcid,
3264 DISPID *dispid )
3266 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3267 ITypeInfo *typeinfo;
3268 HRESULT hr;
3270 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
3272 if (!names || !count || !dispid) return E_INVALIDARG;
3274 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
3275 if (SUCCEEDED(hr))
3277 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
3278 ITypeInfo_Release( typeinfo );
3280 return hr;
3283 static HRESULT WINAPI winhttp_request_Invoke(
3284 IWinHttpRequest *iface,
3285 DISPID member,
3286 REFIID riid,
3287 LCID lcid,
3288 WORD flags,
3289 DISPPARAMS *params,
3290 VARIANT *result,
3291 EXCEPINFO *excep_info,
3292 UINT *arg_err )
3294 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3295 ITypeInfo *typeinfo;
3296 HRESULT hr;
3298 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
3299 lcid, flags, params, result, excep_info, arg_err);
3301 if (!IsEqualIID( riid, &IID_NULL )) return DISP_E_UNKNOWNINTERFACE;
3303 if (member == DISPID_HTTPREQUEST_OPTION)
3305 VARIANT ret_value, option;
3306 UINT err_pos;
3308 if (!result) result = &ret_value;
3309 if (!arg_err) arg_err = &err_pos;
3311 VariantInit( &option );
3312 VariantInit( result );
3314 if (!flags) return S_OK;
3316 if (flags == DISPATCH_PROPERTYPUT)
3318 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
3319 if (FAILED(hr)) return hr;
3321 hr = IWinHttpRequest_put_Option( &request->IWinHttpRequest_iface, V_I4( &option ), params->rgvarg[0] );
3322 if (FAILED(hr))
3323 WARN("put_Option(%d) failed: %x\n", V_I4( &option ), hr);
3324 return hr;
3326 else if (flags & (DISPATCH_PROPERTYGET | DISPATCH_METHOD))
3328 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
3329 if (FAILED(hr)) return hr;
3331 hr = IWinHttpRequest_get_Option( &request->IWinHttpRequest_iface, V_I4( &option ), result );
3332 if (FAILED(hr))
3333 WARN("get_Option(%d) failed: %x\n", V_I4( &option ), hr);
3334 return hr;
3337 FIXME("unsupported flags %x\n", flags);
3338 return E_NOTIMPL;
3341 /* fallback to standard implementation */
3343 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
3344 if (SUCCEEDED(hr))
3346 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
3347 params, result, excep_info, arg_err );
3348 ITypeInfo_Release( typeinfo );
3350 return hr;
3353 static HRESULT WINAPI winhttp_request_SetProxy(
3354 IWinHttpRequest *iface,
3355 HTTPREQUEST_PROXY_SETTING proxy_setting,
3356 VARIANT proxy_server,
3357 VARIANT bypass_list )
3359 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3360 DWORD err = ERROR_SUCCESS;
3362 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
3363 debugstr_variant(&bypass_list));
3365 EnterCriticalSection( &request->cs );
3366 switch (proxy_setting)
3368 case HTTPREQUEST_PROXYSETTING_DEFAULT:
3369 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3370 heap_free( request->proxy.lpszProxy );
3371 heap_free( request->proxy.lpszProxyBypass );
3372 request->proxy.lpszProxy = NULL;
3373 request->proxy.lpszProxyBypass = NULL;
3374 break;
3376 case HTTPREQUEST_PROXYSETTING_DIRECT:
3377 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
3378 heap_free( request->proxy.lpszProxy );
3379 heap_free( request->proxy.lpszProxyBypass );
3380 request->proxy.lpszProxy = NULL;
3381 request->proxy.lpszProxyBypass = NULL;
3382 break;
3384 case HTTPREQUEST_PROXYSETTING_PROXY:
3385 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
3386 if (V_VT( &proxy_server ) == VT_BSTR)
3388 heap_free( request->proxy.lpszProxy );
3389 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
3391 if (V_VT( &bypass_list ) == VT_BSTR)
3393 heap_free( request->proxy.lpszProxyBypass );
3394 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
3396 break;
3398 default:
3399 err = ERROR_INVALID_PARAMETER;
3400 break;
3402 LeaveCriticalSection( &request->cs );
3403 return HRESULT_FROM_WIN32( err );
3406 static HRESULT WINAPI winhttp_request_SetCredentials(
3407 IWinHttpRequest *iface,
3408 BSTR username,
3409 BSTR password,
3410 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
3412 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3413 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
3414 DWORD err = ERROR_SUCCESS;
3416 TRACE("%p, %s, %p, 0x%08x\n", request, debugstr_w(username), password, flags);
3418 EnterCriticalSection( &request->cs );
3419 if (request->state < REQUEST_STATE_OPEN)
3421 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3422 goto done;
3424 switch (flags)
3426 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
3427 target = WINHTTP_AUTH_TARGET_SERVER;
3428 break;
3429 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
3430 target = WINHTTP_AUTH_TARGET_PROXY;
3431 break;
3432 default:
3433 err = ERROR_INVALID_PARAMETER;
3434 goto done;
3436 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
3438 err = GetLastError();
3440 done:
3441 LeaveCriticalSection( &request->cs );
3442 return HRESULT_FROM_WIN32( err );
3445 static void initialize_request( struct winhttp_request *request )
3447 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3448 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3449 request->done = CreateEventW( NULL, FALSE, FALSE, NULL );
3450 request->connect_timeout = 60000;
3451 request->send_timeout = 30000;
3452 request->receive_timeout = 30000;
3453 request->url_codepage = CP_UTF8;
3454 VariantInit( &request->data );
3455 request->state = REQUEST_STATE_INITIALIZED;
3458 static void reset_request( struct winhttp_request *request )
3460 cancel_request( request );
3461 WinHttpCloseHandle( request->hrequest );
3462 request->hrequest = NULL;
3463 WinHttpCloseHandle( request->hconnect );
3464 request->hconnect = NULL;
3465 heap_free( request->buffer );
3466 request->buffer = NULL;
3467 heap_free( request->verb );
3468 request->verb = NULL;
3469 request->offset = 0;
3470 request->bytes_available = 0;
3471 request->bytes_read = 0;
3472 request->error = ERROR_SUCCESS;
3473 request->logon_policy = 0;
3474 request->disable_feature = 0;
3475 request->async = FALSE;
3476 request->connect_timeout = 60000;
3477 request->send_timeout = 30000;
3478 request->receive_timeout = 30000;
3479 request->url_codepage = CP_UTF8;
3480 heap_free( request->proxy.lpszProxy );
3481 request->proxy.lpszProxy = NULL;
3482 heap_free( request->proxy.lpszProxyBypass );
3483 request->proxy.lpszProxyBypass = NULL;
3484 VariantClear( &request->data );
3485 request->state = REQUEST_STATE_INITIALIZED;
3488 static HRESULT WINAPI winhttp_request_Open(
3489 IWinHttpRequest *iface,
3490 BSTR method,
3491 BSTR url,
3492 VARIANT async )
3494 static const WCHAR typeW[] = {'*','/','*',0};
3495 static const WCHAR *acceptW[] = {typeW, NULL};
3496 static const WCHAR httpsW[] = {'h','t','t','p','s'};
3497 static const WCHAR user_agentW[] = {
3498 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
3499 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
3500 'R','e','q','u','e','s','t','.','5',')',0};
3501 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3502 URL_COMPONENTS uc;
3503 WCHAR *hostname, *path = NULL, *verb = NULL;
3504 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0;
3506 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
3507 debugstr_variant(&async));
3509 if (!method || !url) return E_INVALIDARG;
3511 memset( &uc, 0, sizeof(uc) );
3512 uc.dwStructSize = sizeof(uc);
3513 uc.dwSchemeLength = ~0u;
3514 uc.dwHostNameLength = ~0u;
3515 uc.dwUrlPathLength = ~0u;
3516 uc.dwExtraInfoLength = ~0u;
3517 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( GetLastError() );
3519 EnterCriticalSection( &request->cs );
3520 reset_request( request );
3522 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
3523 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
3524 hostname[uc.dwHostNameLength] = 0;
3526 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
3527 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
3528 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
3530 if (!(verb = strdupW( method ))) goto error;
3531 if (SUCCEEDED( VariantChangeType( &async, &async, 0, VT_BOOL )) && V_BOOL( &async )) request->async = TRUE;
3532 else request->async = FALSE;
3534 if (!request->hsession)
3536 if (!(request->hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL,
3537 WINHTTP_FLAG_ASYNC )))
3539 err = GetLastError();
3540 goto error;
3542 if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3544 WinHttpCloseHandle( request->hsession );
3545 request->hsession = NULL;
3546 err = GetLastError();
3547 goto error;
3550 else if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
3552 err = GetLastError();
3553 goto error;
3556 len = ARRAY_SIZE( httpsW );
3557 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
3559 flags |= WINHTTP_FLAG_SECURE;
3561 if (!(request->hrequest = WinHttpOpenRequest( request->hconnect, method, path, NULL, NULL, acceptW, flags )))
3563 err = GetLastError();
3564 goto error;
3566 WinHttpSetOption( request->hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3568 request->state = REQUEST_STATE_OPEN;
3569 request->verb = verb;
3570 heap_free( hostname );
3571 heap_free( path );
3572 LeaveCriticalSection( &request->cs );
3573 return S_OK;
3575 error:
3576 WinHttpCloseHandle( request->hconnect );
3577 request->hconnect = NULL;
3578 heap_free( hostname );
3579 heap_free( path );
3580 heap_free( verb );
3581 LeaveCriticalSection( &request->cs );
3582 return HRESULT_FROM_WIN32( err );
3585 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3586 IWinHttpRequest *iface,
3587 BSTR header,
3588 BSTR value )
3590 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3591 static const WCHAR emptyW[] = {0};
3592 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3593 DWORD len, err = ERROR_SUCCESS;
3594 WCHAR *str;
3596 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3598 if (!header) return E_INVALIDARG;
3600 EnterCriticalSection( &request->cs );
3601 if (request->state < REQUEST_STATE_OPEN)
3603 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3604 goto done;
3606 if (request->state >= REQUEST_STATE_SENT)
3608 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3609 goto done;
3611 len = strlenW( header ) + 4;
3612 if (value) len += strlenW( value );
3613 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3615 err = ERROR_OUTOFMEMORY;
3616 goto done;
3618 sprintfW( str, fmtW, header, value ? value : emptyW );
3619 if (!WinHttpAddRequestHeaders( request->hrequest, str, len,
3620 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
3622 err = GetLastError();
3624 heap_free( str );
3626 done:
3627 LeaveCriticalSection( &request->cs );
3628 return HRESULT_FROM_WIN32( err );
3631 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3632 IWinHttpRequest *iface,
3633 BSTR header,
3634 BSTR *value )
3636 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3637 DWORD size, err = ERROR_SUCCESS;
3639 TRACE("%p, %p\n", request, header);
3641 EnterCriticalSection( &request->cs );
3642 if (request->state < REQUEST_STATE_SENT)
3644 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3645 goto done;
3647 if (!header || !value)
3649 err = ERROR_INVALID_PARAMETER;
3650 goto done;
3652 size = 0;
3653 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3655 err = GetLastError();
3656 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3658 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3660 err = ERROR_OUTOFMEMORY;
3661 goto done;
3663 err = ERROR_SUCCESS;
3664 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3666 err = GetLastError();
3667 SysFreeString( *value );
3669 done:
3670 LeaveCriticalSection( &request->cs );
3671 return HRESULT_FROM_WIN32( err );
3674 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3675 IWinHttpRequest *iface,
3676 BSTR *headers )
3678 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3679 DWORD size, err = ERROR_SUCCESS;
3681 TRACE("%p, %p\n", request, headers);
3683 if (!headers) return E_INVALIDARG;
3685 EnterCriticalSection( &request->cs );
3686 if (request->state < REQUEST_STATE_SENT)
3688 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3689 goto done;
3691 size = 0;
3692 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3694 err = GetLastError();
3695 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3697 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3699 err = ERROR_OUTOFMEMORY;
3700 goto done;
3702 err = ERROR_SUCCESS;
3703 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3705 err = GetLastError();
3706 SysFreeString( *headers );
3708 done:
3709 LeaveCriticalSection( &request->cs );
3710 return HRESULT_FROM_WIN32( err );
3713 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3715 struct winhttp_request *request = (struct winhttp_request *)context;
3717 switch (status)
3719 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3720 request->bytes_available = *(DWORD *)buffer;
3721 request->error = ERROR_SUCCESS;
3722 break;
3723 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3724 request->bytes_read = size;
3725 request->error = ERROR_SUCCESS;
3726 break;
3727 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3729 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3730 request->error = result->dwError;
3731 break;
3733 default: break;
3735 SetEvent( request->wait );
3738 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3740 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3741 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3744 static DWORD wait_for_completion( struct winhttp_request *request )
3746 HANDLE handles[2] = { request->wait, request->cancel };
3747 DWORD ret;
3749 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3751 case WAIT_OBJECT_0:
3752 ret = request->error;
3753 break;
3754 case WAIT_OBJECT_0 + 1:
3755 ret = request->error = ERROR_CANCELLED;
3756 SetEvent( request->done );
3757 break;
3758 default:
3759 ret = request->error = GetLastError();
3760 break;
3762 return ret;
3765 static HRESULT request_receive( struct winhttp_request *request )
3767 DWORD err, size, buflen = 4096;
3769 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3770 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3772 return HRESULT_FROM_WIN32( GetLastError() );
3774 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3775 if (!strcmpW( request->verb, headW ))
3777 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3778 return S_OK;
3780 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3781 request->buffer[0] = 0;
3782 size = 0;
3785 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3786 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3788 err = GetLastError();
3789 goto error;
3791 if ((err = wait_for_completion( request ))) goto error;
3792 if (!request->bytes_available) break;
3793 size += request->bytes_available;
3794 if (buflen < size)
3796 char *tmp;
3797 while (buflen < size) buflen *= 2;
3798 if (!(tmp = heap_realloc( request->buffer, buflen )))
3800 err = ERROR_OUTOFMEMORY;
3801 goto error;
3803 request->buffer = tmp;
3805 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3806 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3807 request->bytes_available, &request->bytes_read ))
3809 err = GetLastError();
3810 goto error;
3812 if ((err = wait_for_completion( request ))) goto error;
3813 request->offset += request->bytes_read;
3814 } while (request->bytes_read);
3816 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3817 return S_OK;
3819 error:
3820 heap_free( request->buffer );
3821 request->buffer = NULL;
3822 return HRESULT_FROM_WIN32( err );
3825 static DWORD request_set_parameters( struct winhttp_request *request )
3827 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3828 sizeof(request->proxy) )) return GetLastError();
3830 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3831 sizeof(request->logon_policy) )) return GetLastError();
3833 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3834 sizeof(request->disable_feature) )) return GetLastError();
3836 if (!WinHttpSetTimeouts( request->hrequest,
3837 request->resolve_timeout,
3838 request->connect_timeout,
3839 request->send_timeout,
3840 request->receive_timeout )) return GetLastError();
3841 return ERROR_SUCCESS;
3844 static void request_set_utf8_content_type( struct winhttp_request *request )
3846 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3847 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3848 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3849 WCHAR headerW[64];
3850 int len;
3852 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3853 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3854 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3855 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3858 static HRESULT request_send( struct winhttp_request *request )
3860 SAFEARRAY *sa = NULL;
3861 VARIANT data;
3862 char *ptr = NULL;
3863 LONG size = 0;
3864 HRESULT hr;
3865 DWORD err;
3867 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3868 if (strcmpW( request->verb, getW ))
3870 VariantInit( &data );
3871 if (V_VT( &request->data ) == VT_BSTR)
3873 UINT cp = CP_ACP;
3874 const WCHAR *str = V_BSTR( &request->data );
3875 int i, len = strlenW( str );
3877 for (i = 0; i < len; i++)
3879 if (str[i] > 127)
3881 cp = CP_UTF8;
3882 break;
3885 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3886 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3887 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3888 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3890 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3892 sa = V_ARRAY( &data );
3893 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3894 if ((hr = SafeArrayGetUBound( sa, 1, &size )) != S_OK)
3896 SafeArrayUnaccessData( sa );
3897 return hr;
3899 size++;
3902 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3903 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3905 err = GetLastError();
3906 goto error;
3908 if ((err = wait_for_completion( request ))) goto error;
3909 if (sa) SafeArrayUnaccessData( sa );
3910 else heap_free( ptr );
3911 request->state = REQUEST_STATE_SENT;
3912 return S_OK;
3914 error:
3915 if (sa) SafeArrayUnaccessData( sa );
3916 else heap_free( ptr );
3917 return HRESULT_FROM_WIN32( err );
3920 static void CALLBACK send_and_receive_proc( TP_CALLBACK_INSTANCE *instance, void *ctx )
3922 struct winhttp_request *request = (struct winhttp_request *)ctx;
3923 if (request_send( request ) == S_OK) request_receive( request );
3924 SetEvent( request->done );
3927 /* critical section must be held */
3928 static DWORD request_wait( struct winhttp_request *request, DWORD timeout )
3930 HANDLE done = request->done;
3931 DWORD err, ret;
3933 LeaveCriticalSection( &request->cs );
3934 while ((err = MsgWaitForMultipleObjects( 1, &done, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3936 MSG msg;
3937 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3939 TranslateMessage( &msg );
3940 DispatchMessageW( &msg );
3943 switch (err)
3945 case WAIT_OBJECT_0:
3946 ret = ERROR_SUCCESS;
3947 break;
3948 case WAIT_TIMEOUT:
3949 ret = ERROR_TIMEOUT;
3950 break;
3951 case WAIT_FAILED:
3952 default:
3953 ret = GetLastError();
3954 break;
3956 EnterCriticalSection( &request->cs );
3957 if (!ret) request->proc_running = FALSE;
3958 return ret;
3961 static HRESULT WINAPI winhttp_request_Send(
3962 IWinHttpRequest *iface,
3963 VARIANT body )
3965 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3966 HRESULT hr;
3968 TRACE("%p, %s\n", request, debugstr_variant(&body));
3970 EnterCriticalSection( &request->cs );
3971 if (request->state < REQUEST_STATE_OPEN)
3973 LeaveCriticalSection( &request->cs );
3974 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3976 if (request->state >= REQUEST_STATE_SENT)
3978 LeaveCriticalSection( &request->cs );
3979 return S_OK;
3981 VariantClear( &request->data );
3982 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK)
3984 LeaveCriticalSection( &request->cs );
3985 return hr;
3987 if (!TrySubmitThreadpoolCallback( send_and_receive_proc, request, NULL ))
3989 LeaveCriticalSection( &request->cs );
3990 return HRESULT_FROM_WIN32( GetLastError() );
3992 request->proc_running = TRUE;
3993 if (!request->async)
3995 hr = HRESULT_FROM_WIN32( request_wait( request, INFINITE ) );
3997 LeaveCriticalSection( &request->cs );
3998 return hr;
4001 static HRESULT WINAPI winhttp_request_get_Status(
4002 IWinHttpRequest *iface,
4003 LONG *status )
4005 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4006 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
4008 TRACE("%p, %p\n", request, status);
4010 if (!status) return E_INVALIDARG;
4012 EnterCriticalSection( &request->cs );
4013 if (request->state < REQUEST_STATE_SENT)
4015 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4016 goto done;
4018 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
4019 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
4021 err = GetLastError();
4022 goto done;
4024 *status = status_code;
4026 done:
4027 LeaveCriticalSection( &request->cs );
4028 return HRESULT_FROM_WIN32( err );
4031 static HRESULT WINAPI winhttp_request_get_StatusText(
4032 IWinHttpRequest *iface,
4033 BSTR *status )
4035 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4036 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
4038 TRACE("%p, %p\n", request, status);
4040 if (!status) return E_INVALIDARG;
4042 EnterCriticalSection( &request->cs );
4043 if (request->state < REQUEST_STATE_SENT)
4045 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4046 goto done;
4048 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
4050 err = GetLastError();
4051 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
4053 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
4055 err = ERROR_OUTOFMEMORY;
4056 goto done;
4058 index = 0;
4059 err = ERROR_SUCCESS;
4060 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
4062 err = GetLastError();
4063 SysFreeString( *status );
4065 done:
4066 LeaveCriticalSection( &request->cs );
4067 return HRESULT_FROM_WIN32( err );
4070 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
4072 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
4073 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
4074 WCHAR *buffer, *p;
4075 DWORD size;
4077 *codepage = CP_ACP;
4078 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
4079 GetLastError() == ERROR_INSUFFICIENT_BUFFER)
4081 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
4082 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
4084 return GetLastError();
4086 if ((p = strstrW( buffer, charsetW )))
4088 p += strlenW( charsetW );
4089 while (*p == ' ') p++;
4090 if (*p++ == '=')
4092 while (*p == ' ') p++;
4093 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
4096 heap_free( buffer );
4098 return ERROR_SUCCESS;
4101 static HRESULT WINAPI winhttp_request_get_ResponseText(
4102 IWinHttpRequest *iface,
4103 BSTR *body )
4105 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4106 UINT codepage;
4107 DWORD err = ERROR_SUCCESS;
4108 int len;
4110 TRACE("%p, %p\n", request, body);
4112 if (!body) return E_INVALIDARG;
4114 EnterCriticalSection( &request->cs );
4115 if (request->state < REQUEST_STATE_SENT)
4117 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4118 goto done;
4120 if ((err = request_get_codepage( request, &codepage ))) goto done;
4121 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
4122 if (!(*body = SysAllocStringLen( NULL, len )))
4124 err = ERROR_OUTOFMEMORY;
4125 goto done;
4127 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
4128 (*body)[len] = 0;
4130 done:
4131 LeaveCriticalSection( &request->cs );
4132 return HRESULT_FROM_WIN32( err );
4135 static HRESULT WINAPI winhttp_request_get_ResponseBody(
4136 IWinHttpRequest *iface,
4137 VARIANT *body )
4139 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4140 SAFEARRAY *sa;
4141 HRESULT hr;
4142 DWORD err = ERROR_SUCCESS;
4143 char *ptr;
4145 TRACE("%p, %p\n", request, body);
4147 if (!body) return E_INVALIDARG;
4149 EnterCriticalSection( &request->cs );
4150 if (request->state < REQUEST_STATE_SENT)
4152 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4153 goto done;
4155 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
4157 err = ERROR_OUTOFMEMORY;
4158 goto done;
4160 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
4162 SafeArrayDestroy( sa );
4163 LeaveCriticalSection( &request->cs );
4164 return hr;
4166 memcpy( ptr, request->buffer, request->offset );
4167 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
4169 SafeArrayDestroy( sa );
4170 LeaveCriticalSection( &request->cs );
4171 return hr;
4173 V_VT( body ) = VT_ARRAY|VT_UI1;
4174 V_ARRAY( body ) = sa;
4176 done:
4177 LeaveCriticalSection( &request->cs );
4178 return HRESULT_FROM_WIN32( err );
4181 struct stream
4183 IStream IStream_iface;
4184 LONG refs;
4185 char *data;
4186 ULARGE_INTEGER pos, size;
4189 static inline struct stream *impl_from_IStream( IStream *iface )
4191 return CONTAINING_RECORD( iface, struct stream, IStream_iface );
4194 static HRESULT WINAPI stream_QueryInterface( IStream *iface, REFIID riid, void **obj )
4196 struct stream *stream = impl_from_IStream( iface );
4198 TRACE("%p, %s, %p\n", stream, debugstr_guid(riid), obj);
4200 if (IsEqualGUID( riid, &IID_IStream ) || IsEqualGUID( riid, &IID_IUnknown ))
4202 *obj = iface;
4204 else
4206 FIXME("interface %s not implemented\n", debugstr_guid(riid));
4207 return E_NOINTERFACE;
4209 IStream_AddRef( iface );
4210 return S_OK;
4213 static ULONG WINAPI stream_AddRef( IStream *iface )
4215 struct stream *stream = impl_from_IStream( iface );
4216 return InterlockedIncrement( &stream->refs );
4219 static ULONG WINAPI stream_Release( IStream *iface )
4221 struct stream *stream = impl_from_IStream( iface );
4222 LONG refs = InterlockedDecrement( &stream->refs );
4223 if (!refs)
4225 heap_free( stream->data );
4226 heap_free( stream );
4228 return refs;
4231 static HRESULT WINAPI stream_Read( IStream *iface, void *buf, ULONG len, ULONG *read )
4233 struct stream *stream = impl_from_IStream( iface );
4234 ULONG size;
4236 if (stream->pos.QuadPart >= stream->size.QuadPart)
4238 *read = 0;
4239 return S_FALSE;
4242 size = min( stream->size.QuadPart - stream->pos.QuadPart, len );
4243 memcpy( buf, stream->data + stream->pos.QuadPart, size );
4244 stream->pos.QuadPart += size;
4245 *read = size;
4247 return S_OK;
4250 static HRESULT WINAPI stream_Write( IStream *iface, const void *buf, ULONG len, ULONG *written )
4252 FIXME("\n");
4253 return E_NOTIMPL;
4256 static HRESULT WINAPI stream_Seek( IStream *iface, LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *newpos )
4258 struct stream *stream = impl_from_IStream( iface );
4260 if (origin == STREAM_SEEK_SET)
4261 stream->pos.QuadPart = move.QuadPart;
4262 else if (origin == STREAM_SEEK_CUR)
4263 stream->pos.QuadPart += move.QuadPart;
4264 else if (origin == STREAM_SEEK_END)
4265 stream->pos.QuadPart = stream->size.QuadPart - move.QuadPart;
4267 if (newpos) newpos->QuadPart = stream->pos.QuadPart;
4268 return S_OK;
4271 static HRESULT WINAPI stream_SetSize( IStream *iface, ULARGE_INTEGER newsize )
4273 FIXME("\n");
4274 return E_NOTIMPL;
4277 static HRESULT WINAPI stream_CopyTo( IStream *iface, IStream *stream, ULARGE_INTEGER len, ULARGE_INTEGER *read,
4278 ULARGE_INTEGER *written )
4280 FIXME("\n");
4281 return E_NOTIMPL;
4284 static HRESULT WINAPI stream_Commit( IStream *iface, DWORD flags )
4286 FIXME("\n");
4287 return E_NOTIMPL;
4290 static HRESULT WINAPI stream_Revert( IStream *iface )
4292 FIXME("\n");
4293 return E_NOTIMPL;
4296 static HRESULT WINAPI stream_LockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
4298 FIXME("\n");
4299 return E_NOTIMPL;
4302 static HRESULT WINAPI stream_UnlockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
4304 FIXME("\n");
4305 return E_NOTIMPL;
4308 static HRESULT WINAPI stream_Stat( IStream *iface, STATSTG *stg, DWORD flag )
4310 FIXME("\n");
4311 return E_NOTIMPL;
4314 static HRESULT WINAPI stream_Clone( IStream *iface, IStream **stream )
4316 FIXME("\n");
4317 return E_NOTIMPL;
4320 static const IStreamVtbl stream_vtbl =
4322 stream_QueryInterface,
4323 stream_AddRef,
4324 stream_Release,
4325 stream_Read,
4326 stream_Write,
4327 stream_Seek,
4328 stream_SetSize,
4329 stream_CopyTo,
4330 stream_Commit,
4331 stream_Revert,
4332 stream_LockRegion,
4333 stream_UnlockRegion,
4334 stream_Stat,
4335 stream_Clone
4338 static HRESULT WINAPI winhttp_request_get_ResponseStream(
4339 IWinHttpRequest *iface,
4340 VARIANT *body )
4342 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4343 DWORD err = ERROR_SUCCESS;
4344 struct stream *stream;
4346 TRACE("%p, %p\n", request, body);
4348 if (!body) return E_INVALIDARG;
4350 EnterCriticalSection( &request->cs );
4351 if (request->state < REQUEST_STATE_SENT)
4353 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
4354 goto done;
4356 if (!(stream = heap_alloc( sizeof(*stream) )))
4358 err = ERROR_OUTOFMEMORY;
4359 goto done;
4361 stream->IStream_iface.lpVtbl = &stream_vtbl;
4362 stream->refs = 1;
4363 if (!(stream->data = heap_alloc( request->offset )))
4365 heap_free( stream );
4366 err = ERROR_OUTOFMEMORY;
4367 goto done;
4369 memcpy( stream->data, request->buffer, request->offset );
4370 stream->pos.QuadPart = 0;
4371 stream->size.QuadPart = request->offset;
4372 V_VT( body ) = VT_UNKNOWN;
4373 V_UNKNOWN( body ) = (IUnknown *)&stream->IStream_iface;
4375 done:
4376 LeaveCriticalSection( &request->cs );
4377 return HRESULT_FROM_WIN32( err );
4380 static HRESULT WINAPI winhttp_request_get_Option(
4381 IWinHttpRequest *iface,
4382 WinHttpRequestOption option,
4383 VARIANT *value )
4385 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4386 HRESULT hr = S_OK;
4388 TRACE("%p, %u, %p\n", request, option, value);
4390 EnterCriticalSection( &request->cs );
4391 switch (option)
4393 case WinHttpRequestOption_URLCodePage:
4394 V_VT( value ) = VT_I4;
4395 V_I4( value ) = request->url_codepage;
4396 break;
4397 default:
4398 FIXME("unimplemented option %u\n", option);
4399 hr = E_NOTIMPL;
4400 break;
4402 LeaveCriticalSection( &request->cs );
4403 return hr;
4406 static HRESULT WINAPI winhttp_request_put_Option(
4407 IWinHttpRequest *iface,
4408 WinHttpRequestOption option,
4409 VARIANT value )
4411 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4412 HRESULT hr = S_OK;
4414 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
4416 EnterCriticalSection( &request->cs );
4417 switch (option)
4419 case WinHttpRequestOption_EnableRedirects:
4421 if (V_BOOL( &value ))
4422 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
4423 else
4424 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
4425 break;
4427 case WinHttpRequestOption_URLCodePage:
4429 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
4430 VARIANT cp;
4432 VariantInit( &cp );
4433 hr = VariantChangeType( &cp, &value, 0, VT_UI4 );
4434 if (SUCCEEDED( hr ))
4436 request->url_codepage = V_UI4( &cp );
4437 TRACE("URL codepage: %u\n", request->url_codepage);
4439 else if (V_VT( &value ) == VT_BSTR && !strcmpiW( V_BSTR( &value ), utf8W ))
4441 TRACE("URL codepage: UTF-8\n");
4442 request->url_codepage = CP_UTF8;
4443 hr = S_OK;
4445 else
4446 FIXME("URL codepage %s is not recognized\n", debugstr_variant( &value ));
4447 break;
4449 default:
4450 FIXME("unimplemented option %u\n", option);
4451 hr = E_NOTIMPL;
4452 break;
4454 LeaveCriticalSection( &request->cs );
4455 return hr;
4458 static HRESULT WINAPI winhttp_request_WaitForResponse(
4459 IWinHttpRequest *iface,
4460 VARIANT timeout,
4461 VARIANT_BOOL *succeeded )
4463 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4464 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
4466 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
4468 EnterCriticalSection( &request->cs );
4469 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
4471 LeaveCriticalSection( &request->cs );
4472 return S_OK;
4474 switch ((err = request_wait( request, msecs )))
4476 case ERROR_TIMEOUT:
4477 if (succeeded) *succeeded = VARIANT_FALSE;
4478 err = ERROR_SUCCESS;
4479 break;
4481 case ERROR_SUCCESS:
4482 if (succeeded) *succeeded = VARIANT_TRUE;
4483 break;
4485 default: break;
4487 LeaveCriticalSection( &request->cs );
4488 return HRESULT_FROM_WIN32( err );
4491 static HRESULT WINAPI winhttp_request_Abort(
4492 IWinHttpRequest *iface )
4494 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4496 TRACE("%p\n", request);
4498 EnterCriticalSection( &request->cs );
4499 cancel_request( request );
4500 LeaveCriticalSection( &request->cs );
4501 return S_OK;
4504 static HRESULT WINAPI winhttp_request_SetTimeouts(
4505 IWinHttpRequest *iface,
4506 LONG resolve_timeout,
4507 LONG connect_timeout,
4508 LONG send_timeout,
4509 LONG receive_timeout )
4511 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4513 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
4515 EnterCriticalSection( &request->cs );
4516 request->resolve_timeout = resolve_timeout;
4517 request->connect_timeout = connect_timeout;
4518 request->send_timeout = send_timeout;
4519 request->receive_timeout = receive_timeout;
4520 LeaveCriticalSection( &request->cs );
4521 return S_OK;
4524 static HRESULT WINAPI winhttp_request_SetClientCertificate(
4525 IWinHttpRequest *iface,
4526 BSTR certificate )
4528 FIXME("\n");
4529 return E_NOTIMPL;
4532 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
4533 IWinHttpRequest *iface,
4534 WinHttpRequestAutoLogonPolicy policy )
4536 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4537 HRESULT hr = S_OK;
4539 TRACE("%p, %u\n", request, policy );
4541 EnterCriticalSection( &request->cs );
4542 switch (policy)
4544 case AutoLogonPolicy_Always:
4545 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
4546 break;
4547 case AutoLogonPolicy_OnlyIfBypassProxy:
4548 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
4549 break;
4550 case AutoLogonPolicy_Never:
4551 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
4552 break;
4553 default: hr = E_INVALIDARG;
4554 break;
4556 LeaveCriticalSection( &request->cs );
4557 return hr;
4560 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
4562 winhttp_request_QueryInterface,
4563 winhttp_request_AddRef,
4564 winhttp_request_Release,
4565 winhttp_request_GetTypeInfoCount,
4566 winhttp_request_GetTypeInfo,
4567 winhttp_request_GetIDsOfNames,
4568 winhttp_request_Invoke,
4569 winhttp_request_SetProxy,
4570 winhttp_request_SetCredentials,
4571 winhttp_request_Open,
4572 winhttp_request_SetRequestHeader,
4573 winhttp_request_GetResponseHeader,
4574 winhttp_request_GetAllResponseHeaders,
4575 winhttp_request_Send,
4576 winhttp_request_get_Status,
4577 winhttp_request_get_StatusText,
4578 winhttp_request_get_ResponseText,
4579 winhttp_request_get_ResponseBody,
4580 winhttp_request_get_ResponseStream,
4581 winhttp_request_get_Option,
4582 winhttp_request_put_Option,
4583 winhttp_request_WaitForResponse,
4584 winhttp_request_Abort,
4585 winhttp_request_SetTimeouts,
4586 winhttp_request_SetClientCertificate,
4587 winhttp_request_SetAutoLogonPolicy
4590 HRESULT WinHttpRequest_create( void **obj )
4592 struct winhttp_request *request;
4594 TRACE("%p\n", obj);
4596 if (!(request = heap_alloc_zero( sizeof(*request) ))) return E_OUTOFMEMORY;
4597 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
4598 request->refs = 1;
4599 InitializeCriticalSection( &request->cs );
4600 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
4601 initialize_request( request );
4603 *obj = &request->IWinHttpRequest_iface;
4604 TRACE("returning iface %p\n", *obj);
4605 return S_OK;