winhttp: Fill the read buffer first in drain_content.
[wine.git] / dlls / winhttp / request.c
blob75a229d5764a0af22cbba846ca48639affa1a6ca
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 DWORD CALLBACK task_thread( LPVOID param )
183 task_header_t *task = param;
185 task->proc( task );
187 release_object( &task->request->hdr );
188 heap_free( task );
189 return ERROR_SUCCESS;
192 static BOOL queue_task( task_header_t *task )
194 return QueueUserWorkItem( task_thread, task, WT_EXECUTELONGFUNCTION );
197 static void free_header( header_t *header )
199 heap_free( header->field );
200 heap_free( header->value );
201 heap_free( header );
204 static BOOL valid_token_char( WCHAR c )
206 if (c < 32 || c == 127) return FALSE;
207 switch (c)
209 case '(': case ')':
210 case '<': case '>':
211 case '@': case ',':
212 case ';': case ':':
213 case '\\': case '\"':
214 case '/': case '[':
215 case ']': case '?':
216 case '=': case '{':
217 case '}': case ' ':
218 case '\t':
219 return FALSE;
220 default:
221 return TRUE;
225 static header_t *parse_header( LPCWSTR string )
227 const WCHAR *p, *q;
228 header_t *header;
229 int len;
231 p = string;
232 if (!(q = strchrW( p, ':' )))
234 WARN("no ':' in line %s\n", debugstr_w(string));
235 return NULL;
237 if (q == string)
239 WARN("empty field name in line %s\n", debugstr_w(string));
240 return NULL;
242 while (*p != ':')
244 if (!valid_token_char( *p ))
246 WARN("invalid character in field name %s\n", debugstr_w(string));
247 return NULL;
249 p++;
251 len = q - string;
252 if (!(header = heap_alloc_zero( sizeof(header_t) ))) return NULL;
253 if (!(header->field = heap_alloc( (len + 1) * sizeof(WCHAR) )))
255 heap_free( header );
256 return NULL;
258 memcpy( header->field, string, len * sizeof(WCHAR) );
259 header->field[len] = 0;
261 q++; /* skip past colon */
262 while (*q == ' ') q++;
263 if (!*q)
265 WARN("no value in line %s\n", debugstr_w(string));
266 return header;
268 len = strlenW( q );
269 if (!(header->value = heap_alloc( (len + 1) * sizeof(WCHAR) )))
271 free_header( header );
272 return NULL;
274 memcpy( header->value, q, len * sizeof(WCHAR) );
275 header->value[len] = 0;
277 return header;
280 static int get_header_index( request_t *request, LPCWSTR field, int requested_index, BOOL request_only )
282 int index;
284 TRACE("%s\n", debugstr_w(field));
286 for (index = 0; index < request->num_headers; index++)
288 if (strcmpiW( request->headers[index].field, field )) continue;
289 if (request_only && !request->headers[index].is_request) continue;
290 if (!request_only && request->headers[index].is_request) continue;
292 if (!requested_index) break;
293 requested_index--;
295 if (index >= request->num_headers) index = -1;
296 TRACE("returning %d\n", index);
297 return index;
300 static BOOL insert_header( request_t *request, header_t *header )
302 DWORD count;
303 header_t *hdrs;
305 count = request->num_headers + 1;
306 if (count > 1)
307 hdrs = heap_realloc_zero( request->headers, sizeof(header_t) * count );
308 else
309 hdrs = heap_alloc_zero( sizeof(header_t) * count );
311 if (hdrs)
313 request->headers = hdrs;
314 request->headers[count - 1].field = strdupW( header->field );
315 request->headers[count - 1].value = strdupW( header->value );
316 request->headers[count - 1].is_request = header->is_request;
317 request->num_headers++;
318 return TRUE;
320 return FALSE;
323 static BOOL delete_header( request_t *request, DWORD index )
325 if (!request->num_headers) return FALSE;
326 if (index >= request->num_headers) return FALSE;
327 request->num_headers--;
329 heap_free( request->headers[index].field );
330 heap_free( request->headers[index].value );
332 memmove( &request->headers[index], &request->headers[index + 1], (request->num_headers - index) * sizeof(header_t) );
333 memset( &request->headers[request->num_headers], 0, sizeof(header_t) );
334 return TRUE;
337 static BOOL process_header( request_t *request, LPCWSTR field, LPCWSTR value, DWORD flags, BOOL request_only )
339 int index;
340 header_t *header;
342 TRACE("%s: %s 0x%08x\n", debugstr_w(field), debugstr_w(value), flags);
344 /* replace wins out over add */
345 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE) flags &= ~WINHTTP_ADDREQ_FLAG_ADD;
347 if (flags & WINHTTP_ADDREQ_FLAG_ADD) index = -1;
348 else
349 index = get_header_index( request, field, 0, request_only );
351 if (index >= 0)
353 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return FALSE;
354 header = &request->headers[index];
356 else if (value)
358 header_t hdr;
360 hdr.field = (LPWSTR)field;
361 hdr.value = (LPWSTR)value;
362 hdr.is_request = request_only;
364 return insert_header( request, &hdr );
366 /* no value to delete */
367 else return TRUE;
369 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
371 delete_header( request, index );
372 if (value)
374 header_t hdr;
376 hdr.field = (LPWSTR)field;
377 hdr.value = (LPWSTR)value;
378 hdr.is_request = request_only;
380 return insert_header( request, &hdr );
382 return TRUE;
384 else if (flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON))
386 WCHAR sep, *tmp;
387 int len, orig_len, value_len;
389 orig_len = strlenW( header->value );
390 value_len = strlenW( value );
392 if (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) sep = ',';
393 else sep = ';';
395 len = orig_len + value_len + 2;
396 if ((tmp = heap_realloc( header->value, (len + 1) * sizeof(WCHAR) )))
398 header->value = tmp;
400 header->value[orig_len] = sep;
401 orig_len++;
402 header->value[orig_len] = ' ';
403 orig_len++;
405 memcpy( &header->value[orig_len], value, value_len * sizeof(WCHAR) );
406 header->value[len] = 0;
407 return TRUE;
410 return TRUE;
413 BOOL add_request_headers( request_t *request, LPCWSTR headers, DWORD len, DWORD flags )
415 BOOL ret = FALSE;
416 WCHAR *buffer, *p, *q;
417 header_t *header;
419 if (len == ~0u) len = strlenW( headers );
420 if (!len) return TRUE;
421 if (!(buffer = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
422 strcpyW( buffer, headers );
424 p = buffer;
427 q = p;
428 while (*q)
430 if (q[0] == '\n' && q[1] == '\r')
432 q[0] = '\r';
433 q[1] = '\n';
435 if (q[0] == '\r' && q[1] == '\n') break;
436 q++;
438 if (!*p) break;
439 if (*q == '\r')
441 *q = 0;
442 q += 2; /* jump over \r\n */
444 if ((header = parse_header( p )))
446 ret = process_header( request, header->field, header->value, flags, TRUE );
447 free_header( header );
449 p = q;
450 } while (ret);
452 heap_free( buffer );
453 return ret;
456 /***********************************************************************
457 * WinHttpAddRequestHeaders (winhttp.@)
459 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, LPCWSTR headers, DWORD len, DWORD flags )
461 BOOL ret;
462 request_t *request;
464 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest, debugstr_w(headers), len, flags);
466 if (!headers)
468 set_last_error( ERROR_INVALID_PARAMETER );
469 return FALSE;
471 if (!(request = (request_t *)grab_object( hrequest )))
473 set_last_error( ERROR_INVALID_HANDLE );
474 return FALSE;
476 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
478 release_object( &request->hdr );
479 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
480 return FALSE;
483 ret = add_request_headers( request, headers, len, flags );
485 release_object( &request->hdr );
486 return ret;
489 static WCHAR *build_request_path( request_t *request )
491 WCHAR *ret;
493 if (strcmpiW( request->connect->hostname, request->connect->servername ))
495 static const WCHAR http[] = { 'h','t','t','p',0 };
496 static const WCHAR https[] = { 'h','t','t','p','s',0 };
497 static const WCHAR fmt[] = { '%','s',':','/','/','%','s',0 };
498 LPCWSTR scheme = request->netconn.secure ? https : http;
499 int len;
501 len = strlenW( scheme ) + strlenW( request->connect->hostname );
502 /* 3 characters for '://', 1 for NUL. */
503 len += 4;
504 if (request->connect->hostport)
506 /* 1 for ':' between host and port, up to 5 for port */
507 len += 6;
509 if (request->path)
510 len += strlenW( request->path );
511 if ((ret = heap_alloc( len * sizeof(WCHAR) )))
513 sprintfW( ret, fmt, scheme, request->connect->hostname );
514 if (request->connect->hostport)
516 static const WCHAR colonFmt[] = { ':','%','u',0 };
518 sprintfW( ret + strlenW( ret ), colonFmt,
519 request->connect->hostport );
521 if (request->path)
522 strcatW( ret, request->path );
525 else
526 ret = request->path;
527 return ret;
530 static WCHAR *build_request_string( request_t *request )
532 static const WCHAR space[] = {' ',0};
533 static const WCHAR crlf[] = {'\r','\n',0};
534 static const WCHAR colon[] = {':',' ',0};
535 static const WCHAR twocrlf[] = {'\r','\n','\r','\n',0};
537 WCHAR *path, *ret;
538 const WCHAR **headers, **p;
539 unsigned int len, i = 0, j;
541 /* allocate space for an array of all the string pointers to be added */
542 len = request->num_headers * 4 + 7;
543 if (!(headers = heap_alloc( len * sizeof(LPCWSTR) ))) return NULL;
545 path = build_request_path( request );
546 headers[i++] = request->verb;
547 headers[i++] = space;
548 headers[i++] = path;
549 headers[i++] = space;
550 headers[i++] = request->version;
552 for (j = 0; j < request->num_headers; j++)
554 if (request->headers[j].is_request)
556 headers[i++] = crlf;
557 headers[i++] = request->headers[j].field;
558 headers[i++] = colon;
559 headers[i++] = request->headers[j].value;
561 TRACE("adding header %s (%s)\n", debugstr_w(request->headers[j].field),
562 debugstr_w(request->headers[j].value));
565 headers[i++] = twocrlf;
566 headers[i] = NULL;
568 len = 0;
569 for (p = headers; *p; p++) len += strlenW( *p );
570 len++;
572 if (!(ret = heap_alloc( len * sizeof(WCHAR) )))
573 goto out;
574 *ret = 0;
575 for (p = headers; *p; p++) strcatW( ret, *p );
577 out:
578 if (path != request->path)
579 heap_free( path );
580 heap_free( headers );
581 return ret;
584 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
586 static BOOL query_headers( request_t *request, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
588 header_t *header = NULL;
589 BOOL request_only, ret = FALSE;
590 int requested_index, header_index = -1;
591 DWORD attr, len;
593 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
594 requested_index = index ? *index : 0;
596 attr = level & ~QUERY_MODIFIER_MASK;
597 switch (attr)
599 case WINHTTP_QUERY_CUSTOM:
601 header_index = get_header_index( request, name, requested_index, request_only );
602 break;
604 case WINHTTP_QUERY_RAW_HEADERS:
606 WCHAR *headers, *p, *q;
608 if (request_only)
609 headers = build_request_string( request );
610 else
611 headers = request->raw_headers;
613 if (!(p = headers)) return FALSE;
614 for (len = 0; *p; p++) if (*p != '\r') len++;
616 if (!buffer || (len + 1) * sizeof(WCHAR) > *buflen)
618 len++;
619 set_last_error( ERROR_INSUFFICIENT_BUFFER );
621 else
623 for (p = headers, q = buffer; *p; p++, q++)
625 if (*p != '\r') *q = *p;
626 else
628 *q = 0;
629 p++; /* skip '\n' */
632 *q = 0;
633 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
634 ret = TRUE;
636 *buflen = len * sizeof(WCHAR);
637 if (request_only) heap_free( headers );
638 return ret;
640 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
642 WCHAR *headers;
644 if (request_only)
645 headers = build_request_string( request );
646 else
647 headers = request->raw_headers;
649 if (!headers) return FALSE;
650 len = strlenW( headers ) * sizeof(WCHAR);
651 if (!buffer || len + sizeof(WCHAR) > *buflen)
653 len += sizeof(WCHAR);
654 set_last_error( ERROR_INSUFFICIENT_BUFFER );
656 else
658 memcpy( buffer, headers, len + sizeof(WCHAR) );
659 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
660 ret = TRUE;
662 *buflen = len;
663 if (request_only) heap_free( headers );
664 return ret;
666 case WINHTTP_QUERY_VERSION:
667 len = strlenW( request->version ) * sizeof(WCHAR);
668 if (!buffer || len + sizeof(WCHAR) > *buflen)
670 len += sizeof(WCHAR);
671 set_last_error( ERROR_INSUFFICIENT_BUFFER );
673 else
675 strcpyW( buffer, request->version );
676 TRACE("returning string: %s\n", debugstr_w(buffer));
677 ret = TRUE;
679 *buflen = len;
680 return ret;
682 case WINHTTP_QUERY_STATUS_TEXT:
683 len = strlenW( request->status_text ) * sizeof(WCHAR);
684 if (!buffer || len + sizeof(WCHAR) > *buflen)
686 len += sizeof(WCHAR);
687 set_last_error( ERROR_INSUFFICIENT_BUFFER );
689 else
691 strcpyW( buffer, request->status_text );
692 TRACE("returning string: %s\n", debugstr_w(buffer));
693 ret = TRUE;
695 *buflen = len;
696 return ret;
698 default:
699 if (attr >= sizeof(attribute_table)/sizeof(attribute_table[0]) || !attribute_table[attr])
701 FIXME("attribute %u not implemented\n", attr);
702 return FALSE;
704 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
705 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
706 break;
709 if (header_index >= 0)
711 header = &request->headers[header_index];
713 if (!header || (request_only && !header->is_request))
715 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND );
716 return FALSE;
718 if (index) *index += 1;
719 if (level & WINHTTP_QUERY_FLAG_NUMBER)
721 if (!buffer || sizeof(int) > *buflen)
723 set_last_error( ERROR_INSUFFICIENT_BUFFER );
725 else
727 int *number = buffer;
728 *number = atoiW( header->value );
729 TRACE("returning number: %d\n", *number);
730 ret = TRUE;
732 *buflen = sizeof(int);
734 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
736 SYSTEMTIME *st = buffer;
737 if (!buffer || sizeof(SYSTEMTIME) > *buflen)
739 set_last_error( ERROR_INSUFFICIENT_BUFFER );
741 else if ((ret = WinHttpTimeToSystemTime( header->value, st )))
743 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
744 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
745 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
747 *buflen = sizeof(SYSTEMTIME);
749 else if (header->value)
751 len = strlenW( header->value ) * sizeof(WCHAR);
752 if (!buffer || len + sizeof(WCHAR) > *buflen)
754 len += sizeof(WCHAR);
755 set_last_error( ERROR_INSUFFICIENT_BUFFER );
757 else
759 strcpyW( buffer, header->value );
760 TRACE("returning string: %s\n", debugstr_w(buffer));
761 ret = TRUE;
763 *buflen = len;
765 return ret;
768 /***********************************************************************
769 * WinHttpQueryHeaders (winhttp.@)
771 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, LPCWSTR name, LPVOID buffer, LPDWORD buflen, LPDWORD index )
773 BOOL ret;
774 request_t *request;
776 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index);
778 if (!(request = (request_t *)grab_object( hrequest )))
780 set_last_error( ERROR_INVALID_HANDLE );
781 return FALSE;
783 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
785 release_object( &request->hdr );
786 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
787 return FALSE;
790 ret = query_headers( request, level, name, buffer, buflen, index );
792 release_object( &request->hdr );
793 return ret;
796 static LPWSTR concatenate_string_list( LPCWSTR *list, int len )
798 LPCWSTR *t;
799 LPWSTR str;
801 for( t = list; *t ; t++ )
802 len += strlenW( *t );
803 len++;
805 str = heap_alloc( len * sizeof(WCHAR) );
806 if (!str) return NULL;
807 *str = 0;
809 for( t = list; *t ; t++ )
810 strcatW( str, *t );
812 return str;
815 static LPWSTR build_header_request_string( request_t *request, LPCWSTR verb,
816 LPCWSTR path, LPCWSTR version )
818 static const WCHAR crlf[] = {'\r','\n',0};
819 static const WCHAR space[] = { ' ',0 };
820 static const WCHAR colon[] = { ':',' ',0 };
821 static const WCHAR twocrlf[] = {'\r','\n','\r','\n', 0};
822 LPWSTR requestString;
823 DWORD len, n;
824 LPCWSTR *req;
825 UINT i;
826 LPWSTR p;
828 /* allocate space for an array of all the string pointers to be added */
829 len = (request->num_headers) * 4 + 10;
830 req = heap_alloc( len * sizeof(LPCWSTR) );
831 if (!req) return NULL;
833 /* add the verb, path and HTTP version string */
834 n = 0;
835 req[n++] = verb;
836 req[n++] = space;
837 req[n++] = path;
838 req[n++] = space;
839 req[n++] = version;
841 /* Append custom request headers */
842 for (i = 0; i < request->num_headers; i++)
844 if (request->headers[i].is_request)
846 req[n++] = crlf;
847 req[n++] = request->headers[i].field;
848 req[n++] = colon;
849 req[n++] = request->headers[i].value;
851 TRACE("Adding custom header %s (%s)\n",
852 debugstr_w(request->headers[i].field),
853 debugstr_w(request->headers[i].value));
857 if( n >= len )
858 ERR("oops. buffer overrun\n");
860 req[n] = NULL;
861 requestString = concatenate_string_list( req, 4 );
862 heap_free( req );
863 if (!requestString) return NULL;
866 * Set (header) termination string for request
867 * Make sure there are exactly two new lines at the end of the request
869 p = &requestString[strlenW(requestString)-1];
870 while ( (*p == '\n') || (*p == '\r') )
871 p--;
872 strcpyW( p+1, twocrlf );
874 return requestString;
877 static BOOL read_reply( request_t *request );
879 static BOOL secure_proxy_connect( request_t *request )
881 static const WCHAR verbConnect[] = {'C','O','N','N','E','C','T',0};
882 static const WCHAR fmt[] = {'%','s',':','%','u',0};
883 BOOL ret = FALSE;
884 LPWSTR path;
885 connect_t *connect = request->connect;
887 path = heap_alloc( (strlenW( connect->hostname ) + 13) * sizeof(WCHAR) );
888 if (path)
890 LPWSTR requestString;
892 sprintfW( path, fmt, connect->hostname, connect->hostport );
893 requestString = build_header_request_string( request, verbConnect,
894 path, http1_1 );
895 heap_free( path );
896 if (requestString)
898 LPSTR req_ascii = strdupWA( requestString );
900 heap_free( requestString );
901 if (req_ascii)
903 int len = strlen( req_ascii ), bytes_sent;
905 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
906 heap_free( req_ascii );
907 if (ret)
908 ret = read_reply( request );
912 return ret;
915 #ifndef INET6_ADDRSTRLEN
916 #define INET6_ADDRSTRLEN 46
917 #endif
919 static WCHAR *addr_to_str( const struct sockaddr *addr )
921 char buf[INET6_ADDRSTRLEN];
922 const void *src;
924 switch (addr->sa_family)
926 case AF_INET:
927 src = &((struct sockaddr_in *)addr)->sin_addr;
928 break;
929 case AF_INET6:
930 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
931 break;
932 default:
933 WARN("unsupported address family %d\n", addr->sa_family);
934 return NULL;
936 if (!inet_ntop( addr->sa_family, src, buf, sizeof(buf) )) return NULL;
937 return strdupAW( buf );
940 static BOOL open_connection( request_t *request )
942 connect_t *connect;
943 WCHAR *addressW = NULL;
944 INTERNET_PORT port;
945 socklen_t slen;
946 struct sockaddr *saddr;
947 DWORD len;
949 if (netconn_connected( &request->netconn )) goto done;
951 connect = request->connect;
952 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
953 saddr = (struct sockaddr *)&connect->sockaddr;
954 slen = sizeof(struct sockaddr);
956 if (!connect->resolved)
958 len = strlenW( connect->servername ) + 1;
959 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, connect->servername, len );
961 if (!netconn_resolve( connect->servername, port, saddr, &slen, request->resolve_timeout )) return FALSE;
962 connect->resolved = TRUE;
964 if (!(addressW = addr_to_str( saddr ))) return FALSE;
965 len = strlenW( addressW ) + 1;
966 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
968 if (!addressW && !(addressW = addr_to_str( saddr ))) return FALSE;
969 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
971 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, 0 );
973 if (!netconn_create( &request->netconn, saddr->sa_family, SOCK_STREAM, 0 ))
975 heap_free( addressW );
976 return FALSE;
978 netconn_set_timeout( &request->netconn, TRUE, request->send_timeout );
979 netconn_set_timeout( &request->netconn, FALSE, request->recv_timeout );
980 if (!netconn_connect( &request->netconn, saddr, slen, request->connect_timeout ))
982 netconn_close( &request->netconn );
983 heap_free( addressW );
984 return FALSE;
986 if (request->hdr.flags & WINHTTP_FLAG_SECURE)
988 if (connect->session->proxy_server &&
989 strcmpiW( connect->hostname, connect->servername ))
991 if (!secure_proxy_connect( request ))
993 heap_free( addressW );
994 return FALSE;
997 if (!netconn_secure_connect( &request->netconn, connect->servername ))
999 netconn_close( &request->netconn );
1000 heap_free( addressW );
1001 return FALSE;
1005 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, strlenW(addressW) + 1 );
1007 done:
1008 request->read_pos = request->read_size = 0;
1009 request->read_chunked = FALSE;
1010 request->read_chunked_size = ~0u;
1011 request->read_chunked_eof = FALSE;
1012 heap_free( addressW );
1013 return TRUE;
1016 void close_connection( request_t *request )
1018 if (!netconn_connected( &request->netconn )) return;
1020 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1021 netconn_close( &request->netconn );
1022 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1025 static BOOL add_host_header( request_t *request, DWORD modifier )
1027 BOOL ret;
1028 DWORD len;
1029 WCHAR *host;
1030 static const WCHAR fmt[] = {'%','s',':','%','u',0};
1031 connect_t *connect = request->connect;
1032 INTERNET_PORT port;
1034 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1036 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1038 return process_header( request, attr_host, connect->hostname, modifier, TRUE );
1040 len = strlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1041 if (!(host = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
1042 sprintfW( host, fmt, connect->hostname, port );
1043 ret = process_header( request, attr_host, host, modifier, TRUE );
1044 heap_free( host );
1045 return ret;
1048 static void clear_response_headers( request_t *request )
1050 unsigned int i;
1052 for (i = 0; i < request->num_headers; i++)
1054 if (!request->headers[i].field) continue;
1055 if (!request->headers[i].value) continue;
1056 if (request->headers[i].is_request) continue;
1057 delete_header( request, i );
1058 i--;
1062 static BOOL send_request( request_t *request, LPCWSTR headers, DWORD headers_len, LPVOID optional,
1063 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
1065 static const WCHAR keep_alive[] = {'K','e','e','p','-','A','l','i','v','e',0};
1066 static const WCHAR no_cache[] = {'n','o','-','c','a','c','h','e',0};
1067 static const WCHAR length_fmt[] = {'%','l','d',0};
1069 BOOL ret = FALSE;
1070 connect_t *connect = request->connect;
1071 session_t *session = connect->session;
1072 WCHAR *req = NULL;
1073 char *req_ascii;
1074 int bytes_sent;
1075 DWORD len, i, flags;
1077 clear_response_headers( request );
1079 flags = WINHTTP_ADDREQ_FLAG_ADD|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
1080 for (i = 0; i < request->num_accept_types; i++)
1082 process_header( request, attr_accept, request->accept_types[i], flags, TRUE );
1084 if (session->agent)
1085 process_header( request, attr_user_agent, session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1087 if (connect->hostname)
1088 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
1090 if (total_len || (request->verb && !strcmpW( request->verb, postW )))
1092 WCHAR length[21]; /* decimal long int + null */
1093 sprintfW( length, length_fmt, total_len );
1094 process_header( request, attr_content_length, length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1096 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
1098 process_header( request, attr_connection, keep_alive, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1100 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
1102 process_header( request, attr_pragma, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1103 process_header( request, attr_cache_control, no_cache, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
1105 if (headers && !add_request_headers( request, headers, headers_len, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
1107 TRACE("failed to add request headers\n");
1108 return FALSE;
1110 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && !add_cookie_headers( request ))
1112 WARN("failed to add cookie headers\n");
1113 return FALSE;
1116 if (context) request->hdr.context = context;
1118 if (!(ret = open_connection( request ))) goto end;
1119 if (!(req = build_request_string( request ))) goto end;
1121 if (!(req_ascii = strdupWA( req ))) goto end;
1122 TRACE("full request: %s\n", debugstr_a(req_ascii));
1123 len = strlen(req_ascii);
1125 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
1127 ret = netconn_send( &request->netconn, req_ascii, len, &bytes_sent );
1128 heap_free( req_ascii );
1129 if (!ret) goto end;
1131 if (optional_len)
1133 if (!netconn_send( &request->netconn, optional, optional_len, &bytes_sent )) goto end;
1134 request->optional = optional;
1135 request->optional_len = optional_len;
1136 len += optional_len;
1138 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(len) );
1140 end:
1141 if (async)
1143 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
1144 else
1146 WINHTTP_ASYNC_RESULT result;
1147 result.dwResult = API_SEND_REQUEST;
1148 result.dwError = get_last_error();
1149 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
1152 heap_free( req );
1153 return ret;
1156 static void task_send_request( task_header_t *task )
1158 send_request_t *s = (send_request_t *)task;
1159 send_request( s->hdr.request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
1160 heap_free( s->headers );
1163 /***********************************************************************
1164 * WinHttpSendRequest (winhttp.@)
1166 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, LPCWSTR headers, DWORD headers_len,
1167 LPVOID optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
1169 BOOL ret;
1170 request_t *request;
1172 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1173 hrequest, debugstr_w(headers), headers_len, optional_len, total_len, context);
1175 if (!(request = (request_t *)grab_object( hrequest )))
1177 set_last_error( ERROR_INVALID_HANDLE );
1178 return FALSE;
1180 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1182 release_object( &request->hdr );
1183 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1184 return FALSE;
1187 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
1189 send_request_t *s;
1191 if (!(s = heap_alloc( sizeof(send_request_t) ))) return FALSE;
1192 s->hdr.request = request;
1193 s->hdr.proc = task_send_request;
1194 s->headers = strdupW( headers );
1195 s->headers_len = headers_len;
1196 s->optional = optional;
1197 s->optional_len = optional_len;
1198 s->total_len = total_len;
1199 s->context = context;
1201 addref_object( &request->hdr );
1202 ret = queue_task( (task_header_t *)s );
1204 else
1205 ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
1207 release_object( &request->hdr );
1208 return ret;
1211 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1213 static const WCHAR basicW[] = {'B','a','s','i','c',0};
1214 static const WCHAR ntlmW[] = {'N','T','L','M',0};
1215 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
1216 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
1217 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
1219 static const struct
1221 const WCHAR *str;
1222 unsigned int len;
1223 DWORD scheme;
1225 auth_schemes[] =
1227 { basicW, ARRAYSIZE(basicW) - 1, WINHTTP_AUTH_SCHEME_BASIC },
1228 { ntlmW, ARRAYSIZE(ntlmW) - 1, WINHTTP_AUTH_SCHEME_NTLM },
1229 { passportW, ARRAYSIZE(passportW) - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
1230 { digestW, ARRAYSIZE(digestW) - 1, WINHTTP_AUTH_SCHEME_DIGEST },
1231 { negotiateW, ARRAYSIZE(negotiateW) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
1233 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
1235 static enum auth_scheme scheme_from_flag( DWORD flag )
1237 int i;
1239 for (i = 0; i < num_auth_schemes; i++) if (flag == auth_schemes[i].scheme) return i;
1240 return SCHEME_INVALID;
1243 static DWORD auth_scheme_from_header( WCHAR *header )
1245 unsigned int i;
1247 for (i = 0; i < num_auth_schemes; i++)
1249 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
1250 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
1252 return 0;
1255 static BOOL query_auth_schemes( request_t *request, DWORD level, LPDWORD supported, LPDWORD first )
1257 DWORD index = 0;
1258 BOOL ret = FALSE;
1260 for (;;)
1262 WCHAR *buffer;
1263 DWORD size, scheme;
1265 size = 0;
1266 query_headers( request, level, NULL, NULL, &size, &index );
1267 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) break;
1269 index--;
1270 if (!(buffer = heap_alloc( size ))) return FALSE;
1271 if (!query_headers( request, level, NULL, buffer, &size, &index ))
1273 heap_free( buffer );
1274 return FALSE;
1276 scheme = auth_scheme_from_header( buffer );
1277 heap_free( buffer );
1278 if (!scheme) break;
1280 if (first && index == 1)
1281 *first = *supported = scheme;
1282 else
1283 *supported |= scheme;
1285 ret = TRUE;
1287 return ret;
1290 /***********************************************************************
1291 * WinHttpQueryAuthSchemes (winhttp.@)
1293 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
1295 BOOL ret = FALSE;
1296 request_t *request;
1298 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
1300 if (!(request = (request_t *)grab_object( hrequest )))
1302 set_last_error( ERROR_INVALID_HANDLE );
1303 return FALSE;
1305 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1307 release_object( &request->hdr );
1308 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1309 return FALSE;
1311 if (!supported || !first || !target)
1313 release_object( &request->hdr );
1314 set_last_error( ERROR_INVALID_PARAMETER );
1315 return FALSE;
1319 if (query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first ))
1321 *target = WINHTTP_AUTH_TARGET_SERVER;
1322 ret = TRUE;
1324 else if (query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first ))
1326 *target = WINHTTP_AUTH_TARGET_PROXY;
1327 ret = TRUE;
1330 release_object( &request->hdr );
1331 return ret;
1334 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
1336 UINT n = 0, x;
1337 static const char base64enc[] =
1338 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1340 while (len > 0)
1342 /* first 6 bits, all from bin[0] */
1343 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
1344 x = (bin[0] & 3) << 4;
1346 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1347 if (len == 1)
1349 base64[n++] = base64enc[x];
1350 base64[n++] = '=';
1351 base64[n++] = '=';
1352 break;
1354 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
1355 x = (bin[1] & 0x0f) << 2;
1357 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1358 if (len == 2)
1360 base64[n++] = base64enc[x];
1361 base64[n++] = '=';
1362 break;
1364 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
1366 /* last 6 bits, all from bin [2] */
1367 base64[n++] = base64enc[bin[2] & 0x3f];
1368 bin += 3;
1369 len -= 3;
1371 base64[n] = 0;
1372 return n;
1375 static inline char decode_char( WCHAR c )
1377 if (c >= 'A' && c <= 'Z') return c - 'A';
1378 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1379 if (c >= '0' && c <= '9') return c - '0' + 52;
1380 if (c == '+') return 62;
1381 if (c == '/') return 63;
1382 return 64;
1385 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
1387 unsigned int i = 0;
1388 char c0, c1, c2, c3;
1389 const WCHAR *p = base64;
1391 while (len > 4)
1393 if ((c0 = decode_char( p[0] )) > 63) return 0;
1394 if ((c1 = decode_char( p[1] )) > 63) return 0;
1395 if ((c2 = decode_char( p[2] )) > 63) return 0;
1396 if ((c3 = decode_char( p[3] )) > 63) return 0;
1398 if (buf)
1400 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1401 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1402 buf[i + 2] = (c2 << 6) | c3;
1404 len -= 4;
1405 i += 3;
1406 p += 4;
1408 if (p[2] == '=')
1410 if ((c0 = decode_char( p[0] )) > 63) return 0;
1411 if ((c1 = decode_char( p[1] )) > 63) return 0;
1413 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1414 i++;
1416 else if (p[3] == '=')
1418 if ((c0 = decode_char( p[0] )) > 63) return 0;
1419 if ((c1 = decode_char( p[1] )) > 63) return 0;
1420 if ((c2 = decode_char( p[2] )) > 63) return 0;
1422 if (buf)
1424 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1425 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1427 i += 2;
1429 else
1431 if ((c0 = decode_char( p[0] )) > 63) return 0;
1432 if ((c1 = decode_char( p[1] )) > 63) return 0;
1433 if ((c2 = decode_char( p[2] )) > 63) return 0;
1434 if ((c3 = decode_char( p[3] )) > 63) return 0;
1436 if (buf)
1438 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1439 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1440 buf[i + 2] = (c2 << 6) | c3;
1442 i += 3;
1444 return i;
1447 static struct authinfo *alloc_authinfo(void)
1449 struct authinfo *ret;
1451 if (!(ret = heap_alloc( sizeof(*ret) ))) return NULL;
1453 SecInvalidateHandle( &ret->cred );
1454 SecInvalidateHandle( &ret->ctx );
1455 memset( &ret->exp, 0, sizeof(ret->exp) );
1456 ret->scheme = 0;
1457 ret->attr = 0;
1458 ret->max_token = 0;
1459 ret->data = NULL;
1460 ret->data_len = 0;
1461 ret->finished = FALSE;
1462 return ret;
1465 void destroy_authinfo( struct authinfo *authinfo )
1467 if (!authinfo) return;
1469 if (SecIsValidHandle( &authinfo->ctx ))
1470 DeleteSecurityContext( &authinfo->ctx );
1471 if (SecIsValidHandle( &authinfo->cred ))
1472 FreeCredentialsHandle( &authinfo->cred );
1474 heap_free( authinfo->data );
1475 heap_free( authinfo );
1478 static BOOL get_authvalue( request_t *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1480 DWORD size, index = 0;
1481 for (;;)
1483 size = len;
1484 if (!query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1485 if (auth_scheme_from_header( buffer ) == scheme) break;
1487 return TRUE;
1490 static BOOL do_authorization( request_t *request, DWORD target, DWORD scheme_flag )
1492 struct authinfo *authinfo, **auth_ptr;
1493 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1494 const WCHAR *auth_target, *username, *password;
1495 WCHAR auth_value[2048], *auth_reply;
1496 DWORD len = sizeof(auth_value), len_scheme, flags;
1497 BOOL ret;
1499 if (scheme == SCHEME_INVALID) return FALSE;
1501 switch (target)
1503 case WINHTTP_AUTH_TARGET_SERVER:
1504 if (!get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len ))
1505 return FALSE;
1506 auth_ptr = &request->authinfo;
1507 auth_target = attr_authorization;
1508 username = request->connect->username;
1509 password = request->connect->password;
1510 break;
1512 case WINHTTP_AUTH_TARGET_PROXY:
1513 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1514 return FALSE;
1515 auth_ptr = &request->proxy_authinfo;
1516 auth_target = attr_proxy_authorization;
1517 username = request->connect->session->proxy_username;
1518 password = request->connect->session->proxy_password;
1519 break;
1521 default:
1522 WARN("unknown target %x\n", target);
1523 return FALSE;
1525 authinfo = *auth_ptr;
1527 switch (scheme)
1529 case SCHEME_BASIC:
1531 int userlen, passlen;
1533 if (!username || !password) return FALSE;
1534 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1536 userlen = WideCharToMultiByte( CP_UTF8, 0, username, strlenW( username ), NULL, 0, NULL, NULL );
1537 passlen = WideCharToMultiByte( CP_UTF8, 0, password, strlenW( password ), NULL, 0, NULL, NULL );
1539 authinfo->data_len = userlen + 1 + passlen;
1540 if (!(authinfo->data = heap_alloc( authinfo->data_len ))) return FALSE;
1542 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1543 authinfo->data[userlen] = ':';
1544 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1546 authinfo->scheme = SCHEME_BASIC;
1547 authinfo->finished = TRUE;
1548 break;
1550 case SCHEME_NTLM:
1551 case SCHEME_NEGOTIATE:
1553 SECURITY_STATUS status;
1554 SecBufferDesc out_desc, in_desc;
1555 SecBuffer out, in;
1556 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1557 const WCHAR *p;
1558 BOOL first = FALSE;
1560 if (!authinfo)
1562 TimeStamp exp;
1563 SEC_WINNT_AUTH_IDENTITY_W id;
1564 WCHAR *domain, *user;
1566 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1568 first = TRUE;
1569 domain = (WCHAR *)username;
1570 user = strchrW( username, '\\' );
1572 if (user) user++;
1573 else
1575 user = (WCHAR *)username;
1576 domain = NULL;
1578 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1579 id.User = user;
1580 id.UserLength = strlenW( user );
1581 id.Domain = domain;
1582 id.DomainLength = domain ? user - domain - 1 : 0;
1583 id.Password = (WCHAR *)password;
1584 id.PasswordLength = strlenW( password );
1586 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1587 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1588 &authinfo->cred, &exp );
1589 if (status == SEC_E_OK)
1591 PSecPkgInfoW info;
1592 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1593 if (status == SEC_E_OK)
1595 authinfo->max_token = info->cbMaxToken;
1596 FreeContextBuffer( info );
1599 if (status != SEC_E_OK)
1601 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1602 debugstr_w(auth_schemes[scheme].str), status);
1603 heap_free( authinfo );
1604 return FALSE;
1606 authinfo->scheme = scheme;
1608 else if (authinfo->finished) return FALSE;
1610 if ((strlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1611 strncmpiW( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1613 ERR("authentication scheme changed from %s to %s\n",
1614 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1615 destroy_authinfo( authinfo );
1616 *auth_ptr = NULL;
1617 return FALSE;
1619 in.BufferType = SECBUFFER_TOKEN;
1620 in.cbBuffer = 0;
1621 in.pvBuffer = NULL;
1623 in_desc.ulVersion = 0;
1624 in_desc.cBuffers = 1;
1625 in_desc.pBuffers = &in;
1627 p = auth_value + auth_schemes[scheme].len;
1628 if (*p == ' ')
1630 int len = strlenW( ++p );
1631 in.cbBuffer = decode_base64( p, len, NULL );
1632 if (!(in.pvBuffer = heap_alloc( in.cbBuffer ))) {
1633 destroy_authinfo( authinfo );
1634 *auth_ptr = NULL;
1635 return FALSE;
1637 decode_base64( p, len, in.pvBuffer );
1639 out.BufferType = SECBUFFER_TOKEN;
1640 out.cbBuffer = authinfo->max_token;
1641 if (!(out.pvBuffer = heap_alloc( authinfo->max_token )))
1643 heap_free( in.pvBuffer );
1644 destroy_authinfo( authinfo );
1645 *auth_ptr = NULL;
1646 return FALSE;
1648 out_desc.ulVersion = 0;
1649 out_desc.cBuffers = 1;
1650 out_desc.pBuffers = &out;
1652 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1653 first ? request->connect->servername : NULL, flags, 0,
1654 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1655 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1656 heap_free( in.pvBuffer );
1657 if (status == SEC_E_OK)
1659 heap_free( authinfo->data );
1660 authinfo->data = out.pvBuffer;
1661 authinfo->data_len = out.cbBuffer;
1662 authinfo->finished = TRUE;
1663 TRACE("sending last auth packet\n");
1665 else if (status == SEC_I_CONTINUE_NEEDED)
1667 heap_free( authinfo->data );
1668 authinfo->data = out.pvBuffer;
1669 authinfo->data_len = out.cbBuffer;
1670 TRACE("sending next auth packet\n");
1672 else
1674 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status);
1675 heap_free( out.pvBuffer );
1676 destroy_authinfo( authinfo );
1677 *auth_ptr = NULL;
1678 return FALSE;
1680 break;
1682 default:
1683 ERR("invalid scheme %u\n", scheme);
1684 return FALSE;
1686 *auth_ptr = authinfo;
1688 len_scheme = auth_schemes[authinfo->scheme].len;
1689 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1690 if (!(auth_reply = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1692 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1693 auth_reply[len_scheme] = ' ';
1694 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1696 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1697 ret = process_header( request, auth_target, auth_reply, flags, TRUE );
1698 heap_free( auth_reply );
1699 return ret;
1702 static BOOL set_credentials( request_t *request, DWORD target, DWORD scheme, const WCHAR *username,
1703 const WCHAR *password )
1705 if ((scheme == WINHTTP_AUTH_SCHEME_BASIC || scheme == WINHTTP_AUTH_SCHEME_DIGEST) &&
1706 (!username || !password))
1708 set_last_error( ERROR_INVALID_PARAMETER );
1709 return FALSE;
1711 switch (target)
1713 case WINHTTP_AUTH_TARGET_SERVER:
1715 heap_free( request->connect->username );
1716 if (!username) request->connect->username = NULL;
1717 else if (!(request->connect->username = strdupW( username ))) return FALSE;
1719 heap_free( request->connect->password );
1720 if (!password) request->connect->password = NULL;
1721 else if (!(request->connect->password = strdupW( password ))) return FALSE;
1722 break;
1724 case WINHTTP_AUTH_TARGET_PROXY:
1726 heap_free( request->connect->session->proxy_username );
1727 if (!username) request->connect->session->proxy_username = NULL;
1728 else if (!(request->connect->session->proxy_username = strdupW( username ))) return FALSE;
1730 heap_free( request->connect->session->proxy_password );
1731 if (!password) request->connect->session->proxy_password = NULL;
1732 else if (!(request->connect->session->proxy_password = strdupW( password ))) return FALSE;
1733 break;
1735 default:
1736 WARN("unknown target %u\n", target);
1737 return FALSE;
1739 return TRUE;
1742 /***********************************************************************
1743 * WinHttpSetCredentials (winhttp.@)
1745 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, LPCWSTR username,
1746 LPCWSTR password, LPVOID params )
1748 BOOL ret;
1749 request_t *request;
1751 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params);
1753 if (!(request = (request_t *)grab_object( hrequest )))
1755 set_last_error( ERROR_INVALID_HANDLE );
1756 return FALSE;
1758 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
1760 release_object( &request->hdr );
1761 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
1762 return FALSE;
1765 ret = set_credentials( request, target, scheme, username, password );
1767 release_object( &request->hdr );
1768 return ret;
1771 static BOOL handle_authorization( request_t *request, DWORD status )
1773 DWORD i, schemes, first, level, target;
1775 switch (status)
1777 case HTTP_STATUS_DENIED:
1778 target = WINHTTP_AUTH_TARGET_SERVER;
1779 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
1780 break;
1782 case HTTP_STATUS_PROXY_AUTH_REQ:
1783 target = WINHTTP_AUTH_TARGET_PROXY;
1784 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
1785 break;
1787 default:
1788 WARN("unhandled status %u\n", status);
1789 return FALSE;
1792 if (!query_auth_schemes( request, level, &schemes, &first )) return FALSE;
1793 if (do_authorization( request, target, first )) return TRUE;
1795 schemes &= ~first;
1796 for (i = 0; i < num_auth_schemes; i++)
1798 if (!(schemes & auth_schemes[i].scheme)) continue;
1799 if (do_authorization( request, target, auth_schemes[i].scheme )) return TRUE;
1801 return FALSE;
1804 /* set the request content length based on the headers */
1805 static DWORD set_content_length( request_t *request )
1807 WCHAR encoding[20];
1808 DWORD buflen;
1810 buflen = sizeof(request->content_length);
1811 if (!query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
1812 NULL, &request->content_length, &buflen, NULL ))
1813 request->content_length = ~0u;
1815 buflen = sizeof(encoding);
1816 if (query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
1817 !strcmpiW( encoding, chunkedW ))
1819 request->content_length = ~0u;
1820 request->read_chunked = TRUE;
1821 request->read_chunked_size = ~0u;
1822 request->read_chunked_eof = FALSE;
1824 request->content_read = 0;
1825 return request->content_length;
1828 /* read some more data into the read buffer */
1829 static BOOL read_more_data( request_t *request, int maxlen, BOOL notify )
1831 int len;
1832 BOOL ret;
1834 if (request->read_chunked_eof) return FALSE;
1836 if (request->read_size && request->read_pos)
1838 /* move existing data to the start of the buffer */
1839 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1840 request->read_pos = 0;
1842 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1844 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1846 ret = netconn_recv( &request->netconn, request->read_buf + request->read_size,
1847 maxlen - request->read_size, 0, &len );
1849 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &len, sizeof(len) );
1851 request->read_size += len;
1852 return ret;
1855 /* remove some amount of data from the read buffer */
1856 static void remove_data( request_t *request, int count )
1858 if (!(request->read_size -= count)) request->read_pos = 0;
1859 else request->read_pos += count;
1862 static BOOL read_line( request_t *request, char *buffer, DWORD *len )
1864 int count, bytes_read, pos = 0;
1866 for (;;)
1868 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1869 if (eol)
1871 count = eol - (request->read_buf + request->read_pos);
1872 bytes_read = count + 1;
1874 else count = bytes_read = request->read_size;
1876 count = min( count, *len - pos );
1877 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
1878 pos += count;
1879 remove_data( request, bytes_read );
1880 if (eol) break;
1882 if (!read_more_data( request, -1, TRUE )) return FALSE;
1883 if (!request->read_size)
1885 *len = 0;
1886 TRACE("returning empty string\n");
1887 return FALSE;
1890 if (pos < *len)
1892 if (pos && buffer[pos - 1] == '\r') pos--;
1893 *len = pos + 1;
1895 buffer[*len - 1] = 0;
1896 TRACE("returning %s\n", debugstr_a(buffer));
1897 return TRUE;
1900 /* discard data contents until we reach end of line */
1901 static BOOL discard_eol( request_t *request, BOOL notify )
1905 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1906 if (eol)
1908 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1909 break;
1911 request->read_pos = request->read_size = 0; /* discard everything */
1912 if (!read_more_data( request, -1, notify )) return FALSE;
1913 } while (request->read_size);
1914 return TRUE;
1917 /* read the size of the next chunk */
1918 static BOOL start_next_chunk( request_t *request, BOOL notify )
1920 DWORD chunk_size = 0;
1922 assert(!request->read_chunked_size || request->read_chunked_size == ~0u);
1924 if (request->read_chunked_eof) return FALSE;
1926 /* read terminator for the previous chunk */
1927 if (!request->read_chunked_size && !discard_eol( request, notify )) return FALSE;
1929 for (;;)
1931 while (request->read_size)
1933 char ch = request->read_buf[request->read_pos];
1934 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
1935 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
1936 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
1937 else if (ch == ';' || ch == '\r' || ch == '\n')
1939 TRACE("reading %u byte chunk\n", chunk_size);
1941 if (request->content_length == ~0u) request->content_length = chunk_size;
1942 else request->content_length += chunk_size;
1944 request->read_chunked_size = chunk_size;
1945 if (!chunk_size) request->read_chunked_eof = TRUE;
1947 return discard_eol( request, notify );
1949 remove_data( request, 1 );
1951 if (!read_more_data( request, -1, notify )) return FALSE;
1952 if (!request->read_size)
1954 request->content_length = request->content_read = 0;
1955 request->read_chunked_size = 0;
1956 return TRUE;
1961 /* return the size of data available to be read immediately */
1962 static DWORD get_available_data( request_t *request )
1964 if (request->read_chunked) return min( request->read_chunked_size, request->read_size );
1965 return request->read_size;
1968 /* check if we have reached the end of the data to read */
1969 static BOOL end_of_read_data( request_t *request )
1971 if (request->read_chunked) return request->read_chunked_eof;
1972 if (request->content_length == ~0u) return FALSE;
1973 return (request->content_length == request->content_read);
1976 static BOOL refill_buffer( request_t *request, BOOL notify )
1978 int len = sizeof(request->read_buf);
1980 if (request->read_chunked)
1982 if (request->read_chunked_eof) return FALSE;
1983 if (request->read_chunked_size == ~0u || !request->read_chunked_size)
1985 if (!start_next_chunk( request, notify )) return FALSE;
1988 if (!request->read_chunked && request->content_length != ~0u)
1989 len = min( len, request->content_length - request->content_read );
1990 if (len <= request->read_size) return TRUE;
1991 if (!read_more_data( request, len, notify )) return FALSE;
1992 if (!request->read_size) request->content_length = request->content_read = 0;
1993 return TRUE;
1996 #define MAX_REPLY_LEN 1460
1997 #define INITIAL_HEADER_BUFFER_LEN 512
1999 static BOOL read_reply( request_t *request )
2001 static const WCHAR crlf[] = {'\r','\n',0};
2003 char buffer[MAX_REPLY_LEN];
2004 DWORD buflen, len, offset, received_len, crlf_len = 2; /* strlenW(crlf) */
2005 char *status_code, *status_text;
2006 WCHAR *versionW, *status_textW, *raw_headers;
2007 WCHAR status_codeW[4]; /* sizeof("nnn") */
2009 if (!netconn_connected( &request->netconn )) return FALSE;
2011 received_len = 0;
2014 buflen = MAX_REPLY_LEN;
2015 if (!read_line( request, buffer, &buflen )) return FALSE;
2016 received_len += buflen;
2018 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2019 if (!(status_code = strchr( buffer, ' ' ))) return FALSE;
2020 status_code++;
2021 if (!(status_text = strchr( status_code, ' ' ))) return FALSE;
2022 if ((len = status_text - status_code) != sizeof("nnn") - 1) return FALSE;
2023 status_text++;
2025 TRACE("version [%s] status code [%s] status text [%s]\n",
2026 debugstr_an(buffer, status_code - buffer - 1),
2027 debugstr_an(status_code, len),
2028 debugstr_a(status_text));
2030 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
2032 /* we rely on the fact that the protocol is ascii */
2033 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2034 status_codeW[len] = 0;
2035 if (!(process_header( request, attr_status, status_codeW, WINHTTP_ADDREQ_FLAG_REPLACE, FALSE ))) return FALSE;
2037 len = status_code - buffer;
2038 if (!(versionW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2039 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2040 versionW[len - 1] = 0;
2042 heap_free( request->version );
2043 request->version = versionW;
2045 len = buflen - (status_text - buffer);
2046 if (!(status_textW = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2047 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2049 heap_free( request->status_text );
2050 request->status_text = status_textW;
2052 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2053 if (!(raw_headers = heap_alloc( len * sizeof(WCHAR) ))) return FALSE;
2054 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2055 memcpy( raw_headers + buflen - 1, crlf, sizeof(crlf) );
2057 heap_free( request->raw_headers );
2058 request->raw_headers = raw_headers;
2060 offset = buflen + crlf_len - 1;
2061 for (;;)
2063 header_t *header;
2065 buflen = MAX_REPLY_LEN;
2066 if (!read_line( request, buffer, &buflen )) return TRUE;
2067 received_len += buflen;
2068 if (!*buffer) break;
2070 while (len - offset < buflen + crlf_len)
2072 WCHAR *tmp;
2073 len *= 2;
2074 if (!(tmp = heap_realloc( raw_headers, len * sizeof(WCHAR) ))) return FALSE;
2075 request->raw_headers = raw_headers = tmp;
2077 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2079 if (!(header = parse_header( raw_headers + offset ))) break;
2080 if (!(process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2082 free_header( header );
2083 break;
2085 free_header( header );
2086 memcpy( raw_headers + offset + buflen - 1, crlf, sizeof(crlf) );
2087 offset += buflen + crlf_len - 1;
2090 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2091 return TRUE;
2094 static void finished_reading( request_t *request )
2096 static const WCHAR closeW[] = {'c','l','o','s','e',0};
2098 BOOL close = FALSE;
2099 WCHAR connection[20];
2100 DWORD size = sizeof(connection);
2102 if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
2103 else if (query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
2104 query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
2106 if (!strcmpiW( connection, closeW )) close = TRUE;
2108 else if (!strcmpW( request->version, http1_0 )) close = TRUE;
2109 if (close) close_connection( request );
2112 static BOOL read_data( request_t *request, void *buffer, DWORD size, DWORD *read, BOOL async )
2114 int count, bytes_read = 0;
2116 if (end_of_read_data( request )) goto done;
2118 while (size)
2120 if (!(count = get_available_data( request )))
2122 if (!refill_buffer( request, async )) goto done;
2123 if (!(count = get_available_data( request ))) goto done;
2125 count = min( count, size );
2126 memcpy( (char *)buffer + bytes_read, request->read_buf + request->read_pos, count );
2127 remove_data( request, count );
2128 if (request->read_chunked) request->read_chunked_size -= count;
2129 size -= count;
2130 bytes_read += count;
2131 request->content_read += count;
2132 if (end_of_read_data( request )) goto done;
2134 if (request->read_chunked && !request->read_chunked_size) refill_buffer( request, async );
2136 done:
2137 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read, request->content_read, request->content_length );
2139 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
2140 if (read) *read = bytes_read;
2141 if (end_of_read_data( request )) finished_reading( request );
2142 return TRUE;
2145 /* read any content returned by the server so that the connection can be reused */
2146 static void drain_content( request_t *request )
2148 DWORD bytes_read;
2149 char buffer[2048];
2151 refill_buffer( request, FALSE );
2152 for (;;)
2154 if (!read_data( request, buffer, sizeof(buffer), &bytes_read, FALSE ) || !bytes_read) return;
2158 static void record_cookies( request_t *request )
2160 unsigned int i;
2162 for (i = 0; i < request->num_headers; i++)
2164 header_t *set_cookie = &request->headers[i];
2165 if (!strcmpiW( set_cookie->field, attr_set_cookie ) && !set_cookie->is_request)
2167 set_cookies( request, set_cookie->value );
2172 static WCHAR *get_redirect_url( request_t *request, DWORD *len )
2174 DWORD size;
2175 WCHAR *ret;
2177 query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2178 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
2179 if (!(ret = heap_alloc( size ))) return NULL;
2180 *len = size / sizeof(WCHAR);
2181 if (query_headers( request, WINHTTP_QUERY_LOCATION, NULL, ret, &size, NULL )) return ret;
2182 heap_free( ret );
2183 return NULL;
2186 static BOOL handle_redirect( request_t *request, DWORD status )
2188 BOOL ret = FALSE;
2189 DWORD len, len_url;
2190 URL_COMPONENTS uc;
2191 connect_t *connect = request->connect;
2192 INTERNET_PORT port;
2193 WCHAR *hostname = NULL, *location;
2194 int index;
2196 if (!(location = get_redirect_url( request, &len_url ))) return FALSE;
2198 memset( &uc, 0, sizeof(uc) );
2199 uc.dwStructSize = sizeof(uc);
2200 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2202 if (!WinHttpCrackUrl( location, len_url, 0, &uc )) /* assume relative redirect */
2204 WCHAR *path, *p;
2206 len = strlenW( location ) + 1;
2207 if (location[0] != '/') len++;
2208 if (!(p = path = heap_alloc( len * sizeof(WCHAR) ))) goto end;
2210 if (location[0] != '/') *p++ = '/';
2211 strcpyW( p, location );
2213 heap_free( request->path );
2214 request->path = path;
2216 drain_content( request );
2217 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2219 else
2221 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2223 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) goto end;
2224 TRACE("redirect from secure page to non-secure page\n");
2225 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2227 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2229 TRACE("redirect from non-secure page to secure page\n");
2230 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2233 drain_content( request );
2234 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_url + 1 );
2236 len = uc.dwHostNameLength;
2237 if (!(hostname = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2238 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2239 hostname[len] = 0;
2241 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2242 if (strcmpiW( connect->hostname, hostname ) || connect->serverport != port)
2244 heap_free( connect->hostname );
2245 connect->hostname = hostname;
2246 connect->hostport = port;
2247 if (!(ret = set_server_for_hostname( connect, hostname, port ))) goto end;
2249 netconn_close( &request->netconn );
2250 if (!(ret = netconn_init( &request->netconn ))) goto end;
2251 request->read_pos = request->read_size = 0;
2252 request->read_chunked = FALSE;
2253 request->read_chunked_eof = FALSE;
2255 else heap_free( hostname );
2257 if (!(ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2258 if (!(ret = open_connection( request ))) goto end;
2260 heap_free( request->path );
2261 request->path = NULL;
2262 if (uc.dwUrlPathLength)
2264 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2265 if (!(request->path = heap_alloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2266 strcpyW( request->path, uc.lpszUrlPath );
2268 else request->path = strdupW( slashW );
2271 /* remove content-type/length headers */
2272 if ((index = get_header_index( request, attr_content_type, 0, TRUE )) >= 0) delete_header( request, index );
2273 if ((index = get_header_index( request, attr_content_length, 0, TRUE )) >= 0 ) delete_header( request, index );
2275 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !strcmpW( request->verb, postW ))
2277 heap_free( request->verb );
2278 request->verb = strdupW( getW );
2279 request->optional = NULL;
2280 request->optional_len = 0;
2282 ret = TRUE;
2284 end:
2285 heap_free( location );
2286 return ret;
2289 static BOOL receive_response( request_t *request, BOOL async )
2291 BOOL ret;
2292 DWORD size, query, status;
2294 for (;;)
2296 if (!(ret = read_reply( request )))
2298 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE );
2299 break;
2301 size = sizeof(DWORD);
2302 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2303 if (!(ret = query_headers( request, query, NULL, &status, &size, NULL ))) break;
2305 set_content_length( request );
2307 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2309 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2311 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2312 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) break;
2314 if (!(ret = handle_redirect( request, status ))) break;
2316 /* recurse synchronously */
2317 send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE );
2318 continue;
2320 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2322 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) break;
2324 drain_content( request );
2325 if (!handle_authorization( request, status ))
2327 ret = TRUE;
2328 break;
2330 /* recurse synchronously */
2331 send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE );
2332 continue;
2334 break;
2337 if (ret) refill_buffer( request, FALSE );
2339 if (async)
2341 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2342 else
2344 WINHTTP_ASYNC_RESULT result;
2345 result.dwResult = API_RECEIVE_RESPONSE;
2346 result.dwError = get_last_error();
2347 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2350 return ret;
2353 static void task_receive_response( task_header_t *task )
2355 receive_response_t *r = (receive_response_t *)task;
2356 receive_response( r->hdr.request, TRUE );
2359 /***********************************************************************
2360 * WinHttpReceiveResponse (winhttp.@)
2362 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
2364 BOOL ret;
2365 request_t *request;
2367 TRACE("%p, %p\n", hrequest, reserved);
2369 if (!(request = (request_t *)grab_object( hrequest )))
2371 set_last_error( ERROR_INVALID_HANDLE );
2372 return FALSE;
2374 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2376 release_object( &request->hdr );
2377 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2378 return FALSE;
2381 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2383 receive_response_t *r;
2385 if (!(r = heap_alloc( sizeof(receive_response_t) ))) return FALSE;
2386 r->hdr.request = request;
2387 r->hdr.proc = task_receive_response;
2389 addref_object( &request->hdr );
2390 ret = queue_task( (task_header_t *)r );
2392 else
2393 ret = receive_response( request, FALSE );
2395 release_object( &request->hdr );
2396 return ret;
2399 static BOOL query_data_available( request_t *request, DWORD *available, BOOL async )
2401 DWORD count = get_available_data( request );
2403 if (!request->read_chunked)
2404 count += netconn_query_data_available( &request->netconn );
2405 if (!count)
2407 refill_buffer( request, async );
2408 count = get_available_data( request );
2409 if (!request->read_chunked)
2410 count += netconn_query_data_available( &request->netconn );
2413 if (async) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
2414 TRACE("%u bytes available\n", count);
2415 if (available) *available = count;
2416 return TRUE;
2419 static void task_query_data_available( task_header_t *task )
2421 query_data_t *q = (query_data_t *)task;
2422 query_data_available( q->hdr.request, q->available, TRUE );
2425 /***********************************************************************
2426 * WinHttpQueryDataAvailable (winhttp.@)
2428 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
2430 BOOL ret;
2431 request_t *request;
2433 TRACE("%p, %p\n", hrequest, available);
2435 if (!(request = (request_t *)grab_object( hrequest )))
2437 set_last_error( ERROR_INVALID_HANDLE );
2438 return FALSE;
2440 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2442 release_object( &request->hdr );
2443 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2444 return FALSE;
2447 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2449 query_data_t *q;
2451 if (!(q = heap_alloc( sizeof(query_data_t) ))) return FALSE;
2452 q->hdr.request = request;
2453 q->hdr.proc = task_query_data_available;
2454 q->available = available;
2456 addref_object( &request->hdr );
2457 ret = queue_task( (task_header_t *)q );
2459 else
2460 ret = query_data_available( request, available, FALSE );
2462 release_object( &request->hdr );
2463 return ret;
2466 static void task_read_data( task_header_t *task )
2468 read_data_t *r = (read_data_t *)task;
2469 read_data( r->hdr.request, r->buffer, r->to_read, r->read, TRUE );
2472 /***********************************************************************
2473 * WinHttpReadData (winhttp.@)
2475 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, LPVOID buffer, DWORD to_read, LPDWORD read )
2477 BOOL ret;
2478 request_t *request;
2480 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_read, read);
2482 if (!(request = (request_t *)grab_object( hrequest )))
2484 set_last_error( ERROR_INVALID_HANDLE );
2485 return FALSE;
2487 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2489 release_object( &request->hdr );
2490 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2491 return FALSE;
2494 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2496 read_data_t *r;
2498 if (!(r = heap_alloc( sizeof(read_data_t) ))) return FALSE;
2499 r->hdr.request = request;
2500 r->hdr.proc = task_read_data;
2501 r->buffer = buffer;
2502 r->to_read = to_read;
2503 r->read = read;
2505 addref_object( &request->hdr );
2506 ret = queue_task( (task_header_t *)r );
2508 else
2509 ret = read_data( request, buffer, to_read, read, FALSE );
2511 release_object( &request->hdr );
2512 return ret;
2515 static BOOL write_data( request_t *request, LPCVOID buffer, DWORD to_write, LPDWORD written, BOOL async )
2517 BOOL ret;
2518 int num_bytes;
2520 ret = netconn_send( &request->netconn, buffer, to_write, &num_bytes );
2522 if (async)
2524 if (ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
2525 else
2527 WINHTTP_ASYNC_RESULT result;
2528 result.dwResult = API_WRITE_DATA;
2529 result.dwError = get_last_error();
2530 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2533 if (ret && written) *written = num_bytes;
2534 return ret;
2537 static void task_write_data( task_header_t *task )
2539 write_data_t *w = (write_data_t *)task;
2540 write_data( w->hdr.request, w->buffer, w->to_write, w->written, TRUE );
2543 /***********************************************************************
2544 * WinHttpWriteData (winhttp.@)
2546 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, LPCVOID buffer, DWORD to_write, LPDWORD written )
2548 BOOL ret;
2549 request_t *request;
2551 TRACE("%p, %p, %d, %p\n", hrequest, buffer, to_write, written);
2553 if (!(request = (request_t *)grab_object( hrequest )))
2555 set_last_error( ERROR_INVALID_HANDLE );
2556 return FALSE;
2558 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2560 release_object( &request->hdr );
2561 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2562 return FALSE;
2565 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2567 write_data_t *w;
2569 if (!(w = heap_alloc( sizeof(write_data_t) ))) return FALSE;
2570 w->hdr.request = request;
2571 w->hdr.proc = task_write_data;
2572 w->buffer = buffer;
2573 w->to_write = to_write;
2574 w->written = written;
2576 addref_object( &request->hdr );
2577 ret = queue_task( (task_header_t *)w );
2579 else
2580 ret = write_data( request, buffer, to_write, written, FALSE );
2582 release_object( &request->hdr );
2583 return ret;
2586 enum request_state
2588 REQUEST_STATE_UNINITIALIZED,
2589 REQUEST_STATE_INITIALIZED,
2590 REQUEST_STATE_CANCELLED,
2591 REQUEST_STATE_OPEN,
2592 REQUEST_STATE_SENT,
2593 REQUEST_STATE_RESPONSE_RECEIVED
2596 struct winhttp_request
2598 IWinHttpRequest IWinHttpRequest_iface;
2599 LONG refs;
2600 CRITICAL_SECTION cs;
2601 enum request_state state;
2602 HINTERNET hsession;
2603 HINTERNET hconnect;
2604 HINTERNET hrequest;
2605 VARIANT data;
2606 WCHAR *verb;
2607 HANDLE thread;
2608 HANDLE wait;
2609 HANDLE cancel;
2610 char *buffer;
2611 DWORD offset;
2612 DWORD bytes_available;
2613 DWORD bytes_read;
2614 DWORD error;
2615 DWORD logon_policy;
2616 DWORD disable_feature;
2617 LONG resolve_timeout;
2618 LONG connect_timeout;
2619 LONG send_timeout;
2620 LONG receive_timeout;
2621 WINHTTP_PROXY_INFO proxy;
2624 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
2626 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
2629 static ULONG WINAPI winhttp_request_AddRef(
2630 IWinHttpRequest *iface )
2632 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2633 return InterlockedIncrement( &request->refs );
2636 /* critical section must be held */
2637 static void cancel_request( struct winhttp_request *request )
2639 if (request->state <= REQUEST_STATE_CANCELLED) return;
2640 if (request->thread) SetEvent( request->cancel );
2641 request->state = REQUEST_STATE_CANCELLED;
2644 /* critical section must be held */
2645 static void free_request( struct winhttp_request *request )
2647 if (request->state < REQUEST_STATE_INITIALIZED) return;
2648 WinHttpCloseHandle( request->hrequest );
2649 WinHttpCloseHandle( request->hconnect );
2650 WinHttpCloseHandle( request->hsession );
2651 CloseHandle( request->thread );
2652 CloseHandle( request->wait );
2653 CloseHandle( request->cancel );
2654 heap_free( request->proxy.lpszProxy );
2655 heap_free( request->proxy.lpszProxyBypass );
2656 heap_free( request->buffer );
2657 heap_free( request->verb );
2658 VariantClear( &request->data );
2661 static ULONG WINAPI winhttp_request_Release(
2662 IWinHttpRequest *iface )
2664 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2665 LONG refs = InterlockedDecrement( &request->refs );
2666 if (!refs)
2668 TRACE("destroying %p\n", request);
2670 EnterCriticalSection( &request->cs );
2671 cancel_request( request );
2672 free_request( request );
2673 LeaveCriticalSection( &request->cs );
2674 request->cs.DebugInfo->Spare[0] = 0;
2675 DeleteCriticalSection( &request->cs );
2676 heap_free( request );
2678 return refs;
2681 static HRESULT WINAPI winhttp_request_QueryInterface(
2682 IWinHttpRequest *iface,
2683 REFIID riid,
2684 void **obj )
2686 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2688 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
2690 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
2691 IsEqualGUID( riid, &IID_IDispatch ) ||
2692 IsEqualGUID( riid, &IID_IUnknown ))
2694 *obj = iface;
2696 else
2698 FIXME("interface %s not implemented\n", debugstr_guid(riid));
2699 return E_NOINTERFACE;
2701 IWinHttpRequest_AddRef( iface );
2702 return S_OK;
2705 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
2706 IWinHttpRequest *iface,
2707 UINT *count )
2709 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2711 TRACE("%p, %p\n", request, count);
2712 *count = 1;
2713 return S_OK;
2716 enum type_id
2718 IWinHttpRequest_tid,
2719 last_tid
2722 static ITypeLib *winhttp_typelib;
2723 static ITypeInfo *winhttp_typeinfo[last_tid];
2725 static REFIID winhttp_tid_id[] =
2727 &IID_IWinHttpRequest
2730 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
2732 HRESULT hr;
2734 if (!winhttp_typelib)
2736 ITypeLib *typelib;
2738 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
2739 if (FAILED(hr))
2741 ERR("LoadRegTypeLib failed: %08x\n", hr);
2742 return hr;
2744 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
2745 ITypeLib_Release( typelib );
2747 if (!winhttp_typeinfo[tid])
2749 ITypeInfo *typeinfo;
2751 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
2752 if (FAILED(hr))
2754 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id[tid]), hr);
2755 return hr;
2757 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
2758 ITypeInfo_Release( typeinfo );
2760 *ret = winhttp_typeinfo[tid];
2761 return S_OK;
2764 static HRESULT WINAPI winhttp_request_GetTypeInfo(
2765 IWinHttpRequest *iface,
2766 UINT index,
2767 LCID lcid,
2768 ITypeInfo **info )
2770 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2771 TRACE("%p, %u, %u, %p\n", request, index, lcid, info);
2773 return get_typeinfo( IWinHttpRequest_tid, info );
2776 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
2777 IWinHttpRequest *iface,
2778 REFIID riid,
2779 LPOLESTR *names,
2780 UINT count,
2781 LCID lcid,
2782 DISPID *dispid )
2784 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2785 ITypeInfo *typeinfo;
2786 HRESULT hr;
2788 TRACE("%p, %s, %p, %u, %u, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid);
2790 if (!names || !count || !dispid) return E_INVALIDARG;
2792 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2793 if (SUCCEEDED(hr))
2795 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
2796 ITypeInfo_Release( typeinfo );
2798 return hr;
2801 static HRESULT WINAPI winhttp_request_Invoke(
2802 IWinHttpRequest *iface,
2803 DISPID member,
2804 REFIID riid,
2805 LCID lcid,
2806 WORD flags,
2807 DISPPARAMS *params,
2808 VARIANT *result,
2809 EXCEPINFO *excep_info,
2810 UINT *arg_err )
2812 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2813 ITypeInfo *typeinfo;
2814 HRESULT hr;
2816 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
2817 lcid, flags, params, result, excep_info, arg_err);
2819 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
2820 if (SUCCEEDED(hr))
2822 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
2823 params, result, excep_info, arg_err );
2824 ITypeInfo_Release( typeinfo );
2826 return hr;
2829 static HRESULT WINAPI winhttp_request_SetProxy(
2830 IWinHttpRequest *iface,
2831 HTTPREQUEST_PROXY_SETTING proxy_setting,
2832 VARIANT proxy_server,
2833 VARIANT bypass_list )
2835 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2836 DWORD err = ERROR_SUCCESS;
2838 TRACE("%p, %u, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
2839 debugstr_variant(&bypass_list));
2841 EnterCriticalSection( &request->cs );
2842 switch (proxy_setting)
2844 case HTTPREQUEST_PROXYSETTING_DEFAULT:
2845 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
2846 heap_free( request->proxy.lpszProxy );
2847 heap_free( request->proxy.lpszProxyBypass );
2848 request->proxy.lpszProxy = NULL;
2849 request->proxy.lpszProxyBypass = NULL;
2850 break;
2852 case HTTPREQUEST_PROXYSETTING_DIRECT:
2853 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
2854 heap_free( request->proxy.lpszProxy );
2855 heap_free( request->proxy.lpszProxyBypass );
2856 request->proxy.lpszProxy = NULL;
2857 request->proxy.lpszProxyBypass = NULL;
2858 break;
2860 case HTTPREQUEST_PROXYSETTING_PROXY:
2861 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
2862 if (V_VT( &proxy_server ) == VT_BSTR)
2864 heap_free( request->proxy.lpszProxy );
2865 request->proxy.lpszProxy = strdupW( V_BSTR( &proxy_server ) );
2867 if (V_VT( &bypass_list ) == VT_BSTR)
2869 heap_free( request->proxy.lpszProxyBypass );
2870 request->proxy.lpszProxyBypass = strdupW( V_BSTR( &bypass_list ) );
2872 break;
2874 default:
2875 err = ERROR_INVALID_PARAMETER;
2876 break;
2878 LeaveCriticalSection( &request->cs );
2879 return HRESULT_FROM_WIN32( err );
2882 static HRESULT WINAPI winhttp_request_SetCredentials(
2883 IWinHttpRequest *iface,
2884 BSTR username,
2885 BSTR password,
2886 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
2888 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2889 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
2890 DWORD err = ERROR_SUCCESS;
2892 TRACE("%p, %s, %p\n", request, debugstr_w(username), password);
2894 EnterCriticalSection( &request->cs );
2895 if (request->state < REQUEST_STATE_OPEN)
2897 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
2898 goto done;
2900 switch (flags)
2902 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
2903 target = WINHTTP_AUTH_TARGET_SERVER;
2904 break;
2905 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
2906 target = WINHTTP_AUTH_TARGET_PROXY;
2907 break;
2908 default:
2909 err = ERROR_INVALID_PARAMETER;
2910 goto done;
2912 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
2914 err = get_last_error();
2916 done:
2917 LeaveCriticalSection( &request->cs );
2918 return HRESULT_FROM_WIN32( err );
2921 static void initialize_request( struct winhttp_request *request )
2923 request->hrequest = NULL;
2924 request->hconnect = NULL;
2925 request->hsession = NULL;
2926 request->thread = NULL;
2927 request->wait = NULL;
2928 request->cancel = NULL;
2929 request->buffer = NULL;
2930 request->verb = NULL;
2931 request->offset = 0;
2932 request->bytes_available = 0;
2933 request->bytes_read = 0;
2934 request->error = ERROR_SUCCESS;
2935 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
2936 request->disable_feature = 0;
2937 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
2938 request->proxy.lpszProxy = NULL;
2939 request->proxy.lpszProxyBypass = NULL;
2940 request->resolve_timeout = 0;
2941 request->connect_timeout = 60000;
2942 request->send_timeout = 30000;
2943 request->receive_timeout = 30000;
2944 VariantInit( &request->data );
2945 request->state = REQUEST_STATE_INITIALIZED;
2948 static HRESULT WINAPI winhttp_request_Open(
2949 IWinHttpRequest *iface,
2950 BSTR method,
2951 BSTR url,
2952 VARIANT async )
2954 static const WCHAR typeW[] = {'*','/','*',0};
2955 static const WCHAR *acceptW[] = {typeW, NULL};
2956 static const WCHAR httpsW[] = {'h','t','t','p','s'};
2957 static const WCHAR user_agentW[] = {
2958 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
2959 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
2960 'R','e','q','u','e','s','t','.','5',')',0};
2961 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
2962 HINTERNET hsession = NULL, hconnect = NULL, hrequest;
2963 URL_COMPONENTS uc;
2964 WCHAR *hostname, *path = NULL, *verb = NULL;
2965 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0, request_flags = 0;
2967 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
2968 debugstr_variant(&async));
2970 if (!method || !url) return E_INVALIDARG;
2972 memset( &uc, 0, sizeof(uc) );
2973 uc.dwStructSize = sizeof(uc);
2974 uc.dwSchemeLength = ~0u;
2975 uc.dwHostNameLength = ~0u;
2976 uc.dwUrlPathLength = ~0u;
2977 uc.dwExtraInfoLength = ~0u;
2978 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( get_last_error() );
2980 EnterCriticalSection( &request->cs );
2981 if (request->state != REQUEST_STATE_INITIALIZED)
2983 cancel_request( request );
2984 free_request( request );
2985 initialize_request( request );
2987 if (!(hostname = heap_alloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
2988 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
2989 hostname[uc.dwHostNameLength] = 0;
2991 if (!(path = heap_alloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
2992 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
2993 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
2995 if (!(verb = strdupW( method ))) goto error;
2996 if (V_VT( &async ) == VT_BOOL && V_BOOL( &async )) flags |= WINHTTP_FLAG_ASYNC;
2997 if (!(hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, flags )))
2999 err = get_last_error();
3000 goto error;
3002 if (!(hconnect = WinHttpConnect( hsession, hostname, uc.nPort, 0 )))
3004 err = get_last_error();
3005 goto error;
3007 len = sizeof(httpsW) / sizeof(WCHAR);
3008 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
3010 request_flags |= WINHTTP_FLAG_SECURE;
3012 if (!(hrequest = WinHttpOpenRequest( hconnect, method, path, NULL, NULL, acceptW, request_flags )))
3014 err = get_last_error();
3015 goto error;
3017 if (flags & WINHTTP_FLAG_ASYNC)
3019 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
3020 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
3021 WinHttpSetOption( hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
3023 request->state = REQUEST_STATE_OPEN;
3024 request->hsession = hsession;
3025 request->hconnect = hconnect;
3026 request->hrequest = hrequest;
3027 request->verb = verb;
3028 heap_free( hostname );
3029 heap_free( path );
3030 LeaveCriticalSection( &request->cs );
3031 return S_OK;
3033 error:
3034 WinHttpCloseHandle( hconnect );
3035 WinHttpCloseHandle( hsession );
3036 heap_free( hostname );
3037 heap_free( path );
3038 heap_free( verb );
3039 LeaveCriticalSection( &request->cs );
3040 return HRESULT_FROM_WIN32( err );
3043 static HRESULT WINAPI winhttp_request_SetRequestHeader(
3044 IWinHttpRequest *iface,
3045 BSTR header,
3046 BSTR value )
3048 static const WCHAR fmtW[] = {'%','s',':',' ','%','s','\r','\n',0};
3049 static const WCHAR emptyW[] = {0};
3050 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3051 DWORD len, err = ERROR_SUCCESS;
3052 WCHAR *str;
3054 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
3056 if (!header) return E_INVALIDARG;
3058 EnterCriticalSection( &request->cs );
3059 if (request->state < REQUEST_STATE_OPEN)
3061 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
3062 goto done;
3064 if (request->state >= REQUEST_STATE_SENT)
3066 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
3067 goto done;
3069 len = strlenW( header ) + 4;
3070 if (value) len += strlenW( value );
3071 if (!(str = heap_alloc( (len + 1) * sizeof(WCHAR) )))
3073 err = ERROR_OUTOFMEMORY;
3074 goto done;
3076 sprintfW( str, fmtW, header, value ? value : emptyW );
3077 if (!WinHttpAddRequestHeaders( request->hrequest, str, len, WINHTTP_ADDREQ_FLAG_REPLACE ))
3079 err = get_last_error();
3081 heap_free( str );
3083 done:
3084 LeaveCriticalSection( &request->cs );
3085 return HRESULT_FROM_WIN32( err );
3088 static HRESULT WINAPI winhttp_request_GetResponseHeader(
3089 IWinHttpRequest *iface,
3090 BSTR header,
3091 BSTR *value )
3093 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3094 DWORD size, err = ERROR_SUCCESS;
3096 TRACE("%p, %p\n", request, header);
3098 EnterCriticalSection( &request->cs );
3099 if (request->state < REQUEST_STATE_SENT)
3101 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3102 goto done;
3104 if (!header || !value)
3106 err = ERROR_INVALID_PARAMETER;
3107 goto done;
3109 size = 0;
3110 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
3112 err = get_last_error();
3113 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3115 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3117 err = ERROR_OUTOFMEMORY;
3118 goto done;
3120 err = ERROR_SUCCESS;
3121 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
3123 err = get_last_error();
3124 SysFreeString( *value );
3126 done:
3127 LeaveCriticalSection( &request->cs );
3128 return HRESULT_FROM_WIN32( err );
3131 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
3132 IWinHttpRequest *iface,
3133 BSTR *headers )
3135 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3136 DWORD size, err = ERROR_SUCCESS;
3138 TRACE("%p, %p\n", request, headers);
3140 if (!headers) return E_INVALIDARG;
3142 EnterCriticalSection( &request->cs );
3143 if (request->state < REQUEST_STATE_SENT)
3145 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3146 goto done;
3148 size = 0;
3149 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
3151 err = get_last_error();
3152 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3154 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
3156 err = ERROR_OUTOFMEMORY;
3157 goto done;
3159 err = ERROR_SUCCESS;
3160 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
3162 err = get_last_error();
3163 SysFreeString( *headers );
3165 done:
3166 LeaveCriticalSection( &request->cs );
3167 return HRESULT_FROM_WIN32( err );
3170 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
3172 struct winhttp_request *request = (struct winhttp_request *)context;
3174 switch (status)
3176 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
3177 request->bytes_available = *(DWORD *)buffer;
3178 request->error = ERROR_SUCCESS;
3179 break;
3180 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
3181 request->bytes_read = size;
3182 request->error = ERROR_SUCCESS;
3183 break;
3184 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
3186 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
3187 request->error = result->dwError;
3188 break;
3190 default: break;
3192 SetEvent( request->wait );
3195 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
3197 if (!request->wait) return;
3198 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
3199 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
3202 static DWORD wait_for_completion( struct winhttp_request *request )
3204 HANDLE handles[2];
3206 if (!request->wait)
3208 request->error = ERROR_SUCCESS;
3209 return ERROR_SUCCESS;
3211 handles[0] = request->wait;
3212 handles[1] = request->cancel;
3213 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
3215 case WAIT_OBJECT_0:
3216 break;
3217 case WAIT_OBJECT_0 + 1:
3218 request->error = ERROR_CANCELLED;
3219 break;
3220 default:
3221 request->error = get_last_error();
3222 break;
3224 return request->error;
3227 static HRESULT request_receive( struct winhttp_request *request )
3229 DWORD err, size, buflen = 4096;
3231 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
3232 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
3234 return HRESULT_FROM_WIN32( get_last_error() );
3236 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
3237 if (!strcmpW( request->verb, headW ))
3239 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3240 return S_OK;
3242 if (!(request->buffer = heap_alloc( buflen ))) return E_OUTOFMEMORY;
3243 request->buffer[0] = 0;
3244 size = 0;
3247 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
3248 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
3250 err = get_last_error();
3251 goto error;
3253 if ((err = wait_for_completion( request ))) goto error;
3254 if (!request->bytes_available) break;
3255 size += request->bytes_available;
3256 if (buflen < size)
3258 char *tmp;
3259 while (buflen < size) buflen *= 2;
3260 if (!(tmp = heap_realloc( request->buffer, buflen )))
3262 err = ERROR_OUTOFMEMORY;
3263 goto error;
3265 request->buffer = tmp;
3267 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
3268 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
3269 request->bytes_available, &request->bytes_read ))
3271 err = get_last_error();
3272 goto error;
3274 if ((err = wait_for_completion( request ))) goto error;
3275 request->offset += request->bytes_read;
3276 } while (request->bytes_read);
3278 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
3279 return S_OK;
3281 error:
3282 heap_free( request->buffer );
3283 request->buffer = NULL;
3284 return HRESULT_FROM_WIN32( err );
3287 static DWORD request_set_parameters( struct winhttp_request *request )
3289 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
3290 sizeof(request->proxy) )) return get_last_error();
3292 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
3293 sizeof(request->logon_policy) )) return get_last_error();
3295 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
3296 sizeof(request->disable_feature) )) return get_last_error();
3298 if (!WinHttpSetTimeouts( request->hrequest,
3299 request->resolve_timeout,
3300 request->connect_timeout,
3301 request->send_timeout,
3302 request->receive_timeout )) return get_last_error();
3303 return ERROR_SUCCESS;
3306 static void request_set_utf8_content_type( struct winhttp_request *request )
3308 static const WCHAR fmtW[] = {'%','s',':',' ','%','s',0};
3309 static const WCHAR text_plainW[] = {'t','e','x','t','/','p','l','a','i','n',0};
3310 static const WCHAR charset_utf8W[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3311 WCHAR headerW[64];
3312 int len;
3314 len = sprintfW( headerW, fmtW, attr_content_type, text_plainW );
3315 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
3316 len = sprintfW( headerW, fmtW, attr_content_type, charset_utf8W );
3317 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
3320 static HRESULT request_send( struct winhttp_request *request )
3322 SAFEARRAY *sa = NULL;
3323 VARIANT data;
3324 char *ptr = NULL;
3325 LONG size = 0;
3326 HRESULT hr;
3327 DWORD err;
3329 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
3330 if (strcmpW( request->verb, getW ))
3332 VariantInit( &data );
3333 if (V_VT( &request->data ) == VT_BSTR)
3335 UINT cp = CP_ACP;
3336 const WCHAR *str = V_BSTR( &request->data );
3337 int i, len = strlenW( str );
3339 for (i = 0; i < len; i++)
3341 if (str[i] > 127)
3343 cp = CP_UTF8;
3344 break;
3347 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
3348 if (!(ptr = heap_alloc( size ))) return E_OUTOFMEMORY;
3349 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
3350 if (cp == CP_UTF8) request_set_utf8_content_type( request );
3352 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
3354 sa = V_ARRAY( &data );
3355 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
3356 if ((hr = SafeArrayGetUBound( sa, 1, &size )) != S_OK)
3358 SafeArrayUnaccessData( sa );
3359 return hr;
3361 size++;
3364 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_REQUEST_SENT );
3365 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
3367 err = get_last_error();
3368 goto error;
3370 if ((err = wait_for_completion( request ))) goto error;
3371 if (sa) SafeArrayUnaccessData( sa );
3372 else heap_free( ptr );
3373 request->state = REQUEST_STATE_SENT;
3374 return S_OK;
3376 error:
3377 if (sa) SafeArrayUnaccessData( sa );
3378 else heap_free( ptr );
3379 return HRESULT_FROM_WIN32( err );
3382 static HRESULT request_send_and_receive( struct winhttp_request *request )
3384 HRESULT hr = request_send( request );
3385 if (hr == S_OK) hr = request_receive( request );
3386 return hr;
3389 static DWORD CALLBACK send_and_receive_proc( void *arg )
3391 struct winhttp_request *request = (struct winhttp_request *)arg;
3392 return request_send_and_receive( request );
3395 static HRESULT WINAPI winhttp_request_Send(
3396 IWinHttpRequest *iface,
3397 VARIANT body )
3399 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3400 HRESULT hr;
3402 TRACE("%p, %s\n", request, debugstr_variant(&body));
3404 EnterCriticalSection( &request->cs );
3405 if (request->state < REQUEST_STATE_OPEN)
3407 LeaveCriticalSection( &request->cs );
3408 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
3410 if (request->state >= REQUEST_STATE_SENT)
3412 LeaveCriticalSection( &request->cs );
3413 return S_OK;
3415 VariantClear( &request->data );
3416 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK) {
3417 LeaveCriticalSection( &request->cs );
3418 return hr;
3421 if (request->wait) /* async request */
3423 if (!(request->thread = CreateThread( NULL, 0, send_and_receive_proc, request, 0, NULL )))
3425 LeaveCriticalSection( &request->cs );
3426 return HRESULT_FROM_WIN32( get_last_error() );
3429 else hr = request_send_and_receive( request );
3430 LeaveCriticalSection( &request->cs );
3431 return hr;
3434 static HRESULT WINAPI winhttp_request_get_Status(
3435 IWinHttpRequest *iface,
3436 LONG *status )
3438 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3439 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
3441 TRACE("%p, %p\n", request, status);
3443 if (!status) return E_INVALIDARG;
3445 EnterCriticalSection( &request->cs );
3446 if (request->state < REQUEST_STATE_SENT)
3448 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3449 goto done;
3451 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
3452 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
3454 err = get_last_error();
3455 goto done;
3457 *status = status_code;
3459 done:
3460 LeaveCriticalSection( &request->cs );
3461 return HRESULT_FROM_WIN32( err );
3464 static HRESULT WINAPI winhttp_request_get_StatusText(
3465 IWinHttpRequest *iface,
3466 BSTR *status )
3468 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3469 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
3471 TRACE("%p, %p\n", request, status);
3473 if (!status) return E_INVALIDARG;
3475 EnterCriticalSection( &request->cs );
3476 if (request->state < REQUEST_STATE_SENT)
3478 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3479 goto done;
3481 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
3483 err = get_last_error();
3484 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
3486 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
3488 err = ERROR_OUTOFMEMORY;
3489 goto done;
3491 index = 0;
3492 err = ERROR_SUCCESS;
3493 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
3495 err = get_last_error();
3496 SysFreeString( *status );
3498 done:
3499 LeaveCriticalSection( &request->cs );
3500 return HRESULT_FROM_WIN32( err );
3503 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
3505 static const WCHAR utf8W[] = {'u','t','f','-','8',0};
3506 static const WCHAR charsetW[] = {'c','h','a','r','s','e','t',0};
3507 WCHAR *buffer, *p;
3508 DWORD size;
3510 *codepage = CP_ACP;
3511 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
3512 get_last_error() == ERROR_INSUFFICIENT_BUFFER)
3514 if (!(buffer = heap_alloc( size ))) return ERROR_OUTOFMEMORY;
3515 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
3517 return get_last_error();
3519 if ((p = strstrW( buffer, charsetW )))
3521 p += strlenW( charsetW );
3522 while (*p == ' ') p++;
3523 if (*p++ == '=')
3525 while (*p == ' ') p++;
3526 if (!strcmpiW( p, utf8W )) *codepage = CP_UTF8;
3529 heap_free( buffer );
3531 return ERROR_SUCCESS;
3534 static HRESULT WINAPI winhttp_request_get_ResponseText(
3535 IWinHttpRequest *iface,
3536 BSTR *body )
3538 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3539 UINT codepage;
3540 DWORD err = ERROR_SUCCESS;
3541 int len;
3543 TRACE("%p, %p\n", request, body);
3545 if (!body) return E_INVALIDARG;
3547 EnterCriticalSection( &request->cs );
3548 if (request->state < REQUEST_STATE_SENT)
3550 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
3551 goto done;
3553 if ((err = request_get_codepage( request, &codepage ))) goto done;
3554 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
3555 if (!(*body = SysAllocStringLen( NULL, len )))
3557 err = ERROR_OUTOFMEMORY;
3558 goto done;
3560 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
3561 (*body)[len] = 0;
3563 done:
3564 LeaveCriticalSection( &request->cs );
3565 return HRESULT_FROM_WIN32( err );
3568 static HRESULT WINAPI winhttp_request_get_ResponseBody(
3569 IWinHttpRequest *iface,
3570 VARIANT *body )
3572 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3573 SAFEARRAY *sa;
3574 HRESULT hr;
3575 DWORD err = ERROR_SUCCESS;
3576 char *ptr;
3578 TRACE("%p, %p\n", request, body);
3580 if (!body) return E_INVALIDARG;
3582 EnterCriticalSection( &request->cs );
3583 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
3585 err = ERROR_OUTOFMEMORY;
3586 goto done;
3588 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
3590 SafeArrayDestroy( sa );
3591 LeaveCriticalSection( &request->cs );
3592 return hr;
3594 memcpy( ptr, request->buffer, request->offset );
3595 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
3597 SafeArrayDestroy( sa );
3598 LeaveCriticalSection( &request->cs );
3599 return hr;
3601 V_VT( body ) = VT_ARRAY|VT_UI1;
3602 V_ARRAY( body ) = sa;
3604 done:
3605 LeaveCriticalSection( &request->cs );
3606 return HRESULT_FROM_WIN32( err );
3609 static HRESULT WINAPI winhttp_request_get_ResponseStream(
3610 IWinHttpRequest *iface,
3611 VARIANT *body )
3613 FIXME("\n");
3614 return E_NOTIMPL;
3617 static HRESULT WINAPI winhttp_request_get_Option(
3618 IWinHttpRequest *iface,
3619 WinHttpRequestOption option,
3620 VARIANT *value )
3622 FIXME("\n");
3623 return E_NOTIMPL;
3626 static HRESULT WINAPI winhttp_request_put_Option(
3627 IWinHttpRequest *iface,
3628 WinHttpRequestOption option,
3629 VARIANT value )
3631 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3632 HRESULT hr = S_OK;
3634 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
3636 EnterCriticalSection( &request->cs );
3637 switch (option)
3639 case WinHttpRequestOption_EnableRedirects:
3641 if (V_BOOL( &value ))
3642 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
3643 else
3644 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
3645 break;
3647 default:
3648 FIXME("unimplemented option %u\n", option);
3649 hr = E_NOTIMPL;
3650 break;
3652 LeaveCriticalSection( &request->cs );
3653 return hr;
3656 /* critical section must be held */
3657 static DWORD wait_for_response( struct winhttp_request *request, DWORD timeout )
3659 HANDLE thread = request->thread;
3660 DWORD err, ret;
3662 LeaveCriticalSection( &request->cs );
3663 while ((err = MsgWaitForMultipleObjects( 1, &thread, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
3665 MSG msg;
3666 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
3668 TranslateMessage( &msg );
3669 DispatchMessageW( &msg );
3672 switch (err)
3674 case WAIT_OBJECT_0:
3675 ret = ERROR_SUCCESS;
3676 break;
3677 case WAIT_TIMEOUT:
3678 ret = ERROR_TIMEOUT;
3679 break;
3680 case WAIT_FAILED:
3681 default:
3682 ret = get_last_error();
3683 break;
3685 EnterCriticalSection( &request->cs );
3686 return ret;
3689 static HRESULT WINAPI winhttp_request_WaitForResponse(
3690 IWinHttpRequest *iface,
3691 VARIANT timeout,
3692 VARIANT_BOOL *succeeded )
3694 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3695 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
3697 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
3699 EnterCriticalSection( &request->cs );
3700 if (!request->thread)
3702 LeaveCriticalSection( &request->cs );
3703 return S_OK;
3705 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
3707 LeaveCriticalSection( &request->cs );
3708 return S_OK;
3710 switch ((err = wait_for_response( request, msecs )))
3712 case ERROR_TIMEOUT:
3713 if (succeeded) *succeeded = VARIANT_FALSE;
3714 err = ERROR_SUCCESS;
3715 break;
3717 case ERROR_SUCCESS:
3718 if (succeeded) *succeeded = VARIANT_TRUE;
3719 break;
3721 default: break;
3723 LeaveCriticalSection( &request->cs );
3724 return HRESULT_FROM_WIN32( err );
3727 static HRESULT WINAPI winhttp_request_Abort(
3728 IWinHttpRequest *iface )
3730 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3732 TRACE("%p\n", request);
3734 EnterCriticalSection( &request->cs );
3735 cancel_request( request );
3736 LeaveCriticalSection( &request->cs );
3737 return S_OK;
3740 static HRESULT WINAPI winhttp_request_SetTimeouts(
3741 IWinHttpRequest *iface,
3742 LONG resolve_timeout,
3743 LONG connect_timeout,
3744 LONG send_timeout,
3745 LONG receive_timeout )
3747 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3749 TRACE("%p, %d, %d, %d, %d\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout);
3751 EnterCriticalSection( &request->cs );
3752 request->resolve_timeout = resolve_timeout;
3753 request->connect_timeout = connect_timeout;
3754 request->send_timeout = send_timeout;
3755 request->receive_timeout = receive_timeout;
3756 LeaveCriticalSection( &request->cs );
3757 return S_OK;
3760 static HRESULT WINAPI winhttp_request_SetClientCertificate(
3761 IWinHttpRequest *iface,
3762 BSTR certificate )
3764 FIXME("\n");
3765 return E_NOTIMPL;
3768 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
3769 IWinHttpRequest *iface,
3770 WinHttpRequestAutoLogonPolicy policy )
3772 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
3773 HRESULT hr = S_OK;
3775 TRACE("%p, %u\n", request, policy );
3777 EnterCriticalSection( &request->cs );
3778 switch (policy)
3780 case AutoLogonPolicy_Always:
3781 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
3782 break;
3783 case AutoLogonPolicy_OnlyIfBypassProxy:
3784 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
3785 break;
3786 case AutoLogonPolicy_Never:
3787 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
3788 break;
3789 default: hr = E_INVALIDARG;
3790 break;
3792 LeaveCriticalSection( &request->cs );
3793 return hr;
3796 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
3798 winhttp_request_QueryInterface,
3799 winhttp_request_AddRef,
3800 winhttp_request_Release,
3801 winhttp_request_GetTypeInfoCount,
3802 winhttp_request_GetTypeInfo,
3803 winhttp_request_GetIDsOfNames,
3804 winhttp_request_Invoke,
3805 winhttp_request_SetProxy,
3806 winhttp_request_SetCredentials,
3807 winhttp_request_Open,
3808 winhttp_request_SetRequestHeader,
3809 winhttp_request_GetResponseHeader,
3810 winhttp_request_GetAllResponseHeaders,
3811 winhttp_request_Send,
3812 winhttp_request_get_Status,
3813 winhttp_request_get_StatusText,
3814 winhttp_request_get_ResponseText,
3815 winhttp_request_get_ResponseBody,
3816 winhttp_request_get_ResponseStream,
3817 winhttp_request_get_Option,
3818 winhttp_request_put_Option,
3819 winhttp_request_WaitForResponse,
3820 winhttp_request_Abort,
3821 winhttp_request_SetTimeouts,
3822 winhttp_request_SetClientCertificate,
3823 winhttp_request_SetAutoLogonPolicy
3826 HRESULT WinHttpRequest_create( void **obj )
3828 struct winhttp_request *request;
3830 TRACE("%p\n", obj);
3832 if (!(request = heap_alloc( sizeof(*request) ))) return E_OUTOFMEMORY;
3833 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
3834 request->refs = 1;
3835 request->state = REQUEST_STATE_UNINITIALIZED;
3836 request->proxy.lpszProxy = NULL;
3837 request->proxy.lpszProxyBypass = NULL;
3838 InitializeCriticalSection( &request->cs );
3839 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
3841 *obj = &request->IWinHttpRequest_iface;
3842 TRACE("returning iface %p\n", *obj);
3843 return S_OK;