qcap: Implement a stubbed SmartTee filter.
[wine/multimedia.git] / dlls / winhttp / request.c
blobd615011e8338d683c535cdfb06ac3e4ba0a67aea
1 /*
2 * Copyright 2004 Mike McCormack for CodeWeavers
3 * Copyright 2006 Rob Shearman for CodeWeavers
4 * Copyright 2008, 2011 Hans Leidekker for CodeWeavers
5 * Copyright 2009 Juan Lang
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #define COBJMACROS
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <assert.h>
28 #ifdef HAVE_ARPA_INET_H
29 # include <arpa/inet.h>
30 #endif
32 #include "windef.h"
33 #include "winbase.h"
34 #include "ole2.h"
35 #include "initguid.h"
36 #include "httprequest.h"
37 #include "winhttp.h"
39 #include "winhttp_private.h"
41 #include "wine/debug.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
45 static const WCHAR attr_accept[] = {'A','c','c','e','p','t',0};
46 static const WCHAR attr_accept_charset[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
47 static const WCHAR attr_accept_encoding[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
48 static const WCHAR attr_accept_language[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
49 static const WCHAR attr_accept_ranges[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
50 static const WCHAR attr_age[] = {'A','g','e',0};
51 static const WCHAR attr_allow[] = {'A','l','l','o','w',0};
52 static const WCHAR attr_authorization[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
53 static const WCHAR attr_cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
54 static const WCHAR attr_connection[] = {'C','o','n','n','e','c','t','i','o','n',0};
55 static const WCHAR attr_content_base[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
56 static const WCHAR attr_content_encoding[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
57 static const WCHAR attr_content_id[] = {'C','o','n','t','e','n','t','-','I','D',0};
58 static const WCHAR attr_content_language[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
59 static const WCHAR attr_content_length[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
60 static const WCHAR attr_content_location[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
61 static const WCHAR attr_content_md5[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
62 static const WCHAR attr_content_range[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
63 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};
64 static const WCHAR attr_content_type[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
65 static const WCHAR attr_cookie[] = {'C','o','o','k','i','e',0};
66 static const WCHAR attr_date[] = {'D','a','t','e',0};
67 static const WCHAR attr_from[] = {'F','r','o','m',0};
68 static const WCHAR attr_etag[] = {'E','T','a','g',0};
69 static const WCHAR attr_expect[] = {'E','x','p','e','c','t',0};
70 static const WCHAR attr_expires[] = {'E','x','p','i','r','e','s',0};
71 static const WCHAR attr_host[] = {'H','o','s','t',0};
72 static const WCHAR attr_if_match[] = {'I','f','-','M','a','t','c','h',0};
73 static const WCHAR attr_if_modified_since[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
74 static const WCHAR attr_if_none_match[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
75 static const WCHAR attr_if_range[] = {'I','f','-','R','a','n','g','e',0};
76 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};
77 static const WCHAR attr_last_modified[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
78 static const WCHAR attr_location[] = {'L','o','c','a','t','i','o','n',0};
79 static const WCHAR attr_max_forwards[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
80 static const WCHAR attr_mime_version[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
81 static const WCHAR attr_pragma[] = {'P','r','a','g','m','a',0};
82 static const WCHAR attr_proxy_authenticate[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
83 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};
84 static const WCHAR attr_proxy_connection[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
85 static const WCHAR attr_public[] = {'P','u','b','l','i','c',0};
86 static const WCHAR attr_range[] = {'R','a','n','g','e',0};
87 static const WCHAR attr_referer[] = {'R','e','f','e','r','e','r',0};
88 static const WCHAR attr_retry_after[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
89 static const WCHAR attr_server[] = {'S','e','r','v','e','r',0};
90 static const WCHAR attr_set_cookie[] = {'S','e','t','-','C','o','o','k','i','e',0};
91 static const WCHAR attr_status[] = {'S','t','a','t','u','s',0};
92 static const WCHAR attr_transfer_encoding[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
93 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};
94 static const WCHAR attr_upgrade[] = {'U','p','g','r','a','d','e',0};
95 static const WCHAR attr_uri[] = {'U','R','I',0};
96 static const WCHAR attr_user_agent[] = {'U','s','e','r','-','A','g','e','n','t',0};
97 static const WCHAR attr_vary[] = {'V','a','r','y',0};
98 static const WCHAR attr_via[] = {'V','i','a',0};
99 static const WCHAR attr_warning[] = {'W','a','r','n','i','n','g',0};
100 static const WCHAR attr_www_authenticate[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
102 static const WCHAR *attribute_table[] =
104 attr_mime_version, /* WINHTTP_QUERY_MIME_VERSION = 0 */
105 attr_content_type, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
106 attr_content_transfer_encoding, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
107 attr_content_id, /* WINHTTP_QUERY_CONTENT_ID = 3 */
108 NULL, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
109 attr_content_length, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
110 attr_content_language, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
111 attr_allow, /* WINHTTP_QUERY_ALLOW = 7 */
112 attr_public, /* WINHTTP_QUERY_PUBLIC = 8 */
113 attr_date, /* WINHTTP_QUERY_DATE = 9 */
114 attr_expires, /* WINHTTP_QUERY_EXPIRES = 10 */
115 attr_last_modified, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
116 NULL, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
117 attr_uri, /* WINHTTP_QUERY_URI = 13 */
118 attr_from, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
119 NULL, /* WINHTTP_QUERY_COST = 15 */
120 NULL, /* WINHTTP_QUERY_LINK = 16 */
121 attr_pragma, /* WINHTTP_QUERY_PRAGMA = 17 */
122 NULL, /* WINHTTP_QUERY_VERSION = 18 */
123 attr_status, /* WINHTTP_QUERY_STATUS_CODE = 19 */
124 NULL, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
125 NULL, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
126 NULL, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
127 attr_connection, /* WINHTTP_QUERY_CONNECTION = 23 */
128 attr_accept, /* WINHTTP_QUERY_ACCEPT = 24 */
129 attr_accept_charset, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
130 attr_accept_encoding, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
131 attr_accept_language, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
132 attr_authorization, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
133 attr_content_encoding, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
134 NULL, /* WINHTTP_QUERY_FORWARDED = 30 */
135 NULL, /* WINHTTP_QUERY_FROM = 31 */
136 attr_if_modified_since, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
137 attr_location, /* WINHTTP_QUERY_LOCATION = 33 */
138 NULL, /* WINHTTP_QUERY_ORIG_URI = 34 */
139 attr_referer, /* WINHTTP_QUERY_REFERER = 35 */
140 attr_retry_after, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
141 attr_server, /* WINHTTP_QUERY_SERVER = 37 */
142 NULL, /* WINHTTP_TITLE = 38 */
143 attr_user_agent, /* WINHTTP_QUERY_USER_AGENT = 39 */
144 attr_www_authenticate, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
145 attr_proxy_authenticate, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
146 attr_accept_ranges, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
147 attr_set_cookie, /* WINHTTP_QUERY_SET_COOKIE = 43 */
148 attr_cookie, /* WINHTTP_QUERY_COOKIE = 44 */
149 NULL, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
150 NULL, /* WINHTTP_QUERY_REFRESH = 46 */
151 NULL, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
152 attr_age, /* WINHTTP_QUERY_AGE = 48 */
153 attr_cache_control, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
154 attr_content_base, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
155 attr_content_location, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
156 attr_content_md5, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
157 attr_content_range, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
158 attr_etag, /* WINHTTP_QUERY_ETAG = 54 */
159 attr_host, /* WINHTTP_QUERY_HOST = 55 */
160 attr_if_match, /* WINHTTP_QUERY_IF_MATCH = 56 */
161 attr_if_none_match, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
162 attr_if_range, /* WINHTTP_QUERY_IF_RANGE = 58 */
163 attr_if_unmodified_since, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
164 attr_max_forwards, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
165 attr_proxy_authorization, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
166 attr_range, /* WINHTTP_QUERY_RANGE = 62 */
167 attr_transfer_encoding, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
168 attr_upgrade, /* WINHTTP_QUERY_UPGRADE = 64 */
169 attr_vary, /* WINHTTP_QUERY_VARY = 65 */
170 attr_via, /* WINHTTP_QUERY_VIA = 66 */
171 attr_warning, /* WINHTTP_QUERY_WARNING = 67 */
172 attr_expect, /* WINHTTP_QUERY_EXPECT = 68 */
173 attr_proxy_connection, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
174 attr_unless_modified_since, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
175 NULL, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
176 NULL, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
177 NULL, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
178 NULL /* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
181 static task_header_t *dequeue_task( request_t *request )
183 task_header_t *task;
185 EnterCriticalSection( &request->task_cs );
186 TRACE("%u tasks queued\n", list_count( &request->task_queue ));
187 task = LIST_ENTRY( list_head( &request->task_queue ), task_header_t, entry );
188 if (task) list_remove( &task->entry );
189 LeaveCriticalSection( &request->task_cs );
191 TRACE("returning task %p\n", task);
192 return task;
195 static DWORD CALLBACK task_proc( LPVOID param )
197 request_t *request = param;
198 HANDLE handles[2];
200 handles[0] = request->task_wait;
201 handles[1] = request->task_cancel;
202 for (;;)
204 DWORD err = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
205 switch (err)
207 case WAIT_OBJECT_0:
209 task_header_t *task;
210 while ((task = dequeue_task( request )))
212 task->proc( task );
213 release_object( &task->request->hdr );
214 heap_free( task );
216 break;
218 case WAIT_OBJECT_0 + 1:
219 TRACE("exiting\n");
220 return 0;
222 default:
223 ERR("wait failed %u (%u)\n", err, GetLastError());
224 break;
227 return 0;
230 static BOOL queue_task( task_header_t *task )
232 request_t *request = task->request;
234 if (!request->task_thread)
236 if (!(request->task_wait = CreateEventW( NULL, FALSE, FALSE, NULL ))) return FALSE;
237 if (!(request->task_cancel = CreateEventW( NULL, FALSE, FALSE, NULL )))
239 CloseHandle( request->task_wait );
240 request->task_wait = NULL;
241 return FALSE;
243 if (!(request->task_thread = CreateThread( NULL, 0, task_proc, request, 0, NULL )))
245 CloseHandle( request->task_wait );
246 request->task_wait = NULL;
247 CloseHandle( request->task_cancel );
248 request->task_cancel = NULL;
249 return FALSE;
251 InitializeCriticalSection( &request->task_cs );
252 request->task_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": request.task_cs");
255 EnterCriticalSection( &request->task_cs );
256 TRACE("queueing task %p\n", task );
257 list_add_tail( &request->task_queue, &task->entry );
258 LeaveCriticalSection( &request->task_cs );
260 SetEvent( request->task_wait );
261 return TRUE;
264 static void free_header( header_t *header )
266 heap_free( header->field );
267 heap_free( header->value );
268 heap_free( header );
271 static BOOL valid_token_char( WCHAR c )
273 if (c < 32 || c == 127) return FALSE;
274 switch (c)
276 case '(': case ')':
277 case '<': case '>':
278 case '@': case ',':
279 case ';': case ':':
280 case '\\': case '\"':
281 case '/': case '[':
282 case ']': case '?':
283 case '=': case '{':
284 case '}': case ' ':
285 case '\t':
286 return FALSE;
287 default:
288 return TRUE;
292 static header_t *parse_header( LPCWSTR string )
294 const WCHAR *p, *q;
295 header_t *header;
296 int len;
298 p = string;
299 if (!(q = strchrW( p, ':' )))
301 WARN("no ':' in line %s\n", debugstr_w(string));
302 return NULL;
304 if (q == string)
306 WARN("empty field name in line %s\n", debugstr_w(string));
307 return NULL;
309 while (*p != ':')
311 if (!valid_token_char( *p ))
313 WARN("invalid character in field name %s\n", debugstr_w(string));
314 return NULL;
316 p++;
318 len = q - string;
319 if (!(header = heap_alloc_zero( sizeof(header_t) ))) return NULL;
320 if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
322 heap_free( header );
323 return NULL;
325 memcpy( header->field, string, len * sizeof(WCHAR) );
326 header->field[len] = 0;
328 q++; /* skip past colon */
329 while (*q == ' ') q++;
330 if (!*q)
332 WARN("no value in line %s\n", debugstr_w(string));
333 return header;
335 len = strlenW( q );
336 if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
338 free_header( header );
339 return NULL;
341 memcpy( header->value, q, len * sizeof(WCHAR) );
342 header->value[len] = 0;
344 return header;
347 static int get_header_index( request_t *request, LPCWSTR field, int requested_index, BOOL request_only )
349 int index;
351 TRACE("%s\n", debugstr_w(field));
353 for (index = 0; index < request->num_headers; index++)
355 if (strcmpiW( request->headers[index].field, field )) continue;
356 if (request_only && !request->headers[index].is_request) continue;
357 if (!request_only && request->headers[index].is_request) continue;
359 if (!requested_index) break;
360 requested_index--;
362 if (index >= request->num_headers) index = -1;
363 TRACE("returning %d\n", index);
364 return index;
367 static BOOL insert_header( request_t *request, header_t *header )
369 DWORD count;
370 header_t *hdrs;
372 count = request->num_headers + 1;
373 if (count > 1)
374 hdrs = heap_realloc_zero( request->headers, sizeof(header_t) * count );
375 else
376 hdrs = heap_alloc_zero( sizeof(header_t) * count );
378 if (hdrs)
380 request->headers = hdrs;
381 request->headers[count - 1].field = strdupW( header->field );
382 request->headers[count - 1].value = strdupW( header->value );
383 request->headers[count - 1].is_request = header->is_request;
384 request->num_headers++;
385 return TRUE;
387 return FALSE;
390 static BOOL delete_header( request_t *request, DWORD index )
392 if (!request->num_headers) return FALSE;
393 if (index >= request->num_headers) return FALSE;
394 request->num_headers--;
396 heap_free( request->headers[index].field );
397 heap_free( request->headers[index].value );
399 memmove( &request->headers[index], &request->headers[index + 1], (request->num_headers - index) * sizeof(header_t) );
400 memset( &request->headers[request->num_headers], 0, sizeof(header_t) );
401 return TRUE;
404 static BOOL process_header( request_t *request, LPCWSTR field, LPCWSTR value, DWORD flags, BOOL request_only )
406 int index;
407 header_t *header;
409 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
411 /* replace wins out over add */
412 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE) flags &= ~WINHTTP_ADDREQ_FLAG_ADD;
414 if (flags & WINHTTP_ADDREQ_FLAG_ADD) index = -1;
415 else
416 index = get_header_index( request, field, 0, request_only );
418 if (index >= 0)
420 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
421 header = &request->headers[index];
423 else if (value)
425 header_t hdr;
427 hdr.field = (LPWSTR)field;
428 hdr.value = (LPWSTR)value;
429 hdr.is_request = request_only;
431 return insert_header( request, &hdr );
433 /* no value to delete */
434 else return TRUE;
436 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
438 delete_header( request, index );
439 if (value)
441 header_t hdr;
443 hdr.field = (LPWSTR)field;
444 hdr.value = (LPWSTR)value;
445 hdr.is_request = request_only;
447 return insert_header( request, &hdr );
449 return TRUE;
451 else if (flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON))
453 WCHAR sep, *tmp;
454 int len, orig_len, value_len;
456 orig_len = strlenW( header->value );
457 value_len = strlenW( value );
459 if (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) sep = ',';
460 else sep = ';';
462 len = orig_len + value_len + 2;
463 if ((tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) )))
465 header->value = tmp;
467 header->value[orig_len] = sep;
468 orig_len++;
469 header->value[orig_len] = ' ';
470 orig_len++;
472 memcpy( &header->value[orig_len], value, value_len * sizeof(WCHAR) );
473 header->value[len] = 0;
474 return TRUE;
477 return TRUE;
480 BOOL add_request_headers( request_t *request, LPCWSTR headers, DWORD len, DWORD flags )
482 BOOL ret = FALSE;
483 WCHAR *buffer, *p, *q;
484 header_t *header;
486 if (len == ~0u) len = strlenW( headers );
487 if (!len) return TRUE;
488 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
489 strcpyW( buffer, headers );
491 p = buffer;
494 q = p;
495 while (*q)
497 if (q[0] == '\n' && q[1] == '\r')
499 q[0] = '\r';
500 q[1] = '\n';
502 if (q[0] == '\r' && q[1] == '\n') break;
503 q++;
505 if (!*p) break;
506 if (*q == '\r')
508 *q = 0;
509 q += 2; /* jump over \r\n */
511 if ((header = parse_header( p )))
513 ret = process_header( request, header->field, header->value, flags, TRUE );
514 free_header( header );
516 p = q;
517 } while (ret);
519 heap_free( buffer );
520 return ret;
523 /***********************************************************************
524 * WinHttpAddRequestHeaders (winhttp.@)
526 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
528 BOOL ret;
529 request_t *request;
531 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest, debugstr_w(headers), len, flags);
533 if (!headers)
535 set_last_error( ERROR_INVALID_PARAMETER );
536 return FALSE;
538 if (!(request = (request_t *)grab_object( hrequest )))
540 set_last_error( ERROR_INVALID_HANDLE );
541 return FALSE;
543 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
545 release_object( &request->hdr );
546 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
547 return FALSE;
550 ret = add_request_headers( request, headers, len, flags );
552 release_object( &request->hdr );
553 return ret;
556 static WCHAR *build_request_path( request_t *request )
558 WCHAR *ret;
560 if (strcmpiW( request->connect->hostname, request->connect->servername ))
562 static const WCHAR http[] = { 'h','t','t','p',0 };
563 static const WCHAR https[] = { 'h','t','t','p','s',0 };
564 static const WCHAR fmt[] = { '%','s',':','/','/','%','s',0 };
565 LPCWSTR scheme = request->netconn.secure ? https : http;
566 int len;
568 len = strlenW( scheme ) + strlenW( request->connect->hostname );
569 /* 3 characters for '://', 1 for NUL. */
570 len += 4;
571 if (request->connect->hostport)
573 /* 1 for ':' between host and port, up to 5 for port */
574 len += 6;
576 if (request->path)
577 len += strlenW( request->path );
578 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
580 sprintfW( ret, fmt, scheme, request->connect->hostname );
581 if (request->connect->hostport)
583 static const WCHAR colonFmt[] = { ':','%','u',0 };
585 sprintfW( ret + strlenW( ret ), colonFmt,
586 request->connect->hostport );
588 if (request->path)
589 strcatW( ret, request->path );
592 else
593 ret = request->path;
594 return ret;
597 static WCHAR *build_request_string( request_t *request )
599 static const WCHAR space[] = {' ',0};
600 static const WCHAR crlf[] = {'\r','\n',0};
601 static const WCHAR colon[] = {':',' ',0};
602 static const WCHAR twocrlf[] = {'\r','\n','\r','\n',0};
604 WCHAR *path, *ret;
605 const WCHAR **headers, **p;
606 unsigned int len, i = 0, j;
608 /* allocate space for an array of all the string pointers to be added */
609 len = request->num_headers * 4 + 7;
610 if (!(headers = heap_alloc( len * sizeof(LPCWSTR) ))) return NULL;
612 path = build_request_path( request );
613 headers[i++] = request->verb;
614 headers[i++] = space;
615 headers[i++] = path;
616 headers[i++] = space;
617 headers[i++] = request->version;
619 for (j = 0; j < request->num_headers; j++)
621 if (request->headers[j].is_request)
623 headers[i++] = crlf;
624 headers[i++] = request->headers[j].field;
625 headers[i++] = colon;
626 headers[i++] = request->headers[j].value;
628 TRACE("adding header %s (%s)\n", debugstr_w(request->headers[j].field),
629 debugstr_w(request->headers[j].value));
632 headers[i++] = twocrlf;
633 headers[i] = NULL;
635 len = 0;
636 for (p = headers; *p; p++) len += strlenW( *p );
637 len++;
639 if (!(ret = heap_alloc( len * sizeof(WCHAR) )))
640 goto out;
641 *ret = 0;
642 for (p = headers; *p; p++) strcatW( ret, *p );
644 out:
645 if (path != request->path)
646 heap_free( path );
647 heap_free( headers );
648 return ret;
651 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
653 static BOOL query_headers( request_t *request, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
655 header_t *header = NULL;
656 BOOL request_only, ret = FALSE;
657 int requested_index, header_index = -1;
658 DWORD attr, len;
660 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
661 requested_index = index ? *index : 0;
663 attr = level & ~QUERY_MODIFIER_MASK;
664 switch (attr)
666 case WINHTTP_QUERY_CUSTOM:
668 header_index = get_header_index( request, name, requested_index, request_only );
669 break;
671 case WINHTTP_QUERY_RAW_HEADERS:
673 WCHAR *headers, *p, *q;
675 if (request_only)
676 headers = build_request_string( request );
677 else
678 headers = request->raw_headers;
680 if (!(p = headers)) return FALSE;
681 for (len = 0; *p; p++) if (*p != '\r') len++;
683 if (!buffer || (len + 1) * sizeof(WCHAR) > *buflen)
685 len++;
686 set_last_error( ERROR_INSUFFICIENT_BUFFER );
688 else
690 for (p = headers, q = buffer; *p; p++, q++)
692 if (*p != '\r') *q = *p;
693 else
695 *q = 0;
696 p++; /* skip '\n' */
699 *q = 0;
700 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
701 ret = TRUE;
703 *buflen = len * sizeof(WCHAR);
704 if (request_only) heap_free( headers );
705 return ret;
707 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
709 WCHAR *headers;
711 if (request_only)
712 headers = build_request_string( request );
713 else
714 headers = request->raw_headers;
716 if (!headers) return FALSE;
717 len = strlenW( headers ) * sizeof(WCHAR);
718 if (!buffer || len + sizeof(WCHAR) > *buflen)
720 len += sizeof(WCHAR);
721 set_last_error( ERROR_INSUFFICIENT_BUFFER );
723 else
725 memcpy( buffer, headers, len + sizeof(WCHAR) );
726 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
727 ret = TRUE;
729 *buflen = len;
730 if (request_only) heap_free( headers );
731 return ret;
733 case WINHTTP_QUERY_VERSION:
734 len = strlenW( request->version ) * sizeof(WCHAR);
735 if (!buffer || len + sizeof(WCHAR) > *buflen)
737 len += sizeof(WCHAR);
738 set_last_error( ERROR_INSUFFICIENT_BUFFER );
740 else
742 strcpyW( buffer, request->version );
743 TRACE("returning string: %s\n", debugstr_w(buffer));
744 ret = TRUE;
746 *buflen = len;
747 return ret;
749 case WINHTTP_QUERY_STATUS_TEXT:
750 len = strlenW( request->status_text ) * sizeof(WCHAR);
751 if (!buffer || len + sizeof(WCHAR) > *buflen)
753 len += sizeof(WCHAR);
754 set_last_error( ERROR_INSUFFICIENT_BUFFER );
756 else
758 strcpyW( buffer, request->status_text );
759 TRACE("returning string: %s\n", debugstr_w(buffer));
760 ret = TRUE;
762 *buflen = len;
763 return ret;
765 default:
766 if (attr >= sizeof(attribute_table)/sizeof(attribute_table[0]) || !attribute_table[attr])
768 FIXME("attribute %u not implemented\n", attr);
769 return FALSE;
771 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
772 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
773 break;
776 if (header_index >= 0)
778 header = &request->headers[header_index];
780 if (!header || (request_only && !header->is_request))
782 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
783 return FALSE;
785 if (index) *index += 1;
786 if (level & WINHTTP_QUERY_FLAG_NUMBER)
788 if (!buffer || sizeof(int) > *buflen)
790 set_last_error( ERROR_INSUFFICIENT_BUFFER );
792 else
794 int *number = buffer;
795 *number = atoiW( header->value );
796 TRACE("returning number: %d\n", *number);
797 ret = TRUE;
799 *buflen = sizeof(int);
801 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
803 SYSTEMTIME *st = buffer;
804 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
806 set_last_error( ERROR_INSUFFICIENT_BUFFER );
808 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
810 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
811 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
812 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
814 *buflen = sizeof(SYSTEMTIME);
816 else if (header->value)
818 len = strlenW( header->value ) * sizeof(WCHAR);
819 if (!buffer || len + sizeof(WCHAR) > *buflen)
821 len += sizeof(WCHAR);
822 set_last_error( ERROR_INSUFFICIENT_BUFFER );
824 else
826 strcpyW( buffer, header->value );
827 TRACE("returning string: %s\n", debugstr_w(buffer));
828 ret = TRUE;
830 *buflen = len;
832 return ret;
835 /***********************************************************************
836 * WinHttpQueryHeaders (winhttp.@)
838 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
840 BOOL ret;
841 request_t *request;
843 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
845 if (!(request = (request_t *)grab_object( hrequest )))
847 set_last_error( ERROR_INVALID_HANDLE );
848 return FALSE;
850 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
852 release_object( &request->hdr );
853 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
854 return FALSE;
857 ret = query_headers( request, level, name, buffer, buflen, index );
859 release_object( &request->hdr );
860 return ret;
863 static LPWSTR concatenate_string_list( LPCWSTR *list, int len )
865 LPCWSTR *t;
866 LPWSTR str;
868 for( t = list; *t ; t++ )
869 len += strlenW( *t );
870 len++;
872 str = heap_alloc( len * sizeof(WCHAR) );
873 if (!str) return NULL;
874 *str = 0;
876 for( t = list; *t ; t++ )
877 strcatW( str, *t );
879 return str;
882 static LPWSTR build_header_request_string( request_t *request, LPCWSTR verb,
883 LPCWSTR path, LPCWSTR version )
885 static const WCHAR crlf[] = {'\r','\n',0};
886 static const WCHAR space[] = { ' ',0 };
887 static const WCHAR colon[] = { ':',' ',0 };
888 static const WCHAR twocrlf[] = {'\r','\n','\r','\n', 0};
889 LPWSTR requestString;
890 DWORD len, n;
891 LPCWSTR *req;
892 UINT i;
893 LPWSTR p;
895 /* allocate space for an array of all the string pointers to be added */
896 len = (request->num_headers) * 4 + 10;
897 req = heap_alloc( len * sizeof(LPCWSTR) );
898 if (!req) return NULL;
900 /* add the verb, path and HTTP version string */
901 n = 0;
902 req[n++] = verb;
903 req[n++] = space;
904 req[n++] = path;
905 req[n++] = space;
906 req[n++] = version;
908 /* Append custom request headers */
909 for (i = 0; i < request->num_headers; i++)
911 if (request->headers[i].is_request)
913 req[n++] = crlf;
914 req[n++] = request->headers[i].field;
915 req[n++] = colon;
916 req[n++] = request->headers[i].value;
918 TRACE("Adding custom header %s (%s)\n",
919 debugstr_w(request->headers[i].field),
920 debugstr_w(request->headers[i].value));
924 if( n >= len )
925 ERR("oops. buffer overrun\n");
927 req[n] = NULL;
928 requestString = concatenate_string_list( req, 4 );
929 heap_free( req );
930 if (!requestString) return NULL;
933 * Set (header) termination string for request
934 * Make sure there are exactly two new lines at the end of the request
936 p = &requestString[strlenW(requestString)-1];
937 while ( (*p == '\n') || (*p == '\r') )
938 p--;
939 strcpyW( p+1, twocrlf );
941 return requestString;
944 static BOOL read_reply( request_t *request );
946 static BOOL secure_proxy_connect( request_t *request )
948 static const WCHAR verbConnect[] = {'C','O','N','N','E','C','T',0};
949 static const WCHAR fmt[] = {'%','s',':','%','u',0};
950 BOOL ret = FALSE;
951 LPWSTR path;
952 connect_t *connect = request->connect;
954 path = heap_alloc( (strlenW( connect->hostname ) + 13) * sizeof(WCHAR) );
955 if (path)
957 LPWSTR requestString;
959 sprintfW( path, fmt, connect->hostname, connect->hostport );
960 requestString = build_header_request_string( request, verbConnect,
961 path, http1_1 );
962 heap_free( path );
963 if (requestString)
965 LPSTR req_ascii = strdupWA( requestString );
967 heap_free( requestString );
968 if (req_ascii)
970 int len = strlen( req_ascii ), bytes_sent;
972 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
973 heap_free( req_ascii );
974 if (ret)
975 ret = read_reply( request );
979 return ret;
982 #ifndef INET6_ADDRSTRLEN
983 #define INET6_ADDRSTRLEN 46
984 #endif
986 static WCHAR *addr_to_str( struct sockaddr *addr )
988 char buf[INET6_ADDRSTRLEN];
989 void *src;
991 switch (addr->sa_family)
993 case AF_INET:
994 src = &((struct sockaddr_in *)addr)->sin_addr;
995 break;
996 case AF_INET6:
997 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
998 break;
999 default:
1000 WARN("unsupported address family %d\n", addr->sa_family);
1001 return NULL;
1003 if (!inet_ntop( addr->sa_family, src, buf, sizeof(buf) )) return NULL;
1004 return strdupAW( buf );
1007 static BOOL open_connection( request_t *request )
1009 connect_t *connect;
1010 WCHAR *addressW = NULL;
1011 INTERNET_PORT port;
1012 socklen_t slen;
1013 struct sockaddr *saddr;
1014 DWORD len;
1016 if (netconn_connected( &request->netconn )) goto done;
1018 connect = request->connect;
1019 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1020 saddr = (struct sockaddr *)&connect->sockaddr;
1021 slen = sizeof(struct sockaddr);
1023 if (!connect->resolved)
1025 len = strlenW( connect->servername ) + 1;
1026 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, connect->servername, len );
1028 if (!netconn_resolve( connect->servername, port, saddr, &slen, request->resolve_timeout )) return FALSE;
1029 connect->resolved = TRUE;
1031 if (!(addressW = addr_to_str( saddr ))) return FALSE;
1032 len = strlenW( addressW ) + 1;
1033 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
1035 if (!addressW && !(addressW = addr_to_str( saddr ))) return FALSE;
1036 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
1038 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
1040 if (!netconn_create( &request->netconn, saddr->sa_family, SOCK_STREAM, 0 ))
1042 heap_free( addressW );
1043 return FALSE;
1045 netconn_set_timeout( &request->netconn, TRUE, request->send_timeout );
1046 netconn_set_timeout( &request->netconn, FALSE, request->recv_timeout );
1047 if (!netconn_connect( &request->netconn, saddr, slen, request->connect_timeout ))
1049 netconn_close( &request->netconn );
1050 heap_free( addressW );
1051 return FALSE;
1053 if (request->hdr.flags & WINHTTP_FLAG_SECURE)
1055 if (connect->session->proxy_server &&
1056 strcmpiW( connect->hostname, connect->servername ))
1058 if (!secure_proxy_connect( request ))
1060 heap_free( addressW );
1061 return FALSE;
1064 if (!netconn_secure_connect( &request->netconn, connect->servername ))
1066 netconn_close( &request->netconn );
1067 heap_free( addressW );
1068 return FALSE;
1072 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
1074 done:
1075 request->read_pos = request->read_size = 0;
1076 request->read_chunked = FALSE;
1077 request->read_chunked_size = ~0u;
1078 request->read_chunked_eof = FALSE;
1079 heap_free( addressW );
1080 return TRUE;
1083 void close_connection( request_t *request )
1085 if (!netconn_connected( &request->netconn )) return;
1087 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1088 netconn_close( &request->netconn );
1089 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1092 static BOOL add_host_header( request_t *request, DWORD modifier )
1094 BOOL ret;
1095 DWORD len;
1096 WCHAR *host;
1097 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1098 connect_t *connect = request->connect;
1099 INTERNET_PORT port;
1101 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1103 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1105 return process_header( request, attr_host, connect->hostname, modifier, TRUE );
1107 len = strlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1108 if (!(host = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1109 sprintfW( host, fmt, connect->hostname, port );
1110 ret = process_header( request, attr_host, host, modifier, TRUE );
1111 heap_free( host );
1112 return ret;
1115 static void clear_response_headers( request_t *request )
1117 unsigned int i;
1119 for (i = 0; i < request->num_headers; i++)
1121 if (!request->headers[i].field) continue;
1122 if (!request->headers[i].value) continue;
1123 if (request->headers[i].is_request) continue;
1124 delete_header( request, i );
1125 i--;
1129 static BOOL send_request( request_t *request, LPCWSTR headers, DWORD headers_len, LPVOID optional,
1130 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
1132 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
1133 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
1134 static const WCHAR length_fmt[] = {'%','l','d',0};
1136 BOOL ret = FALSE;
1137 connect_t *connect = request->connect;
1138 session_t *session = connect->session;
1139 WCHAR *req = NULL;
1140 char *req_ascii;
1141 int bytes_sent;
1142 DWORD len, i, flags;
1144 clear_response_headers( request );
1146 flags = WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
1147 for (i = 0; i < request->num_accept_types; i++)
1149 process_header( request, attr_accept, request->accept_types[i], flags, TRUE );
1151 if (session->agent)
1152 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1154 if (connect->hostname)
1155 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
1157 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
1159 WCHAR length[21]; /* decimal long int + null */
1160 sprintfW( length, length_fmt, total_len );
1161 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1163 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
1165 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1167 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
1169 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1170 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1172 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
1174 TRACE("failed to add request headers\n");
1175 return FALSE;
1177 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
1179 WARN("failed to add cookie headers\n");
1180 return FALSE;
1183 if (context) request->hdr.context = context;
1185 if (!(ret = open_connection( request ))) goto end;
1186 if (!(req = build_request_string( request ))) goto end;
1188 if (!(req_ascii = strdupWA( req ))) goto end;
1189 TRACE("full request: %s\n", debugstr_a(req_ascii));
1190 len = strlen(req_ascii);
1192 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
1194 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
1195 heap_free( req_ascii );
1196 if (!ret) goto end;
1198 if (optional_len)
1200 if (!netconn_send( &request->netconn, optional, optional_len, &bytes_sent )) goto end;
1201 request->optional = optional;
1202 request->optional_len = optional_len;
1203 len += optional_len;
1205 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(len) );
1207 end:
1208 if (async)
1210 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
1211 else
1213 WINHTTP_ASYNC_RESULT result;
1214 result.dwResult = API_SEND_REQUEST;
1215 result.dwError = get_last_error();
1216 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
1219 heap_free( req );
1220 return ret;
1223 static void task_send_request( task_header_t *task )
1225 send_request_t *s = (send_request_t *)task;
1226 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
1227 heap_free( s->headers );
1230 /***********************************************************************
1231 * WinHttpSendRequest (winhttp.@)
1233 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
1234 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
1236 BOOL ret;
1237 request_t *request;
1239 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1240 hrequest, debugstr_w(headers), headers_len, optional_len, total_len, context);
1242 if (!(request = (request_t *)grab_object( hrequest )))
1244 set_last_error( ERROR_INVALID_HANDLE );
1245 return FALSE;
1247 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1249 release_object( &request->hdr );
1250 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1251 return FALSE;
1254 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
1256 send_request_t *s;
1258 if (!(s = heap_alloc( sizeof(send_request_t) ))) return FALSE;
1259 s->hdr.request = request;
1260 s->hdr.proc = task_send_request;
1261 s->headers = strdupW( headers );
1262 s->headers_len = headers_len;
1263 s->optional = optional;
1264 s->optional_len = optional_len;
1265 s->total_len = total_len;
1266 s->context = context;
1268 addref_object( &request->hdr );
1269 ret = queue_task( (task_header_t *)s );
1271 else
1272 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
1274 release_object( &request->hdr );
1275 return ret;
1278 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1280 static const WCHAR basicW[] = {'B','a','s','i','c',0};
1281 static const WCHAR ntlmW[] = {'N','T','L','M',0};
1282 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
1283 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
1284 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
1286 static const struct
1288 const WCHAR *str;
1289 unsigned int len;
1290 DWORD scheme;
1292 auth_schemes[] =
1294 { basicW, ARRAYSIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
1295 { ntlmW, ARRAYSIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
1296 { passportW, ARRAYSIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
1297 { digestW, ARRAYSIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
1298 { negotiateW, ARRAYSIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
1300 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
1302 static enum auth_scheme scheme_from_flag( DWORD flag )
1304 int i;
1306 for (i = 0; i < num_auth_schemes; i++) if (flag == auth_schemes[i].scheme) return i;
1307 return SCHEME_INVALID;
1310 static DWORD auth_scheme_from_header( WCHAR *header )
1312 unsigned int i;
1314 for (i = 0; i < num_auth_schemes; i++)
1316 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
1317 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
1319 return 0;
1322 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
1324 DWORD index = 0;
1325 BOOL ret = FALSE;
1327 for (;;)
1329 WCHAR *buffer;
1330 DWORD size, scheme;
1332 size = 0;
1333 query_headers( request, level, NULL, NULL, &size, &index );
1334 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) break;
1336 index--;
1337 if (!(buffer = heap_alloc( size ))) return FALSE;
1338 if (!query_headers( request, level, NULL, buffer, &size, &index ))
1340 heap_free( buffer );
1341 return FALSE;
1343 scheme = auth_scheme_from_header( buffer );
1344 heap_free( buffer );
1345 if (!scheme) break;
1347 if (first && index == 1)
1348 *first = *supported = scheme;
1349 else
1350 *supported |= scheme;
1352 ret = TRUE;
1354 return ret;
1357 /***********************************************************************
1358 * WinHttpQueryAuthSchemes (winhttp.@)
1360 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
1362 BOOL ret = FALSE;
1363 request_t *request;
1365 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
1367 if (!(request = (request_t *)grab_object( hrequest )))
1369 set_last_error( ERROR_INVALID_HANDLE );
1370 return FALSE;
1372 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1374 release_object( &request->hdr );
1375 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1376 return FALSE;
1378 if (!supported || !first || !target)
1380 release_object( &request->hdr );
1381 set_last_error( ERROR_INVALID_PARAMETER );
1382 return FALSE;
1386 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
1388 *target = WINHTTP_AUTH_TARGET_SERVER;
1389 ret = TRUE;
1391 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
1393 *target = WINHTTP_AUTH_TARGET_PROXY;
1394 ret = TRUE;
1397 release_object( &request->hdr );
1398 return ret;
1401 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
1403 UINT n = 0, x;
1404 static const char base64enc[] =
1405 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1407 while (len > 0)
1409 /* first 6 bits, all from bin[0] */
1410 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
1411 x = (bin[0] & 3) << 4;
1413 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1414 if (len == 1)
1416 base64[n++] = base64enc[x];
1417 base64[n++] = '=';
1418 base64[n++] = '=';
1419 break;
1421 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
1422 x = (bin[1] & 0x0f) << 2;
1424 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1425 if (len == 2)
1427 base64[n++] = base64enc[x];
1428 base64[n++] = '=';
1429 break;
1431 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1433 /* last 6 bits, all from bin [2] */
1434 base64[n++] = base64enc[bin[2] & 0x3f];
1435 bin += 3;
1436 len -= 3;
1438 base64[n] = 0;
1439 return n;
1442 static inline char decode_char( WCHAR c )
1444 if (c >= 'A' && c <= 'Z') return c - 'A';
1445 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1446 if (c >= '0' && c <= '9') return c - '0' + 52;
1447 if (c == '+') return 62;
1448 if (c == '/') return 63;
1449 return 64;
1452 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1454 unsigned int i = 0;
1455 char c0, c1, c2, c3;
1456 const WCHAR *p = base64;
1458 while (len > 4)
1460 if ((c0 = decode_char( p[0] )) > 63) return 0;
1461 if ((c1 = decode_char( p[1] )) > 63) return 0;
1462 if ((c2 = decode_char( p[2] )) > 63) return 0;
1463 if ((c3 = decode_char( p[3] )) > 63) return 0;
1465 if (buf)
1467 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1468 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1469 buf[i + 2] = (c2 << 6) | c3;
1471 len -= 4;
1472 i += 3;
1473 p += 4;
1475 if (p[2] == '=')
1477 if ((c0 = decode_char( p[0] )) > 63) return 0;
1478 if ((c1 = decode_char( p[1] )) > 63) return 0;
1480 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1481 i++;
1483 else if (p[3] == '=')
1485 if ((c0 = decode_char( p[0] )) > 63) return 0;
1486 if ((c1 = decode_char( p[1] )) > 63) return 0;
1487 if ((c2 = decode_char( p[2] )) > 63) return 0;
1489 if (buf)
1491 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1492 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1494 i += 2;
1496 else
1498 if ((c0 = decode_char( p[0] )) > 63) return 0;
1499 if ((c1 = decode_char( p[1] )) > 63) return 0;
1500 if ((c2 = decode_char( p[2] )) > 63) return 0;
1501 if ((c3 = decode_char( p[3] )) > 63) return 0;
1503 if (buf)
1505 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1506 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1507 buf[i + 2] = (c2 << 6) | c3;
1509 i += 3;
1511 return i;
1514 static struct authinfo *alloc_authinfo(void)
1516 struct authinfo *ret;
1518 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1520 SecInvalidateHandle( &ret->cred );
1521 SecInvalidateHandle( &ret->ctx );
1522 memset( &ret->exp, 0, sizeof(ret->exp) );
1523 ret->scheme = 0;
1524 ret->attr = 0;
1525 ret->max_token = 0;
1526 ret->data = NULL;
1527 ret->data_len = 0;
1528 ret->finished = FALSE;
1529 return ret;
1532 void destroy_authinfo( struct authinfo *authinfo )
1534 if (!authinfo) return;
1536 if (SecIsValidHandle( &authinfo->ctx ))
1537 DeleteSecurityContext( &authinfo->ctx );
1538 if (SecIsValidHandle( &authinfo->cred ))
1539 FreeCredentialsHandle( &authinfo->cred );
1541 heap_free( authinfo->data );
1542 heap_free( authinfo );
1545 static BOOL get_authvalue( request_t *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1547 DWORD size, index = 0;
1548 for (;;)
1550 size = len;
1551 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1552 if (auth_scheme_from_header( buffer ) == scheme) break;
1554 return TRUE;
1557 static BOOL do_authorization( request_t *request, DWORD target, DWORD scheme_flag )
1559 struct authinfo *authinfo, **auth_ptr;
1560 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1561 const WCHAR *auth_target, *username, *password;
1562 WCHAR auth_value[2048], *auth_reply;
1563 DWORD len = sizeof(auth_value), len_scheme, flags;
1564 BOOL ret;
1566 if (scheme == SCHEME_INVALID) return FALSE;
1568 switch (target)
1570 case WINHTTP_AUTH_TARGET_SERVER:
1571 if (!get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len ))
1572 return FALSE;
1573 auth_ptr = &request->authinfo;
1574 auth_target = attr_authorization;
1575 username = request->connect->username;
1576 password = request->connect->password;
1577 break;
1579 case WINHTTP_AUTH_TARGET_PROXY:
1580 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1581 return FALSE;
1582 auth_ptr = &request->proxy_authinfo;
1583 auth_target = attr_proxy_authorization;
1584 username = request->connect->session->proxy_username;
1585 password = request->connect->session->proxy_password;
1586 break;
1588 default:
1589 WARN("unknown target %x\n", target);
1590 return FALSE;
1592 authinfo = *auth_ptr;
1594 switch (scheme)
1596 case SCHEME_BASIC:
1598 int userlen, passlen;
1600 if (!username || !password) return FALSE;
1601 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1603 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1604 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1606 authinfo->data_len = userlen + 1 + passlen;
1607 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1609 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1610 authinfo->data[userlen] = ':';
1611 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1613 authinfo->scheme = SCHEME_BASIC;
1614 authinfo->finished = TRUE;
1615 break;
1617 case SCHEME_NTLM:
1618 case SCHEME_NEGOTIATE:
1620 SECURITY_STATUS status;
1621 SecBufferDesc out_desc, in_desc;
1622 SecBuffer out, in;
1623 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1624 const WCHAR *p;
1625 BOOL first = FALSE;
1627 if (!authinfo)
1629 TimeStamp exp;
1630 SEC_WINNT_AUTH_IDENTITY_W id;
1631 WCHAR *domain, *user;
1633 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1635 first = TRUE;
1636 domain = (WCHAR *)username;
1637 user = strchrW( username, '\\' );
1639 if (user) user++;
1640 else
1642 user = (WCHAR *)username;
1643 domain = NULL;
1645 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1646 id.User = user;
1647 id.UserLength = strlenW( user );
1648 id.Domain = domain;
1649 id.DomainLength = domain ? user - domain - 1 : 0;
1650 id.Password = (WCHAR *)password;
1651 id.PasswordLength = strlenW( password );
1653 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1654 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1655 &authinfo->cred, &exp );
1656 if (status == SEC_E_OK)
1658 PSecPkgInfoW info;
1659 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1660 if (status == SEC_E_OK)
1662 authinfo->max_token = info->cbMaxToken;
1663 FreeContextBuffer( info );
1666 if (status != SEC_E_OK)
1668 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1669 debugstr_w(auth_schemes[scheme].str), status);
1670 heap_free( authinfo );
1671 return FALSE;
1673 authinfo->scheme = scheme;
1675 else if (authinfo->finished) return FALSE;
1677 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1678 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1680 ERR("authentication scheme changed from %s to %s\n",
1681 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1682 destroy_authinfo( authinfo );
1683 *auth_ptr = NULL;
1684 return FALSE;
1686 in.BufferType = SECBUFFER_TOKEN;
1687 in.cbBuffer = 0;
1688 in.pvBuffer = NULL;
1690 in_desc.ulVersion = 0;
1691 in_desc.cBuffers = 1;
1692 in_desc.pBuffers = &in;
1694 p = auth_value + auth_schemes[scheme].len;
1695 if (*p == ' ')
1697 int len = strlenW( ++p );
1698 in.cbBuffer = decode_base64( p, len, NULL );
1699 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) {
1700 destroy_authinfo( authinfo );
1701 *auth_ptr = NULL;
1702 return FALSE;
1704 decode_base64( p, len, in.pvBuffer );
1706 out.BufferType = SECBUFFER_TOKEN;
1707 out.cbBuffer = authinfo->max_token;
1708 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1710 heap_free( in.pvBuffer );
1711 destroy_authinfo( authinfo );
1712 *auth_ptr = NULL;
1713 return FALSE;
1715 out_desc.ulVersion = 0;
1716 out_desc.cBuffers = 1;
1717 out_desc.pBuffers = &out;
1719 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1720 first ? request->connect->servername : NULL, flags, 0,
1721 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1722 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1723 heap_free( in.pvBuffer );
1724 if (status == SEC_E_OK)
1726 heap_free( authinfo->data );
1727 authinfo->data = out.pvBuffer;
1728 authinfo->data_len = out.cbBuffer;
1729 authinfo->finished = TRUE;
1730 TRACE("sending last auth packet\n");
1732 else if (status == SEC_I_CONTINUE_NEEDED)
1734 heap_free( authinfo->data );
1735 authinfo->data = out.pvBuffer;
1736 authinfo->data_len = out.cbBuffer;
1737 TRACE("sending next auth packet\n");
1739 else
1741 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1742 heap_free( out.pvBuffer );
1743 destroy_authinfo( authinfo );
1744 *auth_ptr = NULL;
1745 return FALSE;
1747 break;
1749 default:
1750 ERR("invalid scheme %u\n", scheme);
1751 return FALSE;
1753 *auth_ptr = authinfo;
1755 len_scheme = auth_schemes[authinfo->scheme].len;
1756 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1757 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1759 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1760 auth_reply[len_scheme] = ' ';
1761 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1763 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1764 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1765 heap_free( auth_reply );
1766 return ret;
1769 static BOOL set_credentials( request_t *request, DWORD target, DWORD scheme, const WCHAR *username,
1770 const WCHAR *password )
1772 if ((scheme == WINHTTP_AUTH_SCHEME_BASIC || scheme == WINHTTP_AUTH_SCHEME_DIGEST) &&
1773 (!username || !password))
1775 set_last_error( ERROR_INVALID_PARAMETER );
1776 return FALSE;
1778 switch (target)
1780 case WINHTTP_AUTH_TARGET_SERVER:
1782 heap_free( request->connect->username );
1783 if (!username) request->connect->username = NULL;
1784 else if (!(request->connect->username = strdupW( username ))) return FALSE;
1786 heap_free( request->connect->password );
1787 if (!password) request->connect->password = NULL;
1788 else if (!(request->connect->password = strdupW( password ))) return FALSE;
1789 break;
1791 case WINHTTP_AUTH_TARGET_PROXY:
1793 heap_free( request->connect->session->proxy_username );
1794 if (!username) request->connect->session->proxy_username = NULL;
1795 else if (!(request->connect->session->proxy_username = strdupW( username ))) return FALSE;
1797 heap_free( request->connect->session->proxy_password );
1798 if (!password) request->connect->session->proxy_password = NULL;
1799 else if (!(request->connect->session->proxy_password = strdupW( password ))) return FALSE;
1800 break;
1802 default:
1803 WARN("unknown target %u\n", target);
1804 return FALSE;
1806 return TRUE;
1809 /***********************************************************************
1810 * WinHttpSetCredentials (winhttp.@)
1812 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
1813 LPCWSTR password, LPVOID params )
1815 BOOL ret;
1816 request_t *request;
1818 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
1820 if (!(request = (request_t *)grab_object( hrequest )))
1822 set_last_error( ERROR_INVALID_HANDLE );
1823 return FALSE;
1825 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1827 release_object( &request->hdr );
1828 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1829 return FALSE;
1832 ret = set_credentials( request, target, scheme, username, password );
1834 release_object( &request->hdr );
1835 return ret;
1838 static BOOL handle_authorization( request_t *request, DWORD status )
1840 DWORD i, schemes, first, level, target;
1842 switch (status)
1844 case HTTP_STATUS_DENIED:
1845 target = WINHTTP_AUTH_TARGET_SERVER;
1846 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
1847 break;
1849 case HTTP_STATUS_PROXY_AUTH_REQ:
1850 target = WINHTTP_AUTH_TARGET_PROXY;
1851 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
1852 break;
1854 default:
1855 WARN("unhandled status %u\n", status);
1856 return FALSE;
1859 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
1860 if (do_authorization( request, target, first )) return TRUE;
1862 schemes &= ~first;
1863 for (i = 0; i < num_auth_schemes; i++)
1865 if (!(schemes & auth_schemes[i].scheme)) continue;
1866 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
1868 return FALSE;
1871 /* set the request content length based on the headers */
1872 static DWORD set_content_length( request_t *request, DWORD status )
1874 WCHAR encoding[20];
1875 DWORD buflen = sizeof(request->content_length);
1877 if (status == HTTP_STATUS_NO_CONTENT || status == HTTP_STATUS_NOT_MODIFIED || !strcmpW( request->verb, headW ))
1878 request->content_length = 0;
1879 else
1881 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
1882 NULL, &request->content_length, &buflen, NULL ))
1883 request->content_length = ~0u;
1885 buflen = sizeof(encoding);
1886 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
1887 !strcmpiW( encoding, chunkedW ))
1889 request->content_length = ~0u;
1890 request->read_chunked = TRUE;
1891 request->read_chunked_size = ~0u;
1892 request->read_chunked_eof = FALSE;
1895 request->content_read = 0;
1896 return request->content_length;
1899 /* read some more data into the read buffer */
1900 static BOOL read_more_data( request_t *request, int maxlen, BOOL notify )
1902 int len;
1903 BOOL ret;
1905 if (request->read_chunked_eof) return FALSE;
1907 if (request->read_size && request->read_pos)
1909 /* move existing data to the start of the buffer */
1910 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1911 request->read_pos = 0;
1913 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1915 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1917 ret = netconn_recv( &request->netconn, request->read_buf + request->read_size,
1918 maxlen - request->read_size, 0, &len );
1920 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &len, sizeof(len) );
1922 request->read_size += len;
1923 return ret;
1926 /* remove some amount of data from the read buffer */
1927 static void remove_data( request_t *request, int count )
1929 if (!(request->read_size -= count)) request->read_pos = 0;
1930 else request->read_pos += count;
1933 static BOOL read_line( request_t *request, char *buffer, DWORD *len )
1935 int count, bytes_read, pos = 0;
1937 for (;;)
1939 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1940 if (eol)
1942 count = eol - (request->read_buf + request->read_pos);
1943 bytes_read = count + 1;
1945 else count = bytes_read = request->read_size;
1947 count = min( count, *len - pos );
1948 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
1949 pos += count;
1950 remove_data( request, bytes_read );
1951 if (eol) break;
1953 if (!read_more_data( request, -1, TRUE )) return FALSE;
1954 if (!request->read_size)
1956 *len = 0;
1957 TRACE("returning empty string\n");
1958 return FALSE;
1961 if (pos < *len)
1963 if (pos && buffer[pos - 1] == '\r') pos--;
1964 *len = pos + 1;
1966 buffer[*len - 1] = 0;
1967 TRACE("returning %s\n", debugstr_a(buffer));
1968 return TRUE;
1971 /* discard data contents until we reach end of line */
1972 static BOOL discard_eol( request_t *request, BOOL notify )
1976 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1977 if (eol)
1979 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1980 break;
1982 request->read_pos = request->read_size = 0; /* discard everything */
1983 if (!read_more_data( request, -1, notify )) return FALSE;
1984 } while (request->read_size);
1985 return TRUE;
1988 /* read the size of the next chunk */
1989 static BOOL start_next_chunk( request_t *request, BOOL notify )
1991 DWORD chunk_size = 0;
1993 assert(!request->read_chunked_size || request->read_chunked_size == ~0u);
1995 if (request->read_chunked_eof) return FALSE;
1997 /* read terminator for the previous chunk */
1998 if (!request->read_chunked_size && !discard_eol( request, notify )) return FALSE;
2000 for (;;)
2002 while (request->read_size)
2004 char ch = request->read_buf[request->read_pos];
2005 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2006 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2007 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2008 else if (ch == ';' || ch == '\r' || ch == '\n')
2010 TRACE("reading %u byte chunk\n", chunk_size);
2012 if (request->content_length == ~0u) request->content_length = chunk_size;
2013 else request->content_length += chunk_size;
2015 request->read_chunked_size = chunk_size;
2016 if (!chunk_size) request->read_chunked_eof = TRUE;
2018 return discard_eol( request, notify );
2020 remove_data( request, 1 );
2022 if (!read_more_data( request, -1, notify )) return FALSE;
2023 if (!request->read_size)
2025 request->content_length = request->content_read = 0;
2026 request->read_chunked_size = 0;
2027 return TRUE;
2032 /* return the size of data available to be read immediately */
2033 static DWORD get_available_data( request_t *request )
2035 if (request->read_chunked) return min( request->read_chunked_size, request->read_size );
2036 return request->read_size;
2039 /* check if we have reached the end of the data to read */
2040 static BOOL end_of_read_data( request_t *request )
2042 if (!request->content_length) return TRUE;
2043 if (request->read_chunked) return request->read_chunked_eof;
2044 if (request->content_length == ~0u) return FALSE;
2045 return (request->content_length == request->content_read);
2048 static BOOL refill_buffer( request_t *request, BOOL notify )
2050 int len = sizeof(request->read_buf);
2052 if (request->read_chunked)
2054 if (request->read_chunked_eof) return FALSE;
2055 if (request->read_chunked_size == ~0u || !request->read_chunked_size)
2057 if (!start_next_chunk( request, notify )) return FALSE;
2059 len = min( len, request->read_chunked_size );
2061 else if (request->content_length != ~0u)
2063 len = min( len, request->content_length - request->content_read );
2066 if (len <= request->read_size) return TRUE;
2067 if (!read_more_data( request, len, notify )) return FALSE;
2068 if (!request->read_size) request->content_length = request->content_read = 0;
2069 return TRUE;
2072 #define MAX_REPLY_LEN 1460
2073 #define INITIAL_HEADER_BUFFER_LEN 512
2075 static BOOL read_reply( request_t *request )
2077 static const WCHAR crlf[] = {'\r','\n',0};
2079 char buffer[MAX_REPLY_LEN];
2080 DWORD buflen, len, offset, received_len, crlf_len = 2; /* strlenW(crlf) */
2081 char *status_code, *status_text;
2082 WCHAR *versionW, *status_textW, *raw_headers;
2083 WCHAR status_codeW[4]; /* sizeof("nnn") */
2085 if (!netconn_connected( &request->netconn )) return FALSE;
2087 received_len = 0;
2090 buflen = MAX_REPLY_LEN;
2091 if (!read_line( request, buffer, &buflen )) return FALSE;
2092 received_len += buflen;
2094 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2095 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
2096 status_code++;
2097 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
2098 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
2099 status_text++;
2101 TRACE("version [%s] status code [%s] status text [%s]\n",
2102 debugstr_an(buffer, status_code - buffer - 1),
2103 debugstr_an(status_code, len),
2104 debugstr_a(status_text));
2106 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
2108 /* we rely on the fact that the protocol is ascii */
2109 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2110 status_codeW[len] = 0;
2111 if (!(process_header( request, attr_status, status_codeW, WINHTTP_ADDREQ_FLAG_REPLACE, FALSE ))) return FALSE;
2113 len = status_code - buffer;
2114 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2115 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2116 versionW[len - 1] = 0;
2118 heap_free( request->version );
2119 request->version = versionW;
2121 len = buflen - (status_text - buffer);
2122 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2123 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2125 heap_free( request->status_text );
2126 request->status_text = status_textW;
2128 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2129 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2130 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2131 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2133 heap_free( request->raw_headers );
2134 request->raw_headers = raw_headers;
2136 offset = buflen + crlf_len - 1;
2137 for (;;)
2139 header_t *header;
2141 buflen = MAX_REPLY_LEN;
2142 if (!read_line( request, buffer, &buflen )) return TRUE;
2143 received_len += buflen;
2144 if (!*buffer) break;
2146 while (len - offset < buflen + crlf_len)
2148 WCHAR *tmp;
2149 len *= 2;
2150 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2151 request->raw_headers = raw_headers = tmp;
2153 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2155 if (!(header = parse_header( raw_headers + offset ))) break;
2156 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2158 free_header( header );
2159 break;
2161 free_header( header );
2162 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2163 offset += buflen + crlf_len - 1;
2166 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2167 return TRUE;
2170 static void finished_reading( request_t *request )
2172 static const WCHAR closeW[] = {'c','l','o','s','e',0};
2174 BOOL close = FALSE;
2175 WCHAR connection[20];
2176 DWORD size = sizeof(connection);
2178 if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
2179 else if (query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
2180 query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
2182 if (!strcmpiW( connection, closeW )) close = TRUE;
2184 else if (!strcmpW( request->version, http1_0 )) close = TRUE;
2185 if (close) close_connection( request );
2188 static BOOL read_data( request_t *request, void *buffer, DWORD size, DWORD *read, BOOL async )
2190 int count, bytes_read = 0;
2192 if (end_of_read_data( request )) goto done;
2194 while (size)
2196 if (!(count = get_available_data( request )))
2198 if (!refill_buffer( request, async )) goto done;
2199 if (!(count = get_available_data( request ))) goto done;
2201 count = min( count, size );
2202 memcpy( (char *)buffer + bytes_read, request->read_buf + request->read_pos, count );
2203 remove_data( request, count );
2204 if (request->read_chunked) request->read_chunked_size -= count;
2205 size -= count;
2206 bytes_read += count;
2207 request->content_read += count;
2208 if (end_of_read_data( request )) goto done;
2210 if (request->read_chunked && !request->read_chunked_size) refill_buffer( request, async );
2212 done:
2213 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, request->content_read, request->content_length );
2215 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
2216 if (read) *read = bytes_read;
2217 if (end_of_read_data( request )) finished_reading( request );
2218 return TRUE;
2221 /* read any content returned by the server so that the connection can be reused */
2222 static void drain_content( request_t *request )
2224 DWORD bytes_read;
2225 char buffer[2048];
2227 refill_buffer( request, FALSE );
2228 for (;;)
2230 if (!read_data( request, buffer, sizeof(buffer), &bytes_read, FALSE ) || !bytes_read) return;
2234 static void record_cookies( request_t *request )
2236 unsigned int i;
2238 for (i = 0; i < request->num_headers; i++)
2240 header_t *set_cookie = &request->headers[i];
2241 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2243 set_cookies( request, set_cookie->value );
2248 static WCHAR *get_redirect_url( request_t *request, DWORD *len )
2250 DWORD size;
2251 WCHAR *ret;
2253 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2254 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2255 if (!(ret = heap_alloc( size ))) return NULL;
2256 *len = size / sizeof(WCHAR);
2257 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2258 heap_free( ret );
2259 return NULL;
2262 static BOOL handle_redirect( request_t *request, DWORD status )
2264 BOOL ret = FALSE;
2265 DWORD len, len_url;
2266 URL_COMPONENTS uc;
2267 connect_t *connect = request->connect;
2268 INTERNET_PORT port;
2269 WCHAR *hostname = NULL, *location;
2270 int index;
2272 if (!(location = get_redirect_url( request, &len_url ))) return FALSE;
2274 memset( &uc, 0, sizeof(uc) );
2275 uc.dwStructSize = sizeof(uc);
2276 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2278 if (!WinHttpCrackUrl( location, len_url, 0, &uc )) /* assume relative redirect */
2280 WCHAR *path, *p;
2282 len = strlenW( location ) + 1;
2283 if (location[0] != '/') len++;
2284 if (!(p = path = heap_alloc( len * sizeof(WCHAR) ))) goto end;
2286 if (location[0] != '/') *p++ = '/';
2287 strcpyW( p, location );
2289 heap_free( request->path );
2290 request->path = path;
2292 drain_content( request );
2293 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2295 else
2297 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2299 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2300 TRACE("redirect from secure page to non-secure page\n");
2301 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2303 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2305 TRACE("redirect from non-secure page to secure page\n");
2306 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2309 drain_content( request );
2310 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2312 len = uc.dwHostNameLength;
2313 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2314 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2315 hostname[len] = 0;
2317 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2318 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2320 heap_free( connect->hostname );
2321 connect->hostname = hostname;
2322 connect->hostport = port;
2323 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2325 netconn_close( &request->netconn );
2326 if (!(ret = netconn_init( &request->netconn ))) goto end;
2327 request->read_pos = request->read_size = 0;
2328 request->read_chunked = FALSE;
2329 request->read_chunked_eof = FALSE;
2331 else heap_free( hostname );
2333 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2334 if (!(ret = open_connection( request ))) goto end;
2336 heap_free( request->path );
2337 request->path = NULL;
2338 if (uc.dwUrlPathLength)
2340 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2341 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2342 strcpyW( request->path, uc.lpszUrlPath );
2344 else request->path = strdupW( slashW );
2347 /* remove content-type/length headers */
2348 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2349 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2351 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2353 heap_free( request->verb );
2354 request->verb = strdupW( getW );
2355 request->optional = NULL;
2356 request->optional_len = 0;
2358 ret = TRUE;
2360 end:
2361 heap_free( location );
2362 return ret;
2365 static BOOL receive_response( request_t *request, BOOL async )
2367 BOOL ret;
2368 DWORD size, query, status;
2370 for (;;)
2372 if (!(ret = read_reply( request )))
2374 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2375 break;
2377 size = sizeof(DWORD);
2378 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2379 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2381 set_content_length( request, status );
2383 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2385 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2387 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2388 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2390 if (!(ret = handle_redirect( request, status ))) break;
2392 /* recurse synchronously */
2393 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2395 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2397 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2399 drain_content( request );
2400 if (!handle_authorization( request, status )) break;
2402 /* recurse synchronously */
2403 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) continue;
2405 break;
2408 if (request->content_length) refill_buffer( request, FALSE );
2410 if (async)
2412 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2413 else
2415 WINHTTP_ASYNC_RESULT result;
2416 result.dwResult = API_RECEIVE_RESPONSE;
2417 result.dwError = get_last_error();
2418 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2421 return ret;
2424 static void task_receive_response( task_header_t *task )
2426 receive_response_t *r = (receive_response_t *)task;
2427 receive_response( r->hdr.request, TRUE );
2430 /***********************************************************************
2431 * WinHttpReceiveResponse (winhttp.@)
2433 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2435 BOOL ret;
2436 request_t *request;
2438 TRACE("%p, %p\n", hrequest, reserved);
2440 if (!(request = (request_t *)grab_object( hrequest )))
2442 set_last_error( ERROR_INVALID_HANDLE );
2443 return FALSE;
2445 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2447 release_object( &request->hdr );
2448 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2449 return FALSE;
2452 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2454 receive_response_t *r;
2456 if (!(r = heap_alloc( sizeof(receive_response_t) ))) return FALSE;
2457 r->hdr.request = request;
2458 r->hdr.proc = task_receive_response;
2460 addref_object( &request->hdr );
2461 ret = queue_task( (task_header_t *)r );
2463 else
2464 ret = receive_response( request, FALSE );
2466 release_object( &request->hdr );
2467 return ret;
2470 static BOOL query_data_available( request_t *request, DWORD *available, BOOL async )
2472 DWORD count = 0;
2474 if (end_of_read_data( request )) goto done;
2476 count = get_available_data( request );
2477 if (!request->read_chunked)
2478 count += netconn_query_data_available( &request->netconn );
2479 if (!count)
2481 refill_buffer( request, async );
2482 count = get_available_data( request );
2483 if (!request->read_chunked)
2484 count += netconn_query_data_available( &request->netconn );
2487 done:
2488 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2489 TRACE("%u bytes available\n", count);
2490 if (available) *available = count;
2491 return TRUE;
2494 static void task_query_data_available( task_header_t *task )
2496 query_data_t *q = (query_data_t *)task;
2497 query_data_available( q->hdr.request, q->available, TRUE );
2500 /***********************************************************************
2501 * WinHttpQueryDataAvailable (winhttp.@)
2503 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2505 BOOL ret;
2506 request_t *request;
2508 TRACE("%p, %p\n", hrequest, available);
2510 if (!(request = (request_t *)grab_object( hrequest )))
2512 set_last_error( ERROR_INVALID_HANDLE );
2513 return FALSE;
2515 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2517 release_object( &request->hdr );
2518 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2519 return FALSE;
2522 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2524 query_data_t *q;
2526 if (!(q = heap_alloc( sizeof(query_data_t) ))) return FALSE;
2527 q->hdr.request = request;
2528 q->hdr.proc = task_query_data_available;
2529 q->available = available;
2531 addref_object( &request->hdr );
2532 ret = queue_task( (task_header_t *)q );
2534 else
2535 ret = query_data_available( request, available, FALSE );
2537 release_object( &request->hdr );
2538 return ret;
2541 static void task_read_data( task_header_t *task )
2543 read_data_t *r = (read_data_t *)task;
2544 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2547 /***********************************************************************
2548 * WinHttpReadData (winhttp.@)
2550 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2552 BOOL ret;
2553 request_t *request;
2555 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2557 if (!(request = (request_t *)grab_object( hrequest )))
2559 set_last_error( ERROR_INVALID_HANDLE );
2560 return FALSE;
2562 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2564 release_object( &request->hdr );
2565 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2566 return FALSE;
2569 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2571 read_data_t *r;
2573 if (!(r = heap_alloc( sizeof(read_data_t) ))) return FALSE;
2574 r->hdr.request = request;
2575 r->hdr.proc = task_read_data;
2576 r->buffer = buffer;
2577 r->to_read = to_read;
2578 r->read = read;
2580 addref_object( &request->hdr );
2581 ret = queue_task( (task_header_t *)r );
2583 else
2584 ret = read_data( request, buffer, to_read, read, FALSE );
2586 release_object( &request->hdr );
2587 return ret;
2590 static BOOL write_data( request_t *request, LPCVOID buffer, DWORD to_write, LPDWORD written, BOOL async )
2592 BOOL ret;
2593 int num_bytes;
2595 ret = netconn_send( &request->netconn, buffer, to_write, &num_bytes );
2597 if (async)
2599 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
2600 else
2602 WINHTTP_ASYNC_RESULT result;
2603 result.dwResult = API_WRITE_DATA;
2604 result.dwError = get_last_error();
2605 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2608 if (ret && written) *written = num_bytes;
2609 return ret;
2612 static void task_write_data( task_header_t *task )
2614 write_data_t *w = (write_data_t *)task;
2615 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
2618 /***********************************************************************
2619 * WinHttpWriteData (winhttp.@)
2621 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
2623 BOOL ret;
2624 request_t *request;
2626 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
2628 if (!(request = (request_t *)grab_object( hrequest )))
2630 set_last_error( ERROR_INVALID_HANDLE );
2631 return FALSE;
2633 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2635 release_object( &request->hdr );
2636 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2637 return FALSE;
2640 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2642 write_data_t *w;
2644 if (!(w = heap_alloc( sizeof(write_data_t) ))) return FALSE;
2645 w->hdr.request = request;
2646 w->hdr.proc = task_write_data;
2647 w->buffer = buffer;
2648 w->to_write = to_write;
2649 w->written = written;
2651 addref_object( &request->hdr );
2652 ret = queue_task( (task_header_t *)w );
2654 else
2655 ret = write_data( request, buffer, to_write, written, FALSE );
2657 release_object( &request->hdr );
2658 return ret;
2661 enum request_state
2663 REQUEST_STATE_UNINITIALIZED,
2664 REQUEST_STATE_INITIALIZED,
2665 REQUEST_STATE_CANCELLED,
2666 REQUEST_STATE_OPEN,
2667 REQUEST_STATE_SENT,
2668 REQUEST_STATE_RESPONSE_RECEIVED
2671 struct winhttp_request
2673 IWinHttpRequest IWinHttpRequest_iface;
2674 LONG refs;
2675 CRITICAL_SECTION cs;
2676 enum request_state state;
2677 HINTERNET hsession;
2678 HINTERNET hconnect;
2679 HINTERNET hrequest;
2680 VARIANT data;
2681 WCHAR *verb;
2682 HANDLE thread;
2683 HANDLE wait;
2684 HANDLE cancel;
2685 char *buffer;
2686 DWORD offset;
2687 DWORD bytes_available;
2688 DWORD bytes_read;
2689 DWORD error;
2690 DWORD logon_policy;
2691 DWORD disable_feature;
2692 LONG resolve_timeout;
2693 LONG connect_timeout;
2694 LONG send_timeout;
2695 LONG receive_timeout;
2696 WINHTTP_PROXY_INFO proxy;
2699 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
2701 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
2704 static ULONG WINAPI winhttp_request_AddRef(
2705 IWinHttpRequest *iface )
2707 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2708 return InterlockedIncrement( &request->refs );
2711 /* critical section must be held */
2712 static void cancel_request( struct winhttp_request *request )
2714 if (request->state <= REQUEST_STATE_CANCELLED) return;
2715 if (request->thread) SetEvent( request->cancel );
2716 request->state = REQUEST_STATE_CANCELLED;
2719 /* critical section must be held */
2720 static void free_request( struct winhttp_request *request )
2722 if (request->state < REQUEST_STATE_INITIALIZED) return;
2723 WinHttpCloseHandle( request->hrequest );
2724 WinHttpCloseHandle( request->hconnect );
2725 WinHttpCloseHandle( request->hsession );
2726 CloseHandle( request->thread );
2727 CloseHandle( request->wait );
2728 CloseHandle( request->cancel );
2729 heap_free( request->proxy.lpszProxy );
2730 heap_free( request->proxy.lpszProxyBypass );
2731 heap_free( request->buffer );
2732 heap_free( request->verb );
2733 VariantClear( &request->data );
2736 static ULONG WINAPI winhttp_request_Release(
2737 IWinHttpRequest *iface )
2739 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2740 LONG refs = InterlockedDecrement( &request->refs );
2741 if (!refs)
2743 TRACE("destroying %p\n", request);
2745 EnterCriticalSection( &request->cs );
2746 cancel_request( request );
2747 free_request( request );
2748 LeaveCriticalSection( &request->cs );
2749 request->cs.DebugInfo->Spare[0] = 0;
2750 DeleteCriticalSection( &request->cs );
2751 heap_free( request );
2753 return refs;
2756 static HRESULT WINAPI winhttp_request_QueryInterface(
2757 IWinHttpRequest *iface,
2758 REFIID riid,
2759 void **obj )
2761 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2763 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
2765 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
2766 IsEqualGUID( riid, &IID_IDispatch ) ||
2767 IsEqualGUID( riid, &IID_IUnknown ))
2769 *obj = iface;
2771 else
2773 FIXME("interface %s not implemented\n", debugstr_guid(riid));
2774 return E_NOINTERFACE;
2776 IWinHttpRequest_AddRef( iface );
2777 return S_OK;
2780 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
2781 IWinHttpRequest *iface,
2782 UINT *count )
2784 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2786 TRACE("%p, %p\n", request, count);
2787 *count = 1;
2788 return S_OK;
2791 enum type_id
2793 IWinHttpRequest_tid,
2794 last_tid
2797 static ITypeLib *winhttp_typelib;
2798 static ITypeInfo *winhttp_typeinfo[last_tid];
2800 static REFIID winhttp_tid_id[] =
2802 &IID_IWinHttpRequest
2805 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
2807 HRESULT hr;
2809 if (!winhttp_typelib)
2811 ITypeLib *typelib;
2813 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
2814 if (FAILED(hr))
2816 ERR("LoadRegTypeLib failed: %08x\n", hr);
2817 return hr;
2819 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
2820 ITypeLib_Release( typelib );
2822 if (!winhttp_typeinfo[tid])
2824 ITypeInfo *typeinfo;
2826 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
2827 if (FAILED(hr))
2829 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
2830 return hr;
2832 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
2833 ITypeInfo_Release( typeinfo );
2835 *ret = winhttp_typeinfo[tid];
2836 ITypeInfo_AddRef(winhttp_typeinfo[tid]);
2837 return S_OK;
2840 void release_typelib(void)
2842 unsigned i;
2844 for (i = 0; i < sizeof(winhttp_typeinfo)/sizeof(*winhttp_typeinfo); i++)
2845 if (winhttp_typeinfo[i])
2846 ITypeInfo_Release(winhttp_typeinfo[i]);
2848 if (winhttp_typelib)
2849 ITypeLib_Release(winhttp_typelib);
2852 static HRESULT WINAPI winhttp_request_GetTypeInfo(
2853 IWinHttpRequest *iface,
2854 UINT index,
2855 LCID lcid,
2856 ITypeInfo **info )
2858 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2859 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
2861 return get_typeinfo( IWinHttpRequest_tid, info );
2864 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
2865 IWinHttpRequest *iface,
2866 REFIID riid,
2867 LPOLESTR *names,
2868 UINT count,
2869 LCID lcid,
2870 DISPID *dispid )
2872 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2873 ITypeInfo *typeinfo;
2874 HRESULT hr;
2876 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
2878 if (!names || !count || !dispid) return E_INVALIDARG;
2880 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2881 if (SUCCEEDED(hr))
2883 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
2884 ITypeInfo_Release( typeinfo );
2886 return hr;
2889 static HRESULT WINAPI winhttp_request_Invoke(
2890 IWinHttpRequest *iface,
2891 DISPID member,
2892 REFIID riid,
2893 LCID lcid,
2894 WORD flags,
2895 DISPPARAMS *params,
2896 VARIANT *result,
2897 EXCEPINFO *excep_info,
2898 UINT *arg_err )
2900 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2901 ITypeInfo *typeinfo;
2902 HRESULT hr;
2904 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
2905 lcid, flags, params, result, excep_info, arg_err);
2907 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2908 if (SUCCEEDED(hr))
2910 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
2911 params, result, excep_info, arg_err );
2912 ITypeInfo_Release( typeinfo );
2914 return hr;
2917 static HRESULT WINAPI winhttp_request_SetProxy(
2918 IWinHttpRequest *iface,
2919 HTTPREQUEST_PROXY_SETTING proxy_setting,
2920 VARIANT proxy_server,
2921 VARIANT bypass_list )
2923 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2924 DWORD err = ERROR_SUCCESS;
2926 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
2927 debugstr_variant(&bypass_list));
2929 EnterCriticalSection( &request->cs );
2930 switch (proxy_setting)
2932 case HTTPREQUEST_PROXYSETTING_DEFAULT:
2933 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
2934 heap_free( request->proxy.lpszProxy );
2935 heap_free( request->proxy.lpszProxyBypass );
2936 request->proxy.lpszProxy = NULL;
2937 request->proxy.lpszProxyBypass = NULL;
2938 break;
2940 case HTTPREQUEST_PROXYSETTING_DIRECT:
2941 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
2942 heap_free( request->proxy.lpszProxy );
2943 heap_free( request->proxy.lpszProxyBypass );
2944 request->proxy.lpszProxy = NULL;
2945 request->proxy.lpszProxyBypass = NULL;
2946 break;
2948 case HTTPREQUEST_PROXYSETTING_PROXY:
2949 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
2950 if (V_VT( &proxy_server ) == VT_BSTR)
2952 heap_free( request->proxy.lpszProxy );
2953 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
2955 if (V_VT( &bypass_list ) == VT_BSTR)
2957 heap_free( request->proxy.lpszProxyBypass );
2958 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
2960 break;
2962 default:
2963 err = ERROR_INVALID_PARAMETER;
2964 break;
2966 LeaveCriticalSection( &request->cs );
2967 return HRESULT_FROM_WIN32( err );
2970 static HRESULT WINAPI winhttp_request_SetCredentials(
2971 IWinHttpRequest *iface,
2972 BSTR username,
2973 BSTR password,
2974 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
2976 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2977 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
2978 DWORD err = ERROR_SUCCESS;
2980 TRACE("%p, %s, %p\n", request, debugstr_w(username), password);
2982 EnterCriticalSection( &request->cs );
2983 if (request->state < REQUEST_STATE_OPEN)
2985 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
2986 goto done;
2988 switch (flags)
2990 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
2991 target = WINHTTP_AUTH_TARGET_SERVER;
2992 break;
2993 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
2994 target = WINHTTP_AUTH_TARGET_PROXY;
2995 break;
2996 default:
2997 err = ERROR_INVALID_PARAMETER;
2998 goto done;
3000 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
3002 err = get_last_error();
3004 done:
3005 LeaveCriticalSection( &request->cs );
3006 return HRESULT_FROM_WIN32( err );
3009 static void initialize_request( struct winhttp_request *request )
3011 request->hrequest = NULL;
3012 request->hconnect = NULL;
3013 request->hsession = NULL;
3014 request->thread = NULL;
3015 request->wait = NULL;
3016 request->cancel = NULL;
3017 request->buffer = NULL;
3018 request->verb = NULL;
3019 request->offset = 0;
3020 request->bytes_available = 0;
3021 request->bytes_read = 0;
3022 request->error = ERROR_SUCCESS;
3023 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
3024 request->disable_feature = 0;
3025 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
3026 request->proxy.lpszProxy = NULL;
3027 request->proxy.lpszProxyBypass = NULL;
3028 request->resolve_timeout = 0;
3029 request->connect_timeout = 60000;
3030 request->send_timeout = 30000;
3031 request->receive_timeout = 30000;
3032 VariantInit( &request->data );
3033 request->state = REQUEST_STATE_INITIALIZED;
3036 static HRESULT WINAPI winhttp_request_Open(
3037 IWinHttpRequest *iface,
3038 BSTR method,
3039 BSTR url,
3040 VARIANT async )
3042 static const WCHAR typeW[] = {'*','/','*',0};
3043 static const WCHAR *acceptW[] = {typeW, NULL};
3044 static const WCHAR httpsW[] = {'h','t','t','p','s'};
3045 static const WCHAR user_agentW[] = {
3046 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
3047 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
3048 'R','e','q','u','e','s','t','.','5',')',0};
3049 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3050 HINTERNET hsession = NULL, hconnect = NULL, hrequest;
3051 URL_COMPONENTS uc;
3052 WCHAR *hostname, *path = NULL, *verb = NULL;
3053 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0, request_flags = 0;
3055 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
3056 debugstr_variant(&async));
3058 if (!method || !url) return E_INVALIDARG;
3060 memset( &uc, 0, sizeof(uc) );
3061 uc.dwStructSize = sizeof(uc);
3062 uc.dwSchemeLength = ~0u;
3063 uc.dwHostNameLength = ~0u;
3064 uc.dwUrlPathLength = ~0u;
3065 uc.dwExtraInfoLength = ~0u;
3066 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( get_last_error() );
3068 EnterCriticalSection( &request->cs );
3069 if (request->state != REQUEST_STATE_INITIALIZED)
3071 cancel_request( request );
3072 free_request( request );
3073 initialize_request( request );
3075 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
3076 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
3077 hostname[uc.dwHostNameLength] = 0;
3079 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
3080 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
3081 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
3083 if (!(verb = strdupW( method ))) goto error;
3084 if (SUCCEEDED( VariantChangeType( &async, &async, 0, VT_BOOL )) && V_BOOL( &async )) flags |= WINHTTP_FLAG_ASYNC;
3085 if (!(hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, flags )))
3087 err = get_last_error();
3088 goto error;
3090 if (!(hconnect = WinHttpConnect( hsession, hostname, uc.nPort, 0 )))
3092 err = get_last_error();
3093 goto error;
3095 len = sizeof(httpsW) / sizeof(WCHAR);
3096 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
3098 request_flags |= WINHTTP_FLAG_SECURE;
3100 if (!(hrequest = WinHttpOpenRequest( hconnect, method, path, NULL, NULL, acceptW, request_flags )))
3102 err = get_last_error();
3103 goto error;
3105 if (flags & WINHTTP_FLAG_ASYNC)
3107 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3108 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3109 WinHttpSetOption( hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3111 request->state = REQUEST_STATE_OPEN;
3112 request->hsession = hsession;
3113 request->hconnect = hconnect;
3114 request->hrequest = hrequest;
3115 request->verb = verb;
3116 heap_free( hostname );
3117 heap_free( path );
3118 LeaveCriticalSection( &request->cs );
3119 return S_OK;
3121 error:
3122 WinHttpCloseHandle( hconnect );
3123 WinHttpCloseHandle( hsession );
3124 heap_free( hostname );
3125 heap_free( path );
3126 heap_free( verb );
3127 LeaveCriticalSection( &request->cs );
3128 return HRESULT_FROM_WIN32( err );
3131 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3132 IWinHttpRequest *iface,
3133 BSTR header,
3134 BSTR value )
3136 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3137 static const WCHAR emptyW[] = {0};
3138 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3139 DWORD len, err = ERROR_SUCCESS;
3140 WCHAR *str;
3142 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3144 if (!header) return E_INVALIDARG;
3146 EnterCriticalSection( &request->cs );
3147 if (request->state < REQUEST_STATE_OPEN)
3149 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3150 goto done;
3152 if (request->state >= REQUEST_STATE_SENT)
3154 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3155 goto done;
3157 len = strlenW( header ) + 4;
3158 if (value) len += strlenW( value );
3159 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3161 err = ERROR_OUTOFMEMORY;
3162 goto done;
3164 sprintfW( str, fmtW, header, value ? value : emptyW );
3165 if (!WinHttpAddRequestHeaders( request->hrequest, str, len, WINHTTP_ADDREQ_FLAG_REPLACE ))
3167 err = get_last_error();
3169 heap_free( str );
3171 done:
3172 LeaveCriticalSection( &request->cs );
3173 return HRESULT_FROM_WIN32( err );
3176 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3177 IWinHttpRequest *iface,
3178 BSTR header,
3179 BSTR *value )
3181 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3182 DWORD size, err = ERROR_SUCCESS;
3184 TRACE("%p, %p\n", request, header);
3186 EnterCriticalSection( &request->cs );
3187 if (request->state < REQUEST_STATE_SENT)
3189 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3190 goto done;
3192 if (!header || !value)
3194 err = ERROR_INVALID_PARAMETER;
3195 goto done;
3197 size = 0;
3198 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3200 err = get_last_error();
3201 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3203 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3205 err = ERROR_OUTOFMEMORY;
3206 goto done;
3208 err = ERROR_SUCCESS;
3209 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3211 err = get_last_error();
3212 SysFreeString( *value );
3214 done:
3215 LeaveCriticalSection( &request->cs );
3216 return HRESULT_FROM_WIN32( err );
3219 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3220 IWinHttpRequest *iface,
3221 BSTR *headers )
3223 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3224 DWORD size, err = ERROR_SUCCESS;
3226 TRACE("%p, %p\n", request, headers);
3228 if (!headers) return E_INVALIDARG;
3230 EnterCriticalSection( &request->cs );
3231 if (request->state < REQUEST_STATE_SENT)
3233 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3234 goto done;
3236 size = 0;
3237 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3239 err = get_last_error();
3240 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3242 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3244 err = ERROR_OUTOFMEMORY;
3245 goto done;
3247 err = ERROR_SUCCESS;
3248 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3250 err = get_last_error();
3251 SysFreeString( *headers );
3253 done:
3254 LeaveCriticalSection( &request->cs );
3255 return HRESULT_FROM_WIN32( err );
3258 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3260 struct winhttp_request *request = (struct winhttp_request *)context;
3262 switch (status)
3264 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3265 request->bytes_available = *(DWORD *)buffer;
3266 request->error = ERROR_SUCCESS;
3267 break;
3268 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3269 request->bytes_read = size;
3270 request->error = ERROR_SUCCESS;
3271 break;
3272 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3274 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3275 request->error = result->dwError;
3276 break;
3278 default: break;
3280 SetEvent( request->wait );
3283 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3285 if (!request->wait) return;
3286 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3287 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3290 static DWORD wait_for_completion( struct winhttp_request *request )
3292 HANDLE handles[2];
3294 if (!request->wait)
3296 request->error = ERROR_SUCCESS;
3297 return ERROR_SUCCESS;
3299 handles[0] = request->wait;
3300 handles[1] = request->cancel;
3301 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3303 case WAIT_OBJECT_0:
3304 break;
3305 case WAIT_OBJECT_0 + 1:
3306 request->error = ERROR_CANCELLED;
3307 break;
3308 default:
3309 request->error = get_last_error();
3310 break;
3312 return request->error;
3315 static HRESULT request_receive( struct winhttp_request *request )
3317 DWORD err, size, buflen = 4096;
3319 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3320 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3322 return HRESULT_FROM_WIN32( get_last_error() );
3324 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3325 if (!strcmpW( request->verb, headW ))
3327 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3328 return S_OK;
3330 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3331 request->buffer[0] = 0;
3332 size = 0;
3335 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3336 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3338 err = get_last_error();
3339 goto error;
3341 if ((err = wait_for_completion( request ))) goto error;
3342 if (!request->bytes_available) break;
3343 size += request->bytes_available;
3344 if (buflen < size)
3346 char *tmp;
3347 while (buflen < size) buflen *= 2;
3348 if (!(tmp = heap_realloc( request->buffer, buflen )))
3350 err = ERROR_OUTOFMEMORY;
3351 goto error;
3353 request->buffer = tmp;
3355 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3356 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3357 request->bytes_available, &request->bytes_read ))
3359 err = get_last_error();
3360 goto error;
3362 if ((err = wait_for_completion( request ))) goto error;
3363 request->offset += request->bytes_read;
3364 } while (request->bytes_read);
3366 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3367 return S_OK;
3369 error:
3370 heap_free( request->buffer );
3371 request->buffer = NULL;
3372 return HRESULT_FROM_WIN32( err );
3375 static DWORD request_set_parameters( struct winhttp_request *request )
3377 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3378 sizeof(request->proxy) )) return get_last_error();
3380 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3381 sizeof(request->logon_policy) )) return get_last_error();
3383 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3384 sizeof(request->disable_feature) )) return get_last_error();
3386 if (!WinHttpSetTimeouts( request->hrequest,
3387 request->resolve_timeout,
3388 request->connect_timeout,
3389 request->send_timeout,
3390 request->receive_timeout )) return get_last_error();
3391 return ERROR_SUCCESS;
3394 static void request_set_utf8_content_type( struct winhttp_request *request )
3396 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3397 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3398 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3399 WCHAR headerW[64];
3400 int len;
3402 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3403 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3404 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3405 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3408 static HRESULT request_send( struct winhttp_request *request )
3410 SAFEARRAY *sa = NULL;
3411 VARIANT data;
3412 char *ptr = NULL;
3413 LONG size = 0;
3414 HRESULT hr;
3415 DWORD err;
3417 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3418 if (strcmpW( request->verb, getW ))
3420 VariantInit( &data );
3421 if (V_VT( &request->data ) == VT_BSTR)
3423 UINT cp = CP_ACP;
3424 const WCHAR *str = V_BSTR( &request->data );
3425 int i, len = strlenW( str );
3427 for (i = 0; i < len; i++)
3429 if (str[i] > 127)
3431 cp = CP_UTF8;
3432 break;
3435 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3436 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3437 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3438 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3440 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3442 sa = V_ARRAY( &data );
3443 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3444 if ((hr = SafeArrayGetUBound( sa, 1, &size )) != S_OK)
3446 SafeArrayUnaccessData( sa );
3447 return hr;
3449 size++;
3452 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3453 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3455 err = get_last_error();
3456 goto error;
3458 if ((err = wait_for_completion( request ))) goto error;
3459 if (sa) SafeArrayUnaccessData( sa );
3460 else heap_free( ptr );
3461 request->state = REQUEST_STATE_SENT;
3462 return S_OK;
3464 error:
3465 if (sa) SafeArrayUnaccessData( sa );
3466 else heap_free( ptr );
3467 return HRESULT_FROM_WIN32( err );
3470 static HRESULT request_send_and_receive( struct winhttp_request *request )
3472 HRESULT hr = request_send( request );
3473 if (hr == S_OK) hr = request_receive( request );
3474 return hr;
3477 static DWORD CALLBACK send_and_receive_proc( void *arg )
3479 struct winhttp_request *request = (struct winhttp_request *)arg;
3480 return request_send_and_receive( request );
3483 static HRESULT WINAPI winhttp_request_Send(
3484 IWinHttpRequest *iface,
3485 VARIANT body )
3487 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3488 HRESULT hr;
3490 TRACE("%p, %s\n", request, debugstr_variant(&body));
3492 EnterCriticalSection( &request->cs );
3493 if (request->state < REQUEST_STATE_OPEN)
3495 LeaveCriticalSection( &request->cs );
3496 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3498 if (request->state >= REQUEST_STATE_SENT)
3500 LeaveCriticalSection( &request->cs );
3501 return S_OK;
3503 VariantClear( &request->data );
3504 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK) {
3505 LeaveCriticalSection( &request->cs );
3506 return hr;
3509 if (request->wait) /* async request */
3511 if (!(request->thread = CreateThread( NULL, 0, send_and_receive_proc, request, 0, NULL )))
3513 LeaveCriticalSection( &request->cs );
3514 return HRESULT_FROM_WIN32( get_last_error() );
3517 else hr = request_send_and_receive( request );
3518 LeaveCriticalSection( &request->cs );
3519 return hr;
3522 static HRESULT WINAPI winhttp_request_get_Status(
3523 IWinHttpRequest *iface,
3524 LONG *status )
3526 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3527 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
3529 TRACE("%p, %p\n", request, status);
3531 if (!status) return E_INVALIDARG;
3533 EnterCriticalSection( &request->cs );
3534 if (request->state < REQUEST_STATE_SENT)
3536 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3537 goto done;
3539 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
3540 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
3542 err = get_last_error();
3543 goto done;
3545 *status = status_code;
3547 done:
3548 LeaveCriticalSection( &request->cs );
3549 return HRESULT_FROM_WIN32( err );
3552 static HRESULT WINAPI winhttp_request_get_StatusText(
3553 IWinHttpRequest *iface,
3554 BSTR *status )
3556 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3557 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
3559 TRACE("%p, %p\n", request, status);
3561 if (!status) return E_INVALIDARG;
3563 EnterCriticalSection( &request->cs );
3564 if (request->state < REQUEST_STATE_SENT)
3566 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3567 goto done;
3569 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
3571 err = get_last_error();
3572 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3574 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
3576 err = ERROR_OUTOFMEMORY;
3577 goto done;
3579 index = 0;
3580 err = ERROR_SUCCESS;
3581 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
3583 err = get_last_error();
3584 SysFreeString( *status );
3586 done:
3587 LeaveCriticalSection( &request->cs );
3588 return HRESULT_FROM_WIN32( err );
3591 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
3593 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
3594 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
3595 WCHAR *buffer, *p;
3596 DWORD size;
3598 *codepage = CP_ACP;
3599 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
3600 get_last_error() == ERROR_INSUFFICIENT_BUFFER)
3602 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
3603 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
3605 return get_last_error();
3607 if ((p = strstrW( buffer, charsetW )))
3609 p += strlenW( charsetW );
3610 while (*p == ' ') p++;
3611 if (*p++ == '=')
3613 while (*p == ' ') p++;
3614 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
3617 heap_free( buffer );
3619 return ERROR_SUCCESS;
3622 static HRESULT WINAPI winhttp_request_get_ResponseText(
3623 IWinHttpRequest *iface,
3624 BSTR *body )
3626 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3627 UINT codepage;
3628 DWORD err = ERROR_SUCCESS;
3629 int len;
3631 TRACE("%p, %p\n", request, body);
3633 if (!body) return E_INVALIDARG;
3635 EnterCriticalSection( &request->cs );
3636 if (request->state < REQUEST_STATE_SENT)
3638 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3639 goto done;
3641 if ((err = request_get_codepage( request, &codepage ))) goto done;
3642 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
3643 if (!(*body = SysAllocStringLen( NULL, len )))
3645 err = ERROR_OUTOFMEMORY;
3646 goto done;
3648 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
3649 (*body)[len] = 0;
3651 done:
3652 LeaveCriticalSection( &request->cs );
3653 return HRESULT_FROM_WIN32( err );
3656 static HRESULT WINAPI winhttp_request_get_ResponseBody(
3657 IWinHttpRequest *iface,
3658 VARIANT *body )
3660 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3661 SAFEARRAY *sa;
3662 HRESULT hr;
3663 DWORD err = ERROR_SUCCESS;
3664 char *ptr;
3666 TRACE("%p, %p\n", request, body);
3668 if (!body) return E_INVALIDARG;
3670 EnterCriticalSection( &request->cs );
3671 if (request->state < REQUEST_STATE_SENT)
3673 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3674 goto done;
3676 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
3678 err = ERROR_OUTOFMEMORY;
3679 goto done;
3681 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
3683 SafeArrayDestroy( sa );
3684 LeaveCriticalSection( &request->cs );
3685 return hr;
3687 memcpy( ptr, request->buffer, request->offset );
3688 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
3690 SafeArrayDestroy( sa );
3691 LeaveCriticalSection( &request->cs );
3692 return hr;
3694 V_VT( body ) = VT_ARRAY|VT_UI1;
3695 V_ARRAY( body ) = sa;
3697 done:
3698 LeaveCriticalSection( &request->cs );
3699 return HRESULT_FROM_WIN32( err );
3702 struct stream
3704 IStream IStream_iface;
3705 LONG refs;
3706 char *data;
3707 ULARGE_INTEGER pos, size;
3710 static inline struct stream *impl_from_IStream( IStream *iface )
3712 return CONTAINING_RECORD( iface, struct stream, IStream_iface );
3715 static HRESULT WINAPI stream_QueryInterface( IStream *iface, REFIID riid, void **obj )
3717 struct stream *stream = impl_from_IStream( iface );
3719 TRACE("%p, %s, %p\n", stream, debugstr_guid(riid), obj);
3721 if (IsEqualGUID( riid, &IID_IStream ) || IsEqualGUID( riid, &IID_IUnknown ))
3723 *obj = iface;
3725 else
3727 FIXME("interface %s not implemented\n", debugstr_guid(riid));
3728 return E_NOINTERFACE;
3730 IStream_AddRef( iface );
3731 return S_OK;
3734 static ULONG WINAPI stream_AddRef( IStream *iface )
3736 struct stream *stream = impl_from_IStream( iface );
3737 return InterlockedIncrement( &stream->refs );
3740 static ULONG WINAPI stream_Release( IStream *iface )
3742 struct stream *stream = impl_from_IStream( iface );
3743 LONG refs = InterlockedDecrement( &stream->refs );
3744 if (!refs)
3746 heap_free( stream->data );
3747 heap_free( stream );
3749 return refs;
3752 static HRESULT WINAPI stream_Read( IStream *iface, void *buf, ULONG len, ULONG *read )
3754 struct stream *stream = impl_from_IStream( iface );
3755 ULONG size;
3757 if (stream->pos.QuadPart >= stream->size.QuadPart)
3759 *read = 0;
3760 return S_FALSE;
3763 size = min( stream->size.QuadPart - stream->pos.QuadPart, len );
3764 memcpy( buf, stream->data + stream->pos.QuadPart, size );
3765 stream->pos.QuadPart += size;
3766 *read = size;
3768 return S_OK;
3771 static HRESULT WINAPI stream_Write( IStream *iface, const void *buf, ULONG len, ULONG *written )
3773 FIXME("\n");
3774 return E_NOTIMPL;
3777 static HRESULT WINAPI stream_Seek( IStream *iface, LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *newpos )
3779 struct stream *stream = impl_from_IStream( iface );
3781 if (origin == STREAM_SEEK_SET)
3782 stream->pos.QuadPart = move.QuadPart;
3783 else if (origin == STREAM_SEEK_CUR)
3784 stream->pos.QuadPart += move.QuadPart;
3785 else if (origin == STREAM_SEEK_END)
3786 stream->pos.QuadPart = stream->size.QuadPart - move.QuadPart;
3788 if (newpos) newpos->QuadPart = stream->pos.QuadPart;
3789 return S_OK;
3792 static HRESULT WINAPI stream_SetSize( IStream *iface, ULARGE_INTEGER newsize )
3794 FIXME("\n");
3795 return E_NOTIMPL;
3798 static HRESULT WINAPI stream_CopyTo( IStream *iface, IStream *stream, ULARGE_INTEGER len, ULARGE_INTEGER *read,
3799 ULARGE_INTEGER *written )
3801 FIXME("\n");
3802 return E_NOTIMPL;
3805 static HRESULT WINAPI stream_Commit( IStream *iface, DWORD flags )
3807 FIXME("\n");
3808 return E_NOTIMPL;
3811 static HRESULT WINAPI stream_Revert( IStream *iface )
3813 FIXME("\n");
3814 return E_NOTIMPL;
3817 static HRESULT WINAPI stream_LockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
3819 FIXME("\n");
3820 return E_NOTIMPL;
3823 static HRESULT WINAPI stream_UnlockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
3825 FIXME("\n");
3826 return E_NOTIMPL;
3829 static HRESULT WINAPI stream_Stat( IStream *iface, STATSTG *stg, DWORD flag )
3831 FIXME("\n");
3832 return E_NOTIMPL;
3835 static HRESULT WINAPI stream_Clone( IStream *iface, IStream **stream )
3837 FIXME("\n");
3838 return E_NOTIMPL;
3841 static const IStreamVtbl stream_vtbl =
3843 stream_QueryInterface,
3844 stream_AddRef,
3845 stream_Release,
3846 stream_Read,
3847 stream_Write,
3848 stream_Seek,
3849 stream_SetSize,
3850 stream_CopyTo,
3851 stream_Commit,
3852 stream_Revert,
3853 stream_LockRegion,
3854 stream_UnlockRegion,
3855 stream_Stat,
3856 stream_Clone
3859 static HRESULT WINAPI winhttp_request_get_ResponseStream(
3860 IWinHttpRequest *iface,
3861 VARIANT *body )
3863 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3864 DWORD err = ERROR_SUCCESS;
3865 struct stream *stream;
3867 TRACE("%p, %p\n", request, body);
3869 if (!body) return E_INVALIDARG;
3871 EnterCriticalSection( &request->cs );
3872 if (request->state < REQUEST_STATE_SENT)
3874 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3875 goto done;
3877 if (!(stream = heap_alloc( sizeof(*stream) )))
3879 err = ERROR_OUTOFMEMORY;
3880 goto done;
3882 stream->IStream_iface.lpVtbl = &stream_vtbl;
3883 stream->refs = 1;
3884 if (!(stream->data = heap_alloc( request->offset )))
3886 heap_free( stream );
3887 err = ERROR_OUTOFMEMORY;
3888 goto done;
3890 memcpy( stream->data, request->buffer, request->offset );
3891 stream->pos.QuadPart = 0;
3892 stream->size.QuadPart = request->offset;
3893 V_VT( body ) = VT_UNKNOWN;
3894 V_UNKNOWN( body ) = (IUnknown *)&stream->IStream_iface;
3896 done:
3897 LeaveCriticalSection( &request->cs );
3898 return HRESULT_FROM_WIN32( err );
3901 static HRESULT WINAPI winhttp_request_get_Option(
3902 IWinHttpRequest *iface,
3903 WinHttpRequestOption option,
3904 VARIANT *value )
3906 FIXME("\n");
3907 return E_NOTIMPL;
3910 static HRESULT WINAPI winhttp_request_put_Option(
3911 IWinHttpRequest *iface,
3912 WinHttpRequestOption option,
3913 VARIANT value )
3915 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3916 HRESULT hr = S_OK;
3918 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
3920 EnterCriticalSection( &request->cs );
3921 switch (option)
3923 case WinHttpRequestOption_EnableRedirects:
3925 if (V_BOOL( &value ))
3926 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
3927 else
3928 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
3929 break;
3931 default:
3932 FIXME("unimplemented option %u\n", option);
3933 hr = E_NOTIMPL;
3934 break;
3936 LeaveCriticalSection( &request->cs );
3937 return hr;
3940 /* critical section must be held */
3941 static DWORD wait_for_response( struct winhttp_request *request, DWORD timeout )
3943 HANDLE thread = request->thread;
3944 DWORD err, ret;
3946 LeaveCriticalSection( &request->cs );
3947 while ((err = MsgWaitForMultipleObjects( 1, &thread, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3949 MSG msg;
3950 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3952 TranslateMessage( &msg );
3953 DispatchMessageW( &msg );
3956 switch (err)
3958 case WAIT_OBJECT_0:
3959 ret = ERROR_SUCCESS;
3960 break;
3961 case WAIT_TIMEOUT:
3962 ret = ERROR_TIMEOUT;
3963 break;
3964 case WAIT_FAILED:
3965 default:
3966 ret = get_last_error();
3967 break;
3969 EnterCriticalSection( &request->cs );
3970 return ret;
3973 static HRESULT WINAPI winhttp_request_WaitForResponse(
3974 IWinHttpRequest *iface,
3975 VARIANT timeout,
3976 VARIANT_BOOL *succeeded )
3978 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3979 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
3981 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
3983 EnterCriticalSection( &request->cs );
3984 if (!request->thread)
3986 LeaveCriticalSection( &request->cs );
3987 return S_OK;
3989 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
3991 LeaveCriticalSection( &request->cs );
3992 return S_OK;
3994 switch ((err = wait_for_response( request, msecs )))
3996 case ERROR_TIMEOUT:
3997 if (succeeded) *succeeded = VARIANT_FALSE;
3998 err = ERROR_SUCCESS;
3999 break;
4001 case ERROR_SUCCESS:
4002 if (succeeded) *succeeded = VARIANT_TRUE;
4003 break;
4005 default: break;
4007 LeaveCriticalSection( &request->cs );
4008 return HRESULT_FROM_WIN32( err );
4011 static HRESULT WINAPI winhttp_request_Abort(
4012 IWinHttpRequest *iface )
4014 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4016 TRACE("%p\n", request);
4018 EnterCriticalSection( &request->cs );
4019 cancel_request( request );
4020 LeaveCriticalSection( &request->cs );
4021 return S_OK;
4024 static HRESULT WINAPI winhttp_request_SetTimeouts(
4025 IWinHttpRequest *iface,
4026 LONG resolve_timeout,
4027 LONG connect_timeout,
4028 LONG send_timeout,
4029 LONG receive_timeout )
4031 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4033 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
4035 EnterCriticalSection( &request->cs );
4036 request->resolve_timeout = resolve_timeout;
4037 request->connect_timeout = connect_timeout;
4038 request->send_timeout = send_timeout;
4039 request->receive_timeout = receive_timeout;
4040 LeaveCriticalSection( &request->cs );
4041 return S_OK;
4044 static HRESULT WINAPI winhttp_request_SetClientCertificate(
4045 IWinHttpRequest *iface,
4046 BSTR certificate )
4048 FIXME("\n");
4049 return E_NOTIMPL;
4052 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
4053 IWinHttpRequest *iface,
4054 WinHttpRequestAutoLogonPolicy policy )
4056 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4057 HRESULT hr = S_OK;
4059 TRACE("%p, %u\n", request, policy );
4061 EnterCriticalSection( &request->cs );
4062 switch (policy)
4064 case AutoLogonPolicy_Always:
4065 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
4066 break;
4067 case AutoLogonPolicy_OnlyIfBypassProxy:
4068 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
4069 break;
4070 case AutoLogonPolicy_Never:
4071 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
4072 break;
4073 default: hr = E_INVALIDARG;
4074 break;
4076 LeaveCriticalSection( &request->cs );
4077 return hr;
4080 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
4082 winhttp_request_QueryInterface,
4083 winhttp_request_AddRef,
4084 winhttp_request_Release,
4085 winhttp_request_GetTypeInfoCount,
4086 winhttp_request_GetTypeInfo,
4087 winhttp_request_GetIDsOfNames,
4088 winhttp_request_Invoke,
4089 winhttp_request_SetProxy,
4090 winhttp_request_SetCredentials,
4091 winhttp_request_Open,
4092 winhttp_request_SetRequestHeader,
4093 winhttp_request_GetResponseHeader,
4094 winhttp_request_GetAllResponseHeaders,
4095 winhttp_request_Send,
4096 winhttp_request_get_Status,
4097 winhttp_request_get_StatusText,
4098 winhttp_request_get_ResponseText,
4099 winhttp_request_get_ResponseBody,
4100 winhttp_request_get_ResponseStream,
4101 winhttp_request_get_Option,
4102 winhttp_request_put_Option,
4103 winhttp_request_WaitForResponse,
4104 winhttp_request_Abort,
4105 winhttp_request_SetTimeouts,
4106 winhttp_request_SetClientCertificate,
4107 winhttp_request_SetAutoLogonPolicy
4110 HRESULT WinHttpRequest_create( void **obj )
4112 struct winhttp_request *request;
4114 TRACE("%p\n", obj);
4116 if (!(request = heap_alloc( sizeof(*request) ))) return E_OUTOFMEMORY;
4117 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
4118 request->refs = 1;
4119 request->state = REQUEST_STATE_UNINITIALIZED;
4120 request->proxy.lpszProxy = NULL;
4121 request->proxy.lpszProxyBypass = NULL;
4122 InitializeCriticalSection( &request->cs );
4123 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
4125 *obj = &request->IWinHttpRequest_iface;
4126 TRACE("returning iface %p\n", *obj);
4127 return S_OK;