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
32 #include "httprequest.h"
33 #include "httprequestid.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 static DWORD
start_queue( struct queue
*queue
)
127 if (queue
->pool
) return ERROR_SUCCESS
;
129 if (!(queue
->pool
= CreateThreadpool( NULL
))) return GetLastError();
130 SetThreadpoolThreadMinimum( queue
->pool
, 1 );
131 SetThreadpoolThreadMaximum( queue
->pool
, 1 );
133 memset( &queue
->env
, 0, sizeof(queue
->env
) );
134 queue
->env
.Version
= 1;
135 queue
->env
.Pool
= queue
->pool
;
137 TRACE("started %p\n", queue
);
138 return ERROR_SUCCESS
;
141 void stop_queue( struct queue
*queue
)
143 if (!queue
->pool
) return;
144 CloseThreadpool( queue
->pool
);
146 TRACE("stopped %p\n", queue
);
149 static DWORD
queue_task( struct queue
*queue
, PTP_WORK_CALLBACK task
, void *ctx
)
154 if ((ret
= start_queue( queue
))) return ret
;
156 if (!(work
= CreateThreadpoolWork( task
, ctx
, &queue
->env
))) return GetLastError();
157 TRACE("queueing %p in %p\n", work
, queue
);
158 SubmitThreadpoolWork( work
);
159 CloseThreadpoolWork( work
);
161 return ERROR_SUCCESS
;
164 static void free_header( struct header
*header
)
166 free( header
->field
);
167 free( header
->value
);
171 static BOOL
valid_token_char( WCHAR c
)
173 if (c
< 32 || c
== 127) return FALSE
;
180 case '\\': case '\"':
192 static struct header
*parse_header( const WCHAR
*string
)
195 struct header
*header
;
199 if (!(q
= wcschr( p
, ':' )))
201 WARN("no ':' in line %s\n", debugstr_w(string
));
206 WARN("empty field name in line %s\n", debugstr_w(string
));
211 if (!valid_token_char( *p
))
213 WARN("invalid character in field name %s\n", debugstr_w(string
));
219 if (!(header
= calloc( 1, sizeof(*header
) ))) return NULL
;
220 if (!(header
->field
= malloc( (len
+ 1) * sizeof(WCHAR
) )))
225 memcpy( header
->field
, string
, len
* sizeof(WCHAR
) );
226 header
->field
[len
] = 0;
228 q
++; /* skip past colon */
229 while (*q
== ' ') q
++;
232 if (!(header
->value
= malloc( (len
+ 1) * sizeof(WCHAR
) )))
234 free_header( header
);
237 memcpy( header
->value
, q
, len
* sizeof(WCHAR
) );
238 header
->value
[len
] = 0;
243 static int get_header_index( struct request
*request
, const WCHAR
*field
, int requested_index
, BOOL request_only
)
247 TRACE("%s\n", debugstr_w(field
));
249 for (index
= 0; index
< request
->num_headers
; index
++)
251 if (wcsicmp( request
->headers
[index
].field
, field
)) continue;
252 if (request_only
&& !request
->headers
[index
].is_request
) continue;
253 if (!request_only
&& request
->headers
[index
].is_request
) continue;
255 if (!requested_index
) break;
258 if (index
>= request
->num_headers
) index
= -1;
259 TRACE("returning %d\n", index
);
263 static DWORD
insert_header( struct request
*request
, struct header
*header
)
265 DWORD count
= request
->num_headers
+ 1;
268 if (request
->headers
)
270 if ((hdrs
= realloc( request
->headers
, sizeof(*header
) * count
)))
271 memset( &hdrs
[count
- 1], 0, sizeof(*header
) );
273 else hdrs
= calloc( 1, sizeof(*header
) );
274 if (!hdrs
) return ERROR_OUTOFMEMORY
;
276 request
->headers
= hdrs
;
277 request
->headers
[count
- 1].field
= strdupW( header
->field
);
278 request
->headers
[count
- 1].value
= strdupW( header
->value
);
279 request
->headers
[count
- 1].is_request
= header
->is_request
;
280 request
->num_headers
= count
;
281 return ERROR_SUCCESS
;
284 static void delete_header( struct request
*request
, DWORD index
)
286 if (!request
->num_headers
|| index
>= request
->num_headers
) return;
287 request
->num_headers
--;
289 free( request
->headers
[index
].field
);
290 free( request
->headers
[index
].value
);
292 memmove( &request
->headers
[index
], &request
->headers
[index
+ 1],
293 (request
->num_headers
- index
) * sizeof(struct header
) );
294 memset( &request
->headers
[request
->num_headers
], 0, sizeof(struct header
) );
297 DWORD
process_header( struct request
*request
, const WCHAR
*field
, const WCHAR
*value
, DWORD flags
, BOOL request_only
)
302 TRACE("%s: %s 0x%08x\n", debugstr_w(field
), debugstr_w(value
), flags
);
304 if ((index
= get_header_index( request
, field
, 0, request_only
)) >= 0)
306 if (flags
& WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
) return ERROR_WINHTTP_HEADER_ALREADY_EXISTS
;
309 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
)
313 delete_header( request
, index
);
314 if (!value
|| !value
[0]) return ERROR_SUCCESS
;
316 else if (!(flags
& WINHTTP_ADDREQ_FLAG_ADD
)) return ERROR_WINHTTP_HEADER_NOT_FOUND
;
318 hdr
.field
= (LPWSTR
)field
;
319 hdr
.value
= (LPWSTR
)value
;
320 hdr
.is_request
= request_only
;
321 return insert_header( request
, &hdr
);
326 if ((flags
& (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
| WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
)) &&
330 int len
, len_orig
, len_value
;
331 struct header
*header
= &request
->headers
[index
];
333 len_orig
= lstrlenW( header
->value
);
334 len_value
= lstrlenW( value
);
336 len
= len_orig
+ len_value
+ 2;
337 if (!(tmp
= realloc( header
->value
, (len
+ 1) * sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
339 header
->value
[len_orig
++] = (flags
& WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
) ? ',' : ';';
340 header
->value
[len_orig
++] = ' ';
342 memcpy( &header
->value
[len_orig
], value
, len_value
* sizeof(WCHAR
) );
343 header
->value
[len
] = 0;
344 return ERROR_SUCCESS
;
348 hdr
.field
= (LPWSTR
)field
;
349 hdr
.value
= (LPWSTR
)value
;
350 hdr
.is_request
= request_only
;
351 return insert_header( request
, &hdr
);
355 return ERROR_SUCCESS
;
358 DWORD
add_request_headers( struct request
*request
, const WCHAR
*headers
, DWORD len
, DWORD flags
)
360 DWORD ret
= ERROR_WINHTTP_INVALID_HEADER
;
361 WCHAR
*buffer
, *p
, *q
;
362 struct header
*header
;
364 if (len
== ~0u) len
= lstrlenW( headers
);
365 if (!len
) return ERROR_SUCCESS
;
366 if (!(buffer
= malloc( (len
+ 1) * sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
367 memcpy( buffer
, headers
, len
* sizeof(WCHAR
) );
376 if (q
[0] == '\n' && q
[1] == '\r')
381 if (q
[0] == '\r') break;
389 q
+= 2; /* jump over \r\n */
391 q
++; /* jump over \r */
393 if ((header
= parse_header( p
)))
395 ret
= process_header( request
, header
->field
, header
->value
, flags
, TRUE
);
396 free_header( header
);
405 /***********************************************************************
406 * WinHttpAddRequestHeaders (winhttp.@)
408 BOOL WINAPI
WinHttpAddRequestHeaders( HINTERNET hrequest
, LPCWSTR headers
, DWORD len
, DWORD flags
)
411 struct request
*request
;
413 TRACE("%p, %s, %u, 0x%08x\n", hrequest
, debugstr_wn(headers
, len
), len
, flags
);
415 if (!headers
|| !len
)
417 SetLastError( ERROR_INVALID_PARAMETER
);
420 if (!(request
= (struct request
*)grab_object( hrequest
)))
422 SetLastError( ERROR_INVALID_HANDLE
);
425 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
427 release_object( &request
->hdr
);
428 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
432 ret
= add_request_headers( request
, headers
, len
, flags
);
434 release_object( &request
->hdr
);
439 static WCHAR
*build_absolute_request_path( struct request
*request
, const WCHAR
**path
)
445 scheme
= (request
->netconn
? request
->netconn
->secure
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)) ? L
"https" : L
"http";
447 len
= lstrlenW( scheme
) + lstrlenW( request
->connect
->hostname
) + 4; /* '://' + nul */
448 if (request
->connect
->hostport
) len
+= 6; /* ':' between host and port, up to 5 for port */
450 len
+= lstrlenW( request
->path
);
451 if ((ret
= malloc( len
* sizeof(WCHAR
) )))
453 offset
= swprintf( ret
, len
, L
"%s://%s", scheme
, request
->connect
->hostname
);
454 if (request
->connect
->hostport
)
456 offset
+= swprintf( ret
+ offset
, len
- offset
, L
":%u", request
->connect
->hostport
);
458 lstrcpyW( ret
+ offset
, request
->path
);
459 if (path
) *path
= ret
+ offset
;
465 static WCHAR
*build_request_string( struct request
*request
)
470 if (!wcsicmp( request
->connect
->hostname
, request
->connect
->servername
)) path
= request
->path
;
471 else if (!(path
= build_absolute_request_path( request
, NULL
))) return NULL
;
473 len
= lstrlenW( request
->verb
) + 1 /* ' ' */;
474 len
+= lstrlenW( path
) + 1 /* ' ' */;
475 len
+= lstrlenW( request
->version
);
477 for (i
= 0; i
< request
->num_headers
; i
++)
479 if (request
->headers
[i
].is_request
)
480 len
+= lstrlenW( request
->headers
[i
].field
) + lstrlenW( request
->headers
[i
].value
) + 4; /* '\r\n: ' */
482 len
+= 4; /* '\r\n\r\n' */
484 if ((ret
= malloc( (len
+ 1) * sizeof(WCHAR
) )))
486 lstrcpyW( ret
, request
->verb
);
487 lstrcatW( ret
, L
" " );
488 lstrcatW( ret
, path
);
489 lstrcatW( ret
, L
" " );
490 lstrcatW( ret
, request
->version
);
492 for (i
= 0; i
< request
->num_headers
; i
++)
494 if (request
->headers
[i
].is_request
)
496 lstrcatW( ret
, L
"\r\n" );
497 lstrcatW( ret
, request
->headers
[i
].field
);
498 lstrcatW( ret
, L
": " );
499 lstrcatW( ret
, request
->headers
[i
].value
);
502 lstrcatW( ret
, L
"\r\n\r\n" );
505 if (path
!= request
->path
) free( path
);
509 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
511 static DWORD
query_headers( struct request
*request
, DWORD level
, const WCHAR
*name
, void *buffer
, DWORD
*buflen
,
514 struct header
*header
= NULL
;
516 int requested_index
, header_index
= -1;
517 DWORD attr
, len
, ret
= ERROR_WINHTTP_HEADER_NOT_FOUND
;
519 request_only
= level
& WINHTTP_QUERY_FLAG_REQUEST_HEADERS
;
520 requested_index
= index
? *index
: 0;
522 attr
= level
& ~QUERY_MODIFIER_MASK
;
525 case WINHTTP_QUERY_CUSTOM
:
527 header_index
= get_header_index( request
, name
, requested_index
, request_only
);
530 case WINHTTP_QUERY_RAW_HEADERS
:
532 WCHAR
*headers
, *p
, *q
;
535 headers
= build_request_string( request
);
537 headers
= request
->raw_headers
;
539 if (!(p
= headers
)) return ERROR_OUTOFMEMORY
;
540 for (len
= 0; *p
; p
++) if (*p
!= '\r') len
++;
542 if (!buffer
|| len
* sizeof(WCHAR
) > *buflen
) ret
= ERROR_INSUFFICIENT_BUFFER
;
545 for (p
= headers
, q
= buffer
; *p
; p
++, q
++)
547 if (*p
!= '\r') *q
= *p
;
554 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
));
558 *buflen
= len
* sizeof(WCHAR
);
559 if (request_only
) free( headers
);
562 case WINHTTP_QUERY_RAW_HEADERS_CRLF
:
567 headers
= build_request_string( request
);
569 headers
= request
->raw_headers
;
571 if (!headers
) return ERROR_OUTOFMEMORY
;
572 len
= lstrlenW( headers
) * sizeof(WCHAR
);
573 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
575 len
+= sizeof(WCHAR
);
576 ret
= ERROR_INSUFFICIENT_BUFFER
;
580 memcpy( buffer
, headers
, len
+ sizeof(WCHAR
) );
581 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
/ sizeof(WCHAR
)));
585 if (request_only
) free( headers
);
588 case WINHTTP_QUERY_VERSION
:
589 len
= lstrlenW( request
->version
) * sizeof(WCHAR
);
590 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
592 len
+= sizeof(WCHAR
);
593 ret
= ERROR_INSUFFICIENT_BUFFER
;
597 lstrcpyW( buffer
, request
->version
);
598 TRACE("returning string: %s\n", debugstr_w(buffer
));
604 case WINHTTP_QUERY_STATUS_TEXT
:
605 len
= lstrlenW( request
->status_text
) * sizeof(WCHAR
);
606 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
608 len
+= sizeof(WCHAR
);
609 ret
= ERROR_INSUFFICIENT_BUFFER
;
613 lstrcpyW( buffer
, request
->status_text
);
614 TRACE("returning string: %s\n", debugstr_w(buffer
));
620 case WINHTTP_QUERY_REQUEST_METHOD
:
621 len
= lstrlenW( request
->verb
) * sizeof(WCHAR
);
622 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
624 len
+= sizeof(WCHAR
);
625 ret
= ERROR_INSUFFICIENT_BUFFER
;
629 lstrcpyW( buffer
, request
->verb
);
630 TRACE("returning string: %s\n", debugstr_w(buffer
));
637 if (attr
>= ARRAY_SIZE(attribute_table
)) return ERROR_INVALID_PARAMETER
;
638 if (!attribute_table
[attr
])
640 FIXME("attribute %u not implemented\n", attr
);
641 return ERROR_WINHTTP_HEADER_NOT_FOUND
;
643 TRACE("attribute %s\n", debugstr_w(attribute_table
[attr
]));
644 header_index
= get_header_index( request
, attribute_table
[attr
], requested_index
, request_only
);
648 if (header_index
>= 0)
650 header
= &request
->headers
[header_index
];
652 if (!header
|| (request_only
&& !header
->is_request
)) return ERROR_WINHTTP_HEADER_NOT_FOUND
;
653 if (level
& WINHTTP_QUERY_FLAG_NUMBER
)
655 if (!buffer
|| sizeof(int) > *buflen
) ret
= ERROR_INSUFFICIENT_BUFFER
;
658 int *number
= buffer
;
659 *number
= wcstol( header
->value
, NULL
, 10 );
660 TRACE("returning number: %d\n", *number
);
663 *buflen
= sizeof(int);
665 else if (level
& WINHTTP_QUERY_FLAG_SYSTEMTIME
)
667 SYSTEMTIME
*st
= buffer
;
668 if (!buffer
|| sizeof(SYSTEMTIME
) > *buflen
) ret
= ERROR_INSUFFICIENT_BUFFER
;
669 else if (WinHttpTimeToSystemTime( header
->value
, st
))
671 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
672 st
->wYear
, st
->wMonth
, st
->wDay
, st
->wDayOfWeek
,
673 st
->wHour
, st
->wMinute
, st
->wSecond
, st
->wMilliseconds
);
676 *buflen
= sizeof(SYSTEMTIME
);
678 else if (header
->value
)
680 len
= lstrlenW( header
->value
) * sizeof(WCHAR
);
681 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
683 len
+= sizeof(WCHAR
);
684 ret
= ERROR_INSUFFICIENT_BUFFER
;
688 lstrcpyW( buffer
, header
->value
);
689 TRACE("returning string: %s\n", debugstr_w(buffer
));
694 if (!ret
&& index
) *index
+= 1;
698 /***********************************************************************
699 * WinHttpQueryHeaders (winhttp.@)
701 BOOL WINAPI
WinHttpQueryHeaders( HINTERNET hrequest
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
704 struct request
*request
;
706 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest
, level
, debugstr_w(name
), buffer
, buflen
, index
);
708 if (!(request
= (struct request
*)grab_object( hrequest
)))
710 SetLastError( ERROR_INVALID_HANDLE
);
713 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
715 release_object( &request
->hdr
);
716 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
720 ret
= query_headers( request
, level
, name
, buffer
, buflen
, index
);
722 release_object( &request
->hdr
);
735 { L
"Basic", ARRAY_SIZE(L
"Basic") - 1, WINHTTP_AUTH_SCHEME_BASIC
},
736 { L
"NTLM", ARRAY_SIZE(L
"NTLM") - 1, WINHTTP_AUTH_SCHEME_NTLM
},
737 { L
"Passport", ARRAY_SIZE(L
"Passport") - 1, WINHTTP_AUTH_SCHEME_PASSPORT
},
738 { L
"Digest", ARRAY_SIZE(L
"Digest") - 1, WINHTTP_AUTH_SCHEME_DIGEST
},
739 { L
"Negotiate", ARRAY_SIZE(L
"Negotiate") - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE
}
742 static enum auth_scheme
scheme_from_flag( DWORD flag
)
746 for (i
= 0; i
< ARRAY_SIZE( auth_schemes
); i
++) if (flag
== auth_schemes
[i
].scheme
) return i
;
747 return SCHEME_INVALID
;
750 static DWORD
auth_scheme_from_header( const WCHAR
*header
)
754 for (i
= 0; i
< ARRAY_SIZE( auth_schemes
); i
++)
756 if (!wcsnicmp( header
, auth_schemes
[i
].str
, auth_schemes
[i
].len
) &&
757 (header
[auth_schemes
[i
].len
] == ' ' || !header
[auth_schemes
[i
].len
])) return auth_schemes
[i
].scheme
;
762 static DWORD
query_auth_schemes( struct request
*request
, DWORD level
, DWORD
*supported
, DWORD
*first
)
764 DWORD ret
, index
= 0, supported_schemes
= 0, first_scheme
= 0;
772 ret
= query_headers( request
, level
, NULL
, NULL
, &size
, &index
);
773 if (ret
!= ERROR_INSUFFICIENT_BUFFER
)
775 if (index
) ret
= ERROR_SUCCESS
;
779 if (!(buffer
= malloc( size
))) return ERROR_OUTOFMEMORY
;
780 if ((ret
= query_headers( request
, level
, NULL
, buffer
, &size
, &index
)))
785 scheme
= auth_scheme_from_header( buffer
);
787 if (!scheme
) continue;
789 if (!first_scheme
) first_scheme
= scheme
;
790 supported_schemes
|= scheme
;
795 *supported
= supported_schemes
;
796 *first
= first_scheme
;
801 /***********************************************************************
802 * WinHttpQueryAuthSchemes (winhttp.@)
804 BOOL WINAPI
WinHttpQueryAuthSchemes( HINTERNET hrequest
, LPDWORD supported
, LPDWORD first
, LPDWORD target
)
807 struct request
*request
;
809 TRACE("%p, %p, %p, %p\n", hrequest
, supported
, first
, target
);
811 if (!(request
= (struct request
*)grab_object( hrequest
)))
813 SetLastError( ERROR_INVALID_HANDLE
);
816 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
818 release_object( &request
->hdr
);
819 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
822 if (!supported
|| !first
|| !target
)
824 release_object( &request
->hdr
);
825 SetLastError( ERROR_INVALID_PARAMETER
);
830 if (!(ret
= query_auth_schemes( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, supported
, first
)))
832 *target
= WINHTTP_AUTH_TARGET_SERVER
;
834 else if (!(ret
= query_auth_schemes( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, supported
, first
)))
836 *target
= WINHTTP_AUTH_TARGET_PROXY
;
838 else ret
= ERROR_INVALID_OPERATION
;
840 release_object( &request
->hdr
);
845 static UINT
encode_base64( const char *bin
, unsigned int len
, WCHAR
*base64
)
848 static const char base64enc
[] =
849 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
853 /* first 6 bits, all from bin[0] */
854 base64
[n
++] = base64enc
[(bin
[0] & 0xfc) >> 2];
855 x
= (bin
[0] & 3) << 4;
857 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
860 base64
[n
++] = base64enc
[x
];
865 base64
[n
++] = base64enc
[x
| ((bin
[1] & 0xf0) >> 4)];
866 x
= (bin
[1] & 0x0f) << 2;
868 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
871 base64
[n
++] = base64enc
[x
];
875 base64
[n
++] = base64enc
[x
| ((bin
[2] & 0xc0) >> 6)];
877 /* last 6 bits, all from bin [2] */
878 base64
[n
++] = base64enc
[bin
[2] & 0x3f];
886 static inline char decode_char( WCHAR c
)
888 if (c
>= 'A' && c
<= 'Z') return c
- 'A';
889 if (c
>= 'a' && c
<= 'z') return c
- 'a' + 26;
890 if (c
>= '0' && c
<= '9') return c
- '0' + 52;
891 if (c
== '+') return 62;
892 if (c
== '/') return 63;
896 static unsigned int decode_base64( const WCHAR
*base64
, unsigned int len
, char *buf
)
900 const WCHAR
*p
= base64
;
904 if ((c0
= decode_char( p
[0] )) > 63) return 0;
905 if ((c1
= decode_char( p
[1] )) > 63) return 0;
906 if ((c2
= decode_char( p
[2] )) > 63) return 0;
907 if ((c3
= decode_char( p
[3] )) > 63) return 0;
911 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
912 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
913 buf
[i
+ 2] = (c2
<< 6) | c3
;
921 if ((c0
= decode_char( p
[0] )) > 63) return 0;
922 if ((c1
= decode_char( p
[1] )) > 63) return 0;
924 if (buf
) buf
[i
] = (c0
<< 2) | (c1
>> 4);
927 else if (p
[3] == '=')
929 if ((c0
= decode_char( p
[0] )) > 63) return 0;
930 if ((c1
= decode_char( p
[1] )) > 63) return 0;
931 if ((c2
= decode_char( p
[2] )) > 63) return 0;
935 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
936 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
942 if ((c0
= decode_char( p
[0] )) > 63) return 0;
943 if ((c1
= decode_char( p
[1] )) > 63) return 0;
944 if ((c2
= decode_char( p
[2] )) > 63) return 0;
945 if ((c3
= decode_char( p
[3] )) > 63) return 0;
949 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
950 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
951 buf
[i
+ 2] = (c2
<< 6) | c3
;
958 static struct authinfo
*alloc_authinfo(void)
960 struct authinfo
*ret
;
962 if (!(ret
= malloc( sizeof(*ret
) ))) return NULL
;
964 SecInvalidateHandle( &ret
->cred
);
965 SecInvalidateHandle( &ret
->ctx
);
966 memset( &ret
->exp
, 0, sizeof(ret
->exp
) );
972 ret
->finished
= FALSE
;
976 void destroy_authinfo( struct authinfo
*authinfo
)
978 if (!authinfo
) return;
980 if (SecIsValidHandle( &authinfo
->ctx
))
981 DeleteSecurityContext( &authinfo
->ctx
);
982 if (SecIsValidHandle( &authinfo
->cred
))
983 FreeCredentialsHandle( &authinfo
->cred
);
985 free( authinfo
->data
);
989 static BOOL
get_authvalue( struct request
*request
, DWORD level
, DWORD scheme
, WCHAR
*buffer
, DWORD len
)
991 DWORD size
, index
= 0;
995 if (query_headers( request
, level
, NULL
, buffer
, &size
, &index
)) return FALSE
;
996 if (auth_scheme_from_header( buffer
) == scheme
) break;
1001 static BOOL
do_authorization( struct request
*request
, DWORD target
, DWORD scheme_flag
)
1003 struct authinfo
*authinfo
, **auth_ptr
;
1004 enum auth_scheme scheme
= scheme_from_flag( scheme_flag
);
1005 const WCHAR
*auth_target
, *username
, *password
;
1006 WCHAR auth_value
[2048], *auth_reply
;
1007 DWORD len
= sizeof(auth_value
), len_scheme
, flags
;
1008 BOOL ret
, has_auth_value
;
1010 if (scheme
== SCHEME_INVALID
) return FALSE
;
1014 case WINHTTP_AUTH_TARGET_SERVER
:
1015 has_auth_value
= get_authvalue( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, scheme_flag
, auth_value
, len
);
1016 auth_ptr
= &request
->authinfo
;
1017 auth_target
= L
"Authorization";
1018 if (request
->creds
[TARGET_SERVER
][scheme
].username
)
1020 if (scheme
!= SCHEME_BASIC
&& !has_auth_value
) return FALSE
;
1021 username
= request
->creds
[TARGET_SERVER
][scheme
].username
;
1022 password
= request
->creds
[TARGET_SERVER
][scheme
].password
;
1026 if (!has_auth_value
) return FALSE
;
1027 username
= request
->connect
->username
;
1028 password
= request
->connect
->password
;
1032 case WINHTTP_AUTH_TARGET_PROXY
:
1033 if (!get_authvalue( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1035 auth_ptr
= &request
->proxy_authinfo
;
1036 auth_target
= L
"Proxy-Authorization";
1037 if (request
->creds
[TARGET_PROXY
][scheme
].username
)
1039 username
= request
->creds
[TARGET_PROXY
][scheme
].username
;
1040 password
= request
->creds
[TARGET_PROXY
][scheme
].password
;
1044 username
= request
->connect
->session
->proxy_username
;
1045 password
= request
->connect
->session
->proxy_password
;
1050 WARN("unknown target %x\n", target
);
1053 authinfo
= *auth_ptr
;
1059 int userlen
, passlen
;
1061 if (!username
|| !password
) return FALSE
;
1062 if ((!authinfo
&& !(authinfo
= alloc_authinfo())) || authinfo
->finished
) return FALSE
;
1064 userlen
= WideCharToMultiByte( CP_UTF8
, 0, username
, lstrlenW( username
), NULL
, 0, NULL
, NULL
);
1065 passlen
= WideCharToMultiByte( CP_UTF8
, 0, password
, lstrlenW( password
), NULL
, 0, NULL
, NULL
);
1067 authinfo
->data_len
= userlen
+ 1 + passlen
;
1068 if (!(authinfo
->data
= malloc( authinfo
->data_len
))) return FALSE
;
1070 WideCharToMultiByte( CP_UTF8
, 0, username
, -1, authinfo
->data
, userlen
, NULL
, NULL
);
1071 authinfo
->data
[userlen
] = ':';
1072 WideCharToMultiByte( CP_UTF8
, 0, password
, -1, authinfo
->data
+ userlen
+ 1, passlen
, NULL
, NULL
);
1074 authinfo
->scheme
= SCHEME_BASIC
;
1075 authinfo
->finished
= TRUE
;
1079 case SCHEME_NEGOTIATE
:
1081 SECURITY_STATUS status
;
1082 SecBufferDesc out_desc
, in_desc
;
1084 ULONG flags
= ISC_REQ_CONNECTION
|ISC_REQ_USE_DCE_STYLE
|ISC_REQ_MUTUAL_AUTH
|ISC_REQ_DELEGATE
;
1091 SEC_WINNT_AUTH_IDENTITY_W id
;
1092 WCHAR
*domain
, *user
;
1094 if (!username
|| !password
|| !(authinfo
= alloc_authinfo())) return FALSE
;
1097 domain
= (WCHAR
*)username
;
1098 user
= wcschr( username
, '\\' );
1103 user
= (WCHAR
*)username
;
1106 id
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1108 id
.UserLength
= lstrlenW( user
);
1110 id
.DomainLength
= domain
? user
- domain
- 1 : 0;
1111 id
.Password
= (WCHAR
*)password
;
1112 id
.PasswordLength
= lstrlenW( password
);
1114 status
= AcquireCredentialsHandleW( NULL
, (SEC_WCHAR
*)auth_schemes
[scheme
].str
,
1115 SECPKG_CRED_OUTBOUND
, NULL
, &id
, NULL
, NULL
,
1116 &authinfo
->cred
, &exp
);
1117 if (status
== SEC_E_OK
)
1120 status
= QuerySecurityPackageInfoW( (SEC_WCHAR
*)auth_schemes
[scheme
].str
, &info
);
1121 if (status
== SEC_E_OK
)
1123 authinfo
->max_token
= info
->cbMaxToken
;
1124 FreeContextBuffer( info
);
1127 if (status
!= SEC_E_OK
)
1129 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1130 debugstr_w(auth_schemes
[scheme
].str
), status
);
1134 authinfo
->scheme
= scheme
;
1136 else if (authinfo
->finished
) return FALSE
;
1138 if ((lstrlenW( auth_value
) < auth_schemes
[authinfo
->scheme
].len
||
1139 wcsnicmp( auth_value
, auth_schemes
[authinfo
->scheme
].str
, auth_schemes
[authinfo
->scheme
].len
)))
1141 ERR("authentication scheme changed from %s to %s\n",
1142 debugstr_w(auth_schemes
[authinfo
->scheme
].str
), debugstr_w(auth_value
));
1143 destroy_authinfo( authinfo
);
1147 in
.BufferType
= SECBUFFER_TOKEN
;
1151 in_desc
.ulVersion
= 0;
1152 in_desc
.cBuffers
= 1;
1153 in_desc
.pBuffers
= &in
;
1155 p
= auth_value
+ auth_schemes
[scheme
].len
;
1158 int len
= lstrlenW( ++p
);
1159 in
.cbBuffer
= decode_base64( p
, len
, NULL
);
1160 if (!(in
.pvBuffer
= malloc( in
.cbBuffer
))) {
1161 destroy_authinfo( authinfo
);
1165 decode_base64( p
, len
, in
.pvBuffer
);
1167 out
.BufferType
= SECBUFFER_TOKEN
;
1168 out
.cbBuffer
= authinfo
->max_token
;
1169 if (!(out
.pvBuffer
= malloc( authinfo
->max_token
)))
1171 free( in
.pvBuffer
);
1172 destroy_authinfo( authinfo
);
1176 out_desc
.ulVersion
= 0;
1177 out_desc
.cBuffers
= 1;
1178 out_desc
.pBuffers
= &out
;
1180 status
= InitializeSecurityContextW( first
? &authinfo
->cred
: NULL
, first
? NULL
: &authinfo
->ctx
,
1181 first
? request
->connect
->servername
: NULL
, flags
, 0,
1182 SECURITY_NETWORK_DREP
, in
.pvBuffer
? &in_desc
: NULL
, 0,
1183 &authinfo
->ctx
, &out_desc
, &authinfo
->attr
, &authinfo
->exp
);
1184 free( in
.pvBuffer
);
1185 if (status
== SEC_E_OK
)
1187 free( authinfo
->data
);
1188 authinfo
->data
= out
.pvBuffer
;
1189 authinfo
->data_len
= out
.cbBuffer
;
1190 authinfo
->finished
= TRUE
;
1191 TRACE("sending last auth packet\n");
1193 else if (status
== SEC_I_CONTINUE_NEEDED
)
1195 free( authinfo
->data
);
1196 authinfo
->data
= out
.pvBuffer
;
1197 authinfo
->data_len
= out
.cbBuffer
;
1198 TRACE("sending next auth packet\n");
1202 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status
);
1203 free( out
.pvBuffer
);
1204 destroy_authinfo( authinfo
);
1211 ERR("invalid scheme %u\n", scheme
);
1214 *auth_ptr
= authinfo
;
1216 len_scheme
= auth_schemes
[authinfo
->scheme
].len
;
1217 len
= len_scheme
+ 1 + ((authinfo
->data_len
+ 2) * 4) / 3;
1218 if (!(auth_reply
= malloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
1220 memcpy( auth_reply
, auth_schemes
[authinfo
->scheme
].str
, len_scheme
* sizeof(WCHAR
) );
1221 auth_reply
[len_scheme
] = ' ';
1222 encode_base64( authinfo
->data
, authinfo
->data_len
, auth_reply
+ len_scheme
+ 1 );
1224 flags
= WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
;
1225 ret
= !process_header( request
, auth_target
, auth_reply
, flags
, TRUE
);
1230 static WCHAR
*build_proxy_connect_string( struct request
*request
)
1234 int len
= lstrlenW( request
->connect
->hostname
) + 7;
1236 if (!(host
= malloc( len
* sizeof(WCHAR
) ))) return NULL
;
1237 len
= swprintf( host
, len
, L
"%s:%u", request
->connect
->hostname
, request
->connect
->hostport
);
1239 len
+= ARRAY_SIZE(L
"CONNECT");
1240 len
+= ARRAY_SIZE(L
"HTTP/1.1");
1242 for (i
= 0; i
< request
->num_headers
; i
++)
1244 if (request
->headers
[i
].is_request
)
1245 len
+= lstrlenW( request
->headers
[i
].field
) + lstrlenW( request
->headers
[i
].value
) + 4; /* '\r\n: ' */
1247 len
+= 4; /* '\r\n\r\n' */
1249 if ((ret
= malloc( (len
+ 1) * sizeof(WCHAR
) )))
1251 lstrcpyW( ret
, L
"CONNECT" );
1252 lstrcatW( ret
, L
" " );
1253 lstrcatW( ret
, host
);
1254 lstrcatW( ret
, L
" " );
1255 lstrcatW( ret
, L
"HTTP/1.1" );
1257 for (i
= 0; i
< request
->num_headers
; i
++)
1259 if (request
->headers
[i
].is_request
)
1261 lstrcatW( ret
, L
"\r\n" );
1262 lstrcatW( ret
, request
->headers
[i
].field
);
1263 lstrcatW( ret
, L
": " );
1264 lstrcatW( ret
, request
->headers
[i
].value
);
1267 lstrcatW( ret
, L
"\r\n\r\n" );
1274 static DWORD
read_reply( struct request
*request
);
1276 static DWORD
secure_proxy_connect( struct request
*request
)
1280 int len
, bytes_sent
;
1283 if (!(str
= build_proxy_connect_string( request
))) return ERROR_OUTOFMEMORY
;
1284 strA
= strdupWA( str
);
1286 if (!strA
) return ERROR_OUTOFMEMORY
;
1288 len
= strlen( strA
);
1289 ret
= netconn_send( request
->netconn
, strA
, len
, &bytes_sent
, NULL
);
1291 if (!ret
) ret
= read_reply( request
);
1296 static WCHAR
*addr_to_str( struct sockaddr_storage
*addr
)
1298 char buf
[INET6_ADDRSTRLEN
];
1301 switch (addr
->ss_family
)
1304 src
= &((struct sockaddr_in
*)addr
)->sin_addr
;
1307 src
= &((struct sockaddr_in6
*)addr
)->sin6_addr
;
1310 WARN("unsupported address family %d\n", addr
->ss_family
);
1313 if (!inet_ntop( addr
->ss_family
, src
, buf
, sizeof(buf
) )) return NULL
;
1314 return strdupAW( buf
);
1317 static CRITICAL_SECTION connection_pool_cs
;
1318 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
1320 0, 0, &connection_pool_cs
,
1321 { &connection_pool_debug
.ProcessLocksList
, &connection_pool_debug
.ProcessLocksList
},
1322 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
1324 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
1326 static struct list connection_pool
= LIST_INIT( connection_pool
);
1328 void release_host( struct hostdata
*host
)
1332 EnterCriticalSection( &connection_pool_cs
);
1333 if (!(ref
= --host
->ref
)) list_remove( &host
->entry
);
1334 LeaveCriticalSection( &connection_pool_cs
);
1337 assert( list_empty( &host
->connections
) );
1338 free( host
->hostname
);
1342 static BOOL connection_collector_running
;
1344 static void CALLBACK
connection_collector( TP_CALLBACK_INSTANCE
*instance
, void *ctx
)
1346 unsigned int remaining_connections
;
1347 struct netconn
*netconn
, *next_netconn
;
1348 struct hostdata
*host
, *next_host
;
1353 /* FIXME: Use more sophisticated method */
1355 remaining_connections
= 0;
1356 now
= GetTickCount64();
1358 EnterCriticalSection(&connection_pool_cs
);
1360 LIST_FOR_EACH_ENTRY_SAFE(host
, next_host
, &connection_pool
, struct hostdata
, entry
)
1362 LIST_FOR_EACH_ENTRY_SAFE(netconn
, next_netconn
, &host
->connections
, struct netconn
, entry
)
1364 if (netconn
->keep_until
< now
)
1366 TRACE("freeing %p\n", netconn
);
1367 list_remove(&netconn
->entry
);
1368 netconn_close(netconn
);
1370 else remaining_connections
++;
1374 if (!remaining_connections
) connection_collector_running
= FALSE
;
1376 LeaveCriticalSection(&connection_pool_cs
);
1377 } while(remaining_connections
);
1379 FreeLibraryWhenCallbackReturns( instance
, winhttp_instance
);
1382 static void cache_connection( struct netconn
*netconn
)
1384 TRACE( "caching connection %p\n", netconn
);
1386 EnterCriticalSection( &connection_pool_cs
);
1388 netconn
->keep_until
= GetTickCount64() + DEFAULT_KEEP_ALIVE_TIMEOUT
;
1389 list_add_head( &netconn
->host
->connections
, &netconn
->entry
);
1391 if (!connection_collector_running
)
1395 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)winhttp_instance
, &module
);
1397 if (TrySubmitThreadpoolCallback( connection_collector
, NULL
, NULL
)) connection_collector_running
= TRUE
;
1398 else FreeLibrary( winhttp_instance
);
1401 LeaveCriticalSection( &connection_pool_cs
);
1404 static DWORD
map_secure_protocols( DWORD mask
)
1407 if (mask
& WINHTTP_FLAG_SECURE_PROTOCOL_SSL2
) ret
|= SP_PROT_SSL2_CLIENT
;
1408 if (mask
& WINHTTP_FLAG_SECURE_PROTOCOL_SSL3
) ret
|= SP_PROT_SSL3_CLIENT
;
1409 if (mask
& WINHTTP_FLAG_SECURE_PROTOCOL_TLS1
) ret
|= SP_PROT_TLS1_CLIENT
;
1410 if (mask
& WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1
) ret
|= SP_PROT_TLS1_1_CLIENT
;
1411 if (mask
& WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2
) ret
|= SP_PROT_TLS1_2_CLIENT
;
1415 static DWORD
ensure_cred_handle( struct request
*request
)
1417 SECURITY_STATUS status
= SEC_E_OK
;
1419 if (request
->cred_handle_initialized
) return ERROR_SUCCESS
;
1421 if (!request
->cred_handle_initialized
)
1424 memset( &cred
, 0, sizeof(cred
) );
1425 cred
.dwVersion
= SCHANNEL_CRED_VERSION
;
1426 cred
.grbitEnabledProtocols
= map_secure_protocols( request
->connect
->session
->secure_protocols
);
1427 if (request
->client_cert
)
1429 cred
.paCred
= &request
->client_cert
;
1432 status
= AcquireCredentialsHandleW( NULL
, (WCHAR
*)UNISP_NAME_W
, SECPKG_CRED_OUTBOUND
, NULL
,
1433 &cred
, NULL
, NULL
, &request
->cred_handle
, NULL
);
1434 if (status
== SEC_E_OK
)
1435 request
->cred_handle_initialized
= TRUE
;
1438 if (status
!= SEC_E_OK
)
1440 WARN( "AcquireCredentialsHandleW failed: 0x%08x\n", status
);
1443 return ERROR_SUCCESS
;
1446 static DWORD
open_connection( struct request
*request
)
1448 BOOL is_secure
= request
->hdr
.flags
& WINHTTP_FLAG_SECURE
;
1449 struct hostdata
*host
= NULL
, *iter
;
1450 struct netconn
*netconn
= NULL
;
1451 struct connect
*connect
;
1452 WCHAR
*addressW
= NULL
;
1456 if (request
->netconn
) goto done
;
1458 connect
= request
->connect
;
1459 port
= connect
->serverport
? connect
->serverport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
1461 EnterCriticalSection( &connection_pool_cs
);
1463 LIST_FOR_EACH_ENTRY( iter
, &connection_pool
, struct hostdata
, entry
)
1465 if (iter
->port
== port
&& !wcscmp( connect
->servername
, iter
->hostname
) && !is_secure
== !iter
->secure
)
1475 if ((host
= malloc( sizeof(*host
) )))
1478 host
->secure
= is_secure
;
1480 list_init( &host
->connections
);
1481 if ((host
->hostname
= strdupW( connect
->servername
)))
1483 list_add_head( &connection_pool
, &host
->entry
);
1493 LeaveCriticalSection( &connection_pool_cs
);
1495 if (!host
) return ERROR_OUTOFMEMORY
;
1499 EnterCriticalSection( &connection_pool_cs
);
1500 if (!list_empty( &host
->connections
))
1502 netconn
= LIST_ENTRY( list_head( &host
->connections
), struct netconn
, entry
);
1503 list_remove( &netconn
->entry
);
1505 LeaveCriticalSection( &connection_pool_cs
);
1506 if (!netconn
) break;
1508 if (netconn_is_alive( netconn
)) break;
1509 TRACE("connection %p no longer alive, closing\n", netconn
);
1510 netconn_close( netconn
);
1514 if (!connect
->resolved
&& netconn
)
1516 connect
->sockaddr
= netconn
->sockaddr
;
1517 connect
->resolved
= TRUE
;
1520 if (!connect
->resolved
)
1522 len
= lstrlenW( host
->hostname
) + 1;
1523 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME
, host
->hostname
, len
);
1525 if ((ret
= netconn_resolve( host
->hostname
, port
, &connect
->sockaddr
, request
->resolve_timeout
)))
1527 release_host( host
);
1530 connect
->resolved
= TRUE
;
1532 if (!(addressW
= addr_to_str( &connect
->sockaddr
)))
1534 release_host( host
);
1535 return ERROR_OUTOFMEMORY
;
1537 len
= lstrlenW( addressW
) + 1;
1538 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED
, addressW
, len
);
1543 if (!addressW
&& !(addressW
= addr_to_str( &connect
->sockaddr
)))
1545 release_host( host
);
1546 return ERROR_OUTOFMEMORY
;
1549 TRACE("connecting to %s:%u\n", debugstr_w(addressW
), port
);
1551 len
= lstrlenW( addressW
) + 1;
1552 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER
, addressW
, len
);
1554 if ((ret
= netconn_create( host
, &connect
->sockaddr
, request
->connect_timeout
, &netconn
)))
1557 release_host( host
);
1560 netconn_set_timeout( netconn
, TRUE
, request
->send_timeout
);
1561 netconn_set_timeout( netconn
, FALSE
, request
->receive_response_timeout
);
1563 request
->netconn
= netconn
;
1567 if (connect
->session
->proxy_server
&& wcsicmp( connect
->hostname
, connect
->servername
))
1569 if ((ret
= secure_proxy_connect( request
)))
1571 request
->netconn
= NULL
;
1573 netconn_close( netconn
);
1578 CertFreeCertificateContext( request
->server_cert
);
1579 request
->server_cert
= NULL
;
1581 if ((ret
= ensure_cred_handle( request
)) ||
1582 (ret
= netconn_secure_connect( netconn
, connect
->hostname
, request
->security_flags
,
1583 &request
->cred_handle
, request
->check_revocation
)))
1585 request
->netconn
= NULL
;
1587 netconn_close( netconn
);
1592 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER
, addressW
, lstrlenW(addressW
) + 1 );
1596 TRACE("using connection %p\n", netconn
);
1598 netconn_set_timeout( netconn
, TRUE
, request
->send_timeout
);
1599 netconn_set_timeout( netconn
, FALSE
, request
->receive_response_timeout
);
1600 request
->netconn
= netconn
;
1603 if (netconn
->secure
&& !(request
->server_cert
= netconn_get_certificate( netconn
)))
1606 netconn_close( netconn
);
1607 return ERROR_WINHTTP_SECURE_FAILURE
;
1611 request
->read_pos
= request
->read_size
= 0;
1612 request
->read_chunked
= FALSE
;
1613 request
->read_chunked_size
= ~0u;
1614 request
->read_chunked_eof
= FALSE
;
1616 return ERROR_SUCCESS
;
1619 void close_connection( struct request
*request
)
1621 if (!request
->netconn
) return;
1623 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION
, 0, 0 );
1624 netconn_close( request
->netconn
);
1625 request
->netconn
= NULL
;
1626 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED
, 0, 0 );
1629 static DWORD
add_host_header( struct request
*request
, DWORD modifier
)
1633 struct connect
*connect
= request
->connect
;
1636 port
= connect
->hostport
? connect
->hostport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
1638 if (port
== INTERNET_DEFAULT_HTTP_PORT
|| port
== INTERNET_DEFAULT_HTTPS_PORT
)
1640 return process_header( request
, L
"Host", connect
->hostname
, modifier
, TRUE
);
1642 len
= lstrlenW( connect
->hostname
) + 7; /* sizeof(":65335") */
1643 if (!(host
= malloc( len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
1644 swprintf( host
, len
, L
"%s:%u", connect
->hostname
, port
);
1645 ret
= process_header( request
, L
"Host", host
, modifier
, TRUE
);
1650 static void clear_response_headers( struct request
*request
)
1654 for (i
= 0; i
< request
->num_headers
; i
++)
1656 if (!request
->headers
[i
].field
) continue;
1657 if (!request
->headers
[i
].value
) continue;
1658 if (request
->headers
[i
].is_request
) continue;
1659 delete_header( request
, i
);
1664 /* remove some amount of data from the read buffer */
1665 static void remove_data( struct request
*request
, int count
)
1667 if (!(request
->read_size
-= count
)) request
->read_pos
= 0;
1668 else request
->read_pos
+= count
;
1671 /* read some more data into the read buffer */
1672 static DWORD
read_more_data( struct request
*request
, int maxlen
, BOOL notify
)
1677 if (request
->read_chunked_eof
) return ERROR_INSUFFICIENT_BUFFER
;
1679 if (request
->read_size
&& request
->read_pos
)
1681 /* move existing data to the start of the buffer */
1682 memmove( request
->read_buf
, request
->read_buf
+ request
->read_pos
, request
->read_size
);
1683 request
->read_pos
= 0;
1685 if (maxlen
== -1) maxlen
= sizeof(request
->read_buf
);
1687 if (notify
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE
, NULL
, 0 );
1689 ret
= netconn_recv( request
->netconn
, request
->read_buf
+ request
->read_size
,
1690 maxlen
- request
->read_size
, 0, &len
);
1692 if (notify
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED
, &len
, sizeof(len
) );
1694 request
->read_size
+= len
;
1698 /* discard data contents until we reach end of line */
1699 static DWORD
discard_eol( struct request
*request
, BOOL notify
)
1704 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1707 remove_data( request
, (eol
+ 1) - (request
->read_buf
+ request
->read_pos
) );
1710 request
->read_pos
= request
->read_size
= 0; /* discard everything */
1711 if ((ret
= read_more_data( request
, -1, notify
))) return ret
;
1712 } while (request
->read_size
);
1713 return ERROR_SUCCESS
;
1716 /* read the size of the next chunk */
1717 static DWORD
start_next_chunk( struct request
*request
, BOOL notify
)
1719 DWORD ret
, chunk_size
= 0;
1721 assert(!request
->read_chunked_size
|| request
->read_chunked_size
== ~0u);
1723 if (request
->read_chunked_eof
) return ERROR_INSUFFICIENT_BUFFER
;
1725 /* read terminator for the previous chunk */
1726 if (!request
->read_chunked_size
&& (ret
= discard_eol( request
, notify
))) return ret
;
1730 while (request
->read_size
)
1732 char ch
= request
->read_buf
[request
->read_pos
];
1733 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
1734 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
1735 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
1736 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
1738 TRACE("reading %u byte chunk\n", chunk_size
);
1740 if (request
->content_length
== ~0u) request
->content_length
= chunk_size
;
1741 else request
->content_length
+= chunk_size
;
1743 request
->read_chunked_size
= chunk_size
;
1744 if (!chunk_size
) request
->read_chunked_eof
= TRUE
;
1746 return discard_eol( request
, notify
);
1748 remove_data( request
, 1 );
1750 if ((ret
= read_more_data( request
, -1, notify
))) return ret
;
1751 if (!request
->read_size
)
1753 request
->content_length
= request
->content_read
= 0;
1754 request
->read_chunked_size
= 0;
1755 return ERROR_SUCCESS
;
1760 static DWORD
refill_buffer( struct request
*request
, BOOL notify
)
1762 int len
= sizeof(request
->read_buf
);
1765 if (request
->read_chunked
)
1767 if (request
->read_chunked_eof
) return ERROR_INSUFFICIENT_BUFFER
;
1768 if (request
->read_chunked_size
== ~0u || !request
->read_chunked_size
)
1770 if ((ret
= start_next_chunk( request
, notify
))) return ret
;
1772 len
= min( len
, request
->read_chunked_size
);
1774 else if (request
->content_length
!= ~0u)
1776 len
= min( len
, request
->content_length
- request
->content_read
);
1779 if (len
<= request
->read_size
) return ERROR_SUCCESS
;
1780 if ((ret
= read_more_data( request
, len
, notify
))) return ret
;
1781 if (!request
->read_size
) request
->content_length
= request
->content_read
= 0;
1782 return ERROR_SUCCESS
;
1785 static void finished_reading( struct request
*request
)
1788 WCHAR connection
[20];
1789 DWORD size
= sizeof(connection
);
1791 if (!request
->netconn
) return;
1793 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
) close
= TRUE
;
1794 else if (!query_headers( request
, WINHTTP_QUERY_CONNECTION
, NULL
, connection
, &size
, NULL
) ||
1795 !query_headers( request
, WINHTTP_QUERY_PROXY_CONNECTION
, NULL
, connection
, &size
, NULL
))
1797 if (!wcsicmp( connection
, L
"close" )) close
= TRUE
;
1799 else if (!wcscmp( request
->version
, L
"HTTP/1.0" )) close
= TRUE
;
1802 netconn_close( request
->netconn
);
1804 cache_connection( request
->netconn
);
1805 request
->netconn
= NULL
;
1808 /* return the size of data available to be read immediately */
1809 static DWORD
get_available_data( struct request
*request
)
1811 if (request
->read_chunked
) return min( request
->read_chunked_size
, request
->read_size
);
1812 return request
->read_size
;
1815 /* check if we have reached the end of the data to read */
1816 static BOOL
end_of_read_data( struct request
*request
)
1818 if (!request
->content_length
) return TRUE
;
1819 if (request
->read_chunked
) return request
->read_chunked_eof
;
1820 if (request
->content_length
== ~0u) return FALSE
;
1821 return (request
->content_length
== request
->content_read
);
1824 static DWORD
read_data( struct request
*request
, void *buffer
, DWORD size
, DWORD
*read
, BOOL async
)
1826 int count
, bytes_read
= 0;
1827 DWORD ret
= ERROR_SUCCESS
;
1829 if (end_of_read_data( request
)) goto done
;
1833 if (!(count
= get_available_data( request
)))
1835 if ((ret
= refill_buffer( request
, async
))) goto done
;
1836 if (!(count
= get_available_data( request
))) goto done
;
1838 count
= min( count
, size
);
1839 memcpy( (char *)buffer
+ bytes_read
, request
->read_buf
+ request
->read_pos
, count
);
1840 remove_data( request
, count
);
1841 if (request
->read_chunked
) request
->read_chunked_size
-= count
;
1843 bytes_read
+= count
;
1844 request
->content_read
+= count
;
1845 if (end_of_read_data( request
)) goto done
;
1847 if (request
->read_chunked
&& !request
->read_chunked_size
) ret
= refill_buffer( request
, async
);
1850 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read
, request
->content_read
, request
->content_length
);
1851 if (end_of_read_data( request
)) finished_reading( request
);
1854 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
, buffer
, bytes_read
);
1857 WINHTTP_ASYNC_RESULT result
;
1858 result
.dwResult
= API_READ_DATA
;
1859 result
.dwError
= ret
;
1860 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
1864 if (!ret
&& read
) *read
= bytes_read
;
1868 /* read any content returned by the server so that the connection can be reused */
1869 static void drain_content( struct request
*request
)
1871 DWORD size
, bytes_read
, bytes_total
= 0, bytes_left
= request
->content_length
- request
->content_read
;
1874 refill_buffer( request
, FALSE
);
1877 if (request
->read_chunked
) size
= sizeof(buffer
);
1878 else size
= min( sizeof(buffer
), bytes_left
- bytes_total
);
1880 if (read_data( request
, buffer
, size
, &bytes_read
, FALSE
) || !bytes_read
) return;
1881 bytes_total
+= bytes_read
;
1887 ESCAPE_FLAG_NON_PRINTABLE
= 0x01,
1888 ESCAPE_FLAG_SPACE
= 0x02,
1889 ESCAPE_FLAG_PERCENT
= 0x04,
1890 ESCAPE_FLAG_UNSAFE
= 0x08,
1891 ESCAPE_FLAG_DEL
= 0x10,
1892 ESCAPE_FLAG_8BIT
= 0x20,
1893 ESCAPE_FLAG_STRIP_CRLF
= 0x40,
1896 #define ESCAPE_MASK_DEFAULT (ESCAPE_FLAG_NON_PRINTABLE | ESCAPE_FLAG_SPACE | ESCAPE_FLAG_UNSAFE |\
1897 ESCAPE_FLAG_DEL | ESCAPE_FLAG_8BIT)
1898 #define ESCAPE_MASK_PERCENT (ESCAPE_FLAG_PERCENT | ESCAPE_MASK_DEFAULT)
1899 #define ESCAPE_MASK_DISABLE (ESCAPE_FLAG_SPACE | ESCAPE_FLAG_8BIT | ESCAPE_FLAG_STRIP_CRLF)
1901 static inline BOOL
need_escape( char ch
, enum escape_flags flags
)
1903 static const char unsafe
[] = "\"#<>[\\]^`{|}";
1904 const char *ptr
= unsafe
;
1906 if ((flags
& ESCAPE_FLAG_SPACE
) && ch
== ' ') return TRUE
;
1907 if ((flags
& ESCAPE_FLAG_PERCENT
) && ch
== '%') return TRUE
;
1908 if ((flags
& ESCAPE_FLAG_NON_PRINTABLE
) && ch
< 0x20) return TRUE
;
1909 if ((flags
& ESCAPE_FLAG_DEL
) && ch
== 0x7f) return TRUE
;
1910 if ((flags
& ESCAPE_FLAG_8BIT
) && (ch
& 0x80)) return TRUE
;
1911 if ((flags
& ESCAPE_FLAG_UNSAFE
)) while (*ptr
) { if (ch
== *ptr
++) return TRUE
; }
1915 static DWORD
escape_string( const char *src
, DWORD len
, char *dst
, enum escape_flags flags
)
1917 static const char hex
[] = "0123456789ABCDEF";
1921 for (i
= 0; i
< len
; i
++)
1923 if ((flags
& ESCAPE_FLAG_STRIP_CRLF
) && (src
[i
] == '\r' || src
[i
] == '\n'))
1928 if (need_escape( src
[i
], flags
))
1933 ptr
[1] = hex
[(src
[i
] >> 4) & 0xf];
1934 ptr
[2] = hex
[src
[i
] & 0xf];
1939 else if (dst
) *ptr
++ = src
[i
];
1942 if (dst
) dst
[ret
] = 0;
1946 static DWORD
str_to_wire( const WCHAR
*src
, int src_len
, char *dst
, enum escape_flags flags
)
1951 if (src_len
< 0) src_len
= lstrlenW( src
);
1952 len
= WideCharToMultiByte( CP_UTF8
, 0, src
, src_len
, NULL
, 0, NULL
, NULL
);
1953 if (!(utf8
= malloc( len
))) return 0;
1955 WideCharToMultiByte( CP_UTF8
, 0, src
, -1, utf8
, len
, NULL
, NULL
);
1956 len
= escape_string( utf8
, len
, dst
, flags
);
1962 static char *build_wire_path( struct request
*request
, DWORD
*ret_len
)
1965 const WCHAR
*start
, *path
, *query
= NULL
;
1966 DWORD len
, len_path
= 0, len_query
= 0;
1967 enum escape_flags path_flags
, query_flags
;
1970 if (!wcsicmp( request
->connect
->hostname
, request
->connect
->servername
)) start
= full_path
= request
->path
;
1971 else if (!(full_path
= build_absolute_request_path( request
, &start
))) return NULL
;
1973 len
= lstrlenW( full_path
);
1974 if ((path
= wcschr( start
, '/' )))
1976 len_path
= lstrlenW( path
);
1977 if ((query
= wcschr( path
, '?' )))
1979 len_query
= lstrlenW( query
);
1980 len_path
-= len_query
;
1984 if (request
->hdr
.flags
& WINHTTP_FLAG_ESCAPE_DISABLE
) path_flags
= ESCAPE_MASK_DISABLE
;
1985 else if (request
->hdr
.flags
& WINHTTP_FLAG_ESCAPE_PERCENT
) path_flags
= ESCAPE_MASK_PERCENT
;
1986 else path_flags
= ESCAPE_MASK_DEFAULT
;
1988 if (request
->hdr
.flags
& WINHTTP_FLAG_ESCAPE_DISABLE_QUERY
) query_flags
= ESCAPE_MASK_DISABLE
;
1989 else query_flags
= path_flags
;
1991 *ret_len
= str_to_wire( full_path
, len
- len_path
- len_query
, NULL
, 0 );
1992 if (path
) *ret_len
+= str_to_wire( path
, len_path
, NULL
, path_flags
);
1993 if (query
) *ret_len
+= str_to_wire( query
, len_query
, NULL
, query_flags
);
1995 if ((ret
= malloc( *ret_len
+ 1 )))
1997 len
= str_to_wire( full_path
, len
- len_path
- len_query
, ret
, 0 );
1998 if (path
) len
+= str_to_wire( path
, len_path
, ret
+ len
, path_flags
);
1999 if (query
) str_to_wire( query
, len_query
, ret
+ len
, query_flags
);
2002 if (full_path
!= request
->path
) free( full_path
);
2006 static char *build_wire_request( struct request
*request
, DWORD
*len
)
2008 char *path
, *ptr
, *ret
;
2011 if (!(path
= build_wire_path( request
, &len_path
))) return NULL
;
2013 *len
= str_to_wire( request
->verb
, -1, NULL
, 0 ) + 1; /* ' ' */
2014 *len
+= len_path
+ 1; /* ' ' */
2015 *len
+= str_to_wire( request
->version
, -1, NULL
, 0 );
2017 for (i
= 0; i
< request
->num_headers
; i
++)
2019 if (request
->headers
[i
].is_request
)
2021 *len
+= str_to_wire( request
->headers
[i
].field
, -1, NULL
, 0 ) + 2; /* ': ' */
2022 *len
+= str_to_wire( request
->headers
[i
].value
, -1, NULL
, 0 ) + 2; /* '\r\n' */
2025 *len
+= 4; /* '\r\n\r\n' */
2027 if ((ret
= ptr
= malloc( *len
+ 1 )))
2029 ptr
+= str_to_wire( request
->verb
, -1, ptr
, 0 );
2031 memcpy( ptr
, path
, len_path
);
2034 ptr
+= str_to_wire( request
->version
, -1, ptr
, 0 );
2036 for (i
= 0; i
< request
->num_headers
; i
++)
2038 if (request
->headers
[i
].is_request
)
2042 ptr
+= str_to_wire( request
->headers
[i
].field
, -1, ptr
, 0 );
2045 ptr
+= str_to_wire( request
->headers
[i
].value
, -1, ptr
, 0 );
2048 memcpy( ptr
, "\r\n\r\n", sizeof("\r\n\r\n") );
2055 static WCHAR
*create_websocket_key(void)
2059 DWORD base64_len
= ((sizeof(buf
) + 2) * 4) / 3;
2060 if (!RtlGenRandom( buf
, sizeof(buf
) )) return NULL
;
2061 if ((ret
= malloc( (base64_len
+ 1) * sizeof(WCHAR
) ))) encode_base64( buf
, sizeof(buf
), ret
);
2065 static DWORD
add_websocket_key_header( struct request
*request
)
2067 WCHAR
*key
= create_websocket_key();
2068 if (!key
) return ERROR_OUTOFMEMORY
;
2069 process_header( request
, L
"Sec-WebSocket-Key", key
, WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
, TRUE
);
2071 return ERROR_SUCCESS
;
2074 static DWORD
send_request( struct request
*request
, const WCHAR
*headers
, DWORD headers_len
, void *optional
,
2075 DWORD optional_len
, DWORD total_len
, DWORD_PTR context
, BOOL async
)
2077 struct connect
*connect
= request
->connect
;
2078 struct session
*session
= connect
->session
;
2083 drain_content( request
);
2084 clear_response_headers( request
);
2087 process_header( request
, L
"User-Agent", session
->agent
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2089 if (connect
->hostname
)
2090 add_host_header( request
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
2092 if (request
->creds
[TARGET_SERVER
][SCHEME_BASIC
].username
)
2093 do_authorization( request
, WINHTTP_AUTH_TARGET_SERVER
, WINHTTP_AUTH_SCHEME_BASIC
);
2095 if (total_len
|| (request
->verb
&& !wcscmp( request
->verb
, L
"POST" )))
2097 WCHAR length
[21]; /* decimal long int + null */
2098 swprintf( length
, ARRAY_SIZE(length
), L
"%ld", total_len
);
2099 process_header( request
, L
"Content-Length", length
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2101 if (request
->flags
& REQUEST_FLAG_WEBSOCKET_UPGRADE
)
2103 process_header( request
, L
"Upgrade", L
"websocket", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2104 process_header( request
, L
"Connection", L
"Upgrade", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2105 process_header( request
, L
"Sec-WebSocket-Version", L
"13", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2106 if ((ret
= add_websocket_key_header( request
))) return ret
;
2108 else if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
))
2110 process_header( request
, L
"Connection", L
"Keep-Alive", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2112 if (request
->hdr
.flags
& WINHTTP_FLAG_REFRESH
)
2114 process_header( request
, L
"Pragma", L
"no-cache", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2115 process_header( request
, L
"Cache-Control", L
"no-cache", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2117 if (headers
&& (ret
= add_request_headers( request
, headers
, headers_len
,
2118 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)))
2120 TRACE("failed to add request headers: %u\n", ret
);
2123 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
) && (ret
= add_cookie_headers( request
)))
2125 WARN("failed to add cookie headers: %u\n", ret
);
2129 if (context
) request
->hdr
.context
= context
;
2131 if ((ret
= open_connection( request
))) goto end
;
2132 if (!(wire_req
= build_wire_request( request
, &len
)))
2134 ret
= ERROR_OUTOFMEMORY
;
2137 TRACE("full request: %s\n", debugstr_a(wire_req
));
2139 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST
, NULL
, 0 );
2141 ret
= netconn_send( request
->netconn
, wire_req
, len
, &bytes_sent
, NULL
);
2147 if ((ret
= netconn_send( request
->netconn
, optional
, optional_len
, &bytes_sent
, NULL
))) goto end
;
2148 request
->optional
= optional
;
2149 request
->optional_len
= optional_len
;
2150 len
+= optional_len
;
2152 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
, &len
, sizeof(len
) );
2157 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
, NULL
, 0 );
2160 WINHTTP_ASYNC_RESULT result
;
2161 result
.dwResult
= API_SEND_REQUEST
;
2162 result
.dwError
= ret
;
2163 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2169 static void CALLBACK
task_send_request( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2171 struct send_request
*s
= ctx
;
2173 TRACE("running %p\n", work
);
2174 send_request( s
->request
, s
->headers
, s
->headers_len
, s
->optional
, s
->optional_len
, s
->total_len
, s
->context
, TRUE
);
2176 release_object( &s
->request
->hdr
);
2181 /***********************************************************************
2182 * WinHttpSendRequest (winhttp.@)
2184 BOOL WINAPI
WinHttpSendRequest( HINTERNET hrequest
, LPCWSTR headers
, DWORD headers_len
,
2185 LPVOID optional
, DWORD optional_len
, DWORD total_len
, DWORD_PTR context
)
2188 struct request
*request
;
2190 TRACE("%p, %s, %u, %p, %u, %u, %lx\n", hrequest
, debugstr_wn(headers
, headers_len
), headers_len
, optional
,
2191 optional_len
, total_len
, context
);
2193 if (!(request
= (struct request
*)grab_object( hrequest
)))
2195 SetLastError( ERROR_INVALID_HANDLE
);
2198 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2200 release_object( &request
->hdr
);
2201 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2205 if (headers
&& !headers_len
) headers_len
= lstrlenW( headers
);
2207 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2209 struct send_request
*s
;
2211 if (!(s
= malloc( sizeof(*s
) ))) return FALSE
;
2212 s
->request
= request
;
2213 s
->headers
= strdupW( headers
);
2214 s
->headers_len
= headers_len
;
2215 s
->optional
= optional
;
2216 s
->optional_len
= optional_len
;
2217 s
->total_len
= total_len
;
2218 s
->context
= context
;
2220 addref_object( &request
->hdr
);
2221 if ((ret
= queue_task( &request
->queue
, task_send_request
, s
)))
2223 release_object( &request
->hdr
);
2228 else ret
= send_request( request
, headers
, headers_len
, optional
, optional_len
, total_len
, context
, FALSE
);
2230 release_object( &request
->hdr
);
2231 SetLastError( ret
);
2235 static DWORD
set_credentials( struct request
*request
, DWORD target
, DWORD scheme_flag
, const WCHAR
*username
,
2236 const WCHAR
*password
)
2238 enum auth_scheme scheme
= scheme_from_flag( scheme_flag
);
2240 if (scheme
== SCHEME_INVALID
|| ((scheme
== SCHEME_BASIC
|| scheme
== SCHEME_DIGEST
) && (!username
|| !password
)))
2242 return ERROR_INVALID_PARAMETER
;
2246 case WINHTTP_AUTH_TARGET_SERVER
:
2248 free( request
->creds
[TARGET_SERVER
][scheme
].username
);
2249 if (!username
) request
->creds
[TARGET_SERVER
][scheme
].username
= NULL
;
2250 else if (!(request
->creds
[TARGET_SERVER
][scheme
].username
= strdupW( username
))) return ERROR_OUTOFMEMORY
;
2252 free( request
->creds
[TARGET_SERVER
][scheme
].password
);
2253 if (!password
) request
->creds
[TARGET_SERVER
][scheme
].password
= NULL
;
2254 else if (!(request
->creds
[TARGET_SERVER
][scheme
].password
= strdupW( password
))) return ERROR_OUTOFMEMORY
;
2257 case WINHTTP_AUTH_TARGET_PROXY
:
2259 free( request
->creds
[TARGET_PROXY
][scheme
].username
);
2260 if (!username
) request
->creds
[TARGET_PROXY
][scheme
].username
= NULL
;
2261 else if (!(request
->creds
[TARGET_PROXY
][scheme
].username
= strdupW( username
))) return ERROR_OUTOFMEMORY
;
2263 free( request
->creds
[TARGET_PROXY
][scheme
].password
);
2264 if (!password
) request
->creds
[TARGET_PROXY
][scheme
].password
= NULL
;
2265 else if (!(request
->creds
[TARGET_PROXY
][scheme
].password
= strdupW( password
))) return ERROR_OUTOFMEMORY
;
2269 WARN("unknown target %u\n", target
);
2270 return ERROR_INVALID_PARAMETER
;
2272 return ERROR_SUCCESS
;
2275 /***********************************************************************
2276 * WinHttpSetCredentials (winhttp.@)
2278 BOOL WINAPI
WinHttpSetCredentials( HINTERNET hrequest
, DWORD target
, DWORD scheme
, LPCWSTR username
,
2279 LPCWSTR password
, LPVOID params
)
2282 struct request
*request
;
2284 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest
, target
, scheme
, debugstr_w(username
), password
, params
);
2286 if (!(request
= (struct request
*)grab_object( hrequest
)))
2288 SetLastError( ERROR_INVALID_HANDLE
);
2291 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2293 release_object( &request
->hdr
);
2294 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2298 ret
= set_credentials( request
, target
, scheme
, username
, password
);
2300 release_object( &request
->hdr
);
2301 SetLastError( ret
);
2305 static DWORD
handle_authorization( struct request
*request
, DWORD status
)
2307 DWORD ret
, i
, schemes
, first
, level
, target
;
2311 case HTTP_STATUS_DENIED
:
2312 target
= WINHTTP_AUTH_TARGET_SERVER
;
2313 level
= WINHTTP_QUERY_WWW_AUTHENTICATE
;
2316 case HTTP_STATUS_PROXY_AUTH_REQ
:
2317 target
= WINHTTP_AUTH_TARGET_PROXY
;
2318 level
= WINHTTP_QUERY_PROXY_AUTHENTICATE
;
2322 ERR("unhandled status %u\n", status
);
2323 return ERROR_WINHTTP_INTERNAL_ERROR
;
2326 if ((ret
= query_auth_schemes( request
, level
, &schemes
, &first
))) return ret
;
2327 if (do_authorization( request
, target
, first
)) return ERROR_SUCCESS
;
2330 for (i
= 0; i
< ARRAY_SIZE( auth_schemes
); i
++)
2332 if (!(schemes
& auth_schemes
[i
].scheme
)) continue;
2333 if (do_authorization( request
, target
, auth_schemes
[i
].scheme
)) return ERROR_SUCCESS
;
2335 return ERROR_WINHTTP_LOGIN_FAILURE
;
2338 /* set the request content length based on the headers */
2339 static void set_content_length( struct request
*request
, DWORD status
)
2342 DWORD buflen
= sizeof(request
->content_length
);
2344 if (status
== HTTP_STATUS_NO_CONTENT
|| status
== HTTP_STATUS_NOT_MODIFIED
||
2345 status
== HTTP_STATUS_SWITCH_PROTOCOLS
|| !wcscmp( request
->verb
, L
"HEAD" ))
2347 request
->content_length
= 0;
2351 if (query_headers( request
, WINHTTP_QUERY_CONTENT_LENGTH
|WINHTTP_QUERY_FLAG_NUMBER
,
2352 NULL
, &request
->content_length
, &buflen
, NULL
))
2353 request
->content_length
= ~0u;
2355 buflen
= sizeof(encoding
);
2356 if (!query_headers( request
, WINHTTP_QUERY_TRANSFER_ENCODING
, NULL
, encoding
, &buflen
, NULL
) &&
2357 !wcsicmp( encoding
, L
"chunked" ))
2359 request
->content_length
= ~0u;
2360 request
->read_chunked
= TRUE
;
2361 request
->read_chunked_size
= ~0u;
2362 request
->read_chunked_eof
= FALSE
;
2365 request
->content_read
= 0;
2368 static DWORD
read_line( struct request
*request
, char *buffer
, DWORD
*len
)
2370 int count
, bytes_read
, pos
= 0;
2375 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
2378 count
= eol
- (request
->read_buf
+ request
->read_pos
);
2379 bytes_read
= count
+ 1;
2381 else count
= bytes_read
= request
->read_size
;
2383 count
= min( count
, *len
- pos
);
2384 memcpy( buffer
+ pos
, request
->read_buf
+ request
->read_pos
, count
);
2386 remove_data( request
, bytes_read
);
2389 if ((ret
= read_more_data( request
, -1, TRUE
))) return ret
;
2390 if (!request
->read_size
)
2393 TRACE("returning empty string\n");
2394 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
2399 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2402 buffer
[*len
- 1] = 0;
2403 TRACE("returning %s\n", debugstr_a(buffer
));
2404 return ERROR_SUCCESS
;
2407 #define MAX_REPLY_LEN 1460
2408 #define INITIAL_HEADER_BUFFER_LEN 512
2410 static DWORD
read_reply( struct request
*request
)
2412 char buffer
[MAX_REPLY_LEN
];
2413 DWORD ret
, buflen
, len
, offset
, crlf_len
= 2; /* lstrlenW(crlf) */
2414 char *status_code
, *status_text
;
2415 WCHAR
*versionW
, *status_textW
, *raw_headers
;
2416 WCHAR status_codeW
[4]; /* sizeof("nnn") */
2418 if (!request
->netconn
) return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
2422 buflen
= MAX_REPLY_LEN
;
2423 if ((ret
= read_line( request
, buffer
, &buflen
))) return ret
;
2425 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2426 if (!(status_code
= strchr( buffer
, ' ' ))) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
2428 if (!(status_text
= strchr( status_code
, ' ' ))) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
2429 if ((len
= status_text
- status_code
) != sizeof("nnn") - 1) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
2432 TRACE("version [%s] status code [%s] status text [%s]\n",
2433 debugstr_an(buffer
, status_code
- buffer
- 1),
2434 debugstr_an(status_code
, len
),
2435 debugstr_a(status_text
));
2437 } while (!memcmp( status_code
, "100", len
)); /* ignore "100 Continue" responses */
2439 /* we rely on the fact that the protocol is ascii */
2440 MultiByteToWideChar( CP_ACP
, 0, status_code
, len
, status_codeW
, len
);
2441 status_codeW
[len
] = 0;
2442 if ((ret
= process_header( request
, L
"Status", status_codeW
,
2443 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
, FALSE
))) return ret
;
2445 len
= status_code
- buffer
;
2446 if (!(versionW
= malloc( len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
2447 MultiByteToWideChar( CP_ACP
, 0, buffer
, len
- 1, versionW
, len
-1 );
2448 versionW
[len
- 1] = 0;
2450 free( request
->version
);
2451 request
->version
= versionW
;
2453 len
= buflen
- (status_text
- buffer
);
2454 if (!(status_textW
= malloc( len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
2455 MultiByteToWideChar( CP_ACP
, 0, status_text
, len
, status_textW
, len
);
2457 free( request
->status_text
);
2458 request
->status_text
= status_textW
;
2460 len
= max( buflen
+ crlf_len
, INITIAL_HEADER_BUFFER_LEN
);
2461 if (!(raw_headers
= malloc( len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
2462 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
, buflen
);
2463 memcpy( raw_headers
+ buflen
- 1, L
"\r\n", sizeof(L
"\r\n") );
2465 free( request
->raw_headers
);
2466 request
->raw_headers
= raw_headers
;
2468 offset
= buflen
+ crlf_len
- 1;
2471 struct header
*header
;
2473 buflen
= MAX_REPLY_LEN
;
2474 if (read_line( request
, buffer
, &buflen
)) return ERROR_SUCCESS
;
2475 if (!*buffer
) buflen
= 1;
2477 while (len
- offset
< buflen
+ crlf_len
)
2481 if (!(tmp
= realloc( raw_headers
, len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
2482 request
->raw_headers
= raw_headers
= tmp
;
2486 memcpy( raw_headers
+ offset
, L
"\r\n", sizeof(L
"\r\n") );
2489 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
+ offset
, buflen
);
2491 if (!(header
= parse_header( raw_headers
+ offset
))) break;
2492 if ((ret
= process_header( request
, header
->field
, header
->value
, WINHTTP_ADDREQ_FLAG_ADD
, FALSE
)))
2494 free_header( header
);
2497 free_header( header
);
2498 memcpy( raw_headers
+ offset
+ buflen
- 1, L
"\r\n", sizeof(L
"\r\n") );
2499 offset
+= buflen
+ crlf_len
- 1;
2502 TRACE("raw headers: %s\n", debugstr_w(raw_headers
));
2506 static void record_cookies( struct request
*request
)
2510 for (i
= 0; i
< request
->num_headers
; i
++)
2512 struct header
*set_cookie
= &request
->headers
[i
];
2513 if (!wcsicmp( set_cookie
->field
, L
"Set-Cookie" ) && !set_cookie
->is_request
)
2515 set_cookies( request
, set_cookie
->value
);
2520 static DWORD
get_redirect_url( struct request
*request
, WCHAR
**ret_url
, DWORD
*ret_len
)
2525 ret
= query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, NULL
, &size
, NULL
);
2526 if (ret
!= ERROR_INSUFFICIENT_BUFFER
) return ret
;
2527 if (!(url
= malloc( size
))) return ERROR_OUTOFMEMORY
;
2528 if ((ret
= query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, url
, &size
, NULL
)))
2534 *ret_len
= size
/ sizeof(WCHAR
);
2535 return ERROR_SUCCESS
;
2538 static DWORD
handle_redirect( struct request
*request
, DWORD status
)
2540 DWORD ret
, len
, len_loc
= 0;
2542 struct connect
*connect
= request
->connect
;
2544 WCHAR
*hostname
= NULL
, *location
= NULL
;
2546 if ((ret
= get_redirect_url( request
, &location
, &len_loc
))) return ret
;
2548 memset( &uc
, 0, sizeof(uc
) );
2549 uc
.dwStructSize
= sizeof(uc
);
2550 uc
.dwSchemeLength
= uc
.dwHostNameLength
= uc
.dwUrlPathLength
= uc
.dwExtraInfoLength
= ~0u;
2552 if (!WinHttpCrackUrl( location
, len_loc
, 0, &uc
)) /* assume relative redirect */
2556 ret
= ERROR_OUTOFMEMORY
;
2557 if (location
[0] == '/')
2559 if (!(path
= malloc( (len_loc
+ 1) * sizeof(WCHAR
) ))) goto end
;
2560 memcpy( path
, location
, len_loc
* sizeof(WCHAR
) );
2565 if ((p
= wcsrchr( request
->path
, '/' ))) *p
= 0;
2566 len
= lstrlenW( request
->path
) + 1 + len_loc
;
2567 if (!(path
= malloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2568 lstrcpyW( path
, request
->path
);
2569 lstrcatW( path
, L
"/" );
2570 memcpy( path
+ lstrlenW(path
), location
, len_loc
* sizeof(WCHAR
) );
2573 free( request
->path
);
2574 request
->path
= path
;
2575 ret
= ERROR_SUCCESS
;
2577 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_loc
+ 1 );
2581 if (uc
.nScheme
== INTERNET_SCHEME_HTTP
&& request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
2583 if (request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP
)
2585 ret
= ERROR_WINHTTP_REDIRECT_FAILED
;
2588 TRACE("redirect from secure page to non-secure page\n");
2589 request
->hdr
.flags
&= ~WINHTTP_FLAG_SECURE
;
2591 else if (uc
.nScheme
== INTERNET_SCHEME_HTTPS
&& !(request
->hdr
.flags
& WINHTTP_FLAG_SECURE
))
2593 TRACE("redirect from non-secure page to secure page\n");
2594 request
->hdr
.flags
|= WINHTTP_FLAG_SECURE
;
2597 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_loc
+ 1 );
2599 len
= uc
.dwHostNameLength
;
2600 if (!(hostname
= malloc( (len
+ 1) * sizeof(WCHAR
) )))
2602 ret
= ERROR_OUTOFMEMORY
;
2605 memcpy( hostname
, uc
.lpszHostName
, len
* sizeof(WCHAR
) );
2608 port
= uc
.nPort
? uc
.nPort
: (uc
.nScheme
== INTERNET_SCHEME_HTTPS
? 443 : 80);
2609 if (wcsicmp( connect
->hostname
, hostname
) || connect
->serverport
!= port
)
2611 free( connect
->hostname
);
2612 connect
->hostname
= hostname
;
2613 connect
->hostport
= port
;
2614 if (!set_server_for_hostname( connect
, hostname
, port
))
2616 ret
= ERROR_OUTOFMEMORY
;
2620 netconn_close( request
->netconn
);
2621 request
->netconn
= NULL
;
2622 request
->content_length
= request
->content_read
= 0;
2623 request
->read_pos
= request
->read_size
= 0;
2624 request
->read_chunked
= request
->read_chunked_eof
= FALSE
;
2626 else free( hostname
);
2628 if ((ret
= add_host_header( request
, WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
))) goto end
;
2629 if ((ret
= open_connection( request
))) goto end
;
2631 free( request
->path
);
2632 request
->path
= NULL
;
2633 if (uc
.dwUrlPathLength
)
2635 len
= uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
;
2636 if (!(request
->path
= malloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2637 memcpy( request
->path
, uc
.lpszUrlPath
, (len
+ 1) * sizeof(WCHAR
) );
2638 request
->path
[len
] = 0;
2640 else request
->path
= strdupW( L
"/" );
2643 if (status
!= HTTP_STATUS_REDIRECT_KEEP_VERB
&& !wcscmp( request
->verb
, L
"POST" ))
2645 free( request
->verb
);
2646 request
->verb
= strdupW( L
"GET" );
2647 request
->optional
= NULL
;
2648 request
->optional_len
= 0;
2656 static BOOL
is_passport_request( struct request
*request
)
2658 static const WCHAR passportW
[] = {'P','a','s','s','p','o','r','t','1','.','4'};
2660 DWORD len
= ARRAY_SIZE(buf
);
2662 if (!(request
->connect
->session
->passport_flags
& WINHTTP_ENABLE_PASSPORT_AUTH
) ||
2663 query_headers( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, NULL
, buf
, &len
, NULL
)) return FALSE
;
2665 if (!wcsnicmp( buf
, passportW
, ARRAY_SIZE(passportW
) ) &&
2666 (buf
[ARRAY_SIZE(passportW
)] == ' ' || !buf
[ARRAY_SIZE(passportW
)])) return TRUE
;
2671 static DWORD
handle_passport_redirect( struct request
*request
)
2673 DWORD ret
, flags
= WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
;
2674 int i
, len
= lstrlenW( request
->raw_headers
);
2675 WCHAR
*p
= request
->raw_headers
;
2677 if ((ret
= process_header( request
, L
"Status", L
"401", flags
, FALSE
))) return ret
;
2679 for (i
= 0; i
< len
; i
++)
2681 if (i
<= len
- 3 && p
[i
] == '3' && p
[i
+ 1] == '0' && p
[i
+ 2] == '2')
2688 return ERROR_SUCCESS
;
2691 static DWORD
receive_response( struct request
*request
, BOOL async
)
2693 DWORD ret
, size
, query
, status
;
2695 if (!request
->netconn
) return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
2697 netconn_set_timeout( request
->netconn
, FALSE
, request
->receive_response_timeout
);
2700 if ((ret
= read_reply( request
))) break;
2702 size
= sizeof(DWORD
);
2703 query
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
2704 if ((ret
= query_headers( request
, query
, NULL
, &status
, &size
, NULL
))) break;
2706 set_content_length( request
, status
);
2708 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
)) record_cookies( request
);
2710 if (status
== HTTP_STATUS_REDIRECT
&& is_passport_request( request
))
2712 ret
= handle_passport_redirect( request
);
2714 else if (status
== HTTP_STATUS_MOVED
|| status
== HTTP_STATUS_REDIRECT
|| status
== HTTP_STATUS_REDIRECT_KEEP_VERB
)
2716 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_REDIRECTS
||
2717 request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_NEVER
) break;
2719 if (++request
->redirect_count
> request
->max_redirects
) return ERROR_WINHTTP_REDIRECT_FAILED
;
2721 if ((ret
= handle_redirect( request
, status
))) break;
2723 /* recurse synchronously */
2724 if (!(ret
= send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
))) continue;
2726 else if (status
== HTTP_STATUS_DENIED
|| status
== HTTP_STATUS_PROXY_AUTH_REQ
)
2728 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_AUTHENTICATION
) break;
2730 if (handle_authorization( request
, status
)) break;
2732 /* recurse synchronously */
2733 if (!(ret
= send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
))) continue;
2738 if (request
->netconn
) netconn_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
2739 if (request
->content_length
) ret
= refill_buffer( request
, FALSE
);
2743 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
, NULL
, 0 );
2746 WINHTTP_ASYNC_RESULT result
;
2747 result
.dwResult
= API_RECEIVE_RESPONSE
;
2748 result
.dwError
= ret
;
2749 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2755 static void CALLBACK
task_receive_response( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2757 struct receive_response
*r
= ctx
;
2759 TRACE("running %p\n", work
);
2760 receive_response( r
->request
, TRUE
);
2762 release_object( &r
->request
->hdr
);
2766 /***********************************************************************
2767 * WinHttpReceiveResponse (winhttp.@)
2769 BOOL WINAPI
WinHttpReceiveResponse( HINTERNET hrequest
, LPVOID reserved
)
2772 struct request
*request
;
2774 TRACE("%p, %p\n", hrequest
, reserved
);
2776 if (!(request
= (struct request
*)grab_object( hrequest
)))
2778 SetLastError( ERROR_INVALID_HANDLE
);
2781 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2783 release_object( &request
->hdr
);
2784 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2788 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2790 struct receive_response
*r
;
2792 if (!(r
= malloc( sizeof(*r
) ))) return FALSE
;
2793 r
->request
= request
;
2795 addref_object( &request
->hdr
);
2796 if ((ret
= queue_task( &request
->queue
, task_receive_response
, r
)))
2798 release_object( &request
->hdr
);
2802 else ret
= receive_response( request
, FALSE
);
2804 release_object( &request
->hdr
);
2805 SetLastError( ret
);
2809 static DWORD
query_data_ready( struct request
*request
)
2813 count
= get_available_data( request
);
2814 if (!request
->read_chunked
&& request
->netconn
) count
+= netconn_query_data_available( request
->netconn
);
2819 static BOOL
skip_async_queue( struct request
*request
)
2821 return request
->hdr
.recursion_count
< 3 && (end_of_read_data( request
) || query_data_ready( request
));
2824 static DWORD
query_data_available( struct request
*request
, DWORD
*available
, BOOL async
)
2826 DWORD ret
= ERROR_SUCCESS
, count
= 0;
2828 if (end_of_read_data( request
)) goto done
;
2830 if (!(count
= query_data_ready( request
)))
2832 if ((ret
= refill_buffer( request
, async
))) goto done
;
2833 count
= query_data_ready( request
);
2837 TRACE("%u bytes available\n", count
);
2840 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
, &count
, sizeof(count
) );
2843 WINHTTP_ASYNC_RESULT result
;
2844 result
.dwResult
= API_QUERY_DATA_AVAILABLE
;
2845 result
.dwError
= ret
;
2846 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2850 if (!ret
&& available
) *available
= count
;
2854 static void CALLBACK
task_query_data_available( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2856 struct query_data
*q
= ctx
;
2858 TRACE("running %p\n", work
);
2859 query_data_available( q
->request
, q
->available
, TRUE
);
2861 release_object( &q
->request
->hdr
);
2865 /***********************************************************************
2866 * WinHttpQueryDataAvailable (winhttp.@)
2868 BOOL WINAPI
WinHttpQueryDataAvailable( HINTERNET hrequest
, LPDWORD available
)
2871 struct request
*request
;
2874 TRACE("%p, %p\n", hrequest
, available
);
2876 if (!(request
= (struct request
*)grab_object( hrequest
)))
2878 SetLastError( ERROR_INVALID_HANDLE
);
2881 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2883 release_object( &request
->hdr
);
2884 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2888 if ((async
= request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
) && !skip_async_queue( request
))
2890 struct query_data
*q
;
2892 if (!(q
= malloc( sizeof(*q
) ))) return FALSE
;
2893 q
->request
= request
;
2894 q
->available
= available
;
2896 addref_object( &request
->hdr
);
2897 if ((ret
= queue_task( &request
->queue
, task_query_data_available
, q
)))
2899 release_object( &request
->hdr
);
2902 else ret
= ERROR_IO_PENDING
;
2904 else ret
= query_data_available( request
, available
, async
);
2906 release_object( &request
->hdr
);
2907 SetLastError( ret
);
2908 return !ret
|| ret
== ERROR_IO_PENDING
;
2911 static void CALLBACK
task_read_data( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2913 struct read_data
*r
= ctx
;
2915 TRACE("running %p\n", work
);
2916 read_data( r
->request
, r
->buffer
, r
->to_read
, r
->read
, TRUE
);
2918 release_object( &r
->request
->hdr
);
2922 /***********************************************************************
2923 * WinHttpReadData (winhttp.@)
2925 BOOL WINAPI
WinHttpReadData( HINTERNET hrequest
, LPVOID buffer
, DWORD to_read
, LPDWORD read
)
2928 struct request
*request
;
2931 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_read
, read
);
2933 if (!(request
= (struct request
*)grab_object( hrequest
)))
2935 SetLastError( ERROR_INVALID_HANDLE
);
2938 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2940 release_object( &request
->hdr
);
2941 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2945 if ((async
= request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
) && !skip_async_queue( request
))
2947 struct read_data
*r
;
2949 if (!(r
= malloc( sizeof(*r
) ))) return FALSE
;
2950 r
->request
= request
;
2952 r
->to_read
= to_read
;
2955 addref_object( &request
->hdr
);
2956 if ((ret
= queue_task( &request
->queue
, task_read_data
, r
)))
2958 release_object( &request
->hdr
);
2961 else ret
= ERROR_IO_PENDING
;
2963 else ret
= read_data( request
, buffer
, to_read
, read
, async
);
2965 release_object( &request
->hdr
);
2966 SetLastError( ret
);
2967 return !ret
|| ret
== ERROR_IO_PENDING
;
2970 static DWORD
write_data( struct request
*request
, const void *buffer
, DWORD to_write
, DWORD
*written
, BOOL async
)
2975 ret
= netconn_send( request
->netconn
, buffer
, to_write
, &num_bytes
, NULL
);
2979 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
, &num_bytes
, sizeof(num_bytes
) );
2982 WINHTTP_ASYNC_RESULT result
;
2983 result
.dwResult
= API_WRITE_DATA
;
2984 result
.dwError
= ret
;
2985 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2988 if (!ret
&& written
) *written
= num_bytes
;
2992 static void CALLBACK
task_write_data( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2994 struct write_data
*w
= ctx
;
2996 TRACE("running %p\n", work
);
2997 write_data( w
->request
, w
->buffer
, w
->to_write
, w
->written
, TRUE
);
2999 release_object( &w
->request
->hdr
);
3003 /***********************************************************************
3004 * WinHttpWriteData (winhttp.@)
3006 BOOL WINAPI
WinHttpWriteData( HINTERNET hrequest
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
)
3009 struct request
*request
;
3011 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_write
, written
);
3013 if (!(request
= (struct request
*)grab_object( hrequest
)))
3015 SetLastError( ERROR_INVALID_HANDLE
);
3018 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
3020 release_object( &request
->hdr
);
3021 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
3025 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3027 struct write_data
*w
;
3029 if (!(w
= malloc( sizeof(*w
) ))) return FALSE
;
3030 w
->request
= request
;
3032 w
->to_write
= to_write
;
3033 w
->written
= written
;
3035 addref_object( &request
->hdr
);
3036 if ((ret
= queue_task( &request
->queue
, task_write_data
, w
)))
3038 release_object( &request
->hdr
);
3042 else ret
= write_data( request
, buffer
, to_write
, written
, FALSE
);
3044 release_object( &request
->hdr
);
3045 SetLastError( ret
);
3049 static BOOL
socket_query_option( struct object_header
*hdr
, DWORD option
, void *buffer
, DWORD
*buflen
)
3051 FIXME("unimplemented option %u\n", option
);
3052 SetLastError( ERROR_WINHTTP_INVALID_OPTION
);
3056 static void socket_destroy( struct object_header
*hdr
)
3058 struct socket
*socket
= (struct socket
*)hdr
;
3060 TRACE("%p\n", socket
);
3062 stop_queue( &socket
->send_q
);
3063 stop_queue( &socket
->recv_q
);
3065 release_object( &socket
->request
->hdr
);
3066 free( socket
->send_frame_buffer
);
3070 static BOOL
socket_set_option( struct object_header
*hdr
, DWORD option
, void *buffer
, DWORD buflen
)
3072 FIXME("unimplemented option %u\n", option
);
3073 SetLastError( ERROR_WINHTTP_INVALID_OPTION
);
3077 static const struct object_vtbl socket_vtbl
=
3080 socket_query_option
,
3084 HINTERNET WINAPI
WinHttpWebSocketCompleteUpgrade( HINTERNET hrequest
, DWORD_PTR context
)
3086 struct socket
*socket
;
3087 struct request
*request
;
3088 HINTERNET hsocket
= NULL
;
3090 TRACE("%p, %08lx\n", hrequest
, context
);
3092 if (!(request
= (struct request
*)grab_object( hrequest
)))
3094 SetLastError( ERROR_INVALID_HANDLE
);
3097 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
3099 release_object( &request
->hdr
);
3100 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
3103 if (!(socket
= calloc( 1, sizeof(*socket
) )))
3105 release_object( &request
->hdr
);
3108 socket
->hdr
.type
= WINHTTP_HANDLE_TYPE_SOCKET
;
3109 socket
->hdr
.vtbl
= &socket_vtbl
;
3110 socket
->hdr
.refs
= 1;
3111 socket
->hdr
.callback
= request
->hdr
.callback
;
3112 socket
->hdr
.notify_mask
= request
->hdr
.notify_mask
;
3113 socket
->hdr
.context
= context
;
3115 addref_object( &request
->hdr
);
3116 socket
->request
= request
;
3118 if ((hsocket
= alloc_handle( &socket
->hdr
)))
3120 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED
, &hsocket
, sizeof(hsocket
) );
3123 release_object( &socket
->hdr
);
3124 release_object( &request
->hdr
);
3125 TRACE("returning %p\n", hsocket
);
3126 if (hsocket
) SetLastError( ERROR_SUCCESS
);
3130 static DWORD
send_bytes( struct socket
*socket
, char *bytes
, int len
, WSAOVERLAPPED
*ovr
)
3134 if ((err
= netconn_send( socket
->request
->netconn
, bytes
, len
, &count
, ovr
))) return err
;
3135 return (count
== len
) ? ERROR_SUCCESS
: ERROR_INTERNAL_ERROR
;
3138 #define FIN_BIT (1 << 7)
3139 #define MASK_BIT (1 << 7)
3140 #define RESERVED_BIT (7 << 4)
3141 #define CONTROL_BIT (1 << 3)
3143 static DWORD
send_frame( struct socket
*socket
, enum socket_opcode opcode
, USHORT status
, const char *buf
,
3144 DWORD buflen
, BOOL final
, WSAOVERLAPPED
*ovr
)
3146 DWORD i
= 0, j
, offset
= 2, len
= buflen
;
3147 DWORD buffer_size
, ret
= 0, send_size
;
3148 char hdr
[14], *mask
= NULL
;
3151 TRACE( "sending %02x frame, len %u.\n", opcode
, len
);
3153 if (opcode
== SOCKET_OPCODE_CLOSE
) len
+= sizeof(status
);
3155 hdr
[0] = final
? (char)FIN_BIT
: 0;
3157 hdr
[1] = (char)MASK_BIT
;
3158 if (len
< 126) hdr
[1] |= len
;
3159 else if (len
< 65536)
3163 hdr
[3] = len
& 0xff;
3169 hdr
[2] = hdr
[3] = hdr
[4] = hdr
[5] = 0;
3171 hdr
[7] = (len
>> 16) & 0xff;
3172 hdr
[8] = (len
>> 8) & 0xff;
3173 hdr
[9] = len
& 0xff;
3177 buffer_size
= len
+ offset
;
3178 if (len
) buffer_size
+= 4;
3179 assert( buffer_size
- len
< MAX_FRAME_BUFFER_SIZE
);
3180 if (ovr
&& buffer_size
> MAX_FRAME_BUFFER_SIZE
) return WSAEWOULDBLOCK
;
3181 if (buffer_size
> socket
->send_frame_buffer_size
&& socket
->send_frame_buffer_size
< MAX_FRAME_BUFFER_SIZE
)
3186 new_size
= min( buffer_size
, MAX_FRAME_BUFFER_SIZE
);
3187 if (!(new = realloc( socket
->send_frame_buffer
, new_size
)))
3189 ERR("Out of memory, buffer_size %u.\n", buffer_size
);
3190 return ERROR_OUTOFMEMORY
;
3192 socket
->send_frame_buffer
= new;
3193 socket
->send_frame_buffer_size
= new_size
;
3195 ptr
= socket
->send_frame_buffer
;
3197 memcpy(ptr
, hdr
, offset
);
3201 mask
= &hdr
[offset
];
3202 RtlGenRandom( mask
, 4 );
3203 memcpy( ptr
, mask
, 4 );
3207 if (opcode
== SOCKET_OPCODE_CLOSE
) /* prepend status code */
3209 *ptr
++ = (status
>> 8) ^ mask
[i
++ % 4];
3210 *ptr
++ = (status
& 0xff) ^ mask
[i
++ % 4];
3213 offset
= ptr
- socket
->send_frame_buffer
;
3214 send_size
= offset
+ buflen
;
3218 while (j
< buflen
&& offset
< MAX_FRAME_BUFFER_SIZE
)
3219 socket
->send_frame_buffer
[offset
++] = buf
[j
++] ^ mask
[i
++ % 4];
3221 if ((ret
= send_bytes( socket
, socket
->send_frame_buffer
, offset
, ovr
))) return ret
;
3223 if (!(send_size
-= offset
)) break;
3228 return ERROR_SUCCESS
;
3231 static DWORD
complete_send_frame( struct socket
*socket
, WSAOVERLAPPED
*ovr
)
3233 DWORD retflags
, len
;
3235 if (!WSAGetOverlappedResult( socket
->request
->netconn
->socket
, ovr
, &len
, TRUE
, &retflags
))
3236 return WSAGetLastError();
3238 return ERROR_SUCCESS
;
3241 static void send_io_complete( struct object_header
*hdr
)
3243 LONG count
= InterlockedDecrement( &hdr
->pending_sends
);
3244 assert( count
>= 0 );
3247 static enum socket_opcode
map_buffer_type( WINHTTP_WEB_SOCKET_BUFFER_TYPE type
)
3251 case WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
: return SOCKET_OPCODE_TEXT
;
3252 case WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
: return SOCKET_OPCODE_BINARY
;
3253 case WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE
: return SOCKET_OPCODE_CLOSE
;
3255 FIXME("buffer type %u not supported\n", type
);
3256 return SOCKET_OPCODE_INVALID
;
3260 static void socket_send_complete( struct socket
*socket
, DWORD ret
, WINHTTP_WEB_SOCKET_BUFFER_TYPE type
, DWORD len
)
3264 WINHTTP_WEB_SOCKET_STATUS status
;
3265 status
.dwBytesTransferred
= len
;
3266 status
.eBufferType
= type
;
3267 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
, &status
, sizeof(status
) );
3271 WINHTTP_WEB_SOCKET_ASYNC_RESULT result
;
3272 result
.AsyncResult
.dwResult
= API_WRITE_DATA
;
3273 result
.AsyncResult
.dwError
= ret
;
3274 result
.Operation
= WINHTTP_WEB_SOCKET_SEND_OPERATION
;
3275 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
3279 static DWORD
socket_send( struct socket
*socket
, WINHTTP_WEB_SOCKET_BUFFER_TYPE type
, const void *buf
, DWORD len
,
3280 WSAOVERLAPPED
*ovr
)
3282 enum socket_opcode opcode
= map_buffer_type( type
);
3284 return send_frame( socket
, opcode
, 0, buf
, len
, TRUE
, ovr
);
3287 static void CALLBACK
task_socket_send( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3289 struct socket_send
*s
= ctx
;
3292 TRACE("running %p\n", work
);
3294 if (s
->complete_async
) ret
= complete_send_frame( s
->socket
, &s
->ovr
);
3295 else ret
= socket_send( s
->socket
, s
->type
, s
->buf
, s
->len
, NULL
);
3297 send_io_complete( &s
->socket
->hdr
);
3298 socket_send_complete( s
->socket
, ret
, s
->type
, s
->len
);
3300 release_object( &s
->socket
->hdr
);
3304 DWORD WINAPI
WinHttpWebSocketSend( HINTERNET hsocket
, WINHTTP_WEB_SOCKET_BUFFER_TYPE type
, void *buf
, DWORD len
)
3306 struct socket
*socket
;
3309 TRACE("%p, %u, %p, %u\n", hsocket
, type
, buf
, len
);
3311 if (len
&& !buf
) return ERROR_INVALID_PARAMETER
;
3312 if (type
!= WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
&& type
!= WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
)
3314 FIXME("buffer type %u not supported\n", type
);
3315 return ERROR_NOT_SUPPORTED
;
3318 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3319 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3321 release_object( &socket
->hdr
);
3322 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3324 if (socket
->state
!= SOCKET_STATE_OPEN
)
3326 release_object( &socket
->hdr
);
3327 return ERROR_INVALID_OPERATION
;
3330 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3332 BOOL async_send
, complete_async
= FALSE
;
3333 struct socket_send
*s
;
3335 if (!(s
= malloc( sizeof(*s
) )))
3337 release_object( &socket
->hdr
);
3338 return ERROR_OUTOFMEMORY
;
3341 async_send
= InterlockedIncrement( &socket
->hdr
.pending_sends
) > 1 || socket
->hdr
.recursion_count
>= 3;
3344 memset( &s
->ovr
, 0, sizeof(s
->ovr
) );
3345 if ((ret
= socket_send( socket
, type
, buf
, len
, &s
->ovr
)) == WSA_IO_PENDING
)
3348 complete_async
= TRUE
;
3350 else if (ret
== WSAEWOULDBLOCK
) async_send
= TRUE
;
3355 s
->complete_async
= complete_async
;
3361 addref_object( &socket
->hdr
);
3362 if ((ret
= queue_task( &socket
->send_q
, task_socket_send
, s
)))
3364 InterlockedDecrement( &socket
->hdr
.pending_sends
);
3365 release_object( &socket
->hdr
);
3368 else ++socket
->hdr
.pending_sends
;
3372 InterlockedDecrement( &socket
->hdr
.pending_sends
);
3374 socket_send_complete( socket
, ret
, type
, len
);
3375 ret
= ERROR_SUCCESS
;
3378 else ret
= socket_send( socket
, type
, buf
, len
, NULL
);
3380 release_object( &socket
->hdr
);
3384 static DWORD
receive_bytes( struct socket
*socket
, char *buf
, DWORD len
, DWORD
*ret_len
, BOOL read_full_buffer
)
3386 DWORD err
, size
= 0, needed
= len
;
3390 if (socket
->request
->read_size
)
3392 size
= min( needed
, socket
->request
->read_size
);
3393 memcpy( ptr
, socket
->request
->read_buf
+ socket
->request
->read_pos
, size
);
3394 remove_data( socket
->request
, size
);
3400 if ((err
= netconn_recv( socket
->request
->netconn
, ptr
, needed
, 0, &received
))) return err
;
3401 if (!received
) break;
3403 if (!read_full_buffer
) break;
3408 if (size
!= len
&& (read_full_buffer
|| !size
)) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
3409 return ERROR_SUCCESS
;
3412 static BOOL
is_supported_opcode( enum socket_opcode opcode
)
3416 case SOCKET_OPCODE_TEXT
:
3417 case SOCKET_OPCODE_BINARY
:
3418 case SOCKET_OPCODE_CLOSE
:
3419 case SOCKET_OPCODE_PING
:
3420 case SOCKET_OPCODE_PONG
:
3423 FIXME( "opcode %02x not handled\n", opcode
);
3428 static DWORD
receive_frame( struct socket
*socket
, DWORD
*ret_len
, enum socket_opcode
*opcode
)
3430 DWORD ret
, len
, count
;
3433 if ((ret
= receive_bytes( socket
, hdr
, sizeof(hdr
), &count
, TRUE
))) return ret
;
3434 if ((hdr
[0] & RESERVED_BIT
) || (hdr
[1] & MASK_BIT
) || !is_supported_opcode( hdr
[0] & 0xf ))
3436 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
3438 *opcode
= hdr
[0] & 0xf;
3439 TRACE("received %02x frame\n", *opcode
);
3441 len
= hdr
[1] & ~MASK_BIT
;
3445 if ((ret
= receive_bytes( socket
, (char *)&len16
, sizeof(len16
), &count
, TRUE
))) return ret
;
3446 len
= RtlUshortByteSwap( len16
);
3448 else if (len
== 127)
3451 if ((ret
= receive_bytes( socket
, (char *)&len64
, sizeof(len64
), &count
, TRUE
))) return ret
;
3452 if ((len64
= RtlUlonglongByteSwap( len64
)) > ~0u) return ERROR_NOT_SUPPORTED
;
3457 return ERROR_SUCCESS
;
3460 static void CALLBACK
task_socket_send_pong( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3462 struct socket_send
*s
= ctx
;
3464 TRACE("running %p\n", work
);
3465 send_frame( s
->socket
, SOCKET_OPCODE_PONG
, 0, NULL
, 0, TRUE
, NULL
);
3466 send_io_complete( &s
->socket
->hdr
);
3468 release_object( &s
->socket
->hdr
);
3472 static DWORD
socket_send_pong( struct socket
*socket
)
3474 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3476 struct socket_send
*s
;
3479 if (!(s
= malloc( sizeof(*s
) ))) return ERROR_OUTOFMEMORY
;
3482 addref_object( &socket
->hdr
);
3483 InterlockedIncrement( &socket
->hdr
.pending_sends
);
3484 if ((ret
= queue_task( &socket
->send_q
, task_socket_send_pong
, s
)))
3486 InterlockedDecrement( &socket
->hdr
.pending_sends
);
3487 release_object( &socket
->hdr
);
3492 return send_frame( socket
, SOCKET_OPCODE_PONG
, 0, NULL
, 0, TRUE
, NULL
);
3495 static DWORD
socket_drain( struct socket
*socket
)
3499 while (socket
->read_size
)
3502 if ((ret
= receive_bytes( socket
, buf
, min(socket
->read_size
, sizeof(buf
)), &count
, TRUE
))) return ret
;
3503 socket
->read_size
-= count
;
3505 return ERROR_SUCCESS
;
3508 static DWORD
handle_control_frame( struct socket
*socket
)
3510 switch (socket
->opcode
)
3512 case SOCKET_OPCODE_PING
:
3513 return socket_send_pong( socket
);
3515 case SOCKET_OPCODE_PONG
:
3516 return socket_drain( socket
);
3519 ERR("unhandled control opcode %02x\n", socket
->opcode
);
3520 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
3523 return ERROR_SUCCESS
;
3526 static WINHTTP_WEB_SOCKET_BUFFER_TYPE
map_opcode( enum socket_opcode opcode
, BOOL fragment
)
3530 case SOCKET_OPCODE_TEXT
:
3531 if (fragment
) return WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE
;
3532 return WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
;
3534 case SOCKET_OPCODE_BINARY
:
3535 if (fragment
) return WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE
;
3536 return WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
;
3538 case SOCKET_OPCODE_CLOSE
:
3539 return WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE
;
3542 FIXME("opcode %02x not handled\n", opcode
);
3547 static DWORD
socket_receive( struct socket
*socket
, void *buf
, DWORD len
, DWORD
*ret_len
,
3548 WINHTTP_WEB_SOCKET_BUFFER_TYPE
*ret_type
, BOOL async
)
3550 DWORD count
, ret
= ERROR_SUCCESS
;
3552 if (!socket
->read_size
)
3556 if (!(ret
= receive_frame( socket
, &socket
->read_size
, &socket
->opcode
)))
3558 if (!(socket
->opcode
& CONTROL_BIT
) || (ret
= handle_control_frame( socket
))) break;
3560 else if (ret
== WSAETIMEDOUT
) ret
= socket_send_pong( socket
);
3564 if (!ret
) ret
= receive_bytes( socket
, buf
, min(len
, socket
->read_size
), &count
, FALSE
);
3567 if (count
< socket
->read_size
)
3568 WARN("Short read.\n");
3570 socket
->read_size
-= count
;
3574 *ret_type
= map_opcode( socket
->opcode
, socket
->read_size
!= 0 );
3581 WINHTTP_WEB_SOCKET_STATUS status
;
3582 status
.dwBytesTransferred
= count
;
3583 status
.eBufferType
= map_opcode( socket
->opcode
, socket
->read_size
!= 0 );
3584 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
, &status
, sizeof(status
) );
3588 WINHTTP_WEB_SOCKET_ASYNC_RESULT result
;
3589 result
.AsyncResult
.dwResult
= API_READ_DATA
;
3590 result
.AsyncResult
.dwError
= ret
;
3591 result
.Operation
= WINHTTP_WEB_SOCKET_RECEIVE_OPERATION
;
3592 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
3598 static void CALLBACK
task_socket_receive( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3600 struct socket_receive
*r
= ctx
;
3602 TRACE("running %p\n", work
);
3603 socket_receive( r
->socket
, r
->buf
, r
->len
, NULL
, NULL
, TRUE
);
3605 release_object( &r
->socket
->hdr
);
3609 DWORD WINAPI
WinHttpWebSocketReceive( HINTERNET hsocket
, void *buf
, DWORD len
, DWORD
*ret_len
,
3610 WINHTTP_WEB_SOCKET_BUFFER_TYPE
*ret_type
)
3612 struct socket
*socket
;
3615 TRACE("%p, %p, %u, %p, %p\n", hsocket
, buf
, len
, ret_len
, ret_type
);
3617 if (!buf
|| !len
) return ERROR_INVALID_PARAMETER
;
3619 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3620 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3622 release_object( &socket
->hdr
);
3623 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3625 if (socket
->state
> SOCKET_STATE_SHUTDOWN
)
3627 release_object( &socket
->hdr
);
3628 return ERROR_INVALID_OPERATION
;
3631 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3633 struct socket_receive
*r
;
3635 if (!(r
= malloc( sizeof(*r
) ))) return FALSE
;
3640 addref_object( &socket
->hdr
);
3641 if ((ret
= queue_task( &socket
->recv_q
, task_socket_receive
, r
)))
3643 release_object( &socket
->hdr
);
3647 else ret
= socket_receive( socket
, buf
, len
, ret_len
, ret_type
, FALSE
);
3649 release_object( &socket
->hdr
);
3653 static void CALLBACK
task_socket_shutdown( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3655 struct socket_shutdown
*s
= ctx
;
3658 TRACE("running %p\n", work
);
3660 ret
= send_frame( s
->socket
, SOCKET_OPCODE_CLOSE
, s
->status
, s
->reason
, s
->len
, TRUE
, NULL
);
3661 send_io_complete( &s
->socket
->hdr
);
3663 if (!ret
) send_callback( &s
->socket
->hdr
, WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE
, NULL
, 0 );
3666 WINHTTP_WEB_SOCKET_ASYNC_RESULT result
;
3667 result
.AsyncResult
.dwResult
= API_WRITE_DATA
;
3668 result
.AsyncResult
.dwError
= ret
;
3669 result
.Operation
= WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION
;
3670 send_callback( &s
->socket
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
3673 release_object( &s
->socket
->hdr
);
3677 static DWORD
send_socket_shutdown( struct socket
*socket
, USHORT status
, const void *reason
, DWORD len
,
3682 socket
->state
= SOCKET_STATE_SHUTDOWN
;
3684 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3686 struct socket_shutdown
*s
;
3688 if (!(s
= malloc( sizeof(*s
) ))) return FALSE
;
3691 memcpy( s
->reason
, reason
, len
);
3694 addref_object( &socket
->hdr
);
3695 InterlockedIncrement( &socket
->hdr
.pending_sends
);
3696 if ((ret
= queue_task( &socket
->send_q
, task_socket_shutdown
, s
)))
3698 InterlockedDecrement( &socket
->hdr
.pending_sends
);
3699 release_object( &socket
->hdr
);
3703 else ret
= send_frame( socket
, SOCKET_OPCODE_CLOSE
, status
, reason
, len
, TRUE
, NULL
);
3708 DWORD WINAPI
WinHttpWebSocketShutdown( HINTERNET hsocket
, USHORT status
, void *reason
, DWORD len
)
3710 struct socket
*socket
;
3713 TRACE("%p, %u, %p, %u\n", hsocket
, status
, reason
, len
);
3715 if ((len
&& !reason
) || len
> sizeof(socket
->reason
)) return ERROR_INVALID_PARAMETER
;
3717 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3718 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3720 release_object( &socket
->hdr
);
3721 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3723 if (socket
->state
>= SOCKET_STATE_SHUTDOWN
)
3725 release_object( &socket
->hdr
);
3726 return ERROR_INVALID_OPERATION
;
3729 ret
= send_socket_shutdown( socket
, status
, reason
, len
, TRUE
);
3730 release_object( &socket
->hdr
);
3734 static DWORD
socket_close( struct socket
*socket
, USHORT status
, const void *reason
, DWORD len
, BOOL async
)
3738 if ((ret
= socket_drain( socket
))) goto done
;
3740 if (socket
->state
< SOCKET_STATE_SHUTDOWN
)
3742 stop_queue( &socket
->send_q
);
3743 if ((ret
= send_frame( socket
, SOCKET_OPCODE_CLOSE
, status
, reason
, len
, TRUE
, NULL
))) goto done
;
3744 socket
->state
= SOCKET_STATE_SHUTDOWN
;
3749 if ((ret
= receive_frame( socket
, &count
, &socket
->opcode
))) goto done
;
3750 if (socket
->opcode
== SOCKET_OPCODE_CLOSE
) break;
3752 socket
->read_size
= count
;
3753 if ((ret
= socket_drain( socket
))) goto done
;
3756 if ((count
&& (count
< sizeof(socket
->status
) || count
> sizeof(socket
->status
) + sizeof(socket
->reason
))))
3758 ret
= ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
3764 DWORD reason_len
= count
- sizeof(socket
->status
);
3765 if ((ret
= receive_bytes( socket
, (char *)&socket
->status
, sizeof(socket
->status
), &count
, TRUE
))) goto done
;
3766 socket
->status
= RtlUshortByteSwap( socket
->status
);
3767 if ((ret
= receive_bytes( socket
, socket
->reason
, reason_len
, &socket
->reason_len
, TRUE
))) goto done
;
3769 socket
->state
= SOCKET_STATE_CLOSED
;
3774 if (!ret
) send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE
, NULL
, 0 );
3777 WINHTTP_WEB_SOCKET_ASYNC_RESULT result
;
3778 result
.AsyncResult
.dwResult
= API_READ_DATA
; /* FIXME */
3779 result
.AsyncResult
.dwError
= ret
;
3780 result
.Operation
= WINHTTP_WEB_SOCKET_CLOSE_OPERATION
;
3781 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
3787 static void CALLBACK
task_socket_close( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3789 struct socket_shutdown
*s
= ctx
;
3791 socket_close( s
->socket
, s
->status
, s
->reason
, s
->len
, TRUE
);
3793 TRACE("running %p\n", work
);
3794 release_object( &s
->socket
->hdr
);
3798 DWORD WINAPI
WinHttpWebSocketClose( HINTERNET hsocket
, USHORT status
, void *reason
, DWORD len
)
3800 struct socket
*socket
;
3803 TRACE("%p, %u, %p, %u\n", hsocket
, status
, reason
, len
);
3805 if ((len
&& !reason
) || len
> sizeof(socket
->reason
)) return ERROR_INVALID_PARAMETER
;
3807 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3808 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3810 release_object( &socket
->hdr
);
3811 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3813 if (socket
->state
>= SOCKET_STATE_CLOSED
)
3815 release_object( &socket
->hdr
);
3816 return ERROR_INVALID_OPERATION
;
3819 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3821 struct socket_shutdown
*s
;
3823 if (!(s
= malloc( sizeof(*s
) ))) return FALSE
;
3826 memcpy( s
->reason
, reason
, len
);
3829 addref_object( &socket
->hdr
);
3830 if ((ret
= queue_task( &socket
->recv_q
, task_socket_close
, s
)))
3832 release_object( &socket
->hdr
);
3836 else ret
= socket_close( socket
, status
, reason
, len
, FALSE
);
3838 release_object( &socket
->hdr
);
3842 DWORD WINAPI
WinHttpWebSocketQueryCloseStatus( HINTERNET hsocket
, USHORT
*status
, void *reason
, DWORD len
,
3845 struct socket
*socket
;
3848 TRACE("%p, %p, %p, %u, %p\n", hsocket
, status
, reason
, len
, ret_len
);
3850 if (!status
|| (len
&& !reason
) || !ret_len
) return ERROR_INVALID_PARAMETER
;
3852 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3853 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3855 release_object( &socket
->hdr
);
3856 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3858 if (socket
->state
< SOCKET_STATE_CLOSED
)
3860 release_object( &socket
->hdr
);
3861 return ERROR_INVALID_OPERATION
;
3864 *status
= socket
->status
;
3865 *ret_len
= socket
->reason_len
;
3866 if (socket
->reason_len
> len
) ret
= ERROR_INSUFFICIENT_BUFFER
;
3869 memcpy( reason
, socket
->reason
, socket
->reason_len
);
3870 ret
= ERROR_SUCCESS
;
3873 release_object( &socket
->hdr
);
3879 REQUEST_STATE_INITIALIZED
,
3880 REQUEST_STATE_CANCELLED
,
3883 REQUEST_STATE_RESPONSE_RECEIVED
3886 struct winhttp_request
3888 IWinHttpRequest IWinHttpRequest_iface
;
3890 CRITICAL_SECTION cs
;
3891 enum request_state state
;
3903 DWORD bytes_available
;
3907 DWORD disable_feature
;
3908 LONG resolve_timeout
;
3909 LONG connect_timeout
;
3911 LONG receive_timeout
;
3912 WINHTTP_PROXY_INFO proxy
;
3917 static inline struct winhttp_request
*impl_from_IWinHttpRequest( IWinHttpRequest
*iface
)
3919 return CONTAINING_RECORD( iface
, struct winhttp_request
, IWinHttpRequest_iface
);
3922 static ULONG WINAPI
winhttp_request_AddRef(
3923 IWinHttpRequest
*iface
)
3925 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3926 return InterlockedIncrement( &request
->refs
);
3929 /* critical section must be held */
3930 static void cancel_request( struct winhttp_request
*request
)
3932 if (request
->state
<= REQUEST_STATE_CANCELLED
) return;
3934 if (request
->proc_running
)
3936 SetEvent( request
->cancel
);
3937 LeaveCriticalSection( &request
->cs
);
3939 WaitForSingleObject( request
->done
, INFINITE
);
3941 EnterCriticalSection( &request
->cs
);
3943 request
->state
= REQUEST_STATE_CANCELLED
;
3946 /* critical section must be held */
3947 static void free_request( struct winhttp_request
*request
)
3949 if (request
->state
< REQUEST_STATE_INITIALIZED
) return;
3950 WinHttpCloseHandle( request
->hrequest
);
3951 WinHttpCloseHandle( request
->hconnect
);
3952 WinHttpCloseHandle( request
->hsession
);
3953 CloseHandle( request
->done
);
3954 CloseHandle( request
->wait
);
3955 CloseHandle( request
->cancel
);
3956 free( request
->proxy
.lpszProxy
);
3957 free( request
->proxy
.lpszProxyBypass
);
3958 free( request
->buffer
);
3959 free( request
->verb
);
3960 VariantClear( &request
->data
);
3963 static ULONG WINAPI
winhttp_request_Release(
3964 IWinHttpRequest
*iface
)
3966 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3967 LONG refs
= InterlockedDecrement( &request
->refs
);
3970 TRACE("destroying %p\n", request
);
3972 EnterCriticalSection( &request
->cs
);
3973 cancel_request( request
);
3974 free_request( request
);
3975 LeaveCriticalSection( &request
->cs
);
3976 request
->cs
.DebugInfo
->Spare
[0] = 0;
3977 DeleteCriticalSection( &request
->cs
);
3983 static HRESULT WINAPI
winhttp_request_QueryInterface(
3984 IWinHttpRequest
*iface
,
3988 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3990 TRACE("%p, %s, %p\n", request
, debugstr_guid(riid
), obj
);
3992 if (IsEqualGUID( riid
, &IID_IWinHttpRequest
) ||
3993 IsEqualGUID( riid
, &IID_IDispatch
) ||
3994 IsEqualGUID( riid
, &IID_IUnknown
))
4000 FIXME("interface %s not implemented\n", debugstr_guid(riid
));
4001 return E_NOINTERFACE
;
4003 IWinHttpRequest_AddRef( iface
);
4007 static HRESULT WINAPI
winhttp_request_GetTypeInfoCount(
4008 IWinHttpRequest
*iface
,
4011 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4013 TRACE("%p, %p\n", request
, count
);
4020 IWinHttpRequest_tid
,
4024 static ITypeLib
*winhttp_typelib
;
4025 static ITypeInfo
*winhttp_typeinfo
[last_tid
];
4027 static REFIID winhttp_tid_id
[] =
4029 &IID_IWinHttpRequest
4032 static HRESULT
get_typeinfo( enum type_id tid
, ITypeInfo
**ret
)
4036 if (!winhttp_typelib
)
4040 hr
= LoadRegTypeLib( &LIBID_WinHttp
, 5, 1, LOCALE_SYSTEM_DEFAULT
, &typelib
);
4043 ERR("LoadRegTypeLib failed: %08x\n", hr
);
4046 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib
, typelib
, NULL
))
4047 ITypeLib_Release( typelib
);
4049 if (!winhttp_typeinfo
[tid
])
4051 ITypeInfo
*typeinfo
;
4053 hr
= ITypeLib_GetTypeInfoOfGuid( winhttp_typelib
, winhttp_tid_id
[tid
], &typeinfo
);
4056 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id
[tid
]), hr
);
4059 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo
+ tid
), typeinfo
, NULL
))
4060 ITypeInfo_Release( typeinfo
);
4062 *ret
= winhttp_typeinfo
[tid
];
4063 ITypeInfo_AddRef(winhttp_typeinfo
[tid
]);
4067 void release_typelib(void)
4071 for (i
= 0; i
< ARRAY_SIZE(winhttp_typeinfo
); i
++)
4072 if (winhttp_typeinfo
[i
])
4073 ITypeInfo_Release(winhttp_typeinfo
[i
]);
4075 if (winhttp_typelib
)
4076 ITypeLib_Release(winhttp_typelib
);
4079 static HRESULT WINAPI
winhttp_request_GetTypeInfo(
4080 IWinHttpRequest
*iface
,
4085 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4086 TRACE("%p, %u, %u, %p\n", request
, index
, lcid
, info
);
4088 return get_typeinfo( IWinHttpRequest_tid
, info
);
4091 static HRESULT WINAPI
winhttp_request_GetIDsOfNames(
4092 IWinHttpRequest
*iface
,
4099 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4100 ITypeInfo
*typeinfo
;
4103 TRACE("%p, %s, %p, %u, %u, %p\n", request
, debugstr_guid(riid
), names
, count
, lcid
, dispid
);
4105 if (!names
|| !count
|| !dispid
) return E_INVALIDARG
;
4107 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
4110 hr
= ITypeInfo_GetIDsOfNames( typeinfo
, names
, count
, dispid
);
4111 ITypeInfo_Release( typeinfo
);
4116 static HRESULT WINAPI
winhttp_request_Invoke(
4117 IWinHttpRequest
*iface
,
4124 EXCEPINFO
*excep_info
,
4127 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4128 ITypeInfo
*typeinfo
;
4131 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request
, member
, debugstr_guid(riid
),
4132 lcid
, flags
, params
, result
, excep_info
, arg_err
);
4134 if (!IsEqualIID( riid
, &IID_NULL
)) return DISP_E_UNKNOWNINTERFACE
;
4136 if (member
== DISPID_HTTPREQUEST_OPTION
)
4138 VARIANT ret_value
, option
;
4141 if (!result
) result
= &ret_value
;
4142 if (!arg_err
) arg_err
= &err_pos
;
4144 VariantInit( &option
);
4145 VariantInit( result
);
4147 if (!flags
) return S_OK
;
4149 if (flags
== DISPATCH_PROPERTYPUT
)
4151 hr
= DispGetParam( params
, 0, VT_I4
, &option
, arg_err
);
4152 if (FAILED(hr
)) return hr
;
4154 hr
= IWinHttpRequest_put_Option( &request
->IWinHttpRequest_iface
, V_I4( &option
), params
->rgvarg
[0] );
4156 WARN("put_Option(%d) failed: %x\n", V_I4( &option
), hr
);
4159 else if (flags
& (DISPATCH_PROPERTYGET
| DISPATCH_METHOD
))
4161 hr
= DispGetParam( params
, 0, VT_I4
, &option
, arg_err
);
4162 if (FAILED(hr
)) return hr
;
4164 hr
= IWinHttpRequest_get_Option( &request
->IWinHttpRequest_iface
, V_I4( &option
), result
);
4166 WARN("get_Option(%d) failed: %x\n", V_I4( &option
), hr
);
4170 FIXME("unsupported flags %x\n", flags
);
4174 /* fallback to standard implementation */
4176 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
4179 hr
= ITypeInfo_Invoke( typeinfo
, &request
->IWinHttpRequest_iface
, member
, flags
,
4180 params
, result
, excep_info
, arg_err
);
4181 ITypeInfo_Release( typeinfo
);
4186 static HRESULT WINAPI
winhttp_request_SetProxy(
4187 IWinHttpRequest
*iface
,
4188 HTTPREQUEST_PROXY_SETTING proxy_setting
,
4189 VARIANT proxy_server
,
4190 VARIANT bypass_list
)
4192 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4193 DWORD err
= ERROR_SUCCESS
;
4195 TRACE("%p, %u, %s, %s\n", request
, proxy_setting
, debugstr_variant(&proxy_server
),
4196 debugstr_variant(&bypass_list
));
4198 EnterCriticalSection( &request
->cs
);
4199 switch (proxy_setting
)
4201 case HTTPREQUEST_PROXYSETTING_DEFAULT
:
4202 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
4203 free( request
->proxy
.lpszProxy
);
4204 free( request
->proxy
.lpszProxyBypass
);
4205 request
->proxy
.lpszProxy
= NULL
;
4206 request
->proxy
.lpszProxyBypass
= NULL
;
4209 case HTTPREQUEST_PROXYSETTING_DIRECT
:
4210 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NO_PROXY
;
4211 free( request
->proxy
.lpszProxy
);
4212 free( request
->proxy
.lpszProxyBypass
);
4213 request
->proxy
.lpszProxy
= NULL
;
4214 request
->proxy
.lpszProxyBypass
= NULL
;
4217 case HTTPREQUEST_PROXYSETTING_PROXY
:
4218 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
4219 if (V_VT( &proxy_server
) == VT_BSTR
)
4221 free( request
->proxy
.lpszProxy
);
4222 request
->proxy
.lpszProxy
= strdupW( V_BSTR( &proxy_server
) );
4224 if (V_VT( &bypass_list
) == VT_BSTR
)
4226 free( request
->proxy
.lpszProxyBypass
);
4227 request
->proxy
.lpszProxyBypass
= strdupW( V_BSTR( &bypass_list
) );
4232 err
= ERROR_INVALID_PARAMETER
;
4235 LeaveCriticalSection( &request
->cs
);
4236 return HRESULT_FROM_WIN32( err
);
4239 static HRESULT WINAPI
winhttp_request_SetCredentials(
4240 IWinHttpRequest
*iface
,
4243 HTTPREQUEST_SETCREDENTIALS_FLAGS flags
)
4245 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4246 DWORD target
, scheme
= WINHTTP_AUTH_SCHEME_BASIC
; /* FIXME: query supported schemes */
4247 DWORD err
= ERROR_SUCCESS
;
4249 TRACE("%p, %s, %p, 0x%08x\n", request
, debugstr_w(username
), password
, flags
);
4251 EnterCriticalSection( &request
->cs
);
4252 if (request
->state
< REQUEST_STATE_OPEN
)
4254 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
4259 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
:
4260 target
= WINHTTP_AUTH_TARGET_SERVER
;
4262 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY
:
4263 target
= WINHTTP_AUTH_TARGET_PROXY
;
4266 err
= ERROR_INVALID_PARAMETER
;
4269 if (!WinHttpSetCredentials( request
->hrequest
, target
, scheme
, username
, password
, NULL
))
4271 err
= GetLastError();
4274 LeaveCriticalSection( &request
->cs
);
4275 return HRESULT_FROM_WIN32( err
);
4278 static void initialize_request( struct winhttp_request
*request
)
4280 request
->wait
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
4281 request
->cancel
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
4282 request
->done
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
4283 request
->connect_timeout
= 60000;
4284 request
->send_timeout
= 30000;
4285 request
->receive_timeout
= 30000;
4286 request
->url_codepage
= CP_UTF8
;
4287 VariantInit( &request
->data
);
4288 request
->state
= REQUEST_STATE_INITIALIZED
;
4291 static void reset_request( struct winhttp_request
*request
)
4293 cancel_request( request
);
4294 WinHttpCloseHandle( request
->hrequest
);
4295 request
->hrequest
= NULL
;
4296 WinHttpCloseHandle( request
->hconnect
);
4297 request
->hconnect
= NULL
;
4298 free( request
->buffer
);
4299 request
->buffer
= NULL
;
4300 free( request
->verb
);
4301 request
->verb
= NULL
;
4302 request
->offset
= 0;
4303 request
->bytes_available
= 0;
4304 request
->bytes_read
= 0;
4305 request
->error
= ERROR_SUCCESS
;
4306 request
->logon_policy
= 0;
4307 request
->disable_feature
= 0;
4308 request
->async
= FALSE
;
4309 request
->connect_timeout
= 60000;
4310 request
->send_timeout
= 30000;
4311 request
->receive_timeout
= 30000;
4312 request
->url_codepage
= CP_UTF8
;
4313 free( request
->proxy
.lpszProxy
);
4314 request
->proxy
.lpszProxy
= NULL
;
4315 free( request
->proxy
.lpszProxyBypass
);
4316 request
->proxy
.lpszProxyBypass
= NULL
;
4317 VariantClear( &request
->data
);
4318 request
->state
= REQUEST_STATE_INITIALIZED
;
4321 static HRESULT WINAPI
winhttp_request_Open(
4322 IWinHttpRequest
*iface
,
4327 static const WCHAR httpsW
[] = {'h','t','t','p','s'};
4328 static const WCHAR
*acceptW
[] = {L
"*/*", NULL
};
4329 static const WCHAR user_agentW
[] = L
"Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)";
4330 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4332 WCHAR
*hostname
, *path
= NULL
, *verb
= NULL
;
4333 DWORD err
= ERROR_OUTOFMEMORY
, len
, flags
= 0;
4335 TRACE("%p, %s, %s, %s\n", request
, debugstr_w(method
), debugstr_w(url
),
4336 debugstr_variant(&async
));
4338 if (!method
|| !url
) return E_INVALIDARG
;
4340 memset( &uc
, 0, sizeof(uc
) );
4341 uc
.dwStructSize
= sizeof(uc
);
4342 uc
.dwSchemeLength
= ~0u;
4343 uc
.dwHostNameLength
= ~0u;
4344 uc
.dwUrlPathLength
= ~0u;
4345 uc
.dwExtraInfoLength
= ~0u;
4346 if (!WinHttpCrackUrl( url
, 0, 0, &uc
)) return HRESULT_FROM_WIN32( GetLastError() );
4348 EnterCriticalSection( &request
->cs
);
4349 reset_request( request
);
4351 if (!(hostname
= malloc( (uc
.dwHostNameLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
4352 memcpy( hostname
, uc
.lpszHostName
, uc
.dwHostNameLength
* sizeof(WCHAR
) );
4353 hostname
[uc
.dwHostNameLength
] = 0;
4355 if (!(path
= malloc( (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
4356 memcpy( path
, uc
.lpszUrlPath
, (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
) * sizeof(WCHAR
) );
4357 path
[uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
] = 0;
4359 if (!(verb
= strdupW( method
))) goto error
;
4360 if (SUCCEEDED( VariantChangeType( &async
, &async
, 0, VT_BOOL
)) && V_BOOL( &async
)) request
->async
= TRUE
;
4361 else request
->async
= FALSE
;
4363 if (!request
->hsession
)
4365 if (!(request
->hsession
= WinHttpOpen( user_agentW
, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
, NULL
, NULL
,
4366 WINHTTP_FLAG_ASYNC
)))
4368 err
= GetLastError();
4371 if (!(request
->hconnect
= WinHttpConnect( request
->hsession
, hostname
, uc
.nPort
, 0 )))
4373 WinHttpCloseHandle( request
->hsession
);
4374 request
->hsession
= NULL
;
4375 err
= GetLastError();
4379 else if (!(request
->hconnect
= WinHttpConnect( request
->hsession
, hostname
, uc
.nPort
, 0 )))
4381 err
= GetLastError();
4385 len
= ARRAY_SIZE( httpsW
);
4386 if (uc
.dwSchemeLength
== len
&& !memcmp( uc
.lpszScheme
, httpsW
, len
* sizeof(WCHAR
) ))
4388 flags
|= WINHTTP_FLAG_SECURE
;
4390 if (!(request
->hrequest
= WinHttpOpenRequest( request
->hconnect
, method
, path
, NULL
, NULL
, acceptW
, flags
)))
4392 err
= GetLastError();
4395 WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_CONTEXT_VALUE
, &request
, sizeof(request
) );
4397 request
->state
= REQUEST_STATE_OPEN
;
4398 request
->verb
= verb
;
4401 LeaveCriticalSection( &request
->cs
);
4405 WinHttpCloseHandle( request
->hconnect
);
4406 request
->hconnect
= NULL
;
4410 LeaveCriticalSection( &request
->cs
);
4411 return HRESULT_FROM_WIN32( err
);
4414 static HRESULT WINAPI
winhttp_request_SetRequestHeader(
4415 IWinHttpRequest
*iface
,
4419 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4420 DWORD len
, err
= ERROR_SUCCESS
;
4423 TRACE("%p, %s, %s\n", request
, debugstr_w(header
), debugstr_w(value
));
4425 if (!header
) return E_INVALIDARG
;
4427 EnterCriticalSection( &request
->cs
);
4428 if (request
->state
< REQUEST_STATE_OPEN
)
4430 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
4433 if (request
->state
>= REQUEST_STATE_SENT
)
4435 err
= ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND
;
4438 len
= lstrlenW( header
) + 4;
4439 if (value
) len
+= lstrlenW( value
);
4440 if (!(str
= malloc( (len
+ 1) * sizeof(WCHAR
) )))
4442 err
= ERROR_OUTOFMEMORY
;
4445 swprintf( str
, len
+ 1, L
"%s: %s\r\n", header
, value
? value
: L
"" );
4446 if (!WinHttpAddRequestHeaders( request
->hrequest
, str
, len
,
4447 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
))
4449 err
= GetLastError();
4454 LeaveCriticalSection( &request
->cs
);
4455 return HRESULT_FROM_WIN32( err
);
4458 static HRESULT WINAPI
winhttp_request_GetResponseHeader(
4459 IWinHttpRequest
*iface
,
4463 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4464 DWORD size
, err
= ERROR_SUCCESS
;
4466 TRACE("%p, %p\n", request
, header
);
4468 EnterCriticalSection( &request
->cs
);
4469 if (request
->state
< REQUEST_STATE_SENT
)
4471 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4474 if (!header
|| !value
)
4476 err
= ERROR_INVALID_PARAMETER
;
4480 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, NULL
, &size
, NULL
))
4482 err
= GetLastError();
4483 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
4485 if (!(*value
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
4487 err
= ERROR_OUTOFMEMORY
;
4490 err
= ERROR_SUCCESS
;
4491 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, *value
, &size
, NULL
))
4493 err
= GetLastError();
4494 SysFreeString( *value
);
4497 LeaveCriticalSection( &request
->cs
);
4498 return HRESULT_FROM_WIN32( err
);
4501 static HRESULT WINAPI
winhttp_request_GetAllResponseHeaders(
4502 IWinHttpRequest
*iface
,
4505 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4506 DWORD size
, err
= ERROR_SUCCESS
;
4508 TRACE("%p, %p\n", request
, headers
);
4510 if (!headers
) return E_INVALIDARG
;
4512 EnterCriticalSection( &request
->cs
);
4513 if (request
->state
< REQUEST_STATE_SENT
)
4515 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4519 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, NULL
, &size
, NULL
))
4521 err
= GetLastError();
4522 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
4524 if (!(*headers
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
4526 err
= ERROR_OUTOFMEMORY
;
4529 err
= ERROR_SUCCESS
;
4530 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, *headers
, &size
, NULL
))
4532 err
= GetLastError();
4533 SysFreeString( *headers
);
4536 LeaveCriticalSection( &request
->cs
);
4537 return HRESULT_FROM_WIN32( err
);
4540 static void CALLBACK
wait_status_callback( HINTERNET handle
, DWORD_PTR context
, DWORD status
, LPVOID buffer
, DWORD size
)
4542 struct winhttp_request
*request
= (struct winhttp_request
*)context
;
4546 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
:
4547 request
->bytes_available
= *(DWORD
*)buffer
;
4548 request
->error
= ERROR_SUCCESS
;
4550 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE
:
4551 request
->bytes_read
= size
;
4552 request
->error
= ERROR_SUCCESS
;
4554 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
:
4556 WINHTTP_ASYNC_RESULT
*result
= (WINHTTP_ASYNC_RESULT
*)buffer
;
4557 request
->error
= result
->dwError
;
4561 request
->error
= ERROR_SUCCESS
;
4564 SetEvent( request
->wait
);
4567 static void wait_set_status_callback( struct winhttp_request
*request
, DWORD status
)
4569 status
|= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
;
4570 WinHttpSetStatusCallback( request
->hrequest
, wait_status_callback
, status
, 0 );
4573 static DWORD
wait_for_completion( struct winhttp_request
*request
)
4575 HANDLE handles
[2] = { request
->wait
, request
->cancel
};
4578 switch (WaitForMultipleObjects( 2, handles
, FALSE
, INFINITE
))
4581 ret
= request
->error
;
4583 case WAIT_OBJECT_0
+ 1:
4584 ret
= request
->error
= ERROR_CANCELLED
;
4585 SetEvent( request
->done
);
4588 ret
= request
->error
= GetLastError();
4594 static HRESULT
request_receive( struct winhttp_request
*request
)
4596 DWORD err
, size
, buflen
= 4096;
4598 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
);
4599 if (!WinHttpReceiveResponse( request
->hrequest
, NULL
))
4601 return HRESULT_FROM_WIN32( GetLastError() );
4603 if ((err
= wait_for_completion( request
))) return HRESULT_FROM_WIN32( err
);
4604 if (!wcscmp( request
->verb
, L
"HEAD" ))
4606 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
4609 if (!(request
->buffer
= malloc( buflen
))) return E_OUTOFMEMORY
;
4610 request
->buffer
[0] = 0;
4614 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
);
4615 if (!WinHttpQueryDataAvailable( request
->hrequest
, &request
->bytes_available
))
4617 err
= GetLastError();
4620 if ((err
= wait_for_completion( request
))) goto error
;
4621 if (!request
->bytes_available
) break;
4622 size
+= request
->bytes_available
;
4626 while (buflen
< size
) buflen
*= 2;
4627 if (!(tmp
= realloc( request
->buffer
, buflen
)))
4629 err
= ERROR_OUTOFMEMORY
;
4632 request
->buffer
= tmp
;
4634 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
);
4635 if (!WinHttpReadData( request
->hrequest
, request
->buffer
+ request
->offset
,
4636 request
->bytes_available
, &request
->bytes_read
))
4638 err
= GetLastError();
4641 if ((err
= wait_for_completion( request
))) goto error
;
4642 request
->offset
+= request
->bytes_read
;
4643 } while (request
->bytes_read
);
4645 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
4649 free( request
->buffer
);
4650 request
->buffer
= NULL
;
4651 return HRESULT_FROM_WIN32( err
);
4654 static DWORD
request_set_parameters( struct winhttp_request
*request
)
4656 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_PROXY
, &request
->proxy
,
4657 sizeof(request
->proxy
) )) return GetLastError();
4659 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_AUTOLOGON_POLICY
, &request
->logon_policy
,
4660 sizeof(request
->logon_policy
) )) return GetLastError();
4662 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_DISABLE_FEATURE
, &request
->disable_feature
,
4663 sizeof(request
->disable_feature
) )) return GetLastError();
4665 if (!WinHttpSetTimeouts( request
->hrequest
,
4666 request
->resolve_timeout
,
4667 request
->connect_timeout
,
4668 request
->send_timeout
,
4669 request
->receive_timeout
)) return GetLastError();
4670 return ERROR_SUCCESS
;
4673 static void request_set_utf8_content_type( struct winhttp_request
*request
)
4678 len
= swprintf( headerW
, ARRAY_SIZE(headerW
), L
"%s: %s", L
"Content-Type", L
"text/plain" );
4679 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4681 len
= swprintf( headerW
, ARRAY_SIZE(headerW
), L
"%s: %s", L
"Content-Type", L
"charset=utf-8" );
4682 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
);
4685 static HRESULT
request_send( struct winhttp_request
*request
)
4687 SAFEARRAY
*sa
= NULL
;
4694 if ((err
= request_set_parameters( request
))) return HRESULT_FROM_WIN32( err
);
4695 if (wcscmp( request
->verb
, L
"GET" ))
4697 VariantInit( &data
);
4698 if (V_VT( &request
->data
) == VT_BSTR
)
4701 const WCHAR
*str
= V_BSTR( &request
->data
);
4702 int i
, len
= lstrlenW( str
);
4704 for (i
= 0; i
< len
; i
++)
4712 size
= WideCharToMultiByte( cp
, 0, str
, len
, NULL
, 0, NULL
, NULL
);
4713 if (!(ptr
= malloc( size
))) return E_OUTOFMEMORY
;
4714 WideCharToMultiByte( cp
, 0, str
, len
, ptr
, size
, NULL
, NULL
);
4715 if (cp
== CP_UTF8
) request_set_utf8_content_type( request
);
4717 else if (VariantChangeType( &data
, &request
->data
, 0, VT_ARRAY
|VT_UI1
) == S_OK
)
4719 sa
= V_ARRAY( &data
);
4720 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
) return hr
;
4721 if ((hr
= SafeArrayGetUBound( sa
, 1, &size
)) != S_OK
)
4723 SafeArrayUnaccessData( sa
);
4729 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
);
4730 if (!WinHttpSendRequest( request
->hrequest
, NULL
, 0, ptr
, size
, size
, 0 ))
4732 err
= GetLastError();
4735 if ((err
= wait_for_completion( request
))) goto error
;
4736 if (sa
) SafeArrayUnaccessData( sa
);
4738 request
->state
= REQUEST_STATE_SENT
;
4742 if (sa
) SafeArrayUnaccessData( sa
);
4744 return HRESULT_FROM_WIN32( err
);
4747 static void CALLBACK
send_and_receive_proc( TP_CALLBACK_INSTANCE
*instance
, void *ctx
)
4749 struct winhttp_request
*request
= (struct winhttp_request
*)ctx
;
4750 if (request_send( request
) == S_OK
) request_receive( request
);
4751 SetEvent( request
->done
);
4754 /* critical section must be held */
4755 static DWORD
request_wait( struct winhttp_request
*request
, DWORD timeout
)
4757 HANDLE done
= request
->done
;
4760 LeaveCriticalSection( &request
->cs
);
4761 while ((err
= MsgWaitForMultipleObjects( 1, &done
, FALSE
, timeout
, QS_ALLINPUT
)) == WAIT_OBJECT_0
+ 1)
4764 while (PeekMessageW( &msg
, NULL
, 0, 0, PM_REMOVE
))
4766 TranslateMessage( &msg
);
4767 DispatchMessageW( &msg
);
4773 ret
= request
->error
;
4776 ret
= ERROR_TIMEOUT
;
4779 ret
= GetLastError();
4782 EnterCriticalSection( &request
->cs
);
4783 if (err
== WAIT_OBJECT_0
) request
->proc_running
= FALSE
;
4787 static HRESULT WINAPI
winhttp_request_Send(
4788 IWinHttpRequest
*iface
,
4791 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4794 TRACE("%p, %s\n", request
, debugstr_variant(&body
));
4796 EnterCriticalSection( &request
->cs
);
4797 if (request
->state
< REQUEST_STATE_OPEN
)
4799 LeaveCriticalSection( &request
->cs
);
4800 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
);
4802 if (request
->state
>= REQUEST_STATE_SENT
)
4804 LeaveCriticalSection( &request
->cs
);
4807 VariantClear( &request
->data
);
4808 if ((hr
= VariantCopyInd( &request
->data
, &body
)) != S_OK
)
4810 LeaveCriticalSection( &request
->cs
);
4813 if (!TrySubmitThreadpoolCallback( send_and_receive_proc
, request
, NULL
))
4815 LeaveCriticalSection( &request
->cs
);
4816 return HRESULT_FROM_WIN32( GetLastError() );
4818 request
->proc_running
= TRUE
;
4819 if (!request
->async
)
4821 hr
= HRESULT_FROM_WIN32( request_wait( request
, INFINITE
) );
4823 LeaveCriticalSection( &request
->cs
);
4827 static HRESULT WINAPI
winhttp_request_get_Status(
4828 IWinHttpRequest
*iface
,
4831 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4832 DWORD err
= ERROR_SUCCESS
, flags
, status_code
, len
= sizeof(status_code
), index
= 0;
4834 TRACE("%p, %p\n", request
, status
);
4836 if (!status
) return E_INVALIDARG
;
4838 EnterCriticalSection( &request
->cs
);
4839 if (request
->state
< REQUEST_STATE_SENT
)
4841 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4844 flags
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
4845 if (!WinHttpQueryHeaders( request
->hrequest
, flags
, NULL
, &status_code
, &len
, &index
))
4847 err
= GetLastError();
4850 *status
= status_code
;
4853 LeaveCriticalSection( &request
->cs
);
4854 return HRESULT_FROM_WIN32( err
);
4857 static HRESULT WINAPI
winhttp_request_get_StatusText(
4858 IWinHttpRequest
*iface
,
4861 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4862 DWORD err
= ERROR_SUCCESS
, len
= 0, index
= 0;
4864 TRACE("%p, %p\n", request
, status
);
4866 if (!status
) return E_INVALIDARG
;
4868 EnterCriticalSection( &request
->cs
);
4869 if (request
->state
< REQUEST_STATE_SENT
)
4871 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4874 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, NULL
, &len
, &index
))
4876 err
= GetLastError();
4877 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
4879 if (!(*status
= SysAllocStringLen( NULL
, len
/ sizeof(WCHAR
) )))
4881 err
= ERROR_OUTOFMEMORY
;
4885 err
= ERROR_SUCCESS
;
4886 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, *status
, &len
, &index
))
4888 err
= GetLastError();
4889 SysFreeString( *status
);
4892 LeaveCriticalSection( &request
->cs
);
4893 return HRESULT_FROM_WIN32( err
);
4896 static DWORD
request_get_codepage( struct winhttp_request
*request
, UINT
*codepage
)
4902 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, NULL
, &size
, NULL
) &&
4903 GetLastError() == ERROR_INSUFFICIENT_BUFFER
)
4905 if (!(buffer
= malloc( size
))) return ERROR_OUTOFMEMORY
;
4906 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, buffer
, &size
, NULL
))
4908 return GetLastError();
4910 if ((p
= wcsstr( buffer
, L
"charset" )))
4912 p
+= lstrlenW( L
"charset" );
4913 while (*p
== ' ') p
++;
4916 while (*p
== ' ') p
++;
4917 if (!wcsicmp( p
, L
"utf-8" )) *codepage
= CP_UTF8
;
4922 return ERROR_SUCCESS
;
4925 static HRESULT WINAPI
winhttp_request_get_ResponseText(
4926 IWinHttpRequest
*iface
,
4929 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4931 DWORD err
= ERROR_SUCCESS
;
4934 TRACE("%p, %p\n", request
, body
);
4936 if (!body
) return E_INVALIDARG
;
4938 EnterCriticalSection( &request
->cs
);
4939 if (request
->state
< REQUEST_STATE_SENT
)
4941 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4944 if ((err
= request_get_codepage( request
, &codepage
))) goto done
;
4945 len
= MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, NULL
, 0 );
4946 if (!(*body
= SysAllocStringLen( NULL
, len
)))
4948 err
= ERROR_OUTOFMEMORY
;
4951 MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, *body
, len
);
4955 LeaveCriticalSection( &request
->cs
);
4956 return HRESULT_FROM_WIN32( err
);
4959 static HRESULT WINAPI
winhttp_request_get_ResponseBody(
4960 IWinHttpRequest
*iface
,
4963 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4966 DWORD err
= ERROR_SUCCESS
;
4969 TRACE("%p, %p\n", request
, body
);
4971 if (!body
) return E_INVALIDARG
;
4973 EnterCriticalSection( &request
->cs
);
4974 if (request
->state
< REQUEST_STATE_SENT
)
4976 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4979 if (!(sa
= SafeArrayCreateVector( VT_UI1
, 0, request
->offset
)))
4981 err
= ERROR_OUTOFMEMORY
;
4984 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
)
4986 SafeArrayDestroy( sa
);
4987 LeaveCriticalSection( &request
->cs
);
4990 memcpy( ptr
, request
->buffer
, request
->offset
);
4991 if ((hr
= SafeArrayUnaccessData( sa
)) != S_OK
)
4993 SafeArrayDestroy( sa
);
4994 LeaveCriticalSection( &request
->cs
);
4997 V_VT( body
) = VT_ARRAY
|VT_UI1
;
4998 V_ARRAY( body
) = sa
;
5001 LeaveCriticalSection( &request
->cs
);
5002 return HRESULT_FROM_WIN32( err
);
5007 IStream IStream_iface
;
5010 ULARGE_INTEGER pos
, size
;
5013 static inline struct stream
*impl_from_IStream( IStream
*iface
)
5015 return CONTAINING_RECORD( iface
, struct stream
, IStream_iface
);
5018 static HRESULT WINAPI
stream_QueryInterface( IStream
*iface
, REFIID riid
, void **obj
)
5020 struct stream
*stream
= impl_from_IStream( iface
);
5022 TRACE("%p, %s, %p\n", stream
, debugstr_guid(riid
), obj
);
5024 if (IsEqualGUID( riid
, &IID_IStream
) || IsEqualGUID( riid
, &IID_IUnknown
))
5030 FIXME("interface %s not implemented\n", debugstr_guid(riid
));
5031 return E_NOINTERFACE
;
5033 IStream_AddRef( iface
);
5037 static ULONG WINAPI
stream_AddRef( IStream
*iface
)
5039 struct stream
*stream
= impl_from_IStream( iface
);
5040 return InterlockedIncrement( &stream
->refs
);
5043 static ULONG WINAPI
stream_Release( IStream
*iface
)
5045 struct stream
*stream
= impl_from_IStream( iface
);
5046 LONG refs
= InterlockedDecrement( &stream
->refs
);
5049 free( stream
->data
);
5055 static HRESULT WINAPI
stream_Read( IStream
*iface
, void *buf
, ULONG len
, ULONG
*read
)
5057 struct stream
*stream
= impl_from_IStream( iface
);
5060 if (stream
->pos
.QuadPart
>= stream
->size
.QuadPart
)
5066 size
= min( stream
->size
.QuadPart
- stream
->pos
.QuadPart
, len
);
5067 memcpy( buf
, stream
->data
+ stream
->pos
.QuadPart
, size
);
5068 stream
->pos
.QuadPart
+= size
;
5074 static HRESULT WINAPI
stream_Write( IStream
*iface
, const void *buf
, ULONG len
, ULONG
*written
)
5080 static HRESULT WINAPI
stream_Seek( IStream
*iface
, LARGE_INTEGER move
, DWORD origin
, ULARGE_INTEGER
*newpos
)
5082 struct stream
*stream
= impl_from_IStream( iface
);
5084 if (origin
== STREAM_SEEK_SET
)
5085 stream
->pos
.QuadPart
= move
.QuadPart
;
5086 else if (origin
== STREAM_SEEK_CUR
)
5087 stream
->pos
.QuadPart
+= move
.QuadPart
;
5088 else if (origin
== STREAM_SEEK_END
)
5089 stream
->pos
.QuadPart
= stream
->size
.QuadPart
- move
.QuadPart
;
5091 if (newpos
) newpos
->QuadPart
= stream
->pos
.QuadPart
;
5095 static HRESULT WINAPI
stream_SetSize( IStream
*iface
, ULARGE_INTEGER newsize
)
5101 static HRESULT WINAPI
stream_CopyTo( IStream
*iface
, IStream
*stream
, ULARGE_INTEGER len
, ULARGE_INTEGER
*read
,
5102 ULARGE_INTEGER
*written
)
5108 static HRESULT WINAPI
stream_Commit( IStream
*iface
, DWORD flags
)
5114 static HRESULT WINAPI
stream_Revert( IStream
*iface
)
5120 static HRESULT WINAPI
stream_LockRegion( IStream
*iface
, ULARGE_INTEGER offset
, ULARGE_INTEGER len
, DWORD locktype
)
5126 static HRESULT WINAPI
stream_UnlockRegion( IStream
*iface
, ULARGE_INTEGER offset
, ULARGE_INTEGER len
, DWORD locktype
)
5132 static HRESULT WINAPI
stream_Stat( IStream
*iface
, STATSTG
*stg
, DWORD flag
)
5138 static HRESULT WINAPI
stream_Clone( IStream
*iface
, IStream
**stream
)
5144 static const IStreamVtbl stream_vtbl
=
5146 stream_QueryInterface
,
5157 stream_UnlockRegion
,
5162 static HRESULT WINAPI
winhttp_request_get_ResponseStream(
5163 IWinHttpRequest
*iface
,
5166 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5167 DWORD err
= ERROR_SUCCESS
;
5168 struct stream
*stream
;
5170 TRACE("%p, %p\n", request
, body
);
5172 if (!body
) return E_INVALIDARG
;
5174 EnterCriticalSection( &request
->cs
);
5175 if (request
->state
< REQUEST_STATE_SENT
)
5177 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
5180 if (!(stream
= malloc( sizeof(*stream
) )))
5182 err
= ERROR_OUTOFMEMORY
;
5185 stream
->IStream_iface
.lpVtbl
= &stream_vtbl
;
5187 if (!(stream
->data
= malloc( request
->offset
)))
5190 err
= ERROR_OUTOFMEMORY
;
5193 memcpy( stream
->data
, request
->buffer
, request
->offset
);
5194 stream
->pos
.QuadPart
= 0;
5195 stream
->size
.QuadPart
= request
->offset
;
5196 V_VT( body
) = VT_UNKNOWN
;
5197 V_UNKNOWN( body
) = (IUnknown
*)&stream
->IStream_iface
;
5200 LeaveCriticalSection( &request
->cs
);
5201 return HRESULT_FROM_WIN32( err
);
5204 static HRESULT WINAPI
winhttp_request_get_Option(
5205 IWinHttpRequest
*iface
,
5206 WinHttpRequestOption option
,
5209 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5212 TRACE("%p, %u, %p\n", request
, option
, value
);
5214 EnterCriticalSection( &request
->cs
);
5217 case WinHttpRequestOption_URLCodePage
:
5218 V_VT( value
) = VT_I4
;
5219 V_I4( value
) = request
->url_codepage
;
5222 FIXME("unimplemented option %u\n", option
);
5226 LeaveCriticalSection( &request
->cs
);
5230 static HRESULT WINAPI
winhttp_request_put_Option(
5231 IWinHttpRequest
*iface
,
5232 WinHttpRequestOption option
,
5235 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5238 TRACE("%p, %u, %s\n", request
, option
, debugstr_variant(&value
));
5240 EnterCriticalSection( &request
->cs
);
5243 case WinHttpRequestOption_EnableRedirects
:
5245 if (V_BOOL( &value
))
5246 request
->disable_feature
&= ~WINHTTP_DISABLE_REDIRECTS
;
5248 request
->disable_feature
|= WINHTTP_DISABLE_REDIRECTS
;
5251 case WinHttpRequestOption_URLCodePage
:
5255 hr
= VariantChangeType( &cp
, &value
, 0, VT_UI4
);
5256 if (SUCCEEDED( hr
))
5258 request
->url_codepage
= V_UI4( &cp
);
5259 TRACE("URL codepage: %u\n", request
->url_codepage
);
5261 else if (V_VT( &value
) == VT_BSTR
&& !wcsicmp( V_BSTR( &value
), L
"utf-8" ))
5263 TRACE("URL codepage: UTF-8\n");
5264 request
->url_codepage
= CP_UTF8
;
5268 FIXME("URL codepage %s is not recognized\n", debugstr_variant( &value
));
5272 FIXME("unimplemented option %u\n", option
);
5276 LeaveCriticalSection( &request
->cs
);
5280 static HRESULT WINAPI
winhttp_request_WaitForResponse(
5281 IWinHttpRequest
*iface
,
5283 VARIANT_BOOL
*succeeded
)
5285 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5286 DWORD err
, msecs
= (V_I4(&timeout
) == -1) ? INFINITE
: V_I4(&timeout
) * 1000;
5288 TRACE("%p, %s, %p\n", request
, debugstr_variant(&timeout
), succeeded
);
5290 EnterCriticalSection( &request
->cs
);
5291 if (request
->state
>= REQUEST_STATE_RESPONSE_RECEIVED
)
5293 LeaveCriticalSection( &request
->cs
);
5296 switch ((err
= request_wait( request
, msecs
)))
5299 if (succeeded
) *succeeded
= VARIANT_FALSE
;
5300 err
= ERROR_SUCCESS
;
5304 if (succeeded
) *succeeded
= VARIANT_TRUE
;
5307 LeaveCriticalSection( &request
->cs
);
5308 return HRESULT_FROM_WIN32( err
);
5311 static HRESULT WINAPI
winhttp_request_Abort(
5312 IWinHttpRequest
*iface
)
5314 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5316 TRACE("%p\n", request
);
5318 EnterCriticalSection( &request
->cs
);
5319 cancel_request( request
);
5320 LeaveCriticalSection( &request
->cs
);
5324 static HRESULT WINAPI
winhttp_request_SetTimeouts(
5325 IWinHttpRequest
*iface
,
5326 LONG resolve_timeout
,
5327 LONG connect_timeout
,
5329 LONG receive_timeout
)
5331 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5333 TRACE("%p, %d, %d, %d, %d\n", request
, resolve_timeout
, connect_timeout
, send_timeout
, receive_timeout
);
5335 EnterCriticalSection( &request
->cs
);
5336 request
->resolve_timeout
= resolve_timeout
;
5337 request
->connect_timeout
= connect_timeout
;
5338 request
->send_timeout
= send_timeout
;
5339 request
->receive_timeout
= receive_timeout
;
5340 LeaveCriticalSection( &request
->cs
);
5344 static HRESULT WINAPI
winhttp_request_SetClientCertificate(
5345 IWinHttpRequest
*iface
,
5352 static HRESULT WINAPI
winhttp_request_SetAutoLogonPolicy(
5353 IWinHttpRequest
*iface
,
5354 WinHttpRequestAutoLogonPolicy policy
)
5356 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5359 TRACE("%p, %u\n", request
, policy
);
5361 EnterCriticalSection( &request
->cs
);
5364 case AutoLogonPolicy_Always
:
5365 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW
;
5367 case AutoLogonPolicy_OnlyIfBypassProxy
:
5368 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
5370 case AutoLogonPolicy_Never
:
5371 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH
;
5373 default: hr
= E_INVALIDARG
;
5376 LeaveCriticalSection( &request
->cs
);
5380 static const struct IWinHttpRequestVtbl winhttp_request_vtbl
=
5382 winhttp_request_QueryInterface
,
5383 winhttp_request_AddRef
,
5384 winhttp_request_Release
,
5385 winhttp_request_GetTypeInfoCount
,
5386 winhttp_request_GetTypeInfo
,
5387 winhttp_request_GetIDsOfNames
,
5388 winhttp_request_Invoke
,
5389 winhttp_request_SetProxy
,
5390 winhttp_request_SetCredentials
,
5391 winhttp_request_Open
,
5392 winhttp_request_SetRequestHeader
,
5393 winhttp_request_GetResponseHeader
,
5394 winhttp_request_GetAllResponseHeaders
,
5395 winhttp_request_Send
,
5396 winhttp_request_get_Status
,
5397 winhttp_request_get_StatusText
,
5398 winhttp_request_get_ResponseText
,
5399 winhttp_request_get_ResponseBody
,
5400 winhttp_request_get_ResponseStream
,
5401 winhttp_request_get_Option
,
5402 winhttp_request_put_Option
,
5403 winhttp_request_WaitForResponse
,
5404 winhttp_request_Abort
,
5405 winhttp_request_SetTimeouts
,
5406 winhttp_request_SetClientCertificate
,
5407 winhttp_request_SetAutoLogonPolicy
5410 HRESULT
WinHttpRequest_create( void **obj
)
5412 struct winhttp_request
*request
;
5416 if (!(request
= calloc( 1, sizeof(*request
) ))) return E_OUTOFMEMORY
;
5417 request
->IWinHttpRequest_iface
.lpVtbl
= &winhttp_request_vtbl
;
5419 InitializeCriticalSection( &request
->cs
);
5420 request
->cs
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": winhttp_request.cs");
5421 initialize_request( request
);
5423 *obj
= &request
->IWinHttpRequest_iface
;
5424 TRACE("returning iface %p\n", *obj
);