2 * Copyright 2004 Mike McCormack for CodeWeavers
3 * Copyright 2006 Rob Shearman for CodeWeavers
4 * Copyright 2008, 2011 Hans Leidekker for CodeWeavers
5 * Copyright 2009 Juan Lang
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "winhttp_private.h"
24 #ifdef HAVE_ARPA_INET_H
25 # include <arpa/inet.h>
29 #include <httprequest.h>
31 #include "inet_ntop.c"
33 static const WCHAR attr_accept
[] = {'A','c','c','e','p','t',0};
34 static const WCHAR attr_accept_charset
[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
35 static const WCHAR attr_accept_encoding
[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
36 static const WCHAR attr_accept_language
[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
37 static const WCHAR attr_accept_ranges
[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
38 static const WCHAR attr_age
[] = {'A','g','e',0};
39 static const WCHAR attr_allow
[] = {'A','l','l','o','w',0};
40 static const WCHAR attr_authorization
[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
41 static const WCHAR attr_cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
42 static const WCHAR attr_connection
[] = {'C','o','n','n','e','c','t','i','o','n',0};
43 static const WCHAR attr_content_base
[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
44 static const WCHAR attr_content_encoding
[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
45 static const WCHAR attr_content_id
[] = {'C','o','n','t','e','n','t','-','I','D',0};
46 static const WCHAR attr_content_language
[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
47 static const WCHAR attr_content_length
[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
48 static const WCHAR attr_content_location
[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
49 static const WCHAR attr_content_md5
[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
50 static const WCHAR attr_content_range
[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
51 static const WCHAR attr_content_transfer_encoding
[] = {'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
52 static const WCHAR attr_content_type
[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
53 static const WCHAR attr_cookie
[] = {'C','o','o','k','i','e',0};
54 static const WCHAR attr_date
[] = {'D','a','t','e',0};
55 static const WCHAR attr_from
[] = {'F','r','o','m',0};
56 static const WCHAR attr_etag
[] = {'E','T','a','g',0};
57 static const WCHAR attr_expect
[] = {'E','x','p','e','c','t',0};
58 static const WCHAR attr_expires
[] = {'E','x','p','i','r','e','s',0};
59 static const WCHAR attr_host
[] = {'H','o','s','t',0};
60 static const WCHAR attr_if_match
[] = {'I','f','-','M','a','t','c','h',0};
61 static const WCHAR attr_if_modified_since
[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
62 static const WCHAR attr_if_none_match
[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
63 static const WCHAR attr_if_range
[] = {'I','f','-','R','a','n','g','e',0};
64 static const WCHAR attr_if_unmodified_since
[] = {'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
65 static const WCHAR attr_last_modified
[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
66 static const WCHAR attr_location
[] = {'L','o','c','a','t','i','o','n',0};
67 static const WCHAR attr_max_forwards
[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
68 static const WCHAR attr_mime_version
[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
69 static const WCHAR attr_pragma
[] = {'P','r','a','g','m','a',0};
70 static const WCHAR attr_proxy_authenticate
[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
71 static const WCHAR attr_proxy_authorization
[] = {'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0};
72 static const WCHAR attr_proxy_connection
[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
73 static const WCHAR attr_public
[] = {'P','u','b','l','i','c',0};
74 static const WCHAR attr_range
[] = {'R','a','n','g','e',0};
75 static const WCHAR attr_referer
[] = {'R','e','f','e','r','e','r',0};
76 static const WCHAR attr_retry_after
[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
77 static const WCHAR attr_server
[] = {'S','e','r','v','e','r',0};
78 static const WCHAR attr_set_cookie
[] = {'S','e','t','-','C','o','o','k','i','e',0};
79 static const WCHAR attr_status
[] = {'S','t','a','t','u','s',0};
80 static const WCHAR attr_transfer_encoding
[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
81 static const WCHAR attr_unless_modified_since
[] = {'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
82 static const WCHAR attr_upgrade
[] = {'U','p','g','r','a','d','e',0};
83 static const WCHAR attr_uri
[] = {'U','R','I',0};
84 static const WCHAR attr_user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',0};
85 static const WCHAR attr_vary
[] = {'V','a','r','y',0};
86 static const WCHAR attr_via
[] = {'V','i','a',0};
87 static const WCHAR attr_warning
[] = {'W','a','r','n','i','n','g',0};
88 static const WCHAR attr_www_authenticate
[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
90 static const WCHAR
*attribute_table
[] =
92 attr_mime_version
, /* WINHTTP_QUERY_MIME_VERSION = 0 */
93 attr_content_type
, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
94 attr_content_transfer_encoding
, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
95 attr_content_id
, /* WINHTTP_QUERY_CONTENT_ID = 3 */
96 NULL
, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
97 attr_content_length
, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
98 attr_content_language
, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
99 attr_allow
, /* WINHTTP_QUERY_ALLOW = 7 */
100 attr_public
, /* WINHTTP_QUERY_PUBLIC = 8 */
101 attr_date
, /* WINHTTP_QUERY_DATE = 9 */
102 attr_expires
, /* WINHTTP_QUERY_EXPIRES = 10 */
103 attr_last_modified
, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
104 NULL
, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
105 attr_uri
, /* WINHTTP_QUERY_URI = 13 */
106 attr_from
, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
107 NULL
, /* WINHTTP_QUERY_COST = 15 */
108 NULL
, /* WINHTTP_QUERY_LINK = 16 */
109 attr_pragma
, /* WINHTTP_QUERY_PRAGMA = 17 */
110 NULL
, /* WINHTTP_QUERY_VERSION = 18 */
111 attr_status
, /* WINHTTP_QUERY_STATUS_CODE = 19 */
112 NULL
, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
113 NULL
, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
114 NULL
, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
115 attr_connection
, /* WINHTTP_QUERY_CONNECTION = 23 */
116 attr_accept
, /* WINHTTP_QUERY_ACCEPT = 24 */
117 attr_accept_charset
, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
118 attr_accept_encoding
, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
119 attr_accept_language
, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
120 attr_authorization
, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
121 attr_content_encoding
, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
122 NULL
, /* WINHTTP_QUERY_FORWARDED = 30 */
123 NULL
, /* WINHTTP_QUERY_FROM = 31 */
124 attr_if_modified_since
, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
125 attr_location
, /* WINHTTP_QUERY_LOCATION = 33 */
126 NULL
, /* WINHTTP_QUERY_ORIG_URI = 34 */
127 attr_referer
, /* WINHTTP_QUERY_REFERER = 35 */
128 attr_retry_after
, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
129 attr_server
, /* WINHTTP_QUERY_SERVER = 37 */
130 NULL
, /* WINHTTP_TITLE = 38 */
131 attr_user_agent
, /* WINHTTP_QUERY_USER_AGENT = 39 */
132 attr_www_authenticate
, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
133 attr_proxy_authenticate
, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
134 attr_accept_ranges
, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
135 attr_set_cookie
, /* WINHTTP_QUERY_SET_COOKIE = 43 */
136 attr_cookie
, /* WINHTTP_QUERY_COOKIE = 44 */
137 NULL
, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
138 NULL
, /* WINHTTP_QUERY_REFRESH = 46 */
139 NULL
, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
140 attr_age
, /* WINHTTP_QUERY_AGE = 48 */
141 attr_cache_control
, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
142 attr_content_base
, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
143 attr_content_location
, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
144 attr_content_md5
, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
145 attr_content_range
, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
146 attr_etag
, /* WINHTTP_QUERY_ETAG = 54 */
147 attr_host
, /* WINHTTP_QUERY_HOST = 55 */
148 attr_if_match
, /* WINHTTP_QUERY_IF_MATCH = 56 */
149 attr_if_none_match
, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
150 attr_if_range
, /* WINHTTP_QUERY_IF_RANGE = 58 */
151 attr_if_unmodified_since
, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
152 attr_max_forwards
, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
153 attr_proxy_authorization
, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
154 attr_range
, /* WINHTTP_QUERY_RANGE = 62 */
155 attr_transfer_encoding
, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
156 attr_upgrade
, /* WINHTTP_QUERY_UPGRADE = 64 */
157 attr_vary
, /* WINHTTP_QUERY_VARY = 65 */
158 attr_via
, /* WINHTTP_QUERY_VIA = 66 */
159 attr_warning
, /* WINHTTP_QUERY_WARNING = 67 */
160 attr_expect
, /* WINHTTP_QUERY_EXPECT = 68 */
161 attr_proxy_connection
, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
162 attr_unless_modified_since
, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
163 NULL
, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
164 NULL
, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
165 NULL
, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
166 NULL
/* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
169 static DWORD CALLBACK
task_thread( LPVOID param
)
171 task_header_t
*task
= param
;
175 release_object( &task
->request
->hdr
);
177 return ERROR_SUCCESS
;
180 static BOOL
queue_task( task_header_t
*task
)
182 return QueueUserWorkItem( task_thread
, task
, WT_EXECUTELONGFUNCTION
);
185 static void free_header( header_t
*header
)
187 heap_free( header
->field
);
188 heap_free( header
->value
);
192 static BOOL
valid_token_char( WCHAR c
)
194 if (c
< 32 || c
== 127) return FALSE
;
201 case '\\': case '\"':
213 static header_t
*parse_header( LPCWSTR string
)
220 if (!(q
= strchrW( p
, ':' )))
222 WARN("no ':' in line %s\n", debugstr_w(string
));
227 WARN("empty field name in line %s\n", debugstr_w(string
));
232 if (!valid_token_char( *p
))
234 WARN("invalid character in field name %s\n", debugstr_w(string
));
240 if (!(header
= heap_alloc_zero( sizeof(header_t
) ))) return NULL
;
241 if (!(header
->field
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
246 memcpy( header
->field
, string
, len
* sizeof(WCHAR
) );
247 header
->field
[len
] = 0;
249 q
++; /* skip past colon */
250 while (*q
== ' ') q
++;
253 WARN("no value in line %s\n", debugstr_w(string
));
257 if (!(header
->value
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
259 free_header( header
);
262 memcpy( header
->value
, q
, len
* sizeof(WCHAR
) );
263 header
->value
[len
] = 0;
268 static int get_header_index( request_t
*request
, LPCWSTR field
, int requested_index
, BOOL request_only
)
272 TRACE("%s\n", debugstr_w(field
));
274 for (index
= 0; index
< request
->num_headers
; index
++)
276 if (strcmpiW( request
->headers
[index
].field
, field
)) continue;
277 if (request_only
&& !request
->headers
[index
].is_request
) continue;
278 if (!request_only
&& request
->headers
[index
].is_request
) continue;
280 if (!requested_index
) break;
283 if (index
>= request
->num_headers
) index
= -1;
284 TRACE("returning %d\n", index
);
288 static BOOL
insert_header( request_t
*request
, header_t
*header
)
293 count
= request
->num_headers
+ 1;
295 hdrs
= heap_realloc_zero( request
->headers
, sizeof(header_t
) * count
);
297 hdrs
= heap_alloc_zero( sizeof(header_t
) * count
);
301 request
->headers
= hdrs
;
302 request
->headers
[count
- 1].field
= strdupW( header
->field
);
303 request
->headers
[count
- 1].value
= strdupW( header
->value
);
304 request
->headers
[count
- 1].is_request
= header
->is_request
;
305 request
->num_headers
++;
311 static BOOL
delete_header( request_t
*request
, DWORD index
)
313 if (!request
->num_headers
) return FALSE
;
314 if (index
>= request
->num_headers
) return FALSE
;
315 request
->num_headers
--;
317 heap_free( request
->headers
[index
].field
);
318 heap_free( request
->headers
[index
].value
);
320 memmove( &request
->headers
[index
], &request
->headers
[index
+ 1], (request
->num_headers
- index
) * sizeof(header_t
) );
321 memset( &request
->headers
[request
->num_headers
], 0, sizeof(header_t
) );
325 static BOOL
process_header( request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD flags
, BOOL request_only
)
330 TRACE("%s: %s 0x%08x\n", debugstr_w(field
), debugstr_w(value
), flags
);
332 /* replace wins out over add */
333 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
) flags
&= ~WINHTTP_ADDREQ_FLAG_ADD
;
335 if (flags
& WINHTTP_ADDREQ_FLAG_ADD
) index
= -1;
337 index
= get_header_index( request
, field
, 0, request_only
);
341 if (flags
& WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
) return FALSE
;
342 header
= &request
->headers
[index
];
348 hdr
.field
= (LPWSTR
)field
;
349 hdr
.value
= (LPWSTR
)value
;
350 hdr
.is_request
= request_only
;
352 return insert_header( request
, &hdr
);
354 /* no value to delete */
357 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
)
359 delete_header( request
, index
);
364 hdr
.field
= (LPWSTR
)field
;
365 hdr
.value
= (LPWSTR
)value
;
366 hdr
.is_request
= request_only
;
368 return insert_header( request
, &hdr
);
372 else if (flags
& (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
| WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
))
375 int len
, orig_len
, value_len
;
377 orig_len
= strlenW( header
->value
);
378 value_len
= strlenW( value
);
380 if (flags
& WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
) sep
= ',';
383 len
= orig_len
+ value_len
+ 2;
384 if ((tmp
= heap_realloc( header
->value
, (len
+ 1) * sizeof(WCHAR
) )))
388 header
->value
[orig_len
] = sep
;
390 header
->value
[orig_len
] = ' ';
393 memcpy( &header
->value
[orig_len
], value
, value_len
* sizeof(WCHAR
) );
394 header
->value
[len
] = 0;
401 BOOL
add_request_headers( request_t
*request
, LPCWSTR headers
, DWORD len
, DWORD flags
)
404 WCHAR
*buffer
, *p
, *q
;
407 if (len
== ~0u) len
= strlenW( headers
);
408 if (!len
) return TRUE
;
409 if (!(buffer
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
410 strcpyW( buffer
, headers
);
418 if (q
[0] == '\n' && q
[1] == '\r')
423 if (q
[0] == '\r' && q
[1] == '\n') break;
430 q
+= 2; /* jump over \r\n */
432 if ((header
= parse_header( p
)))
434 ret
= process_header( request
, header
->field
, header
->value
, flags
, TRUE
);
435 free_header( header
);
444 /***********************************************************************
445 * WinHttpAddRequestHeaders (winhttp.@)
447 BOOL WINAPI
WinHttpAddRequestHeaders( HINTERNET hrequest
, LPCWSTR headers
, DWORD len
, DWORD flags
)
452 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest
, debugstr_w(headers
), len
, flags
);
456 set_last_error( ERROR_INVALID_PARAMETER
);
459 if (!(request
= (request_t
*)grab_object( hrequest
)))
461 set_last_error( ERROR_INVALID_HANDLE
);
464 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
466 release_object( &request
->hdr
);
467 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
471 ret
= add_request_headers( request
, headers
, len
, flags
);
473 release_object( &request
->hdr
);
477 static WCHAR
*build_request_path( request_t
*request
)
481 if (strcmpiW( request
->connect
->hostname
, request
->connect
->servername
))
483 static const WCHAR http
[] = { 'h','t','t','p',0 };
484 static const WCHAR https
[] = { 'h','t','t','p','s',0 };
485 static const WCHAR fmt
[] = { '%','s',':','/','/','%','s',0 };
486 LPCWSTR scheme
= request
->netconn
.secure
? https
: http
;
489 len
= strlenW( scheme
) + strlenW( request
->connect
->hostname
);
490 /* 3 characters for '://', 1 for NUL. */
492 if (request
->connect
->hostport
)
494 /* 1 for ':' between host and port, up to 5 for port */
498 len
+= strlenW( request
->path
);
499 if ((ret
= heap_alloc( len
* sizeof(WCHAR
) )))
501 sprintfW( ret
, fmt
, scheme
, request
->connect
->hostname
);
502 if (request
->connect
->hostport
)
504 static const WCHAR colonFmt
[] = { ':','%','u',0 };
506 sprintfW( ret
+ strlenW( ret
), colonFmt
,
507 request
->connect
->hostport
);
510 strcatW( ret
, request
->path
);
518 static WCHAR
*build_request_string( request_t
*request
)
520 static const WCHAR space
[] = {' ',0};
521 static const WCHAR crlf
[] = {'\r','\n',0};
522 static const WCHAR colon
[] = {':',' ',0};
523 static const WCHAR twocrlf
[] = {'\r','\n','\r','\n',0};
526 const WCHAR
**headers
, **p
;
527 unsigned int len
, i
= 0, j
;
529 /* allocate space for an array of all the string pointers to be added */
530 len
= request
->num_headers
* 4 + 7;
531 if (!(headers
= heap_alloc( len
* sizeof(LPCWSTR
) ))) return NULL
;
533 path
= build_request_path( request
);
534 headers
[i
++] = request
->verb
;
535 headers
[i
++] = space
;
537 headers
[i
++] = space
;
538 headers
[i
++] = request
->version
;
540 for (j
= 0; j
< request
->num_headers
; j
++)
542 if (request
->headers
[j
].is_request
)
545 headers
[i
++] = request
->headers
[j
].field
;
546 headers
[i
++] = colon
;
547 headers
[i
++] = request
->headers
[j
].value
;
549 TRACE("adding header %s (%s)\n", debugstr_w(request
->headers
[j
].field
),
550 debugstr_w(request
->headers
[j
].value
));
553 headers
[i
++] = twocrlf
;
557 for (p
= headers
; *p
; p
++) len
+= strlenW( *p
);
560 if (!(ret
= heap_alloc( len
* sizeof(WCHAR
) )))
563 for (p
= headers
; *p
; p
++) strcatW( ret
, *p
);
566 if (path
!= request
->path
)
568 heap_free( headers
);
572 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
574 static BOOL
query_headers( request_t
*request
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
576 header_t
*header
= NULL
;
577 BOOL request_only
, ret
= FALSE
;
578 int requested_index
, header_index
= -1;
581 request_only
= level
& WINHTTP_QUERY_FLAG_REQUEST_HEADERS
;
582 requested_index
= index
? *index
: 0;
584 attr
= level
& ~QUERY_MODIFIER_MASK
;
587 case WINHTTP_QUERY_CUSTOM
:
589 header_index
= get_header_index( request
, name
, requested_index
, request_only
);
592 case WINHTTP_QUERY_RAW_HEADERS
:
594 WCHAR
*headers
, *p
, *q
;
597 headers
= build_request_string( request
);
599 headers
= request
->raw_headers
;
601 if (!(p
= headers
)) return FALSE
;
602 for (len
= 0; *p
; p
++) if (*p
!= '\r') len
++;
604 if (!buffer
|| (len
+ 1) * sizeof(WCHAR
) > *buflen
)
607 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
611 for (p
= headers
, q
= buffer
; *p
; p
++, q
++)
613 if (*p
!= '\r') *q
= *p
;
621 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
));
624 *buflen
= len
* sizeof(WCHAR
);
625 if (request_only
) heap_free( headers
);
628 case WINHTTP_QUERY_RAW_HEADERS_CRLF
:
633 headers
= build_request_string( request
);
635 headers
= request
->raw_headers
;
637 if (!headers
) return FALSE
;
638 len
= strlenW( headers
) * sizeof(WCHAR
);
639 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
641 len
+= sizeof(WCHAR
);
642 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
646 memcpy( buffer
, headers
, len
+ sizeof(WCHAR
) );
647 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
/ sizeof(WCHAR
)));
651 if (request_only
) heap_free( headers
);
654 case WINHTTP_QUERY_VERSION
:
655 len
= strlenW( request
->version
) * sizeof(WCHAR
);
656 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
658 len
+= sizeof(WCHAR
);
659 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
663 strcpyW( buffer
, request
->version
);
664 TRACE("returning string: %s\n", debugstr_w(buffer
));
670 case WINHTTP_QUERY_STATUS_TEXT
:
671 len
= strlenW( request
->status_text
) * sizeof(WCHAR
);
672 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
674 len
+= sizeof(WCHAR
);
675 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
679 strcpyW( buffer
, request
->status_text
);
680 TRACE("returning string: %s\n", debugstr_w(buffer
));
687 if (attr
>= sizeof(attribute_table
)/sizeof(attribute_table
[0]) || !attribute_table
[attr
])
689 FIXME("attribute %u not implemented\n", attr
);
692 TRACE("attribute %s\n", debugstr_w(attribute_table
[attr
]));
693 header_index
= get_header_index( request
, attribute_table
[attr
], requested_index
, request_only
);
697 if (header_index
>= 0)
699 header
= &request
->headers
[header_index
];
701 if (!header
|| (request_only
&& !header
->is_request
))
703 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND
);
706 if (index
) *index
+= 1;
707 if (level
& WINHTTP_QUERY_FLAG_NUMBER
)
709 if (!buffer
|| sizeof(int) > *buflen
)
711 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
715 int *number
= buffer
;
716 *number
= atoiW( header
->value
);
717 TRACE("returning number: %d\n", *number
);
720 *buflen
= sizeof(int);
722 else if (level
& WINHTTP_QUERY_FLAG_SYSTEMTIME
)
724 SYSTEMTIME
*st
= buffer
;
725 if (!buffer
|| sizeof(SYSTEMTIME
) > *buflen
)
727 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
729 else if ((ret
= WinHttpTimeToSystemTime( header
->value
, st
)))
731 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
732 st
->wYear
, st
->wMonth
, st
->wDay
, st
->wDayOfWeek
,
733 st
->wHour
, st
->wMinute
, st
->wSecond
, st
->wMilliseconds
);
735 *buflen
= sizeof(SYSTEMTIME
);
737 else if (header
->value
)
739 len
= strlenW( header
->value
) * sizeof(WCHAR
);
740 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
742 len
+= sizeof(WCHAR
);
743 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
747 strcpyW( buffer
, header
->value
);
748 TRACE("returning string: %s\n", debugstr_w(buffer
));
756 /***********************************************************************
757 * WinHttpQueryHeaders (winhttp.@)
759 BOOL WINAPI
WinHttpQueryHeaders( HINTERNET hrequest
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
764 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest
, level
, debugstr_w(name
), buffer
, buflen
, index
);
766 if (!(request
= (request_t
*)grab_object( hrequest
)))
768 set_last_error( ERROR_INVALID_HANDLE
);
771 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
773 release_object( &request
->hdr
);
774 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
778 ret
= query_headers( request
, level
, name
, buffer
, buflen
, index
);
780 release_object( &request
->hdr
);
784 static LPWSTR
concatenate_string_list( LPCWSTR
*list
, int len
)
789 for( t
= list
; *t
; t
++ )
790 len
+= strlenW( *t
);
793 str
= heap_alloc( len
* sizeof(WCHAR
) );
794 if (!str
) return NULL
;
797 for( t
= list
; *t
; t
++ )
803 static LPWSTR
build_header_request_string( request_t
*request
, LPCWSTR verb
,
804 LPCWSTR path
, LPCWSTR version
)
806 static const WCHAR crlf
[] = {'\r','\n',0};
807 static const WCHAR space
[] = { ' ',0 };
808 static const WCHAR colon
[] = { ':',' ',0 };
809 static const WCHAR twocrlf
[] = {'\r','\n','\r','\n', 0};
810 LPWSTR requestString
;
816 /* allocate space for an array of all the string pointers to be added */
817 len
= (request
->num_headers
) * 4 + 10;
818 req
= heap_alloc( len
* sizeof(LPCWSTR
) );
819 if (!req
) return NULL
;
821 /* add the verb, path and HTTP version string */
829 /* Append custom request headers */
830 for (i
= 0; i
< request
->num_headers
; i
++)
832 if (request
->headers
[i
].is_request
)
835 req
[n
++] = request
->headers
[i
].field
;
837 req
[n
++] = request
->headers
[i
].value
;
839 TRACE("Adding custom header %s (%s)\n",
840 debugstr_w(request
->headers
[i
].field
),
841 debugstr_w(request
->headers
[i
].value
));
846 ERR("oops. buffer overrun\n");
849 requestString
= concatenate_string_list( req
, 4 );
851 if (!requestString
) return NULL
;
854 * Set (header) termination string for request
855 * Make sure there's exactly two new lines at the end of the request
857 p
= &requestString
[strlenW(requestString
)-1];
858 while ( (*p
== '\n') || (*p
== '\r') )
860 strcpyW( p
+1, twocrlf
);
862 return requestString
;
865 static BOOL
read_reply( request_t
*request
);
867 static BOOL
secure_proxy_connect( request_t
*request
)
869 static const WCHAR verbConnect
[] = {'C','O','N','N','E','C','T',0};
870 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
873 connect_t
*connect
= request
->connect
;
875 path
= heap_alloc( (strlenW( connect
->hostname
) + 13) * sizeof(WCHAR
) );
878 LPWSTR requestString
;
880 sprintfW( path
, fmt
, connect
->hostname
, connect
->hostport
);
881 requestString
= build_header_request_string( request
, verbConnect
,
886 LPSTR req_ascii
= strdupWA( requestString
);
888 heap_free( requestString
);
891 int len
= strlen( req_ascii
), bytes_sent
;
893 ret
= netconn_send( &request
->netconn
, req_ascii
, len
, &bytes_sent
);
894 heap_free( req_ascii
);
896 ret
= read_reply( request
);
903 #ifndef INET6_ADDRSTRLEN
904 #define INET6_ADDRSTRLEN 46
907 static WCHAR
*addr_to_str( const struct sockaddr
*addr
)
909 char buf
[INET6_ADDRSTRLEN
];
912 switch (addr
->sa_family
)
915 src
= &((struct sockaddr_in
*)addr
)->sin_addr
;
918 src
= &((struct sockaddr_in6
*)addr
)->sin6_addr
;
921 WARN("unsupported address family %d\n", addr
->sa_family
);
924 if (!inet_ntop( addr
->sa_family
, src
, buf
, sizeof(buf
) )) return NULL
;
925 return strdupAW( buf
);
928 static BOOL
open_connection( request_t
*request
)
931 WCHAR
*addressW
= NULL
;
934 struct sockaddr
*saddr
;
937 if (netconn_connected( &request
->netconn
)) goto done
;
939 connect
= request
->connect
;
940 port
= connect
->serverport
? connect
->serverport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
941 saddr
= (struct sockaddr
*)&connect
->sockaddr
;
942 slen
= sizeof(struct sockaddr
);
944 if (!connect
->resolved
)
946 len
= strlenW( connect
->servername
) + 1;
947 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME
, connect
->servername
, len
);
949 if (!netconn_resolve( connect
->servername
, port
, saddr
, &slen
, request
->resolve_timeout
)) return FALSE
;
950 connect
->resolved
= TRUE
;
952 if (!(addressW
= addr_to_str( saddr
))) return FALSE
;
953 len
= strlenW( addressW
) + 1;
954 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED
, addressW
, len
);
956 if (!addressW
&& !(addressW
= addr_to_str( saddr
))) return FALSE
;
957 TRACE("connecting to %s:%u\n", debugstr_w(addressW
), port
);
959 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER
, addressW
, 0 );
961 if (!netconn_create( &request
->netconn
, saddr
->sa_family
, SOCK_STREAM
, 0 ))
963 heap_free( addressW
);
966 netconn_set_timeout( &request
->netconn
, TRUE
, request
->send_timeout
);
967 netconn_set_timeout( &request
->netconn
, FALSE
, request
->recv_timeout
);
968 if (!netconn_connect( &request
->netconn
, saddr
, slen
, request
->connect_timeout
))
970 netconn_close( &request
->netconn
);
971 heap_free( addressW
);
974 if (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
976 if (connect
->session
->proxy_server
&&
977 strcmpiW( connect
->hostname
, connect
->servername
))
979 if (!secure_proxy_connect( request
))
981 heap_free( addressW
);
985 if (!netconn_secure_connect( &request
->netconn
, connect
->servername
))
987 netconn_close( &request
->netconn
);
988 heap_free( addressW
);
993 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER
, addressW
, strlenW(addressW
) + 1 );
996 request
->read_pos
= request
->read_size
= 0;
997 request
->read_chunked
= FALSE
;
998 heap_free( addressW
);
1002 void close_connection( request_t
*request
)
1004 if (!netconn_connected( &request
->netconn
)) return;
1006 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION
, 0, 0 );
1007 netconn_close( &request
->netconn
);
1008 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED
, 0, 0 );
1011 static BOOL
add_host_header( request_t
*request
, DWORD modifier
)
1016 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
1017 connect_t
*connect
= request
->connect
;
1020 port
= connect
->hostport
? connect
->hostport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
1022 if (port
== INTERNET_DEFAULT_HTTP_PORT
|| port
== INTERNET_DEFAULT_HTTPS_PORT
)
1024 return process_header( request
, attr_host
, connect
->hostname
, modifier
, TRUE
);
1026 len
= strlenW( connect
->hostname
) + 7; /* sizeof(":65335") */
1027 if (!(host
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
1028 sprintfW( host
, fmt
, connect
->hostname
, port
);
1029 ret
= process_header( request
, attr_host
, host
, modifier
, TRUE
);
1034 static void clear_response_headers( request_t
*request
)
1038 for (i
= 0; i
< request
->num_headers
; i
++)
1040 if (!request
->headers
[i
].field
) continue;
1041 if (!request
->headers
[i
].value
) continue;
1042 if (request
->headers
[i
].is_request
) continue;
1043 delete_header( request
, i
);
1048 static BOOL
send_request( request_t
*request
, LPCWSTR headers
, DWORD headers_len
, LPVOID optional
,
1049 DWORD optional_len
, DWORD total_len
, DWORD_PTR context
, BOOL async
)
1051 static const WCHAR keep_alive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
1052 static const WCHAR no_cache
[] = {'n','o','-','c','a','c','h','e',0};
1053 static const WCHAR length_fmt
[] = {'%','l','d',0};
1056 connect_t
*connect
= request
->connect
;
1057 session_t
*session
= connect
->session
;
1061 DWORD len
, i
, flags
;
1063 clear_response_headers( request
);
1065 flags
= WINHTTP_ADDREQ_FLAG_ADD
|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
;
1066 for (i
= 0; i
< request
->num_accept_types
; i
++)
1068 process_header( request
, attr_accept
, request
->accept_types
[i
], flags
, TRUE
);
1071 process_header( request
, attr_user_agent
, session
->agent
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1073 if (connect
->hostname
)
1074 add_host_header( request
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
1076 if (total_len
|| (request
->verb
&& !strcmpW( request
->verb
, postW
)))
1078 WCHAR length
[21]; /* decimal long int + null */
1079 sprintfW( length
, length_fmt
, total_len
);
1080 process_header( request
, attr_content_length
, length
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1082 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
))
1084 process_header( request
, attr_connection
, keep_alive
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1086 if (request
->hdr
.flags
& WINHTTP_FLAG_REFRESH
)
1088 process_header( request
, attr_pragma
, no_cache
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1089 process_header( request
, attr_cache_control
, no_cache
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1091 if (headers
&& !add_request_headers( request
, headers
, headers_len
, WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
))
1093 TRACE("failed to add request headers\n");
1096 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
) && !add_cookie_headers( request
))
1098 WARN("failed to add cookie headers\n");
1102 if (context
) request
->hdr
.context
= context
;
1104 if (!(ret
= open_connection( request
))) goto end
;
1105 if (!(req
= build_request_string( request
))) goto end
;
1107 if (!(req_ascii
= strdupWA( req
))) goto end
;
1108 TRACE("full request: %s\n", debugstr_a(req_ascii
));
1109 len
= strlen(req_ascii
);
1111 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST
, NULL
, 0 );
1113 ret
= netconn_send( &request
->netconn
, req_ascii
, len
, &bytes_sent
);
1114 heap_free( req_ascii
);
1119 if (!netconn_send( &request
->netconn
, optional
, optional_len
, &bytes_sent
)) goto end
;
1120 request
->optional
= optional
;
1121 request
->optional_len
= optional_len
;
1122 len
+= optional_len
;
1124 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
, &len
, sizeof(DWORD
) );
1129 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
, NULL
, 0 );
1132 WINHTTP_ASYNC_RESULT result
;
1133 result
.dwResult
= API_SEND_REQUEST
;
1134 result
.dwError
= get_last_error();
1135 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
1142 static void task_send_request( task_header_t
*task
)
1144 send_request_t
*s
= (send_request_t
*)task
;
1145 send_request( s
->hdr
.request
, s
->headers
, s
->headers_len
, s
->optional
, s
->optional_len
, s
->total_len
, s
->context
, TRUE
);
1146 heap_free( s
->headers
);
1149 /***********************************************************************
1150 * WinHttpSendRequest (winhttp.@)
1152 BOOL WINAPI
WinHttpSendRequest( HINTERNET hrequest
, LPCWSTR headers
, DWORD headers_len
,
1153 LPVOID optional
, DWORD optional_len
, DWORD total_len
, DWORD_PTR context
)
1158 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1159 hrequest
, debugstr_w(headers
), headers_len
, optional_len
, total_len
, context
);
1161 if (!(request
= (request_t
*)grab_object( hrequest
)))
1163 set_last_error( ERROR_INVALID_HANDLE
);
1166 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1168 release_object( &request
->hdr
);
1169 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1173 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
1177 if (!(s
= heap_alloc( sizeof(send_request_t
) ))) return FALSE
;
1178 s
->hdr
.request
= request
;
1179 s
->hdr
.proc
= task_send_request
;
1180 s
->headers
= strdupW( headers
);
1181 s
->headers_len
= headers_len
;
1182 s
->optional
= optional
;
1183 s
->optional_len
= optional_len
;
1184 s
->total_len
= total_len
;
1185 s
->context
= context
;
1187 addref_object( &request
->hdr
);
1188 ret
= queue_task( (task_header_t
*)s
);
1191 ret
= send_request( request
, headers
, headers_len
, optional
, optional_len
, total_len
, context
, FALSE
);
1193 release_object( &request
->hdr
);
1197 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1199 static const WCHAR basicW
[] = {'B','a','s','i','c',0};
1200 static const WCHAR ntlmW
[] = {'N','T','L','M',0};
1201 static const WCHAR passportW
[] = {'P','a','s','s','p','o','r','t',0};
1202 static const WCHAR digestW
[] = {'D','i','g','e','s','t',0};
1203 static const WCHAR negotiateW
[] = {'N','e','g','o','t','i','a','t','e',0};
1213 { basicW
, ARRAYSIZE(basicW
) - 1, WINHTTP_AUTH_SCHEME_BASIC
},
1214 { ntlmW
, ARRAYSIZE(ntlmW
) - 1, WINHTTP_AUTH_SCHEME_NTLM
},
1215 { passportW
, ARRAYSIZE(passportW
) - 1, WINHTTP_AUTH_SCHEME_PASSPORT
},
1216 { digestW
, ARRAYSIZE(digestW
) - 1, WINHTTP_AUTH_SCHEME_DIGEST
},
1217 { negotiateW
, ARRAYSIZE(negotiateW
) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE
}
1219 static const unsigned int num_auth_schemes
= sizeof(auth_schemes
)/sizeof(auth_schemes
[0]);
1221 static enum auth_scheme
scheme_from_flag( DWORD flag
)
1225 for (i
= 0; i
< num_auth_schemes
; i
++) if (flag
== auth_schemes
[i
].scheme
) return i
;
1226 return SCHEME_INVALID
;
1229 static DWORD
auth_scheme_from_header( WCHAR
*header
)
1233 for (i
= 0; i
< num_auth_schemes
; i
++)
1235 if (!strncmpiW( header
, auth_schemes
[i
].str
, auth_schemes
[i
].len
) &&
1236 (header
[auth_schemes
[i
].len
] == ' ' || !header
[auth_schemes
[i
].len
])) return auth_schemes
[i
].scheme
;
1241 static BOOL
query_auth_schemes( request_t
*request
, DWORD level
, LPDWORD supported
, LPDWORD first
)
1252 query_headers( request
, level
, NULL
, NULL
, &size
, &index
);
1253 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER
) break;
1256 if (!(buffer
= heap_alloc( size
))) return FALSE
;
1257 if (!query_headers( request
, level
, NULL
, buffer
, &size
, &index
))
1259 heap_free( buffer
);
1262 scheme
= auth_scheme_from_header( buffer
);
1263 heap_free( buffer
);
1266 if (first
&& index
== 1)
1267 *first
= *supported
= scheme
;
1269 *supported
|= scheme
;
1276 /***********************************************************************
1277 * WinHttpQueryAuthSchemes (winhttp.@)
1279 BOOL WINAPI
WinHttpQueryAuthSchemes( HINTERNET hrequest
, LPDWORD supported
, LPDWORD first
, LPDWORD target
)
1284 TRACE("%p, %p, %p, %p\n", hrequest
, supported
, first
, target
);
1286 if (!(request
= (request_t
*)grab_object( hrequest
)))
1288 set_last_error( ERROR_INVALID_HANDLE
);
1291 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1293 release_object( &request
->hdr
);
1294 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1297 if (!supported
|| !first
|| !target
)
1299 release_object( &request
->hdr
);
1300 set_last_error( ERROR_INVALID_PARAMETER
);
1305 if (query_auth_schemes( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, supported
, first
))
1307 *target
= WINHTTP_AUTH_TARGET_SERVER
;
1310 else if (query_auth_schemes( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, supported
, first
))
1312 *target
= WINHTTP_AUTH_TARGET_PROXY
;
1316 release_object( &request
->hdr
);
1320 static UINT
encode_base64( const char *bin
, unsigned int len
, WCHAR
*base64
)
1323 static const char base64enc
[] =
1324 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1328 /* first 6 bits, all from bin[0] */
1329 base64
[n
++] = base64enc
[(bin
[0] & 0xfc) >> 2];
1330 x
= (bin
[0] & 3) << 4;
1332 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1335 base64
[n
++] = base64enc
[x
];
1340 base64
[n
++] = base64enc
[x
| ((bin
[1] & 0xf0) >> 4)];
1341 x
= (bin
[1] & 0x0f) << 2;
1343 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1346 base64
[n
++] = base64enc
[x
];
1350 base64
[n
++] = base64enc
[x
| ((bin
[2] & 0xc0) >> 6)];
1352 /* last 6 bits, all from bin [2] */
1353 base64
[n
++] = base64enc
[bin
[2] & 0x3f];
1361 static inline char decode_char( WCHAR c
)
1363 if (c
>= 'A' && c
<= 'Z') return c
- 'A';
1364 if (c
>= 'a' && c
<= 'z') return c
- 'a' + 26;
1365 if (c
>= '0' && c
<= '9') return c
- '0' + 52;
1366 if (c
== '+') return 62;
1367 if (c
== '/') return 63;
1371 static unsigned int decode_base64( const WCHAR
*base64
, unsigned int len
, char *buf
)
1374 char c0
, c1
, c2
, c3
;
1375 const WCHAR
*p
= base64
;
1379 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1380 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1381 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1382 if ((c3
= decode_char( p
[3] )) > 63) return 0;
1386 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1387 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1388 buf
[i
+ 2] = (c2
<< 6) | c3
;
1396 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1397 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1399 if (buf
) buf
[i
] = (c0
<< 2) | (c1
>> 4);
1402 else if (p
[3] == '=')
1404 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1405 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1406 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1410 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1411 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1418 static struct authinfo
*alloc_authinfo(void)
1420 struct authinfo
*ret
;
1422 if (!(ret
= heap_alloc( sizeof(*ret
) ))) return NULL
;
1424 SecInvalidateHandle( &ret
->cred
);
1425 SecInvalidateHandle( &ret
->ctx
);
1426 memset( &ret
->exp
, 0, sizeof(ret
->exp
) );
1432 ret
->finished
= FALSE
;
1436 void destroy_authinfo( struct authinfo
*authinfo
)
1438 if (!authinfo
) return;
1440 if (SecIsValidHandle( &authinfo
->ctx
))
1441 DeleteSecurityContext( &authinfo
->ctx
);
1442 if (SecIsValidHandle( &authinfo
->cred
))
1443 FreeCredentialsHandle( &authinfo
->cred
);
1445 heap_free( authinfo
->data
);
1446 heap_free( authinfo
);
1449 static BOOL
get_authvalue( request_t
*request
, DWORD level
, DWORD scheme
, WCHAR
*buffer
, DWORD len
)
1451 DWORD size
, index
= 0;
1455 if (!query_headers( request
, level
, NULL
, buffer
, &size
, &index
)) return FALSE
;
1456 if (auth_scheme_from_header( buffer
) == scheme
) break;
1461 static BOOL
do_authorization( request_t
*request
, DWORD target
, DWORD scheme_flag
)
1463 struct authinfo
*authinfo
, **auth_ptr
;
1464 enum auth_scheme scheme
= scheme_from_flag( scheme_flag
);
1465 const WCHAR
*auth_target
, *username
, *password
;
1466 WCHAR auth_value
[2048], *auth_reply
;
1467 DWORD len
= sizeof(auth_value
), len_scheme
, flags
;
1470 if (scheme
== SCHEME_INVALID
) return FALSE
;
1474 case WINHTTP_AUTH_TARGET_SERVER
:
1475 if (!get_authvalue( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1477 auth_ptr
= &request
->authinfo
;
1478 auth_target
= attr_authorization
;
1479 username
= request
->connect
->username
;
1480 password
= request
->connect
->password
;
1483 case WINHTTP_AUTH_TARGET_PROXY
:
1484 if (!get_authvalue( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1486 auth_ptr
= &request
->proxy_authinfo
;
1487 auth_target
= attr_proxy_authorization
;
1488 username
= request
->connect
->session
->proxy_username
;
1489 password
= request
->connect
->session
->proxy_password
;
1493 WARN("unknown target %x\n", target
);
1496 authinfo
= *auth_ptr
;
1502 int userlen
, passlen
;
1504 if (!username
|| !password
) return FALSE
;
1505 if ((!authinfo
&& !(authinfo
= alloc_authinfo())) || authinfo
->finished
) return FALSE
;
1507 userlen
= WideCharToMultiByte( CP_UTF8
, 0, username
, strlenW( username
), NULL
, 0, NULL
, NULL
);
1508 passlen
= WideCharToMultiByte( CP_UTF8
, 0, password
, strlenW( password
), NULL
, 0, NULL
, NULL
);
1510 authinfo
->data_len
= userlen
+ 1 + passlen
;
1511 if (!(authinfo
->data
= heap_alloc( authinfo
->data_len
))) return FALSE
;
1513 WideCharToMultiByte( CP_UTF8
, 0, username
, -1, authinfo
->data
, userlen
, NULL
, NULL
);
1514 authinfo
->data
[userlen
] = ':';
1515 WideCharToMultiByte( CP_UTF8
, 0, password
, -1, authinfo
->data
+ userlen
+ 1, passlen
, NULL
, NULL
);
1517 authinfo
->scheme
= SCHEME_BASIC
;
1518 authinfo
->finished
= TRUE
;
1522 case SCHEME_NEGOTIATE
:
1524 SECURITY_STATUS status
;
1525 SecBufferDesc out_desc
, in_desc
;
1527 ULONG flags
= ISC_REQ_CONNECTION
|ISC_REQ_USE_DCE_STYLE
|ISC_REQ_MUTUAL_AUTH
|ISC_REQ_DELEGATE
;
1534 SEC_WINNT_AUTH_IDENTITY_W id
;
1535 WCHAR
*domain
, *user
;
1537 if (!username
|| !password
|| !(authinfo
= alloc_authinfo())) return FALSE
;
1540 domain
= (WCHAR
*)username
;
1541 user
= strchrW( username
, '\\' );
1546 user
= (WCHAR
*)username
;
1549 id
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1551 id
.UserLength
= strlenW( user
);
1553 id
.DomainLength
= domain
? user
- domain
- 1 : 0;
1554 id
.Password
= (WCHAR
*)password
;
1555 id
.PasswordLength
= strlenW( password
);
1557 status
= AcquireCredentialsHandleW( NULL
, (SEC_WCHAR
*)auth_schemes
[scheme
].str
,
1558 SECPKG_CRED_OUTBOUND
, NULL
, &id
, NULL
, NULL
,
1559 &authinfo
->cred
, &exp
);
1560 if (status
== SEC_E_OK
)
1563 status
= QuerySecurityPackageInfoW( (SEC_WCHAR
*)auth_schemes
[scheme
].str
, &info
);
1564 if (status
== SEC_E_OK
)
1566 authinfo
->max_token
= info
->cbMaxToken
;
1567 FreeContextBuffer( info
);
1570 if (status
!= SEC_E_OK
)
1572 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1573 debugstr_w(auth_schemes
[scheme
].str
), status
);
1574 heap_free( authinfo
);
1577 authinfo
->scheme
= scheme
;
1579 else if (authinfo
->finished
) return FALSE
;
1581 if ((strlenW( auth_value
) < auth_schemes
[authinfo
->scheme
].len
||
1582 strncmpiW( auth_value
, auth_schemes
[authinfo
->scheme
].str
, auth_schemes
[authinfo
->scheme
].len
)))
1584 ERR("authentication scheme changed from %s to %s\n",
1585 debugstr_w(auth_schemes
[authinfo
->scheme
].str
), debugstr_w(auth_value
));
1586 destroy_authinfo( authinfo
);
1590 in
.BufferType
= SECBUFFER_TOKEN
;
1594 in_desc
.ulVersion
= 0;
1595 in_desc
.cBuffers
= 1;
1596 in_desc
.pBuffers
= &in
;
1598 p
= auth_value
+ auth_schemes
[scheme
].len
;
1601 int len
= strlenW( ++p
);
1602 in
.cbBuffer
= decode_base64( p
, len
, NULL
);
1603 if (!(in
.pvBuffer
= heap_alloc( in
.cbBuffer
))) return FALSE
;
1604 decode_base64( p
, len
, in
.pvBuffer
);
1606 out
.BufferType
= SECBUFFER_TOKEN
;
1607 out
.cbBuffer
= authinfo
->max_token
;
1608 if (!(out
.pvBuffer
= heap_alloc( authinfo
->max_token
)))
1610 heap_free( in
.pvBuffer
);
1613 out_desc
.ulVersion
= 0;
1614 out_desc
.cBuffers
= 1;
1615 out_desc
.pBuffers
= &out
;
1617 status
= InitializeSecurityContextW( first
? &authinfo
->cred
: NULL
, first
? NULL
: &authinfo
->ctx
,
1618 first
? request
->connect
->servername
: NULL
, flags
, 0,
1619 SECURITY_NETWORK_DREP
, in
.pvBuffer
? &in_desc
: NULL
, 0,
1620 &authinfo
->ctx
, &out_desc
, &authinfo
->attr
, &authinfo
->exp
);
1621 heap_free( in
.pvBuffer
);
1622 if (status
== SEC_E_OK
)
1624 heap_free( authinfo
->data
);
1625 authinfo
->data
= out
.pvBuffer
;
1626 authinfo
->data_len
= out
.cbBuffer
;
1627 authinfo
->finished
= TRUE
;
1628 TRACE("sending last auth packet\n");
1630 else if (status
== SEC_I_CONTINUE_NEEDED
)
1632 heap_free( authinfo
->data
);
1633 authinfo
->data
= out
.pvBuffer
;
1634 authinfo
->data_len
= out
.cbBuffer
;
1635 TRACE("sending next auth packet\n");
1639 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status
);
1640 heap_free( out
.pvBuffer
);
1641 destroy_authinfo( authinfo
);
1648 ERR("invalid scheme %u\n", scheme
);
1651 *auth_ptr
= authinfo
;
1653 len_scheme
= auth_schemes
[authinfo
->scheme
].len
;
1654 len
= len_scheme
+ 1 + ((authinfo
->data_len
+ 2) * 4) / 3;
1655 if (!(auth_reply
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
1657 memcpy( auth_reply
, auth_schemes
[authinfo
->scheme
].str
, len_scheme
* sizeof(WCHAR
) );
1658 auth_reply
[len_scheme
] = ' ';
1659 encode_base64( authinfo
->data
, authinfo
->data_len
, auth_reply
+ len_scheme
+ 1 );
1661 flags
= WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
;
1662 ret
= process_header( request
, auth_target
, auth_reply
, flags
, TRUE
);
1663 heap_free( auth_reply
);
1667 static BOOL
set_credentials( request_t
*request
, DWORD target
, DWORD scheme
, const WCHAR
*username
,
1668 const WCHAR
*password
)
1670 if ((scheme
== WINHTTP_AUTH_SCHEME_BASIC
|| scheme
== WINHTTP_AUTH_SCHEME_DIGEST
) &&
1671 (!username
|| !password
))
1673 set_last_error( ERROR_INVALID_PARAMETER
);
1678 case WINHTTP_AUTH_TARGET_SERVER
:
1680 heap_free( request
->connect
->username
);
1681 if (!username
) request
->connect
->username
= NULL
;
1682 else if (!(request
->connect
->username
= strdupW( username
))) return FALSE
;
1684 heap_free( request
->connect
->password
);
1685 if (!password
) request
->connect
->password
= NULL
;
1686 else if (!(request
->connect
->password
= strdupW( password
))) return FALSE
;
1689 case WINHTTP_AUTH_TARGET_PROXY
:
1691 heap_free( request
->connect
->session
->proxy_username
);
1692 if (!username
) request
->connect
->session
->proxy_username
= NULL
;
1693 else if (!(request
->connect
->session
->proxy_username
= strdupW( username
))) return FALSE
;
1695 heap_free( request
->connect
->session
->proxy_password
);
1696 if (!password
) request
->connect
->session
->proxy_password
= NULL
;
1697 else if (!(request
->connect
->session
->proxy_password
= strdupW( password
))) return FALSE
;
1701 WARN("unknown target %u\n", target
);
1707 /***********************************************************************
1708 * WinHttpSetCredentials (winhttp.@)
1710 BOOL WINAPI
WinHttpSetCredentials( HINTERNET hrequest
, DWORD target
, DWORD scheme
, LPCWSTR username
,
1711 LPCWSTR password
, LPVOID params
)
1716 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest
, target
, scheme
, debugstr_w(username
), password
, params
);
1718 if (!(request
= (request_t
*)grab_object( hrequest
)))
1720 set_last_error( ERROR_INVALID_HANDLE
);
1723 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1725 release_object( &request
->hdr
);
1726 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1730 ret
= set_credentials( request
, target
, scheme
, username
, password
);
1732 release_object( &request
->hdr
);
1736 static BOOL
handle_authorization( request_t
*request
, DWORD status
)
1738 DWORD i
, schemes
, first
, level
, target
;
1742 case HTTP_STATUS_DENIED
:
1743 target
= WINHTTP_AUTH_TARGET_SERVER
;
1744 level
= WINHTTP_QUERY_WWW_AUTHENTICATE
;
1747 case HTTP_STATUS_PROXY_AUTH_REQ
:
1748 target
= WINHTTP_AUTH_TARGET_PROXY
;
1749 level
= WINHTTP_QUERY_PROXY_AUTHENTICATE
;
1753 WARN("unhandled status %u\n", status
);
1757 if (!query_auth_schemes( request
, level
, &schemes
, &first
)) return FALSE
;
1758 if (do_authorization( request
, target
, first
)) return TRUE
;
1761 for (i
= 0; i
< num_auth_schemes
; i
++)
1763 if (!(schemes
& auth_schemes
[i
].scheme
)) continue;
1764 if (do_authorization( request
, target
, auth_schemes
[i
].scheme
)) return TRUE
;
1769 /* set the request content length based on the headers */
1770 static DWORD
set_content_length( request_t
*request
)
1775 buflen
= sizeof(request
->content_length
);
1776 if (!query_headers( request
, WINHTTP_QUERY_CONTENT_LENGTH
|WINHTTP_QUERY_FLAG_NUMBER
,
1777 NULL
, &request
->content_length
, &buflen
, NULL
))
1778 request
->content_length
= ~0u;
1780 buflen
= sizeof(encoding
);
1781 if (query_headers( request
, WINHTTP_QUERY_TRANSFER_ENCODING
, NULL
, encoding
, &buflen
, NULL
) &&
1782 !strcmpiW( encoding
, chunkedW
))
1784 request
->content_length
= ~0u;
1785 request
->read_chunked
= TRUE
;
1787 request
->content_read
= 0;
1788 return request
->content_length
;
1791 /* read some more data into the read buffer */
1792 static BOOL
read_more_data( request_t
*request
, int maxlen
)
1796 if (request
->read_size
&& request
->read_pos
)
1798 /* move existing data to the start of the buffer */
1799 memmove( request
->read_buf
, request
->read_buf
+ request
->read_pos
, request
->read_size
);
1800 request
->read_pos
= 0;
1802 if (maxlen
== -1) maxlen
= sizeof(request
->read_buf
);
1803 if (!netconn_recv( &request
->netconn
, request
->read_buf
+ request
->read_size
,
1804 maxlen
- request
->read_size
, 0, &len
)) return FALSE
;
1805 request
->read_size
+= len
;
1809 /* remove some amount of data from the read buffer */
1810 static void remove_data( request_t
*request
, int count
)
1812 if (!(request
->read_size
-= count
)) request
->read_pos
= 0;
1813 else request
->read_pos
+= count
;
1816 static BOOL
read_line( request_t
*request
, char *buffer
, DWORD
*len
)
1818 int count
, bytes_read
, pos
= 0;
1822 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1825 count
= eol
- (request
->read_buf
+ request
->read_pos
);
1826 bytes_read
= count
+ 1;
1828 else count
= bytes_read
= request
->read_size
;
1830 count
= min( count
, *len
- pos
);
1831 memcpy( buffer
+ pos
, request
->read_buf
+ request
->read_pos
, count
);
1833 remove_data( request
, bytes_read
);
1836 if (!read_more_data( request
, -1 )) return FALSE
;
1837 if (!request
->read_size
)
1840 TRACE("returning empty string\n");
1846 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
1849 buffer
[*len
- 1] = 0;
1850 TRACE("returning %s\n", debugstr_a(buffer
));
1854 /* discard data contents until we reach end of line */
1855 static BOOL
discard_eol( request_t
*request
)
1859 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1862 remove_data( request
, (eol
+ 1) - (request
->read_buf
+ request
->read_pos
) );
1865 request
->read_pos
= request
->read_size
= 0; /* discard everything */
1866 if (!read_more_data( request
, -1 )) return FALSE
;
1867 } while (request
->read_size
);
1871 /* read the size of the next chunk */
1872 static BOOL
start_next_chunk( request_t
*request
)
1874 DWORD chunk_size
= 0;
1876 if (!request
->content_length
) return TRUE
;
1877 if (request
->content_length
== request
->content_read
)
1879 /* read terminator for the previous chunk */
1880 if (!discard_eol( request
)) return FALSE
;
1881 request
->content_length
= ~0u;
1882 request
->content_read
= 0;
1886 while (request
->read_size
)
1888 char ch
= request
->read_buf
[request
->read_pos
];
1889 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
1890 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
1891 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
1892 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
1894 TRACE("reading %u byte chunk\n", chunk_size
);
1895 request
->content_length
= chunk_size
;
1896 request
->content_read
= 0;
1897 if (!discard_eol( request
)) return FALSE
;
1900 remove_data( request
, 1 );
1902 if (!read_more_data( request
, -1 )) return FALSE
;
1903 if (!request
->read_size
)
1905 request
->content_length
= request
->content_read
= 0;
1911 /* return the size of data available to be read immediately */
1912 static DWORD
get_available_data( request_t
*request
)
1914 if (request
->read_chunked
&&
1915 (request
->content_length
== ~0u || request
->content_length
== request
->content_read
))
1917 return min( request
->read_size
, request
->content_length
- request
->content_read
);
1920 /* check if we have reached the end of the data to read */
1921 static BOOL
end_of_read_data( request_t
*request
)
1923 if (request
->read_chunked
) return (request
->content_length
== 0);
1924 if (request
->content_length
== ~0u) return FALSE
;
1925 return (request
->content_length
== request
->content_read
);
1928 static BOOL
refill_buffer( request_t
*request
)
1930 int len
= sizeof(request
->read_buf
);
1932 if (request
->read_chunked
&&
1933 (request
->content_length
== ~0u || request
->content_length
== request
->content_read
))
1935 if (!start_next_chunk( request
)) return FALSE
;
1937 if (request
->content_length
!= ~0u) len
= min( len
, request
->content_length
- request
->content_read
);
1938 if (len
<= request
->read_size
) return TRUE
;
1939 if (!read_more_data( request
, len
)) return FALSE
;
1940 if (!request
->read_size
) request
->content_length
= request
->content_read
= 0;
1944 #define MAX_REPLY_LEN 1460
1945 #define INITIAL_HEADER_BUFFER_LEN 512
1947 static BOOL
read_reply( request_t
*request
)
1949 static const WCHAR crlf
[] = {'\r','\n',0};
1951 char buffer
[MAX_REPLY_LEN
];
1952 DWORD buflen
, len
, offset
, received_len
, crlf_len
= 2; /* strlenW(crlf) */
1953 char *status_code
, *status_text
;
1954 WCHAR
*versionW
, *status_textW
, *raw_headers
;
1955 WCHAR status_codeW
[4]; /* sizeof("nnn") */
1957 if (!netconn_connected( &request
->netconn
)) return FALSE
;
1959 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE
, NULL
, 0 );
1964 buflen
= MAX_REPLY_LEN
;
1965 if (!read_line( request
, buffer
, &buflen
)) return FALSE
;
1966 received_len
+= buflen
;
1968 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
1969 if (!(status_code
= strchr( buffer
, ' ' ))) return FALSE
;
1971 if (!(status_text
= strchr( status_code
, ' ' ))) return FALSE
;
1972 if ((len
= status_text
- status_code
) != sizeof("nnn") - 1) return FALSE
;
1975 TRACE("version [%s] status code [%s] status text [%s]\n",
1976 debugstr_an(buffer
, status_code
- buffer
- 1),
1977 debugstr_an(status_code
, len
),
1978 debugstr_a(status_text
));
1980 } while (!memcmp( status_code
, "100", len
)); /* ignore "100 Continue" responses */
1982 /* we rely on the fact that the protocol is ascii */
1983 MultiByteToWideChar( CP_ACP
, 0, status_code
, len
, status_codeW
, len
);
1984 status_codeW
[len
] = 0;
1985 if (!(process_header( request
, attr_status
, status_codeW
, WINHTTP_ADDREQ_FLAG_REPLACE
, FALSE
))) return FALSE
;
1987 len
= status_code
- buffer
;
1988 if (!(versionW
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
1989 MultiByteToWideChar( CP_ACP
, 0, buffer
, len
- 1, versionW
, len
-1 );
1990 versionW
[len
- 1] = 0;
1992 heap_free( request
->version
);
1993 request
->version
= versionW
;
1995 len
= buflen
- (status_text
- buffer
);
1996 if (!(status_textW
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
1997 MultiByteToWideChar( CP_ACP
, 0, status_text
, len
, status_textW
, len
);
1999 heap_free( request
->status_text
);
2000 request
->status_text
= status_textW
;
2002 len
= max( buflen
+ crlf_len
, INITIAL_HEADER_BUFFER_LEN
);
2003 if (!(raw_headers
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2004 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
, buflen
);
2005 memcpy( raw_headers
+ buflen
- 1, crlf
, sizeof(crlf
) );
2007 heap_free( request
->raw_headers
);
2008 request
->raw_headers
= raw_headers
;
2010 offset
= buflen
+ crlf_len
- 1;
2015 buflen
= MAX_REPLY_LEN
;
2016 if (!read_line( request
, buffer
, &buflen
)) goto end
;
2017 received_len
+= buflen
;
2018 if (!*buffer
) break;
2020 while (len
- offset
< buflen
+ crlf_len
)
2024 if (!(tmp
= heap_realloc( raw_headers
, len
* sizeof(WCHAR
) ))) return FALSE
;
2025 request
->raw_headers
= raw_headers
= tmp
;
2027 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
+ offset
, buflen
);
2029 if (!(header
= parse_header( raw_headers
+ offset
))) break;
2030 if (!(process_header( request
, header
->field
, header
->value
, WINHTTP_ADDREQ_FLAG_ADD
, FALSE
)))
2032 free_header( header
);
2035 free_header( header
);
2036 memcpy( raw_headers
+ offset
+ buflen
- 1, crlf
, sizeof(crlf
) );
2037 offset
+= buflen
+ crlf_len
- 1;
2040 TRACE("raw headers: %s\n", debugstr_w(raw_headers
));
2043 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED
, &received_len
, sizeof(DWORD
) );
2047 static void finished_reading( request_t
*request
)
2049 static const WCHAR closeW
[] = {'c','l','o','s','e',0};
2052 WCHAR connection
[20];
2053 DWORD size
= sizeof(connection
);
2055 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
) close
= TRUE
;
2056 else if (query_headers( request
, WINHTTP_QUERY_CONNECTION
, NULL
, connection
, &size
, NULL
) ||
2057 query_headers( request
, WINHTTP_QUERY_PROXY_CONNECTION
, NULL
, connection
, &size
, NULL
))
2059 if (!strcmpiW( connection
, closeW
)) close
= TRUE
;
2061 else if (!strcmpW( request
->version
, http1_0
)) close
= TRUE
;
2062 if (close
) close_connection( request
);
2065 static BOOL
read_data( request_t
*request
, void *buffer
, DWORD size
, DWORD
*read
, BOOL async
)
2068 int len
, bytes_read
= 0;
2070 if (request
->read_chunked
&&
2071 (request
->content_length
== ~0u || request
->content_length
== request
->content_read
))
2073 if (!start_next_chunk( request
)) goto done
;
2075 if (request
->content_length
!= ~0u) size
= min( size
, request
->content_length
- request
->content_read
);
2077 if (request
->read_size
)
2079 bytes_read
= min( request
->read_size
, size
);
2080 memcpy( buffer
, request
->read_buf
+ request
->read_pos
, bytes_read
);
2081 remove_data( request
, bytes_read
);
2083 if (size
> bytes_read
&& (!bytes_read
|| !async
))
2085 if ((ret
= netconn_recv( &request
->netconn
, (char *)buffer
+ bytes_read
, size
- bytes_read
,
2086 async
? 0 : MSG_WAITALL
, &len
)))
2091 request
->content_read
+= bytes_read
;
2092 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read
, request
->content_read
, request
->content_length
);
2095 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
, buffer
, bytes_read
);
2098 WINHTTP_ASYNC_RESULT result
;
2099 result
.dwResult
= API_READ_DATA
;
2100 result
.dwError
= get_last_error();
2101 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2104 if (read
) *read
= bytes_read
;
2105 if (!bytes_read
&& request
->content_read
== request
->content_length
) finished_reading( request
);
2109 /* read any content returned by the server so that the connection can be reused */
2110 static void drain_content( request_t
*request
)
2115 if (request
->content_length
== ~0u)
2117 finished_reading( request
);
2122 if (!read_data( request
, buffer
, sizeof(buffer
), &bytes_read
, FALSE
) || !bytes_read
) return;
2126 static void record_cookies( request_t
*request
)
2130 for (i
= 0; i
< request
->num_headers
; i
++)
2132 header_t
*set_cookie
= &request
->headers
[i
];
2133 if (!strcmpiW( set_cookie
->field
, attr_set_cookie
) && !set_cookie
->is_request
)
2135 set_cookies( request
, set_cookie
->value
);
2140 static WCHAR
*get_redirect_url( request_t
*request
, DWORD
*len
)
2145 query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, NULL
, &size
, NULL
);
2146 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER
) return FALSE
;
2147 if (!(ret
= heap_alloc( size
))) return NULL
;
2148 *len
= size
/ sizeof(WCHAR
);
2149 if (query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, ret
, &size
, NULL
)) return ret
;
2154 static BOOL
handle_redirect( request_t
*request
, DWORD status
)
2159 connect_t
*connect
= request
->connect
;
2161 WCHAR
*hostname
= NULL
, *location
;
2164 if (!(location
= get_redirect_url( request
, &len_url
))) return FALSE
;
2166 memset( &uc
, 0, sizeof(uc
) );
2167 uc
.dwStructSize
= sizeof(uc
);
2168 uc
.dwSchemeLength
= uc
.dwHostNameLength
= uc
.dwUrlPathLength
= uc
.dwExtraInfoLength
= ~0u;
2170 if (!WinHttpCrackUrl( location
, len_url
, 0, &uc
)) /* assume relative redirect */
2174 len
= strlenW( location
) + 1;
2175 if (location
[0] != '/') len
++;
2176 if (!(p
= path
= heap_alloc( len
* sizeof(WCHAR
) ))) goto end
;
2178 if (location
[0] != '/') *p
++ = '/';
2179 strcpyW( p
, location
);
2181 heap_free( request
->path
);
2182 request
->path
= path
;
2184 drain_content( request
);
2185 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_url
+ 1 );
2189 if (uc
.nScheme
== INTERNET_SCHEME_HTTP
&& request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
2191 if (request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP
) goto end
;
2192 TRACE("redirect from secure page to non-secure page\n");
2193 request
->hdr
.flags
&= ~WINHTTP_FLAG_SECURE
;
2195 else if (uc
.nScheme
== INTERNET_SCHEME_HTTPS
&& !(request
->hdr
.flags
& WINHTTP_FLAG_SECURE
))
2197 TRACE("redirect from non-secure page to secure page\n");
2198 request
->hdr
.flags
|= WINHTTP_FLAG_SECURE
;
2201 drain_content( request
);
2202 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_url
+ 1 );
2204 len
= uc
.dwHostNameLength
;
2205 if (!(hostname
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2206 memcpy( hostname
, uc
.lpszHostName
, len
* sizeof(WCHAR
) );
2209 port
= uc
.nPort
? uc
.nPort
: (uc
.nScheme
== INTERNET_SCHEME_HTTPS
? 443 : 80);
2210 if (strcmpiW( connect
->hostname
, hostname
) || connect
->serverport
!= port
)
2212 heap_free( connect
->hostname
);
2213 connect
->hostname
= hostname
;
2214 connect
->hostport
= port
;
2215 if (!(ret
= set_server_for_hostname( connect
, hostname
, port
))) goto end
;
2217 netconn_close( &request
->netconn
);
2218 if (!(ret
= netconn_init( &request
->netconn
))) goto end
;
2219 request
->read_pos
= request
->read_size
= 0;
2220 request
->read_chunked
= FALSE
;
2222 if (!(ret
= add_host_header( request
, WINHTTP_ADDREQ_FLAG_REPLACE
))) goto end
;
2223 if (!(ret
= open_connection( request
))) goto end
;
2225 heap_free( request
->path
);
2226 request
->path
= NULL
;
2227 if (uc
.dwUrlPathLength
)
2229 len
= uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
;
2230 if (!(request
->path
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2231 strcpyW( request
->path
, uc
.lpszUrlPath
);
2233 else request
->path
= strdupW( slashW
);
2236 /* remove content-type/length headers */
2237 if ((index
= get_header_index( request
, attr_content_type
, 0, TRUE
)) >= 0) delete_header( request
, index
);
2238 if ((index
= get_header_index( request
, attr_content_length
, 0, TRUE
)) >= 0 ) delete_header( request
, index
);
2240 if (status
!= HTTP_STATUS_REDIRECT_KEEP_VERB
&& !strcmpW( request
->verb
, postW
))
2242 heap_free( request
->verb
);
2243 request
->verb
= strdupW( getW
);
2244 request
->optional
= NULL
;
2245 request
->optional_len
= 0;
2250 if (!ret
) heap_free( hostname
);
2251 heap_free( location
);
2255 static BOOL
receive_response( request_t
*request
, BOOL async
)
2258 DWORD size
, query
, status
;
2262 if (!(ret
= read_reply( request
)))
2264 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE
);
2267 size
= sizeof(DWORD
);
2268 query
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
2269 if (!(ret
= query_headers( request
, query
, NULL
, &status
, &size
, NULL
))) break;
2271 set_content_length( request
);
2273 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
)) record_cookies( request
);
2275 if (status
== HTTP_STATUS_MOVED
|| status
== HTTP_STATUS_REDIRECT
|| status
== HTTP_STATUS_REDIRECT_KEEP_VERB
)
2277 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_REDIRECTS
||
2278 request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_NEVER
) break;
2280 if (!(ret
= handle_redirect( request
, status
))) break;
2282 /* recurse synchronously */
2283 send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
);
2286 else if (status
== HTTP_STATUS_DENIED
|| status
== HTTP_STATUS_PROXY_AUTH_REQ
)
2288 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_AUTHENTICATION
) break;
2290 drain_content( request
);
2291 if (!handle_authorization( request
, status
))
2296 /* recurse synchronously */
2297 send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
);
2305 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
, NULL
, 0 );
2308 WINHTTP_ASYNC_RESULT result
;
2309 result
.dwResult
= API_RECEIVE_RESPONSE
;
2310 result
.dwError
= get_last_error();
2311 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2317 static void task_receive_response( task_header_t
*task
)
2319 receive_response_t
*r
= (receive_response_t
*)task
;
2320 receive_response( r
->hdr
.request
, TRUE
);
2323 /***********************************************************************
2324 * WinHttpReceiveResponse (winhttp.@)
2326 BOOL WINAPI
WinHttpReceiveResponse( HINTERNET hrequest
, LPVOID reserved
)
2331 TRACE("%p, %p\n", hrequest
, reserved
);
2333 if (!(request
= (request_t
*)grab_object( hrequest
)))
2335 set_last_error( ERROR_INVALID_HANDLE
);
2338 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2340 release_object( &request
->hdr
);
2341 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2345 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2347 receive_response_t
*r
;
2349 if (!(r
= heap_alloc( sizeof(receive_response_t
) ))) return FALSE
;
2350 r
->hdr
.request
= request
;
2351 r
->hdr
.proc
= task_receive_response
;
2353 addref_object( &request
->hdr
);
2354 ret
= queue_task( (task_header_t
*)r
);
2357 ret
= receive_response( request
, FALSE
);
2359 release_object( &request
->hdr
);
2363 static BOOL
query_data_available( request_t
*request
, DWORD
*available
, BOOL async
)
2368 if (!(count
= get_available_data( request
)))
2370 if (end_of_read_data( request
))
2372 if (available
) *available
= 0;
2376 refill_buffer( request
);
2377 count
= get_available_data( request
);
2379 if (count
== sizeof(request
->read_buf
)) /* check if we have even more pending in the socket */
2382 if ((ret
= netconn_query_data_available( &request
->netconn
, &extra
)))
2384 count
= min( count
+ extra
, request
->content_length
- request
->content_read
);
2389 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
, &count
, sizeof(count
) );
2392 WINHTTP_ASYNC_RESULT result
;
2393 result
.dwResult
= API_QUERY_DATA_AVAILABLE
;
2394 result
.dwError
= get_last_error();
2395 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2400 TRACE("%u bytes available\n", count
);
2401 if (available
) *available
= count
;
2406 static void task_query_data_available( task_header_t
*task
)
2408 query_data_t
*q
= (query_data_t
*)task
;
2409 query_data_available( q
->hdr
.request
, q
->available
, TRUE
);
2412 /***********************************************************************
2413 * WinHttpQueryDataAvailable (winhttp.@)
2415 BOOL WINAPI
WinHttpQueryDataAvailable( HINTERNET hrequest
, LPDWORD available
)
2420 TRACE("%p, %p\n", hrequest
, available
);
2422 if (!(request
= (request_t
*)grab_object( hrequest
)))
2424 set_last_error( ERROR_INVALID_HANDLE
);
2427 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2429 release_object( &request
->hdr
);
2430 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2434 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2438 if (!(q
= heap_alloc( sizeof(query_data_t
) ))) return FALSE
;
2439 q
->hdr
.request
= request
;
2440 q
->hdr
.proc
= task_query_data_available
;
2441 q
->available
= available
;
2443 addref_object( &request
->hdr
);
2444 ret
= queue_task( (task_header_t
*)q
);
2447 ret
= query_data_available( request
, available
, FALSE
);
2449 release_object( &request
->hdr
);
2453 static void task_read_data( task_header_t
*task
)
2455 read_data_t
*r
= (read_data_t
*)task
;
2456 read_data( r
->hdr
.request
, r
->buffer
, r
->to_read
, r
->read
, TRUE
);
2459 /***********************************************************************
2460 * WinHttpReadData (winhttp.@)
2462 BOOL WINAPI
WinHttpReadData( HINTERNET hrequest
, LPVOID buffer
, DWORD to_read
, LPDWORD read
)
2467 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_read
, read
);
2469 if (!(request
= (request_t
*)grab_object( hrequest
)))
2471 set_last_error( ERROR_INVALID_HANDLE
);
2474 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2476 release_object( &request
->hdr
);
2477 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2481 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2485 if (!(r
= heap_alloc( sizeof(read_data_t
) ))) return FALSE
;
2486 r
->hdr
.request
= request
;
2487 r
->hdr
.proc
= task_read_data
;
2489 r
->to_read
= to_read
;
2492 addref_object( &request
->hdr
);
2493 ret
= queue_task( (task_header_t
*)r
);
2496 ret
= read_data( request
, buffer
, to_read
, read
, FALSE
);
2498 release_object( &request
->hdr
);
2502 static BOOL
write_data( request_t
*request
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
, BOOL async
)
2507 ret
= netconn_send( &request
->netconn
, buffer
, to_write
, &num_bytes
);
2511 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
, &num_bytes
, sizeof(DWORD
) );
2514 WINHTTP_ASYNC_RESULT result
;
2515 result
.dwResult
= API_WRITE_DATA
;
2516 result
.dwError
= get_last_error();
2517 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2520 if (ret
&& written
) *written
= num_bytes
;
2524 static void task_write_data( task_header_t
*task
)
2526 write_data_t
*w
= (write_data_t
*)task
;
2527 write_data( w
->hdr
.request
, w
->buffer
, w
->to_write
, w
->written
, TRUE
);
2530 /***********************************************************************
2531 * WinHttpWriteData (winhttp.@)
2533 BOOL WINAPI
WinHttpWriteData( HINTERNET hrequest
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
)
2538 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_write
, written
);
2540 if (!(request
= (request_t
*)grab_object( hrequest
)))
2542 set_last_error( ERROR_INVALID_HANDLE
);
2545 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2547 release_object( &request
->hdr
);
2548 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2552 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2556 if (!(w
= heap_alloc( sizeof(write_data_t
) ))) return FALSE
;
2557 w
->hdr
.request
= request
;
2558 w
->hdr
.proc
= task_write_data
;
2560 w
->to_write
= to_write
;
2561 w
->written
= written
;
2563 addref_object( &request
->hdr
);
2564 ret
= queue_task( (task_header_t
*)w
);
2567 ret
= write_data( request
, buffer
, to_write
, written
, FALSE
);
2569 release_object( &request
->hdr
);
2575 REQUEST_STATE_UNINITIALIZED
,
2576 REQUEST_STATE_INITIALIZED
,
2577 REQUEST_STATE_CANCELLED
,
2580 REQUEST_STATE_RESPONSE_RECEIVED
2583 struct winhttp_request
2585 IWinHttpRequest IWinHttpRequest_iface
;
2587 CRITICAL_SECTION cs
;
2588 enum request_state state
;
2599 DWORD bytes_available
;
2603 DWORD disable_feature
;
2604 LONG resolve_timeout
;
2605 LONG connect_timeout
;
2607 LONG receive_timeout
;
2608 WINHTTP_PROXY_INFO proxy
;
2611 static inline struct winhttp_request
*impl_from_IWinHttpRequest( IWinHttpRequest
*iface
)
2613 return CONTAINING_RECORD( iface
, struct winhttp_request
, IWinHttpRequest_iface
);
2616 static ULONG WINAPI
winhttp_request_AddRef(
2617 IWinHttpRequest
*iface
)
2619 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2620 return InterlockedIncrement( &request
->refs
);
2623 /* critical section must be held */
2624 static void cancel_request( struct winhttp_request
*request
)
2626 if (request
->state
<= REQUEST_STATE_CANCELLED
) return;
2627 if (request
->thread
) SetEvent( request
->cancel
);
2628 request
->state
= REQUEST_STATE_CANCELLED
;
2631 /* critical section must be held */
2632 static void free_request( struct winhttp_request
*request
)
2634 if (request
->state
< REQUEST_STATE_INITIALIZED
) return;
2635 WinHttpCloseHandle( request
->hrequest
);
2636 WinHttpCloseHandle( request
->hconnect
);
2637 WinHttpCloseHandle( request
->hsession
);
2638 CloseHandle( request
->thread
);
2639 CloseHandle( request
->wait
);
2640 CloseHandle( request
->cancel
);
2641 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2642 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2643 heap_free( request
->buffer
);
2644 heap_free( request
->verb
);
2645 VariantClear( &request
->data
);
2648 static ULONG WINAPI
winhttp_request_Release(
2649 IWinHttpRequest
*iface
)
2651 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2652 LONG refs
= InterlockedDecrement( &request
->refs
);
2655 TRACE("destroying %p\n", request
);
2657 EnterCriticalSection( &request
->cs
);
2658 cancel_request( request
);
2659 free_request( request
);
2660 LeaveCriticalSection( &request
->cs
);
2661 request
->cs
.DebugInfo
->Spare
[0] = 0;
2662 DeleteCriticalSection( &request
->cs
);
2663 heap_free( request
);
2668 static HRESULT WINAPI
winhttp_request_QueryInterface(
2669 IWinHttpRequest
*iface
,
2673 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2675 TRACE("%p, %s, %p\n", request
, debugstr_guid(riid
), obj
);
2677 if (IsEqualGUID( riid
, &IID_IWinHttpRequest
) ||
2678 IsEqualGUID( riid
, &IID_IDispatch
) ||
2679 IsEqualGUID( riid
, &IID_IUnknown
))
2685 FIXME("interface %s not implemented\n", debugstr_guid(riid
));
2686 return E_NOINTERFACE
;
2688 IWinHttpRequest_AddRef( iface
);
2692 static HRESULT WINAPI
winhttp_request_GetTypeInfoCount(
2693 IWinHttpRequest
*iface
,
2696 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2698 TRACE("%p, %p\n", request
, count
);
2705 IWinHttpRequest_tid
,
2709 static ITypeLib
*winhttp_typelib
;
2710 static ITypeInfo
*winhttp_typeinfo
[last_tid
];
2712 static REFIID winhttp_tid_id
[] =
2714 &IID_IWinHttpRequest
2717 static HRESULT
get_typeinfo( enum type_id tid
, ITypeInfo
**ret
)
2721 if (!winhttp_typelib
)
2725 hr
= LoadRegTypeLib( &LIBID_WinHttp
, 5, 1, LOCALE_SYSTEM_DEFAULT
, &typelib
);
2728 ERR("LoadRegTypeLib failed: %08x\n", hr
);
2731 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib
, typelib
, NULL
))
2732 ITypeLib_Release( typelib
);
2734 if (!winhttp_typeinfo
[tid
])
2736 ITypeInfo
*typeinfo
;
2738 hr
= ITypeLib_GetTypeInfoOfGuid( winhttp_typelib
, winhttp_tid_id
[tid
], &typeinfo
);
2741 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id
[tid
]), hr
);
2744 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo
+ tid
), typeinfo
, NULL
))
2745 ITypeInfo_Release( typeinfo
);
2747 *ret
= winhttp_typeinfo
[tid
];
2751 static HRESULT WINAPI
winhttp_request_GetTypeInfo(
2752 IWinHttpRequest
*iface
,
2757 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2758 TRACE("%p, %u, %u, %p\n", request
, index
, lcid
, info
);
2760 return get_typeinfo( IWinHttpRequest_tid
, info
);
2763 static HRESULT WINAPI
winhttp_request_GetIDsOfNames(
2764 IWinHttpRequest
*iface
,
2771 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2772 ITypeInfo
*typeinfo
;
2775 TRACE("%p, %s, %p, %u, %u, %p\n", request
, debugstr_guid(riid
), names
, count
, lcid
, dispid
);
2777 if (!names
|| !count
|| !dispid
) return E_INVALIDARG
;
2779 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
2782 hr
= ITypeInfo_GetIDsOfNames( typeinfo
, names
, count
, dispid
);
2783 ITypeInfo_Release( typeinfo
);
2788 static HRESULT WINAPI
winhttp_request_Invoke(
2789 IWinHttpRequest
*iface
,
2796 EXCEPINFO
*excep_info
,
2799 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2800 ITypeInfo
*typeinfo
;
2803 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request
, member
, debugstr_guid(riid
),
2804 lcid
, flags
, params
, result
, excep_info
, arg_err
);
2806 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
2809 hr
= ITypeInfo_Invoke( typeinfo
, &request
->IWinHttpRequest_iface
, member
, flags
,
2810 params
, result
, excep_info
, arg_err
);
2811 ITypeInfo_Release( typeinfo
);
2816 static HRESULT WINAPI
winhttp_request_SetProxy(
2817 IWinHttpRequest
*iface
,
2818 HTTPREQUEST_PROXY_SETTING proxy_setting
,
2819 VARIANT proxy_server
,
2820 VARIANT bypass_list
)
2822 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2823 DWORD err
= ERROR_SUCCESS
;
2825 TRACE("%p, %u, %s, %s\n", request
, proxy_setting
, debugstr_variant(&proxy_server
),
2826 debugstr_variant(&bypass_list
));
2828 EnterCriticalSection( &request
->cs
);
2829 switch (proxy_setting
)
2831 case HTTPREQUEST_PROXYSETTING_DEFAULT
:
2832 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
2833 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2834 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2835 request
->proxy
.lpszProxy
= NULL
;
2836 request
->proxy
.lpszProxyBypass
= NULL
;
2839 case HTTPREQUEST_PROXYSETTING_DIRECT
:
2840 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NO_PROXY
;
2841 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2842 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2843 request
->proxy
.lpszProxy
= NULL
;
2844 request
->proxy
.lpszProxyBypass
= NULL
;
2847 case HTTPREQUEST_PROXYSETTING_PROXY
:
2848 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
2849 if (V_VT( &proxy_server
) == VT_BSTR
)
2851 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2852 request
->proxy
.lpszProxy
= strdupW( V_BSTR( &proxy_server
) );
2854 if (V_VT( &bypass_list
) == VT_BSTR
)
2856 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2857 request
->proxy
.lpszProxyBypass
= strdupW( V_BSTR( &bypass_list
) );
2862 err
= ERROR_INVALID_PARAMETER
;
2865 LeaveCriticalSection( &request
->cs
);
2866 return HRESULT_FROM_WIN32( err
);
2869 static HRESULT WINAPI
winhttp_request_SetCredentials(
2870 IWinHttpRequest
*iface
,
2873 HTTPREQUEST_SETCREDENTIALS_FLAGS flags
)
2875 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2876 DWORD target
, scheme
= WINHTTP_AUTH_SCHEME_BASIC
; /* FIXME: query supported schemes */
2877 DWORD err
= ERROR_SUCCESS
;
2879 TRACE("%p, %s, %p\n", request
, debugstr_w(username
), password
);
2881 EnterCriticalSection( &request
->cs
);
2882 if (request
->state
< REQUEST_STATE_OPEN
)
2884 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
2889 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
:
2890 target
= WINHTTP_AUTH_TARGET_SERVER
;
2892 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY
:
2893 target
= WINHTTP_AUTH_TARGET_PROXY
;
2896 err
= ERROR_INVALID_PARAMETER
;
2899 if (!WinHttpSetCredentials( request
->hrequest
, target
, scheme
, username
, password
, NULL
))
2901 err
= get_last_error();
2904 LeaveCriticalSection( &request
->cs
);
2905 return HRESULT_FROM_WIN32( err
);
2908 static void initialize_request( struct winhttp_request
*request
)
2910 request
->hrequest
= NULL
;
2911 request
->hconnect
= NULL
;
2912 request
->hsession
= NULL
;
2913 request
->thread
= NULL
;
2914 request
->wait
= NULL
;
2915 request
->cancel
= NULL
;
2916 request
->buffer
= NULL
;
2917 request
->verb
= NULL
;
2918 request
->offset
= 0;
2919 request
->bytes_available
= 0;
2920 request
->bytes_read
= 0;
2921 request
->error
= ERROR_SUCCESS
;
2922 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
2923 request
->disable_feature
= WINHTTP_DISABLE_AUTHENTICATION
;
2924 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
2925 request
->proxy
.lpszProxy
= NULL
;
2926 request
->proxy
.lpszProxyBypass
= NULL
;
2927 request
->resolve_timeout
= 0;
2928 request
->connect_timeout
= 60000;
2929 request
->send_timeout
= 30000;
2930 request
->receive_timeout
= 30000;
2931 VariantInit( &request
->data
);
2932 request
->state
= REQUEST_STATE_INITIALIZED
;
2935 static HRESULT WINAPI
winhttp_request_Open(
2936 IWinHttpRequest
*iface
,
2941 static const WCHAR typeW
[] = {'*','/','*',0};
2942 static const WCHAR
*acceptW
[] = {typeW
, NULL
};
2943 static const WCHAR httpsW
[] = {'h','t','t','p','s'};
2944 static const WCHAR user_agentW
[] = {
2945 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
2946 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
2947 'R','e','q','u','e','s','t','.','5',')',0};
2948 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2949 HINTERNET hsession
= NULL
, hconnect
= NULL
, hrequest
;
2951 WCHAR
*hostname
, *path
= NULL
, *verb
= NULL
;
2952 DWORD err
= ERROR_OUTOFMEMORY
, len
, flags
= 0, request_flags
= 0;
2954 TRACE("%p, %s, %s, %s\n", request
, debugstr_w(method
), debugstr_w(url
),
2955 debugstr_variant(&async
));
2957 if (!method
|| !url
) return E_INVALIDARG
;
2959 memset( &uc
, 0, sizeof(uc
) );
2960 uc
.dwStructSize
= sizeof(uc
);
2961 uc
.dwSchemeLength
= ~0u;
2962 uc
.dwHostNameLength
= ~0u;
2963 uc
.dwUrlPathLength
= ~0u;
2964 uc
.dwExtraInfoLength
= ~0u;
2965 if (!WinHttpCrackUrl( url
, 0, 0, &uc
)) return HRESULT_FROM_WIN32( get_last_error() );
2967 EnterCriticalSection( &request
->cs
);
2968 if (request
->state
!= REQUEST_STATE_INITIALIZED
)
2970 cancel_request( request
);
2971 free_request( request
);
2972 initialize_request( request
);
2974 if (!(hostname
= heap_alloc( (uc
.dwHostNameLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
2975 memcpy( hostname
, uc
.lpszHostName
, uc
.dwHostNameLength
* sizeof(WCHAR
) );
2976 hostname
[uc
.dwHostNameLength
] = 0;
2978 if (!(path
= heap_alloc( (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
2979 memcpy( path
, uc
.lpszUrlPath
, (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
) * sizeof(WCHAR
) );
2980 path
[uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
] = 0;
2982 if (!(verb
= strdupW( method
))) goto error
;
2983 if (V_BOOL( &async
)) flags
|= WINHTTP_FLAG_ASYNC
;
2984 if (!(hsession
= WinHttpOpen( user_agentW
, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
, NULL
, NULL
, flags
)))
2986 err
= get_last_error();
2989 if (!(hconnect
= WinHttpConnect( hsession
, hostname
, uc
.nPort
, 0 )))
2991 err
= get_last_error();
2994 len
= sizeof(httpsW
) / sizeof(WCHAR
);
2995 if (uc
.dwSchemeLength
== len
&& !memcmp( uc
.lpszScheme
, httpsW
, len
* sizeof(WCHAR
) ))
2997 request_flags
|= WINHTTP_FLAG_SECURE
;
2999 if (!(hrequest
= WinHttpOpenRequest( hconnect
, method
, path
, NULL
, NULL
, acceptW
, request_flags
)))
3001 err
= get_last_error();
3004 if (flags
& WINHTTP_FLAG_ASYNC
)
3006 request
->wait
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
3007 request
->cancel
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
3008 WinHttpSetOption( hrequest
, WINHTTP_OPTION_CONTEXT_VALUE
, &request
, sizeof(request
) );
3010 request
->state
= REQUEST_STATE_OPEN
;
3011 request
->hsession
= hsession
;
3012 request
->hconnect
= hconnect
;
3013 request
->hrequest
= hrequest
;
3014 request
->verb
= verb
;
3015 heap_free( hostname
);
3017 LeaveCriticalSection( &request
->cs
);
3021 WinHttpCloseHandle( hconnect
);
3022 WinHttpCloseHandle( hsession
);
3023 heap_free( hostname
);
3026 LeaveCriticalSection( &request
->cs
);
3027 return HRESULT_FROM_WIN32( err
);
3030 static HRESULT WINAPI
winhttp_request_SetRequestHeader(
3031 IWinHttpRequest
*iface
,
3035 static const WCHAR fmtW
[] = {'%','s',':',' ','%','s','\r','\n',0};
3036 static const WCHAR emptyW
[] = {0};
3037 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3038 DWORD len
, err
= ERROR_SUCCESS
;
3041 TRACE("%p, %s, %s\n", request
, debugstr_w(header
), debugstr_w(value
));
3043 if (!header
) return E_INVALIDARG
;
3045 EnterCriticalSection( &request
->cs
);
3046 if (request
->state
< REQUEST_STATE_OPEN
)
3048 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
3051 if (request
->state
>= REQUEST_STATE_SENT
)
3053 err
= ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND
;
3056 len
= strlenW( header
) + 4;
3057 if (value
) len
+= strlenW( value
);
3058 if (!(str
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
3060 err
= ERROR_OUTOFMEMORY
;
3063 sprintfW( str
, fmtW
, header
, value
? value
: emptyW
);
3064 if (!WinHttpAddRequestHeaders( request
->hrequest
, str
, len
, WINHTTP_ADDREQ_FLAG_REPLACE
))
3066 err
= get_last_error();
3071 LeaveCriticalSection( &request
->cs
);
3072 return HRESULT_FROM_WIN32( err
);
3075 static HRESULT WINAPI
winhttp_request_GetResponseHeader(
3076 IWinHttpRequest
*iface
,
3080 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3081 DWORD size
, err
= ERROR_SUCCESS
;
3083 TRACE("%p, %p\n", request
, header
);
3085 EnterCriticalSection( &request
->cs
);
3086 if (request
->state
< REQUEST_STATE_SENT
)
3088 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3091 if (!header
|| !value
)
3093 err
= ERROR_INVALID_PARAMETER
;
3097 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, NULL
, &size
, NULL
))
3099 err
= get_last_error();
3100 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3102 if (!(*value
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
3104 err
= ERROR_OUTOFMEMORY
;
3107 err
= ERROR_SUCCESS
;
3108 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, *value
, &size
, NULL
))
3110 err
= get_last_error();
3111 SysFreeString( *value
);
3114 LeaveCriticalSection( &request
->cs
);
3115 return HRESULT_FROM_WIN32( err
);
3118 static HRESULT WINAPI
winhttp_request_GetAllResponseHeaders(
3119 IWinHttpRequest
*iface
,
3122 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3123 DWORD size
, err
= ERROR_SUCCESS
;
3125 TRACE("%p, %p\n", request
, headers
);
3127 if (!headers
) return E_INVALIDARG
;
3129 EnterCriticalSection( &request
->cs
);
3130 if (request
->state
< REQUEST_STATE_SENT
)
3132 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3136 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, NULL
, &size
, NULL
))
3138 err
= get_last_error();
3139 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3141 if (!(*headers
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
3143 err
= ERROR_OUTOFMEMORY
;
3146 err
= ERROR_SUCCESS
;
3147 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, *headers
, &size
, NULL
))
3149 err
= get_last_error();
3150 SysFreeString( *headers
);
3153 LeaveCriticalSection( &request
->cs
);
3154 return HRESULT_FROM_WIN32( err
);
3157 static void CALLBACK
wait_status_callback( HINTERNET handle
, DWORD_PTR context
, DWORD status
, LPVOID buffer
, DWORD size
)
3159 struct winhttp_request
*request
= (struct winhttp_request
*)context
;
3163 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
:
3164 request
->bytes_available
= *(DWORD
*)buffer
;
3165 request
->error
= ERROR_SUCCESS
;
3167 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE
:
3168 request
->bytes_read
= size
;
3169 request
->error
= ERROR_SUCCESS
;
3171 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
:
3173 WINHTTP_ASYNC_RESULT
*result
= (WINHTTP_ASYNC_RESULT
*)buffer
;
3174 request
->error
= result
->dwError
;
3179 SetEvent( request
->wait
);
3182 static void wait_set_status_callback( struct winhttp_request
*request
, DWORD status
)
3184 if (!request
->wait
) return;
3185 status
|= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
;
3186 WinHttpSetStatusCallback( request
->hrequest
, wait_status_callback
, status
, 0 );
3189 static DWORD
wait_for_completion( struct winhttp_request
*request
)
3195 request
->error
= ERROR_SUCCESS
;
3196 return ERROR_SUCCESS
;
3198 handles
[0] = request
->wait
;
3199 handles
[1] = request
->cancel
;
3200 switch (WaitForMultipleObjects( 2, handles
, FALSE
, INFINITE
))
3204 case WAIT_OBJECT_0
+ 1:
3205 request
->error
= ERROR_CANCELLED
;
3208 request
->error
= get_last_error();
3211 return request
->error
;
3214 static HRESULT
request_receive( struct winhttp_request
*request
)
3216 DWORD err
, size
, buflen
= 4096;
3218 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
);
3219 if (!WinHttpReceiveResponse( request
->hrequest
, NULL
))
3221 return HRESULT_FROM_WIN32( get_last_error() );
3223 if ((err
= wait_for_completion( request
))) return HRESULT_FROM_WIN32( err
);
3224 if (!strcmpW( request
->verb
, headW
))
3226 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
3229 if (!(request
->buffer
= heap_alloc( buflen
))) return E_OUTOFMEMORY
;
3230 request
->buffer
[0] = 0;
3234 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
);
3235 if (!WinHttpQueryDataAvailable( request
->hrequest
, &request
->bytes_available
))
3237 err
= get_last_error();
3240 if ((err
= wait_for_completion( request
))) goto error
;
3241 if (!request
->bytes_available
) break;
3242 size
+= request
->bytes_available
;
3246 while (buflen
< size
) buflen
*= 2;
3247 if (!(tmp
= heap_realloc( request
->buffer
, buflen
)))
3249 err
= ERROR_OUTOFMEMORY
;
3252 request
->buffer
= tmp
;
3254 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
);
3255 if (!WinHttpReadData( request
->hrequest
, request
->buffer
+ request
->offset
,
3256 request
->bytes_available
, &request
->bytes_read
))
3258 err
= get_last_error();
3261 if ((err
= wait_for_completion( request
))) goto error
;
3262 request
->offset
+= request
->bytes_read
;
3263 } while (request
->bytes_read
);
3265 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
3269 heap_free( request
->buffer
);
3270 request
->buffer
= NULL
;
3271 return HRESULT_FROM_WIN32( err
);
3274 static DWORD
request_set_parameters( struct winhttp_request
*request
)
3276 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_PROXY
, &request
->proxy
,
3277 sizeof(request
->proxy
) )) return get_last_error();
3279 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_AUTOLOGON_POLICY
, &request
->logon_policy
,
3280 sizeof(request
->logon_policy
) )) return get_last_error();
3282 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_DISABLE_FEATURE
, &request
->disable_feature
,
3283 sizeof(request
->disable_feature
) )) return get_last_error();
3285 if (!WinHttpSetTimeouts( request
->hrequest
,
3286 request
->resolve_timeout
,
3287 request
->connect_timeout
,
3288 request
->send_timeout
,
3289 request
->receive_timeout
)) return get_last_error();
3290 return ERROR_SUCCESS
;
3293 static void request_set_utf8_content_type( struct winhttp_request
*request
)
3295 static const WCHAR fmtW
[] = {'%','s',':',' ','%','s',0};
3296 static const WCHAR text_plainW
[] = {'t','e','x','t','/','p','l','a','i','n',0};
3297 static const WCHAR charset_utf8W
[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3301 len
= sprintfW( headerW
, fmtW
, attr_content_type
, text_plainW
);
3302 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
3303 len
= sprintfW( headerW
, fmtW
, attr_content_type
, charset_utf8W
);
3304 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
);
3307 static HRESULT
request_send( struct winhttp_request
*request
)
3309 SAFEARRAY
*sa
= NULL
;
3316 if ((err
= request_set_parameters( request
))) return HRESULT_FROM_WIN32( err
);
3317 if (strcmpW( request
->verb
, getW
))
3319 VariantInit( &data
);
3320 if (V_VT( &request
->data
) == VT_BSTR
)
3323 const WCHAR
*str
= V_BSTR( &request
->data
);
3324 int i
, len
= strlenW( str
);
3326 for (i
= 0; i
< len
; i
++)
3334 size
= WideCharToMultiByte( cp
, 0, str
, len
, NULL
, 0, NULL
, NULL
);
3335 if (!(ptr
= heap_alloc( size
))) return E_OUTOFMEMORY
;
3336 WideCharToMultiByte( cp
, 0, str
, len
, ptr
, size
, NULL
, NULL
);
3337 if (cp
== CP_UTF8
) request_set_utf8_content_type( request
);
3339 else if (VariantChangeType( &data
, &request
->data
, 0, VT_ARRAY
|VT_UI1
) == S_OK
)
3341 sa
= V_ARRAY( &data
);
3342 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
) return hr
;
3343 if ((hr
= SafeArrayGetUBound( sa
, 1, &size
) != S_OK
))
3345 SafeArrayUnaccessData( sa
);
3351 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
);
3352 if (!WinHttpSendRequest( request
->hrequest
, NULL
, 0, ptr
, size
, size
, 0 ))
3354 err
= get_last_error();
3357 if ((err
= wait_for_completion( request
))) goto error
;
3358 if (sa
) SafeArrayUnaccessData( sa
);
3359 else heap_free( ptr
);
3360 request
->state
= REQUEST_STATE_SENT
;
3364 if (sa
) SafeArrayUnaccessData( sa
);
3365 else heap_free( ptr
);
3366 return HRESULT_FROM_WIN32( err
);
3369 static HRESULT
request_send_and_receive( struct winhttp_request
*request
)
3371 HRESULT hr
= request_send( request
);
3372 if (hr
== S_OK
) hr
= request_receive( request
);
3376 static DWORD CALLBACK
send_and_receive_proc( void *arg
)
3378 struct winhttp_request
*request
= (struct winhttp_request
*)arg
;
3379 return request_send_and_receive( request
);
3382 static HRESULT WINAPI
winhttp_request_Send(
3383 IWinHttpRequest
*iface
,
3386 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3389 TRACE("%p, %s\n", request
, debugstr_variant(&body
));
3391 EnterCriticalSection( &request
->cs
);
3392 if (request
->state
< REQUEST_STATE_OPEN
)
3394 LeaveCriticalSection( &request
->cs
);
3395 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
);
3397 if (request
->state
>= REQUEST_STATE_SENT
)
3399 LeaveCriticalSection( &request
->cs
);
3402 VariantClear( &request
->data
);
3403 if ((hr
= VariantCopyInd( &request
->data
, &body
)) != S_OK
) {
3404 LeaveCriticalSection( &request
->cs
);
3408 if (request
->wait
) /* async request */
3410 if (!(request
->thread
= CreateThread( NULL
, 0, send_and_receive_proc
, request
, 0, NULL
)))
3412 LeaveCriticalSection( &request
->cs
);
3413 return HRESULT_FROM_WIN32( get_last_error() );
3416 else hr
= request_send_and_receive( request
);
3417 LeaveCriticalSection( &request
->cs
);
3421 static HRESULT WINAPI
winhttp_request_get_Status(
3422 IWinHttpRequest
*iface
,
3425 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3426 DWORD err
= ERROR_SUCCESS
, flags
, status_code
, len
= sizeof(status_code
), index
= 0;
3428 TRACE("%p, %p\n", request
, status
);
3430 if (!status
) return E_INVALIDARG
;
3432 EnterCriticalSection( &request
->cs
);
3433 if (request
->state
< REQUEST_STATE_SENT
)
3435 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3438 flags
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
3439 if (!WinHttpQueryHeaders( request
->hrequest
, flags
, NULL
, &status_code
, &len
, &index
))
3441 err
= get_last_error();
3444 *status
= status_code
;
3447 LeaveCriticalSection( &request
->cs
);
3448 return HRESULT_FROM_WIN32( err
);
3451 static HRESULT WINAPI
winhttp_request_get_StatusText(
3452 IWinHttpRequest
*iface
,
3455 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3456 DWORD err
= ERROR_SUCCESS
, len
= 0, index
= 0;
3458 TRACE("%p, %p\n", request
, status
);
3460 if (!status
) return E_INVALIDARG
;
3462 EnterCriticalSection( &request
->cs
);
3463 if (request
->state
< REQUEST_STATE_SENT
)
3465 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3468 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, NULL
, &len
, &index
))
3470 err
= get_last_error();
3471 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3473 if (!(*status
= SysAllocStringLen( NULL
, len
/ sizeof(WCHAR
) )))
3475 err
= ERROR_OUTOFMEMORY
;
3479 err
= ERROR_SUCCESS
;
3480 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, *status
, &len
, &index
))
3482 err
= get_last_error();
3483 SysFreeString( *status
);
3486 LeaveCriticalSection( &request
->cs
);
3487 return HRESULT_FROM_WIN32( err
);
3490 static DWORD
request_get_codepage( struct winhttp_request
*request
, UINT
*codepage
)
3492 static const WCHAR utf8W
[] = {'u','t','f','-','8',0};
3493 static const WCHAR charsetW
[] = {'c','h','a','r','s','e','t',0};
3498 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, NULL
, &size
, NULL
) &&
3499 get_last_error() == ERROR_INSUFFICIENT_BUFFER
)
3501 if (!(buffer
= heap_alloc( size
))) return ERROR_OUTOFMEMORY
;
3502 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, buffer
, &size
, NULL
))
3504 return get_last_error();
3506 if ((p
= strstrW( buffer
, charsetW
)))
3508 p
+= strlenW( charsetW
);
3509 while (*p
== ' ') p
++;
3512 while (*p
== ' ') p
++;
3513 if (!strcmpiW( p
, utf8W
)) *codepage
= CP_UTF8
;
3516 heap_free( buffer
);
3518 return ERROR_SUCCESS
;
3521 static HRESULT WINAPI
winhttp_request_get_ResponseText(
3522 IWinHttpRequest
*iface
,
3525 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3527 DWORD err
= ERROR_SUCCESS
;
3530 TRACE("%p, %p\n", request
, body
);
3532 if (!body
) return E_INVALIDARG
;
3534 EnterCriticalSection( &request
->cs
);
3535 if (request
->state
< REQUEST_STATE_SENT
)
3537 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3540 if ((err
= request_get_codepage( request
, &codepage
))) goto done
;
3541 len
= MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, NULL
, 0 );
3542 if (!(*body
= SysAllocStringLen( NULL
, len
)))
3544 err
= ERROR_OUTOFMEMORY
;
3547 MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, *body
, len
);
3551 LeaveCriticalSection( &request
->cs
);
3552 return HRESULT_FROM_WIN32( err
);
3555 static HRESULT WINAPI
winhttp_request_get_ResponseBody(
3556 IWinHttpRequest
*iface
,
3559 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3562 DWORD err
= ERROR_SUCCESS
;
3565 TRACE("%p, %p\n", request
, body
);
3567 if (!body
) return E_INVALIDARG
;
3569 EnterCriticalSection( &request
->cs
);
3570 if (!(sa
= SafeArrayCreateVector( VT_UI1
, 0, request
->offset
)))
3572 err
= ERROR_OUTOFMEMORY
;
3575 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
)
3577 SafeArrayDestroy( sa
);
3578 LeaveCriticalSection( &request
->cs
);
3581 memcpy( ptr
, request
->buffer
, request
->offset
);
3582 if ((hr
= SafeArrayUnaccessData( sa
)) != S_OK
)
3584 SafeArrayDestroy( sa
);
3585 LeaveCriticalSection( &request
->cs
);
3588 V_VT( body
) = VT_ARRAY
|VT_UI1
;
3589 V_ARRAY( body
) = sa
;
3592 LeaveCriticalSection( &request
->cs
);
3593 return HRESULT_FROM_WIN32( err
);
3596 static HRESULT WINAPI
winhttp_request_get_ResponseStream(
3597 IWinHttpRequest
*iface
,
3604 static HRESULT WINAPI
winhttp_request_get_Option(
3605 IWinHttpRequest
*iface
,
3606 WinHttpRequestOption option
,
3613 static HRESULT WINAPI
winhttp_request_put_Option(
3614 IWinHttpRequest
*iface
,
3615 WinHttpRequestOption option
,
3618 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3621 TRACE("%p, %u, %s\n", request
, option
, debugstr_variant(&value
));
3623 EnterCriticalSection( &request
->cs
);
3626 case WinHttpRequestOption_EnableRedirects
:
3628 if (V_BOOL( &value
))
3629 request
->disable_feature
&= ~WINHTTP_DISABLE_REDIRECTS
;
3631 request
->disable_feature
|= WINHTTP_DISABLE_REDIRECTS
;
3635 FIXME("unimplemented option %u\n", option
);
3639 LeaveCriticalSection( &request
->cs
);
3643 /* critical section must be held */
3644 static DWORD
wait_for_response( struct winhttp_request
*request
, DWORD timeout
)
3646 HANDLE thread
= request
->thread
;
3649 LeaveCriticalSection( &request
->cs
);
3650 while ((err
= MsgWaitForMultipleObjects( 1, &thread
, FALSE
, timeout
, QS_ALLINPUT
)) == WAIT_OBJECT_0
+ 1)
3653 while (PeekMessageW( &msg
, NULL
, 0, 0, PM_REMOVE
))
3655 TranslateMessage( &msg
);
3656 DispatchMessageW( &msg
);
3662 ret
= ERROR_SUCCESS
;
3665 ret
= ERROR_TIMEOUT
;
3669 ret
= get_last_error();
3672 EnterCriticalSection( &request
->cs
);
3676 static HRESULT WINAPI
winhttp_request_WaitForResponse(
3677 IWinHttpRequest
*iface
,
3679 VARIANT_BOOL
*succeeded
)
3681 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3682 DWORD err
, msecs
= (V_I4(&timeout
) == -1) ? INFINITE
: V_I4(&timeout
) * 1000;
3684 TRACE("%p, %s, %p\n", request
, debugstr_variant(&timeout
), succeeded
);
3686 EnterCriticalSection( &request
->cs
);
3687 if (!request
->thread
)
3689 LeaveCriticalSection( &request
->cs
);
3692 if (request
->state
>= REQUEST_STATE_RESPONSE_RECEIVED
)
3694 LeaveCriticalSection( &request
->cs
);
3697 switch ((err
= wait_for_response( request
, msecs
)))
3700 if (succeeded
) *succeeded
= VARIANT_FALSE
;
3701 err
= ERROR_SUCCESS
;
3705 if (succeeded
) *succeeded
= VARIANT_TRUE
;
3710 LeaveCriticalSection( &request
->cs
);
3711 return HRESULT_FROM_WIN32( err
);
3714 static HRESULT WINAPI
winhttp_request_Abort(
3715 IWinHttpRequest
*iface
)
3717 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3719 TRACE("%p\n", request
);
3721 EnterCriticalSection( &request
->cs
);
3722 cancel_request( request
);
3723 LeaveCriticalSection( &request
->cs
);
3727 static HRESULT WINAPI
winhttp_request_SetTimeouts(
3728 IWinHttpRequest
*iface
,
3729 LONG resolve_timeout
,
3730 LONG connect_timeout
,
3732 LONG receive_timeout
)
3734 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3736 TRACE("%p, %d, %d, %d, %d\n", request
, resolve_timeout
, connect_timeout
, send_timeout
, receive_timeout
);
3738 EnterCriticalSection( &request
->cs
);
3739 request
->resolve_timeout
= resolve_timeout
;
3740 request
->connect_timeout
= connect_timeout
;
3741 request
->send_timeout
= send_timeout
;
3742 request
->receive_timeout
= receive_timeout
;
3743 LeaveCriticalSection( &request
->cs
);
3747 static HRESULT WINAPI
winhttp_request_SetClientCertificate(
3748 IWinHttpRequest
*iface
,
3755 static HRESULT WINAPI
winhttp_request_SetAutoLogonPolicy(
3756 IWinHttpRequest
*iface
,
3757 WinHttpRequestAutoLogonPolicy policy
)
3759 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3762 TRACE("%p, %u\n", request
, policy
);
3764 EnterCriticalSection( &request
->cs
);
3767 case AutoLogonPolicy_Always
:
3768 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW
;
3770 case AutoLogonPolicy_OnlyIfBypassProxy
:
3771 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
3773 case AutoLogonPolicy_Never
:
3774 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH
;
3776 default: hr
= E_INVALIDARG
;
3779 LeaveCriticalSection( &request
->cs
);
3783 static const struct IWinHttpRequestVtbl winhttp_request_vtbl
=
3785 winhttp_request_QueryInterface
,
3786 winhttp_request_AddRef
,
3787 winhttp_request_Release
,
3788 winhttp_request_GetTypeInfoCount
,
3789 winhttp_request_GetTypeInfo
,
3790 winhttp_request_GetIDsOfNames
,
3791 winhttp_request_Invoke
,
3792 winhttp_request_SetProxy
,
3793 winhttp_request_SetCredentials
,
3794 winhttp_request_Open
,
3795 winhttp_request_SetRequestHeader
,
3796 winhttp_request_GetResponseHeader
,
3797 winhttp_request_GetAllResponseHeaders
,
3798 winhttp_request_Send
,
3799 winhttp_request_get_Status
,
3800 winhttp_request_get_StatusText
,
3801 winhttp_request_get_ResponseText
,
3802 winhttp_request_get_ResponseBody
,
3803 winhttp_request_get_ResponseStream
,
3804 winhttp_request_get_Option
,
3805 winhttp_request_put_Option
,
3806 winhttp_request_WaitForResponse
,
3807 winhttp_request_Abort
,
3808 winhttp_request_SetTimeouts
,
3809 winhttp_request_SetClientCertificate
,
3810 winhttp_request_SetAutoLogonPolicy
3813 HRESULT
WinHttpRequest_create( IUnknown
*unknown
, void **obj
)
3815 struct winhttp_request
*request
;
3817 TRACE("%p, %p\n", unknown
, obj
);
3819 if (!(request
= heap_alloc( sizeof(*request
) ))) return E_OUTOFMEMORY
;
3820 request
->IWinHttpRequest_iface
.lpVtbl
= &winhttp_request_vtbl
;
3822 request
->state
= REQUEST_STATE_UNINITIALIZED
;
3823 request
->proxy
.lpszProxy
= NULL
;
3824 request
->proxy
.lpszProxyBypass
= NULL
;
3825 InitializeCriticalSection( &request
->cs
);
3826 request
->cs
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": winhttp_request.cs");
3828 *obj
= &request
->IWinHttpRequest_iface
;
3829 TRACE("returning iface %p\n", *obj
);