kernelbase: Implement GetConsoleOriginalTitleA().
[wine.git] / dlls / winhttp / request.c
blob07d0ff19b7c5702def410dfabf7abaa7af6888c0
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 #include <assert.h>
23 #include <stdarg.h>
24 #include <wchar.h>
26 #define COBJMACROS
27 #include "windef.h"
28 #include "winbase.h"
29 #include "ws2tcpip.h"
30 #include "ole2.h"
31 #include "initguid.h"
32 #include "httprequest.h"
33 #include "httprequestid.h"
34 #include "schannel.h"
35 #include "winhttp.h"
36 #include "ntsecapi.h"
37 #include "winternl.h"
39 #include "wine/debug.h"
40 #include "winhttp_private.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
44 #define DEFAULT_KEEP_ALIVE_TIMEOUT 30000
46 static const WCHAR *attribute_table[] =
48 L"Mime-Version", /* WINHTTP_QUERY_MIME_VERSION = 0 */
49 L"Content-Type" , /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
50 L"Content-Transfer-Encoding", /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
51 L"Content-ID", /* WINHTTP_QUERY_CONTENT_ID = 3 */
52 NULL, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
53 L"Content-Length", /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
54 L"Content-Language", /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
55 L"Allow", /* WINHTTP_QUERY_ALLOW = 7 */
56 L"Public", /* WINHTTP_QUERY_PUBLIC = 8 */
57 L"Date", /* WINHTTP_QUERY_DATE = 9 */
58 L"Expires", /* WINHTTP_QUERY_EXPIRES = 10 */
59 L"Last-Modified", /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
60 NULL, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
61 L"URI", /* WINHTTP_QUERY_URI = 13 */
62 L"From", /* WINHTTP_QUERY_DERIVED_FROM = 14 */
63 NULL, /* WINHTTP_QUERY_COST = 15 */
64 NULL, /* WINHTTP_QUERY_LINK = 16 */
65 L"Pragma", /* WINHTTP_QUERY_PRAGMA = 17 */
66 NULL, /* WINHTTP_QUERY_VERSION = 18 */
67 L"Status", /* WINHTTP_QUERY_STATUS_CODE = 19 */
68 NULL, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
69 NULL, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
70 NULL, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
71 L"Connection", /* WINHTTP_QUERY_CONNECTION = 23 */
72 L"Accept", /* WINHTTP_QUERY_ACCEPT = 24 */
73 L"Accept-Charset", /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
74 L"Accept-Encoding", /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
75 L"Accept-Language", /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
76 L"Authorization", /* WINHTTP_QUERY_AUTHORIZATION = 28 */
77 L"Content-Encoding", /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
78 NULL, /* WINHTTP_QUERY_FORWARDED = 30 */
79 NULL, /* WINHTTP_QUERY_FROM = 31 */
80 L"If-Modified-Since", /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
81 L"Location", /* WINHTTP_QUERY_LOCATION = 33 */
82 NULL, /* WINHTTP_QUERY_ORIG_URI = 34 */
83 L"Referer", /* WINHTTP_QUERY_REFERER = 35 */
84 L"Retry-After", /* WINHTTP_QUERY_RETRY_AFTER = 36 */
85 L"Server", /* WINHTTP_QUERY_SERVER = 37 */
86 NULL, /* WINHTTP_TITLE = 38 */
87 L"User-Agent", /* WINHTTP_QUERY_USER_AGENT = 39 */
88 L"WWW-Authenticate", /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
89 L"Proxy-Authenticate", /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
90 L"Accept-Ranges", /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
91 L"Set-Cookie", /* WINHTTP_QUERY_SET_COOKIE = 43 */
92 L"Cookie", /* WINHTTP_QUERY_COOKIE = 44 */
93 NULL, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
94 NULL, /* WINHTTP_QUERY_REFRESH = 46 */
95 NULL, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
96 L"Age", /* WINHTTP_QUERY_AGE = 48 */
97 L"Cache-Control", /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
98 L"Content-Base", /* WINHTTP_QUERY_CONTENT_BASE = 50 */
99 L"Content-Location", /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
100 L"Content-MD5", /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
101 L"Content-Range", /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
102 L"ETag", /* WINHTTP_QUERY_ETAG = 54 */
103 L"Host", /* WINHTTP_QUERY_HOST = 55 */
104 L"If-Match", /* WINHTTP_QUERY_IF_MATCH = 56 */
105 L"If-None-Match", /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
106 L"If-Range", /* WINHTTP_QUERY_IF_RANGE = 58 */
107 L"If-Unmodified-Since", /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
108 L"Max-Forwards", /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
109 L"Proxy-Authorization", /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
110 L"Range", /* WINHTTP_QUERY_RANGE = 62 */
111 L"Transfer-Encoding", /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
112 L"Upgrade", /* WINHTTP_QUERY_UPGRADE = 64 */
113 L"Vary", /* WINHTTP_QUERY_VARY = 65 */
114 L"Via", /* WINHTTP_QUERY_VIA = 66 */
115 L"Warning", /* WINHTTP_QUERY_WARNING = 67 */
116 L"Expect", /* WINHTTP_QUERY_EXPECT = 68 */
117 L"Proxy-Connection", /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
118 L"Unless-Modified-Since", /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
119 NULL, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
120 NULL, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
121 NULL, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
122 NULL /* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
125 void init_queue( struct queue *queue )
127 InitializeSRWLock( &queue->lock );
128 list_init( &queue->queued_tasks );
129 queue->callback_running = FALSE;
132 void stop_queue( struct queue *queue )
134 assert( list_empty( &queue->queued_tasks ));
135 TRACE("stopped %p\n", queue);
138 static void addref_task( struct task_header *task )
140 InterlockedIncrement( &task->refs );
143 static void release_task( struct task_header *task )
145 if (!InterlockedDecrement( &task->refs ))
146 free( task );
149 static struct task_header *get_next_task( struct queue *queue, struct task_header *prev_task )
151 struct task_header *task;
152 struct list *entry;
154 AcquireSRWLockExclusive( &queue->lock );
155 assert( queue->callback_running );
156 if (prev_task)
158 list_remove( &prev_task->entry );
159 release_task( prev_task );
161 if ((entry = list_head( &queue->queued_tasks )))
163 task = LIST_ENTRY( entry, struct task_header, entry );
164 addref_task( task );
166 else
168 task = NULL;
169 queue->callback_running = FALSE;
171 ReleaseSRWLockExclusive( &queue->lock );
172 return task;
175 static void CALLBACK task_callback( TP_CALLBACK_INSTANCE *instance, void *ctx )
177 struct task_header *task, *next_task;
178 struct queue *queue = ctx;
180 TRACE( "instance %p.\n", instance );
182 task = get_next_task( queue, NULL );
183 while (task)
185 task->callback( task, FALSE );
186 /* Queue object may be freed by release_object() unless there is another task referencing it. */
187 next_task = get_next_task( queue, task );
188 release_object( task->obj );
189 release_task( task );
190 task = next_task;
192 TRACE( "instance %p exiting.\n", instance );
195 static DWORD queue_task( struct queue *queue, TASK_CALLBACK task, struct task_header *task_hdr,
196 struct object_header *obj )
198 BOOL callback_running;
200 TRACE("queueing %p in %p\n", task_hdr, queue);
201 task_hdr->callback = task;
202 task_hdr->completion_sent = 0;
203 task_hdr->refs = 1;
204 task_hdr->obj = obj;
205 addref_object( obj );
207 AcquireSRWLockExclusive( &queue->lock );
208 list_add_tail( &queue->queued_tasks, &task_hdr->entry );
209 if (!(callback_running = queue->callback_running))
211 if ((queue->callback_running = TrySubmitThreadpoolCallback( task_callback, queue, NULL )))
212 callback_running = TRUE;
213 else
214 list_remove( &task_hdr->entry );
216 ReleaseSRWLockExclusive( &queue->lock );
218 if (!callback_running)
220 release_object( obj );
221 free( task_hdr );
222 ERR( "Submiting threadpool callback failed, err %lu.\n", GetLastError() );
223 return ERROR_OUTOFMEMORY;
226 return ERROR_SUCCESS;
229 static BOOL task_needs_completion( struct task_header *task_hdr )
231 return !InterlockedExchange( &task_hdr->completion_sent, 1 );
234 static BOOL cancel_queue( struct queue *queue )
236 struct task_header *task_hdr, *found;
237 BOOL cancelled = FALSE;
239 while (1)
241 AcquireSRWLockExclusive( &queue->lock );
242 found = NULL;
243 LIST_FOR_EACH_ENTRY( task_hdr, &queue->queued_tasks, struct task_header, entry )
245 if (task_needs_completion( task_hdr ))
247 found = task_hdr;
248 addref_task( found );
249 break;
252 ReleaseSRWLockExclusive( &queue->lock );
253 if (!found) break;
254 cancelled = TRUE;
255 found->callback( found, TRUE );
256 release_task( found );
258 return cancelled;
261 static void free_header( struct header *header )
263 free( header->field );
264 free( header->value );
265 free( header );
268 static BOOL valid_token_char( WCHAR c )
270 if (c < 32 || c == 127) return FALSE;
271 switch (c)
273 case '(': case ')':
274 case '<': case '>':
275 case '@': case ',':
276 case ';': case ':':
277 case '\\': case '\"':
278 case '/': case '[':
279 case ']': case '?':
280 case '=': case '{':
281 case '}': case ' ':
282 case '\t':
283 return FALSE;
284 default:
285 return TRUE;
289 static struct header *parse_header( const WCHAR *string, size_t string_len )
291 const WCHAR *p, *q;
292 struct header *header;
293 int len;
295 p = string;
296 if (!(q = wcschr( p, ':' )))
298 WARN("no ':' in line %s\n", debugstr_w(string));
299 return NULL;
301 if (q == string)
303 WARN("empty field name in line %s\n", debugstr_w(string));
304 return NULL;
306 while (*p != ':')
308 if (!valid_token_char( *p ))
310 WARN("invalid character in field name %s\n", debugstr_w(string));
311 return NULL;
313 p++;
315 len = q - string;
316 if (!(header = calloc( 1, sizeof(*header) ))) return NULL;
317 if (!(header->field = malloc( (len + 1) * sizeof(WCHAR) )))
319 free( header );
320 return NULL;
322 memcpy( header->field, string, len * sizeof(WCHAR) );
323 header->field[len] = 0;
325 q++; /* skip past colon */
326 while (*q == ' ') q++;
327 len = (string + string_len) - q;
329 if (!(header->value = malloc( (len + 1) * sizeof(WCHAR) )))
331 free_header( header );
332 return NULL;
334 memcpy( header->value, q, len * sizeof(WCHAR) );
335 header->value[len] = 0;
337 return header;
340 static int get_header_index( struct request *request, const WCHAR *field, int requested_index, BOOL request_only )
342 int index;
344 TRACE("%s\n", debugstr_w(field));
346 for (index = 0; index < request->num_headers; index++)
348 if (wcsicmp( request->headers[index].field, field )) continue;
349 if (request_only && !request->headers[index].is_request) continue;
350 if (!request_only && request->headers[index].is_request) continue;
352 if (!requested_index) break;
353 requested_index--;
355 if (index >= request->num_headers) index = -1;
356 TRACE("returning %d\n", index);
357 return index;
360 static DWORD insert_header( struct request *request, struct header *header )
362 DWORD count = request->num_headers + 1;
363 struct header *hdrs;
365 if (request->headers)
367 if ((hdrs = realloc( request->headers, sizeof(*header) * count )))
368 memset( &hdrs[count - 1], 0, sizeof(*header) );
370 else hdrs = calloc( 1, sizeof(*header) );
371 if (!hdrs) return ERROR_OUTOFMEMORY;
373 request->headers = hdrs;
374 request->headers[count - 1].field = wcsdup( header->field );
375 request->headers[count - 1].value = wcsdup( header->value );
376 request->headers[count - 1].is_request = header->is_request;
377 request->num_headers = count;
378 return ERROR_SUCCESS;
381 static void delete_header( struct request *request, DWORD index )
383 if (!request->num_headers || index >= request->num_headers) return;
384 request->num_headers--;
386 free( request->headers[index].field );
387 free( request->headers[index].value );
389 memmove( &request->headers[index], &request->headers[index + 1],
390 (request->num_headers - index) * sizeof(struct header) );
391 memset( &request->headers[request->num_headers], 0, sizeof(struct header) );
394 DWORD process_header( struct request *request, const WCHAR *field, const WCHAR *value, DWORD flags, BOOL request_only )
396 int index;
397 struct header hdr;
399 TRACE( "%s: %s %#lx\n", debugstr_w(field), debugstr_w(value), flags );
401 if ((index = get_header_index( request, field, 0, request_only )) >= 0)
403 if (flags & WINHTTP_ADDREQ_FLAG_ADD_IF_NEW) return ERROR_WINHTTP_HEADER_ALREADY_EXISTS;
406 if (flags & WINHTTP_ADDREQ_FLAG_REPLACE)
408 if (index >= 0)
410 delete_header( request, index );
411 if (!value || !value[0]) return ERROR_SUCCESS;
413 else if (!(flags & WINHTTP_ADDREQ_FLAG_ADD)) return ERROR_WINHTTP_HEADER_NOT_FOUND;
415 hdr.field = (LPWSTR)field;
416 hdr.value = (LPWSTR)value;
417 hdr.is_request = request_only;
418 return insert_header( request, &hdr );
420 else if (value)
423 if ((flags & (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON)) &&
424 index >= 0)
426 WCHAR *tmp;
427 int len, len_orig, len_value;
428 struct header *header = &request->headers[index];
430 len_orig = lstrlenW( header->value );
431 len_value = lstrlenW( value );
433 len = len_orig + len_value + 2;
434 if (!(tmp = realloc( header->value, (len + 1) * sizeof(WCHAR) ))) return ERROR_OUTOFMEMORY;
435 header->value = tmp;
436 header->value[len_orig++] = (flags & WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA) ? ',' : ';';
437 header->value[len_orig++] = ' ';
439 memcpy( &header->value[len_orig], value, len_value * sizeof(WCHAR) );
440 header->value[len] = 0;
441 return ERROR_SUCCESS;
443 else
445 hdr.field = (LPWSTR)field;
446 hdr.value = (LPWSTR)value;
447 hdr.is_request = request_only;
448 return insert_header( request, &hdr );
452 return ERROR_SUCCESS;
455 DWORD add_request_headers( struct request *request, const WCHAR *headers, DWORD len, DWORD flags )
457 DWORD ret = ERROR_WINHTTP_INVALID_HEADER;
458 struct header *header;
459 const WCHAR *p, *q;
461 if (len == ~0u) len = lstrlenW( headers );
462 if (!len) return ERROR_SUCCESS;
464 p = headers;
467 const WCHAR *end;
469 if (p >= headers + len) break;
471 for (q = p; q < headers + len && *q != '\r' && *q != '\n'; ++q)
473 end = q;
474 while (*q == '\r' || *q == '\n')
475 ++q;
477 if ((header = parse_header( p, end - p )))
479 ret = process_header( request, header->field, header->value, flags, TRUE );
480 free_header( header );
482 p = q;
483 } while (!ret);
485 return ret;
488 /***********************************************************************
489 * WinHttpAddRequestHeaders (winhttp.@)
491 BOOL WINAPI WinHttpAddRequestHeaders( HINTERNET hrequest, const WCHAR *headers, DWORD len, DWORD flags )
493 DWORD ret;
494 struct request *request;
496 TRACE( "%p, %s, %lu, %#lx\n", hrequest, debugstr_wn(headers, len), len, flags );
498 if (!headers || !len)
500 SetLastError( ERROR_INVALID_PARAMETER );
501 return FALSE;
503 if (!(request = (struct request *)grab_object( hrequest )))
505 SetLastError( ERROR_INVALID_HANDLE );
506 return FALSE;
508 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
510 release_object( &request->hdr );
511 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
512 return FALSE;
515 ret = add_request_headers( request, headers, len, flags );
517 release_object( &request->hdr );
518 SetLastError( ret );
519 return !ret;
522 static WCHAR *build_absolute_request_path( struct request *request, const WCHAR **path )
524 const WCHAR *scheme;
525 WCHAR *ret;
526 int len, offset;
528 scheme = (request->netconn ? request->netconn->secure : (request->hdr.flags & WINHTTP_FLAG_SECURE)) ? L"https" : L"http";
530 len = lstrlenW( scheme ) + lstrlenW( request->connect->hostname ) + 4; /* '://' + nul */
531 if (request->connect->hostport) len += 6; /* ':' between host and port, up to 5 for port */
533 len += lstrlenW( request->path );
534 if ((ret = malloc( len * sizeof(WCHAR) )))
536 offset = swprintf( ret, len, L"%s://%s", scheme, request->connect->hostname );
537 if (request->connect->hostport)
539 offset += swprintf( ret + offset, len - offset, L":%u", request->connect->hostport );
541 lstrcpyW( ret + offset, request->path );
542 if (path) *path = ret + offset;
545 return ret;
548 static WCHAR *build_request_string( struct request *request )
550 WCHAR *path, *ret;
551 unsigned int i, len;
553 if (!wcsicmp( request->connect->hostname, request->connect->servername )) path = request->path;
554 else if (!(path = build_absolute_request_path( request, NULL ))) return NULL;
556 len = lstrlenW( request->verb ) + 1 /* ' ' */;
557 len += lstrlenW( path ) + 1 /* ' ' */;
558 len += lstrlenW( request->version );
560 for (i = 0; i < request->num_headers; i++)
562 if (request->headers[i].is_request)
563 len += lstrlenW( request->headers[i].field ) + lstrlenW( request->headers[i].value ) + 4; /* '\r\n: ' */
565 len += 4; /* '\r\n\r\n' */
567 if ((ret = malloc( (len + 1) * sizeof(WCHAR) )))
569 lstrcpyW( ret, request->verb );
570 lstrcatW( ret, L" " );
571 lstrcatW( ret, path );
572 lstrcatW( ret, L" " );
573 lstrcatW( ret, request->version );
575 for (i = 0; i < request->num_headers; i++)
577 if (request->headers[i].is_request)
579 lstrcatW( ret, L"\r\n" );
580 lstrcatW( ret, request->headers[i].field );
581 lstrcatW( ret, L": " );
582 lstrcatW( ret, request->headers[i].value );
585 lstrcatW( ret, L"\r\n\r\n" );
588 if (path != request->path) free( path );
589 return ret;
592 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
594 static DWORD query_headers( struct request *request, DWORD level, const WCHAR *name, void *buffer, DWORD *buflen,
595 DWORD *index )
597 struct header *header = NULL;
598 BOOL request_only;
599 int requested_index, header_index = -1;
600 DWORD attr, len, ret = ERROR_WINHTTP_HEADER_NOT_FOUND;
602 request_only = level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS;
603 requested_index = index ? *index : 0;
605 attr = level & ~QUERY_MODIFIER_MASK;
606 switch (attr)
608 case WINHTTP_QUERY_CUSTOM:
610 header_index = get_header_index( request, name, requested_index, request_only );
611 break;
613 case WINHTTP_QUERY_RAW_HEADERS:
615 WCHAR *headers, *p, *q;
617 if (request_only)
618 headers = build_request_string( request );
619 else
620 headers = request->raw_headers;
622 if (!(p = headers)) return ERROR_OUTOFMEMORY;
623 for (len = 0; *p; p++) if (*p != '\r') len++;
625 if (!buffer || len * sizeof(WCHAR) > *buflen) ret = ERROR_INSUFFICIENT_BUFFER;
626 else
628 for (p = headers, q = buffer; *p; p++, q++)
630 if (*p != '\r') *q = *p;
631 else
633 *q = 0;
634 p++; /* skip '\n' */
637 TRACE("returning data: %s\n", debugstr_wn(buffer, len));
638 if (len) len--;
639 ret = ERROR_SUCCESS;
641 *buflen = len * sizeof(WCHAR);
642 if (request_only) free( headers );
643 return ret;
645 case WINHTTP_QUERY_RAW_HEADERS_CRLF:
647 WCHAR *headers;
649 if (request_only)
650 headers = build_request_string( request );
651 else
652 headers = request->raw_headers;
654 if (!headers) return ERROR_OUTOFMEMORY;
655 len = lstrlenW( headers ) * sizeof(WCHAR);
656 if (!buffer || len + sizeof(WCHAR) > *buflen)
658 len += sizeof(WCHAR);
659 ret = ERROR_INSUFFICIENT_BUFFER;
661 else
663 memcpy( buffer, headers, len + sizeof(WCHAR) );
664 TRACE("returning data: %s\n", debugstr_wn(buffer, len / sizeof(WCHAR)));
665 ret = ERROR_SUCCESS;
667 *buflen = len;
668 if (request_only) free( headers );
669 return ret;
671 case WINHTTP_QUERY_VERSION:
672 len = lstrlenW( request->version ) * sizeof(WCHAR);
673 if (!buffer || len + sizeof(WCHAR) > *buflen)
675 len += sizeof(WCHAR);
676 ret = ERROR_INSUFFICIENT_BUFFER;
678 else
680 lstrcpyW( buffer, request->version );
681 TRACE("returning string: %s\n", debugstr_w(buffer));
682 ret = ERROR_SUCCESS;
684 *buflen = len;
685 return ret;
687 case WINHTTP_QUERY_STATUS_TEXT:
688 len = lstrlenW( request->status_text ) * sizeof(WCHAR);
689 if (!buffer || len + sizeof(WCHAR) > *buflen)
691 len += sizeof(WCHAR);
692 ret = ERROR_INSUFFICIENT_BUFFER;
694 else
696 lstrcpyW( buffer, request->status_text );
697 TRACE("returning string: %s\n", debugstr_w(buffer));
698 ret = ERROR_SUCCESS;
700 *buflen = len;
701 return ret;
703 case WINHTTP_QUERY_REQUEST_METHOD:
704 len = lstrlenW( request->verb ) * sizeof(WCHAR);
705 if (!buffer || len + sizeof(WCHAR) > *buflen)
707 len += sizeof(WCHAR);
708 ret = ERROR_INSUFFICIENT_BUFFER;
710 else
712 lstrcpyW( buffer, request->verb );
713 TRACE("returning string: %s\n", debugstr_w(buffer));
714 ret = ERROR_SUCCESS;
716 *buflen = len;
717 return ret;
719 default:
720 if (attr >= ARRAY_SIZE(attribute_table)) return ERROR_INVALID_PARAMETER;
721 if (!attribute_table[attr])
723 FIXME( "attribute %lu not implemented\n", attr );
724 return ERROR_WINHTTP_HEADER_NOT_FOUND;
726 TRACE("attribute %s\n", debugstr_w(attribute_table[attr]));
727 header_index = get_header_index( request, attribute_table[attr], requested_index, request_only );
728 break;
731 if (header_index >= 0)
733 header = &request->headers[header_index];
735 if (!header || (request_only && !header->is_request)) return ERROR_WINHTTP_HEADER_NOT_FOUND;
736 if (level & WINHTTP_QUERY_FLAG_NUMBER)
738 if (!buffer || sizeof(int) > *buflen) ret = ERROR_INSUFFICIENT_BUFFER;
739 else
741 int *number = buffer;
742 *number = wcstol( header->value, NULL, 10 );
743 TRACE("returning number: %d\n", *number);
744 ret = ERROR_SUCCESS;
746 *buflen = sizeof(int);
748 else if (level & WINHTTP_QUERY_FLAG_SYSTEMTIME)
750 SYSTEMTIME *st = buffer;
751 if (!buffer || sizeof(SYSTEMTIME) > *buflen) ret = ERROR_INSUFFICIENT_BUFFER;
752 else if (WinHttpTimeToSystemTime( header->value, st ))
754 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
755 st->wYear, st->wMonth, st->wDay, st->wDayOfWeek,
756 st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
757 ret = ERROR_SUCCESS;
759 *buflen = sizeof(SYSTEMTIME);
761 else if (header->value)
763 len = lstrlenW( header->value ) * sizeof(WCHAR);
764 if (!buffer || len + sizeof(WCHAR) > *buflen)
766 len += sizeof(WCHAR);
767 ret = ERROR_INSUFFICIENT_BUFFER;
769 else
771 lstrcpyW( buffer, header->value );
772 TRACE("returning string: %s\n", debugstr_w(buffer));
773 ret = ERROR_SUCCESS;
775 *buflen = len;
777 if (!ret && index) *index += 1;
778 return ret;
781 /***********************************************************************
782 * WinHttpQueryHeaders (winhttp.@)
784 BOOL WINAPI WinHttpQueryHeaders( HINTERNET hrequest, DWORD level, const WCHAR *name, void *buffer, DWORD *buflen,
785 DWORD *index )
787 DWORD ret;
788 struct request *request;
790 TRACE( "%p, %#lx, %s, %p, %p, %p\n", hrequest, level, debugstr_w(name), buffer, buflen, index );
792 if (!(request = (struct request *)grab_object( hrequest )))
794 SetLastError( ERROR_INVALID_HANDLE );
795 return FALSE;
797 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
799 release_object( &request->hdr );
800 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
801 return FALSE;
803 if (request->state < REQUEST_RESPONSE_STATE_RESPONSE_RECEIVED && !(level & WINHTTP_QUERY_FLAG_REQUEST_HEADERS)
804 && ((level & ~QUERY_MODIFIER_MASK) != WINHTTP_QUERY_REQUEST_METHOD))
806 release_object( &request->hdr );
807 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_STATE );
808 return FALSE;
811 ret = query_headers( request, level, name, buffer, buflen, index );
813 release_object( &request->hdr );
814 SetLastError( ret );
815 return !ret;
818 static const struct
820 const WCHAR *str;
821 unsigned int len;
822 DWORD scheme;
824 auth_schemes[] =
826 { L"Basic", ARRAY_SIZE(L"Basic") - 1, WINHTTP_AUTH_SCHEME_BASIC },
827 { L"NTLM", ARRAY_SIZE(L"NTLM") - 1, WINHTTP_AUTH_SCHEME_NTLM },
828 { L"Passport", ARRAY_SIZE(L"Passport") - 1, WINHTTP_AUTH_SCHEME_PASSPORT },
829 { L"Digest", ARRAY_SIZE(L"Digest") - 1, WINHTTP_AUTH_SCHEME_DIGEST },
830 { L"Negotiate", ARRAY_SIZE(L"Negotiate") - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE }
833 static enum auth_scheme scheme_from_flag( DWORD flag )
835 int i;
837 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++) if (flag == auth_schemes[i].scheme) return i;
838 return SCHEME_INVALID;
841 static DWORD auth_scheme_from_header( const WCHAR *header )
843 unsigned int i;
845 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++)
847 if (!wcsnicmp( header, auth_schemes[i].str, auth_schemes[i].len ) &&
848 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
850 return 0;
853 static DWORD query_auth_schemes( struct request *request, DWORD level, DWORD *supported, DWORD *first )
855 DWORD ret, index = 0, supported_schemes = 0, first_scheme = 0;
857 for (;;)
859 WCHAR *buffer;
860 DWORD size, scheme;
862 size = 0;
863 ret = query_headers( request, level, NULL, NULL, &size, &index );
864 if (ret != ERROR_INSUFFICIENT_BUFFER)
866 if (index) ret = ERROR_SUCCESS;
867 break;
870 if (!(buffer = malloc( size ))) return ERROR_OUTOFMEMORY;
871 if ((ret = query_headers( request, level, NULL, buffer, &size, &index )))
873 free( buffer );
874 return ret;
876 scheme = auth_scheme_from_header( buffer );
877 free( buffer );
878 if (!scheme) continue;
880 if (!first_scheme) first_scheme = scheme;
881 supported_schemes |= scheme;
884 if (!ret)
886 *supported = supported_schemes;
887 *first = first_scheme;
889 return ret;
892 /***********************************************************************
893 * WinHttpQueryAuthSchemes (winhttp.@)
895 BOOL WINAPI WinHttpQueryAuthSchemes( HINTERNET hrequest, LPDWORD supported, LPDWORD first, LPDWORD target )
897 DWORD ret;
898 struct request *request;
900 TRACE("%p, %p, %p, %p\n", hrequest, supported, first, target);
902 if (!(request = (struct request *)grab_object( hrequest )))
904 SetLastError( ERROR_INVALID_HANDLE );
905 return FALSE;
907 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
909 release_object( &request->hdr );
910 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
911 return FALSE;
913 if (!supported || !first || !target)
915 release_object( &request->hdr );
916 SetLastError( ERROR_INVALID_PARAMETER );
917 return FALSE;
921 if (!(ret = query_auth_schemes( request, WINHTTP_QUERY_WWW_AUTHENTICATE, supported, first )))
923 *target = WINHTTP_AUTH_TARGET_SERVER;
925 else if (!(ret = query_auth_schemes( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, supported, first )))
927 *target = WINHTTP_AUTH_TARGET_PROXY;
929 else ret = ERROR_INVALID_OPERATION;
931 release_object( &request->hdr );
932 SetLastError( ret );
933 return !ret;
936 static UINT encode_base64( const char *bin, unsigned int len, WCHAR *base64 )
938 UINT n = 0, x;
939 static const char base64enc[] =
940 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
942 while (len > 0)
944 /* first 6 bits, all from bin[0] */
945 base64[n++] = base64enc[(bin[0] & 0xfc) >> 2];
946 x = (bin[0] & 3) << 4;
948 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
949 if (len == 1)
951 base64[n++] = base64enc[x];
952 base64[n++] = '=';
953 base64[n++] = '=';
954 break;
956 base64[n++] = base64enc[x | ((bin[1] & 0xf0) >> 4)];
957 x = (bin[1] & 0x0f) << 2;
959 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
960 if (len == 2)
962 base64[n++] = base64enc[x];
963 base64[n++] = '=';
964 break;
966 base64[n++] = base64enc[x | ((bin[2] & 0xc0) >> 6)];
968 /* last 6 bits, all from bin [2] */
969 base64[n++] = base64enc[bin[2] & 0x3f];
970 bin += 3;
971 len -= 3;
973 base64[n] = 0;
974 return n;
977 static inline char decode_char( WCHAR c )
979 if (c >= 'A' && c <= 'Z') return c - 'A';
980 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
981 if (c >= '0' && c <= '9') return c - '0' + 52;
982 if (c == '+') return 62;
983 if (c == '/') return 63;
984 return 64;
987 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
989 unsigned int i = 0;
990 char c0, c1, c2, c3;
991 const WCHAR *p = base64;
993 while (len > 4)
995 if ((c0 = decode_char( p[0] )) > 63) return 0;
996 if ((c1 = decode_char( p[1] )) > 63) return 0;
997 if ((c2 = decode_char( p[2] )) > 63) return 0;
998 if ((c3 = decode_char( p[3] )) > 63) return 0;
1000 if (buf)
1002 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1003 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1004 buf[i + 2] = (c2 << 6) | c3;
1006 len -= 4;
1007 i += 3;
1008 p += 4;
1010 if (p[2] == '=')
1012 if ((c0 = decode_char( p[0] )) > 63) return 0;
1013 if ((c1 = decode_char( p[1] )) > 63) return 0;
1015 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
1016 i++;
1018 else if (p[3] == '=')
1020 if ((c0 = decode_char( p[0] )) > 63) return 0;
1021 if ((c1 = decode_char( p[1] )) > 63) return 0;
1022 if ((c2 = decode_char( p[2] )) > 63) return 0;
1024 if (buf)
1026 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1027 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1029 i += 2;
1031 else
1033 if ((c0 = decode_char( p[0] )) > 63) return 0;
1034 if ((c1 = decode_char( p[1] )) > 63) return 0;
1035 if ((c2 = decode_char( p[2] )) > 63) return 0;
1036 if ((c3 = decode_char( p[3] )) > 63) return 0;
1038 if (buf)
1040 buf[i + 0] = (c0 << 2) | (c1 >> 4);
1041 buf[i + 1] = (c1 << 4) | (c2 >> 2);
1042 buf[i + 2] = (c2 << 6) | c3;
1044 i += 3;
1046 return i;
1049 static struct authinfo *alloc_authinfo(void)
1051 struct authinfo *ret;
1053 if (!(ret = malloc( sizeof(*ret) ))) return NULL;
1055 SecInvalidateHandle( &ret->cred );
1056 SecInvalidateHandle( &ret->ctx );
1057 memset( &ret->exp, 0, sizeof(ret->exp) );
1058 ret->scheme = 0;
1059 ret->attr = 0;
1060 ret->max_token = 0;
1061 ret->data = NULL;
1062 ret->data_len = 0;
1063 ret->finished = FALSE;
1064 return ret;
1067 void destroy_authinfo( struct authinfo *authinfo )
1069 if (!authinfo) return;
1071 if (SecIsValidHandle( &authinfo->ctx ))
1072 DeleteSecurityContext( &authinfo->ctx );
1073 if (SecIsValidHandle( &authinfo->cred ))
1074 FreeCredentialsHandle( &authinfo->cred );
1076 free( authinfo->data );
1077 free( authinfo );
1080 static BOOL get_authvalue( struct request *request, DWORD level, DWORD scheme, WCHAR *buffer, DWORD len )
1082 DWORD size, index = 0;
1083 for (;;)
1085 size = len;
1086 if (query_headers( request, level, NULL, buffer, &size, &index )) return FALSE;
1087 if (auth_scheme_from_header( buffer ) == scheme) break;
1089 return TRUE;
1092 static BOOL do_authorization( struct request *request, DWORD target, DWORD scheme_flag )
1094 struct authinfo *authinfo, **auth_ptr;
1095 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
1096 const WCHAR *auth_target, *username, *password;
1097 WCHAR auth_value[2048], *auth_reply;
1098 DWORD len = sizeof(auth_value), len_scheme, flags;
1099 BOOL ret, has_auth_value;
1101 if (scheme == SCHEME_INVALID) return FALSE;
1103 switch (target)
1105 case WINHTTP_AUTH_TARGET_SERVER:
1106 has_auth_value = get_authvalue( request, WINHTTP_QUERY_WWW_AUTHENTICATE, scheme_flag, auth_value, len );
1107 auth_ptr = &request->authinfo;
1108 auth_target = L"Authorization";
1109 if (request->creds[TARGET_SERVER][scheme].username)
1111 if (scheme != SCHEME_BASIC && !has_auth_value) return FALSE;
1112 username = request->creds[TARGET_SERVER][scheme].username;
1113 password = request->creds[TARGET_SERVER][scheme].password;
1115 else
1117 if (!has_auth_value) return FALSE;
1118 username = request->connect->username;
1119 password = request->connect->password;
1121 break;
1123 case WINHTTP_AUTH_TARGET_PROXY:
1124 if (!get_authvalue( request, WINHTTP_QUERY_PROXY_AUTHENTICATE, scheme_flag, auth_value, len ))
1125 return FALSE;
1126 auth_ptr = &request->proxy_authinfo;
1127 auth_target = L"Proxy-Authorization";
1128 if (request->creds[TARGET_PROXY][scheme].username)
1130 username = request->creds[TARGET_PROXY][scheme].username;
1131 password = request->creds[TARGET_PROXY][scheme].password;
1133 else
1135 username = request->connect->session->proxy_username;
1136 password = request->connect->session->proxy_password;
1138 break;
1140 default:
1141 WARN( "unknown target %#lx\n", target );
1142 return FALSE;
1144 authinfo = *auth_ptr;
1146 switch (scheme)
1148 case SCHEME_BASIC:
1150 int userlen, passlen;
1152 if (!username || !password) return FALSE;
1153 if ((!authinfo && !(authinfo = alloc_authinfo())) || authinfo->finished) return FALSE;
1155 userlen = WideCharToMultiByte( CP_UTF8, 0, username, lstrlenW( username ), NULL, 0, NULL, NULL );
1156 passlen = WideCharToMultiByte( CP_UTF8, 0, password, lstrlenW( password ), NULL, 0, NULL, NULL );
1158 authinfo->data_len = userlen + 1 + passlen;
1159 if (!(authinfo->data = malloc( authinfo->data_len ))) return FALSE;
1161 WideCharToMultiByte( CP_UTF8, 0, username, -1, authinfo->data, userlen, NULL, NULL );
1162 authinfo->data[userlen] = ':';
1163 WideCharToMultiByte( CP_UTF8, 0, password, -1, authinfo->data + userlen + 1, passlen, NULL, NULL );
1165 authinfo->scheme = SCHEME_BASIC;
1166 authinfo->finished = TRUE;
1167 break;
1169 case SCHEME_NTLM:
1170 case SCHEME_NEGOTIATE:
1172 SECURITY_STATUS status;
1173 SecBufferDesc out_desc, in_desc;
1174 SecBuffer out, in;
1175 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
1176 const WCHAR *p;
1177 BOOL first = FALSE;
1179 if (!authinfo)
1181 TimeStamp exp;
1182 SEC_WINNT_AUTH_IDENTITY_W id;
1183 WCHAR *domain, *user;
1185 if (!username || !password || !(authinfo = alloc_authinfo())) return FALSE;
1187 first = TRUE;
1188 domain = (WCHAR *)username;
1189 user = wcschr( username, '\\' );
1191 if (user) user++;
1192 else
1194 user = (WCHAR *)username;
1195 domain = NULL;
1197 id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1198 id.User = user;
1199 id.UserLength = lstrlenW( user );
1200 id.Domain = domain;
1201 id.DomainLength = domain ? user - domain - 1 : 0;
1202 id.Password = (WCHAR *)password;
1203 id.PasswordLength = lstrlenW( password );
1205 status = AcquireCredentialsHandleW( NULL, (SEC_WCHAR *)auth_schemes[scheme].str,
1206 SECPKG_CRED_OUTBOUND, NULL, &id, NULL, NULL,
1207 &authinfo->cred, &exp );
1208 if (status == SEC_E_OK)
1210 PSecPkgInfoW info;
1211 status = QuerySecurityPackageInfoW( (SEC_WCHAR *)auth_schemes[scheme].str, &info );
1212 if (status == SEC_E_OK)
1214 authinfo->max_token = info->cbMaxToken;
1215 FreeContextBuffer( info );
1218 if (status != SEC_E_OK)
1220 WARN( "AcquireCredentialsHandleW for scheme %s failed with error %#lx\n",
1221 debugstr_w(auth_schemes[scheme].str), status );
1222 free( authinfo );
1223 return FALSE;
1225 authinfo->scheme = scheme;
1227 else if (authinfo->finished) return FALSE;
1229 if ((lstrlenW( auth_value ) < auth_schemes[authinfo->scheme].len ||
1230 wcsnicmp( auth_value, auth_schemes[authinfo->scheme].str, auth_schemes[authinfo->scheme].len )))
1232 ERR("authentication scheme changed from %s to %s\n",
1233 debugstr_w(auth_schemes[authinfo->scheme].str), debugstr_w(auth_value));
1234 destroy_authinfo( authinfo );
1235 *auth_ptr = NULL;
1236 return FALSE;
1238 in.BufferType = SECBUFFER_TOKEN;
1239 in.cbBuffer = 0;
1240 in.pvBuffer = NULL;
1242 in_desc.ulVersion = 0;
1243 in_desc.cBuffers = 1;
1244 in_desc.pBuffers = &in;
1246 p = auth_value + auth_schemes[scheme].len;
1247 if (*p == ' ')
1249 int len = lstrlenW( ++p );
1250 in.cbBuffer = decode_base64( p, len, NULL );
1251 if (!(in.pvBuffer = malloc( in.cbBuffer ))) {
1252 destroy_authinfo( authinfo );
1253 *auth_ptr = NULL;
1254 return FALSE;
1256 decode_base64( p, len, in.pvBuffer );
1258 out.BufferType = SECBUFFER_TOKEN;
1259 out.cbBuffer = authinfo->max_token;
1260 if (!(out.pvBuffer = malloc( authinfo->max_token )))
1262 free( in.pvBuffer );
1263 destroy_authinfo( authinfo );
1264 *auth_ptr = NULL;
1265 return FALSE;
1267 out_desc.ulVersion = 0;
1268 out_desc.cBuffers = 1;
1269 out_desc.pBuffers = &out;
1271 status = InitializeSecurityContextW( first ? &authinfo->cred : NULL, first ? NULL : &authinfo->ctx,
1272 first ? request->connect->servername : NULL, flags, 0,
1273 SECURITY_NETWORK_DREP, in.pvBuffer ? &in_desc : NULL, 0,
1274 &authinfo->ctx, &out_desc, &authinfo->attr, &authinfo->exp );
1275 free( in.pvBuffer );
1276 if (status == SEC_E_OK)
1278 free( authinfo->data );
1279 authinfo->data = out.pvBuffer;
1280 authinfo->data_len = out.cbBuffer;
1281 authinfo->finished = TRUE;
1282 TRACE("sending last auth packet\n");
1284 else if (status == SEC_I_CONTINUE_NEEDED)
1286 free( authinfo->data );
1287 authinfo->data = out.pvBuffer;
1288 authinfo->data_len = out.cbBuffer;
1289 TRACE("sending next auth packet\n");
1291 else
1293 ERR( "InitializeSecurityContextW failed with error %#lx\n", status );
1294 free( out.pvBuffer );
1295 destroy_authinfo( authinfo );
1296 *auth_ptr = NULL;
1297 return FALSE;
1299 break;
1301 default:
1302 ERR("invalid scheme %u\n", scheme);
1303 return FALSE;
1305 *auth_ptr = authinfo;
1307 len_scheme = auth_schemes[authinfo->scheme].len;
1308 len = len_scheme + 1 + ((authinfo->data_len + 2) * 4) / 3;
1309 if (!(auth_reply = malloc( (len + 1) * sizeof(WCHAR) ))) return FALSE;
1311 memcpy( auth_reply, auth_schemes[authinfo->scheme].str, len_scheme * sizeof(WCHAR) );
1312 auth_reply[len_scheme] = ' ';
1313 encode_base64( authinfo->data, authinfo->data_len, auth_reply + len_scheme + 1 );
1315 flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
1316 ret = !process_header( request, auth_target, auth_reply, flags, TRUE );
1317 free( auth_reply );
1318 return ret;
1321 static WCHAR *build_proxy_connect_string( struct request *request )
1323 WCHAR *ret, *host;
1324 unsigned int i;
1325 int len = lstrlenW( request->connect->hostname ) + 7;
1327 if (!(host = malloc( len * sizeof(WCHAR) ))) return NULL;
1328 len = swprintf( host, len, L"%s:%u", request->connect->hostname, request->connect->hostport );
1330 len += ARRAY_SIZE(L"CONNECT");
1331 len += ARRAY_SIZE(L"HTTP/1.1");
1333 for (i = 0; i < request->num_headers; i++)
1335 if (request->headers[i].is_request)
1336 len += lstrlenW( request->headers[i].field ) + lstrlenW( request->headers[i].value ) + 4; /* '\r\n: ' */
1338 len += 4; /* '\r\n\r\n' */
1340 if ((ret = malloc( (len + 1) * sizeof(WCHAR) )))
1342 lstrcpyW( ret, L"CONNECT" );
1343 lstrcatW( ret, L" " );
1344 lstrcatW( ret, host );
1345 lstrcatW( ret, L" " );
1346 lstrcatW( ret, L"HTTP/1.1" );
1348 for (i = 0; i < request->num_headers; i++)
1350 if (request->headers[i].is_request)
1352 lstrcatW( ret, L"\r\n" );
1353 lstrcatW( ret, request->headers[i].field );
1354 lstrcatW( ret, L": " );
1355 lstrcatW( ret, request->headers[i].value );
1358 lstrcatW( ret, L"\r\n\r\n" );
1361 free( host );
1362 return ret;
1365 static DWORD read_reply( struct request *request );
1367 static DWORD secure_proxy_connect( struct request *request )
1369 WCHAR *str;
1370 char *strA;
1371 int len, bytes_sent;
1372 DWORD ret;
1374 if (!(str = build_proxy_connect_string( request ))) return ERROR_OUTOFMEMORY;
1375 strA = strdupWA( str );
1376 free( str );
1377 if (!strA) return ERROR_OUTOFMEMORY;
1379 len = strlen( strA );
1380 ret = netconn_send( request->netconn, strA, len, &bytes_sent, NULL );
1381 free( strA );
1382 if (!ret) ret = read_reply( request );
1384 return ret;
1387 static WCHAR *addr_to_str( struct sockaddr_storage *addr )
1389 char buf[INET6_ADDRSTRLEN];
1390 void *src;
1392 switch (addr->ss_family)
1394 case AF_INET:
1395 src = &((struct sockaddr_in *)addr)->sin_addr;
1396 break;
1397 case AF_INET6:
1398 src = &((struct sockaddr_in6 *)addr)->sin6_addr;
1399 break;
1400 default:
1401 WARN("unsupported address family %d\n", addr->ss_family);
1402 return NULL;
1404 if (!inet_ntop( addr->ss_family, src, buf, sizeof(buf) )) return NULL;
1405 return strdupAW( buf );
1408 static CRITICAL_SECTION connection_pool_cs;
1409 static CRITICAL_SECTION_DEBUG connection_pool_debug =
1411 0, 0, &connection_pool_cs,
1412 { &connection_pool_debug.ProcessLocksList, &connection_pool_debug.ProcessLocksList },
1413 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
1415 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
1417 static struct list connection_pool = LIST_INIT( connection_pool );
1419 void release_host( struct hostdata *host )
1421 LONG ref;
1423 EnterCriticalSection( &connection_pool_cs );
1424 if (!(ref = --host->ref)) list_remove( &host->entry );
1425 LeaveCriticalSection( &connection_pool_cs );
1426 if (ref) return;
1428 assert( list_empty( &host->connections ) );
1429 free( host->hostname );
1430 free( host );
1433 static BOOL connection_collector_running;
1435 static void CALLBACK connection_collector( TP_CALLBACK_INSTANCE *instance, void *ctx )
1437 unsigned int remaining_connections;
1438 struct netconn *netconn, *next_netconn;
1439 struct hostdata *host, *next_host;
1440 ULONGLONG now;
1444 /* FIXME: Use more sophisticated method */
1445 Sleep(5000);
1446 remaining_connections = 0;
1447 now = GetTickCount64();
1449 EnterCriticalSection(&connection_pool_cs);
1451 LIST_FOR_EACH_ENTRY_SAFE(host, next_host, &connection_pool, struct hostdata, entry)
1453 LIST_FOR_EACH_ENTRY_SAFE(netconn, next_netconn, &host->connections, struct netconn, entry)
1455 if (netconn->keep_until < now)
1457 TRACE("freeing %p\n", netconn);
1458 list_remove(&netconn->entry);
1459 netconn_release(netconn);
1461 else remaining_connections++;
1465 if (!remaining_connections) connection_collector_running = FALSE;
1467 LeaveCriticalSection(&connection_pool_cs);
1468 } while(remaining_connections);
1470 FreeLibraryWhenCallbackReturns( instance, winhttp_instance );
1473 static void cache_connection( struct netconn *netconn )
1475 TRACE( "caching connection %p\n", netconn );
1477 EnterCriticalSection( &connection_pool_cs );
1479 netconn->keep_until = GetTickCount64() + DEFAULT_KEEP_ALIVE_TIMEOUT;
1480 list_add_head( &netconn->host->connections, &netconn->entry );
1482 if (!connection_collector_running)
1484 HMODULE module;
1486 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR *)winhttp_instance, &module );
1488 if (TrySubmitThreadpoolCallback( connection_collector, NULL, NULL )) connection_collector_running = TRUE;
1489 else FreeLibrary( winhttp_instance );
1492 LeaveCriticalSection( &connection_pool_cs );
1495 static DWORD map_secure_protocols( DWORD mask )
1497 DWORD ret = 0;
1498 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL2) ret |= SP_PROT_SSL2_CLIENT;
1499 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_SSL3) ret |= SP_PROT_SSL3_CLIENT;
1500 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1) ret |= SP_PROT_TLS1_CLIENT;
1501 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1) ret |= SP_PROT_TLS1_1_CLIENT;
1502 if (mask & WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2) ret |= SP_PROT_TLS1_2_CLIENT;
1503 return ret;
1506 static DWORD ensure_cred_handle( struct request *request )
1508 SECURITY_STATUS status = SEC_E_OK;
1510 if (request->cred_handle_initialized) return ERROR_SUCCESS;
1512 if (!request->cred_handle_initialized)
1514 SCHANNEL_CRED cred;
1515 memset( &cred, 0, sizeof(cred) );
1516 cred.dwVersion = SCHANNEL_CRED_VERSION;
1517 cred.grbitEnabledProtocols = map_secure_protocols( request->connect->session->secure_protocols );
1518 if (request->client_cert)
1520 cred.paCred = &request->client_cert;
1521 cred.cCreds = 1;
1523 status = AcquireCredentialsHandleW( NULL, (WCHAR *)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL,
1524 &cred, NULL, NULL, &request->cred_handle, NULL );
1525 if (status == SEC_E_OK)
1526 request->cred_handle_initialized = TRUE;
1529 if (status != SEC_E_OK)
1531 WARN( "AcquireCredentialsHandleW failed: %#lx\n", status );
1532 return status;
1534 return ERROR_SUCCESS;
1537 static DWORD open_connection( struct request *request )
1539 BOOL is_secure = request->hdr.flags & WINHTTP_FLAG_SECURE;
1540 struct hostdata *host = NULL, *iter;
1541 struct netconn *netconn = NULL;
1542 struct connect *connect;
1543 WCHAR *addressW = NULL;
1544 INTERNET_PORT port;
1545 DWORD ret, len;
1547 if (request->netconn) goto done;
1549 connect = request->connect;
1550 port = connect->serverport ? connect->serverport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1552 EnterCriticalSection( &connection_pool_cs );
1554 LIST_FOR_EACH_ENTRY( iter, &connection_pool, struct hostdata, entry )
1556 if (iter->port == port && !wcscmp( connect->servername, iter->hostname ) && !is_secure == !iter->secure)
1558 host = iter;
1559 host->ref++;
1560 break;
1564 if (!host)
1566 if ((host = malloc( sizeof(*host) )))
1568 host->ref = 1;
1569 host->secure = is_secure;
1570 host->port = port;
1571 list_init( &host->connections );
1572 if ((host->hostname = wcsdup( connect->servername )))
1574 list_add_head( &connection_pool, &host->entry );
1576 else
1578 free( host );
1579 host = NULL;
1584 LeaveCriticalSection( &connection_pool_cs );
1586 if (!host) return ERROR_OUTOFMEMORY;
1588 for (;;)
1590 EnterCriticalSection( &connection_pool_cs );
1591 if (!list_empty( &host->connections ))
1593 netconn = LIST_ENTRY( list_head( &host->connections ), struct netconn, entry );
1594 list_remove( &netconn->entry );
1596 LeaveCriticalSection( &connection_pool_cs );
1597 if (!netconn) break;
1599 if (netconn_is_alive( netconn )) break;
1600 TRACE("connection %p no longer alive, closing\n", netconn);
1601 netconn_release( netconn );
1602 netconn = NULL;
1605 if (!connect->resolved && netconn)
1607 connect->sockaddr = netconn->sockaddr;
1608 connect->resolved = TRUE;
1611 if (!connect->resolved)
1613 len = lstrlenW( host->hostname ) + 1;
1614 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME, host->hostname, len );
1616 if ((ret = netconn_resolve( host->hostname, port, &connect->sockaddr, request->resolve_timeout )))
1618 release_host( host );
1619 return ret;
1621 connect->resolved = TRUE;
1623 if (!(addressW = addr_to_str( &connect->sockaddr )))
1625 release_host( host );
1626 return ERROR_OUTOFMEMORY;
1628 len = lstrlenW( addressW ) + 1;
1629 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED, addressW, len );
1632 if (!netconn)
1634 if (!addressW && !(addressW = addr_to_str( &connect->sockaddr )))
1636 release_host( host );
1637 return ERROR_OUTOFMEMORY;
1640 TRACE("connecting to %s:%u\n", debugstr_w(addressW), port);
1642 len = lstrlenW( addressW ) + 1;
1643 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER, addressW, len );
1645 if ((ret = netconn_create( host, &connect->sockaddr, request->connect_timeout, &netconn )))
1647 free( addressW );
1648 release_host( host );
1649 return ret;
1651 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1652 netconn_set_timeout( netconn, FALSE, request->receive_response_timeout );
1654 request->netconn = netconn;
1656 if (is_secure)
1658 if (connect->session->proxy_server && wcsicmp( connect->hostname, connect->servername ))
1660 if ((ret = secure_proxy_connect( request )))
1662 request->netconn = NULL;
1663 free( addressW );
1664 netconn_release( netconn );
1665 return ret;
1669 CertFreeCertificateContext( request->server_cert );
1670 request->server_cert = NULL;
1672 if ((ret = ensure_cred_handle( request )) ||
1673 (ret = netconn_secure_connect( netconn, connect->hostname, request->security_flags,
1674 &request->cred_handle, request->check_revocation )))
1676 request->netconn = NULL;
1677 free( addressW );
1678 netconn_release( netconn );
1679 return ret;
1683 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER, addressW, lstrlenW(addressW) + 1 );
1685 else
1687 TRACE("using connection %p\n", netconn);
1689 netconn_set_timeout( netconn, TRUE, request->send_timeout );
1690 netconn_set_timeout( netconn, FALSE, request->receive_response_timeout );
1691 request->netconn = netconn;
1694 if (netconn->secure && !(request->server_cert = netconn_get_certificate( netconn )))
1696 free( addressW );
1697 netconn_release( netconn );
1698 return ERROR_WINHTTP_SECURE_FAILURE;
1701 done:
1702 request->read_pos = request->read_size = 0;
1703 request->read_chunked = FALSE;
1704 request->read_chunked_size = ~0u;
1705 request->read_chunked_eof = FALSE;
1706 free( addressW );
1707 return ERROR_SUCCESS;
1710 void close_connection( struct request *request )
1712 if (!request->netconn) return;
1714 netconn_release( request->netconn );
1715 request->netconn = NULL;
1718 static DWORD add_host_header( struct request *request, DWORD modifier )
1720 DWORD ret, len;
1721 WCHAR *host;
1722 struct connect *connect = request->connect;
1723 INTERNET_PORT port;
1725 port = connect->hostport ? connect->hostport : (request->hdr.flags & WINHTTP_FLAG_SECURE ? 443 : 80);
1727 if (port == INTERNET_DEFAULT_HTTP_PORT || port == INTERNET_DEFAULT_HTTPS_PORT)
1729 return process_header( request, L"Host", connect->hostname, modifier, TRUE );
1731 len = lstrlenW( connect->hostname ) + 7; /* sizeof(":65335") */
1732 if (!(host = malloc( len * sizeof(WCHAR) ))) return ERROR_OUTOFMEMORY;
1733 swprintf( host, len, L"%s:%u", connect->hostname, port );
1734 ret = process_header( request, L"Host", host, modifier, TRUE );
1735 free( host );
1736 return ret;
1739 static void clear_response_headers( struct request *request )
1741 unsigned int i;
1743 for (i = 0; i < request->num_headers; i++)
1745 if (!request->headers[i].field) continue;
1746 if (!request->headers[i].value) continue;
1747 if (request->headers[i].is_request) continue;
1748 delete_header( request, i );
1749 i--;
1753 /* remove some amount of data from the read buffer */
1754 static void remove_data( struct request *request, int count )
1756 if (!(request->read_size -= count)) request->read_pos = 0;
1757 else request->read_pos += count;
1760 /* read some more data into the read buffer */
1761 static DWORD read_more_data( struct request *request, int maxlen, BOOL notify )
1763 int len;
1764 DWORD ret;
1766 if (request->read_chunked_eof) return ERROR_INSUFFICIENT_BUFFER;
1768 if (request->read_size && request->read_pos)
1770 /* move existing data to the start of the buffer */
1771 memmove( request->read_buf, request->read_buf + request->read_pos, request->read_size );
1772 request->read_pos = 0;
1774 if (maxlen == -1) maxlen = sizeof(request->read_buf);
1776 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
1778 ret = netconn_recv( request->netconn, request->read_buf + request->read_size,
1779 maxlen - request->read_size, 0, &len );
1781 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED, &len, sizeof(len) );
1782 request->read_reply_len += len;
1784 request->read_size += len;
1785 return ret;
1788 /* discard data contents until we reach end of line */
1789 static DWORD discard_eol( struct request *request, BOOL notify )
1791 DWORD ret;
1794 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1795 if (eol)
1797 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1798 break;
1800 request->read_pos = request->read_size = 0; /* discard everything */
1801 if ((ret = read_more_data( request, -1, notify ))) return ret;
1802 } while (request->read_size);
1803 return ERROR_SUCCESS;
1806 static void update_value_from_digit( DWORD *value, char ch )
1808 if (ch >= '0' && ch <= '9') *value = *value * 16 + ch - '0';
1809 else if (ch >= 'a' && ch <= 'f') *value = *value * 16 + ch - 'a' + 10;
1810 else if (ch >= 'A' && ch <= 'F') *value = *value * 16 + ch - 'A' + 10;
1813 /* read chunk size if already in the read buffer */
1814 static BOOL get_chunk_size( struct request *request )
1816 DWORD chunk_size;
1817 char *p, *eol;
1819 if (request->read_chunked_size != ~0ul) return TRUE;
1821 eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
1822 if (!eol) return FALSE;
1824 chunk_size = 0;
1825 for (p = request->read_buf + request->read_pos; p != eol; ++p)
1827 if (*p == ';' || *p == '\r') break;
1828 update_value_from_digit( &chunk_size, *p );
1831 request->read_chunked_size = chunk_size;
1832 if (!chunk_size) request->read_chunked_eof = TRUE;
1834 remove_data( request, (eol + 1) - (request->read_buf + request->read_pos) );
1835 return TRUE;
1838 /* read the size of the next chunk */
1839 static DWORD start_next_chunk( struct request *request, BOOL notify )
1841 DWORD ret, chunk_size = 0;
1843 assert(!request->read_chunked_size || request->read_chunked_size == ~0u);
1845 if (request->read_chunked_eof) return ERROR_INSUFFICIENT_BUFFER;
1847 /* read terminator for the previous chunk */
1848 if (!request->read_chunked_size && (ret = discard_eol( request, notify ))) return ret;
1850 for (;;)
1852 while (request->read_size)
1854 char ch = request->read_buf[request->read_pos];
1856 if (ch == ';' || ch == '\r' || ch == '\n')
1858 TRACE( "reading %lu byte chunk\n", chunk_size );
1860 if (request->content_length == ~0u) request->content_length = chunk_size;
1861 else request->content_length += chunk_size;
1863 request->read_chunked_size = chunk_size;
1864 if (!chunk_size) request->read_chunked_eof = TRUE;
1866 return discard_eol( request, notify );
1868 update_value_from_digit( &chunk_size, ch );
1869 remove_data( request, 1 );
1871 if ((ret = read_more_data( request, -1, notify ))) return ret;
1872 if (!request->read_size)
1874 request->content_length = request->content_read = 0;
1875 request->read_chunked_size = 0;
1876 return ERROR_SUCCESS;
1881 static DWORD refill_buffer( struct request *request, BOOL notify )
1883 int len = sizeof(request->read_buf);
1884 DWORD ret;
1886 if (request->read_chunked)
1888 if (request->read_chunked_eof) return ERROR_INSUFFICIENT_BUFFER;
1889 if (request->read_chunked_size == ~0u || !request->read_chunked_size)
1891 if ((ret = start_next_chunk( request, notify ))) return ret;
1893 len = min( len, request->read_chunked_size );
1895 else if (request->content_length != ~0u)
1897 len = min( len, request->content_length - request->content_read );
1900 if (len <= request->read_size) return ERROR_SUCCESS;
1901 if ((ret = read_more_data( request, len, notify ))) return ret;
1902 if (!request->read_size) request->content_length = request->content_read = 0;
1903 return ERROR_SUCCESS;
1906 static void finished_reading( struct request *request )
1908 BOOL close = FALSE, notify;
1909 WCHAR connection[20];
1910 DWORD size = sizeof(connection);
1912 if (!request->netconn) return;
1914 if (request->netconn->socket == -1) close = TRUE;
1915 else if (request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE) close = TRUE;
1916 else if (!query_headers( request, WINHTTP_QUERY_CONNECTION, NULL, connection, &size, NULL ) ||
1917 !query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION, NULL, connection, &size, NULL ))
1919 if (!wcsicmp( connection, L"close" )) close = TRUE;
1921 else if (!wcscmp( request->version, L"HTTP/1.0" )) close = TRUE;
1923 if (close)
1925 size = sizeof(connection);
1926 notify = (!query_headers( request, WINHTTP_QUERY_CONNECTION | WINHTTP_QUERY_FLAG_REQUEST_HEADERS,
1927 NULL, connection, &size, NULL )
1928 || !query_headers( request, WINHTTP_QUERY_PROXY_CONNECTION | WINHTTP_QUERY_FLAG_REQUEST_HEADERS,
1929 NULL, connection, &size, NULL ))
1930 && !wcsicmp( connection, L"close" );
1932 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION, 0, 0 );
1933 netconn_release( request->netconn );
1934 if (notify) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED, 0, 0 );
1936 else
1937 cache_connection( request->netconn );
1938 request->netconn = NULL;
1941 /* return the size of data available to be read immediately */
1942 static DWORD get_available_data( struct request *request )
1944 if (request->read_chunked)
1946 if (!get_chunk_size( request )) return 0;
1947 return min( request->read_chunked_size, request->read_size );
1949 return request->read_size;
1952 /* check if we have reached the end of the data to read */
1953 static BOOL end_of_read_data( struct request *request )
1955 if (!request->content_length) return TRUE;
1956 if (request->read_chunked) return request->read_chunked_eof;
1957 if (request->content_length == ~0u) return FALSE;
1958 return (request->content_length == request->content_read);
1961 static DWORD read_data( struct request *request, void *buffer, DWORD size, DWORD *read, BOOL async )
1963 int count, bytes_read = 0;
1964 DWORD ret = ERROR_SUCCESS;
1966 if (request->read_chunked && request->read_chunked_size == ~0u
1967 && (ret = start_next_chunk( request, async ))) goto done;
1969 if (end_of_read_data( request )) goto done;
1971 while (size)
1973 if (!(count = get_available_data( request )))
1975 if ((ret = refill_buffer( request, async ))) goto done;
1976 if (!(count = get_available_data( request ))) goto done;
1978 count = min( count, size );
1979 memcpy( (char *)buffer + bytes_read, request->read_buf + request->read_pos, count );
1980 remove_data( request, count );
1981 if (request->read_chunked) request->read_chunked_size -= count;
1982 size -= count;
1983 bytes_read += count;
1984 request->content_read += count;
1985 if (end_of_read_data( request )) goto done;
1987 if (request->read_chunked && !request->read_chunked_size) ret = refill_buffer( request, async );
1989 done:
1990 TRACE( "retrieved %u bytes (%lu/%lu)\n", bytes_read, request->content_read, request->content_length );
1991 if (end_of_read_data( request )) finished_reading( request );
1992 if (async)
1994 if (!ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytes_read );
1995 else
1997 WINHTTP_ASYNC_RESULT result;
1998 result.dwResult = API_READ_DATA;
1999 result.dwError = ret;
2000 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2004 if (!ret && read) *read = bytes_read;
2005 return ret;
2008 /* read any content returned by the server so that the connection can be reused */
2009 static void drain_content( struct request *request )
2011 DWORD size, bytes_read, bytes_total = 0, bytes_left = request->content_length - request->content_read;
2012 char buffer[2048];
2014 refill_buffer( request, FALSE );
2015 for (;;)
2017 if (request->read_chunked) size = sizeof(buffer);
2018 else size = min( sizeof(buffer), bytes_left - bytes_total );
2020 if (read_data( request, buffer, size, &bytes_read, FALSE ) || !bytes_read) return;
2021 bytes_total += bytes_read;
2025 enum escape_flags
2027 ESCAPE_FLAG_NON_PRINTABLE = 0x01,
2028 ESCAPE_FLAG_SPACE = 0x02,
2029 ESCAPE_FLAG_PERCENT = 0x04,
2030 ESCAPE_FLAG_UNSAFE = 0x08,
2031 ESCAPE_FLAG_DEL = 0x10,
2032 ESCAPE_FLAG_8BIT = 0x20,
2033 ESCAPE_FLAG_STRIP_CRLF = 0x40,
2036 #define ESCAPE_MASK_DEFAULT (ESCAPE_FLAG_NON_PRINTABLE | ESCAPE_FLAG_SPACE | ESCAPE_FLAG_UNSAFE |\
2037 ESCAPE_FLAG_DEL | ESCAPE_FLAG_8BIT)
2038 #define ESCAPE_MASK_PERCENT (ESCAPE_FLAG_PERCENT | ESCAPE_MASK_DEFAULT)
2039 #define ESCAPE_MASK_DISABLE (ESCAPE_FLAG_SPACE | ESCAPE_FLAG_8BIT | ESCAPE_FLAG_STRIP_CRLF)
2041 static inline BOOL need_escape( char ch, enum escape_flags flags )
2043 static const char unsafe[] = "\"#<>[\\]^`{|}";
2044 const char *ptr = unsafe;
2046 if ((flags & ESCAPE_FLAG_SPACE) && ch == ' ') return TRUE;
2047 if ((flags & ESCAPE_FLAG_PERCENT) && ch == '%') return TRUE;
2048 if ((flags & ESCAPE_FLAG_NON_PRINTABLE) && ch < 0x20) return TRUE;
2049 if ((flags & ESCAPE_FLAG_DEL) && ch == 0x7f) return TRUE;
2050 if ((flags & ESCAPE_FLAG_8BIT) && (ch & 0x80)) return TRUE;
2051 if ((flags & ESCAPE_FLAG_UNSAFE)) while (*ptr) { if (ch == *ptr++) return TRUE; }
2052 return FALSE;
2055 static DWORD escape_string( const char *src, DWORD len, char *dst, enum escape_flags flags )
2057 static const char hex[] = "0123456789ABCDEF";
2058 DWORD i, ret = len;
2059 char *ptr = dst;
2061 for (i = 0; i < len; i++)
2063 if ((flags & ESCAPE_FLAG_STRIP_CRLF) && (src[i] == '\r' || src[i] == '\n'))
2065 ret--;
2066 continue;
2068 if (need_escape( src[i], flags ))
2070 if (dst)
2072 ptr[0] = '%';
2073 ptr[1] = hex[(src[i] >> 4) & 0xf];
2074 ptr[2] = hex[src[i] & 0xf];
2075 ptr += 3;
2077 ret += 2;
2079 else if (dst) *ptr++ = src[i];
2082 if (dst) dst[ret] = 0;
2083 return ret;
2086 static DWORD str_to_wire( const WCHAR *src, int src_len, char *dst, enum escape_flags flags )
2088 DWORD len;
2089 char *utf8;
2091 if (src_len < 0) src_len = lstrlenW( src );
2092 len = WideCharToMultiByte( CP_UTF8, 0, src, src_len, NULL, 0, NULL, NULL );
2093 if (!(utf8 = malloc( len ))) return 0;
2095 WideCharToMultiByte( CP_UTF8, 0, src, -1, utf8, len, NULL, NULL );
2096 len = escape_string( utf8, len, dst, flags );
2097 free( utf8 );
2099 return len;
2102 static char *build_wire_path( struct request *request, DWORD *ret_len )
2104 WCHAR *full_path;
2105 const WCHAR *start, *path, *query = NULL;
2106 DWORD len, len_path = 0, len_query = 0;
2107 enum escape_flags path_flags, query_flags;
2108 char *ret;
2110 if (!wcsicmp( request->connect->hostname, request->connect->servername )) start = full_path = request->path;
2111 else if (!(full_path = build_absolute_request_path( request, &start ))) return NULL;
2113 len = lstrlenW( full_path );
2114 if ((path = wcschr( start, '/' )))
2116 len_path = lstrlenW( path );
2117 if ((query = wcschr( path, '?' )))
2119 len_query = lstrlenW( query );
2120 len_path -= len_query;
2124 if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_DISABLE) path_flags = ESCAPE_MASK_DISABLE;
2125 else if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_PERCENT) path_flags = ESCAPE_MASK_PERCENT;
2126 else path_flags = ESCAPE_MASK_DEFAULT;
2128 if (request->hdr.flags & WINHTTP_FLAG_ESCAPE_DISABLE_QUERY) query_flags = ESCAPE_MASK_DISABLE;
2129 else query_flags = path_flags;
2131 *ret_len = str_to_wire( full_path, len - len_path - len_query, NULL, 0 );
2132 if (path) *ret_len += str_to_wire( path, len_path, NULL, path_flags );
2133 if (query) *ret_len += str_to_wire( query, len_query, NULL, query_flags );
2135 if ((ret = malloc( *ret_len + 1 )))
2137 len = str_to_wire( full_path, len - len_path - len_query, ret, 0 );
2138 if (path) len += str_to_wire( path, len_path, ret + len, path_flags );
2139 if (query) str_to_wire( query, len_query, ret + len, query_flags );
2142 if (full_path != request->path) free( full_path );
2143 return ret;
2146 static char *build_wire_request( struct request *request, DWORD *len )
2148 char *path, *ptr, *ret;
2149 DWORD i, len_path;
2151 if (!(path = build_wire_path( request, &len_path ))) return NULL;
2153 *len = str_to_wire( request->verb, -1, NULL, 0 ) + 1; /* ' ' */
2154 *len += len_path + 1; /* ' ' */
2155 *len += str_to_wire( request->version, -1, NULL, 0 );
2157 for (i = 0; i < request->num_headers; i++)
2159 if (request->headers[i].is_request)
2161 *len += str_to_wire( request->headers[i].field, -1, NULL, 0 ) + 2; /* ': ' */
2162 *len += str_to_wire( request->headers[i].value, -1, NULL, 0 ) + 2; /* '\r\n' */
2165 *len += 4; /* '\r\n\r\n' */
2167 if ((ret = ptr = malloc( *len + 1 )))
2169 ptr += str_to_wire( request->verb, -1, ptr, 0 );
2170 *ptr++ = ' ';
2171 memcpy( ptr, path, len_path );
2172 ptr += len_path;
2173 *ptr++ = ' ';
2174 ptr += str_to_wire( request->version, -1, ptr, 0 );
2176 for (i = 0; i < request->num_headers; i++)
2178 if (request->headers[i].is_request)
2180 *ptr++ = '\r';
2181 *ptr++ = '\n';
2182 ptr += str_to_wire( request->headers[i].field, -1, ptr, 0 );
2183 *ptr++ = ':';
2184 *ptr++ = ' ';
2185 ptr += str_to_wire( request->headers[i].value, -1, ptr, 0 );
2188 memcpy( ptr, "\r\n\r\n", sizeof("\r\n\r\n") );
2191 free( path );
2192 return ret;
2195 static WCHAR *create_websocket_key(void)
2197 WCHAR *ret;
2198 char buf[16];
2199 DWORD base64_len = ((sizeof(buf) + 2) * 4) / 3;
2200 if (!RtlGenRandom( buf, sizeof(buf) )) return NULL;
2201 if ((ret = malloc( (base64_len + 1) * sizeof(WCHAR) ))) encode_base64( buf, sizeof(buf), ret );
2202 return ret;
2205 static DWORD add_websocket_key_header( struct request *request )
2207 WCHAR *key = create_websocket_key();
2208 if (!key) return ERROR_OUTOFMEMORY;
2209 process_header( request, L"Sec-WebSocket-Key", key, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE, TRUE );
2210 free( key );
2211 return ERROR_SUCCESS;
2214 static DWORD send_request( struct request *request, const WCHAR *headers, DWORD headers_len, void *optional,
2215 DWORD optional_len, DWORD total_len, DWORD_PTR context, BOOL async )
2217 struct connect *connect = request->connect;
2218 struct session *session = connect->session;
2219 DWORD ret, len, buflen, content_length;
2220 char *wire_req;
2221 int bytes_sent;
2223 TRACE( "request state %d.\n", request->state );
2225 request->read_reply_status = ERROR_WINHTTP_INCORRECT_HANDLE_STATE;
2226 request->read_reply_len = 0;
2227 request->state = REQUEST_RESPONSE_STATE_NONE;
2229 if (request->flags & REQUEST_FLAG_WEBSOCKET_UPGRADE
2230 && request->websocket_set_send_buffer_size < MIN_WEBSOCKET_SEND_BUFFER_SIZE)
2232 WARN( "Invalid send buffer size %u.\n", request->websocket_set_send_buffer_size );
2233 ret = ERROR_NOT_ENOUGH_MEMORY;
2234 goto end;
2237 drain_content( request );
2238 clear_response_headers( request );
2240 if (session->agent)
2241 process_header( request, L"User-Agent", session->agent, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2243 if (connect->hostname)
2244 add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
2246 if (request->creds[TARGET_SERVER][SCHEME_BASIC].username)
2247 do_authorization( request, WINHTTP_AUTH_TARGET_SERVER, WINHTTP_AUTH_SCHEME_BASIC );
2249 if (total_len || (request->verb && (!wcscmp( request->verb, L"POST" ) || !wcscmp( request->verb, L"PUT" ))))
2251 WCHAR length[21]; /* decimal long int + null */
2252 swprintf( length, ARRAY_SIZE(length), L"%ld", total_len );
2253 process_header( request, L"Content-Length", length, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2255 if (request->flags & REQUEST_FLAG_WEBSOCKET_UPGRADE)
2257 request->websocket_send_buffer_size = request->websocket_set_send_buffer_size;
2258 process_header( request, L"Upgrade", L"websocket", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2259 process_header( request, L"Connection", L"Upgrade", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2260 process_header( request, L"Sec-WebSocket-Version", L"13", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2261 if ((ret = add_websocket_key_header( request ))) return ret;
2263 else if (!(request->hdr.disable_flags & WINHTTP_DISABLE_KEEP_ALIVE))
2265 process_header( request, L"Connection", L"Keep-Alive", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2267 if (request->hdr.flags & WINHTTP_FLAG_REFRESH)
2269 process_header( request, L"Pragma", L"no-cache", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2270 process_header( request, L"Cache-Control", L"no-cache", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW, TRUE );
2272 if (headers && (ret = add_request_headers( request, headers, headers_len,
2273 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE )))
2275 TRACE( "failed to add request headers: %lu\n", ret );
2276 return ret;
2278 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES) && (ret = add_cookie_headers( request )))
2280 WARN( "failed to add cookie headers: %lu\n", ret );
2281 return ret;
2284 if (context) request->hdr.context = context;
2286 if ((ret = open_connection( request ))) goto end;
2287 if (!(wire_req = build_wire_request( request, &len )))
2289 ret = ERROR_OUTOFMEMORY;
2290 goto end;
2292 TRACE("full request: %s\n", debugstr_a(wire_req));
2294 request->state = REQUEST_RESPONSE_STATE_SENDING_REQUEST;
2295 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST, NULL, 0 );
2297 ret = netconn_send( request->netconn, wire_req, len, &bytes_sent, NULL );
2298 free( wire_req );
2299 if (ret) goto end;
2301 if (optional_len)
2303 if ((ret = netconn_send( request->netconn, optional, optional_len, &bytes_sent, NULL ))) goto end;
2304 request->optional = optional;
2305 request->optional_len = optional_len;
2306 len += optional_len;
2308 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_SENT, &len, sizeof(len) );
2310 buflen = sizeof(content_length);
2311 if (query_headers( request, WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_CONTENT_LENGTH
2312 | WINHTTP_QUERY_FLAG_NUMBER, NULL, &content_length, &buflen, NULL ))
2313 content_length = total_len;
2315 if (content_length <= optional_len)
2317 netconn_set_timeout( request->netconn, FALSE, request->receive_response_timeout );
2318 request->read_reply_status = read_reply( request );
2319 if (request->state == REQUEST_RESPONSE_STATE_READ_RESPONSE_QUEUED)
2320 request->state = REQUEST_RESPONSE_STATE_READ_RESPONSE_QUEUED_REPLY_RECEIVED;
2321 else
2322 request->state = REQUEST_RESPONSE_STATE_REPLY_RECEIVED;
2324 else
2326 if (request->state == REQUEST_RESPONSE_STATE_READ_RESPONSE_QUEUED)
2327 request->state = REQUEST_RESPONSE_STATE_READ_RESPONSE_QUEUED_REQUEST_SENT;
2328 else
2329 request->state = REQUEST_RESPONSE_STATE_REQUEST_SENT;
2332 end:
2333 if (async)
2335 if (!ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, NULL, 0 );
2336 else
2338 WINHTTP_ASYNC_RESULT result;
2339 result.dwResult = API_SEND_REQUEST;
2340 result.dwError = ret;
2341 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2344 return ret;
2347 static void task_send_request( void *ctx, BOOL abort )
2349 struct send_request *s = ctx;
2350 struct request *request = (struct request *)s->task_hdr.obj;
2352 if (abort) return;
2354 TRACE( "running %p\n", ctx );
2355 send_request( request, s->headers, s->headers_len, s->optional, s->optional_len, s->total_len, s->context, TRUE );
2357 free( s->headers );
2360 /***********************************************************************
2361 * WinHttpSendRequest (winhttp.@)
2363 BOOL WINAPI WinHttpSendRequest( HINTERNET hrequest, const WCHAR *headers, DWORD headers_len,
2364 void *optional, DWORD optional_len, DWORD total_len, DWORD_PTR context )
2366 DWORD ret;
2367 struct request *request;
2369 TRACE( "%p, %s, %lu, %p, %lu, %lu, %Ix\n", hrequest, debugstr_wn(headers, headers_len), headers_len, optional,
2370 optional_len, total_len, context );
2372 if (!(request = (struct request *)grab_object( hrequest )))
2374 SetLastError( ERROR_INVALID_HANDLE );
2375 return FALSE;
2377 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2379 release_object( &request->hdr );
2380 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2381 return FALSE;
2384 if (headers && !headers_len) headers_len = lstrlenW( headers );
2386 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
2388 struct send_request *s;
2390 if (!(s = malloc( sizeof(*s) )))
2392 release_object( &request->hdr );
2393 SetLastError( ERROR_OUTOFMEMORY );
2394 return FALSE;
2396 s->headers = wcsdup( headers );
2397 s->headers_len = headers_len;
2398 s->optional = optional;
2399 s->optional_len = optional_len;
2400 s->total_len = total_len;
2401 s->context = context;
2403 if ((ret = queue_task( &request->queue, task_send_request, &s->task_hdr, &request->hdr )))
2405 free( s->headers );
2406 free( s );
2409 else ret = send_request( request, headers, headers_len, optional, optional_len, total_len, context, FALSE );
2411 release_object( &request->hdr );
2412 SetLastError( ret );
2413 return !ret;
2416 static DWORD set_credentials( struct request *request, DWORD target, DWORD scheme_flag, const WCHAR *username,
2417 const WCHAR *password )
2419 enum auth_scheme scheme = scheme_from_flag( scheme_flag );
2421 if (scheme == SCHEME_INVALID || ((scheme == SCHEME_BASIC || scheme == SCHEME_DIGEST) && (!username || !password)))
2423 return ERROR_INVALID_PARAMETER;
2425 switch (target)
2427 case WINHTTP_AUTH_TARGET_SERVER:
2429 free( request->creds[TARGET_SERVER][scheme].username );
2430 if (!username) request->creds[TARGET_SERVER][scheme].username = NULL;
2431 else if (!(request->creds[TARGET_SERVER][scheme].username = wcsdup( username ))) return ERROR_OUTOFMEMORY;
2433 free( request->creds[TARGET_SERVER][scheme].password );
2434 if (!password) request->creds[TARGET_SERVER][scheme].password = NULL;
2435 else if (!(request->creds[TARGET_SERVER][scheme].password = wcsdup( password ))) return ERROR_OUTOFMEMORY;
2436 break;
2438 case WINHTTP_AUTH_TARGET_PROXY:
2440 free( request->creds[TARGET_PROXY][scheme].username );
2441 if (!username) request->creds[TARGET_PROXY][scheme].username = NULL;
2442 else if (!(request->creds[TARGET_PROXY][scheme].username = wcsdup( username ))) return ERROR_OUTOFMEMORY;
2444 free( request->creds[TARGET_PROXY][scheme].password );
2445 if (!password) request->creds[TARGET_PROXY][scheme].password = NULL;
2446 else if (!(request->creds[TARGET_PROXY][scheme].password = wcsdup( password ))) return ERROR_OUTOFMEMORY;
2447 break;
2449 default:
2450 WARN( "unknown target %lu\n", target );
2451 return ERROR_INVALID_PARAMETER;
2453 return ERROR_SUCCESS;
2456 /***********************************************************************
2457 * WinHttpSetCredentials (winhttp.@)
2459 BOOL WINAPI WinHttpSetCredentials( HINTERNET hrequest, DWORD target, DWORD scheme, const WCHAR *username,
2460 const WCHAR *password, void *params )
2462 DWORD ret;
2463 struct request *request;
2465 TRACE( "%p, %lu, %#lx, %s, %p, %p\n", hrequest, target, scheme, debugstr_w(username), password, params );
2467 if (!(request = (struct request *)grab_object( hrequest )))
2469 SetLastError( ERROR_INVALID_HANDLE );
2470 return FALSE;
2472 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
2474 release_object( &request->hdr );
2475 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
2476 return FALSE;
2479 ret = set_credentials( request, target, scheme, username, password );
2481 release_object( &request->hdr );
2482 SetLastError( ret );
2483 return !ret;
2486 static DWORD handle_authorization( struct request *request, DWORD status )
2488 DWORD ret, i, schemes, first, level, target;
2490 switch (status)
2492 case HTTP_STATUS_DENIED:
2493 target = WINHTTP_AUTH_TARGET_SERVER;
2494 level = WINHTTP_QUERY_WWW_AUTHENTICATE;
2495 break;
2497 case HTTP_STATUS_PROXY_AUTH_REQ:
2498 target = WINHTTP_AUTH_TARGET_PROXY;
2499 level = WINHTTP_QUERY_PROXY_AUTHENTICATE;
2500 break;
2502 default:
2503 ERR( "unhandled status %lu\n", status );
2504 return ERROR_WINHTTP_INTERNAL_ERROR;
2507 if ((ret = query_auth_schemes( request, level, &schemes, &first ))) return ret;
2508 if (do_authorization( request, target, first )) return ERROR_SUCCESS;
2510 schemes &= ~first;
2511 for (i = 0; i < ARRAY_SIZE( auth_schemes ); i++)
2513 if (!(schemes & auth_schemes[i].scheme)) continue;
2514 if (do_authorization( request, target, auth_schemes[i].scheme )) return ERROR_SUCCESS;
2516 return ERROR_WINHTTP_LOGIN_FAILURE;
2519 /* set the request content length based on the headers */
2520 static void set_content_length( struct request *request, DWORD status )
2522 WCHAR encoding[20];
2523 DWORD buflen = sizeof(request->content_length);
2525 if (status == HTTP_STATUS_NO_CONTENT || status == HTTP_STATUS_NOT_MODIFIED ||
2526 status == HTTP_STATUS_SWITCH_PROTOCOLS || !wcscmp( request->verb, L"HEAD" ))
2528 request->content_length = 0;
2530 else
2532 if (query_headers( request, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER,
2533 NULL, &request->content_length, &buflen, NULL ))
2534 request->content_length = ~0u;
2536 buflen = sizeof(encoding);
2537 if (!query_headers( request, WINHTTP_QUERY_TRANSFER_ENCODING, NULL, encoding, &buflen, NULL ) &&
2538 !wcsicmp( encoding, L"chunked" ))
2540 request->content_length = ~0u;
2541 request->read_chunked = TRUE;
2542 request->read_chunked_size = ~0u;
2543 request->read_chunked_eof = FALSE;
2546 request->content_read = 0;
2549 static DWORD read_line( struct request *request, char *buffer, DWORD *len )
2551 int count, bytes_read, pos = 0;
2552 DWORD ret;
2554 for (;;)
2556 char *eol = memchr( request->read_buf + request->read_pos, '\n', request->read_size );
2557 if (eol)
2559 count = eol - (request->read_buf + request->read_pos);
2560 bytes_read = count + 1;
2562 else count = bytes_read = request->read_size;
2564 count = min( count, *len - pos );
2565 memcpy( buffer + pos, request->read_buf + request->read_pos, count );
2566 pos += count;
2567 remove_data( request, bytes_read );
2568 if (eol) break;
2570 if ((ret = read_more_data( request, -1, FALSE ))) return ret;
2571 if (!request->read_size)
2573 *len = 0;
2574 TRACE("returning empty string\n");
2575 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
2578 if (pos < *len)
2580 if (pos && buffer[pos - 1] == '\r') pos--;
2581 *len = pos + 1;
2583 buffer[*len - 1] = 0;
2584 TRACE("returning %s\n", debugstr_a(buffer));
2585 return ERROR_SUCCESS;
2588 #define MAX_REPLY_LEN 1460
2589 #define INITIAL_HEADER_BUFFER_LEN 512
2591 static DWORD read_reply( struct request *request )
2593 char buffer[MAX_REPLY_LEN];
2594 DWORD ret, buflen, len, offset, crlf_len = 2; /* lstrlenW(crlf) */
2595 char *status_code, *status_text;
2596 WCHAR *versionW, *status_textW, *raw_headers;
2597 WCHAR status_codeW[4]; /* sizeof("nnn") */
2599 if (!request->netconn) return ERROR_WINHTTP_INCORRECT_HANDLE_STATE;
2603 buflen = MAX_REPLY_LEN;
2604 if ((ret = read_line( request, buffer, &buflen ))) return ret;
2606 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2607 if (!(status_code = strchr( buffer, ' ' ))) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
2608 status_code++;
2609 if (!(status_text = strchr( status_code, ' ' ))) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
2610 if ((len = status_text - status_code) != sizeof("nnn") - 1) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
2611 status_text++;
2613 TRACE("version [%s] status code [%s] status text [%s]\n",
2614 debugstr_an(buffer, status_code - buffer - 1),
2615 debugstr_an(status_code, len),
2616 debugstr_a(status_text));
2618 } while (!memcmp( status_code, "100", len )); /* ignore "100 Continue" responses */
2620 /* we rely on the fact that the protocol is ascii */
2621 MultiByteToWideChar( CP_ACP, 0, status_code, len, status_codeW, len );
2622 status_codeW[len] = 0;
2623 if ((ret = process_header( request, L"Status", status_codeW,
2624 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE, FALSE ))) return ret;
2626 len = status_code - buffer;
2627 if (!(versionW = malloc( len * sizeof(WCHAR) ))) return ERROR_OUTOFMEMORY;
2628 MultiByteToWideChar( CP_ACP, 0, buffer, len - 1, versionW, len -1 );
2629 versionW[len - 1] = 0;
2631 free( request->version );
2632 request->version = versionW;
2634 len = buflen - (status_text - buffer);
2635 if (!(status_textW = malloc( len * sizeof(WCHAR) ))) return ERROR_OUTOFMEMORY;
2636 MultiByteToWideChar( CP_ACP, 0, status_text, len, status_textW, len );
2638 free( request->status_text );
2639 request->status_text = status_textW;
2641 len = max( buflen + crlf_len, INITIAL_HEADER_BUFFER_LEN );
2642 if (!(raw_headers = malloc( len * sizeof(WCHAR) ))) return ERROR_OUTOFMEMORY;
2643 MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers, buflen );
2644 memcpy( raw_headers + buflen - 1, L"\r\n", sizeof(L"\r\n") );
2646 free( request->raw_headers );
2647 request->raw_headers = raw_headers;
2649 offset = buflen + crlf_len - 1;
2650 for (;;)
2652 struct header *header;
2653 int lenW;
2655 buflen = MAX_REPLY_LEN;
2656 if (read_line( request, buffer, &buflen )) return ERROR_SUCCESS;
2657 if (!*buffer) buflen = 1;
2659 while (len - offset < buflen + crlf_len)
2661 WCHAR *tmp;
2662 len *= 2;
2663 if (!(tmp = realloc( raw_headers, len * sizeof(WCHAR) ))) return ERROR_OUTOFMEMORY;
2664 request->raw_headers = raw_headers = tmp;
2666 if (!*buffer)
2668 memcpy( raw_headers + offset, L"\r\n", sizeof(L"\r\n") );
2669 break;
2671 lenW = MultiByteToWideChar( CP_ACP, 0, buffer, buflen, raw_headers + offset, buflen );
2673 if (!(header = parse_header( raw_headers + offset, lenW - 1 ))) break;
2674 if ((ret = process_header( request, header->field, header->value, WINHTTP_ADDREQ_FLAG_ADD, FALSE )))
2676 free_header( header );
2677 break;
2679 free_header( header );
2680 memcpy( raw_headers + offset + buflen - 1, L"\r\n", sizeof(L"\r\n") );
2681 offset += buflen + crlf_len - 1;
2684 TRACE("raw headers: %s\n", debugstr_w(raw_headers));
2685 return ret;
2688 static void record_cookies( struct request *request )
2690 unsigned int i;
2692 for (i = 0; i < request->num_headers; i++)
2694 struct header *set_cookie = &request->headers[i];
2695 if (!wcsicmp( set_cookie->field, L"Set-Cookie" ) && !set_cookie->is_request)
2697 set_cookies( request, set_cookie->value );
2702 static DWORD get_redirect_url( struct request *request, WCHAR **ret_url, DWORD *ret_len )
2704 DWORD size, ret;
2705 WCHAR *url;
2707 ret = query_headers( request, WINHTTP_QUERY_LOCATION, NULL, NULL, &size, NULL );
2708 if (ret != ERROR_INSUFFICIENT_BUFFER) return ret;
2709 if (!(url = malloc( size ))) return ERROR_OUTOFMEMORY;
2710 if ((ret = query_headers( request, WINHTTP_QUERY_LOCATION, NULL, url, &size, NULL )))
2712 free( url );
2713 return ret;
2715 *ret_url = url;
2716 *ret_len = size / sizeof(WCHAR);
2717 return ERROR_SUCCESS;
2720 static DWORD handle_redirect( struct request *request, DWORD status )
2722 DWORD ret, len, len_loc = 0;
2723 URL_COMPONENTS uc;
2724 struct connect *connect = request->connect;
2725 INTERNET_PORT port;
2726 WCHAR *hostname = NULL, *location = NULL;
2728 if ((ret = get_redirect_url( request, &location, &len_loc ))) return ret;
2730 memset( &uc, 0, sizeof(uc) );
2731 uc.dwStructSize = sizeof(uc);
2732 uc.dwSchemeLength = uc.dwHostNameLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = ~0u;
2734 if (!WinHttpCrackUrl( location, len_loc, 0, &uc )) /* assume relative redirect */
2736 WCHAR *path, *p;
2738 ret = ERROR_OUTOFMEMORY;
2739 if (location[0] == '/')
2741 if (!(path = malloc( (len_loc + 1) * sizeof(WCHAR) ))) goto end;
2742 memcpy( path, location, len_loc * sizeof(WCHAR) );
2743 path[len_loc] = 0;
2745 else
2747 if ((p = wcsrchr( request->path, '/' ))) *p = 0;
2748 len = lstrlenW( request->path ) + 1 + len_loc;
2749 if (!(path = malloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2750 lstrcpyW( path, request->path );
2751 lstrcatW( path, L"/" );
2752 memcpy( path + lstrlenW(path), location, len_loc * sizeof(WCHAR) );
2753 path[len_loc] = 0;
2755 free( request->path );
2756 request->path = path;
2757 ret = ERROR_SUCCESS;
2759 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_loc + 1 );
2761 else
2763 if (uc.nScheme == INTERNET_SCHEME_HTTP && request->hdr.flags & WINHTTP_FLAG_SECURE)
2765 if (request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP)
2767 ret = ERROR_WINHTTP_REDIRECT_FAILED;
2768 goto end;
2770 TRACE("redirect from secure page to non-secure page\n");
2771 request->hdr.flags &= ~WINHTTP_FLAG_SECURE;
2773 else if (uc.nScheme == INTERNET_SCHEME_HTTPS && !(request->hdr.flags & WINHTTP_FLAG_SECURE))
2775 TRACE("redirect from non-secure page to secure page\n");
2776 request->hdr.flags |= WINHTTP_FLAG_SECURE;
2779 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REDIRECT, location, len_loc + 1 );
2781 len = uc.dwHostNameLength;
2782 if (!(hostname = malloc( (len + 1) * sizeof(WCHAR) )))
2784 ret = ERROR_OUTOFMEMORY;
2785 goto end;
2787 memcpy( hostname, uc.lpszHostName, len * sizeof(WCHAR) );
2788 hostname[len] = 0;
2790 port = uc.nPort ? uc.nPort : (uc.nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80);
2791 if (wcsicmp( connect->hostname, hostname ) || connect->serverport != port)
2793 free( connect->hostname );
2794 connect->hostname = hostname;
2795 connect->hostport = port;
2796 if (!set_server_for_hostname( connect, hostname, port ))
2798 ret = ERROR_OUTOFMEMORY;
2799 goto end;
2802 netconn_release( request->netconn );
2803 request->netconn = NULL;
2804 request->content_length = request->content_read = 0;
2805 request->read_pos = request->read_size = 0;
2806 request->read_chunked = request->read_chunked_eof = FALSE;
2808 else free( hostname );
2810 if ((ret = add_host_header( request, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))) goto end;
2812 free( request->path );
2813 request->path = NULL;
2814 if (uc.dwUrlPathLength)
2816 len = uc.dwUrlPathLength + uc.dwExtraInfoLength;
2817 if (!(request->path = malloc( (len + 1) * sizeof(WCHAR) ))) goto end;
2818 memcpy( request->path, uc.lpszUrlPath, (len + 1) * sizeof(WCHAR) );
2819 request->path[len] = 0;
2821 else request->path = wcsdup( L"/" );
2824 if (status != HTTP_STATUS_REDIRECT_KEEP_VERB && !wcscmp( request->verb, L"POST" ))
2826 free( request->verb );
2827 request->verb = wcsdup( L"GET" );
2828 request->optional = NULL;
2829 request->optional_len = 0;
2832 end:
2833 free( location );
2834 return ret;
2837 static BOOL is_passport_request( struct request *request )
2839 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t','1','.','4'};
2840 WCHAR buf[1024];
2841 DWORD len = ARRAY_SIZE(buf);
2843 if (!(request->connect->session->passport_flags & WINHTTP_ENABLE_PASSPORT_AUTH) ||
2844 query_headers( request, WINHTTP_QUERY_WWW_AUTHENTICATE, NULL, buf, &len, NULL )) return FALSE;
2846 if (!wcsnicmp( buf, passportW, ARRAY_SIZE(passportW) ) &&
2847 (buf[ARRAY_SIZE(passportW)] == ' ' || !buf[ARRAY_SIZE(passportW)])) return TRUE;
2849 return FALSE;
2852 static DWORD handle_passport_redirect( struct request *request )
2854 DWORD ret, flags = WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE;
2855 int i, len = lstrlenW( request->raw_headers );
2856 WCHAR *p = request->raw_headers;
2858 if ((ret = process_header( request, L"Status", L"401", flags, FALSE ))) return ret;
2860 for (i = 0; i < len; i++)
2862 if (i <= len - 3 && p[i] == '3' && p[i + 1] == '0' && p[i + 2] == '2')
2864 p[i] = '4';
2865 p[i + 2] = '1';
2866 break;
2869 return ERROR_SUCCESS;
2872 static void task_receive_response( void *ctx, BOOL abort );
2874 static DWORD queue_receive_response( struct request *request )
2876 struct receive_response *r;
2877 DWORD ret;
2879 if (!(r = malloc( sizeof(*r) ))) return ERROR_OUTOFMEMORY;
2880 if ((ret = queue_task( &request->queue, task_receive_response, &r->task_hdr, &request->hdr )))
2881 free( r );
2882 return ret;
2885 static DWORD receive_response( struct request *request )
2887 BOOL async_mode = request->connect->hdr.flags & WINHTTP_FLAG_ASYNC;
2888 DWORD ret, size, query, status;
2890 TRACE( "request state %d.\n", request->state );
2892 switch (request->state)
2894 case REQUEST_RESPONSE_RECURSIVE_REQUEST:
2895 TRACE( "Sending request.\n" );
2896 if ((ret = send_request( request, NULL, 0, request->optional, request->optional_len, 0, 0, FALSE ))) goto done;
2897 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
2898 break;
2900 case REQUEST_RESPONSE_STATE_SENDING_REQUEST:
2901 if (!async_mode)
2903 ret = ERROR_WINHTTP_INCORRECT_HANDLE_STATE;
2904 goto done;
2906 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
2907 request->state = REQUEST_RESPONSE_STATE_READ_RESPONSE_QUEUED;
2908 return queue_receive_response( request );
2911 case REQUEST_RESPONSE_STATE_REQUEST_SENT:
2912 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
2913 if (async_mode)
2915 request->state = REQUEST_RESPONSE_STATE_READ_RESPONSE_QUEUED_REQUEST_SENT;
2916 return queue_receive_response( request );
2918 /* fallthrough */
2919 case REQUEST_RESPONSE_STATE_READ_RESPONSE_QUEUED_REQUEST_SENT:
2920 netconn_set_timeout( request->netconn, FALSE, request->receive_response_timeout );
2921 request->read_reply_status = read_reply( request );
2922 request->state = REQUEST_RESPONSE_STATE_REPLY_RECEIVED;
2923 break;
2925 case REQUEST_RESPONSE_STATE_REPLY_RECEIVED:
2926 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE, NULL, 0 );
2927 break;
2929 case REQUEST_RESPONSE_STATE_READ_RESPONSE_QUEUED_REPLY_RECEIVED:
2930 request->state = REQUEST_RESPONSE_STATE_REPLY_RECEIVED;
2931 break;
2933 default:
2934 ret = ERROR_WINHTTP_INCORRECT_HANDLE_STATE;
2935 goto done;
2938 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED,
2939 &request->read_reply_len, sizeof(request->read_reply_len) );
2940 if ((ret = request->read_reply_status)) goto done;
2942 size = sizeof(DWORD);
2943 query = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
2944 if ((ret = query_headers( request, query, NULL, &status, &size, NULL ))) goto done;
2946 set_content_length( request, status );
2948 if (!(request->hdr.disable_flags & WINHTTP_DISABLE_COOKIES)) record_cookies( request );
2950 if (status == HTTP_STATUS_REDIRECT && is_passport_request( request ))
2952 ret = handle_passport_redirect( request );
2953 goto done;
2955 if (status == HTTP_STATUS_MOVED || status == HTTP_STATUS_REDIRECT || status == HTTP_STATUS_REDIRECT_KEEP_VERB)
2957 if (request->hdr.disable_flags & WINHTTP_DISABLE_REDIRECTS ||
2958 request->hdr.redirect_policy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) goto done;
2960 if (++request->redirect_count > request->max_redirects)
2962 ret = ERROR_WINHTTP_REDIRECT_FAILED;
2963 goto done;
2966 if ((ret = handle_redirect( request, status ))) goto done;
2968 else if (status == HTTP_STATUS_DENIED || status == HTTP_STATUS_PROXY_AUTH_REQ)
2970 if (request->hdr.disable_flags & WINHTTP_DISABLE_AUTHENTICATION) goto done;
2972 if (handle_authorization( request, status )) goto done;
2974 else goto done;
2976 request->state = REQUEST_RESPONSE_RECURSIVE_REQUEST;
2977 return async_mode ? queue_receive_response( request ) : receive_response( request );
2979 done:
2980 if (!ret)
2982 request->state = REQUEST_RESPONSE_STATE_RESPONSE_RECEIVED;
2983 if (request->netconn) netconn_set_timeout( request->netconn, FALSE, request->receive_timeout );
2985 if (async_mode)
2987 if (!ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, NULL, 0 );
2988 else
2990 WINHTTP_ASYNC_RESULT result;
2991 result.dwResult = API_RECEIVE_RESPONSE;
2992 result.dwError = ret;
2993 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
2995 return ERROR_SUCCESS;
2997 return ret;
3000 static void task_receive_response( void *ctx, BOOL abort )
3002 struct receive_response *r = ctx;
3003 struct request *request = (struct request *)r->task_hdr.obj;
3005 if (abort) return;
3007 TRACE("running %p\n", ctx);
3008 receive_response( request );
3011 /***********************************************************************
3012 * WinHttpReceiveResponse (winhttp.@)
3014 BOOL WINAPI WinHttpReceiveResponse( HINTERNET hrequest, LPVOID reserved )
3016 DWORD ret;
3017 struct request *request;
3019 TRACE("%p, %p\n", hrequest, reserved);
3021 if (!(request = (struct request *)grab_object( hrequest )))
3023 SetLastError( ERROR_INVALID_HANDLE );
3024 return FALSE;
3026 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
3028 release_object( &request->hdr );
3029 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
3030 return FALSE;
3033 ret = receive_response( request );
3035 release_object( &request->hdr );
3036 SetLastError( ret );
3037 return !ret;
3040 static DWORD query_data_ready( struct request *request )
3042 DWORD count;
3044 count = get_available_data( request );
3045 if (!request->read_chunked && request->netconn) count += netconn_query_data_available( request->netconn );
3047 return count;
3050 static BOOL skip_async_queue( struct request *request )
3052 return request->hdr.recursion_count < 3 && (end_of_read_data( request ) || query_data_ready( request ));
3055 static DWORD query_data_available( struct request *request, DWORD *available, BOOL async )
3057 DWORD ret = ERROR_SUCCESS, count = 0;
3059 if (end_of_read_data( request )) goto done;
3061 if (!(count = query_data_ready( request )))
3063 if ((ret = refill_buffer( request, async ))) goto done;
3064 count = query_data_ready( request );
3067 done:
3068 TRACE( "%lu bytes available\n", count );
3069 if (async)
3071 if (!ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, &count, sizeof(count) );
3072 else
3074 WINHTTP_ASYNC_RESULT result;
3075 result.dwResult = API_QUERY_DATA_AVAILABLE;
3076 result.dwError = ret;
3077 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
3081 if (!ret && available) *available = count;
3082 return ret;
3085 static void task_query_data_available( void *ctx, BOOL abort )
3087 struct query_data *q = ctx;
3088 struct request *request = (struct request *)q->task_hdr.obj;
3090 if (abort) return;
3092 TRACE("running %p\n", ctx);
3093 query_data_available( request, q->available, TRUE );
3096 /***********************************************************************
3097 * WinHttpQueryDataAvailable (winhttp.@)
3099 BOOL WINAPI WinHttpQueryDataAvailable( HINTERNET hrequest, LPDWORD available )
3101 DWORD ret;
3102 struct request *request;
3103 BOOL async;
3105 TRACE("%p, %p\n", hrequest, available);
3107 if (!(request = (struct request *)grab_object( hrequest )))
3109 SetLastError( ERROR_INVALID_HANDLE );
3110 return FALSE;
3112 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
3114 release_object( &request->hdr );
3115 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
3116 return FALSE;
3119 if ((async = request->connect->hdr.flags & WINHTTP_FLAG_ASYNC) && !skip_async_queue( request ))
3121 struct query_data *q;
3123 if (!(q = malloc( sizeof(*q) )))
3125 release_object( &request->hdr );
3126 SetLastError( ERROR_OUTOFMEMORY );
3127 return FALSE;
3130 q->available = available;
3132 if ((ret = queue_task( &request->queue, task_query_data_available, &q->task_hdr, &request->hdr )))
3133 free( q );
3134 else
3135 ret = ERROR_IO_PENDING;
3137 else ret = query_data_available( request, available, async );
3139 release_object( &request->hdr );
3140 SetLastError( ret );
3141 return !ret || ret == ERROR_IO_PENDING;
3144 static void task_read_data( void *ctx, BOOL abort )
3146 struct read_data *r = ctx;
3147 struct request *request = (struct request *)r->task_hdr.obj;
3149 if (abort) return;
3151 TRACE("running %p\n", ctx);
3152 read_data( request, r->buffer, r->to_read, r->read, TRUE );
3155 /***********************************************************************
3156 * WinHttpReadData (winhttp.@)
3158 BOOL WINAPI WinHttpReadData( HINTERNET hrequest, void *buffer, DWORD to_read, DWORD *read )
3160 DWORD ret;
3161 struct request *request;
3162 BOOL async;
3164 TRACE( "%p, %p, %lu, %p\n", hrequest, buffer, to_read, read );
3166 if (!(request = (struct request *)grab_object( hrequest )))
3168 SetLastError( ERROR_INVALID_HANDLE );
3169 return FALSE;
3171 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
3173 release_object( &request->hdr );
3174 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
3175 return FALSE;
3178 if ((async = request->connect->hdr.flags & WINHTTP_FLAG_ASYNC) && !skip_async_queue( request ))
3180 struct read_data *r;
3182 if (!(r = malloc( sizeof(*r) )))
3184 release_object( &request->hdr );
3185 SetLastError( ERROR_OUTOFMEMORY );
3186 return FALSE;
3188 r->buffer = buffer;
3189 r->to_read = to_read;
3190 r->read = read;
3192 if ((ret = queue_task( &request->queue, task_read_data, &r->task_hdr, &request->hdr )))
3193 free( r );
3194 else
3195 ret = ERROR_IO_PENDING;
3197 else ret = read_data( request, buffer, to_read, read, async );
3199 release_object( &request->hdr );
3200 SetLastError( ret );
3201 return !ret || ret == ERROR_IO_PENDING;
3204 static DWORD write_data( struct request *request, const void *buffer, DWORD to_write, DWORD *written, BOOL async )
3206 DWORD ret;
3207 int num_bytes;
3209 ret = netconn_send( request->netconn, buffer, to_write, &num_bytes, NULL );
3211 if (async)
3213 if (!ret) send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &num_bytes, sizeof(num_bytes) );
3214 else
3216 WINHTTP_ASYNC_RESULT result;
3217 result.dwResult = API_WRITE_DATA;
3218 result.dwError = ret;
3219 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
3222 if (!ret && written) *written = num_bytes;
3223 return ret;
3226 static void task_write_data( void *ctx, BOOL abort )
3228 struct write_data *w = ctx;
3229 struct request *request = (struct request *)w->task_hdr.obj;
3231 if (abort) return;
3233 TRACE("running %p\n", ctx);
3234 write_data( request, w->buffer, w->to_write, w->written, TRUE );
3237 /***********************************************************************
3238 * WinHttpWriteData (winhttp.@)
3240 BOOL WINAPI WinHttpWriteData( HINTERNET hrequest, const void *buffer, DWORD to_write, DWORD *written )
3242 DWORD ret;
3243 struct request *request;
3245 TRACE( "%p, %p, %lu, %p\n", hrequest, buffer, to_write, written );
3247 if (!(request = (struct request *)grab_object( hrequest )))
3249 SetLastError( ERROR_INVALID_HANDLE );
3250 return FALSE;
3252 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
3254 release_object( &request->hdr );
3255 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
3256 return FALSE;
3259 if (request->connect->hdr.flags & WINHTTP_FLAG_ASYNC)
3261 struct write_data *w;
3263 if (!(w = malloc( sizeof(*w) )))
3265 release_object( &request->hdr );
3266 SetLastError( ERROR_OUTOFMEMORY );
3267 return FALSE;
3269 w->buffer = buffer;
3270 w->to_write = to_write;
3271 w->written = written;
3273 if ((ret = queue_task( &request->queue, task_write_data, &w->task_hdr, &request->hdr )))
3274 free( w );
3276 else ret = write_data( request, buffer, to_write, written, FALSE );
3278 release_object( &request->hdr );
3279 SetLastError( ret );
3280 return !ret;
3283 static void socket_handle_closing( struct object_header *hdr )
3285 struct socket *socket = (struct socket *)hdr;
3286 BOOL pending_tasks;
3288 pending_tasks = cancel_queue( &socket->send_q );
3289 pending_tasks = cancel_queue( &socket->recv_q ) || pending_tasks;
3291 if (pending_tasks)
3292 netconn_cancel_io( socket->netconn );
3295 static BOOL socket_query_option( struct object_header *hdr, DWORD option, void *buffer, DWORD *buflen )
3297 switch (option)
3299 case WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL:
3300 SetLastError( ERROR_INVALID_PARAMETER );
3301 return FALSE;
3304 FIXME( "unimplemented option %lu\n", option );
3305 SetLastError( ERROR_WINHTTP_INVALID_OPTION );
3306 return FALSE;
3309 static void socket_destroy( struct object_header *hdr )
3311 struct socket *socket = (struct socket *)hdr;
3313 TRACE("%p\n", socket);
3315 stop_queue( &socket->send_q );
3316 stop_queue( &socket->recv_q );
3318 netconn_release( socket->netconn );
3319 free( socket->read_buffer );
3320 free( socket->send_frame_buffer );
3321 free( socket );
3324 static BOOL socket_set_option( struct object_header *hdr, DWORD option, void *buffer, DWORD buflen )
3326 struct socket *socket = (struct socket *)hdr;
3328 switch (option)
3330 case WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL:
3332 DWORD interval;
3334 if (buflen != sizeof(DWORD) || (interval = *(DWORD *)buffer) < 15000)
3336 WARN( "Invalid parameters for WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL.\n" );
3337 SetLastError( ERROR_INVALID_PARAMETER );
3338 return FALSE;
3340 socket->keepalive_interval = interval;
3341 netconn_set_timeout( socket->netconn, FALSE, socket->keepalive_interval );
3342 SetLastError( ERROR_SUCCESS );
3343 TRACE( "WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL %lu.\n", interval);
3344 return TRUE;
3348 FIXME( "unimplemented option %lu\n", option );
3349 SetLastError( ERROR_WINHTTP_INVALID_OPTION );
3350 return FALSE;
3353 static const struct object_vtbl socket_vtbl =
3355 socket_handle_closing,
3356 socket_destroy,
3357 socket_query_option,
3358 socket_set_option,
3361 HINTERNET WINAPI WinHttpWebSocketCompleteUpgrade( HINTERNET hrequest, DWORD_PTR context )
3363 struct socket *socket;
3364 struct request *request;
3365 HINTERNET hsocket = NULL;
3367 TRACE( "%p, %Ix\n", hrequest, context );
3369 if (!(request = (struct request *)grab_object( hrequest )))
3371 SetLastError( ERROR_INVALID_HANDLE );
3372 return NULL;
3374 if (request->hdr.type != WINHTTP_HANDLE_TYPE_REQUEST)
3376 release_object( &request->hdr );
3377 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE );
3378 return NULL;
3380 if (!(socket = calloc( 1, sizeof(*socket) )))
3382 release_object( &request->hdr );
3383 return NULL;
3385 socket->hdr.type = WINHTTP_HANDLE_TYPE_SOCKET;
3386 socket->hdr.vtbl = &socket_vtbl;
3387 socket->hdr.refs = 1;
3388 socket->hdr.callback = request->hdr.callback;
3389 socket->hdr.notify_mask = request->hdr.notify_mask;
3390 socket->hdr.context = context;
3391 socket->hdr.flags = request->connect->hdr.flags & WINHTTP_FLAG_ASYNC;
3392 socket->keepalive_interval = 30000;
3393 socket->send_buffer_size = request->websocket_send_buffer_size;
3394 if (request->read_size)
3396 if (!(socket->read_buffer = malloc( request->read_size )))
3398 ERR( "No memory.\n" );
3399 free( socket );
3400 release_object( &request->hdr );
3401 return NULL;
3403 socket->bytes_in_read_buffer = request->read_size;
3404 memcpy( socket->read_buffer, request->read_buf + request->read_pos, request->read_size );
3405 request->read_pos = request->read_size = 0;
3407 InitializeSRWLock( &socket->send_lock );
3408 init_queue( &socket->send_q );
3409 init_queue( &socket->recv_q );
3410 netconn_addref( request->netconn );
3411 socket->netconn = request->netconn;
3413 netconn_set_timeout( socket->netconn, FALSE, socket->keepalive_interval );
3415 if ((hsocket = alloc_handle( &socket->hdr )))
3417 send_callback( &request->hdr, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED, &hsocket, sizeof(hsocket) );
3420 release_object( &socket->hdr );
3421 release_object( &request->hdr );
3422 TRACE("returning %p\n", hsocket);
3423 if (hsocket) SetLastError( ERROR_SUCCESS );
3424 return hsocket;
3427 static DWORD send_bytes( struct socket *socket, char *bytes, int len, int *sent, WSAOVERLAPPED *ovr )
3429 int count;
3430 DWORD err;
3431 err = netconn_send( socket->netconn, bytes, len, &count, ovr );
3432 if (sent) *sent = count;
3433 if (err) return err;
3434 return (count == len || (ovr && count)) ? ERROR_SUCCESS : ERROR_INTERNAL_ERROR;
3437 #define FIN_BIT (1 << 7)
3438 #define MASK_BIT (1 << 7)
3439 #define RESERVED_BIT (7 << 4)
3440 #define CONTROL_BIT (1 << 3)
3442 static DWORD send_frame( struct socket *socket, enum socket_opcode opcode, USHORT status, const char *buf,
3443 DWORD buflen, BOOL final, WSAOVERLAPPED *ovr )
3445 DWORD i, offset = 2, len = buflen, buffer_size, ret = 0;
3446 int sent_size;
3447 char hdr[14];
3448 char *ptr;
3450 TRACE( "sending %02x frame, len %lu\n", opcode, len );
3452 if (opcode == SOCKET_OPCODE_CLOSE) len += sizeof(status);
3454 hdr[0] = final ? (char)FIN_BIT : 0;
3455 hdr[0] |= opcode;
3456 hdr[1] = (char)MASK_BIT;
3457 if (len < 126) hdr[1] |= len;
3458 else if (len < 65536)
3460 hdr[1] |= 126;
3461 hdr[2] = len >> 8;
3462 hdr[3] = len & 0xff;
3463 offset += 2;
3465 else
3467 hdr[1] |= 127;
3468 hdr[2] = hdr[3] = hdr[4] = hdr[5] = 0;
3469 hdr[6] = len >> 24;
3470 hdr[7] = (len >> 16) & 0xff;
3471 hdr[8] = (len >> 8) & 0xff;
3472 hdr[9] = len & 0xff;
3473 offset += 8;
3476 buffer_size = len + offset + 4;
3477 assert( buffer_size - len < socket->send_buffer_size );
3478 if (buffer_size > socket->send_frame_buffer_size && socket->send_frame_buffer_size < socket->send_buffer_size)
3480 DWORD new_size;
3481 void *new;
3483 new_size = min( buffer_size, socket->send_buffer_size );
3484 if (!(new = realloc( socket->send_frame_buffer, new_size )))
3486 ERR( "out of memory, buffer_size %lu\n", buffer_size);
3487 return ERROR_OUTOFMEMORY;
3489 socket->send_frame_buffer = new;
3490 socket->send_frame_buffer_size = new_size;
3492 ptr = socket->send_frame_buffer;
3494 memcpy(ptr, hdr, offset);
3495 ptr += offset;
3497 RtlGenRandom( socket->mask, 4 );
3498 memcpy( ptr, socket->mask, 4 );
3499 ptr += 4;
3500 socket->mask_index = 0;
3502 if (opcode == SOCKET_OPCODE_CLOSE) /* prepend status code */
3504 *ptr++ = (status >> 8) ^ socket->mask[socket->mask_index++ % 4];
3505 *ptr++ = (status & 0xff) ^ socket->mask[socket->mask_index++ % 4];
3508 offset = ptr - socket->send_frame_buffer;
3509 socket->send_remaining_size = offset + buflen;
3510 socket->client_buffer_offset = 0;
3511 while (socket->send_remaining_size)
3513 len = min( buflen, socket->send_buffer_size - offset );
3514 for (i = 0; i < len; ++i)
3516 socket->send_frame_buffer[offset++] = buf[socket->client_buffer_offset++]
3517 ^ socket->mask[socket->mask_index++ % 4];
3520 sent_size = 0;
3521 ret = send_bytes( socket, socket->send_frame_buffer, offset, &sent_size, ovr );
3522 socket->send_remaining_size -= sent_size;
3523 if (ret)
3525 if (ovr && ret == WSA_IO_PENDING)
3527 memmove( socket->send_frame_buffer, socket->send_frame_buffer + sent_size, offset - sent_size );
3528 socket->bytes_in_send_frame_buffer = offset - sent_size;
3530 return ret;
3532 assert( sent_size == offset );
3533 offset = 0;
3534 buflen -= len;
3536 return ERROR_SUCCESS;
3539 static DWORD complete_send_frame( struct socket *socket, WSAOVERLAPPED *ovr, const char *buf )
3541 DWORD ret, len, i;
3543 if (!netconn_wait_overlapped_result( socket->netconn, ovr, &len ))
3544 return WSAGetLastError();
3546 if (socket->bytes_in_send_frame_buffer)
3548 ret = send_bytes( socket, socket->send_frame_buffer, socket->bytes_in_send_frame_buffer, NULL, NULL );
3549 if (ret) return ret;
3552 assert( socket->bytes_in_send_frame_buffer <= socket->send_remaining_size );
3553 socket->send_remaining_size -= socket->bytes_in_send_frame_buffer;
3555 while (socket->send_remaining_size)
3557 len = min( socket->send_remaining_size, socket->send_buffer_size );
3558 for (i = 0; i < len; ++i)
3560 socket->send_frame_buffer[i] = buf[socket->client_buffer_offset++]
3561 ^ socket->mask[socket->mask_index++ % 4];
3563 ret = send_bytes( socket, socket->send_frame_buffer, len, NULL, NULL );
3564 if (ret) return ret;
3565 socket->send_remaining_size -= len;
3567 return ERROR_SUCCESS;
3570 static void send_io_complete( struct object_header *hdr )
3572 LONG count = InterlockedDecrement( &hdr->pending_sends );
3573 assert( count >= 0 );
3576 /* returns FALSE if sending callback should be omitted. */
3577 static void receive_io_complete( struct socket *socket )
3579 LONG count = InterlockedDecrement( &socket->hdr.pending_receives );
3580 assert( count >= 0 );
3583 static BOOL socket_can_send( struct socket *socket )
3585 return socket->state == SOCKET_STATE_OPEN && !socket->close_frame_received;
3588 static BOOL socket_can_receive( struct socket *socket )
3590 return socket->state <= SOCKET_STATE_SHUTDOWN && !socket->close_frame_received;
3593 static BOOL validate_buffer_type( WINHTTP_WEB_SOCKET_BUFFER_TYPE type, enum fragment_type current_fragment )
3595 switch (current_fragment)
3597 case SOCKET_FRAGMENT_NONE:
3598 return type == WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
3599 || type == WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE
3600 || type == WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
3601 || type == WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE;
3602 case SOCKET_FRAGMENT_BINARY:
3603 return type == WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
3604 || type == WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE;
3605 case SOCKET_FRAGMENT_UTF8:
3606 return type == WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
3607 || type == WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE;
3609 assert( 0 );
3610 return FALSE;
3613 static enum socket_opcode map_buffer_type( struct socket *socket, WINHTTP_WEB_SOCKET_BUFFER_TYPE type )
3615 switch (type)
3617 case WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE:
3618 if (socket->sending_fragment_type)
3620 socket->sending_fragment_type = SOCKET_FRAGMENT_NONE;
3621 return SOCKET_OPCODE_CONTINUE;
3623 return SOCKET_OPCODE_TEXT;
3625 case WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE:
3626 if (socket->sending_fragment_type)
3628 socket->sending_fragment_type = SOCKET_FRAGMENT_NONE;
3629 return SOCKET_OPCODE_CONTINUE;
3631 return SOCKET_OPCODE_BINARY;
3633 case WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE:
3634 if (!socket->sending_fragment_type)
3636 socket->sending_fragment_type = SOCKET_FRAGMENT_UTF8;
3637 return SOCKET_OPCODE_TEXT;
3639 return SOCKET_OPCODE_CONTINUE;
3641 case WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE:
3642 if (!socket->sending_fragment_type)
3644 socket->sending_fragment_type = SOCKET_FRAGMENT_BINARY;
3645 return SOCKET_OPCODE_BINARY;
3647 return SOCKET_OPCODE_CONTINUE;
3649 case WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE:
3650 return SOCKET_OPCODE_CLOSE;
3652 default:
3653 FIXME("buffer type %u not supported\n", type);
3654 return SOCKET_OPCODE_INVALID;
3658 static void socket_send_complete( struct socket *socket, DWORD ret, WINHTTP_WEB_SOCKET_BUFFER_TYPE type, DWORD len )
3660 if (!ret)
3662 WINHTTP_WEB_SOCKET_STATUS status;
3663 status.dwBytesTransferred = len;
3664 status.eBufferType = type;
3665 send_callback( &socket->hdr, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, &status, sizeof(status) );
3667 else
3669 WINHTTP_WEB_SOCKET_ASYNC_RESULT result;
3670 result.AsyncResult.dwResult = API_WRITE_DATA;
3671 result.AsyncResult.dwError = ret;
3672 result.Operation = WINHTTP_WEB_SOCKET_SEND_OPERATION;
3673 send_callback( &socket->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
3677 static DWORD socket_send( struct socket *socket, WINHTTP_WEB_SOCKET_BUFFER_TYPE type, const void *buf, DWORD len,
3678 WSAOVERLAPPED *ovr )
3680 enum socket_opcode opcode = map_buffer_type( socket, type );
3681 BOOL final = (type != WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE &&
3682 type != WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE);
3684 return send_frame( socket, opcode, 0, buf, len, final, ovr );
3687 static void task_socket_send( void *ctx, BOOL abort )
3689 struct socket_send *s = ctx;
3690 struct socket *socket = (struct socket *)s->task_hdr.obj;
3691 DWORD ret;
3693 if (abort) return;
3695 TRACE("running %p\n", ctx);
3697 if (s->complete_async) ret = complete_send_frame( socket, &s->ovr, s->buf );
3698 else ret = socket_send( socket, s->type, s->buf, s->len, NULL );
3700 send_io_complete( &socket->hdr );
3701 InterlockedExchange( &socket->pending_noncontrol_send, 0 );
3702 socket_send_complete( socket, ret, s->type, s->len );
3705 DWORD WINAPI WinHttpWebSocketSend( HINTERNET hsocket, WINHTTP_WEB_SOCKET_BUFFER_TYPE type, void *buf, DWORD len )
3707 struct socket *socket;
3708 DWORD ret = 0;
3710 TRACE( "%p, %u, %p, %lu\n", hsocket, type, buf, len );
3712 if (len && !buf) return ERROR_INVALID_PARAMETER;
3714 if (!(socket = (struct socket *)grab_object( hsocket ))) return ERROR_INVALID_HANDLE;
3715 if (socket->hdr.type != WINHTTP_HANDLE_TYPE_SOCKET)
3717 release_object( &socket->hdr );
3718 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE;
3720 if (!socket_can_send( socket ))
3722 release_object( &socket->hdr );
3723 return ERROR_INVALID_OPERATION;
3726 if (socket->hdr.flags & WINHTTP_FLAG_ASYNC)
3728 BOOL async_send, complete_async = FALSE;
3729 struct socket_send *s;
3731 if (InterlockedCompareExchange( &socket->pending_noncontrol_send, 1, 0 ))
3733 WARN( "Previous send is still queued.\n" );
3734 release_object( &socket->hdr );
3735 return ERROR_INVALID_OPERATION;
3737 if (!validate_buffer_type( type, socket->sending_fragment_type ))
3739 WARN( "Invalid buffer type %u, sending_fragment_type %u.\n", type, socket->sending_fragment_type );
3740 InterlockedExchange( &socket->pending_noncontrol_send, 0 );
3741 release_object( &socket->hdr );
3742 return ERROR_INVALID_PARAMETER;
3745 if (!(s = malloc( sizeof(*s) )))
3747 InterlockedExchange( &socket->pending_noncontrol_send, 0 );
3748 release_object( &socket->hdr );
3749 return ERROR_OUTOFMEMORY;
3752 AcquireSRWLockExclusive( &socket->send_lock );
3753 async_send = InterlockedIncrement( &socket->hdr.pending_sends ) > 1 || socket->hdr.recursion_count >= 3;
3754 if (!async_send)
3756 memset( &s->ovr, 0, sizeof(s->ovr) );
3757 if ((ret = socket_send( socket, type, buf, len, &s->ovr )) == WSA_IO_PENDING)
3759 async_send = TRUE;
3760 complete_async = TRUE;
3764 if (async_send)
3766 s->complete_async = complete_async;
3767 TRACE("queueing, complete_async %#x.\n", complete_async);
3768 s->type = type;
3769 s->buf = buf;
3770 s->len = len;
3772 if ((ret = queue_task( &socket->send_q, task_socket_send, &s->task_hdr, &socket->hdr )))
3773 free( s );
3775 if (!async_send || ret)
3777 InterlockedDecrement( &socket->hdr.pending_sends );
3778 InterlockedExchange( &socket->pending_noncontrol_send, 0 );
3780 ReleaseSRWLockExclusive( &socket->send_lock );
3781 if (!async_send)
3783 TRACE("sent sync.\n");
3784 free( s );
3785 socket_send_complete( socket, ret, type, len );
3786 ret = ERROR_SUCCESS;
3789 else
3791 if (validate_buffer_type( type, socket->sending_fragment_type ))
3793 ret = socket_send( socket, type, buf, len, NULL );
3795 else
3797 WARN( "Invalid buffer type %u, sending_fragment_type %u.\n", type, socket->sending_fragment_type );
3798 ret = ERROR_INVALID_PARAMETER;
3802 release_object( &socket->hdr );
3803 return ret;
3806 static DWORD receive_bytes( struct socket *socket, char *buf, DWORD len, DWORD *ret_len, BOOL read_full_buffer )
3808 DWORD err, size = 0, needed = len;
3809 char *ptr = buf;
3810 int received;
3812 if (socket->bytes_in_read_buffer)
3814 size = min( needed, socket->bytes_in_read_buffer );
3815 memcpy( ptr, socket->read_buffer, size );
3816 memmove( socket->read_buffer, socket->read_buffer + size, socket->bytes_in_read_buffer - size );
3817 socket->bytes_in_read_buffer -= size;
3818 needed -= size;
3819 ptr += size;
3821 while (size != len)
3823 if ((err = netconn_recv( socket->netconn, ptr, needed, 0, &received ))) return err;
3824 if (!received) break;
3825 size += received;
3826 if (!read_full_buffer) break;
3827 needed -= received;
3828 ptr += received;
3830 *ret_len = size;
3831 if (size != len && (read_full_buffer || !size)) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
3832 return ERROR_SUCCESS;
3835 static BOOL is_supported_opcode( enum socket_opcode opcode )
3837 switch (opcode)
3839 case SOCKET_OPCODE_CONTINUE:
3840 case SOCKET_OPCODE_TEXT:
3841 case SOCKET_OPCODE_BINARY:
3842 case SOCKET_OPCODE_CLOSE:
3843 case SOCKET_OPCODE_PING:
3844 case SOCKET_OPCODE_PONG:
3845 return TRUE;
3846 default:
3847 FIXME( "opcode %02x not handled\n", opcode );
3848 return FALSE;
3852 static DWORD receive_frame( struct socket *socket, DWORD *ret_len, enum socket_opcode *opcode, BOOL *final )
3854 DWORD ret, len, count;
3855 char hdr[2];
3857 if ((ret = receive_bytes( socket, hdr, sizeof(hdr), &count, TRUE ))) return ret;
3858 if ((hdr[0] & RESERVED_BIT) || (hdr[1] & MASK_BIT) || !is_supported_opcode( hdr[0] & 0xf ))
3860 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
3862 *opcode = hdr[0] & 0xf;
3863 *final = hdr[0] & FIN_BIT;
3864 TRACE("received %02x frame, final %#x\n", *opcode, *final);
3866 len = hdr[1] & ~MASK_BIT;
3867 if (len == 126)
3869 USHORT len16;
3870 if ((ret = receive_bytes( socket, (char *)&len16, sizeof(len16), &count, TRUE ))) return ret;
3871 len = RtlUshortByteSwap( len16 );
3873 else if (len == 127)
3875 ULONGLONG len64;
3876 if ((ret = receive_bytes( socket, (char *)&len64, sizeof(len64), &count, TRUE ))) return ret;
3877 if ((len64 = RtlUlonglongByteSwap( len64 )) > ~0u) return ERROR_NOT_SUPPORTED;
3878 len = len64;
3881 *ret_len = len;
3882 return ERROR_SUCCESS;
3885 static void task_socket_send_pong( void *ctx, BOOL abort )
3887 struct socket_send *s = ctx;
3888 struct socket *socket = (struct socket *)s->task_hdr.obj;
3890 if (abort) return;
3892 TRACE("running %p\n", ctx);
3894 if (s->complete_async) complete_send_frame( socket, &s->ovr, NULL );
3895 else send_frame( socket, SOCKET_OPCODE_PONG, 0, NULL, 0, TRUE, NULL );
3897 send_io_complete( &socket->hdr );
3900 static DWORD socket_send_pong( struct socket *socket )
3902 if (socket->hdr.flags & WINHTTP_FLAG_ASYNC)
3904 BOOL async_send, complete_async = FALSE;
3905 struct socket_send *s;
3906 DWORD ret = 0;
3908 if (!(s = malloc( sizeof(*s) ))) return ERROR_OUTOFMEMORY;
3910 AcquireSRWLockExclusive( &socket->send_lock );
3911 async_send = InterlockedIncrement( &socket->hdr.pending_sends ) > 1;
3912 if (!async_send)
3914 memset( &s->ovr, 0, sizeof(s->ovr) );
3915 if ((ret = send_frame( socket, SOCKET_OPCODE_PONG, 0, NULL, 0, TRUE, &s->ovr )) == WSA_IO_PENDING)
3917 async_send = TRUE;
3918 complete_async = TRUE;
3922 if (async_send)
3924 s->complete_async = complete_async;
3925 if ((ret = queue_task( &socket->send_q, task_socket_send_pong, &s->task_hdr, &socket->hdr )))
3927 InterlockedDecrement( &socket->hdr.pending_sends );
3928 free( s );
3931 else
3933 InterlockedDecrement( &socket->hdr.pending_sends );
3934 free( s );
3936 ReleaseSRWLockExclusive( &socket->send_lock );
3937 return ret;
3939 return send_frame( socket, SOCKET_OPCODE_PONG, 0, NULL, 0, TRUE, NULL );
3942 static DWORD socket_drain( struct socket *socket )
3944 DWORD ret, count;
3946 while (socket->read_size)
3948 char buf[1024];
3949 if ((ret = receive_bytes( socket, buf, min(socket->read_size, sizeof(buf)), &count, TRUE ))) return ret;
3950 socket->read_size -= count;
3952 return ERROR_SUCCESS;
3955 static DWORD receive_close_status( struct socket *socket, DWORD len )
3957 DWORD reason_len, ret;
3959 socket->close_frame_received = TRUE;
3960 if ((len && (len < sizeof(socket->status) || len > sizeof(socket->status) + sizeof(socket->reason))))
3961 return (socket->close_frame_receive_err = ERROR_WINHTTP_INVALID_SERVER_RESPONSE);
3963 if (!len) return (socket->close_frame_receive_err = ERROR_SUCCESS);
3965 reason_len = len - sizeof(socket->status);
3966 if ((ret = receive_bytes( socket, (char *)&socket->status, sizeof(socket->status), &len, TRUE )))
3967 return (socket->close_frame_receive_err = ret);
3968 socket->status = RtlUshortByteSwap( socket->status );
3969 return (socket->close_frame_receive_err
3970 = receive_bytes( socket, socket->reason, reason_len, &socket->reason_len, TRUE ));
3973 static DWORD handle_control_frame( struct socket *socket )
3975 DWORD ret;
3977 TRACE( "opcode %u.\n", socket->opcode );
3979 switch (socket->opcode)
3981 case SOCKET_OPCODE_PING:
3982 return socket_send_pong( socket );
3984 case SOCKET_OPCODE_PONG:
3985 return socket_drain( socket );
3987 case SOCKET_OPCODE_CLOSE:
3988 if (socket->state < SOCKET_STATE_SHUTDOWN)
3989 WARN( "SOCKET_OPCODE_CLOSE received, socket->state %u.\n", socket->state );
3990 if (socket->close_frame_received)
3992 FIXME( "Close frame already received.\n" );
3993 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
3996 ret = receive_close_status( socket, socket->read_size );
3997 socket->read_size = 0;
3998 return ret;
4000 default:
4001 ERR("unhandled control opcode %02x\n", socket->opcode);
4002 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
4005 return ERROR_SUCCESS;
4008 static WINHTTP_WEB_SOCKET_BUFFER_TYPE map_opcode( struct socket *socket, enum socket_opcode opcode, BOOL fragment )
4010 enum fragment_type frag_type = socket->receiving_fragment_type;
4012 switch (opcode)
4014 case SOCKET_OPCODE_TEXT:
4015 if (frag_type && frag_type != SOCKET_FRAGMENT_UTF8)
4016 FIXME( "Received SOCKET_OPCODE_TEXT with prev fragment %u.\n", frag_type );
4017 if (fragment)
4019 socket->receiving_fragment_type = SOCKET_FRAGMENT_UTF8;
4020 return WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE;
4022 socket->receiving_fragment_type = SOCKET_FRAGMENT_NONE;
4023 return WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE;
4025 case SOCKET_OPCODE_BINARY:
4026 if (frag_type && frag_type != SOCKET_FRAGMENT_BINARY)
4027 FIXME( "Received SOCKET_OPCODE_BINARY with prev fragment %u.\n", frag_type );
4028 if (fragment)
4030 socket->receiving_fragment_type = SOCKET_FRAGMENT_BINARY;
4031 return WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE;
4033 socket->receiving_fragment_type = SOCKET_FRAGMENT_NONE;
4034 return WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE;
4036 case SOCKET_OPCODE_CONTINUE:
4037 if (!frag_type)
4039 FIXME( "Received SOCKET_OPCODE_CONTINUE without starting fragment.\n" );
4040 return ~0u;
4042 if (fragment)
4044 return frag_type == SOCKET_FRAGMENT_BINARY ? WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE
4045 : WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE;
4047 socket->receiving_fragment_type = SOCKET_FRAGMENT_NONE;
4048 return frag_type == SOCKET_FRAGMENT_BINARY ? WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
4049 : WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE;
4051 case SOCKET_OPCODE_CLOSE:
4052 return WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE;
4054 default:
4055 FIXME("opcode %02x not handled\n", opcode);
4056 return ~0u;
4060 static DWORD socket_receive( struct socket *socket, void *buf, DWORD len, DWORD *ret_len,
4061 WINHTTP_WEB_SOCKET_BUFFER_TYPE *ret_type )
4063 BOOL final = socket->last_receive_final;
4064 DWORD count, ret = ERROR_SUCCESS;
4066 if (!socket->read_size)
4068 for (;;)
4070 if (!(ret = receive_frame( socket, &socket->read_size, &socket->opcode, &final )))
4072 if (!(socket->opcode & CONTROL_BIT) || (ret = handle_control_frame( socket ))
4073 || socket->opcode == SOCKET_OPCODE_CLOSE) break;
4075 else if (ret == WSAETIMEDOUT) ret = socket_send_pong( socket );
4076 if (ret) break;
4079 if (!ret)
4081 socket->last_receive_final = final;
4082 ret = receive_bytes( socket, buf, min(len, socket->read_size), &count, FALSE );
4084 if (!ret)
4086 if (count < socket->read_size)
4087 WARN("Short read.\n");
4089 socket->read_size -= count;
4090 *ret_len = count;
4091 *ret_type = map_opcode( socket, socket->opcode, !final || socket->read_size != 0 );
4092 TRACE( "len %lu, *ret_len %lu, *ret_type %u.\n", len, *ret_len, *ret_type );
4093 if (*ret_type == ~0u)
4095 FIXME( "Unexpected opcode %u.\n", socket->opcode );
4096 socket->read_size = 0;
4097 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE;
4100 return ret;
4103 static void socket_receive_complete( struct socket *socket, DWORD ret, WINHTTP_WEB_SOCKET_BUFFER_TYPE type, DWORD len )
4105 if (!ret)
4107 WINHTTP_WEB_SOCKET_STATUS status;
4108 status.dwBytesTransferred = len;
4109 status.eBufferType = type;
4110 send_callback( &socket->hdr, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, &status, sizeof(status) );
4112 else
4114 WINHTTP_WEB_SOCKET_ASYNC_RESULT result;
4115 result.AsyncResult.dwResult = 0;
4116 result.AsyncResult.dwError = ret;
4117 result.Operation = WINHTTP_WEB_SOCKET_RECEIVE_OPERATION;
4118 send_callback( &socket->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
4122 static void task_socket_receive( void *ctx, BOOL abort )
4124 struct socket_receive *r = ctx;
4125 struct socket *socket = (struct socket *)r->task_hdr.obj;
4126 DWORD ret, count;
4127 WINHTTP_WEB_SOCKET_BUFFER_TYPE type;
4129 if (abort)
4131 socket_receive_complete( socket, ERROR_WINHTTP_OPERATION_CANCELLED, 0, 0 );
4132 return;
4135 TRACE("running %p\n", ctx);
4136 ret = socket_receive( socket, r->buf, r->len, &count, &type );
4137 receive_io_complete( socket );
4138 if (task_needs_completion( &r->task_hdr ))
4139 socket_receive_complete( socket, ret, type, count );
4142 DWORD WINAPI WinHttpWebSocketReceive( HINTERNET hsocket, void *buf, DWORD len, DWORD *ret_len,
4143 WINHTTP_WEB_SOCKET_BUFFER_TYPE *ret_type )
4145 struct socket *socket;
4146 DWORD ret;
4148 TRACE( "%p, %p, %lu, %p, %p\n", hsocket, buf, len, ret_len, ret_type );
4150 if (!buf || !len) return ERROR_INVALID_PARAMETER;
4152 if (!(socket = (struct socket *)grab_object( hsocket ))) return ERROR_INVALID_HANDLE;
4153 if (socket->hdr.type != WINHTTP_HANDLE_TYPE_SOCKET)
4155 release_object( &socket->hdr );
4156 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE;
4158 if (!socket_can_receive( socket ))
4160 release_object( &socket->hdr );
4161 return ERROR_INVALID_OPERATION;
4164 if (socket->hdr.flags & WINHTTP_FLAG_ASYNC)
4166 struct socket_receive *r;
4168 if (InterlockedIncrement( &socket->hdr.pending_receives ) > 1)
4170 InterlockedDecrement( &socket->hdr.pending_receives );
4171 WARN( "Attempt to queue receive while another is pending.\n" );
4172 release_object( &socket->hdr );
4173 return ERROR_INVALID_OPERATION;
4176 if (!(r = malloc( sizeof(*r) )))
4178 InterlockedDecrement( &socket->hdr.pending_receives );
4179 release_object( &socket->hdr );
4180 return ERROR_OUTOFMEMORY;
4182 r->buf = buf;
4183 r->len = len;
4185 if ((ret = queue_task( &socket->recv_q, task_socket_receive, &r->task_hdr, &socket->hdr )))
4187 InterlockedDecrement( &socket->hdr.pending_receives );
4188 free( r );
4191 else ret = socket_receive( socket, buf, len, ret_len, ret_type );
4193 release_object( &socket->hdr );
4194 return ret;
4197 static void socket_shutdown_complete( struct socket *socket, DWORD ret )
4199 if (!ret) send_callback( &socket->hdr, WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE, NULL, 0 );
4200 else
4202 WINHTTP_WEB_SOCKET_ASYNC_RESULT result;
4203 result.AsyncResult.dwResult = API_WRITE_DATA;
4204 result.AsyncResult.dwError = ret;
4205 result.Operation = WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION;
4206 send_callback( &socket->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
4210 static void task_socket_shutdown( void *ctx, BOOL abort )
4212 struct socket_shutdown *s = ctx;
4213 struct socket *socket = (struct socket *)s->task_hdr.obj;
4214 DWORD ret;
4216 if (abort) return;
4218 TRACE("running %p\n", ctx);
4220 if (s->complete_async) ret = complete_send_frame( socket, &s->ovr, s->reason );
4221 else ret = send_frame( socket, SOCKET_OPCODE_CLOSE, s->status, s->reason, s->len, TRUE, NULL );
4223 send_io_complete( &socket->hdr );
4224 if (s->send_callback) socket_shutdown_complete( socket, ret );
4227 static DWORD send_socket_shutdown( struct socket *socket, USHORT status, const void *reason, DWORD len,
4228 BOOL send_callback)
4230 DWORD ret;
4232 if (socket->state < SOCKET_STATE_SHUTDOWN) socket->state = SOCKET_STATE_SHUTDOWN;
4234 if (socket->hdr.flags & WINHTTP_FLAG_ASYNC)
4236 BOOL async_send, complete_async = FALSE;
4237 struct socket_shutdown *s;
4239 if (!(s = malloc( sizeof(*s) ))) return FALSE;
4241 AcquireSRWLockExclusive( &socket->send_lock );
4242 async_send = InterlockedIncrement( &socket->hdr.pending_sends ) > 1 || socket->hdr.recursion_count >= 3;
4243 if (!async_send)
4245 memset( &s->ovr, 0, sizeof(s->ovr) );
4246 if ((ret = send_frame( socket, SOCKET_OPCODE_CLOSE, status, reason, len, TRUE, &s->ovr )) == WSA_IO_PENDING)
4248 async_send = TRUE;
4249 complete_async = TRUE;
4253 if (async_send)
4255 s->complete_async = complete_async;
4256 s->status = status;
4257 memcpy( s->reason, reason, len );
4258 s->len = len;
4259 s->send_callback = send_callback;
4261 if ((ret = queue_task( &socket->send_q, task_socket_shutdown, &s->task_hdr, &socket->hdr )))
4263 InterlockedDecrement( &socket->hdr.pending_sends );
4264 free( s );
4267 else InterlockedDecrement( &socket->hdr.pending_sends );
4268 ReleaseSRWLockExclusive( &socket->send_lock );
4269 if (!async_send)
4271 free( s );
4272 if (send_callback)
4274 socket_shutdown_complete( socket, ret );
4275 ret = ERROR_SUCCESS;
4279 else ret = send_frame( socket, SOCKET_OPCODE_CLOSE, status, reason, len, TRUE, NULL );
4281 return ret;
4284 DWORD WINAPI WinHttpWebSocketShutdown( HINTERNET hsocket, USHORT status, void *reason, DWORD len )
4286 struct socket *socket;
4287 DWORD ret;
4289 TRACE( "%p, %u, %p, %lu\n", hsocket, status, reason, len );
4291 if ((len && !reason) || len > sizeof(socket->reason)) return ERROR_INVALID_PARAMETER;
4293 if (!(socket = (struct socket *)grab_object( hsocket ))) return ERROR_INVALID_HANDLE;
4294 if (socket->hdr.type != WINHTTP_HANDLE_TYPE_SOCKET)
4296 release_object( &socket->hdr );
4297 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE;
4299 if (socket->state >= SOCKET_STATE_SHUTDOWN)
4301 release_object( &socket->hdr );
4302 return ERROR_INVALID_OPERATION;
4305 ret = send_socket_shutdown( socket, status, reason, len, TRUE );
4306 release_object( &socket->hdr );
4307 return ret;
4310 static DWORD socket_close( struct socket *socket )
4312 BOOL final = FALSE;
4313 DWORD ret, count;
4315 if (socket->close_frame_received) return socket->close_frame_receive_err;
4317 if ((ret = socket_drain( socket ))) return ret;
4319 while (1)
4321 if ((ret = receive_frame( socket, &count, &socket->opcode, &final ))) return ret;
4322 if (socket->opcode == SOCKET_OPCODE_CLOSE) break;
4324 socket->read_size = count;
4325 if ((ret = socket_drain( socket ))) return ret;
4327 if (!final)
4328 FIXME( "Received close opcode without FIN bit.\n" );
4330 return receive_close_status( socket, count );
4333 static void socket_close_complete( struct socket *socket, DWORD ret )
4335 if (!ret) send_callback( &socket->hdr, WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE, NULL, 0 );
4336 else
4338 WINHTTP_WEB_SOCKET_ASYNC_RESULT result;
4339 result.AsyncResult.dwResult = API_READ_DATA; /* FIXME */
4340 result.AsyncResult.dwError = ret;
4341 result.Operation = WINHTTP_WEB_SOCKET_CLOSE_OPERATION;
4342 send_callback( &socket->hdr, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result) );
4346 static void task_socket_close( void *ctx, BOOL abort )
4348 struct socket_shutdown *s = ctx;
4349 struct socket *socket = (struct socket *)s->task_hdr.obj;
4350 DWORD ret;
4352 if (abort)
4354 socket_close_complete( socket, ERROR_WINHTTP_OPERATION_CANCELLED );
4355 return;
4358 TRACE("running %p\n", ctx);
4360 ret = socket_close( socket );
4361 receive_io_complete( socket );
4362 if (task_needs_completion( &s->task_hdr ))
4363 socket_close_complete( socket, ret );
4366 DWORD WINAPI WinHttpWebSocketClose( HINTERNET hsocket, USHORT status, void *reason, DWORD len )
4368 enum socket_state prev_state;
4369 LONG pending_receives = 0;
4370 struct socket *socket;
4371 DWORD ret;
4373 TRACE( "%p, %u, %p, %lu\n", hsocket, status, reason, len );
4375 if ((len && !reason) || len > sizeof(socket->reason)) return ERROR_INVALID_PARAMETER;
4377 if (!(socket = (struct socket *)grab_object( hsocket ))) return ERROR_INVALID_HANDLE;
4378 if (socket->hdr.type != WINHTTP_HANDLE_TYPE_SOCKET)
4380 release_object( &socket->hdr );
4381 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE;
4383 if (socket->state >= SOCKET_STATE_CLOSED)
4385 release_object( &socket->hdr );
4386 return ERROR_INVALID_OPERATION;
4389 prev_state = socket->state;
4390 socket->state = SOCKET_STATE_CLOSED;
4392 if (socket->hdr.flags & WINHTTP_FLAG_ASYNC)
4394 pending_receives = InterlockedIncrement( &socket->hdr.pending_receives );
4395 cancel_queue( &socket->recv_q );
4398 if (prev_state < SOCKET_STATE_SHUTDOWN && (ret = send_socket_shutdown( socket, status, reason, len, FALSE )))
4399 goto done;
4401 if (pending_receives == 1 && socket->close_frame_received)
4403 if (socket->hdr.flags & WINHTTP_FLAG_ASYNC)
4404 socket_close_complete( socket, socket->close_frame_receive_err );
4405 goto done;
4408 if (socket->hdr.flags & WINHTTP_FLAG_ASYNC)
4410 struct socket_shutdown *s;
4412 if (!(s = calloc( 1, sizeof(*s) )))
4414 ret = ERROR_OUTOFMEMORY;
4415 goto done;
4417 if ((ret = queue_task( &socket->recv_q, task_socket_close, &s->task_hdr, &socket->hdr )))
4419 InterlockedDecrement( &socket->hdr.pending_receives );
4420 free( s );
4423 else ret = socket_close( socket );
4425 done:
4426 release_object( &socket->hdr );
4427 return ret;
4430 DWORD WINAPI WinHttpWebSocketQueryCloseStatus( HINTERNET hsocket, USHORT *status, void *reason, DWORD len,
4431 DWORD *ret_len )
4433 struct socket *socket;
4434 DWORD ret;
4436 TRACE( "%p, %p, %p, %lu, %p\n", hsocket, status, reason, len, ret_len );
4438 if (!status || (len && !reason) || !ret_len) return ERROR_INVALID_PARAMETER;
4440 if (!(socket = (struct socket *)grab_object( hsocket ))) return ERROR_INVALID_HANDLE;
4441 if (socket->hdr.type != WINHTTP_HANDLE_TYPE_SOCKET)
4443 release_object( &socket->hdr );
4444 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE;
4447 if (!socket->close_frame_received || socket->close_frame_receive_err)
4449 ret = socket->close_frame_received ? socket->close_frame_receive_err : ERROR_INVALID_OPERATION;
4450 release_object( &socket->hdr );
4451 return ret;
4453 *status = socket->status;
4454 *ret_len = socket->reason_len;
4455 if (socket->reason_len > len) ret = ERROR_INSUFFICIENT_BUFFER;
4456 else
4458 memcpy( reason, socket->reason, socket->reason_len );
4459 ret = ERROR_SUCCESS;
4462 release_object( &socket->hdr );
4463 return ret;
4466 enum request_state
4468 REQUEST_STATE_INITIALIZED,
4469 REQUEST_STATE_CANCELLED,
4470 REQUEST_STATE_OPEN,
4471 REQUEST_STATE_SENT,
4472 REQUEST_STATE_RESPONSE_RECEIVED
4475 struct winhttp_request
4477 IWinHttpRequest IWinHttpRequest_iface;
4478 LONG refs;
4479 CRITICAL_SECTION cs;
4480 enum request_state state;
4481 HINTERNET hsession;
4482 HINTERNET hconnect;
4483 HINTERNET hrequest;
4484 VARIANT data;
4485 WCHAR *verb;
4486 HANDLE done;
4487 HANDLE wait;
4488 HANDLE cancel;
4489 BOOL proc_running;
4490 char *buffer;
4491 DWORD offset;
4492 DWORD bytes_available;
4493 DWORD bytes_read;
4494 DWORD error;
4495 DWORD logon_policy;
4496 DWORD disable_feature;
4497 LONG resolve_timeout;
4498 LONG connect_timeout;
4499 LONG send_timeout;
4500 LONG receive_timeout;
4501 WINHTTP_PROXY_INFO proxy;
4502 BOOL async;
4503 UINT url_codepage;
4506 static inline struct winhttp_request *impl_from_IWinHttpRequest( IWinHttpRequest *iface )
4508 return CONTAINING_RECORD( iface, struct winhttp_request, IWinHttpRequest_iface );
4511 static ULONG WINAPI winhttp_request_AddRef(
4512 IWinHttpRequest *iface )
4514 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4515 return InterlockedIncrement( &request->refs );
4518 /* critical section must be held */
4519 static void cancel_request( struct winhttp_request *request )
4521 if (request->state <= REQUEST_STATE_CANCELLED) return;
4523 if (request->proc_running)
4525 SetEvent( request->cancel );
4526 LeaveCriticalSection( &request->cs );
4528 WaitForSingleObject( request->done, INFINITE );
4530 EnterCriticalSection( &request->cs );
4532 request->state = REQUEST_STATE_CANCELLED;
4535 /* critical section must be held */
4536 static void free_request( struct winhttp_request *request )
4538 if (request->state < REQUEST_STATE_INITIALIZED) return;
4539 WinHttpCloseHandle( request->hrequest );
4540 WinHttpCloseHandle( request->hconnect );
4541 WinHttpCloseHandle( request->hsession );
4542 CloseHandle( request->done );
4543 CloseHandle( request->wait );
4544 CloseHandle( request->cancel );
4545 free( request->proxy.lpszProxy );
4546 free( request->proxy.lpszProxyBypass );
4547 free( request->buffer );
4548 free( request->verb );
4549 VariantClear( &request->data );
4552 static ULONG WINAPI winhttp_request_Release(
4553 IWinHttpRequest *iface )
4555 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4556 LONG refs = InterlockedDecrement( &request->refs );
4557 if (!refs)
4559 TRACE("destroying %p\n", request);
4561 EnterCriticalSection( &request->cs );
4562 cancel_request( request );
4563 free_request( request );
4564 LeaveCriticalSection( &request->cs );
4565 request->cs.DebugInfo->Spare[0] = 0;
4566 DeleteCriticalSection( &request->cs );
4567 free( request );
4569 return refs;
4572 static HRESULT WINAPI winhttp_request_QueryInterface(
4573 IWinHttpRequest *iface,
4574 REFIID riid,
4575 void **obj )
4577 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4579 TRACE("%p, %s, %p\n", request, debugstr_guid(riid), obj );
4581 if (IsEqualGUID( riid, &IID_IWinHttpRequest ) ||
4582 IsEqualGUID( riid, &IID_IDispatch ) ||
4583 IsEqualGUID( riid, &IID_IUnknown ))
4585 *obj = iface;
4587 else
4589 FIXME("interface %s not implemented\n", debugstr_guid(riid));
4590 return E_NOINTERFACE;
4592 IWinHttpRequest_AddRef( iface );
4593 return S_OK;
4596 static HRESULT WINAPI winhttp_request_GetTypeInfoCount(
4597 IWinHttpRequest *iface,
4598 UINT *count )
4600 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4602 TRACE("%p, %p\n", request, count);
4603 *count = 1;
4604 return S_OK;
4607 enum type_id
4609 IWinHttpRequest_tid,
4610 last_tid
4613 static ITypeLib *winhttp_typelib;
4614 static ITypeInfo *winhttp_typeinfo[last_tid];
4616 static REFIID winhttp_tid_id[] =
4618 &IID_IWinHttpRequest
4621 static HRESULT get_typeinfo( enum type_id tid, ITypeInfo **ret )
4623 HRESULT hr;
4625 if (!winhttp_typelib)
4627 ITypeLib *typelib;
4629 hr = LoadRegTypeLib( &LIBID_WinHttp, 5, 1, LOCALE_SYSTEM_DEFAULT, &typelib );
4630 if (FAILED(hr))
4632 ERR( "LoadRegTypeLib failed: %#lx\n", hr );
4633 return hr;
4635 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib, typelib, NULL ))
4636 ITypeLib_Release( typelib );
4638 if (!winhttp_typeinfo[tid])
4640 ITypeInfo *typeinfo;
4642 hr = ITypeLib_GetTypeInfoOfGuid( winhttp_typelib, winhttp_tid_id[tid], &typeinfo );
4643 if (FAILED(hr))
4645 ERR( "GetTypeInfoOfGuid(%s) failed: %#lx\n", debugstr_guid(winhttp_tid_id[tid]), hr );
4646 return hr;
4648 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo + tid), typeinfo, NULL ))
4649 ITypeInfo_Release( typeinfo );
4651 *ret = winhttp_typeinfo[tid];
4652 ITypeInfo_AddRef(winhttp_typeinfo[tid]);
4653 return S_OK;
4656 void release_typelib(void)
4658 unsigned i;
4660 for (i = 0; i < ARRAY_SIZE(winhttp_typeinfo); i++)
4661 if (winhttp_typeinfo[i])
4662 ITypeInfo_Release(winhttp_typeinfo[i]);
4664 if (winhttp_typelib)
4665 ITypeLib_Release(winhttp_typelib);
4668 static HRESULT WINAPI winhttp_request_GetTypeInfo(
4669 IWinHttpRequest *iface,
4670 UINT index,
4671 LCID lcid,
4672 ITypeInfo **info )
4674 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4675 TRACE( "%p, %u, %lu, %p\n", request, index, lcid, info );
4677 return get_typeinfo( IWinHttpRequest_tid, info );
4680 static HRESULT WINAPI winhttp_request_GetIDsOfNames(
4681 IWinHttpRequest *iface,
4682 REFIID riid,
4683 LPOLESTR *names,
4684 UINT count,
4685 LCID lcid,
4686 DISPID *dispid )
4688 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4689 ITypeInfo *typeinfo;
4690 HRESULT hr;
4692 TRACE( "%p, %s, %p, %u, %lu, %p\n", request, debugstr_guid(riid), names, count, lcid, dispid );
4694 if (!names || !count || !dispid) return E_INVALIDARG;
4696 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
4697 if (SUCCEEDED(hr))
4699 hr = ITypeInfo_GetIDsOfNames( typeinfo, names, count, dispid );
4700 ITypeInfo_Release( typeinfo );
4702 return hr;
4705 static HRESULT WINAPI winhttp_request_Invoke(
4706 IWinHttpRequest *iface,
4707 DISPID member,
4708 REFIID riid,
4709 LCID lcid,
4710 WORD flags,
4711 DISPPARAMS *params,
4712 VARIANT *result,
4713 EXCEPINFO *excep_info,
4714 UINT *arg_err )
4716 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4717 ITypeInfo *typeinfo;
4718 HRESULT hr;
4720 TRACE( "%p, %ld, %s, %lu, %d, %p, %p, %p, %p\n", request, member, debugstr_guid(riid),
4721 lcid, flags, params, result, excep_info, arg_err );
4723 if (!IsEqualIID( riid, &IID_NULL )) return DISP_E_UNKNOWNINTERFACE;
4725 if (member == DISPID_HTTPREQUEST_OPTION)
4727 VARIANT ret_value, option;
4728 UINT err_pos;
4730 if (!result) result = &ret_value;
4731 if (!arg_err) arg_err = &err_pos;
4733 VariantInit( &option );
4734 VariantInit( result );
4736 if (!flags) return S_OK;
4738 if (flags == DISPATCH_PROPERTYPUT)
4740 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
4741 if (FAILED(hr)) return hr;
4743 hr = IWinHttpRequest_put_Option( &request->IWinHttpRequest_iface, V_I4( &option ), params->rgvarg[0] );
4744 if (FAILED(hr))
4745 WARN( "put_Option(%ld) failed: %#lx\n", V_I4( &option ), hr );
4746 return hr;
4748 else if (flags & (DISPATCH_PROPERTYGET | DISPATCH_METHOD))
4750 hr = DispGetParam( params, 0, VT_I4, &option, arg_err );
4751 if (FAILED(hr)) return hr;
4753 hr = IWinHttpRequest_get_Option( &request->IWinHttpRequest_iface, V_I4( &option ), result );
4754 if (FAILED(hr))
4755 WARN( "get_Option(%ld) failed: %#lx\n", V_I4( &option ), hr );
4756 return hr;
4759 FIXME("unsupported flags %x\n", flags);
4760 return E_NOTIMPL;
4763 /* fallback to standard implementation */
4765 hr = get_typeinfo( IWinHttpRequest_tid, &typeinfo );
4766 if (SUCCEEDED(hr))
4768 hr = ITypeInfo_Invoke( typeinfo, &request->IWinHttpRequest_iface, member, flags,
4769 params, result, excep_info, arg_err );
4770 ITypeInfo_Release( typeinfo );
4772 return hr;
4775 static HRESULT WINAPI winhttp_request_SetProxy(
4776 IWinHttpRequest *iface,
4777 HTTPREQUEST_PROXY_SETTING proxy_setting,
4778 VARIANT proxy_server,
4779 VARIANT bypass_list )
4781 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4782 DWORD err = ERROR_SUCCESS;
4784 TRACE( "%p, %lu, %s, %s\n", request, proxy_setting, debugstr_variant(&proxy_server),
4785 debugstr_variant(&bypass_list) );
4787 EnterCriticalSection( &request->cs );
4788 switch (proxy_setting)
4790 case HTTPREQUEST_PROXYSETTING_DEFAULT:
4791 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
4792 free( request->proxy.lpszProxy );
4793 free( request->proxy.lpszProxyBypass );
4794 request->proxy.lpszProxy = NULL;
4795 request->proxy.lpszProxyBypass = NULL;
4796 break;
4798 case HTTPREQUEST_PROXYSETTING_DIRECT:
4799 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
4800 free( request->proxy.lpszProxy );
4801 free( request->proxy.lpszProxyBypass );
4802 request->proxy.lpszProxy = NULL;
4803 request->proxy.lpszProxyBypass = NULL;
4804 break;
4806 case HTTPREQUEST_PROXYSETTING_PROXY:
4807 request->proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
4808 if (V_VT( &proxy_server ) == VT_BSTR)
4810 free( request->proxy.lpszProxy );
4811 request->proxy.lpszProxy = wcsdup( V_BSTR( &proxy_server ) );
4813 if (V_VT( &bypass_list ) == VT_BSTR)
4815 free( request->proxy.lpszProxyBypass );
4816 request->proxy.lpszProxyBypass = wcsdup( V_BSTR( &bypass_list ) );
4818 break;
4820 default:
4821 err = ERROR_INVALID_PARAMETER;
4822 break;
4824 LeaveCriticalSection( &request->cs );
4825 return HRESULT_FROM_WIN32( err );
4828 static HRESULT WINAPI winhttp_request_SetCredentials(
4829 IWinHttpRequest *iface,
4830 BSTR username,
4831 BSTR password,
4832 HTTPREQUEST_SETCREDENTIALS_FLAGS flags )
4834 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4835 DWORD target, scheme = WINHTTP_AUTH_SCHEME_BASIC; /* FIXME: query supported schemes */
4836 DWORD err = ERROR_SUCCESS;
4838 TRACE( "%p, %s, %p, %#lx\n", request, debugstr_w(username), password, flags );
4840 EnterCriticalSection( &request->cs );
4841 if (request->state < REQUEST_STATE_OPEN)
4843 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
4844 goto done;
4846 switch (flags)
4848 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER:
4849 target = WINHTTP_AUTH_TARGET_SERVER;
4850 break;
4851 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY:
4852 target = WINHTTP_AUTH_TARGET_PROXY;
4853 break;
4854 default:
4855 err = ERROR_INVALID_PARAMETER;
4856 goto done;
4858 if (!WinHttpSetCredentials( request->hrequest, target, scheme, username, password, NULL ))
4860 err = GetLastError();
4862 done:
4863 LeaveCriticalSection( &request->cs );
4864 return HRESULT_FROM_WIN32( err );
4867 static void initialize_request( struct winhttp_request *request )
4869 request->wait = CreateEventW( NULL, FALSE, FALSE, NULL );
4870 request->cancel = CreateEventW( NULL, FALSE, FALSE, NULL );
4871 request->done = CreateEventW( NULL, FALSE, FALSE, NULL );
4872 request->connect_timeout = 60000;
4873 request->send_timeout = 30000;
4874 request->receive_timeout = 30000;
4875 request->url_codepage = CP_UTF8;
4876 VariantInit( &request->data );
4877 request->state = REQUEST_STATE_INITIALIZED;
4880 static void reset_request( struct winhttp_request *request )
4882 cancel_request( request );
4883 WinHttpCloseHandle( request->hrequest );
4884 request->hrequest = NULL;
4885 WinHttpCloseHandle( request->hconnect );
4886 request->hconnect = NULL;
4887 free( request->buffer );
4888 request->buffer = NULL;
4889 free( request->verb );
4890 request->verb = NULL;
4891 request->offset = 0;
4892 request->bytes_available = 0;
4893 request->bytes_read = 0;
4894 request->error = ERROR_SUCCESS;
4895 request->logon_policy = 0;
4896 request->disable_feature = 0;
4897 request->async = FALSE;
4898 request->connect_timeout = 60000;
4899 request->send_timeout = 30000;
4900 request->receive_timeout = 30000;
4901 request->url_codepage = CP_UTF8;
4902 free( request->proxy.lpszProxy );
4903 request->proxy.lpszProxy = NULL;
4904 free( request->proxy.lpszProxyBypass );
4905 request->proxy.lpszProxyBypass = NULL;
4906 VariantClear( &request->data );
4907 request->state = REQUEST_STATE_INITIALIZED;
4910 static HRESULT WINAPI winhttp_request_Open(
4911 IWinHttpRequest *iface,
4912 BSTR method,
4913 BSTR url,
4914 VARIANT async )
4916 static const WCHAR httpsW[] = {'h','t','t','p','s'};
4917 static const WCHAR *acceptW[] = {L"*/*", NULL};
4918 static const WCHAR user_agentW[] = L"Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)";
4919 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
4920 URL_COMPONENTS uc;
4921 WCHAR *hostname, *path = NULL, *verb = NULL;
4922 DWORD err = ERROR_OUTOFMEMORY, len, flags = 0;
4924 TRACE("%p, %s, %s, %s\n", request, debugstr_w(method), debugstr_w(url),
4925 debugstr_variant(&async));
4927 if (!method || !url) return E_INVALIDARG;
4929 memset( &uc, 0, sizeof(uc) );
4930 uc.dwStructSize = sizeof(uc);
4931 uc.dwSchemeLength = ~0u;
4932 uc.dwHostNameLength = ~0u;
4933 uc.dwUrlPathLength = ~0u;
4934 uc.dwExtraInfoLength = ~0u;
4935 if (!WinHttpCrackUrl( url, 0, 0, &uc )) return HRESULT_FROM_WIN32( GetLastError() );
4937 EnterCriticalSection( &request->cs );
4938 reset_request( request );
4940 if (!(hostname = malloc( (uc.dwHostNameLength + 1) * sizeof(WCHAR) ))) goto error;
4941 memcpy( hostname, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
4942 hostname[uc.dwHostNameLength] = 0;
4944 if (!(path = malloc( (uc.dwUrlPathLength + uc.dwExtraInfoLength + 1) * sizeof(WCHAR) ))) goto error;
4945 memcpy( path, uc.lpszUrlPath, (uc.dwUrlPathLength + uc.dwExtraInfoLength) * sizeof(WCHAR) );
4946 path[uc.dwUrlPathLength + uc.dwExtraInfoLength] = 0;
4948 if (!(verb = wcsdup( method ))) goto error;
4949 if (SUCCEEDED( VariantChangeType( &async, &async, 0, VT_BOOL )) && V_BOOL( &async )) request->async = TRUE;
4950 else request->async = FALSE;
4952 if (!request->hsession)
4954 if (!(request->hsession = WinHttpOpen( user_agentW, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL,
4955 WINHTTP_FLAG_ASYNC )))
4957 err = GetLastError();
4958 goto error;
4960 if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
4962 WinHttpCloseHandle( request->hsession );
4963 request->hsession = NULL;
4964 err = GetLastError();
4965 goto error;
4968 else if (!(request->hconnect = WinHttpConnect( request->hsession, hostname, uc.nPort, 0 )))
4970 err = GetLastError();
4971 goto error;
4974 len = ARRAY_SIZE( httpsW );
4975 if (uc.dwSchemeLength == len && !memcmp( uc.lpszScheme, httpsW, len * sizeof(WCHAR) ))
4977 flags |= WINHTTP_FLAG_SECURE;
4979 if (!(request->hrequest = WinHttpOpenRequest( request->hconnect, method, path, NULL, NULL, acceptW, flags )))
4981 err = GetLastError();
4982 goto error;
4984 WinHttpSetOption( request->hrequest, WINHTTP_OPTION_CONTEXT_VALUE, &request, sizeof(request) );
4986 request->state = REQUEST_STATE_OPEN;
4987 request->verb = verb;
4988 free( hostname );
4989 free( path );
4990 LeaveCriticalSection( &request->cs );
4991 return S_OK;
4993 error:
4994 WinHttpCloseHandle( request->hconnect );
4995 request->hconnect = NULL;
4996 free( hostname );
4997 free( path );
4998 free( verb );
4999 LeaveCriticalSection( &request->cs );
5000 return HRESULT_FROM_WIN32( err );
5003 static HRESULT WINAPI winhttp_request_SetRequestHeader(
5004 IWinHttpRequest *iface,
5005 BSTR header,
5006 BSTR value )
5008 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5009 DWORD len, err = ERROR_SUCCESS;
5010 WCHAR *str;
5012 TRACE("%p, %s, %s\n", request, debugstr_w(header), debugstr_w(value));
5014 if (!header) return E_INVALIDARG;
5016 EnterCriticalSection( &request->cs );
5017 if (request->state < REQUEST_STATE_OPEN)
5019 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN;
5020 goto done;
5022 if (request->state >= REQUEST_STATE_SENT)
5024 err = ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND;
5025 goto done;
5027 len = lstrlenW( header ) + 4;
5028 if (value) len += lstrlenW( value );
5029 if (!(str = malloc( (len + 1) * sizeof(WCHAR) )))
5031 err = ERROR_OUTOFMEMORY;
5032 goto done;
5034 swprintf( str, len + 1, L"%s: %s\r\n", header, value ? value : L"" );
5035 if (!WinHttpAddRequestHeaders( request->hrequest, str, len,
5036 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE ))
5038 err = GetLastError();
5040 free( str );
5042 done:
5043 LeaveCriticalSection( &request->cs );
5044 return HRESULT_FROM_WIN32( err );
5047 static HRESULT WINAPI winhttp_request_GetResponseHeader(
5048 IWinHttpRequest *iface,
5049 BSTR header,
5050 BSTR *value )
5052 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5053 DWORD size, err = ERROR_SUCCESS;
5055 TRACE("%p, %p\n", request, header);
5057 EnterCriticalSection( &request->cs );
5058 if (request->state < REQUEST_STATE_SENT)
5060 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
5061 goto done;
5063 if (!header || !value)
5065 err = ERROR_INVALID_PARAMETER;
5066 goto done;
5068 size = 0;
5069 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, NULL, &size, NULL ))
5071 err = GetLastError();
5072 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
5074 if (!(*value = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
5076 err = ERROR_OUTOFMEMORY;
5077 goto done;
5079 err = ERROR_SUCCESS;
5080 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CUSTOM, header, *value, &size, NULL ))
5082 err = GetLastError();
5083 SysFreeString( *value );
5085 done:
5086 LeaveCriticalSection( &request->cs );
5087 return HRESULT_FROM_WIN32( err );
5090 static HRESULT WINAPI winhttp_request_GetAllResponseHeaders(
5091 IWinHttpRequest *iface,
5092 BSTR *headers )
5094 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5095 DWORD size, err = ERROR_SUCCESS;
5097 TRACE("%p, %p\n", request, headers);
5099 if (!headers) return E_INVALIDARG;
5101 EnterCriticalSection( &request->cs );
5102 if (request->state < REQUEST_STATE_SENT)
5104 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
5105 goto done;
5107 size = 0;
5108 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, NULL, &size, NULL ))
5110 err = GetLastError();
5111 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
5113 if (!(*headers = SysAllocStringLen( NULL, size / sizeof(WCHAR) )))
5115 err = ERROR_OUTOFMEMORY;
5116 goto done;
5118 err = ERROR_SUCCESS;
5119 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, *headers, &size, NULL ))
5121 err = GetLastError();
5122 SysFreeString( *headers );
5124 done:
5125 LeaveCriticalSection( &request->cs );
5126 return HRESULT_FROM_WIN32( err );
5129 static void CALLBACK wait_status_callback( HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID buffer, DWORD size )
5131 struct winhttp_request *request = (struct winhttp_request *)context;
5133 switch (status)
5135 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
5136 request->bytes_available = *(DWORD *)buffer;
5137 request->error = ERROR_SUCCESS;
5138 break;
5139 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
5140 request->bytes_read = size;
5141 request->error = ERROR_SUCCESS;
5142 break;
5143 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
5145 WINHTTP_ASYNC_RESULT *result = (WINHTTP_ASYNC_RESULT *)buffer;
5146 request->error = result->dwError;
5147 break;
5149 default:
5150 request->error = ERROR_SUCCESS;
5151 break;
5153 SetEvent( request->wait );
5156 static void wait_set_status_callback( struct winhttp_request *request, DWORD status )
5158 status |= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
5159 WinHttpSetStatusCallback( request->hrequest, wait_status_callback, status, 0 );
5162 static DWORD wait_for_completion( struct winhttp_request *request )
5164 HANDLE handles[2] = { request->wait, request->cancel };
5165 DWORD ret;
5167 switch (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ))
5169 case WAIT_OBJECT_0:
5170 ret = request->error;
5171 break;
5172 case WAIT_OBJECT_0 + 1:
5173 ret = request->error = ERROR_CANCELLED;
5174 SetEvent( request->done );
5175 break;
5176 default:
5177 ret = request->error = GetLastError();
5178 break;
5180 return ret;
5183 static HRESULT request_receive( struct winhttp_request *request )
5185 DWORD err, size, buflen = 4096;
5187 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE );
5188 if (!WinHttpReceiveResponse( request->hrequest, NULL ))
5190 return HRESULT_FROM_WIN32( GetLastError() );
5192 if ((err = wait_for_completion( request ))) return HRESULT_FROM_WIN32( err );
5193 if (!wcscmp( request->verb, L"HEAD" ))
5195 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
5196 return S_OK;
5198 if (!(request->buffer = malloc( buflen ))) return E_OUTOFMEMORY;
5199 request->buffer[0] = 0;
5200 size = 0;
5203 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE );
5204 if (!WinHttpQueryDataAvailable( request->hrequest, &request->bytes_available ))
5206 err = GetLastError();
5207 goto error;
5209 if ((err = wait_for_completion( request ))) goto error;
5210 if (!request->bytes_available) break;
5211 size += request->bytes_available;
5212 if (buflen < size)
5214 char *tmp;
5215 while (buflen < size) buflen *= 2;
5216 if (!(tmp = realloc( request->buffer, buflen )))
5218 err = ERROR_OUTOFMEMORY;
5219 goto error;
5221 request->buffer = tmp;
5223 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_READ_COMPLETE );
5224 if (!WinHttpReadData( request->hrequest, request->buffer + request->offset,
5225 request->bytes_available, &request->bytes_read ))
5227 err = GetLastError();
5228 goto error;
5230 if ((err = wait_for_completion( request ))) goto error;
5231 request->offset += request->bytes_read;
5232 } while (request->bytes_read);
5234 request->state = REQUEST_STATE_RESPONSE_RECEIVED;
5235 return S_OK;
5237 error:
5238 free( request->buffer );
5239 request->buffer = NULL;
5240 return HRESULT_FROM_WIN32( err );
5243 static DWORD request_set_parameters( struct winhttp_request *request )
5245 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_PROXY, &request->proxy,
5246 sizeof(request->proxy) )) return GetLastError();
5248 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_AUTOLOGON_POLICY, &request->logon_policy,
5249 sizeof(request->logon_policy) )) return GetLastError();
5251 if (!WinHttpSetOption( request->hrequest, WINHTTP_OPTION_DISABLE_FEATURE, &request->disable_feature,
5252 sizeof(request->disable_feature) )) return GetLastError();
5254 if (!WinHttpSetTimeouts( request->hrequest,
5255 request->resolve_timeout,
5256 request->connect_timeout,
5257 request->send_timeout,
5258 request->receive_timeout )) return GetLastError();
5259 return ERROR_SUCCESS;
5262 static void request_set_utf8_content_type( struct winhttp_request *request )
5264 WCHAR headerW[64];
5265 int len;
5267 len = swprintf( headerW, ARRAY_SIZE(headerW), L"%s: %s", L"Content-Type", L"text/plain" );
5268 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW );
5270 len = swprintf( headerW, ARRAY_SIZE(headerW), L"%s: %s", L"Content-Type", L"charset=utf-8" );
5271 WinHttpAddRequestHeaders( request->hrequest, headerW, len, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON );
5274 static HRESULT request_send( struct winhttp_request *request )
5276 SAFEARRAY *sa = NULL;
5277 VARIANT data;
5278 char *ptr = NULL;
5279 LONG size = 0;
5280 HRESULT hr;
5281 DWORD err;
5283 if ((err = request_set_parameters( request ))) return HRESULT_FROM_WIN32( err );
5284 if (wcscmp( request->verb, L"GET" ))
5286 VariantInit( &data );
5287 if (V_VT( &request->data ) == VT_BSTR)
5289 UINT cp = CP_ACP;
5290 const WCHAR *str = V_BSTR( &request->data );
5291 int i, len = lstrlenW( str );
5293 for (i = 0; i < len; i++)
5295 if (str[i] > 127)
5297 cp = CP_UTF8;
5298 break;
5301 size = WideCharToMultiByte( cp, 0, str, len, NULL, 0, NULL, NULL );
5302 if (!(ptr = malloc( size ))) return E_OUTOFMEMORY;
5303 WideCharToMultiByte( cp, 0, str, len, ptr, size, NULL, NULL );
5304 if (cp == CP_UTF8) request_set_utf8_content_type( request );
5306 else if (VariantChangeType( &data, &request->data, 0, VT_ARRAY|VT_UI1 ) == S_OK)
5308 sa = V_ARRAY( &data );
5309 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK) return hr;
5310 if ((hr = SafeArrayGetUBound( sa, 1, &size )) != S_OK)
5312 SafeArrayUnaccessData( sa );
5313 return hr;
5315 size++;
5318 wait_set_status_callback( request, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE );
5319 if (!WinHttpSendRequest( request->hrequest, NULL, 0, ptr, size, size, 0 ))
5321 err = GetLastError();
5322 goto error;
5324 if ((err = wait_for_completion( request ))) goto error;
5325 if (sa) SafeArrayUnaccessData( sa );
5326 else free( ptr );
5327 request->state = REQUEST_STATE_SENT;
5328 return S_OK;
5330 error:
5331 if (sa) SafeArrayUnaccessData( sa );
5332 else free( ptr );
5333 return HRESULT_FROM_WIN32( err );
5336 static void CALLBACK send_and_receive_proc( TP_CALLBACK_INSTANCE *instance, void *ctx )
5338 struct winhttp_request *request = (struct winhttp_request *)ctx;
5339 if (request_send( request ) == S_OK) request_receive( request );
5340 SetEvent( request->done );
5343 /* critical section must be held */
5344 static DWORD request_wait( struct winhttp_request *request, DWORD timeout )
5346 HANDLE done = request->done;
5347 DWORD err, ret;
5349 LeaveCriticalSection( &request->cs );
5350 while ((err = MsgWaitForMultipleObjects( 1, &done, FALSE, timeout, QS_ALLINPUT )) == WAIT_OBJECT_0 + 1)
5352 MSG msg;
5353 while (PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ))
5355 TranslateMessage( &msg );
5356 DispatchMessageW( &msg );
5359 switch (err)
5361 case WAIT_OBJECT_0:
5362 ret = request->error;
5363 break;
5364 case WAIT_TIMEOUT:
5365 ret = ERROR_TIMEOUT;
5366 break;
5367 default:
5368 ret = GetLastError();
5369 break;
5371 EnterCriticalSection( &request->cs );
5372 if (err == WAIT_OBJECT_0) request->proc_running = FALSE;
5373 return ret;
5376 static HRESULT WINAPI winhttp_request_Send(
5377 IWinHttpRequest *iface,
5378 VARIANT body )
5380 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5381 HRESULT hr;
5383 TRACE("%p, %s\n", request, debugstr_variant(&body));
5385 EnterCriticalSection( &request->cs );
5386 if (request->state < REQUEST_STATE_OPEN)
5388 LeaveCriticalSection( &request->cs );
5389 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN );
5391 if (request->state >= REQUEST_STATE_SENT)
5393 LeaveCriticalSection( &request->cs );
5394 return S_OK;
5396 VariantClear( &request->data );
5397 if ((hr = VariantCopyInd( &request->data, &body )) != S_OK)
5399 LeaveCriticalSection( &request->cs );
5400 return hr;
5402 if (!TrySubmitThreadpoolCallback( send_and_receive_proc, request, NULL ))
5404 LeaveCriticalSection( &request->cs );
5405 return HRESULT_FROM_WIN32( GetLastError() );
5407 request->proc_running = TRUE;
5408 if (!request->async)
5410 hr = HRESULT_FROM_WIN32( request_wait( request, INFINITE ) );
5412 LeaveCriticalSection( &request->cs );
5413 return hr;
5416 static HRESULT WINAPI winhttp_request_get_Status(
5417 IWinHttpRequest *iface,
5418 LONG *status )
5420 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5421 DWORD err = ERROR_SUCCESS, flags, status_code, len = sizeof(status_code), index = 0;
5423 TRACE("%p, %p\n", request, status);
5425 if (!status) return E_INVALIDARG;
5427 EnterCriticalSection( &request->cs );
5428 if (request->state < REQUEST_STATE_SENT)
5430 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
5431 goto done;
5433 flags = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER;
5434 if (!WinHttpQueryHeaders( request->hrequest, flags, NULL, &status_code, &len, &index ))
5436 err = GetLastError();
5437 goto done;
5439 *status = status_code;
5441 done:
5442 LeaveCriticalSection( &request->cs );
5443 return HRESULT_FROM_WIN32( err );
5446 static HRESULT WINAPI winhttp_request_get_StatusText(
5447 IWinHttpRequest *iface,
5448 BSTR *status )
5450 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5451 DWORD err = ERROR_SUCCESS, len = 0, index = 0;
5453 TRACE("%p, %p\n", request, status);
5455 if (!status) return E_INVALIDARG;
5457 EnterCriticalSection( &request->cs );
5458 if (request->state < REQUEST_STATE_SENT)
5460 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
5461 goto done;
5463 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, NULL, &len, &index ))
5465 err = GetLastError();
5466 if (err != ERROR_INSUFFICIENT_BUFFER) goto done;
5468 if (!(*status = SysAllocStringLen( NULL, len / sizeof(WCHAR) )))
5470 err = ERROR_OUTOFMEMORY;
5471 goto done;
5473 index = 0;
5474 err = ERROR_SUCCESS;
5475 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_STATUS_TEXT, NULL, *status, &len, &index ))
5477 err = GetLastError();
5478 SysFreeString( *status );
5480 done:
5481 LeaveCriticalSection( &request->cs );
5482 return HRESULT_FROM_WIN32( err );
5485 static DWORD request_get_codepage( struct winhttp_request *request, UINT *codepage )
5487 WCHAR *buffer, *p;
5488 DWORD size;
5490 *codepage = CP_ACP;
5491 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, NULL, &size, NULL ) &&
5492 GetLastError() == ERROR_INSUFFICIENT_BUFFER)
5494 if (!(buffer = malloc( size ))) return ERROR_OUTOFMEMORY;
5495 if (!WinHttpQueryHeaders( request->hrequest, WINHTTP_QUERY_CONTENT_TYPE, NULL, buffer, &size, NULL ))
5497 return GetLastError();
5499 if ((p = wcsstr( buffer, L"charset" )))
5501 p += lstrlenW( L"charset" );
5502 while (*p == ' ') p++;
5503 if (*p++ == '=')
5505 while (*p == ' ') p++;
5506 if (!wcsicmp( p, L"utf-8" )) *codepage = CP_UTF8;
5509 free( buffer );
5511 return ERROR_SUCCESS;
5514 static HRESULT WINAPI winhttp_request_get_ResponseText(
5515 IWinHttpRequest *iface,
5516 BSTR *body )
5518 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5519 UINT codepage;
5520 DWORD err = ERROR_SUCCESS;
5521 int len;
5523 TRACE("%p, %p\n", request, body);
5525 if (!body) return E_INVALIDARG;
5527 EnterCriticalSection( &request->cs );
5528 if (request->state < REQUEST_STATE_SENT)
5530 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
5531 goto done;
5533 if ((err = request_get_codepage( request, &codepage ))) goto done;
5534 len = MultiByteToWideChar( codepage, 0, request->buffer, request->offset, NULL, 0 );
5535 if (!(*body = SysAllocStringLen( NULL, len )))
5537 err = ERROR_OUTOFMEMORY;
5538 goto done;
5540 MultiByteToWideChar( codepage, 0, request->buffer, request->offset, *body, len );
5541 (*body)[len] = 0;
5543 done:
5544 LeaveCriticalSection( &request->cs );
5545 return HRESULT_FROM_WIN32( err );
5548 static HRESULT WINAPI winhttp_request_get_ResponseBody(
5549 IWinHttpRequest *iface,
5550 VARIANT *body )
5552 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5553 SAFEARRAY *sa;
5554 HRESULT hr;
5555 DWORD err = ERROR_SUCCESS;
5556 char *ptr;
5558 TRACE("%p, %p\n", request, body);
5560 if (!body) return E_INVALIDARG;
5562 EnterCriticalSection( &request->cs );
5563 if (request->state < REQUEST_STATE_SENT)
5565 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
5566 goto done;
5568 if (!(sa = SafeArrayCreateVector( VT_UI1, 0, request->offset )))
5570 err = ERROR_OUTOFMEMORY;
5571 goto done;
5573 if ((hr = SafeArrayAccessData( sa, (void **)&ptr )) != S_OK)
5575 SafeArrayDestroy( sa );
5576 LeaveCriticalSection( &request->cs );
5577 return hr;
5579 memcpy( ptr, request->buffer, request->offset );
5580 if ((hr = SafeArrayUnaccessData( sa )) != S_OK)
5582 SafeArrayDestroy( sa );
5583 LeaveCriticalSection( &request->cs );
5584 return hr;
5586 V_VT( body ) = VT_ARRAY|VT_UI1;
5587 V_ARRAY( body ) = sa;
5589 done:
5590 LeaveCriticalSection( &request->cs );
5591 return HRESULT_FROM_WIN32( err );
5594 struct stream
5596 IStream IStream_iface;
5597 LONG refs;
5598 char *data;
5599 ULARGE_INTEGER pos, size;
5602 static inline struct stream *impl_from_IStream( IStream *iface )
5604 return CONTAINING_RECORD( iface, struct stream, IStream_iface );
5607 static HRESULT WINAPI stream_QueryInterface( IStream *iface, REFIID riid, void **obj )
5609 struct stream *stream = impl_from_IStream( iface );
5611 TRACE("%p, %s, %p\n", stream, debugstr_guid(riid), obj);
5613 if (IsEqualGUID( riid, &IID_IStream ) || IsEqualGUID( riid, &IID_IUnknown ))
5615 *obj = iface;
5617 else
5619 FIXME("interface %s not implemented\n", debugstr_guid(riid));
5620 return E_NOINTERFACE;
5622 IStream_AddRef( iface );
5623 return S_OK;
5626 static ULONG WINAPI stream_AddRef( IStream *iface )
5628 struct stream *stream = impl_from_IStream( iface );
5629 return InterlockedIncrement( &stream->refs );
5632 static ULONG WINAPI stream_Release( IStream *iface )
5634 struct stream *stream = impl_from_IStream( iface );
5635 LONG refs = InterlockedDecrement( &stream->refs );
5636 if (!refs)
5638 free( stream->data );
5639 free( stream );
5641 return refs;
5644 static HRESULT WINAPI stream_Read( IStream *iface, void *buf, ULONG len, ULONG *read )
5646 struct stream *stream = impl_from_IStream( iface );
5647 ULONG size;
5649 if (stream->pos.QuadPart >= stream->size.QuadPart)
5651 *read = 0;
5652 return S_FALSE;
5655 size = min( stream->size.QuadPart - stream->pos.QuadPart, len );
5656 memcpy( buf, stream->data + stream->pos.QuadPart, size );
5657 stream->pos.QuadPart += size;
5658 *read = size;
5660 return S_OK;
5663 static HRESULT WINAPI stream_Write( IStream *iface, const void *buf, ULONG len, ULONG *written )
5665 FIXME("\n");
5666 return E_NOTIMPL;
5669 static HRESULT WINAPI stream_Seek( IStream *iface, LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *newpos )
5671 struct stream *stream = impl_from_IStream( iface );
5673 if (origin == STREAM_SEEK_SET)
5674 stream->pos.QuadPart = move.QuadPart;
5675 else if (origin == STREAM_SEEK_CUR)
5676 stream->pos.QuadPart += move.QuadPart;
5677 else if (origin == STREAM_SEEK_END)
5678 stream->pos.QuadPart = stream->size.QuadPart - move.QuadPart;
5680 if (newpos) newpos->QuadPart = stream->pos.QuadPart;
5681 return S_OK;
5684 static HRESULT WINAPI stream_SetSize( IStream *iface, ULARGE_INTEGER newsize )
5686 FIXME("\n");
5687 return E_NOTIMPL;
5690 static HRESULT WINAPI stream_CopyTo( IStream *iface, IStream *stream, ULARGE_INTEGER len, ULARGE_INTEGER *read,
5691 ULARGE_INTEGER *written )
5693 FIXME("\n");
5694 return E_NOTIMPL;
5697 static HRESULT WINAPI stream_Commit( IStream *iface, DWORD flags )
5699 FIXME("\n");
5700 return E_NOTIMPL;
5703 static HRESULT WINAPI stream_Revert( IStream *iface )
5705 FIXME("\n");
5706 return E_NOTIMPL;
5709 static HRESULT WINAPI stream_LockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
5711 FIXME("\n");
5712 return E_NOTIMPL;
5715 static HRESULT WINAPI stream_UnlockRegion( IStream *iface, ULARGE_INTEGER offset, ULARGE_INTEGER len, DWORD locktype )
5717 FIXME("\n");
5718 return E_NOTIMPL;
5721 static HRESULT WINAPI stream_Stat( IStream *iface, STATSTG *stg, DWORD flag )
5723 FIXME("\n");
5724 return E_NOTIMPL;
5727 static HRESULT WINAPI stream_Clone( IStream *iface, IStream **stream )
5729 FIXME("\n");
5730 return E_NOTIMPL;
5733 static const IStreamVtbl stream_vtbl =
5735 stream_QueryInterface,
5736 stream_AddRef,
5737 stream_Release,
5738 stream_Read,
5739 stream_Write,
5740 stream_Seek,
5741 stream_SetSize,
5742 stream_CopyTo,
5743 stream_Commit,
5744 stream_Revert,
5745 stream_LockRegion,
5746 stream_UnlockRegion,
5747 stream_Stat,
5748 stream_Clone
5751 static HRESULT WINAPI winhttp_request_get_ResponseStream(
5752 IWinHttpRequest *iface,
5753 VARIANT *body )
5755 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5756 DWORD err = ERROR_SUCCESS;
5757 struct stream *stream;
5759 TRACE("%p, %p\n", request, body);
5761 if (!body) return E_INVALIDARG;
5763 EnterCriticalSection( &request->cs );
5764 if (request->state < REQUEST_STATE_SENT)
5766 err = ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND;
5767 goto done;
5769 if (!(stream = malloc( sizeof(*stream) )))
5771 err = ERROR_OUTOFMEMORY;
5772 goto done;
5774 stream->IStream_iface.lpVtbl = &stream_vtbl;
5775 stream->refs = 1;
5776 if (!(stream->data = malloc( request->offset )))
5778 free( stream );
5779 err = ERROR_OUTOFMEMORY;
5780 goto done;
5782 memcpy( stream->data, request->buffer, request->offset );
5783 stream->pos.QuadPart = 0;
5784 stream->size.QuadPart = request->offset;
5785 V_VT( body ) = VT_UNKNOWN;
5786 V_UNKNOWN( body ) = (IUnknown *)&stream->IStream_iface;
5788 done:
5789 LeaveCriticalSection( &request->cs );
5790 return HRESULT_FROM_WIN32( err );
5793 static HRESULT WINAPI winhttp_request_get_Option(
5794 IWinHttpRequest *iface,
5795 WinHttpRequestOption option,
5796 VARIANT *value )
5798 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5799 HRESULT hr = S_OK;
5801 TRACE("%p, %u, %p\n", request, option, value);
5803 EnterCriticalSection( &request->cs );
5804 switch (option)
5806 case WinHttpRequestOption_URLCodePage:
5807 V_VT( value ) = VT_I4;
5808 V_I4( value ) = request->url_codepage;
5809 break;
5810 default:
5811 FIXME("unimplemented option %u\n", option);
5812 hr = E_NOTIMPL;
5813 break;
5815 LeaveCriticalSection( &request->cs );
5816 return hr;
5819 static HRESULT WINAPI winhttp_request_put_Option(
5820 IWinHttpRequest *iface,
5821 WinHttpRequestOption option,
5822 VARIANT value )
5824 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5825 HRESULT hr = S_OK;
5827 TRACE("%p, %u, %s\n", request, option, debugstr_variant(&value));
5829 EnterCriticalSection( &request->cs );
5830 switch (option)
5832 case WinHttpRequestOption_EnableRedirects:
5834 if (V_BOOL( &value ))
5835 request->disable_feature &= ~WINHTTP_DISABLE_REDIRECTS;
5836 else
5837 request->disable_feature |= WINHTTP_DISABLE_REDIRECTS;
5838 break;
5840 case WinHttpRequestOption_URLCodePage:
5842 VARIANT cp;
5843 VariantInit( &cp );
5844 hr = VariantChangeType( &cp, &value, 0, VT_UI4 );
5845 if (SUCCEEDED( hr ))
5847 request->url_codepage = V_UI4( &cp );
5848 TRACE("URL codepage: %u\n", request->url_codepage);
5850 else if (V_VT( &value ) == VT_BSTR && !wcsicmp( V_BSTR( &value ), L"utf-8" ))
5852 TRACE("URL codepage: UTF-8\n");
5853 request->url_codepage = CP_UTF8;
5854 hr = S_OK;
5856 else
5857 FIXME("URL codepage %s is not recognized\n", debugstr_variant( &value ));
5858 break;
5860 default:
5861 FIXME("unimplemented option %u\n", option);
5862 hr = E_NOTIMPL;
5863 break;
5865 LeaveCriticalSection( &request->cs );
5866 return hr;
5869 static HRESULT WINAPI winhttp_request_WaitForResponse(
5870 IWinHttpRequest *iface,
5871 VARIANT timeout,
5872 VARIANT_BOOL *succeeded )
5874 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5875 DWORD err, msecs = (V_I4(&timeout) == -1) ? INFINITE : V_I4(&timeout) * 1000;
5877 TRACE("%p, %s, %p\n", request, debugstr_variant(&timeout), succeeded);
5879 EnterCriticalSection( &request->cs );
5880 if (request->state >= REQUEST_STATE_RESPONSE_RECEIVED)
5882 LeaveCriticalSection( &request->cs );
5883 return S_OK;
5885 switch ((err = request_wait( request, msecs )))
5887 case ERROR_TIMEOUT:
5888 if (succeeded) *succeeded = VARIANT_FALSE;
5889 err = ERROR_SUCCESS;
5890 break;
5892 default:
5893 if (succeeded) *succeeded = VARIANT_TRUE;
5894 break;
5896 LeaveCriticalSection( &request->cs );
5897 return HRESULT_FROM_WIN32( err );
5900 static HRESULT WINAPI winhttp_request_Abort(
5901 IWinHttpRequest *iface )
5903 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5905 TRACE("%p\n", request);
5907 EnterCriticalSection( &request->cs );
5908 cancel_request( request );
5909 LeaveCriticalSection( &request->cs );
5910 return S_OK;
5913 static HRESULT WINAPI winhttp_request_SetTimeouts(
5914 IWinHttpRequest *iface,
5915 LONG resolve_timeout,
5916 LONG connect_timeout,
5917 LONG send_timeout,
5918 LONG receive_timeout )
5920 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5922 TRACE( "%p, %ld, %ld, %ld, %ld\n", request, resolve_timeout, connect_timeout, send_timeout, receive_timeout );
5924 EnterCriticalSection( &request->cs );
5925 request->resolve_timeout = resolve_timeout;
5926 request->connect_timeout = connect_timeout;
5927 request->send_timeout = send_timeout;
5928 request->receive_timeout = receive_timeout;
5929 LeaveCriticalSection( &request->cs );
5930 return S_OK;
5933 static HRESULT WINAPI winhttp_request_SetClientCertificate(
5934 IWinHttpRequest *iface,
5935 BSTR certificate )
5937 FIXME("\n");
5938 return E_NOTIMPL;
5941 static HRESULT WINAPI winhttp_request_SetAutoLogonPolicy(
5942 IWinHttpRequest *iface,
5943 WinHttpRequestAutoLogonPolicy policy )
5945 struct winhttp_request *request = impl_from_IWinHttpRequest( iface );
5946 HRESULT hr = S_OK;
5948 TRACE("%p, %u\n", request, policy );
5950 EnterCriticalSection( &request->cs );
5951 switch (policy)
5953 case AutoLogonPolicy_Always:
5954 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
5955 break;
5956 case AutoLogonPolicy_OnlyIfBypassProxy:
5957 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
5958 break;
5959 case AutoLogonPolicy_Never:
5960 request->logon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
5961 break;
5962 default: hr = E_INVALIDARG;
5963 break;
5965 LeaveCriticalSection( &request->cs );
5966 return hr;
5969 static const struct IWinHttpRequestVtbl winhttp_request_vtbl =
5971 winhttp_request_QueryInterface,
5972 winhttp_request_AddRef,
5973 winhttp_request_Release,
5974 winhttp_request_GetTypeInfoCount,
5975 winhttp_request_GetTypeInfo,
5976 winhttp_request_GetIDsOfNames,
5977 winhttp_request_Invoke,
5978 winhttp_request_SetProxy,
5979 winhttp_request_SetCredentials,
5980 winhttp_request_Open,
5981 winhttp_request_SetRequestHeader,
5982 winhttp_request_GetResponseHeader,
5983 winhttp_request_GetAllResponseHeaders,
5984 winhttp_request_Send,
5985 winhttp_request_get_Status,
5986 winhttp_request_get_StatusText,
5987 winhttp_request_get_ResponseText,
5988 winhttp_request_get_ResponseBody,
5989 winhttp_request_get_ResponseStream,
5990 winhttp_request_get_Option,
5991 winhttp_request_put_Option,
5992 winhttp_request_WaitForResponse,
5993 winhttp_request_Abort,
5994 winhttp_request_SetTimeouts,
5995 winhttp_request_SetClientCertificate,
5996 winhttp_request_SetAutoLogonPolicy
5999 HRESULT WinHttpRequest_create( void **obj )
6001 struct winhttp_request *request;
6003 TRACE("%p\n", obj);
6005 if (!(request = calloc( 1, sizeof(*request) ))) return E_OUTOFMEMORY;
6006 request->IWinHttpRequest_iface.lpVtbl = &winhttp_request_vtbl;
6007 request->refs = 1;
6008 InitializeCriticalSection( &request->cs );
6009 request->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": winhttp_request.cs");
6010 initialize_request( request );
6012 *obj = &request->IWinHttpRequest_iface;
6013 TRACE("returning iface %p\n", *obj);
6014 return S_OK;