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
);
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 close_connection( request
);
1806 cache_connection( request
->netconn
);
1807 request
->netconn
= NULL
;
1810 /* return the size of data available to be read immediately */
1811 static DWORD
get_available_data( struct request
*request
)
1813 if (request
->read_chunked
) return min( request
->read_chunked_size
, request
->read_size
);
1814 return request
->read_size
;
1817 /* check if we have reached the end of the data to read */
1818 static BOOL
end_of_read_data( struct request
*request
)
1820 if (!request
->content_length
) return TRUE
;
1821 if (request
->read_chunked
) return request
->read_chunked_eof
;
1822 if (request
->content_length
== ~0u) return FALSE
;
1823 return (request
->content_length
== request
->content_read
);
1826 static DWORD
read_data( struct request
*request
, void *buffer
, DWORD size
, DWORD
*read
, BOOL async
)
1828 int count
, bytes_read
= 0;
1829 DWORD ret
= ERROR_SUCCESS
;
1831 if (end_of_read_data( request
)) goto done
;
1835 if (!(count
= get_available_data( request
)))
1837 if ((ret
= refill_buffer( request
, async
))) goto done
;
1838 if (!(count
= get_available_data( request
))) goto done
;
1840 count
= min( count
, size
);
1841 memcpy( (char *)buffer
+ bytes_read
, request
->read_buf
+ request
->read_pos
, count
);
1842 remove_data( request
, count
);
1843 if (request
->read_chunked
) request
->read_chunked_size
-= count
;
1845 bytes_read
+= count
;
1846 request
->content_read
+= count
;
1847 if (end_of_read_data( request
)) goto done
;
1849 if (request
->read_chunked
&& !request
->read_chunked_size
) ret
= refill_buffer( request
, async
);
1852 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read
, request
->content_read
, request
->content_length
);
1855 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
, buffer
, bytes_read
);
1858 WINHTTP_ASYNC_RESULT result
;
1859 result
.dwResult
= API_READ_DATA
;
1860 result
.dwError
= ret
;
1861 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
1865 if (!ret
&& read
) *read
= bytes_read
;
1866 if (end_of_read_data( request
)) finished_reading( request
);
1870 /* read any content returned by the server so that the connection can be reused */
1871 static void drain_content( struct request
*request
)
1873 DWORD size
, bytes_read
, bytes_total
= 0, bytes_left
= request
->content_length
- request
->content_read
;
1876 refill_buffer( request
, FALSE
);
1879 if (request
->read_chunked
) size
= sizeof(buffer
);
1882 if (bytes_total
>= bytes_left
) return;
1883 size
= min( sizeof(buffer
), bytes_left
- bytes_total
);
1885 if (read_data( request
, buffer
, size
, &bytes_read
, FALSE
) || !bytes_read
) return;
1886 bytes_total
+= bytes_read
;
1892 ESCAPE_FLAG_NON_PRINTABLE
= 0x01,
1893 ESCAPE_FLAG_SPACE
= 0x02,
1894 ESCAPE_FLAG_PERCENT
= 0x04,
1895 ESCAPE_FLAG_UNSAFE
= 0x08,
1896 ESCAPE_FLAG_DEL
= 0x10,
1897 ESCAPE_FLAG_8BIT
= 0x20,
1898 ESCAPE_FLAG_STRIP_CRLF
= 0x40,
1901 #define ESCAPE_MASK_DEFAULT (ESCAPE_FLAG_NON_PRINTABLE | ESCAPE_FLAG_SPACE | ESCAPE_FLAG_UNSAFE |\
1902 ESCAPE_FLAG_DEL | ESCAPE_FLAG_8BIT)
1903 #define ESCAPE_MASK_PERCENT (ESCAPE_FLAG_PERCENT | ESCAPE_MASK_DEFAULT)
1904 #define ESCAPE_MASK_DISABLE (ESCAPE_FLAG_SPACE | ESCAPE_FLAG_8BIT | ESCAPE_FLAG_STRIP_CRLF)
1906 static inline BOOL
need_escape( char ch
, enum escape_flags flags
)
1908 static const char unsafe
[] = "\"#<>[\\]^`{|}";
1909 const char *ptr
= unsafe
;
1911 if ((flags
& ESCAPE_FLAG_SPACE
) && ch
== ' ') return TRUE
;
1912 if ((flags
& ESCAPE_FLAG_PERCENT
) && ch
== '%') return TRUE
;
1913 if ((flags
& ESCAPE_FLAG_NON_PRINTABLE
) && ch
< 0x20) return TRUE
;
1914 if ((flags
& ESCAPE_FLAG_DEL
) && ch
== 0x7f) return TRUE
;
1915 if ((flags
& ESCAPE_FLAG_8BIT
) && (ch
& 0x80)) return TRUE
;
1916 if ((flags
& ESCAPE_FLAG_UNSAFE
)) while (*ptr
) { if (ch
== *ptr
++) return TRUE
; }
1920 static DWORD
escape_string( const char *src
, DWORD len
, char *dst
, enum escape_flags flags
)
1922 static const char hex
[] = "0123456789ABCDEF";
1926 for (i
= 0; i
< len
; i
++)
1928 if ((flags
& ESCAPE_FLAG_STRIP_CRLF
) && (src
[i
] == '\r' || src
[i
] == '\n'))
1933 if (need_escape( src
[i
], flags
))
1938 ptr
[1] = hex
[(src
[i
] >> 4) & 0xf];
1939 ptr
[2] = hex
[src
[i
] & 0xf];
1944 else if (dst
) *ptr
++ = src
[i
];
1947 if (dst
) dst
[ret
] = 0;
1951 static DWORD
str_to_wire( const WCHAR
*src
, int src_len
, char *dst
, enum escape_flags flags
)
1956 if (src_len
< 0) src_len
= lstrlenW( src
);
1957 len
= WideCharToMultiByte( CP_UTF8
, 0, src
, src_len
, NULL
, 0, NULL
, NULL
);
1958 if (!(utf8
= malloc( len
))) return 0;
1960 WideCharToMultiByte( CP_UTF8
, 0, src
, -1, utf8
, len
, NULL
, NULL
);
1961 len
= escape_string( utf8
, len
, dst
, flags
);
1967 static char *build_wire_path( struct request
*request
, DWORD
*ret_len
)
1970 const WCHAR
*start
, *path
, *query
= NULL
;
1971 DWORD len
, len_path
= 0, len_query
= 0;
1972 enum escape_flags path_flags
, query_flags
;
1975 if (!wcsicmp( request
->connect
->hostname
, request
->connect
->servername
)) start
= full_path
= request
->path
;
1976 else if (!(full_path
= build_absolute_request_path( request
, &start
))) return NULL
;
1978 len
= lstrlenW( full_path
);
1979 if ((path
= wcschr( start
, '/' )))
1981 len_path
= lstrlenW( path
);
1982 if ((query
= wcschr( path
, '?' )))
1984 len_query
= lstrlenW( query
);
1985 len_path
-= len_query
;
1989 if (request
->hdr
.flags
& WINHTTP_FLAG_ESCAPE_DISABLE
) path_flags
= ESCAPE_MASK_DISABLE
;
1990 else if (request
->hdr
.flags
& WINHTTP_FLAG_ESCAPE_PERCENT
) path_flags
= ESCAPE_MASK_PERCENT
;
1991 else path_flags
= ESCAPE_MASK_DEFAULT
;
1993 if (request
->hdr
.flags
& WINHTTP_FLAG_ESCAPE_DISABLE_QUERY
) query_flags
= ESCAPE_MASK_DISABLE
;
1994 else query_flags
= path_flags
;
1996 *ret_len
= str_to_wire( full_path
, len
- len_path
- len_query
, NULL
, 0 );
1997 if (path
) *ret_len
+= str_to_wire( path
, len_path
, NULL
, path_flags
);
1998 if (query
) *ret_len
+= str_to_wire( query
, len_query
, NULL
, query_flags
);
2000 if ((ret
= malloc( *ret_len
+ 1 )))
2002 len
= str_to_wire( full_path
, len
- len_path
- len_query
, ret
, 0 );
2003 if (path
) len
+= str_to_wire( path
, len_path
, ret
+ len
, path_flags
);
2004 if (query
) str_to_wire( query
, len_query
, ret
+ len
, query_flags
);
2007 if (full_path
!= request
->path
) free( full_path
);
2011 static char *build_wire_request( struct request
*request
, DWORD
*len
)
2013 char *path
, *ptr
, *ret
;
2016 if (!(path
= build_wire_path( request
, &len_path
))) return NULL
;
2018 *len
= str_to_wire( request
->verb
, -1, NULL
, 0 ) + 1; /* ' ' */
2019 *len
+= len_path
+ 1; /* ' ' */
2020 *len
+= str_to_wire( request
->version
, -1, NULL
, 0 );
2022 for (i
= 0; i
< request
->num_headers
; i
++)
2024 if (request
->headers
[i
].is_request
)
2026 *len
+= str_to_wire( request
->headers
[i
].field
, -1, NULL
, 0 ) + 2; /* ': ' */
2027 *len
+= str_to_wire( request
->headers
[i
].value
, -1, NULL
, 0 ) + 2; /* '\r\n' */
2030 *len
+= 4; /* '\r\n\r\n' */
2032 if ((ret
= ptr
= malloc( *len
+ 1 )))
2034 ptr
+= str_to_wire( request
->verb
, -1, ptr
, 0 );
2036 memcpy( ptr
, path
, len_path
);
2039 ptr
+= str_to_wire( request
->version
, -1, ptr
, 0 );
2041 for (i
= 0; i
< request
->num_headers
; i
++)
2043 if (request
->headers
[i
].is_request
)
2047 ptr
+= str_to_wire( request
->headers
[i
].field
, -1, ptr
, 0 );
2050 ptr
+= str_to_wire( request
->headers
[i
].value
, -1, ptr
, 0 );
2053 memcpy( ptr
, "\r\n\r\n", sizeof("\r\n\r\n") );
2060 static WCHAR
*create_websocket_key(void)
2064 DWORD base64_len
= ((sizeof(buf
) + 2) * 4) / 3;
2065 if (!RtlGenRandom( buf
, sizeof(buf
) )) return NULL
;
2066 if ((ret
= malloc( (base64_len
+ 1) * sizeof(WCHAR
) ))) encode_base64( buf
, sizeof(buf
), ret
);
2070 static DWORD
add_websocket_key_header( struct request
*request
)
2072 WCHAR
*key
= create_websocket_key();
2073 if (!key
) return ERROR_OUTOFMEMORY
;
2074 process_header( request
, L
"Sec-WebSocket-Key", key
, WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
, TRUE
);
2076 return ERROR_SUCCESS
;
2079 static DWORD
send_request( struct request
*request
, const WCHAR
*headers
, DWORD headers_len
, void *optional
,
2080 DWORD optional_len
, DWORD total_len
, DWORD_PTR context
, BOOL async
)
2082 struct connect
*connect
= request
->connect
;
2083 struct session
*session
= connect
->session
;
2088 clear_response_headers( request
);
2089 drain_content( request
);
2092 process_header( request
, L
"User-Agent", session
->agent
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2094 if (connect
->hostname
)
2095 add_host_header( request
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
2097 if (request
->creds
[TARGET_SERVER
][SCHEME_BASIC
].username
)
2098 do_authorization( request
, WINHTTP_AUTH_TARGET_SERVER
, WINHTTP_AUTH_SCHEME_BASIC
);
2100 if (total_len
|| (request
->verb
&& !wcscmp( request
->verb
, L
"POST" )))
2102 WCHAR length
[21]; /* decimal long int + null */
2103 swprintf( length
, ARRAY_SIZE(length
), L
"%ld", total_len
);
2104 process_header( request
, L
"Content-Length", length
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2106 if (request
->flags
& REQUEST_FLAG_WEBSOCKET_UPGRADE
)
2108 process_header( request
, L
"Upgrade", L
"websocket", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2109 process_header( request
, L
"Connection", L
"Upgrade", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2110 process_header( request
, L
"Sec-WebSocket-Version", L
"13", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2111 if ((ret
= add_websocket_key_header( request
))) return ret
;
2113 else if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
))
2115 process_header( request
, L
"Connection", L
"Keep-Alive", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2117 if (request
->hdr
.flags
& WINHTTP_FLAG_REFRESH
)
2119 process_header( request
, L
"Pragma", L
"no-cache", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2120 process_header( request
, L
"Cache-Control", L
"no-cache", WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
2122 if (headers
&& (ret
= add_request_headers( request
, headers
, headers_len
,
2123 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)))
2125 TRACE("failed to add request headers: %u\n", ret
);
2128 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
) && (ret
= add_cookie_headers( request
)))
2130 WARN("failed to add cookie headers: %u\n", ret
);
2134 if (context
) request
->hdr
.context
= context
;
2136 if ((ret
= open_connection( request
))) goto end
;
2137 if (!(wire_req
= build_wire_request( request
, &len
)))
2139 ret
= ERROR_OUTOFMEMORY
;
2142 TRACE("full request: %s\n", debugstr_a(wire_req
));
2144 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST
, NULL
, 0 );
2146 ret
= netconn_send( request
->netconn
, wire_req
, len
, &bytes_sent
);
2152 if ((ret
= netconn_send( request
->netconn
, optional
, optional_len
, &bytes_sent
))) goto end
;
2153 request
->optional
= optional
;
2154 request
->optional_len
= optional_len
;
2155 len
+= optional_len
;
2157 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
, &len
, sizeof(len
) );
2162 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
, NULL
, 0 );
2165 WINHTTP_ASYNC_RESULT result
;
2166 result
.dwResult
= API_SEND_REQUEST
;
2167 result
.dwError
= ret
;
2168 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2174 static void CALLBACK
task_send_request( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2176 struct send_request
*s
= ctx
;
2178 TRACE("running %p\n", work
);
2179 send_request( s
->request
, s
->headers
, s
->headers_len
, s
->optional
, s
->optional_len
, s
->total_len
, s
->context
, TRUE
);
2181 release_object( &s
->request
->hdr
);
2186 /***********************************************************************
2187 * WinHttpSendRequest (winhttp.@)
2189 BOOL WINAPI
WinHttpSendRequest( HINTERNET hrequest
, LPCWSTR headers
, DWORD headers_len
,
2190 LPVOID optional
, DWORD optional_len
, DWORD total_len
, DWORD_PTR context
)
2193 struct request
*request
;
2195 TRACE("%p, %s, %u, %p, %u, %u, %lx\n", hrequest
, debugstr_wn(headers
, headers_len
), headers_len
, optional
,
2196 optional_len
, total_len
, context
);
2198 if (!(request
= (struct request
*)grab_object( hrequest
)))
2200 SetLastError( ERROR_INVALID_HANDLE
);
2203 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2205 release_object( &request
->hdr
);
2206 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2210 if (headers
&& !headers_len
) headers_len
= lstrlenW( headers
);
2212 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2214 struct send_request
*s
;
2216 if (!(s
= malloc( sizeof(*s
) ))) return FALSE
;
2217 s
->request
= request
;
2218 s
->headers
= strdupW( headers
);
2219 s
->headers_len
= headers_len
;
2220 s
->optional
= optional
;
2221 s
->optional_len
= optional_len
;
2222 s
->total_len
= total_len
;
2223 s
->context
= context
;
2225 addref_object( &request
->hdr
);
2226 if ((ret
= queue_task( &request
->queue
, task_send_request
, s
)))
2228 release_object( &request
->hdr
);
2233 else ret
= send_request( request
, headers
, headers_len
, optional
, optional_len
, total_len
, context
, FALSE
);
2235 release_object( &request
->hdr
);
2236 SetLastError( ret
);
2240 static DWORD
set_credentials( struct request
*request
, DWORD target
, DWORD scheme_flag
, const WCHAR
*username
,
2241 const WCHAR
*password
)
2243 enum auth_scheme scheme
= scheme_from_flag( scheme_flag
);
2245 if (scheme
== SCHEME_INVALID
|| ((scheme
== SCHEME_BASIC
|| scheme
== SCHEME_DIGEST
) && (!username
|| !password
)))
2247 return ERROR_INVALID_PARAMETER
;
2251 case WINHTTP_AUTH_TARGET_SERVER
:
2253 free( request
->creds
[TARGET_SERVER
][scheme
].username
);
2254 if (!username
) request
->creds
[TARGET_SERVER
][scheme
].username
= NULL
;
2255 else if (!(request
->creds
[TARGET_SERVER
][scheme
].username
= strdupW( username
))) return ERROR_OUTOFMEMORY
;
2257 free( request
->creds
[TARGET_SERVER
][scheme
].password
);
2258 if (!password
) request
->creds
[TARGET_SERVER
][scheme
].password
= NULL
;
2259 else if (!(request
->creds
[TARGET_SERVER
][scheme
].password
= strdupW( password
))) return ERROR_OUTOFMEMORY
;
2262 case WINHTTP_AUTH_TARGET_PROXY
:
2264 free( request
->creds
[TARGET_PROXY
][scheme
].username
);
2265 if (!username
) request
->creds
[TARGET_PROXY
][scheme
].username
= NULL
;
2266 else if (!(request
->creds
[TARGET_PROXY
][scheme
].username
= strdupW( username
))) return ERROR_OUTOFMEMORY
;
2268 free( request
->creds
[TARGET_PROXY
][scheme
].password
);
2269 if (!password
) request
->creds
[TARGET_PROXY
][scheme
].password
= NULL
;
2270 else if (!(request
->creds
[TARGET_PROXY
][scheme
].password
= strdupW( password
))) return ERROR_OUTOFMEMORY
;
2274 WARN("unknown target %u\n", target
);
2275 return ERROR_INVALID_PARAMETER
;
2277 return ERROR_SUCCESS
;
2280 /***********************************************************************
2281 * WinHttpSetCredentials (winhttp.@)
2283 BOOL WINAPI
WinHttpSetCredentials( HINTERNET hrequest
, DWORD target
, DWORD scheme
, LPCWSTR username
,
2284 LPCWSTR password
, LPVOID params
)
2287 struct request
*request
;
2289 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest
, target
, scheme
, debugstr_w(username
), password
, params
);
2291 if (!(request
= (struct request
*)grab_object( hrequest
)))
2293 SetLastError( ERROR_INVALID_HANDLE
);
2296 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2298 release_object( &request
->hdr
);
2299 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2303 ret
= set_credentials( request
, target
, scheme
, username
, password
);
2305 release_object( &request
->hdr
);
2306 SetLastError( ret
);
2310 static DWORD
handle_authorization( struct request
*request
, DWORD status
)
2312 DWORD ret
, i
, schemes
, first
, level
, target
;
2316 case HTTP_STATUS_DENIED
:
2317 target
= WINHTTP_AUTH_TARGET_SERVER
;
2318 level
= WINHTTP_QUERY_WWW_AUTHENTICATE
;
2321 case HTTP_STATUS_PROXY_AUTH_REQ
:
2322 target
= WINHTTP_AUTH_TARGET_PROXY
;
2323 level
= WINHTTP_QUERY_PROXY_AUTHENTICATE
;
2327 ERR("unhandled status %u\n", status
);
2328 return ERROR_WINHTTP_INTERNAL_ERROR
;
2331 if ((ret
= query_auth_schemes( request
, level
, &schemes
, &first
))) return ret
;
2332 if (do_authorization( request
, target
, first
)) return ERROR_SUCCESS
;
2335 for (i
= 0; i
< ARRAY_SIZE( auth_schemes
); i
++)
2337 if (!(schemes
& auth_schemes
[i
].scheme
)) continue;
2338 if (do_authorization( request
, target
, auth_schemes
[i
].scheme
)) return ERROR_SUCCESS
;
2340 return ERROR_WINHTTP_LOGIN_FAILURE
;
2343 /* set the request content length based on the headers */
2344 static void set_content_length( struct request
*request
, DWORD status
)
2347 DWORD buflen
= sizeof(request
->content_length
);
2349 if (status
== HTTP_STATUS_NO_CONTENT
|| status
== HTTP_STATUS_NOT_MODIFIED
||
2350 status
== HTTP_STATUS_SWITCH_PROTOCOLS
|| !wcscmp( request
->verb
, L
"HEAD" ))
2352 request
->content_length
= 0;
2356 if (query_headers( request
, WINHTTP_QUERY_CONTENT_LENGTH
|WINHTTP_QUERY_FLAG_NUMBER
,
2357 NULL
, &request
->content_length
, &buflen
, NULL
))
2358 request
->content_length
= ~0u;
2360 buflen
= sizeof(encoding
);
2361 if (!query_headers( request
, WINHTTP_QUERY_TRANSFER_ENCODING
, NULL
, encoding
, &buflen
, NULL
) &&
2362 !wcsicmp( encoding
, L
"chunked" ))
2364 request
->content_length
= ~0u;
2365 request
->read_chunked
= TRUE
;
2366 request
->read_chunked_size
= ~0u;
2367 request
->read_chunked_eof
= FALSE
;
2370 request
->content_read
= 0;
2373 static DWORD
read_line( struct request
*request
, char *buffer
, DWORD
*len
)
2375 int count
, bytes_read
, pos
= 0;
2380 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
2383 count
= eol
- (request
->read_buf
+ request
->read_pos
);
2384 bytes_read
= count
+ 1;
2386 else count
= bytes_read
= request
->read_size
;
2388 count
= min( count
, *len
- pos
);
2389 memcpy( buffer
+ pos
, request
->read_buf
+ request
->read_pos
, count
);
2391 remove_data( request
, bytes_read
);
2394 if ((ret
= read_more_data( request
, -1, TRUE
))) return ret
;
2395 if (!request
->read_size
)
2398 TRACE("returning empty string\n");
2399 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
2404 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2407 buffer
[*len
- 1] = 0;
2408 TRACE("returning %s\n", debugstr_a(buffer
));
2409 return ERROR_SUCCESS
;
2412 #define MAX_REPLY_LEN 1460
2413 #define INITIAL_HEADER_BUFFER_LEN 512
2415 static DWORD
read_reply( struct request
*request
)
2417 char buffer
[MAX_REPLY_LEN
];
2418 DWORD ret
, buflen
, len
, offset
, crlf_len
= 2; /* lstrlenW(crlf) */
2419 char *status_code
, *status_text
;
2420 WCHAR
*versionW
, *status_textW
, *raw_headers
;
2421 WCHAR status_codeW
[4]; /* sizeof("nnn") */
2423 if (!request
->netconn
) return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
2427 buflen
= MAX_REPLY_LEN
;
2428 if ((ret
= read_line( request
, buffer
, &buflen
))) return ret
;
2430 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2431 if (!(status_code
= strchr( buffer
, ' ' ))) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
2433 if (!(status_text
= strchr( status_code
, ' ' ))) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
2434 if ((len
= status_text
- status_code
) != sizeof("nnn") - 1) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
2437 TRACE("version [%s] status code [%s] status text [%s]\n",
2438 debugstr_an(buffer
, status_code
- buffer
- 1),
2439 debugstr_an(status_code
, len
),
2440 debugstr_a(status_text
));
2442 } while (!memcmp( status_code
, "100", len
)); /* ignore "100 Continue" responses */
2444 /* we rely on the fact that the protocol is ascii */
2445 MultiByteToWideChar( CP_ACP
, 0, status_code
, len
, status_codeW
, len
);
2446 status_codeW
[len
] = 0;
2447 if ((ret
= process_header( request
, L
"Status", status_codeW
,
2448 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
, FALSE
))) return ret
;
2450 len
= status_code
- buffer
;
2451 if (!(versionW
= malloc( len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
2452 MultiByteToWideChar( CP_ACP
, 0, buffer
, len
- 1, versionW
, len
-1 );
2453 versionW
[len
- 1] = 0;
2455 free( request
->version
);
2456 request
->version
= versionW
;
2458 len
= buflen
- (status_text
- buffer
);
2459 if (!(status_textW
= malloc( len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
2460 MultiByteToWideChar( CP_ACP
, 0, status_text
, len
, status_textW
, len
);
2462 free( request
->status_text
);
2463 request
->status_text
= status_textW
;
2465 len
= max( buflen
+ crlf_len
, INITIAL_HEADER_BUFFER_LEN
);
2466 if (!(raw_headers
= malloc( len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
2467 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
, buflen
);
2468 memcpy( raw_headers
+ buflen
- 1, L
"\r\n", sizeof(L
"\r\n") );
2470 free( request
->raw_headers
);
2471 request
->raw_headers
= raw_headers
;
2473 offset
= buflen
+ crlf_len
- 1;
2476 struct header
*header
;
2478 buflen
= MAX_REPLY_LEN
;
2479 if (read_line( request
, buffer
, &buflen
)) return ERROR_SUCCESS
;
2480 if (!*buffer
) buflen
= 1;
2482 while (len
- offset
< buflen
+ crlf_len
)
2486 if (!(tmp
= realloc( raw_headers
, len
* sizeof(WCHAR
) ))) return ERROR_OUTOFMEMORY
;
2487 request
->raw_headers
= raw_headers
= tmp
;
2491 memcpy( raw_headers
+ offset
, L
"\r\n", sizeof(L
"\r\n") );
2494 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
+ offset
, buflen
);
2496 if (!(header
= parse_header( raw_headers
+ offset
))) break;
2497 if ((ret
= process_header( request
, header
->field
, header
->value
, WINHTTP_ADDREQ_FLAG_ADD
, FALSE
)))
2499 free_header( header
);
2502 free_header( header
);
2503 memcpy( raw_headers
+ offset
+ buflen
- 1, L
"\r\n", sizeof(L
"\r\n") );
2504 offset
+= buflen
+ crlf_len
- 1;
2507 TRACE("raw headers: %s\n", debugstr_w(raw_headers
));
2511 static void record_cookies( struct request
*request
)
2515 for (i
= 0; i
< request
->num_headers
; i
++)
2517 struct header
*set_cookie
= &request
->headers
[i
];
2518 if (!wcsicmp( set_cookie
->field
, L
"Set-Cookie" ) && !set_cookie
->is_request
)
2520 set_cookies( request
, set_cookie
->value
);
2525 static DWORD
get_redirect_url( struct request
*request
, WCHAR
**ret_url
, DWORD
*ret_len
)
2530 ret
= query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, NULL
, &size
, NULL
);
2531 if (ret
!= ERROR_INSUFFICIENT_BUFFER
) return ret
;
2532 if (!(url
= malloc( size
))) return ERROR_OUTOFMEMORY
;
2533 if ((ret
= query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, url
, &size
, NULL
)))
2539 *ret_len
= size
/ sizeof(WCHAR
);
2540 return ERROR_SUCCESS
;
2543 static DWORD
handle_redirect( struct request
*request
, DWORD status
)
2545 DWORD ret
, len
, len_loc
= 0;
2547 struct connect
*connect
= request
->connect
;
2549 WCHAR
*hostname
= NULL
, *location
= NULL
;
2552 if ((ret
= get_redirect_url( request
, &location
, &len_loc
))) return ret
;
2554 memset( &uc
, 0, sizeof(uc
) );
2555 uc
.dwStructSize
= sizeof(uc
);
2556 uc
.dwSchemeLength
= uc
.dwHostNameLength
= uc
.dwUrlPathLength
= uc
.dwExtraInfoLength
= ~0u;
2558 if (!WinHttpCrackUrl( location
, len_loc
, 0, &uc
)) /* assume relative redirect */
2562 ret
= ERROR_OUTOFMEMORY
;
2563 if (location
[0] == '/')
2565 if (!(path
= malloc( (len_loc
+ 1) * sizeof(WCHAR
) ))) goto end
;
2566 memcpy( path
, location
, len_loc
* sizeof(WCHAR
) );
2571 if ((p
= wcsrchr( request
->path
, '/' ))) *p
= 0;
2572 len
= lstrlenW( request
->path
) + 1 + len_loc
;
2573 if (!(path
= malloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2574 lstrcpyW( path
, request
->path
);
2575 lstrcatW( path
, L
"/" );
2576 memcpy( path
+ lstrlenW(path
), location
, len_loc
* sizeof(WCHAR
) );
2579 free( request
->path
);
2580 request
->path
= path
;
2582 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_loc
+ 1 );
2586 if (uc
.nScheme
== INTERNET_SCHEME_HTTP
&& request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
2588 if (request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP
)
2590 ret
= ERROR_WINHTTP_REDIRECT_FAILED
;
2593 TRACE("redirect from secure page to non-secure page\n");
2594 request
->hdr
.flags
&= ~WINHTTP_FLAG_SECURE
;
2596 else if (uc
.nScheme
== INTERNET_SCHEME_HTTPS
&& !(request
->hdr
.flags
& WINHTTP_FLAG_SECURE
))
2598 TRACE("redirect from non-secure page to secure page\n");
2599 request
->hdr
.flags
|= WINHTTP_FLAG_SECURE
;
2602 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_loc
+ 1 );
2604 len
= uc
.dwHostNameLength
;
2605 if (!(hostname
= malloc( (len
+ 1) * sizeof(WCHAR
) )))
2607 ret
= ERROR_OUTOFMEMORY
;
2610 memcpy( hostname
, uc
.lpszHostName
, len
* sizeof(WCHAR
) );
2613 port
= uc
.nPort
? uc
.nPort
: (uc
.nScheme
== INTERNET_SCHEME_HTTPS
? 443 : 80);
2614 if (wcsicmp( connect
->hostname
, hostname
) || connect
->serverport
!= port
)
2616 free( connect
->hostname
);
2617 connect
->hostname
= hostname
;
2618 connect
->hostport
= port
;
2619 if (!set_server_for_hostname( connect
, hostname
, port
))
2621 ret
= ERROR_OUTOFMEMORY
;
2625 netconn_close( request
->netconn
);
2626 request
->netconn
= NULL
;
2627 request
->content_length
= request
->content_read
= 0;
2628 request
->read_pos
= request
->read_size
= 0;
2629 request
->read_chunked
= request
->read_chunked_eof
= FALSE
;
2631 else free( hostname
);
2633 if ((ret
= add_host_header( request
, WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
))) goto end
;
2634 if ((ret
= open_connection( request
))) goto end
;
2636 free( request
->path
);
2637 request
->path
= NULL
;
2638 if (uc
.dwUrlPathLength
)
2640 len
= uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
;
2641 if (!(request
->path
= malloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2642 memcpy( request
->path
, uc
.lpszUrlPath
, (len
+ 1) * sizeof(WCHAR
) );
2643 request
->path
[len
] = 0;
2645 else request
->path
= strdupW( L
"/" );
2648 /* remove content-type/length headers */
2649 if ((index
= get_header_index( request
, L
"Content-Type", 0, TRUE
)) >= 0) delete_header( request
, index
);
2650 if ((index
= get_header_index( request
, L
"Content-Length", 0, TRUE
)) >= 0 ) delete_header( request
, index
);
2652 if (status
!= HTTP_STATUS_REDIRECT_KEEP_VERB
&& !wcscmp( request
->verb
, L
"POST" ))
2654 free( request
->verb
);
2655 request
->verb
= strdupW( L
"GET" );
2656 request
->optional
= NULL
;
2657 request
->optional_len
= 0;
2665 static BOOL
is_passport_request( struct request
*request
)
2667 static const WCHAR passportW
[] = {'P','a','s','s','p','o','r','t','1','.','4'};
2669 DWORD len
= ARRAY_SIZE(buf
);
2671 if (!(request
->connect
->session
->passport_flags
& WINHTTP_ENABLE_PASSPORT_AUTH
) ||
2672 query_headers( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, NULL
, buf
, &len
, NULL
)) return FALSE
;
2674 if (!wcsnicmp( buf
, passportW
, ARRAY_SIZE(passportW
) ) &&
2675 (buf
[ARRAY_SIZE(passportW
)] == ' ' || !buf
[ARRAY_SIZE(passportW
)])) return TRUE
;
2680 static DWORD
handle_passport_redirect( struct request
*request
)
2682 DWORD ret
, flags
= WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
;
2683 int i
, len
= lstrlenW( request
->raw_headers
);
2684 WCHAR
*p
= request
->raw_headers
;
2686 if ((ret
= process_header( request
, L
"Status", L
"401", flags
, FALSE
))) return ret
;
2688 for (i
= 0; i
< len
; i
++)
2690 if (i
<= len
- 3 && p
[i
] == '3' && p
[i
+ 1] == '0' && p
[i
+ 2] == '2')
2697 return ERROR_SUCCESS
;
2700 static DWORD
receive_response( struct request
*request
, BOOL async
)
2702 DWORD ret
, size
, query
, status
;
2704 if (!request
->netconn
) return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
2706 netconn_set_timeout( request
->netconn
, FALSE
, request
->receive_response_timeout
);
2709 if ((ret
= read_reply( request
))) break;
2711 size
= sizeof(DWORD
);
2712 query
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
2713 if ((ret
= query_headers( request
, query
, NULL
, &status
, &size
, NULL
))) break;
2715 set_content_length( request
, status
);
2717 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
)) record_cookies( request
);
2719 if (status
== HTTP_STATUS_REDIRECT
&& is_passport_request( request
))
2721 ret
= handle_passport_redirect( request
);
2723 else if (status
== HTTP_STATUS_MOVED
|| status
== HTTP_STATUS_REDIRECT
|| status
== HTTP_STATUS_REDIRECT_KEEP_VERB
)
2725 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_REDIRECTS
||
2726 request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_NEVER
) break;
2728 if (++request
->redirect_count
> request
->max_redirects
) return ERROR_WINHTTP_REDIRECT_FAILED
;
2730 if ((ret
= handle_redirect( request
, status
))) break;
2732 /* recurse synchronously */
2733 if (!(ret
= send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
))) continue;
2735 else if (status
== HTTP_STATUS_DENIED
|| status
== HTTP_STATUS_PROXY_AUTH_REQ
)
2737 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_AUTHENTICATION
) break;
2739 if ((ret
= handle_authorization( request
, status
))) break;
2741 /* recurse synchronously */
2742 if (!(ret
= send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
))) continue;
2747 if (request
->netconn
) netconn_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
2748 if (request
->content_length
) ret
= refill_buffer( request
, FALSE
);
2752 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
, NULL
, 0 );
2755 WINHTTP_ASYNC_RESULT result
;
2756 result
.dwResult
= API_RECEIVE_RESPONSE
;
2757 result
.dwError
= ret
;
2758 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2764 static void CALLBACK
task_receive_response( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2766 struct receive_response
*r
= ctx
;
2768 TRACE("running %p\n", work
);
2769 receive_response( r
->request
, TRUE
);
2771 release_object( &r
->request
->hdr
);
2775 /***********************************************************************
2776 * WinHttpReceiveResponse (winhttp.@)
2778 BOOL WINAPI
WinHttpReceiveResponse( HINTERNET hrequest
, LPVOID reserved
)
2781 struct request
*request
;
2783 TRACE("%p, %p\n", hrequest
, reserved
);
2785 if (!(request
= (struct request
*)grab_object( hrequest
)))
2787 SetLastError( ERROR_INVALID_HANDLE
);
2790 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2792 release_object( &request
->hdr
);
2793 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2797 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2799 struct receive_response
*r
;
2801 if (!(r
= malloc( sizeof(*r
) ))) return FALSE
;
2802 r
->request
= request
;
2804 addref_object( &request
->hdr
);
2805 if ((ret
= queue_task( &request
->queue
, task_receive_response
, r
)))
2807 release_object( &request
->hdr
);
2811 else ret
= receive_response( request
, FALSE
);
2813 release_object( &request
->hdr
);
2814 SetLastError( ret
);
2818 static DWORD
query_data_available( struct request
*request
, DWORD
*available
, BOOL async
)
2820 DWORD ret
= ERROR_SUCCESS
, count
= 0;
2822 if (end_of_read_data( request
)) goto done
;
2824 count
= get_available_data( request
);
2825 if (!request
->read_chunked
&& request
->netconn
) count
+= netconn_query_data_available( request
->netconn
);
2828 if ((ret
= refill_buffer( request
, async
))) goto done
;
2829 count
= get_available_data( request
);
2830 if (!request
->read_chunked
&& request
->netconn
) count
+= netconn_query_data_available( request
->netconn
);
2834 TRACE("%u bytes available\n", count
);
2837 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
, &count
, sizeof(count
) );
2840 WINHTTP_ASYNC_RESULT result
;
2841 result
.dwResult
= API_QUERY_DATA_AVAILABLE
;
2842 result
.dwError
= ret
;
2843 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2847 if (!ret
&& available
) *available
= count
;
2851 static void CALLBACK
task_query_data_available( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2853 struct query_data
*q
= ctx
;
2855 TRACE("running %p\n", work
);
2856 query_data_available( q
->request
, q
->available
, TRUE
);
2858 release_object( &q
->request
->hdr
);
2862 /***********************************************************************
2863 * WinHttpQueryDataAvailable (winhttp.@)
2865 BOOL WINAPI
WinHttpQueryDataAvailable( HINTERNET hrequest
, LPDWORD available
)
2868 struct request
*request
;
2870 TRACE("%p, %p\n", hrequest
, available
);
2872 if (!(request
= (struct request
*)grab_object( hrequest
)))
2874 SetLastError( ERROR_INVALID_HANDLE
);
2877 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2879 release_object( &request
->hdr
);
2880 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2884 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2886 struct query_data
*q
;
2888 if (!(q
= malloc( sizeof(*q
) ))) return FALSE
;
2889 q
->request
= request
;
2890 q
->available
= available
;
2892 addref_object( &request
->hdr
);
2893 if ((ret
= queue_task( &request
->queue
, task_query_data_available
, q
)))
2895 release_object( &request
->hdr
);
2899 else ret
= query_data_available( request
, available
, FALSE
);
2901 release_object( &request
->hdr
);
2902 SetLastError( ret
);
2906 static void CALLBACK
task_read_data( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2908 struct read_data
*r
= ctx
;
2910 TRACE("running %p\n", work
);
2911 read_data( r
->request
, r
->buffer
, r
->to_read
, r
->read
, TRUE
);
2913 release_object( &r
->request
->hdr
);
2917 /***********************************************************************
2918 * WinHttpReadData (winhttp.@)
2920 BOOL WINAPI
WinHttpReadData( HINTERNET hrequest
, LPVOID buffer
, DWORD to_read
, LPDWORD read
)
2923 struct request
*request
;
2925 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_read
, read
);
2927 if (!(request
= (struct request
*)grab_object( hrequest
)))
2929 SetLastError( ERROR_INVALID_HANDLE
);
2932 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2934 release_object( &request
->hdr
);
2935 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2939 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2941 struct read_data
*r
;
2943 if (!(r
= malloc( sizeof(*r
) ))) return FALSE
;
2944 r
->request
= request
;
2946 r
->to_read
= to_read
;
2949 addref_object( &request
->hdr
);
2950 if ((ret
= queue_task( &request
->queue
, task_read_data
, r
)))
2952 release_object( &request
->hdr
);
2956 else ret
= read_data( request
, buffer
, to_read
, read
, FALSE
);
2958 release_object( &request
->hdr
);
2959 SetLastError( ret
);
2963 static DWORD
write_data( struct request
*request
, const void *buffer
, DWORD to_write
, DWORD
*written
, BOOL async
)
2968 ret
= netconn_send( request
->netconn
, buffer
, to_write
, &num_bytes
);
2972 if (!ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
, &num_bytes
, sizeof(num_bytes
) );
2975 WINHTTP_ASYNC_RESULT result
;
2976 result
.dwResult
= API_WRITE_DATA
;
2977 result
.dwError
= ret
;
2978 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2981 if (!ret
&& written
) *written
= num_bytes
;
2985 static void CALLBACK
task_write_data( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
2987 struct write_data
*w
= ctx
;
2989 TRACE("running %p\n", work
);
2990 write_data( w
->request
, w
->buffer
, w
->to_write
, w
->written
, TRUE
);
2992 release_object( &w
->request
->hdr
);
2996 /***********************************************************************
2997 * WinHttpWriteData (winhttp.@)
2999 BOOL WINAPI
WinHttpWriteData( HINTERNET hrequest
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
)
3002 struct request
*request
;
3004 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_write
, written
);
3006 if (!(request
= (struct request
*)grab_object( hrequest
)))
3008 SetLastError( ERROR_INVALID_HANDLE
);
3011 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
3013 release_object( &request
->hdr
);
3014 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
3018 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3020 struct write_data
*w
;
3022 if (!(w
= malloc( sizeof(*w
) ))) return FALSE
;
3023 w
->request
= request
;
3025 w
->to_write
= to_write
;
3026 w
->written
= written
;
3028 addref_object( &request
->hdr
);
3029 if ((ret
= queue_task( &request
->queue
, task_write_data
, w
)))
3031 release_object( &request
->hdr
);
3035 else ret
= write_data( request
, buffer
, to_write
, written
, FALSE
);
3037 release_object( &request
->hdr
);
3038 SetLastError( ret
);
3042 static BOOL
socket_query_option( struct object_header
*hdr
, DWORD option
, void *buffer
, DWORD
*buflen
)
3044 FIXME("unimplemented option %u\n", option
);
3045 SetLastError( ERROR_WINHTTP_INVALID_OPTION
);
3049 static void socket_destroy( struct object_header
*hdr
)
3051 struct socket
*socket
= (struct socket
*)hdr
;
3053 TRACE("%p\n", socket
);
3055 stop_queue( &socket
->send_q
);
3056 stop_queue( &socket
->recv_q
);
3058 release_object( &socket
->request
->hdr
);
3062 static BOOL
socket_set_option( struct object_header
*hdr
, DWORD option
, void *buffer
, DWORD buflen
)
3064 FIXME("unimplemented option %u\n", option
);
3065 SetLastError( ERROR_WINHTTP_INVALID_OPTION
);
3069 static const struct object_vtbl socket_vtbl
=
3072 socket_query_option
,
3076 HINTERNET WINAPI
WinHttpWebSocketCompleteUpgrade( HINTERNET hrequest
, DWORD_PTR context
)
3078 struct socket
*socket
;
3079 struct request
*request
;
3080 HINTERNET hsocket
= NULL
;
3082 TRACE("%p, %08lx\n", hrequest
, context
);
3084 if (!(request
= (struct request
*)grab_object( hrequest
)))
3086 SetLastError( ERROR_INVALID_HANDLE
);
3089 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
3091 release_object( &request
->hdr
);
3092 SetLastError( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
3095 if (!(socket
= calloc( 1, sizeof(*socket
) )))
3097 release_object( &request
->hdr
);
3100 socket
->hdr
.type
= WINHTTP_HANDLE_TYPE_SOCKET
;
3101 socket
->hdr
.vtbl
= &socket_vtbl
;
3102 socket
->hdr
.refs
= 1;
3103 socket
->hdr
.callback
= request
->hdr
.callback
;
3104 socket
->hdr
.notify_mask
= request
->hdr
.notify_mask
;
3105 socket
->hdr
.context
= context
;
3107 addref_object( &request
->hdr
);
3108 socket
->request
= request
;
3110 if ((hsocket
= alloc_handle( &socket
->hdr
)))
3112 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED
, &hsocket
, sizeof(hsocket
) );
3115 release_object( &socket
->hdr
);
3116 release_object( &request
->hdr
);
3117 TRACE("returning %p\n", hsocket
);
3118 if (hsocket
) SetLastError( ERROR_SUCCESS
);
3122 static DWORD
send_bytes( struct netconn
*netconn
, char *bytes
, int len
)
3126 if ((err
= netconn_send( netconn
, bytes
, len
, &count
))) return err
;
3127 return (count
== len
) ? ERROR_SUCCESS
: ERROR_INTERNAL_ERROR
;
3130 #define FIN_BIT (1 << 7)
3131 #define MASK_BIT (1 << 7)
3132 #define RESERVED_BIT (7 << 4)
3133 #define CONTROL_BIT (1 << 3)
3135 static DWORD
send_frame( struct netconn
*netconn
, enum socket_opcode opcode
, USHORT status
, const char *buf
,
3136 DWORD buflen
, BOOL final
)
3138 DWORD i
= 0, j
, ret
, offset
= 2, len
= buflen
;
3139 char hdr
[14], byte
, *mask
= NULL
;
3141 TRACE("sending %02x frame\n", opcode
);
3143 if (opcode
== SOCKET_OPCODE_CLOSE
) len
+= sizeof(status
);
3145 hdr
[0] = final
? (char)FIN_BIT
: 0;
3147 hdr
[1] = (char)MASK_BIT
;
3148 if (len
< 126) hdr
[1] |= len
;
3149 else if (len
< 65536)
3153 hdr
[3] = len
& 0xff;
3159 hdr
[2] = hdr
[3] = hdr
[4] = hdr
[5] = 0;
3161 hdr
[7] = (len
>> 16) & 0xff;
3162 hdr
[8] = (len
>> 8) & 0xff;
3163 hdr
[9] = len
& 0xff;
3167 if ((ret
= send_bytes( netconn
, hdr
, offset
))) return ret
;
3170 mask
= &hdr
[offset
];
3171 RtlGenRandom( mask
, 4 );
3172 if ((ret
= send_bytes( netconn
, mask
, 4 ))) return ret
;
3175 if (opcode
== SOCKET_OPCODE_CLOSE
) /* prepend status code */
3177 byte
= (status
>> 8) ^ mask
[i
++ % 4];
3178 if ((ret
= send_bytes( netconn
, &byte
, 1 ))) return ret
;
3180 byte
= (status
& 0xff) ^ mask
[i
++ % 4];
3181 if ((ret
= send_bytes( netconn
, &byte
, 1 ))) return ret
;
3184 for (j
= 0; j
< buflen
; j
++)
3186 byte
= buf
[j
] ^ mask
[i
++ % 4];
3187 if ((ret
= send_bytes( netconn
, &byte
, 1 ))) return ret
;
3190 return ERROR_SUCCESS
;
3193 static enum socket_opcode
map_buffer_type( WINHTTP_WEB_SOCKET_BUFFER_TYPE type
)
3197 case WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
: return SOCKET_OPCODE_TEXT
;
3198 case WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
: return SOCKET_OPCODE_BINARY
;
3199 case WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE
: return SOCKET_OPCODE_CLOSE
;
3201 FIXME("buffer type %u not supported\n", type
);
3202 return SOCKET_OPCODE_INVALID
;
3206 static DWORD
socket_send( struct socket
*socket
, WINHTTP_WEB_SOCKET_BUFFER_TYPE type
, const void *buf
, DWORD len
,
3209 enum socket_opcode opcode
= map_buffer_type( type
);
3212 ret
= send_frame( socket
->request
->netconn
, opcode
, 0, buf
, len
, TRUE
);
3217 WINHTTP_WEB_SOCKET_STATUS status
;
3218 status
.dwBytesTransferred
= len
;
3219 status
.eBufferType
= type
;
3220 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
, &status
, sizeof(status
) );
3224 WINHTTP_WEB_SOCKET_ASYNC_RESULT result
;
3225 result
.AsyncResult
.dwResult
= API_WRITE_DATA
;
3226 result
.AsyncResult
.dwError
= ret
;
3227 result
.Operation
= WINHTTP_WEB_SOCKET_SEND_OPERATION
;
3228 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
3234 static void CALLBACK
task_socket_send( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3236 struct socket_send
*s
= ctx
;
3238 TRACE("running %p\n", work
);
3239 socket_send( s
->socket
, s
->type
, s
->buf
, s
->len
, TRUE
);
3241 release_object( &s
->socket
->hdr
);
3245 DWORD WINAPI
WinHttpWebSocketSend( HINTERNET hsocket
, WINHTTP_WEB_SOCKET_BUFFER_TYPE type
, void *buf
, DWORD len
)
3247 struct socket
*socket
;
3250 TRACE("%p, %u, %p, %u\n", hsocket
, type
, buf
, len
);
3252 if (len
&& !buf
) return ERROR_INVALID_PARAMETER
;
3253 if (type
!= WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
&& type
!= WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
)
3255 FIXME("buffer type %u not supported\n", type
);
3256 return ERROR_NOT_SUPPORTED
;
3259 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3260 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3262 release_object( &socket
->hdr
);
3263 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3265 if (socket
->state
!= SOCKET_STATE_OPEN
)
3267 release_object( &socket
->hdr
);
3268 return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
3271 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3273 struct socket_send
*s
;
3275 if (!(s
= malloc( sizeof(*s
) ))) return FALSE
;
3281 addref_object( &socket
->hdr
);
3282 if ((ret
= queue_task( &socket
->send_q
, task_socket_send
, s
)))
3284 release_object( &socket
->hdr
);
3288 else ret
= socket_send( socket
, type
, buf
, len
, FALSE
);
3290 release_object( &socket
->hdr
);
3294 static DWORD
receive_bytes( struct netconn
*netconn
, char *buf
, DWORD len
, DWORD
*ret_len
)
3297 if ((err
= netconn_recv( netconn
, buf
, len
, 0, (int *)ret_len
))) return err
;
3298 if (*ret_len
!= len
) return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
3299 return ERROR_SUCCESS
;
3302 static BOOL
is_supported_opcode( enum socket_opcode opcode
)
3306 case SOCKET_OPCODE_TEXT
:
3307 case SOCKET_OPCODE_BINARY
:
3308 case SOCKET_OPCODE_CLOSE
:
3309 case SOCKET_OPCODE_PING
:
3310 case SOCKET_OPCODE_PONG
:
3313 FIXME( "opcode %02x not handled\n", opcode
);
3318 static DWORD
receive_frame( struct netconn
*netconn
, DWORD
*ret_len
, enum socket_opcode
*opcode
)
3320 DWORD ret
, len
, count
;
3323 if ((ret
= receive_bytes( netconn
, hdr
, sizeof(hdr
), &count
))) return ret
;
3324 if ((hdr
[0] & RESERVED_BIT
) || (hdr
[1] & MASK_BIT
) || !is_supported_opcode( hdr
[0] & 0xf ))
3326 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
3328 *opcode
= hdr
[0] & 0xf;
3329 TRACE("received %02x frame\n", *opcode
);
3331 len
= hdr
[1] & ~MASK_BIT
;
3335 if ((ret
= receive_bytes( netconn
, (char *)&len16
, sizeof(len16
), &count
))) return ret
;
3336 len
= RtlUshortByteSwap( len16
);
3338 else if (len
== 127)
3341 if ((ret
= receive_bytes( netconn
, (char *)&len64
, sizeof(len64
), &count
))) return ret
;
3342 if ((len64
= RtlUlonglongByteSwap( len64
)) > ~0u) return ERROR_NOT_SUPPORTED
;
3347 return ERROR_SUCCESS
;
3350 static void CALLBACK
task_socket_send_pong( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3352 struct socket_send
*s
= ctx
;
3354 TRACE("running %p\n", work
);
3355 send_frame( s
->socket
->request
->netconn
, SOCKET_OPCODE_PONG
, 0, NULL
, 0, TRUE
);
3357 release_object( &s
->socket
->hdr
);
3361 static DWORD
socket_send_pong( struct socket
*socket
)
3363 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3365 struct socket_send
*s
;
3368 if (!(s
= malloc( sizeof(*s
) ))) return ERROR_OUTOFMEMORY
;
3371 addref_object( &socket
->hdr
);
3372 if ((ret
= queue_task( &socket
->send_q
, task_socket_send_pong
, s
)))
3374 release_object( &socket
->hdr
);
3379 return send_frame( socket
->request
->netconn
, SOCKET_OPCODE_PONG
, 0, NULL
, 0, TRUE
);
3382 static DWORD
socket_drain( struct socket
*socket
)
3384 struct netconn
*netconn
= socket
->request
->netconn
;
3387 while (socket
->read_size
)
3390 if ((ret
= receive_bytes( netconn
, buf
, min(socket
->read_size
, sizeof(buf
)), &count
))) return ret
;
3391 socket
->read_size
-= count
;
3393 return ERROR_SUCCESS
;
3396 static DWORD
handle_control_frame( struct socket
*socket
)
3398 switch (socket
->opcode
)
3400 case SOCKET_OPCODE_PING
:
3401 return socket_send_pong( socket
);
3403 case SOCKET_OPCODE_PONG
:
3404 return socket_drain( socket
);
3407 ERR("unhandled control opcode %02x\n", socket
->opcode
);
3408 return ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
3411 return ERROR_SUCCESS
;
3414 static WINHTTP_WEB_SOCKET_BUFFER_TYPE
map_opcode( enum socket_opcode opcode
, BOOL fragment
)
3418 case SOCKET_OPCODE_TEXT
:
3419 if (fragment
) return WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE
;
3420 return WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
;
3422 case SOCKET_OPCODE_BINARY
:
3423 if (fragment
) return WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE
;
3424 return WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
;
3426 case SOCKET_OPCODE_CLOSE
:
3427 return WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE
;
3430 FIXME("opcode %02x not handled\n", opcode
);
3435 static DWORD
socket_receive( struct socket
*socket
, void *buf
, DWORD len
, DWORD
*ret_len
,
3436 WINHTTP_WEB_SOCKET_BUFFER_TYPE
*ret_type
, BOOL async
)
3438 struct netconn
*netconn
= socket
->request
->netconn
;
3439 DWORD count
, ret
= ERROR_SUCCESS
;
3441 if (!socket
->read_size
)
3445 if (!(ret
= receive_frame( netconn
, &socket
->read_size
, &socket
->opcode
)))
3447 if (!(socket
->opcode
& CONTROL_BIT
) || (ret
= handle_control_frame( socket
))) break;
3449 else if (ret
== WSAETIMEDOUT
) ret
= socket_send_pong( socket
);
3453 if (!ret
) ret
= receive_bytes( netconn
, buf
, min(len
, socket
->read_size
), &count
);
3456 socket
->read_size
-= count
;
3460 *ret_type
= map_opcode( socket
->opcode
, socket
->read_size
!= 0 );
3467 WINHTTP_WEB_SOCKET_STATUS status
;
3468 status
.dwBytesTransferred
= count
;
3469 status
.eBufferType
= map_opcode( socket
->opcode
, socket
->read_size
!= 0 );
3470 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
, &status
, sizeof(status
) );
3474 WINHTTP_WEB_SOCKET_ASYNC_RESULT result
;
3475 result
.AsyncResult
.dwResult
= API_READ_DATA
;
3476 result
.AsyncResult
.dwError
= ret
;
3477 result
.Operation
= WINHTTP_WEB_SOCKET_RECEIVE_OPERATION
;
3478 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
3484 static void CALLBACK
task_socket_receive( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3486 struct socket_receive
*r
= ctx
;
3488 TRACE("running %p\n", work
);
3489 socket_receive( r
->socket
, r
->buf
, r
->len
, NULL
, NULL
, TRUE
);
3491 release_object( &r
->socket
->hdr
);
3495 DWORD WINAPI
WinHttpWebSocketReceive( HINTERNET hsocket
, void *buf
, DWORD len
, DWORD
*ret_len
,
3496 WINHTTP_WEB_SOCKET_BUFFER_TYPE
*ret_type
)
3498 struct socket
*socket
;
3501 TRACE("%p, %p, %u, %p, %p\n", hsocket
, buf
, len
, ret_len
, ret_type
);
3503 if (!buf
|| !len
) return ERROR_INVALID_PARAMETER
;
3505 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3506 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3508 release_object( &socket
->hdr
);
3509 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3511 if (socket
->state
!= SOCKET_STATE_OPEN
)
3513 release_object( &socket
->hdr
);
3514 return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
3517 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3519 struct socket_receive
*r
;
3521 if (!(r
= malloc( sizeof(*r
) ))) return FALSE
;
3526 addref_object( &socket
->hdr
);
3527 if ((ret
= queue_task( &socket
->recv_q
, task_socket_receive
, r
)))
3529 release_object( &socket
->hdr
);
3533 else ret
= socket_receive( socket
, buf
, len
, ret_len
, ret_type
, FALSE
);
3535 release_object( &socket
->hdr
);
3539 static DWORD
socket_shutdown( struct socket
*socket
, USHORT status
, const void *reason
, DWORD len
, BOOL async
)
3541 struct netconn
*netconn
= socket
->request
->netconn
;
3544 stop_queue( &socket
->send_q
);
3545 if (!(ret
= send_frame( netconn
, SOCKET_OPCODE_CLOSE
, status
, reason
, len
, TRUE
)))
3547 socket
->state
= SOCKET_STATE_SHUTDOWN
;
3551 if (!ret
) send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE
, NULL
, 0 );
3554 WINHTTP_WEB_SOCKET_ASYNC_RESULT result
;
3555 result
.AsyncResult
.dwResult
= API_WRITE_DATA
;
3556 result
.AsyncResult
.dwError
= ret
;
3557 result
.Operation
= WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION
;
3558 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
3564 static void CALLBACK
task_socket_shutdown( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3566 struct socket_shutdown
*s
= ctx
;
3568 socket_shutdown( s
->socket
, s
->status
, s
->reason
, s
->len
, TRUE
);
3570 TRACE("running %p\n", work
);
3571 release_object( &s
->socket
->hdr
);
3575 DWORD WINAPI
WinHttpWebSocketShutdown( HINTERNET hsocket
, USHORT status
, void *reason
, DWORD len
)
3577 struct socket
*socket
;
3580 TRACE("%p, %u, %p, %u\n", hsocket
, status
, reason
, len
);
3582 if ((len
&& !reason
) || len
> sizeof(socket
->reason
)) return ERROR_INVALID_PARAMETER
;
3584 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3585 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3587 release_object( &socket
->hdr
);
3588 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3590 if (socket
->state
>= SOCKET_STATE_SHUTDOWN
)
3592 release_object( &socket
->hdr
);
3593 return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
3596 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3598 struct socket_shutdown
*s
;
3600 if (!(s
= malloc( sizeof(*s
) ))) return FALSE
;
3603 memcpy( s
->reason
, reason
, len
);
3606 addref_object( &socket
->hdr
);
3607 if ((ret
= queue_task( &socket
->send_q
, task_socket_shutdown
, s
)))
3609 release_object( &socket
->hdr
);
3613 else ret
= socket_shutdown( socket
, status
, reason
, len
, FALSE
);
3615 release_object( &socket
->hdr
);
3619 static DWORD
socket_close( struct socket
*socket
, USHORT status
, const void *reason
, DWORD len
, BOOL async
)
3621 struct netconn
*netconn
= socket
->request
->netconn
;
3624 if ((ret
= socket_drain( socket
))) goto done
;
3626 if (socket
->state
< SOCKET_STATE_SHUTDOWN
)
3628 stop_queue( &socket
->send_q
);
3629 if ((ret
= send_frame( netconn
, SOCKET_OPCODE_CLOSE
, status
, reason
, len
, TRUE
))) goto done
;
3630 socket
->state
= SOCKET_STATE_SHUTDOWN
;
3633 if ((ret
= receive_frame( netconn
, &count
, &socket
->opcode
))) goto done
;
3634 if (socket
->opcode
!= SOCKET_OPCODE_CLOSE
||
3635 (count
&& (count
< sizeof(socket
->status
) || count
> sizeof(socket
->status
) + sizeof(socket
->reason
))))
3637 ret
= ERROR_WINHTTP_INVALID_SERVER_RESPONSE
;
3643 DWORD reason_len
= count
- sizeof(socket
->status
);
3644 if ((ret
= receive_bytes( netconn
, (char *)&socket
->status
, sizeof(socket
->status
), &count
))) goto done
;
3645 socket
->status
= RtlUshortByteSwap( socket
->status
);
3646 if ((ret
= receive_bytes( netconn
, socket
->reason
, reason_len
, &socket
->reason_len
))) goto done
;
3648 socket
->state
= SOCKET_STATE_CLOSED
;
3653 if (!ret
) send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE
, NULL
, 0 );
3656 WINHTTP_WEB_SOCKET_ASYNC_RESULT result
;
3657 result
.AsyncResult
.dwResult
= API_READ_DATA
; /* FIXME */
3658 result
.AsyncResult
.dwError
= ret
;
3659 result
.Operation
= WINHTTP_WEB_SOCKET_CLOSE_OPERATION
;
3660 send_callback( &socket
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
3666 static void CALLBACK
task_socket_close( TP_CALLBACK_INSTANCE
*instance
, void *ctx
, TP_WORK
*work
)
3668 struct socket_shutdown
*s
= ctx
;
3670 socket_close( s
->socket
, s
->status
, s
->reason
, s
->len
, TRUE
);
3672 TRACE("running %p\n", work
);
3673 release_object( &s
->socket
->hdr
);
3677 DWORD WINAPI
WinHttpWebSocketClose( HINTERNET hsocket
, USHORT status
, void *reason
, DWORD len
)
3679 struct socket
*socket
;
3682 TRACE("%p, %u, %p, %u\n", hsocket
, status
, reason
, len
);
3684 if ((len
&& !reason
) || len
> sizeof(socket
->reason
)) return ERROR_INVALID_PARAMETER
;
3686 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3687 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3689 release_object( &socket
->hdr
);
3690 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3692 if (socket
->state
>= SOCKET_STATE_CLOSED
)
3694 release_object( &socket
->hdr
);
3695 return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
3698 if (socket
->request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
3700 struct socket_shutdown
*s
;
3702 if (!(s
= malloc( sizeof(*s
) ))) return FALSE
;
3705 memcpy( s
->reason
, reason
, len
);
3708 addref_object( &socket
->hdr
);
3709 if ((ret
= queue_task( &socket
->recv_q
, task_socket_close
, s
)))
3711 release_object( &socket
->hdr
);
3715 else ret
= socket_close( socket
, status
, reason
, len
, FALSE
);
3717 release_object( &socket
->hdr
);
3721 DWORD WINAPI
WinHttpWebSocketQueryCloseStatus( HINTERNET hsocket
, USHORT
*status
, void *reason
, DWORD len
,
3724 struct socket
*socket
;
3727 TRACE("%p, %p, %p, %u, %p\n", hsocket
, status
, reason
, len
, ret_len
);
3729 if (!status
|| (len
&& !reason
) || !ret_len
) return ERROR_INVALID_PARAMETER
;
3731 if (!(socket
= (struct socket
*)grab_object( hsocket
))) return ERROR_INVALID_HANDLE
;
3732 if (socket
->hdr
.type
!= WINHTTP_HANDLE_TYPE_SOCKET
)
3734 release_object( &socket
->hdr
);
3735 return ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
;
3737 if (socket
->state
< SOCKET_STATE_CLOSED
)
3739 release_object( &socket
->hdr
);
3740 return ERROR_WINHTTP_INCORRECT_HANDLE_STATE
;
3743 *status
= socket
->status
;
3744 *ret_len
= socket
->reason_len
;
3745 if (socket
->reason_len
> len
) ret
= ERROR_INSUFFICIENT_BUFFER
;
3748 memcpy( reason
, socket
->reason
, socket
->reason_len
);
3749 ret
= ERROR_SUCCESS
;
3752 release_object( &socket
->hdr
);
3758 REQUEST_STATE_INITIALIZED
,
3759 REQUEST_STATE_CANCELLED
,
3762 REQUEST_STATE_RESPONSE_RECEIVED
3765 struct winhttp_request
3767 IWinHttpRequest IWinHttpRequest_iface
;
3769 CRITICAL_SECTION cs
;
3770 enum request_state state
;
3782 DWORD bytes_available
;
3786 DWORD disable_feature
;
3787 LONG resolve_timeout
;
3788 LONG connect_timeout
;
3790 LONG receive_timeout
;
3791 WINHTTP_PROXY_INFO proxy
;
3796 static inline struct winhttp_request
*impl_from_IWinHttpRequest( IWinHttpRequest
*iface
)
3798 return CONTAINING_RECORD( iface
, struct winhttp_request
, IWinHttpRequest_iface
);
3801 static ULONG WINAPI
winhttp_request_AddRef(
3802 IWinHttpRequest
*iface
)
3804 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3805 return InterlockedIncrement( &request
->refs
);
3808 /* critical section must be held */
3809 static void cancel_request( struct winhttp_request
*request
)
3811 if (request
->state
<= REQUEST_STATE_CANCELLED
) return;
3813 if (request
->proc_running
)
3815 SetEvent( request
->cancel
);
3816 LeaveCriticalSection( &request
->cs
);
3818 WaitForSingleObject( request
->done
, INFINITE
);
3820 EnterCriticalSection( &request
->cs
);
3822 request
->state
= REQUEST_STATE_CANCELLED
;
3825 /* critical section must be held */
3826 static void free_request( struct winhttp_request
*request
)
3828 if (request
->state
< REQUEST_STATE_INITIALIZED
) return;
3829 WinHttpCloseHandle( request
->hrequest
);
3830 WinHttpCloseHandle( request
->hconnect
);
3831 WinHttpCloseHandle( request
->hsession
);
3832 CloseHandle( request
->done
);
3833 CloseHandle( request
->wait
);
3834 CloseHandle( request
->cancel
);
3835 free( request
->proxy
.lpszProxy
);
3836 free( request
->proxy
.lpszProxyBypass
);
3837 free( request
->buffer
);
3838 free( request
->verb
);
3839 VariantClear( &request
->data
);
3842 static ULONG WINAPI
winhttp_request_Release(
3843 IWinHttpRequest
*iface
)
3845 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3846 LONG refs
= InterlockedDecrement( &request
->refs
);
3849 TRACE("destroying %p\n", request
);
3851 EnterCriticalSection( &request
->cs
);
3852 cancel_request( request
);
3853 free_request( request
);
3854 LeaveCriticalSection( &request
->cs
);
3855 request
->cs
.DebugInfo
->Spare
[0] = 0;
3856 DeleteCriticalSection( &request
->cs
);
3862 static HRESULT WINAPI
winhttp_request_QueryInterface(
3863 IWinHttpRequest
*iface
,
3867 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3869 TRACE("%p, %s, %p\n", request
, debugstr_guid(riid
), obj
);
3871 if (IsEqualGUID( riid
, &IID_IWinHttpRequest
) ||
3872 IsEqualGUID( riid
, &IID_IDispatch
) ||
3873 IsEqualGUID( riid
, &IID_IUnknown
))
3879 FIXME("interface %s not implemented\n", debugstr_guid(riid
));
3880 return E_NOINTERFACE
;
3882 IWinHttpRequest_AddRef( iface
);
3886 static HRESULT WINAPI
winhttp_request_GetTypeInfoCount(
3887 IWinHttpRequest
*iface
,
3890 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3892 TRACE("%p, %p\n", request
, count
);
3899 IWinHttpRequest_tid
,
3903 static ITypeLib
*winhttp_typelib
;
3904 static ITypeInfo
*winhttp_typeinfo
[last_tid
];
3906 static REFIID winhttp_tid_id
[] =
3908 &IID_IWinHttpRequest
3911 static HRESULT
get_typeinfo( enum type_id tid
, ITypeInfo
**ret
)
3915 if (!winhttp_typelib
)
3919 hr
= LoadRegTypeLib( &LIBID_WinHttp
, 5, 1, LOCALE_SYSTEM_DEFAULT
, &typelib
);
3922 ERR("LoadRegTypeLib failed: %08x\n", hr
);
3925 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib
, typelib
, NULL
))
3926 ITypeLib_Release( typelib
);
3928 if (!winhttp_typeinfo
[tid
])
3930 ITypeInfo
*typeinfo
;
3932 hr
= ITypeLib_GetTypeInfoOfGuid( winhttp_typelib
, winhttp_tid_id
[tid
], &typeinfo
);
3935 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id
[tid
]), hr
);
3938 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo
+ tid
), typeinfo
, NULL
))
3939 ITypeInfo_Release( typeinfo
);
3941 *ret
= winhttp_typeinfo
[tid
];
3942 ITypeInfo_AddRef(winhttp_typeinfo
[tid
]);
3946 void release_typelib(void)
3950 for (i
= 0; i
< ARRAY_SIZE(winhttp_typeinfo
); i
++)
3951 if (winhttp_typeinfo
[i
])
3952 ITypeInfo_Release(winhttp_typeinfo
[i
]);
3954 if (winhttp_typelib
)
3955 ITypeLib_Release(winhttp_typelib
);
3958 static HRESULT WINAPI
winhttp_request_GetTypeInfo(
3959 IWinHttpRequest
*iface
,
3964 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3965 TRACE("%p, %u, %u, %p\n", request
, index
, lcid
, info
);
3967 return get_typeinfo( IWinHttpRequest_tid
, info
);
3970 static HRESULT WINAPI
winhttp_request_GetIDsOfNames(
3971 IWinHttpRequest
*iface
,
3978 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3979 ITypeInfo
*typeinfo
;
3982 TRACE("%p, %s, %p, %u, %u, %p\n", request
, debugstr_guid(riid
), names
, count
, lcid
, dispid
);
3984 if (!names
|| !count
|| !dispid
) return E_INVALIDARG
;
3986 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
3989 hr
= ITypeInfo_GetIDsOfNames( typeinfo
, names
, count
, dispid
);
3990 ITypeInfo_Release( typeinfo
);
3995 static HRESULT WINAPI
winhttp_request_Invoke(
3996 IWinHttpRequest
*iface
,
4003 EXCEPINFO
*excep_info
,
4006 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4007 ITypeInfo
*typeinfo
;
4010 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request
, member
, debugstr_guid(riid
),
4011 lcid
, flags
, params
, result
, excep_info
, arg_err
);
4013 if (!IsEqualIID( riid
, &IID_NULL
)) return DISP_E_UNKNOWNINTERFACE
;
4015 if (member
== DISPID_HTTPREQUEST_OPTION
)
4017 VARIANT ret_value
, option
;
4020 if (!result
) result
= &ret_value
;
4021 if (!arg_err
) arg_err
= &err_pos
;
4023 VariantInit( &option
);
4024 VariantInit( result
);
4026 if (!flags
) return S_OK
;
4028 if (flags
== DISPATCH_PROPERTYPUT
)
4030 hr
= DispGetParam( params
, 0, VT_I4
, &option
, arg_err
);
4031 if (FAILED(hr
)) return hr
;
4033 hr
= IWinHttpRequest_put_Option( &request
->IWinHttpRequest_iface
, V_I4( &option
), params
->rgvarg
[0] );
4035 WARN("put_Option(%d) failed: %x\n", V_I4( &option
), hr
);
4038 else if (flags
& (DISPATCH_PROPERTYGET
| DISPATCH_METHOD
))
4040 hr
= DispGetParam( params
, 0, VT_I4
, &option
, arg_err
);
4041 if (FAILED(hr
)) return hr
;
4043 hr
= IWinHttpRequest_get_Option( &request
->IWinHttpRequest_iface
, V_I4( &option
), result
);
4045 WARN("get_Option(%d) failed: %x\n", V_I4( &option
), hr
);
4049 FIXME("unsupported flags %x\n", flags
);
4053 /* fallback to standard implementation */
4055 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
4058 hr
= ITypeInfo_Invoke( typeinfo
, &request
->IWinHttpRequest_iface
, member
, flags
,
4059 params
, result
, excep_info
, arg_err
);
4060 ITypeInfo_Release( typeinfo
);
4065 static HRESULT WINAPI
winhttp_request_SetProxy(
4066 IWinHttpRequest
*iface
,
4067 HTTPREQUEST_PROXY_SETTING proxy_setting
,
4068 VARIANT proxy_server
,
4069 VARIANT bypass_list
)
4071 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4072 DWORD err
= ERROR_SUCCESS
;
4074 TRACE("%p, %u, %s, %s\n", request
, proxy_setting
, debugstr_variant(&proxy_server
),
4075 debugstr_variant(&bypass_list
));
4077 EnterCriticalSection( &request
->cs
);
4078 switch (proxy_setting
)
4080 case HTTPREQUEST_PROXYSETTING_DEFAULT
:
4081 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
4082 free( request
->proxy
.lpszProxy
);
4083 free( request
->proxy
.lpszProxyBypass
);
4084 request
->proxy
.lpszProxy
= NULL
;
4085 request
->proxy
.lpszProxyBypass
= NULL
;
4088 case HTTPREQUEST_PROXYSETTING_DIRECT
:
4089 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NO_PROXY
;
4090 free( request
->proxy
.lpszProxy
);
4091 free( request
->proxy
.lpszProxyBypass
);
4092 request
->proxy
.lpszProxy
= NULL
;
4093 request
->proxy
.lpszProxyBypass
= NULL
;
4096 case HTTPREQUEST_PROXYSETTING_PROXY
:
4097 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
4098 if (V_VT( &proxy_server
) == VT_BSTR
)
4100 free( request
->proxy
.lpszProxy
);
4101 request
->proxy
.lpszProxy
= strdupW( V_BSTR( &proxy_server
) );
4103 if (V_VT( &bypass_list
) == VT_BSTR
)
4105 free( request
->proxy
.lpszProxyBypass
);
4106 request
->proxy
.lpszProxyBypass
= strdupW( V_BSTR( &bypass_list
) );
4111 err
= ERROR_INVALID_PARAMETER
;
4114 LeaveCriticalSection( &request
->cs
);
4115 return HRESULT_FROM_WIN32( err
);
4118 static HRESULT WINAPI
winhttp_request_SetCredentials(
4119 IWinHttpRequest
*iface
,
4122 HTTPREQUEST_SETCREDENTIALS_FLAGS flags
)
4124 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4125 DWORD target
, scheme
= WINHTTP_AUTH_SCHEME_BASIC
; /* FIXME: query supported schemes */
4126 DWORD err
= ERROR_SUCCESS
;
4128 TRACE("%p, %s, %p, 0x%08x\n", request
, debugstr_w(username
), password
, flags
);
4130 EnterCriticalSection( &request
->cs
);
4131 if (request
->state
< REQUEST_STATE_OPEN
)
4133 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
4138 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
:
4139 target
= WINHTTP_AUTH_TARGET_SERVER
;
4141 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY
:
4142 target
= WINHTTP_AUTH_TARGET_PROXY
;
4145 err
= ERROR_INVALID_PARAMETER
;
4148 if (!WinHttpSetCredentials( request
->hrequest
, target
, scheme
, username
, password
, NULL
))
4150 err
= GetLastError();
4153 LeaveCriticalSection( &request
->cs
);
4154 return HRESULT_FROM_WIN32( err
);
4157 static void initialize_request( struct winhttp_request
*request
)
4159 request
->wait
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
4160 request
->cancel
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
4161 request
->done
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
4162 request
->connect_timeout
= 60000;
4163 request
->send_timeout
= 30000;
4164 request
->receive_timeout
= 30000;
4165 request
->url_codepage
= CP_UTF8
;
4166 VariantInit( &request
->data
);
4167 request
->state
= REQUEST_STATE_INITIALIZED
;
4170 static void reset_request( struct winhttp_request
*request
)
4172 cancel_request( request
);
4173 WinHttpCloseHandle( request
->hrequest
);
4174 request
->hrequest
= NULL
;
4175 WinHttpCloseHandle( request
->hconnect
);
4176 request
->hconnect
= NULL
;
4177 free( request
->buffer
);
4178 request
->buffer
= NULL
;
4179 free( request
->verb
);
4180 request
->verb
= NULL
;
4181 request
->offset
= 0;
4182 request
->bytes_available
= 0;
4183 request
->bytes_read
= 0;
4184 request
->error
= ERROR_SUCCESS
;
4185 request
->logon_policy
= 0;
4186 request
->disable_feature
= 0;
4187 request
->async
= FALSE
;
4188 request
->connect_timeout
= 60000;
4189 request
->send_timeout
= 30000;
4190 request
->receive_timeout
= 30000;
4191 request
->url_codepage
= CP_UTF8
;
4192 free( request
->proxy
.lpszProxy
);
4193 request
->proxy
.lpszProxy
= NULL
;
4194 free( request
->proxy
.lpszProxyBypass
);
4195 request
->proxy
.lpszProxyBypass
= NULL
;
4196 VariantClear( &request
->data
);
4197 request
->state
= REQUEST_STATE_INITIALIZED
;
4200 static HRESULT WINAPI
winhttp_request_Open(
4201 IWinHttpRequest
*iface
,
4206 static const WCHAR httpsW
[] = {'h','t','t','p','s'};
4207 static const WCHAR
*acceptW
[] = {L
"*/*", NULL
};
4208 static const WCHAR user_agentW
[] = L
"Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)";
4209 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4211 WCHAR
*hostname
, *path
= NULL
, *verb
= NULL
;
4212 DWORD err
= ERROR_OUTOFMEMORY
, len
, flags
= 0;
4214 TRACE("%p, %s, %s, %s\n", request
, debugstr_w(method
), debugstr_w(url
),
4215 debugstr_variant(&async
));
4217 if (!method
|| !url
) return E_INVALIDARG
;
4219 memset( &uc
, 0, sizeof(uc
) );
4220 uc
.dwStructSize
= sizeof(uc
);
4221 uc
.dwSchemeLength
= ~0u;
4222 uc
.dwHostNameLength
= ~0u;
4223 uc
.dwUrlPathLength
= ~0u;
4224 uc
.dwExtraInfoLength
= ~0u;
4225 if (!WinHttpCrackUrl( url
, 0, 0, &uc
)) return HRESULT_FROM_WIN32( GetLastError() );
4227 EnterCriticalSection( &request
->cs
);
4228 reset_request( request
);
4230 if (!(hostname
= malloc( (uc
.dwHostNameLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
4231 memcpy( hostname
, uc
.lpszHostName
, uc
.dwHostNameLength
* sizeof(WCHAR
) );
4232 hostname
[uc
.dwHostNameLength
] = 0;
4234 if (!(path
= malloc( (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
4235 memcpy( path
, uc
.lpszUrlPath
, (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
) * sizeof(WCHAR
) );
4236 path
[uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
] = 0;
4238 if (!(verb
= strdupW( method
))) goto error
;
4239 if (SUCCEEDED( VariantChangeType( &async
, &async
, 0, VT_BOOL
)) && V_BOOL( &async
)) request
->async
= TRUE
;
4240 else request
->async
= FALSE
;
4242 if (!request
->hsession
)
4244 if (!(request
->hsession
= WinHttpOpen( user_agentW
, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
, NULL
, NULL
,
4245 WINHTTP_FLAG_ASYNC
)))
4247 err
= GetLastError();
4250 if (!(request
->hconnect
= WinHttpConnect( request
->hsession
, hostname
, uc
.nPort
, 0 )))
4252 WinHttpCloseHandle( request
->hsession
);
4253 request
->hsession
= NULL
;
4254 err
= GetLastError();
4258 else if (!(request
->hconnect
= WinHttpConnect( request
->hsession
, hostname
, uc
.nPort
, 0 )))
4260 err
= GetLastError();
4264 len
= ARRAY_SIZE( httpsW
);
4265 if (uc
.dwSchemeLength
== len
&& !memcmp( uc
.lpszScheme
, httpsW
, len
* sizeof(WCHAR
) ))
4267 flags
|= WINHTTP_FLAG_SECURE
;
4269 if (!(request
->hrequest
= WinHttpOpenRequest( request
->hconnect
, method
, path
, NULL
, NULL
, acceptW
, flags
)))
4271 err
= GetLastError();
4274 WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_CONTEXT_VALUE
, &request
, sizeof(request
) );
4276 request
->state
= REQUEST_STATE_OPEN
;
4277 request
->verb
= verb
;
4280 LeaveCriticalSection( &request
->cs
);
4284 WinHttpCloseHandle( request
->hconnect
);
4285 request
->hconnect
= NULL
;
4289 LeaveCriticalSection( &request
->cs
);
4290 return HRESULT_FROM_WIN32( err
);
4293 static HRESULT WINAPI
winhttp_request_SetRequestHeader(
4294 IWinHttpRequest
*iface
,
4298 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4299 DWORD len
, err
= ERROR_SUCCESS
;
4302 TRACE("%p, %s, %s\n", request
, debugstr_w(header
), debugstr_w(value
));
4304 if (!header
) return E_INVALIDARG
;
4306 EnterCriticalSection( &request
->cs
);
4307 if (request
->state
< REQUEST_STATE_OPEN
)
4309 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
4312 if (request
->state
>= REQUEST_STATE_SENT
)
4314 err
= ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND
;
4317 len
= lstrlenW( header
) + 4;
4318 if (value
) len
+= lstrlenW( value
);
4319 if (!(str
= malloc( (len
+ 1) * sizeof(WCHAR
) )))
4321 err
= ERROR_OUTOFMEMORY
;
4324 swprintf( str
, len
+ 1, L
"%s: %s\r\n", header
, value
? value
: L
"" );
4325 if (!WinHttpAddRequestHeaders( request
->hrequest
, str
, len
,
4326 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
))
4328 err
= GetLastError();
4333 LeaveCriticalSection( &request
->cs
);
4334 return HRESULT_FROM_WIN32( err
);
4337 static HRESULT WINAPI
winhttp_request_GetResponseHeader(
4338 IWinHttpRequest
*iface
,
4342 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4343 DWORD size
, err
= ERROR_SUCCESS
;
4345 TRACE("%p, %p\n", request
, header
);
4347 EnterCriticalSection( &request
->cs
);
4348 if (request
->state
< REQUEST_STATE_SENT
)
4350 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4353 if (!header
|| !value
)
4355 err
= ERROR_INVALID_PARAMETER
;
4359 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, NULL
, &size
, NULL
))
4361 err
= GetLastError();
4362 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
4364 if (!(*value
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
4366 err
= ERROR_OUTOFMEMORY
;
4369 err
= ERROR_SUCCESS
;
4370 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, *value
, &size
, NULL
))
4372 err
= GetLastError();
4373 SysFreeString( *value
);
4376 LeaveCriticalSection( &request
->cs
);
4377 return HRESULT_FROM_WIN32( err
);
4380 static HRESULT WINAPI
winhttp_request_GetAllResponseHeaders(
4381 IWinHttpRequest
*iface
,
4384 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4385 DWORD size
, err
= ERROR_SUCCESS
;
4387 TRACE("%p, %p\n", request
, headers
);
4389 if (!headers
) return E_INVALIDARG
;
4391 EnterCriticalSection( &request
->cs
);
4392 if (request
->state
< REQUEST_STATE_SENT
)
4394 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4398 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, NULL
, &size
, NULL
))
4400 err
= GetLastError();
4401 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
4403 if (!(*headers
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
4405 err
= ERROR_OUTOFMEMORY
;
4408 err
= ERROR_SUCCESS
;
4409 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, *headers
, &size
, NULL
))
4411 err
= GetLastError();
4412 SysFreeString( *headers
);
4415 LeaveCriticalSection( &request
->cs
);
4416 return HRESULT_FROM_WIN32( err
);
4419 static void CALLBACK
wait_status_callback( HINTERNET handle
, DWORD_PTR context
, DWORD status
, LPVOID buffer
, DWORD size
)
4421 struct winhttp_request
*request
= (struct winhttp_request
*)context
;
4425 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
:
4426 request
->bytes_available
= *(DWORD
*)buffer
;
4427 request
->error
= ERROR_SUCCESS
;
4429 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE
:
4430 request
->bytes_read
= size
;
4431 request
->error
= ERROR_SUCCESS
;
4433 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
:
4435 WINHTTP_ASYNC_RESULT
*result
= (WINHTTP_ASYNC_RESULT
*)buffer
;
4436 request
->error
= result
->dwError
;
4440 request
->error
= ERROR_SUCCESS
;
4443 SetEvent( request
->wait
);
4446 static void wait_set_status_callback( struct winhttp_request
*request
, DWORD status
)
4448 status
|= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
;
4449 WinHttpSetStatusCallback( request
->hrequest
, wait_status_callback
, status
, 0 );
4452 static DWORD
wait_for_completion( struct winhttp_request
*request
)
4454 HANDLE handles
[2] = { request
->wait
, request
->cancel
};
4457 switch (WaitForMultipleObjects( 2, handles
, FALSE
, INFINITE
))
4460 ret
= request
->error
;
4462 case WAIT_OBJECT_0
+ 1:
4463 ret
= request
->error
= ERROR_CANCELLED
;
4464 SetEvent( request
->done
);
4467 ret
= request
->error
= GetLastError();
4473 static HRESULT
request_receive( struct winhttp_request
*request
)
4475 DWORD err
, size
, buflen
= 4096;
4477 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
);
4478 if (!WinHttpReceiveResponse( request
->hrequest
, NULL
))
4480 return HRESULT_FROM_WIN32( GetLastError() );
4482 if ((err
= wait_for_completion( request
))) return HRESULT_FROM_WIN32( err
);
4483 if (!wcscmp( request
->verb
, L
"HEAD" ))
4485 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
4488 if (!(request
->buffer
= malloc( buflen
))) return E_OUTOFMEMORY
;
4489 request
->buffer
[0] = 0;
4493 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
);
4494 if (!WinHttpQueryDataAvailable( request
->hrequest
, &request
->bytes_available
))
4496 err
= GetLastError();
4499 if ((err
= wait_for_completion( request
))) goto error
;
4500 if (!request
->bytes_available
) break;
4501 size
+= request
->bytes_available
;
4505 while (buflen
< size
) buflen
*= 2;
4506 if (!(tmp
= realloc( request
->buffer
, buflen
)))
4508 err
= ERROR_OUTOFMEMORY
;
4511 request
->buffer
= tmp
;
4513 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
);
4514 if (!WinHttpReadData( request
->hrequest
, request
->buffer
+ request
->offset
,
4515 request
->bytes_available
, &request
->bytes_read
))
4517 err
= GetLastError();
4520 if ((err
= wait_for_completion( request
))) goto error
;
4521 request
->offset
+= request
->bytes_read
;
4522 } while (request
->bytes_read
);
4524 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
4528 free( request
->buffer
);
4529 request
->buffer
= NULL
;
4530 return HRESULT_FROM_WIN32( err
);
4533 static DWORD
request_set_parameters( struct winhttp_request
*request
)
4535 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_PROXY
, &request
->proxy
,
4536 sizeof(request
->proxy
) )) return GetLastError();
4538 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_AUTOLOGON_POLICY
, &request
->logon_policy
,
4539 sizeof(request
->logon_policy
) )) return GetLastError();
4541 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_DISABLE_FEATURE
, &request
->disable_feature
,
4542 sizeof(request
->disable_feature
) )) return GetLastError();
4544 if (!WinHttpSetTimeouts( request
->hrequest
,
4545 request
->resolve_timeout
,
4546 request
->connect_timeout
,
4547 request
->send_timeout
,
4548 request
->receive_timeout
)) return GetLastError();
4549 return ERROR_SUCCESS
;
4552 static void request_set_utf8_content_type( struct winhttp_request
*request
)
4557 len
= swprintf( headerW
, ARRAY_SIZE(headerW
), L
"%s: %s", L
"Content-Type", L
"text/plain" );
4558 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4560 len
= swprintf( headerW
, ARRAY_SIZE(headerW
), L
"%s: %s", L
"Content-Type", L
"charset=utf-8" );
4561 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
);
4564 static HRESULT
request_send( struct winhttp_request
*request
)
4566 SAFEARRAY
*sa
= NULL
;
4573 if ((err
= request_set_parameters( request
))) return HRESULT_FROM_WIN32( err
);
4574 if (wcscmp( request
->verb
, L
"GET" ))
4576 VariantInit( &data
);
4577 if (V_VT( &request
->data
) == VT_BSTR
)
4580 const WCHAR
*str
= V_BSTR( &request
->data
);
4581 int i
, len
= lstrlenW( str
);
4583 for (i
= 0; i
< len
; i
++)
4591 size
= WideCharToMultiByte( cp
, 0, str
, len
, NULL
, 0, NULL
, NULL
);
4592 if (!(ptr
= malloc( size
))) return E_OUTOFMEMORY
;
4593 WideCharToMultiByte( cp
, 0, str
, len
, ptr
, size
, NULL
, NULL
);
4594 if (cp
== CP_UTF8
) request_set_utf8_content_type( request
);
4596 else if (VariantChangeType( &data
, &request
->data
, 0, VT_ARRAY
|VT_UI1
) == S_OK
)
4598 sa
= V_ARRAY( &data
);
4599 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
) return hr
;
4600 if ((hr
= SafeArrayGetUBound( sa
, 1, &size
)) != S_OK
)
4602 SafeArrayUnaccessData( sa
);
4608 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
);
4609 if (!WinHttpSendRequest( request
->hrequest
, NULL
, 0, ptr
, size
, size
, 0 ))
4611 err
= GetLastError();
4614 if ((err
= wait_for_completion( request
))) goto error
;
4615 if (sa
) SafeArrayUnaccessData( sa
);
4617 request
->state
= REQUEST_STATE_SENT
;
4621 if (sa
) SafeArrayUnaccessData( sa
);
4623 return HRESULT_FROM_WIN32( err
);
4626 static void CALLBACK
send_and_receive_proc( TP_CALLBACK_INSTANCE
*instance
, void *ctx
)
4628 struct winhttp_request
*request
= (struct winhttp_request
*)ctx
;
4629 if (request_send( request
) == S_OK
) request_receive( request
);
4630 SetEvent( request
->done
);
4633 /* critical section must be held */
4634 static DWORD
request_wait( struct winhttp_request
*request
, DWORD timeout
)
4636 HANDLE done
= request
->done
;
4639 LeaveCriticalSection( &request
->cs
);
4640 while ((err
= MsgWaitForMultipleObjects( 1, &done
, FALSE
, timeout
, QS_ALLINPUT
)) == WAIT_OBJECT_0
+ 1)
4643 while (PeekMessageW( &msg
, NULL
, 0, 0, PM_REMOVE
))
4645 TranslateMessage( &msg
);
4646 DispatchMessageW( &msg
);
4652 ret
= request
->error
;
4655 ret
= ERROR_TIMEOUT
;
4658 ret
= GetLastError();
4661 EnterCriticalSection( &request
->cs
);
4662 if (err
== WAIT_OBJECT_0
) request
->proc_running
= FALSE
;
4666 static HRESULT WINAPI
winhttp_request_Send(
4667 IWinHttpRequest
*iface
,
4670 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4673 TRACE("%p, %s\n", request
, debugstr_variant(&body
));
4675 EnterCriticalSection( &request
->cs
);
4676 if (request
->state
< REQUEST_STATE_OPEN
)
4678 LeaveCriticalSection( &request
->cs
);
4679 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
);
4681 if (request
->state
>= REQUEST_STATE_SENT
)
4683 LeaveCriticalSection( &request
->cs
);
4686 VariantClear( &request
->data
);
4687 if ((hr
= VariantCopyInd( &request
->data
, &body
)) != S_OK
)
4689 LeaveCriticalSection( &request
->cs
);
4692 if (!TrySubmitThreadpoolCallback( send_and_receive_proc
, request
, NULL
))
4694 LeaveCriticalSection( &request
->cs
);
4695 return HRESULT_FROM_WIN32( GetLastError() );
4697 request
->proc_running
= TRUE
;
4698 if (!request
->async
)
4700 hr
= HRESULT_FROM_WIN32( request_wait( request
, INFINITE
) );
4702 LeaveCriticalSection( &request
->cs
);
4706 static HRESULT WINAPI
winhttp_request_get_Status(
4707 IWinHttpRequest
*iface
,
4710 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4711 DWORD err
= ERROR_SUCCESS
, flags
, status_code
, len
= sizeof(status_code
), index
= 0;
4713 TRACE("%p, %p\n", request
, status
);
4715 if (!status
) return E_INVALIDARG
;
4717 EnterCriticalSection( &request
->cs
);
4718 if (request
->state
< REQUEST_STATE_SENT
)
4720 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4723 flags
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
4724 if (!WinHttpQueryHeaders( request
->hrequest
, flags
, NULL
, &status_code
, &len
, &index
))
4726 err
= GetLastError();
4729 *status
= status_code
;
4732 LeaveCriticalSection( &request
->cs
);
4733 return HRESULT_FROM_WIN32( err
);
4736 static HRESULT WINAPI
winhttp_request_get_StatusText(
4737 IWinHttpRequest
*iface
,
4740 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4741 DWORD err
= ERROR_SUCCESS
, len
= 0, index
= 0;
4743 TRACE("%p, %p\n", request
, status
);
4745 if (!status
) return E_INVALIDARG
;
4747 EnterCriticalSection( &request
->cs
);
4748 if (request
->state
< REQUEST_STATE_SENT
)
4750 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4753 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, NULL
, &len
, &index
))
4755 err
= GetLastError();
4756 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
4758 if (!(*status
= SysAllocStringLen( NULL
, len
/ sizeof(WCHAR
) )))
4760 err
= ERROR_OUTOFMEMORY
;
4764 err
= ERROR_SUCCESS
;
4765 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, *status
, &len
, &index
))
4767 err
= GetLastError();
4768 SysFreeString( *status
);
4771 LeaveCriticalSection( &request
->cs
);
4772 return HRESULT_FROM_WIN32( err
);
4775 static DWORD
request_get_codepage( struct winhttp_request
*request
, UINT
*codepage
)
4781 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, NULL
, &size
, NULL
) &&
4782 GetLastError() == ERROR_INSUFFICIENT_BUFFER
)
4784 if (!(buffer
= malloc( size
))) return ERROR_OUTOFMEMORY
;
4785 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, buffer
, &size
, NULL
))
4787 return GetLastError();
4789 if ((p
= wcsstr( buffer
, L
"charset" )))
4791 p
+= lstrlenW( L
"charset" );
4792 while (*p
== ' ') p
++;
4795 while (*p
== ' ') p
++;
4796 if (!wcsicmp( p
, L
"utf-8" )) *codepage
= CP_UTF8
;
4801 return ERROR_SUCCESS
;
4804 static HRESULT WINAPI
winhttp_request_get_ResponseText(
4805 IWinHttpRequest
*iface
,
4808 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4810 DWORD err
= ERROR_SUCCESS
;
4813 TRACE("%p, %p\n", request
, body
);
4815 if (!body
) return E_INVALIDARG
;
4817 EnterCriticalSection( &request
->cs
);
4818 if (request
->state
< REQUEST_STATE_SENT
)
4820 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4823 if ((err
= request_get_codepage( request
, &codepage
))) goto done
;
4824 len
= MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, NULL
, 0 );
4825 if (!(*body
= SysAllocStringLen( NULL
, len
)))
4827 err
= ERROR_OUTOFMEMORY
;
4830 MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, *body
, len
);
4834 LeaveCriticalSection( &request
->cs
);
4835 return HRESULT_FROM_WIN32( err
);
4838 static HRESULT WINAPI
winhttp_request_get_ResponseBody(
4839 IWinHttpRequest
*iface
,
4842 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
4845 DWORD err
= ERROR_SUCCESS
;
4848 TRACE("%p, %p\n", request
, body
);
4850 if (!body
) return E_INVALIDARG
;
4852 EnterCriticalSection( &request
->cs
);
4853 if (request
->state
< REQUEST_STATE_SENT
)
4855 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
4858 if (!(sa
= SafeArrayCreateVector( VT_UI1
, 0, request
->offset
)))
4860 err
= ERROR_OUTOFMEMORY
;
4863 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
)
4865 SafeArrayDestroy( sa
);
4866 LeaveCriticalSection( &request
->cs
);
4869 memcpy( ptr
, request
->buffer
, request
->offset
);
4870 if ((hr
= SafeArrayUnaccessData( sa
)) != S_OK
)
4872 SafeArrayDestroy( sa
);
4873 LeaveCriticalSection( &request
->cs
);
4876 V_VT( body
) = VT_ARRAY
|VT_UI1
;
4877 V_ARRAY( body
) = sa
;
4880 LeaveCriticalSection( &request
->cs
);
4881 return HRESULT_FROM_WIN32( err
);
4886 IStream IStream_iface
;
4889 ULARGE_INTEGER pos
, size
;
4892 static inline struct stream
*impl_from_IStream( IStream
*iface
)
4894 return CONTAINING_RECORD( iface
, struct stream
, IStream_iface
);
4897 static HRESULT WINAPI
stream_QueryInterface( IStream
*iface
, REFIID riid
, void **obj
)
4899 struct stream
*stream
= impl_from_IStream( iface
);
4901 TRACE("%p, %s, %p\n", stream
, debugstr_guid(riid
), obj
);
4903 if (IsEqualGUID( riid
, &IID_IStream
) || IsEqualGUID( riid
, &IID_IUnknown
))
4909 FIXME("interface %s not implemented\n", debugstr_guid(riid
));
4910 return E_NOINTERFACE
;
4912 IStream_AddRef( iface
);
4916 static ULONG WINAPI
stream_AddRef( IStream
*iface
)
4918 struct stream
*stream
= impl_from_IStream( iface
);
4919 return InterlockedIncrement( &stream
->refs
);
4922 static ULONG WINAPI
stream_Release( IStream
*iface
)
4924 struct stream
*stream
= impl_from_IStream( iface
);
4925 LONG refs
= InterlockedDecrement( &stream
->refs
);
4928 free( stream
->data
);
4934 static HRESULT WINAPI
stream_Read( IStream
*iface
, void *buf
, ULONG len
, ULONG
*read
)
4936 struct stream
*stream
= impl_from_IStream( iface
);
4939 if (stream
->pos
.QuadPart
>= stream
->size
.QuadPart
)
4945 size
= min( stream
->size
.QuadPart
- stream
->pos
.QuadPart
, len
);
4946 memcpy( buf
, stream
->data
+ stream
->pos
.QuadPart
, size
);
4947 stream
->pos
.QuadPart
+= size
;
4953 static HRESULT WINAPI
stream_Write( IStream
*iface
, const void *buf
, ULONG len
, ULONG
*written
)
4959 static HRESULT WINAPI
stream_Seek( IStream
*iface
, LARGE_INTEGER move
, DWORD origin
, ULARGE_INTEGER
*newpos
)
4961 struct stream
*stream
= impl_from_IStream( iface
);
4963 if (origin
== STREAM_SEEK_SET
)
4964 stream
->pos
.QuadPart
= move
.QuadPart
;
4965 else if (origin
== STREAM_SEEK_CUR
)
4966 stream
->pos
.QuadPart
+= move
.QuadPart
;
4967 else if (origin
== STREAM_SEEK_END
)
4968 stream
->pos
.QuadPart
= stream
->size
.QuadPart
- move
.QuadPart
;
4970 if (newpos
) newpos
->QuadPart
= stream
->pos
.QuadPart
;
4974 static HRESULT WINAPI
stream_SetSize( IStream
*iface
, ULARGE_INTEGER newsize
)
4980 static HRESULT WINAPI
stream_CopyTo( IStream
*iface
, IStream
*stream
, ULARGE_INTEGER len
, ULARGE_INTEGER
*read
,
4981 ULARGE_INTEGER
*written
)
4987 static HRESULT WINAPI
stream_Commit( IStream
*iface
, DWORD flags
)
4993 static HRESULT WINAPI
stream_Revert( IStream
*iface
)
4999 static HRESULT WINAPI
stream_LockRegion( IStream
*iface
, ULARGE_INTEGER offset
, ULARGE_INTEGER len
, DWORD locktype
)
5005 static HRESULT WINAPI
stream_UnlockRegion( IStream
*iface
, ULARGE_INTEGER offset
, ULARGE_INTEGER len
, DWORD locktype
)
5011 static HRESULT WINAPI
stream_Stat( IStream
*iface
, STATSTG
*stg
, DWORD flag
)
5017 static HRESULT WINAPI
stream_Clone( IStream
*iface
, IStream
**stream
)
5023 static const IStreamVtbl stream_vtbl
=
5025 stream_QueryInterface
,
5036 stream_UnlockRegion
,
5041 static HRESULT WINAPI
winhttp_request_get_ResponseStream(
5042 IWinHttpRequest
*iface
,
5045 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5046 DWORD err
= ERROR_SUCCESS
;
5047 struct stream
*stream
;
5049 TRACE("%p, %p\n", request
, body
);
5051 if (!body
) return E_INVALIDARG
;
5053 EnterCriticalSection( &request
->cs
);
5054 if (request
->state
< REQUEST_STATE_SENT
)
5056 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
5059 if (!(stream
= malloc( sizeof(*stream
) )))
5061 err
= ERROR_OUTOFMEMORY
;
5064 stream
->IStream_iface
.lpVtbl
= &stream_vtbl
;
5066 if (!(stream
->data
= malloc( request
->offset
)))
5069 err
= ERROR_OUTOFMEMORY
;
5072 memcpy( stream
->data
, request
->buffer
, request
->offset
);
5073 stream
->pos
.QuadPart
= 0;
5074 stream
->size
.QuadPart
= request
->offset
;
5075 V_VT( body
) = VT_UNKNOWN
;
5076 V_UNKNOWN( body
) = (IUnknown
*)&stream
->IStream_iface
;
5079 LeaveCriticalSection( &request
->cs
);
5080 return HRESULT_FROM_WIN32( err
);
5083 static HRESULT WINAPI
winhttp_request_get_Option(
5084 IWinHttpRequest
*iface
,
5085 WinHttpRequestOption option
,
5088 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5091 TRACE("%p, %u, %p\n", request
, option
, value
);
5093 EnterCriticalSection( &request
->cs
);
5096 case WinHttpRequestOption_URLCodePage
:
5097 V_VT( value
) = VT_I4
;
5098 V_I4( value
) = request
->url_codepage
;
5101 FIXME("unimplemented option %u\n", option
);
5105 LeaveCriticalSection( &request
->cs
);
5109 static HRESULT WINAPI
winhttp_request_put_Option(
5110 IWinHttpRequest
*iface
,
5111 WinHttpRequestOption option
,
5114 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5117 TRACE("%p, %u, %s\n", request
, option
, debugstr_variant(&value
));
5119 EnterCriticalSection( &request
->cs
);
5122 case WinHttpRequestOption_EnableRedirects
:
5124 if (V_BOOL( &value
))
5125 request
->disable_feature
&= ~WINHTTP_DISABLE_REDIRECTS
;
5127 request
->disable_feature
|= WINHTTP_DISABLE_REDIRECTS
;
5130 case WinHttpRequestOption_URLCodePage
:
5134 hr
= VariantChangeType( &cp
, &value
, 0, VT_UI4
);
5135 if (SUCCEEDED( hr
))
5137 request
->url_codepage
= V_UI4( &cp
);
5138 TRACE("URL codepage: %u\n", request
->url_codepage
);
5140 else if (V_VT( &value
) == VT_BSTR
&& !wcsicmp( V_BSTR( &value
), L
"utf-8" ))
5142 TRACE("URL codepage: UTF-8\n");
5143 request
->url_codepage
= CP_UTF8
;
5147 FIXME("URL codepage %s is not recognized\n", debugstr_variant( &value
));
5151 FIXME("unimplemented option %u\n", option
);
5155 LeaveCriticalSection( &request
->cs
);
5159 static HRESULT WINAPI
winhttp_request_WaitForResponse(
5160 IWinHttpRequest
*iface
,
5162 VARIANT_BOOL
*succeeded
)
5164 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5165 DWORD err
, msecs
= (V_I4(&timeout
) == -1) ? INFINITE
: V_I4(&timeout
) * 1000;
5167 TRACE("%p, %s, %p\n", request
, debugstr_variant(&timeout
), succeeded
);
5169 EnterCriticalSection( &request
->cs
);
5170 if (request
->state
>= REQUEST_STATE_RESPONSE_RECEIVED
)
5172 LeaveCriticalSection( &request
->cs
);
5175 switch ((err
= request_wait( request
, msecs
)))
5178 if (succeeded
) *succeeded
= VARIANT_FALSE
;
5179 err
= ERROR_SUCCESS
;
5183 if (succeeded
) *succeeded
= VARIANT_TRUE
;
5186 LeaveCriticalSection( &request
->cs
);
5187 return HRESULT_FROM_WIN32( err
);
5190 static HRESULT WINAPI
winhttp_request_Abort(
5191 IWinHttpRequest
*iface
)
5193 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5195 TRACE("%p\n", request
);
5197 EnterCriticalSection( &request
->cs
);
5198 cancel_request( request
);
5199 LeaveCriticalSection( &request
->cs
);
5203 static HRESULT WINAPI
winhttp_request_SetTimeouts(
5204 IWinHttpRequest
*iface
,
5205 LONG resolve_timeout
,
5206 LONG connect_timeout
,
5208 LONG receive_timeout
)
5210 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5212 TRACE("%p, %d, %d, %d, %d\n", request
, resolve_timeout
, connect_timeout
, send_timeout
, receive_timeout
);
5214 EnterCriticalSection( &request
->cs
);
5215 request
->resolve_timeout
= resolve_timeout
;
5216 request
->connect_timeout
= connect_timeout
;
5217 request
->send_timeout
= send_timeout
;
5218 request
->receive_timeout
= receive_timeout
;
5219 LeaveCriticalSection( &request
->cs
);
5223 static HRESULT WINAPI
winhttp_request_SetClientCertificate(
5224 IWinHttpRequest
*iface
,
5231 static HRESULT WINAPI
winhttp_request_SetAutoLogonPolicy(
5232 IWinHttpRequest
*iface
,
5233 WinHttpRequestAutoLogonPolicy policy
)
5235 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
5238 TRACE("%p, %u\n", request
, policy
);
5240 EnterCriticalSection( &request
->cs
);
5243 case AutoLogonPolicy_Always
:
5244 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW
;
5246 case AutoLogonPolicy_OnlyIfBypassProxy
:
5247 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
5249 case AutoLogonPolicy_Never
:
5250 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH
;
5252 default: hr
= E_INVALIDARG
;
5255 LeaveCriticalSection( &request
->cs
);
5259 static const struct IWinHttpRequestVtbl winhttp_request_vtbl
=
5261 winhttp_request_QueryInterface
,
5262 winhttp_request_AddRef
,
5263 winhttp_request_Release
,
5264 winhttp_request_GetTypeInfoCount
,
5265 winhttp_request_GetTypeInfo
,
5266 winhttp_request_GetIDsOfNames
,
5267 winhttp_request_Invoke
,
5268 winhttp_request_SetProxy
,
5269 winhttp_request_SetCredentials
,
5270 winhttp_request_Open
,
5271 winhttp_request_SetRequestHeader
,
5272 winhttp_request_GetResponseHeader
,
5273 winhttp_request_GetAllResponseHeaders
,
5274 winhttp_request_Send
,
5275 winhttp_request_get_Status
,
5276 winhttp_request_get_StatusText
,
5277 winhttp_request_get_ResponseText
,
5278 winhttp_request_get_ResponseBody
,
5279 winhttp_request_get_ResponseStream
,
5280 winhttp_request_get_Option
,
5281 winhttp_request_put_Option
,
5282 winhttp_request_WaitForResponse
,
5283 winhttp_request_Abort
,
5284 winhttp_request_SetTimeouts
,
5285 winhttp_request_SetClientCertificate
,
5286 winhttp_request_SetAutoLogonPolicy
5289 HRESULT
WinHttpRequest_create( void **obj
)
5291 struct winhttp_request
*request
;
5295 if (!(request
= calloc( 1, sizeof(*request
) ))) return E_OUTOFMEMORY
;
5296 request
->IWinHttpRequest_iface
.lpVtbl
= &winhttp_request_vtbl
;
5298 InitializeCriticalSection( &request
->cs
);
5299 request
->cs
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": winhttp_request.cs");
5300 initialize_request( request
);
5302 *obj
= &request
->IWinHttpRequest_iface
;
5303 TRACE("returning iface %p\n", *obj
);