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>
30 #include <httprequest.h>
32 #include "inet_ntop.c"
34 static const WCHAR attr_accept
[] = {'A','c','c','e','p','t',0};
35 static const WCHAR attr_accept_charset
[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
36 static const WCHAR attr_accept_encoding
[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
37 static const WCHAR attr_accept_language
[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
38 static const WCHAR attr_accept_ranges
[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
39 static const WCHAR attr_age
[] = {'A','g','e',0};
40 static const WCHAR attr_allow
[] = {'A','l','l','o','w',0};
41 static const WCHAR attr_authorization
[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
42 static const WCHAR attr_cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
43 static const WCHAR attr_connection
[] = {'C','o','n','n','e','c','t','i','o','n',0};
44 static const WCHAR attr_content_base
[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
45 static const WCHAR attr_content_encoding
[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
46 static const WCHAR attr_content_id
[] = {'C','o','n','t','e','n','t','-','I','D',0};
47 static const WCHAR attr_content_language
[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
48 static const WCHAR attr_content_length
[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
49 static const WCHAR attr_content_location
[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
50 static const WCHAR attr_content_md5
[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
51 static const WCHAR attr_content_range
[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
52 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};
53 static const WCHAR attr_content_type
[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
54 static const WCHAR attr_cookie
[] = {'C','o','o','k','i','e',0};
55 static const WCHAR attr_date
[] = {'D','a','t','e',0};
56 static const WCHAR attr_from
[] = {'F','r','o','m',0};
57 static const WCHAR attr_etag
[] = {'E','T','a','g',0};
58 static const WCHAR attr_expect
[] = {'E','x','p','e','c','t',0};
59 static const WCHAR attr_expires
[] = {'E','x','p','i','r','e','s',0};
60 static const WCHAR attr_host
[] = {'H','o','s','t',0};
61 static const WCHAR attr_if_match
[] = {'I','f','-','M','a','t','c','h',0};
62 static const WCHAR attr_if_modified_since
[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
63 static const WCHAR attr_if_none_match
[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
64 static const WCHAR attr_if_range
[] = {'I','f','-','R','a','n','g','e',0};
65 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};
66 static const WCHAR attr_last_modified
[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
67 static const WCHAR attr_location
[] = {'L','o','c','a','t','i','o','n',0};
68 static const WCHAR attr_max_forwards
[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
69 static const WCHAR attr_mime_version
[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
70 static const WCHAR attr_pragma
[] = {'P','r','a','g','m','a',0};
71 static const WCHAR attr_proxy_authenticate
[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
72 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};
73 static const WCHAR attr_proxy_connection
[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
74 static const WCHAR attr_public
[] = {'P','u','b','l','i','c',0};
75 static const WCHAR attr_range
[] = {'R','a','n','g','e',0};
76 static const WCHAR attr_referer
[] = {'R','e','f','e','r','e','r',0};
77 static const WCHAR attr_retry_after
[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
78 static const WCHAR attr_server
[] = {'S','e','r','v','e','r',0};
79 static const WCHAR attr_set_cookie
[] = {'S','e','t','-','C','o','o','k','i','e',0};
80 static const WCHAR attr_status
[] = {'S','t','a','t','u','s',0};
81 static const WCHAR attr_transfer_encoding
[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
82 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};
83 static const WCHAR attr_upgrade
[] = {'U','p','g','r','a','d','e',0};
84 static const WCHAR attr_uri
[] = {'U','R','I',0};
85 static const WCHAR attr_user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',0};
86 static const WCHAR attr_vary
[] = {'V','a','r','y',0};
87 static const WCHAR attr_via
[] = {'V','i','a',0};
88 static const WCHAR attr_warning
[] = {'W','a','r','n','i','n','g',0};
89 static const WCHAR attr_www_authenticate
[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
91 static const WCHAR
*attribute_table
[] =
93 attr_mime_version
, /* WINHTTP_QUERY_MIME_VERSION = 0 */
94 attr_content_type
, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
95 attr_content_transfer_encoding
, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
96 attr_content_id
, /* WINHTTP_QUERY_CONTENT_ID = 3 */
97 NULL
, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
98 attr_content_length
, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
99 attr_content_language
, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
100 attr_allow
, /* WINHTTP_QUERY_ALLOW = 7 */
101 attr_public
, /* WINHTTP_QUERY_PUBLIC = 8 */
102 attr_date
, /* WINHTTP_QUERY_DATE = 9 */
103 attr_expires
, /* WINHTTP_QUERY_EXPIRES = 10 */
104 attr_last_modified
, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
105 NULL
, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
106 attr_uri
, /* WINHTTP_QUERY_URI = 13 */
107 attr_from
, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
108 NULL
, /* WINHTTP_QUERY_COST = 15 */
109 NULL
, /* WINHTTP_QUERY_LINK = 16 */
110 attr_pragma
, /* WINHTTP_QUERY_PRAGMA = 17 */
111 NULL
, /* WINHTTP_QUERY_VERSION = 18 */
112 attr_status
, /* WINHTTP_QUERY_STATUS_CODE = 19 */
113 NULL
, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
114 NULL
, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
115 NULL
, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
116 attr_connection
, /* WINHTTP_QUERY_CONNECTION = 23 */
117 attr_accept
, /* WINHTTP_QUERY_ACCEPT = 24 */
118 attr_accept_charset
, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
119 attr_accept_encoding
, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
120 attr_accept_language
, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
121 attr_authorization
, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
122 attr_content_encoding
, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
123 NULL
, /* WINHTTP_QUERY_FORWARDED = 30 */
124 NULL
, /* WINHTTP_QUERY_FROM = 31 */
125 attr_if_modified_since
, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
126 attr_location
, /* WINHTTP_QUERY_LOCATION = 33 */
127 NULL
, /* WINHTTP_QUERY_ORIG_URI = 34 */
128 attr_referer
, /* WINHTTP_QUERY_REFERER = 35 */
129 attr_retry_after
, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
130 attr_server
, /* WINHTTP_QUERY_SERVER = 37 */
131 NULL
, /* WINHTTP_TITLE = 38 */
132 attr_user_agent
, /* WINHTTP_QUERY_USER_AGENT = 39 */
133 attr_www_authenticate
, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
134 attr_proxy_authenticate
, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
135 attr_accept_ranges
, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
136 attr_set_cookie
, /* WINHTTP_QUERY_SET_COOKIE = 43 */
137 attr_cookie
, /* WINHTTP_QUERY_COOKIE = 44 */
138 NULL
, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
139 NULL
, /* WINHTTP_QUERY_REFRESH = 46 */
140 NULL
, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
141 attr_age
, /* WINHTTP_QUERY_AGE = 48 */
142 attr_cache_control
, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
143 attr_content_base
, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
144 attr_content_location
, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
145 attr_content_md5
, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
146 attr_content_range
, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
147 attr_etag
, /* WINHTTP_QUERY_ETAG = 54 */
148 attr_host
, /* WINHTTP_QUERY_HOST = 55 */
149 attr_if_match
, /* WINHTTP_QUERY_IF_MATCH = 56 */
150 attr_if_none_match
, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
151 attr_if_range
, /* WINHTTP_QUERY_IF_RANGE = 58 */
152 attr_if_unmodified_since
, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
153 attr_max_forwards
, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
154 attr_proxy_authorization
, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
155 attr_range
, /* WINHTTP_QUERY_RANGE = 62 */
156 attr_transfer_encoding
, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
157 attr_upgrade
, /* WINHTTP_QUERY_UPGRADE = 64 */
158 attr_vary
, /* WINHTTP_QUERY_VARY = 65 */
159 attr_via
, /* WINHTTP_QUERY_VIA = 66 */
160 attr_warning
, /* WINHTTP_QUERY_WARNING = 67 */
161 attr_expect
, /* WINHTTP_QUERY_EXPECT = 68 */
162 attr_proxy_connection
, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
163 attr_unless_modified_since
, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
164 NULL
, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
165 NULL
, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
166 NULL
, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
167 NULL
/* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
170 static DWORD CALLBACK
task_thread( LPVOID param
)
172 task_header_t
*task
= param
;
176 release_object( &task
->request
->hdr
);
178 return ERROR_SUCCESS
;
181 static BOOL
queue_task( task_header_t
*task
)
183 return QueueUserWorkItem( task_thread
, task
, WT_EXECUTELONGFUNCTION
);
186 static void free_header( header_t
*header
)
188 heap_free( header
->field
);
189 heap_free( header
->value
);
193 static BOOL
valid_token_char( WCHAR c
)
195 if (c
< 32 || c
== 127) return FALSE
;
202 case '\\': case '\"':
214 static header_t
*parse_header( LPCWSTR string
)
221 if (!(q
= strchrW( p
, ':' )))
223 WARN("no ':' in line %s\n", debugstr_w(string
));
228 WARN("empty field name in line %s\n", debugstr_w(string
));
233 if (!valid_token_char( *p
))
235 WARN("invalid character in field name %s\n", debugstr_w(string
));
241 if (!(header
= heap_alloc_zero( sizeof(header_t
) ))) return NULL
;
242 if (!(header
->field
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
247 memcpy( header
->field
, string
, len
* sizeof(WCHAR
) );
248 header
->field
[len
] = 0;
250 q
++; /* skip past colon */
251 while (*q
== ' ') q
++;
254 WARN("no value in line %s\n", debugstr_w(string
));
258 if (!(header
->value
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
260 free_header( header
);
263 memcpy( header
->value
, q
, len
* sizeof(WCHAR
) );
264 header
->value
[len
] = 0;
269 static int get_header_index( request_t
*request
, LPCWSTR field
, int requested_index
, BOOL request_only
)
273 TRACE("%s\n", debugstr_w(field
));
275 for (index
= 0; index
< request
->num_headers
; index
++)
277 if (strcmpiW( request
->headers
[index
].field
, field
)) continue;
278 if (request_only
&& !request
->headers
[index
].is_request
) continue;
279 if (!request_only
&& request
->headers
[index
].is_request
) continue;
281 if (!requested_index
) break;
284 if (index
>= request
->num_headers
) index
= -1;
285 TRACE("returning %d\n", index
);
289 static BOOL
insert_header( request_t
*request
, header_t
*header
)
294 count
= request
->num_headers
+ 1;
296 hdrs
= heap_realloc_zero( request
->headers
, sizeof(header_t
) * count
);
298 hdrs
= heap_alloc_zero( sizeof(header_t
) * count
);
302 request
->headers
= hdrs
;
303 request
->headers
[count
- 1].field
= strdupW( header
->field
);
304 request
->headers
[count
- 1].value
= strdupW( header
->value
);
305 request
->headers
[count
- 1].is_request
= header
->is_request
;
306 request
->num_headers
++;
312 static BOOL
delete_header( request_t
*request
, DWORD index
)
314 if (!request
->num_headers
) return FALSE
;
315 if (index
>= request
->num_headers
) return FALSE
;
316 request
->num_headers
--;
318 heap_free( request
->headers
[index
].field
);
319 heap_free( request
->headers
[index
].value
);
321 memmove( &request
->headers
[index
], &request
->headers
[index
+ 1], (request
->num_headers
- index
) * sizeof(header_t
) );
322 memset( &request
->headers
[request
->num_headers
], 0, sizeof(header_t
) );
326 static BOOL
process_header( request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD flags
, BOOL request_only
)
331 TRACE("%s: %s 0x%08x\n", debugstr_w(field
), debugstr_w(value
), flags
);
333 /* replace wins out over add */
334 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
) flags
&= ~WINHTTP_ADDREQ_FLAG_ADD
;
336 if (flags
& WINHTTP_ADDREQ_FLAG_ADD
) index
= -1;
338 index
= get_header_index( request
, field
, 0, request_only
);
342 if (flags
& WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
) return FALSE
;
343 header
= &request
->headers
[index
];
349 hdr
.field
= (LPWSTR
)field
;
350 hdr
.value
= (LPWSTR
)value
;
351 hdr
.is_request
= request_only
;
353 return insert_header( request
, &hdr
);
355 /* no value to delete */
358 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
)
360 delete_header( request
, index
);
365 hdr
.field
= (LPWSTR
)field
;
366 hdr
.value
= (LPWSTR
)value
;
367 hdr
.is_request
= request_only
;
369 return insert_header( request
, &hdr
);
373 else if (flags
& (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
| WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
))
376 int len
, orig_len
, value_len
;
378 orig_len
= strlenW( header
->value
);
379 value_len
= strlenW( value
);
381 if (flags
& WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
) sep
= ',';
384 len
= orig_len
+ value_len
+ 2;
385 if ((tmp
= heap_realloc( header
->value
, (len
+ 1) * sizeof(WCHAR
) )))
389 header
->value
[orig_len
] = sep
;
391 header
->value
[orig_len
] = ' ';
394 memcpy( &header
->value
[orig_len
], value
, value_len
* sizeof(WCHAR
) );
395 header
->value
[len
] = 0;
402 BOOL
add_request_headers( request_t
*request
, LPCWSTR headers
, DWORD len
, DWORD flags
)
405 WCHAR
*buffer
, *p
, *q
;
408 if (len
== ~0u) len
= strlenW( headers
);
409 if (!len
) return TRUE
;
410 if (!(buffer
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
411 strcpyW( buffer
, headers
);
419 if (q
[0] == '\n' && q
[1] == '\r')
424 if (q
[0] == '\r' && q
[1] == '\n') break;
431 q
+= 2; /* jump over \r\n */
433 if ((header
= parse_header( p
)))
435 ret
= process_header( request
, header
->field
, header
->value
, flags
, TRUE
);
436 free_header( header
);
445 /***********************************************************************
446 * WinHttpAddRequestHeaders (winhttp.@)
448 BOOL WINAPI
WinHttpAddRequestHeaders( HINTERNET hrequest
, LPCWSTR headers
, DWORD len
, DWORD flags
)
453 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest
, debugstr_w(headers
), len
, flags
);
457 set_last_error( ERROR_INVALID_PARAMETER
);
460 if (!(request
= (request_t
*)grab_object( hrequest
)))
462 set_last_error( ERROR_INVALID_HANDLE
);
465 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
467 release_object( &request
->hdr
);
468 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
472 ret
= add_request_headers( request
, headers
, len
, flags
);
474 release_object( &request
->hdr
);
478 static WCHAR
*build_request_path( request_t
*request
)
482 if (strcmpiW( request
->connect
->hostname
, request
->connect
->servername
))
484 static const WCHAR http
[] = { 'h','t','t','p',0 };
485 static const WCHAR https
[] = { 'h','t','t','p','s',0 };
486 static const WCHAR fmt
[] = { '%','s',':','/','/','%','s',0 };
487 LPCWSTR scheme
= request
->netconn
.secure
? https
: http
;
490 len
= strlenW( scheme
) + strlenW( request
->connect
->hostname
);
491 /* 3 characters for '://', 1 for NUL. */
493 if (request
->connect
->hostport
)
495 /* 1 for ':' between host and port, up to 5 for port */
499 len
+= strlenW( request
->path
);
500 if ((ret
= heap_alloc( len
* sizeof(WCHAR
) )))
502 sprintfW( ret
, fmt
, scheme
, request
->connect
->hostname
);
503 if (request
->connect
->hostport
)
505 static const WCHAR colonFmt
[] = { ':','%','u',0 };
507 sprintfW( ret
+ strlenW( ret
), colonFmt
,
508 request
->connect
->hostport
);
511 strcatW( ret
, request
->path
);
519 static WCHAR
*build_request_string( request_t
*request
)
521 static const WCHAR space
[] = {' ',0};
522 static const WCHAR crlf
[] = {'\r','\n',0};
523 static const WCHAR colon
[] = {':',' ',0};
524 static const WCHAR twocrlf
[] = {'\r','\n','\r','\n',0};
527 const WCHAR
**headers
, **p
;
528 unsigned int len
, i
= 0, j
;
530 /* allocate space for an array of all the string pointers to be added */
531 len
= request
->num_headers
* 4 + 7;
532 if (!(headers
= heap_alloc( len
* sizeof(LPCWSTR
) ))) return NULL
;
534 path
= build_request_path( request
);
535 headers
[i
++] = request
->verb
;
536 headers
[i
++] = space
;
538 headers
[i
++] = space
;
539 headers
[i
++] = request
->version
;
541 for (j
= 0; j
< request
->num_headers
; j
++)
543 if (request
->headers
[j
].is_request
)
546 headers
[i
++] = request
->headers
[j
].field
;
547 headers
[i
++] = colon
;
548 headers
[i
++] = request
->headers
[j
].value
;
550 TRACE("adding header %s (%s)\n", debugstr_w(request
->headers
[j
].field
),
551 debugstr_w(request
->headers
[j
].value
));
554 headers
[i
++] = twocrlf
;
558 for (p
= headers
; *p
; p
++) len
+= strlenW( *p
);
561 if (!(ret
= heap_alloc( len
* sizeof(WCHAR
) )))
564 for (p
= headers
; *p
; p
++) strcatW( ret
, *p
);
567 if (path
!= request
->path
)
569 heap_free( headers
);
573 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
575 static BOOL
query_headers( request_t
*request
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
577 header_t
*header
= NULL
;
578 BOOL request_only
, ret
= FALSE
;
579 int requested_index
, header_index
= -1;
582 request_only
= level
& WINHTTP_QUERY_FLAG_REQUEST_HEADERS
;
583 requested_index
= index
? *index
: 0;
585 attr
= level
& ~QUERY_MODIFIER_MASK
;
588 case WINHTTP_QUERY_CUSTOM
:
590 header_index
= get_header_index( request
, name
, requested_index
, request_only
);
593 case WINHTTP_QUERY_RAW_HEADERS
:
595 WCHAR
*headers
, *p
, *q
;
598 headers
= build_request_string( request
);
600 headers
= request
->raw_headers
;
602 if (!(p
= headers
)) return FALSE
;
603 for (len
= 0; *p
; p
++) if (*p
!= '\r') len
++;
605 if (!buffer
|| (len
+ 1) * sizeof(WCHAR
) > *buflen
)
608 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
612 for (p
= headers
, q
= buffer
; *p
; p
++, q
++)
614 if (*p
!= '\r') *q
= *p
;
622 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
));
625 *buflen
= len
* sizeof(WCHAR
);
626 if (request_only
) heap_free( headers
);
629 case WINHTTP_QUERY_RAW_HEADERS_CRLF
:
634 headers
= build_request_string( request
);
636 headers
= request
->raw_headers
;
638 if (!headers
) return FALSE
;
639 len
= strlenW( headers
) * sizeof(WCHAR
);
640 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
642 len
+= sizeof(WCHAR
);
643 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
647 memcpy( buffer
, headers
, len
+ sizeof(WCHAR
) );
648 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
/ sizeof(WCHAR
)));
652 if (request_only
) heap_free( headers
);
655 case WINHTTP_QUERY_VERSION
:
656 len
= strlenW( request
->version
) * sizeof(WCHAR
);
657 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
659 len
+= sizeof(WCHAR
);
660 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
664 strcpyW( buffer
, request
->version
);
665 TRACE("returning string: %s\n", debugstr_w(buffer
));
671 case WINHTTP_QUERY_STATUS_TEXT
:
672 len
= strlenW( request
->status_text
) * sizeof(WCHAR
);
673 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
675 len
+= sizeof(WCHAR
);
676 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
680 strcpyW( buffer
, request
->status_text
);
681 TRACE("returning string: %s\n", debugstr_w(buffer
));
688 if (attr
>= sizeof(attribute_table
)/sizeof(attribute_table
[0]) || !attribute_table
[attr
])
690 FIXME("attribute %u not implemented\n", attr
);
693 TRACE("attribute %s\n", debugstr_w(attribute_table
[attr
]));
694 header_index
= get_header_index( request
, attribute_table
[attr
], requested_index
, request_only
);
698 if (header_index
>= 0)
700 header
= &request
->headers
[header_index
];
702 if (!header
|| (request_only
&& !header
->is_request
))
704 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND
);
707 if (index
) *index
+= 1;
708 if (level
& WINHTTP_QUERY_FLAG_NUMBER
)
710 if (!buffer
|| sizeof(int) > *buflen
)
712 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
716 int *number
= buffer
;
717 *number
= atoiW( header
->value
);
718 TRACE("returning number: %d\n", *number
);
721 *buflen
= sizeof(int);
723 else if (level
& WINHTTP_QUERY_FLAG_SYSTEMTIME
)
725 SYSTEMTIME
*st
= buffer
;
726 if (!buffer
|| sizeof(SYSTEMTIME
) > *buflen
)
728 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
730 else if ((ret
= WinHttpTimeToSystemTime( header
->value
, st
)))
732 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
733 st
->wYear
, st
->wMonth
, st
->wDay
, st
->wDayOfWeek
,
734 st
->wHour
, st
->wMinute
, st
->wSecond
, st
->wMilliseconds
);
736 *buflen
= sizeof(SYSTEMTIME
);
738 else if (header
->value
)
740 len
= strlenW( header
->value
) * sizeof(WCHAR
);
741 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
743 len
+= sizeof(WCHAR
);
744 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
748 strcpyW( buffer
, header
->value
);
749 TRACE("returning string: %s\n", debugstr_w(buffer
));
757 /***********************************************************************
758 * WinHttpQueryHeaders (winhttp.@)
760 BOOL WINAPI
WinHttpQueryHeaders( HINTERNET hrequest
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
765 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest
, level
, debugstr_w(name
), buffer
, buflen
, index
);
767 if (!(request
= (request_t
*)grab_object( hrequest
)))
769 set_last_error( ERROR_INVALID_HANDLE
);
772 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
774 release_object( &request
->hdr
);
775 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
779 ret
= query_headers( request
, level
, name
, buffer
, buflen
, index
);
781 release_object( &request
->hdr
);
785 static LPWSTR
concatenate_string_list( LPCWSTR
*list
, int len
)
790 for( t
= list
; *t
; t
++ )
791 len
+= strlenW( *t
);
794 str
= heap_alloc( len
* sizeof(WCHAR
) );
795 if (!str
) return NULL
;
798 for( t
= list
; *t
; t
++ )
804 static LPWSTR
build_header_request_string( request_t
*request
, LPCWSTR verb
,
805 LPCWSTR path
, LPCWSTR version
)
807 static const WCHAR crlf
[] = {'\r','\n',0};
808 static const WCHAR space
[] = { ' ',0 };
809 static const WCHAR colon
[] = { ':',' ',0 };
810 static const WCHAR twocrlf
[] = {'\r','\n','\r','\n', 0};
811 LPWSTR requestString
;
817 /* allocate space for an array of all the string pointers to be added */
818 len
= (request
->num_headers
) * 4 + 10;
819 req
= heap_alloc( len
* sizeof(LPCWSTR
) );
820 if (!req
) return NULL
;
822 /* add the verb, path and HTTP version string */
830 /* Append custom request headers */
831 for (i
= 0; i
< request
->num_headers
; i
++)
833 if (request
->headers
[i
].is_request
)
836 req
[n
++] = request
->headers
[i
].field
;
838 req
[n
++] = request
->headers
[i
].value
;
840 TRACE("Adding custom header %s (%s)\n",
841 debugstr_w(request
->headers
[i
].field
),
842 debugstr_w(request
->headers
[i
].value
));
847 ERR("oops. buffer overrun\n");
850 requestString
= concatenate_string_list( req
, 4 );
852 if (!requestString
) return NULL
;
855 * Set (header) termination string for request
856 * Make sure there are exactly two new lines at the end of the request
858 p
= &requestString
[strlenW(requestString
)-1];
859 while ( (*p
== '\n') || (*p
== '\r') )
861 strcpyW( p
+1, twocrlf
);
863 return requestString
;
866 static BOOL
read_reply( request_t
*request
);
868 static BOOL
secure_proxy_connect( request_t
*request
)
870 static const WCHAR verbConnect
[] = {'C','O','N','N','E','C','T',0};
871 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
874 connect_t
*connect
= request
->connect
;
876 path
= heap_alloc( (strlenW( connect
->hostname
) + 13) * sizeof(WCHAR
) );
879 LPWSTR requestString
;
881 sprintfW( path
, fmt
, connect
->hostname
, connect
->hostport
);
882 requestString
= build_header_request_string( request
, verbConnect
,
887 LPSTR req_ascii
= strdupWA( requestString
);
889 heap_free( requestString
);
892 int len
= strlen( req_ascii
), bytes_sent
;
894 ret
= netconn_send( &request
->netconn
, req_ascii
, len
, &bytes_sent
);
895 heap_free( req_ascii
);
897 ret
= read_reply( request
);
904 #ifndef INET6_ADDRSTRLEN
905 #define INET6_ADDRSTRLEN 46
908 static WCHAR
*addr_to_str( const struct sockaddr
*addr
)
910 char buf
[INET6_ADDRSTRLEN
];
913 switch (addr
->sa_family
)
916 src
= &((struct sockaddr_in
*)addr
)->sin_addr
;
919 src
= &((struct sockaddr_in6
*)addr
)->sin6_addr
;
922 WARN("unsupported address family %d\n", addr
->sa_family
);
925 if (!inet_ntop( addr
->sa_family
, src
, buf
, sizeof(buf
) )) return NULL
;
926 return strdupAW( buf
);
929 static BOOL
open_connection( request_t
*request
)
932 WCHAR
*addressW
= NULL
;
935 struct sockaddr
*saddr
;
938 if (netconn_connected( &request
->netconn
)) goto done
;
940 connect
= request
->connect
;
941 port
= connect
->serverport
? connect
->serverport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
942 saddr
= (struct sockaddr
*)&connect
->sockaddr
;
943 slen
= sizeof(struct sockaddr
);
945 if (!connect
->resolved
)
947 len
= strlenW( connect
->servername
) + 1;
948 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME
, connect
->servername
, len
);
950 if (!netconn_resolve( connect
->servername
, port
, saddr
, &slen
, request
->resolve_timeout
)) return FALSE
;
951 connect
->resolved
= TRUE
;
953 if (!(addressW
= addr_to_str( saddr
))) return FALSE
;
954 len
= strlenW( addressW
) + 1;
955 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED
, addressW
, len
);
957 if (!addressW
&& !(addressW
= addr_to_str( saddr
))) return FALSE
;
958 TRACE("connecting to %s:%u\n", debugstr_w(addressW
), port
);
960 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER
, addressW
, 0 );
962 if (!netconn_create( &request
->netconn
, saddr
->sa_family
, SOCK_STREAM
, 0 ))
964 heap_free( addressW
);
967 netconn_set_timeout( &request
->netconn
, TRUE
, request
->send_timeout
);
968 netconn_set_timeout( &request
->netconn
, FALSE
, request
->recv_timeout
);
969 if (!netconn_connect( &request
->netconn
, saddr
, slen
, request
->connect_timeout
))
971 netconn_close( &request
->netconn
);
972 heap_free( addressW
);
975 if (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
977 if (connect
->session
->proxy_server
&&
978 strcmpiW( connect
->hostname
, connect
->servername
))
980 if (!secure_proxy_connect( request
))
982 heap_free( addressW
);
986 if (!netconn_secure_connect( &request
->netconn
, connect
->servername
))
988 netconn_close( &request
->netconn
);
989 heap_free( addressW
);
994 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER
, addressW
, strlenW(addressW
) + 1 );
997 request
->read_pos
= request
->read_size
= 0;
998 request
->read_chunked
= FALSE
;
999 request
->read_chunked_size
= ~0u;
1000 request
->read_chunked_eof
= FALSE
;
1001 heap_free( addressW
);
1005 void close_connection( request_t
*request
)
1007 if (!netconn_connected( &request
->netconn
)) return;
1009 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION
, 0, 0 );
1010 netconn_close( &request
->netconn
);
1011 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED
, 0, 0 );
1014 static BOOL
add_host_header( request_t
*request
, DWORD modifier
)
1019 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
1020 connect_t
*connect
= request
->connect
;
1023 port
= connect
->hostport
? connect
->hostport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
1025 if (port
== INTERNET_DEFAULT_HTTP_PORT
|| port
== INTERNET_DEFAULT_HTTPS_PORT
)
1027 return process_header( request
, attr_host
, connect
->hostname
, modifier
, TRUE
);
1029 len
= strlenW( connect
->hostname
) + 7; /* sizeof(":65335") */
1030 if (!(host
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
1031 sprintfW( host
, fmt
, connect
->hostname
, port
);
1032 ret
= process_header( request
, attr_host
, host
, modifier
, TRUE
);
1037 static void clear_response_headers( request_t
*request
)
1041 for (i
= 0; i
< request
->num_headers
; i
++)
1043 if (!request
->headers
[i
].field
) continue;
1044 if (!request
->headers
[i
].value
) continue;
1045 if (request
->headers
[i
].is_request
) continue;
1046 delete_header( request
, i
);
1051 static BOOL
send_request( request_t
*request
, LPCWSTR headers
, DWORD headers_len
, LPVOID optional
,
1052 DWORD optional_len
, DWORD total_len
, DWORD_PTR context
, BOOL async
)
1054 static const WCHAR keep_alive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
1055 static const WCHAR no_cache
[] = {'n','o','-','c','a','c','h','e',0};
1056 static const WCHAR length_fmt
[] = {'%','l','d',0};
1059 connect_t
*connect
= request
->connect
;
1060 session_t
*session
= connect
->session
;
1064 DWORD len
, i
, flags
;
1066 clear_response_headers( request
);
1068 flags
= WINHTTP_ADDREQ_FLAG_ADD
|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
;
1069 for (i
= 0; i
< request
->num_accept_types
; i
++)
1071 process_header( request
, attr_accept
, request
->accept_types
[i
], flags
, TRUE
);
1074 process_header( request
, attr_user_agent
, session
->agent
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1076 if (connect
->hostname
)
1077 add_host_header( request
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
1079 if (total_len
|| (request
->verb
&& !strcmpW( request
->verb
, postW
)))
1081 WCHAR length
[21]; /* decimal long int + null */
1082 sprintfW( length
, length_fmt
, total_len
);
1083 process_header( request
, attr_content_length
, length
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1085 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
))
1087 process_header( request
, attr_connection
, keep_alive
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1089 if (request
->hdr
.flags
& WINHTTP_FLAG_REFRESH
)
1091 process_header( request
, attr_pragma
, no_cache
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1092 process_header( request
, attr_cache_control
, no_cache
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1094 if (headers
&& !add_request_headers( request
, headers
, headers_len
, WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
))
1096 TRACE("failed to add request headers\n");
1099 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
) && !add_cookie_headers( request
))
1101 WARN("failed to add cookie headers\n");
1105 if (context
) request
->hdr
.context
= context
;
1107 if (!(ret
= open_connection( request
))) goto end
;
1108 if (!(req
= build_request_string( request
))) goto end
;
1110 if (!(req_ascii
= strdupWA( req
))) goto end
;
1111 TRACE("full request: %s\n", debugstr_a(req_ascii
));
1112 len
= strlen(req_ascii
);
1114 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST
, NULL
, 0 );
1116 ret
= netconn_send( &request
->netconn
, req_ascii
, len
, &bytes_sent
);
1117 heap_free( req_ascii
);
1122 if (!netconn_send( &request
->netconn
, optional
, optional_len
, &bytes_sent
)) goto end
;
1123 request
->optional
= optional
;
1124 request
->optional_len
= optional_len
;
1125 len
+= optional_len
;
1127 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
, &len
, sizeof(len
) );
1132 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
, NULL
, 0 );
1135 WINHTTP_ASYNC_RESULT result
;
1136 result
.dwResult
= API_SEND_REQUEST
;
1137 result
.dwError
= get_last_error();
1138 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
1145 static void task_send_request( task_header_t
*task
)
1147 send_request_t
*s
= (send_request_t
*)task
;
1148 send_request( s
->hdr
.request
, s
->headers
, s
->headers_len
, s
->optional
, s
->optional_len
, s
->total_len
, s
->context
, TRUE
);
1149 heap_free( s
->headers
);
1152 /***********************************************************************
1153 * WinHttpSendRequest (winhttp.@)
1155 BOOL WINAPI
WinHttpSendRequest( HINTERNET hrequest
, LPCWSTR headers
, DWORD headers_len
,
1156 LPVOID optional
, DWORD optional_len
, DWORD total_len
, DWORD_PTR context
)
1161 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1162 hrequest
, debugstr_w(headers
), headers_len
, optional_len
, total_len
, context
);
1164 if (!(request
= (request_t
*)grab_object( hrequest
)))
1166 set_last_error( ERROR_INVALID_HANDLE
);
1169 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1171 release_object( &request
->hdr
);
1172 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1176 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
1180 if (!(s
= heap_alloc( sizeof(send_request_t
) ))) return FALSE
;
1181 s
->hdr
.request
= request
;
1182 s
->hdr
.proc
= task_send_request
;
1183 s
->headers
= strdupW( headers
);
1184 s
->headers_len
= headers_len
;
1185 s
->optional
= optional
;
1186 s
->optional_len
= optional_len
;
1187 s
->total_len
= total_len
;
1188 s
->context
= context
;
1190 addref_object( &request
->hdr
);
1191 ret
= queue_task( (task_header_t
*)s
);
1194 ret
= send_request( request
, headers
, headers_len
, optional
, optional_len
, total_len
, context
, FALSE
);
1196 release_object( &request
->hdr
);
1201 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1203 static const WCHAR basicW
[] = {'B','a','s','i','c',0};
1204 static const WCHAR ntlmW
[] = {'N','T','L','M',0};
1205 static const WCHAR passportW
[] = {'P','a','s','s','p','o','r','t',0};
1206 static const WCHAR digestW
[] = {'D','i','g','e','s','t',0};
1207 static const WCHAR negotiateW
[] = {'N','e','g','o','t','i','a','t','e',0};
1217 { basicW
, ARRAYSIZE(basicW
) - 1, WINHTTP_AUTH_SCHEME_BASIC
},
1218 { ntlmW
, ARRAYSIZE(ntlmW
) - 1, WINHTTP_AUTH_SCHEME_NTLM
},
1219 { passportW
, ARRAYSIZE(passportW
) - 1, WINHTTP_AUTH_SCHEME_PASSPORT
},
1220 { digestW
, ARRAYSIZE(digestW
) - 1, WINHTTP_AUTH_SCHEME_DIGEST
},
1221 { negotiateW
, ARRAYSIZE(negotiateW
) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE
}
1223 static const unsigned int num_auth_schemes
= sizeof(auth_schemes
)/sizeof(auth_schemes
[0]);
1225 static enum auth_scheme
scheme_from_flag( DWORD flag
)
1229 for (i
= 0; i
< num_auth_schemes
; i
++) if (flag
== auth_schemes
[i
].scheme
) return i
;
1230 return SCHEME_INVALID
;
1233 static DWORD
auth_scheme_from_header( WCHAR
*header
)
1237 for (i
= 0; i
< num_auth_schemes
; i
++)
1239 if (!strncmpiW( header
, auth_schemes
[i
].str
, auth_schemes
[i
].len
) &&
1240 (header
[auth_schemes
[i
].len
] == ' ' || !header
[auth_schemes
[i
].len
])) return auth_schemes
[i
].scheme
;
1245 static BOOL
query_auth_schemes( request_t
*request
, DWORD level
, LPDWORD supported
, LPDWORD first
)
1256 query_headers( request
, level
, NULL
, NULL
, &size
, &index
);
1257 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER
) break;
1260 if (!(buffer
= heap_alloc( size
))) return FALSE
;
1261 if (!query_headers( request
, level
, NULL
, buffer
, &size
, &index
))
1263 heap_free( buffer
);
1266 scheme
= auth_scheme_from_header( buffer
);
1267 heap_free( buffer
);
1270 if (first
&& index
== 1)
1271 *first
= *supported
= scheme
;
1273 *supported
|= scheme
;
1280 /***********************************************************************
1281 * WinHttpQueryAuthSchemes (winhttp.@)
1283 BOOL WINAPI
WinHttpQueryAuthSchemes( HINTERNET hrequest
, LPDWORD supported
, LPDWORD first
, LPDWORD target
)
1288 TRACE("%p, %p, %p, %p\n", hrequest
, supported
, first
, target
);
1290 if (!(request
= (request_t
*)grab_object( hrequest
)))
1292 set_last_error( ERROR_INVALID_HANDLE
);
1295 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1297 release_object( &request
->hdr
);
1298 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1301 if (!supported
|| !first
|| !target
)
1303 release_object( &request
->hdr
);
1304 set_last_error( ERROR_INVALID_PARAMETER
);
1309 if (query_auth_schemes( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, supported
, first
))
1311 *target
= WINHTTP_AUTH_TARGET_SERVER
;
1314 else if (query_auth_schemes( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, supported
, first
))
1316 *target
= WINHTTP_AUTH_TARGET_PROXY
;
1320 release_object( &request
->hdr
);
1324 static UINT
encode_base64( const char *bin
, unsigned int len
, WCHAR
*base64
)
1327 static const char base64enc
[] =
1328 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1332 /* first 6 bits, all from bin[0] */
1333 base64
[n
++] = base64enc
[(bin
[0] & 0xfc) >> 2];
1334 x
= (bin
[0] & 3) << 4;
1336 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1339 base64
[n
++] = base64enc
[x
];
1344 base64
[n
++] = base64enc
[x
| ((bin
[1] & 0xf0) >> 4)];
1345 x
= (bin
[1] & 0x0f) << 2;
1347 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1350 base64
[n
++] = base64enc
[x
];
1354 base64
[n
++] = base64enc
[x
| ((bin
[2] & 0xc0) >> 6)];
1356 /* last 6 bits, all from bin [2] */
1357 base64
[n
++] = base64enc
[bin
[2] & 0x3f];
1365 static inline char decode_char( WCHAR c
)
1367 if (c
>= 'A' && c
<= 'Z') return c
- 'A';
1368 if (c
>= 'a' && c
<= 'z') return c
- 'a' + 26;
1369 if (c
>= '0' && c
<= '9') return c
- '0' + 52;
1370 if (c
== '+') return 62;
1371 if (c
== '/') return 63;
1375 static unsigned int decode_base64( const WCHAR
*base64
, unsigned int len
, char *buf
)
1378 char c0
, c1
, c2
, c3
;
1379 const WCHAR
*p
= base64
;
1383 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1384 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1385 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1386 if ((c3
= decode_char( p
[3] )) > 63) return 0;
1390 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1391 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1392 buf
[i
+ 2] = (c2
<< 6) | c3
;
1400 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1401 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1403 if (buf
) buf
[i
] = (c0
<< 2) | (c1
>> 4);
1406 else if (p
[3] == '=')
1408 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1409 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1410 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1414 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1415 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1421 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1422 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1423 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1424 if ((c3
= decode_char( p
[3] )) > 63) return 0;
1428 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1429 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1430 buf
[i
+ 2] = (c2
<< 6) | c3
;
1437 static struct authinfo
*alloc_authinfo(void)
1439 struct authinfo
*ret
;
1441 if (!(ret
= heap_alloc( sizeof(*ret
) ))) return NULL
;
1443 SecInvalidateHandle( &ret
->cred
);
1444 SecInvalidateHandle( &ret
->ctx
);
1445 memset( &ret
->exp
, 0, sizeof(ret
->exp
) );
1451 ret
->finished
= FALSE
;
1455 void destroy_authinfo( struct authinfo
*authinfo
)
1457 if (!authinfo
) return;
1459 if (SecIsValidHandle( &authinfo
->ctx
))
1460 DeleteSecurityContext( &authinfo
->ctx
);
1461 if (SecIsValidHandle( &authinfo
->cred
))
1462 FreeCredentialsHandle( &authinfo
->cred
);
1464 heap_free( authinfo
->data
);
1465 heap_free( authinfo
);
1468 static BOOL
get_authvalue( request_t
*request
, DWORD level
, DWORD scheme
, WCHAR
*buffer
, DWORD len
)
1470 DWORD size
, index
= 0;
1474 if (!query_headers( request
, level
, NULL
, buffer
, &size
, &index
)) return FALSE
;
1475 if (auth_scheme_from_header( buffer
) == scheme
) break;
1480 static BOOL
do_authorization( request_t
*request
, DWORD target
, DWORD scheme_flag
)
1482 struct authinfo
*authinfo
, **auth_ptr
;
1483 enum auth_scheme scheme
= scheme_from_flag( scheme_flag
);
1484 const WCHAR
*auth_target
, *username
, *password
;
1485 WCHAR auth_value
[2048], *auth_reply
;
1486 DWORD len
= sizeof(auth_value
), len_scheme
, flags
;
1489 if (scheme
== SCHEME_INVALID
) return FALSE
;
1493 case WINHTTP_AUTH_TARGET_SERVER
:
1494 if (!get_authvalue( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1496 auth_ptr
= &request
->authinfo
;
1497 auth_target
= attr_authorization
;
1498 username
= request
->connect
->username
;
1499 password
= request
->connect
->password
;
1502 case WINHTTP_AUTH_TARGET_PROXY
:
1503 if (!get_authvalue( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1505 auth_ptr
= &request
->proxy_authinfo
;
1506 auth_target
= attr_proxy_authorization
;
1507 username
= request
->connect
->session
->proxy_username
;
1508 password
= request
->connect
->session
->proxy_password
;
1512 WARN("unknown target %x\n", target
);
1515 authinfo
= *auth_ptr
;
1521 int userlen
, passlen
;
1523 if (!username
|| !password
) return FALSE
;
1524 if ((!authinfo
&& !(authinfo
= alloc_authinfo())) || authinfo
->finished
) return FALSE
;
1526 userlen
= WideCharToMultiByte( CP_UTF8
, 0, username
, strlenW( username
), NULL
, 0, NULL
, NULL
);
1527 passlen
= WideCharToMultiByte( CP_UTF8
, 0, password
, strlenW( password
), NULL
, 0, NULL
, NULL
);
1529 authinfo
->data_len
= userlen
+ 1 + passlen
;
1530 if (!(authinfo
->data
= heap_alloc( authinfo
->data_len
))) return FALSE
;
1532 WideCharToMultiByte( CP_UTF8
, 0, username
, -1, authinfo
->data
, userlen
, NULL
, NULL
);
1533 authinfo
->data
[userlen
] = ':';
1534 WideCharToMultiByte( CP_UTF8
, 0, password
, -1, authinfo
->data
+ userlen
+ 1, passlen
, NULL
, NULL
);
1536 authinfo
->scheme
= SCHEME_BASIC
;
1537 authinfo
->finished
= TRUE
;
1541 case SCHEME_NEGOTIATE
:
1543 SECURITY_STATUS status
;
1544 SecBufferDesc out_desc
, in_desc
;
1546 ULONG flags
= ISC_REQ_CONNECTION
|ISC_REQ_USE_DCE_STYLE
|ISC_REQ_MUTUAL_AUTH
|ISC_REQ_DELEGATE
;
1553 SEC_WINNT_AUTH_IDENTITY_W id
;
1554 WCHAR
*domain
, *user
;
1556 if (!username
|| !password
|| !(authinfo
= alloc_authinfo())) return FALSE
;
1559 domain
= (WCHAR
*)username
;
1560 user
= strchrW( username
, '\\' );
1565 user
= (WCHAR
*)username
;
1568 id
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1570 id
.UserLength
= strlenW( user
);
1572 id
.DomainLength
= domain
? user
- domain
- 1 : 0;
1573 id
.Password
= (WCHAR
*)password
;
1574 id
.PasswordLength
= strlenW( password
);
1576 status
= AcquireCredentialsHandleW( NULL
, (SEC_WCHAR
*)auth_schemes
[scheme
].str
,
1577 SECPKG_CRED_OUTBOUND
, NULL
, &id
, NULL
, NULL
,
1578 &authinfo
->cred
, &exp
);
1579 if (status
== SEC_E_OK
)
1582 status
= QuerySecurityPackageInfoW( (SEC_WCHAR
*)auth_schemes
[scheme
].str
, &info
);
1583 if (status
== SEC_E_OK
)
1585 authinfo
->max_token
= info
->cbMaxToken
;
1586 FreeContextBuffer( info
);
1589 if (status
!= SEC_E_OK
)
1591 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1592 debugstr_w(auth_schemes
[scheme
].str
), status
);
1593 heap_free( authinfo
);
1596 authinfo
->scheme
= scheme
;
1598 else if (authinfo
->finished
) return FALSE
;
1600 if ((strlenW( auth_value
) < auth_schemes
[authinfo
->scheme
].len
||
1601 strncmpiW( auth_value
, auth_schemes
[authinfo
->scheme
].str
, auth_schemes
[authinfo
->scheme
].len
)))
1603 ERR("authentication scheme changed from %s to %s\n",
1604 debugstr_w(auth_schemes
[authinfo
->scheme
].str
), debugstr_w(auth_value
));
1605 destroy_authinfo( authinfo
);
1609 in
.BufferType
= SECBUFFER_TOKEN
;
1613 in_desc
.ulVersion
= 0;
1614 in_desc
.cBuffers
= 1;
1615 in_desc
.pBuffers
= &in
;
1617 p
= auth_value
+ auth_schemes
[scheme
].len
;
1620 int len
= strlenW( ++p
);
1621 in
.cbBuffer
= decode_base64( p
, len
, NULL
);
1622 if (!(in
.pvBuffer
= heap_alloc( in
.cbBuffer
))) {
1623 destroy_authinfo( authinfo
);
1627 decode_base64( p
, len
, in
.pvBuffer
);
1629 out
.BufferType
= SECBUFFER_TOKEN
;
1630 out
.cbBuffer
= authinfo
->max_token
;
1631 if (!(out
.pvBuffer
= heap_alloc( authinfo
->max_token
)))
1633 heap_free( in
.pvBuffer
);
1634 destroy_authinfo( authinfo
);
1638 out_desc
.ulVersion
= 0;
1639 out_desc
.cBuffers
= 1;
1640 out_desc
.pBuffers
= &out
;
1642 status
= InitializeSecurityContextW( first
? &authinfo
->cred
: NULL
, first
? NULL
: &authinfo
->ctx
,
1643 first
? request
->connect
->servername
: NULL
, flags
, 0,
1644 SECURITY_NETWORK_DREP
, in
.pvBuffer
? &in_desc
: NULL
, 0,
1645 &authinfo
->ctx
, &out_desc
, &authinfo
->attr
, &authinfo
->exp
);
1646 heap_free( in
.pvBuffer
);
1647 if (status
== SEC_E_OK
)
1649 heap_free( authinfo
->data
);
1650 authinfo
->data
= out
.pvBuffer
;
1651 authinfo
->data_len
= out
.cbBuffer
;
1652 authinfo
->finished
= TRUE
;
1653 TRACE("sending last auth packet\n");
1655 else if (status
== SEC_I_CONTINUE_NEEDED
)
1657 heap_free( authinfo
->data
);
1658 authinfo
->data
= out
.pvBuffer
;
1659 authinfo
->data_len
= out
.cbBuffer
;
1660 TRACE("sending next auth packet\n");
1664 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status
);
1665 heap_free( out
.pvBuffer
);
1666 destroy_authinfo( authinfo
);
1673 ERR("invalid scheme %u\n", scheme
);
1676 *auth_ptr
= authinfo
;
1678 len_scheme
= auth_schemes
[authinfo
->scheme
].len
;
1679 len
= len_scheme
+ 1 + ((authinfo
->data_len
+ 2) * 4) / 3;
1680 if (!(auth_reply
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
1682 memcpy( auth_reply
, auth_schemes
[authinfo
->scheme
].str
, len_scheme
* sizeof(WCHAR
) );
1683 auth_reply
[len_scheme
] = ' ';
1684 encode_base64( authinfo
->data
, authinfo
->data_len
, auth_reply
+ len_scheme
+ 1 );
1686 flags
= WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
;
1687 ret
= process_header( request
, auth_target
, auth_reply
, flags
, TRUE
);
1688 heap_free( auth_reply
);
1692 static BOOL
set_credentials( request_t
*request
, DWORD target
, DWORD scheme
, const WCHAR
*username
,
1693 const WCHAR
*password
)
1695 if ((scheme
== WINHTTP_AUTH_SCHEME_BASIC
|| scheme
== WINHTTP_AUTH_SCHEME_DIGEST
) &&
1696 (!username
|| !password
))
1698 set_last_error( ERROR_INVALID_PARAMETER
);
1703 case WINHTTP_AUTH_TARGET_SERVER
:
1705 heap_free( request
->connect
->username
);
1706 if (!username
) request
->connect
->username
= NULL
;
1707 else if (!(request
->connect
->username
= strdupW( username
))) return FALSE
;
1709 heap_free( request
->connect
->password
);
1710 if (!password
) request
->connect
->password
= NULL
;
1711 else if (!(request
->connect
->password
= strdupW( password
))) return FALSE
;
1714 case WINHTTP_AUTH_TARGET_PROXY
:
1716 heap_free( request
->connect
->session
->proxy_username
);
1717 if (!username
) request
->connect
->session
->proxy_username
= NULL
;
1718 else if (!(request
->connect
->session
->proxy_username
= strdupW( username
))) return FALSE
;
1720 heap_free( request
->connect
->session
->proxy_password
);
1721 if (!password
) request
->connect
->session
->proxy_password
= NULL
;
1722 else if (!(request
->connect
->session
->proxy_password
= strdupW( password
))) return FALSE
;
1726 WARN("unknown target %u\n", target
);
1732 /***********************************************************************
1733 * WinHttpSetCredentials (winhttp.@)
1735 BOOL WINAPI
WinHttpSetCredentials( HINTERNET hrequest
, DWORD target
, DWORD scheme
, LPCWSTR username
,
1736 LPCWSTR password
, LPVOID params
)
1741 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest
, target
, scheme
, debugstr_w(username
), password
, params
);
1743 if (!(request
= (request_t
*)grab_object( hrequest
)))
1745 set_last_error( ERROR_INVALID_HANDLE
);
1748 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1750 release_object( &request
->hdr
);
1751 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1755 ret
= set_credentials( request
, target
, scheme
, username
, password
);
1757 release_object( &request
->hdr
);
1761 static BOOL
handle_authorization( request_t
*request
, DWORD status
)
1763 DWORD i
, schemes
, first
, level
, target
;
1767 case HTTP_STATUS_DENIED
:
1768 target
= WINHTTP_AUTH_TARGET_SERVER
;
1769 level
= WINHTTP_QUERY_WWW_AUTHENTICATE
;
1772 case HTTP_STATUS_PROXY_AUTH_REQ
:
1773 target
= WINHTTP_AUTH_TARGET_PROXY
;
1774 level
= WINHTTP_QUERY_PROXY_AUTHENTICATE
;
1778 WARN("unhandled status %u\n", status
);
1782 if (!query_auth_schemes( request
, level
, &schemes
, &first
)) return FALSE
;
1783 if (do_authorization( request
, target
, first
)) return TRUE
;
1786 for (i
= 0; i
< num_auth_schemes
; i
++)
1788 if (!(schemes
& auth_schemes
[i
].scheme
)) continue;
1789 if (do_authorization( request
, target
, auth_schemes
[i
].scheme
)) return TRUE
;
1794 /* set the request content length based on the headers */
1795 static DWORD
set_content_length( request_t
*request
)
1800 buflen
= sizeof(request
->content_length
);
1801 if (!query_headers( request
, WINHTTP_QUERY_CONTENT_LENGTH
|WINHTTP_QUERY_FLAG_NUMBER
,
1802 NULL
, &request
->content_length
, &buflen
, NULL
))
1803 request
->content_length
= ~0u;
1805 buflen
= sizeof(encoding
);
1806 if (query_headers( request
, WINHTTP_QUERY_TRANSFER_ENCODING
, NULL
, encoding
, &buflen
, NULL
) &&
1807 !strcmpiW( encoding
, chunkedW
))
1809 request
->content_length
= ~0u;
1810 request
->read_chunked
= TRUE
;
1811 request
->read_chunked_size
= ~0u;
1812 request
->read_chunked_eof
= FALSE
;
1814 request
->content_read
= 0;
1815 return request
->content_length
;
1818 /* read some more data into the read buffer */
1819 static BOOL
read_more_data( request_t
*request
, int maxlen
, BOOL notify
)
1824 if (request
->read_chunked_eof
) return FALSE
;
1826 if (request
->read_size
&& request
->read_pos
)
1828 /* move existing data to the start of the buffer */
1829 memmove( request
->read_buf
, request
->read_buf
+ request
->read_pos
, request
->read_size
);
1830 request
->read_pos
= 0;
1832 if (maxlen
== -1) maxlen
= sizeof(request
->read_buf
);
1834 if (notify
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE
, NULL
, 0 );
1836 ret
= netconn_recv( &request
->netconn
, request
->read_buf
+ request
->read_size
,
1837 maxlen
- request
->read_size
, 0, &len
);
1839 if (notify
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED
, &len
, sizeof(len
) );
1841 request
->read_size
+= len
;
1845 /* remove some amount of data from the read buffer */
1846 static void remove_data( request_t
*request
, int count
)
1848 if (!(request
->read_size
-= count
)) request
->read_pos
= 0;
1849 else request
->read_pos
+= count
;
1852 static BOOL
read_line( request_t
*request
, char *buffer
, DWORD
*len
)
1854 int count
, bytes_read
, pos
= 0;
1858 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1861 count
= eol
- (request
->read_buf
+ request
->read_pos
);
1862 bytes_read
= count
+ 1;
1864 else count
= bytes_read
= request
->read_size
;
1866 count
= min( count
, *len
- pos
);
1867 memcpy( buffer
+ pos
, request
->read_buf
+ request
->read_pos
, count
);
1869 remove_data( request
, bytes_read
);
1872 if (!read_more_data( request
, -1, TRUE
)) return FALSE
;
1873 if (!request
->read_size
)
1876 TRACE("returning empty string\n");
1882 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
1885 buffer
[*len
- 1] = 0;
1886 TRACE("returning %s\n", debugstr_a(buffer
));
1890 /* discard data contents until we reach end of line */
1891 static BOOL
discard_eol( request_t
*request
, BOOL notify
)
1895 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1898 remove_data( request
, (eol
+ 1) - (request
->read_buf
+ request
->read_pos
) );
1901 request
->read_pos
= request
->read_size
= 0; /* discard everything */
1902 if (!read_more_data( request
, -1, notify
)) return FALSE
;
1903 } while (request
->read_size
);
1907 /* read the size of the next chunk */
1908 static BOOL
start_next_chunk( request_t
*request
, BOOL notify
)
1910 DWORD chunk_size
= 0;
1912 assert(!request
->read_chunked_size
|| request
->read_chunked_size
== ~0u);
1914 if (request
->read_chunked_eof
) return FALSE
;
1916 /* read terminator for the previous chunk */
1917 if (!request
->read_chunked_size
&& !discard_eol( request
, notify
)) return FALSE
;
1921 while (request
->read_size
)
1923 char ch
= request
->read_buf
[request
->read_pos
];
1924 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
1925 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
1926 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
1927 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
1929 TRACE("reading %u byte chunk\n", chunk_size
);
1931 if (request
->content_length
== ~0u) request
->content_length
= chunk_size
;
1932 else request
->content_length
+= chunk_size
;
1934 request
->read_chunked_size
= chunk_size
;
1935 if (!chunk_size
) request
->read_chunked_eof
= TRUE
;
1937 return discard_eol( request
, notify
);
1939 remove_data( request
, 1 );
1941 if (!read_more_data( request
, -1, notify
)) return FALSE
;
1942 if (!request
->read_size
)
1944 request
->content_length
= request
->content_read
= 0;
1945 request
->read_chunked_size
= 0;
1951 /* return the size of data available to be read immediately */
1952 static DWORD
get_available_data( request_t
*request
)
1954 if (request
->read_chunked
) return min( request
->read_chunked_size
, request
->read_size
);
1955 return request
->read_size
;
1958 /* check if we have reached the end of the data to read */
1959 static BOOL
end_of_read_data( request_t
*request
)
1961 if (request
->read_chunked
) return request
->read_chunked_eof
;
1962 if (request
->content_length
== ~0u) return FALSE
;
1963 return (request
->content_length
== request
->content_read
);
1966 static BOOL
refill_buffer( request_t
*request
, BOOL notify
)
1968 int len
= sizeof(request
->read_buf
);
1970 if (request
->read_chunked
)
1972 if (request
->read_chunked_eof
) return FALSE
;
1973 if (request
->read_chunked_size
== ~0u || !request
->read_chunked_size
)
1975 if (!start_next_chunk( request
, notify
)) return FALSE
;
1978 if (!request
->read_chunked
&& request
->content_length
!= ~0u)
1979 len
= min( len
, request
->content_length
- request
->content_read
);
1980 if (len
<= request
->read_size
) return TRUE
;
1981 if (!read_more_data( request
, len
, notify
)) return FALSE
;
1982 if (!request
->read_size
) request
->content_length
= request
->content_read
= 0;
1986 #define MAX_REPLY_LEN 1460
1987 #define INITIAL_HEADER_BUFFER_LEN 512
1989 static BOOL
read_reply( request_t
*request
)
1991 static const WCHAR crlf
[] = {'\r','\n',0};
1993 char buffer
[MAX_REPLY_LEN
];
1994 DWORD buflen
, len
, offset
, received_len
, crlf_len
= 2; /* strlenW(crlf) */
1995 char *status_code
, *status_text
;
1996 WCHAR
*versionW
, *status_textW
, *raw_headers
;
1997 WCHAR status_codeW
[4]; /* sizeof("nnn") */
1999 if (!netconn_connected( &request
->netconn
)) return FALSE
;
2004 buflen
= MAX_REPLY_LEN
;
2005 if (!read_line( request
, buffer
, &buflen
)) return FALSE
;
2006 received_len
+= buflen
;
2008 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2009 if (!(status_code
= strchr( buffer
, ' ' ))) return FALSE
;
2011 if (!(status_text
= strchr( status_code
, ' ' ))) return FALSE
;
2012 if ((len
= status_text
- status_code
) != sizeof("nnn") - 1) return FALSE
;
2015 TRACE("version [%s] status code [%s] status text [%s]\n",
2016 debugstr_an(buffer
, status_code
- buffer
- 1),
2017 debugstr_an(status_code
, len
),
2018 debugstr_a(status_text
));
2020 } while (!memcmp( status_code
, "100", len
)); /* ignore "100 Continue" responses */
2022 /* we rely on the fact that the protocol is ascii */
2023 MultiByteToWideChar( CP_ACP
, 0, status_code
, len
, status_codeW
, len
);
2024 status_codeW
[len
] = 0;
2025 if (!(process_header( request
, attr_status
, status_codeW
, WINHTTP_ADDREQ_FLAG_REPLACE
, FALSE
))) return FALSE
;
2027 len
= status_code
- buffer
;
2028 if (!(versionW
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2029 MultiByteToWideChar( CP_ACP
, 0, buffer
, len
- 1, versionW
, len
-1 );
2030 versionW
[len
- 1] = 0;
2032 heap_free( request
->version
);
2033 request
->version
= versionW
;
2035 len
= buflen
- (status_text
- buffer
);
2036 if (!(status_textW
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2037 MultiByteToWideChar( CP_ACP
, 0, status_text
, len
, status_textW
, len
);
2039 heap_free( request
->status_text
);
2040 request
->status_text
= status_textW
;
2042 len
= max( buflen
+ crlf_len
, INITIAL_HEADER_BUFFER_LEN
);
2043 if (!(raw_headers
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2044 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
, buflen
);
2045 memcpy( raw_headers
+ buflen
- 1, crlf
, sizeof(crlf
) );
2047 heap_free( request
->raw_headers
);
2048 request
->raw_headers
= raw_headers
;
2050 offset
= buflen
+ crlf_len
- 1;
2055 buflen
= MAX_REPLY_LEN
;
2056 if (!read_line( request
, buffer
, &buflen
)) return TRUE
;
2057 received_len
+= buflen
;
2058 if (!*buffer
) break;
2060 while (len
- offset
< buflen
+ crlf_len
)
2064 if (!(tmp
= heap_realloc( raw_headers
, len
* sizeof(WCHAR
) ))) return FALSE
;
2065 request
->raw_headers
= raw_headers
= tmp
;
2067 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
+ offset
, buflen
);
2069 if (!(header
= parse_header( raw_headers
+ offset
))) break;
2070 if (!(process_header( request
, header
->field
, header
->value
, WINHTTP_ADDREQ_FLAG_ADD
, FALSE
)))
2072 free_header( header
);
2075 free_header( header
);
2076 memcpy( raw_headers
+ offset
+ buflen
- 1, crlf
, sizeof(crlf
) );
2077 offset
+= buflen
+ crlf_len
- 1;
2080 TRACE("raw headers: %s\n", debugstr_w(raw_headers
));
2084 static void finished_reading( request_t
*request
)
2086 static const WCHAR closeW
[] = {'c','l','o','s','e',0};
2089 WCHAR connection
[20];
2090 DWORD size
= sizeof(connection
);
2092 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
) close
= TRUE
;
2093 else if (query_headers( request
, WINHTTP_QUERY_CONNECTION
, NULL
, connection
, &size
, NULL
) ||
2094 query_headers( request
, WINHTTP_QUERY_PROXY_CONNECTION
, NULL
, connection
, &size
, NULL
))
2096 if (!strcmpiW( connection
, closeW
)) close
= TRUE
;
2098 else if (!strcmpW( request
->version
, http1_0
)) close
= TRUE
;
2099 if (close
) close_connection( request
);
2102 static BOOL
read_data( request_t
*request
, void *buffer
, DWORD size
, DWORD
*read
, BOOL async
)
2104 int count
, bytes_read
= 0;
2106 if (end_of_read_data( request
)) goto done
;
2110 if (!(count
= get_available_data( request
)))
2112 if (!refill_buffer( request
, async
)) goto done
;
2113 if (!(count
= get_available_data( request
))) goto done
;
2115 count
= min( count
, size
);
2116 memcpy( (char *)buffer
+ bytes_read
, request
->read_buf
+ request
->read_pos
, count
);
2117 remove_data( request
, count
);
2118 if (request
->read_chunked
) request
->read_chunked_size
-= count
;
2120 bytes_read
+= count
;
2121 request
->content_read
+= count
;
2122 if (end_of_read_data( request
)) goto done
;
2124 if (request
->read_chunked
&& !request
->read_chunked_size
) refill_buffer( request
, async
);
2127 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read
, request
->content_read
, request
->content_length
);
2129 if (async
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
, buffer
, bytes_read
);
2130 if (read
) *read
= bytes_read
;
2131 if (end_of_read_data( request
)) finished_reading( request
);
2135 /* read any content returned by the server so that the connection can be reused */
2136 static void drain_content( request_t
*request
)
2143 if (!read_data( request
, buffer
, sizeof(buffer
), &bytes_read
, FALSE
) || !bytes_read
) return;
2147 static void record_cookies( request_t
*request
)
2151 for (i
= 0; i
< request
->num_headers
; i
++)
2153 header_t
*set_cookie
= &request
->headers
[i
];
2154 if (!strcmpiW( set_cookie
->field
, attr_set_cookie
) && !set_cookie
->is_request
)
2156 set_cookies( request
, set_cookie
->value
);
2161 static WCHAR
*get_redirect_url( request_t
*request
, DWORD
*len
)
2166 query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, NULL
, &size
, NULL
);
2167 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER
) return FALSE
;
2168 if (!(ret
= heap_alloc( size
))) return NULL
;
2169 *len
= size
/ sizeof(WCHAR
);
2170 if (query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, ret
, &size
, NULL
)) return ret
;
2175 static BOOL
handle_redirect( request_t
*request
, DWORD status
)
2180 connect_t
*connect
= request
->connect
;
2182 WCHAR
*hostname
= NULL
, *location
;
2185 if (!(location
= get_redirect_url( request
, &len_url
))) return FALSE
;
2187 memset( &uc
, 0, sizeof(uc
) );
2188 uc
.dwStructSize
= sizeof(uc
);
2189 uc
.dwSchemeLength
= uc
.dwHostNameLength
= uc
.dwUrlPathLength
= uc
.dwExtraInfoLength
= ~0u;
2191 if (!WinHttpCrackUrl( location
, len_url
, 0, &uc
)) /* assume relative redirect */
2195 len
= strlenW( location
) + 1;
2196 if (location
[0] != '/') len
++;
2197 if (!(p
= path
= heap_alloc( len
* sizeof(WCHAR
) ))) goto end
;
2199 if (location
[0] != '/') *p
++ = '/';
2200 strcpyW( p
, location
);
2202 heap_free( request
->path
);
2203 request
->path
= path
;
2205 drain_content( request
);
2206 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_url
+ 1 );
2210 if (uc
.nScheme
== INTERNET_SCHEME_HTTP
&& request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
2212 if (request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP
) goto end
;
2213 TRACE("redirect from secure page to non-secure page\n");
2214 request
->hdr
.flags
&= ~WINHTTP_FLAG_SECURE
;
2216 else if (uc
.nScheme
== INTERNET_SCHEME_HTTPS
&& !(request
->hdr
.flags
& WINHTTP_FLAG_SECURE
))
2218 TRACE("redirect from non-secure page to secure page\n");
2219 request
->hdr
.flags
|= WINHTTP_FLAG_SECURE
;
2222 drain_content( request
);
2223 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_url
+ 1 );
2225 len
= uc
.dwHostNameLength
;
2226 if (!(hostname
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2227 memcpy( hostname
, uc
.lpszHostName
, len
* sizeof(WCHAR
) );
2230 port
= uc
.nPort
? uc
.nPort
: (uc
.nScheme
== INTERNET_SCHEME_HTTPS
? 443 : 80);
2231 if (strcmpiW( connect
->hostname
, hostname
) || connect
->serverport
!= port
)
2233 heap_free( connect
->hostname
);
2234 connect
->hostname
= hostname
;
2235 connect
->hostport
= port
;
2236 if (!(ret
= set_server_for_hostname( connect
, hostname
, port
))) goto end
;
2238 netconn_close( &request
->netconn
);
2239 if (!(ret
= netconn_init( &request
->netconn
))) goto end
;
2240 request
->read_pos
= request
->read_size
= 0;
2241 request
->read_chunked
= FALSE
;
2242 request
->read_chunked_eof
= FALSE
;
2244 else heap_free( hostname
);
2246 if (!(ret
= add_host_header( request
, WINHTTP_ADDREQ_FLAG_REPLACE
))) goto end
;
2247 if (!(ret
= open_connection( request
))) goto end
;
2249 heap_free( request
->path
);
2250 request
->path
= NULL
;
2251 if (uc
.dwUrlPathLength
)
2253 len
= uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
;
2254 if (!(request
->path
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2255 strcpyW( request
->path
, uc
.lpszUrlPath
);
2257 else request
->path
= strdupW( slashW
);
2260 /* remove content-type/length headers */
2261 if ((index
= get_header_index( request
, attr_content_type
, 0, TRUE
)) >= 0) delete_header( request
, index
);
2262 if ((index
= get_header_index( request
, attr_content_length
, 0, TRUE
)) >= 0 ) delete_header( request
, index
);
2264 if (status
!= HTTP_STATUS_REDIRECT_KEEP_VERB
&& !strcmpW( request
->verb
, postW
))
2266 heap_free( request
->verb
);
2267 request
->verb
= strdupW( getW
);
2268 request
->optional
= NULL
;
2269 request
->optional_len
= 0;
2274 heap_free( location
);
2278 static BOOL
receive_response( request_t
*request
, BOOL async
)
2281 DWORD size
, query
, status
;
2285 if (!(ret
= read_reply( request
)))
2287 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE
);
2290 size
= sizeof(DWORD
);
2291 query
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
2292 if (!(ret
= query_headers( request
, query
, NULL
, &status
, &size
, NULL
))) break;
2294 set_content_length( request
);
2296 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
)) record_cookies( request
);
2298 if (status
== HTTP_STATUS_MOVED
|| status
== HTTP_STATUS_REDIRECT
|| status
== HTTP_STATUS_REDIRECT_KEEP_VERB
)
2300 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_REDIRECTS
||
2301 request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_NEVER
) break;
2303 if (!(ret
= handle_redirect( request
, status
))) break;
2305 /* recurse synchronously */
2306 send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
);
2309 else if (status
== HTTP_STATUS_DENIED
|| status
== HTTP_STATUS_PROXY_AUTH_REQ
)
2311 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_AUTHENTICATION
) break;
2313 drain_content( request
);
2314 if (!handle_authorization( request
, status
))
2319 /* recurse synchronously */
2320 send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
);
2326 if (ret
) refill_buffer( request
, FALSE
);
2330 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
, NULL
, 0 );
2333 WINHTTP_ASYNC_RESULT result
;
2334 result
.dwResult
= API_RECEIVE_RESPONSE
;
2335 result
.dwError
= get_last_error();
2336 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2342 static void task_receive_response( task_header_t
*task
)
2344 receive_response_t
*r
= (receive_response_t
*)task
;
2345 receive_response( r
->hdr
.request
, TRUE
);
2348 /***********************************************************************
2349 * WinHttpReceiveResponse (winhttp.@)
2351 BOOL WINAPI
WinHttpReceiveResponse( HINTERNET hrequest
, LPVOID reserved
)
2356 TRACE("%p, %p\n", hrequest
, reserved
);
2358 if (!(request
= (request_t
*)grab_object( hrequest
)))
2360 set_last_error( ERROR_INVALID_HANDLE
);
2363 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2365 release_object( &request
->hdr
);
2366 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2370 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2372 receive_response_t
*r
;
2374 if (!(r
= heap_alloc( sizeof(receive_response_t
) ))) return FALSE
;
2375 r
->hdr
.request
= request
;
2376 r
->hdr
.proc
= task_receive_response
;
2378 addref_object( &request
->hdr
);
2379 ret
= queue_task( (task_header_t
*)r
);
2382 ret
= receive_response( request
, FALSE
);
2384 release_object( &request
->hdr
);
2388 static BOOL
query_data_available( request_t
*request
, DWORD
*available
, BOOL async
)
2390 DWORD count
= get_available_data( request
);
2392 if (!request
->read_chunked
)
2393 count
+= netconn_query_data_available( &request
->netconn
);
2396 refill_buffer( request
, async
);
2397 count
= get_available_data( request
);
2398 if (!request
->read_chunked
)
2399 count
+= netconn_query_data_available( &request
->netconn
);
2402 if (async
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
, &count
, sizeof(count
) );
2403 TRACE("%u bytes available\n", count
);
2404 if (available
) *available
= count
;
2408 static void task_query_data_available( task_header_t
*task
)
2410 query_data_t
*q
= (query_data_t
*)task
;
2411 query_data_available( q
->hdr
.request
, q
->available
, TRUE
);
2414 /***********************************************************************
2415 * WinHttpQueryDataAvailable (winhttp.@)
2417 BOOL WINAPI
WinHttpQueryDataAvailable( HINTERNET hrequest
, LPDWORD available
)
2422 TRACE("%p, %p\n", hrequest
, available
);
2424 if (!(request
= (request_t
*)grab_object( hrequest
)))
2426 set_last_error( ERROR_INVALID_HANDLE
);
2429 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2431 release_object( &request
->hdr
);
2432 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2436 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2440 if (!(q
= heap_alloc( sizeof(query_data_t
) ))) return FALSE
;
2441 q
->hdr
.request
= request
;
2442 q
->hdr
.proc
= task_query_data_available
;
2443 q
->available
= available
;
2445 addref_object( &request
->hdr
);
2446 ret
= queue_task( (task_header_t
*)q
);
2449 ret
= query_data_available( request
, available
, FALSE
);
2451 release_object( &request
->hdr
);
2455 static void task_read_data( task_header_t
*task
)
2457 read_data_t
*r
= (read_data_t
*)task
;
2458 read_data( r
->hdr
.request
, r
->buffer
, r
->to_read
, r
->read
, TRUE
);
2461 /***********************************************************************
2462 * WinHttpReadData (winhttp.@)
2464 BOOL WINAPI
WinHttpReadData( HINTERNET hrequest
, LPVOID buffer
, DWORD to_read
, LPDWORD read
)
2469 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_read
, read
);
2471 if (!(request
= (request_t
*)grab_object( hrequest
)))
2473 set_last_error( ERROR_INVALID_HANDLE
);
2476 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2478 release_object( &request
->hdr
);
2479 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2483 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2487 if (!(r
= heap_alloc( sizeof(read_data_t
) ))) return FALSE
;
2488 r
->hdr
.request
= request
;
2489 r
->hdr
.proc
= task_read_data
;
2491 r
->to_read
= to_read
;
2494 addref_object( &request
->hdr
);
2495 ret
= queue_task( (task_header_t
*)r
);
2498 ret
= read_data( request
, buffer
, to_read
, read
, FALSE
);
2500 release_object( &request
->hdr
);
2504 static BOOL
write_data( request_t
*request
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
, BOOL async
)
2509 ret
= netconn_send( &request
->netconn
, buffer
, to_write
, &num_bytes
);
2513 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
, &num_bytes
, sizeof(num_bytes
) );
2516 WINHTTP_ASYNC_RESULT result
;
2517 result
.dwResult
= API_WRITE_DATA
;
2518 result
.dwError
= get_last_error();
2519 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2522 if (ret
&& written
) *written
= num_bytes
;
2526 static void task_write_data( task_header_t
*task
)
2528 write_data_t
*w
= (write_data_t
*)task
;
2529 write_data( w
->hdr
.request
, w
->buffer
, w
->to_write
, w
->written
, TRUE
);
2532 /***********************************************************************
2533 * WinHttpWriteData (winhttp.@)
2535 BOOL WINAPI
WinHttpWriteData( HINTERNET hrequest
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
)
2540 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_write
, written
);
2542 if (!(request
= (request_t
*)grab_object( hrequest
)))
2544 set_last_error( ERROR_INVALID_HANDLE
);
2547 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2549 release_object( &request
->hdr
);
2550 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2554 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2558 if (!(w
= heap_alloc( sizeof(write_data_t
) ))) return FALSE
;
2559 w
->hdr
.request
= request
;
2560 w
->hdr
.proc
= task_write_data
;
2562 w
->to_write
= to_write
;
2563 w
->written
= written
;
2565 addref_object( &request
->hdr
);
2566 ret
= queue_task( (task_header_t
*)w
);
2569 ret
= write_data( request
, buffer
, to_write
, written
, FALSE
);
2571 release_object( &request
->hdr
);
2577 REQUEST_STATE_UNINITIALIZED
,
2578 REQUEST_STATE_INITIALIZED
,
2579 REQUEST_STATE_CANCELLED
,
2582 REQUEST_STATE_RESPONSE_RECEIVED
2585 struct winhttp_request
2587 IWinHttpRequest IWinHttpRequest_iface
;
2589 CRITICAL_SECTION cs
;
2590 enum request_state state
;
2601 DWORD bytes_available
;
2605 DWORD disable_feature
;
2606 LONG resolve_timeout
;
2607 LONG connect_timeout
;
2609 LONG receive_timeout
;
2610 WINHTTP_PROXY_INFO proxy
;
2613 static inline struct winhttp_request
*impl_from_IWinHttpRequest( IWinHttpRequest
*iface
)
2615 return CONTAINING_RECORD( iface
, struct winhttp_request
, IWinHttpRequest_iface
);
2618 static ULONG WINAPI
winhttp_request_AddRef(
2619 IWinHttpRequest
*iface
)
2621 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2622 return InterlockedIncrement( &request
->refs
);
2625 /* critical section must be held */
2626 static void cancel_request( struct winhttp_request
*request
)
2628 if (request
->state
<= REQUEST_STATE_CANCELLED
) return;
2629 if (request
->thread
) SetEvent( request
->cancel
);
2630 request
->state
= REQUEST_STATE_CANCELLED
;
2633 /* critical section must be held */
2634 static void free_request( struct winhttp_request
*request
)
2636 if (request
->state
< REQUEST_STATE_INITIALIZED
) return;
2637 WinHttpCloseHandle( request
->hrequest
);
2638 WinHttpCloseHandle( request
->hconnect
);
2639 WinHttpCloseHandle( request
->hsession
);
2640 CloseHandle( request
->thread
);
2641 CloseHandle( request
->wait
);
2642 CloseHandle( request
->cancel
);
2643 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2644 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2645 heap_free( request
->buffer
);
2646 heap_free( request
->verb
);
2647 VariantClear( &request
->data
);
2650 static ULONG WINAPI
winhttp_request_Release(
2651 IWinHttpRequest
*iface
)
2653 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2654 LONG refs
= InterlockedDecrement( &request
->refs
);
2657 TRACE("destroying %p\n", request
);
2659 EnterCriticalSection( &request
->cs
);
2660 cancel_request( request
);
2661 free_request( request
);
2662 LeaveCriticalSection( &request
->cs
);
2663 request
->cs
.DebugInfo
->Spare
[0] = 0;
2664 DeleteCriticalSection( &request
->cs
);
2665 heap_free( request
);
2670 static HRESULT WINAPI
winhttp_request_QueryInterface(
2671 IWinHttpRequest
*iface
,
2675 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2677 TRACE("%p, %s, %p\n", request
, debugstr_guid(riid
), obj
);
2679 if (IsEqualGUID( riid
, &IID_IWinHttpRequest
) ||
2680 IsEqualGUID( riid
, &IID_IDispatch
) ||
2681 IsEqualGUID( riid
, &IID_IUnknown
))
2687 FIXME("interface %s not implemented\n", debugstr_guid(riid
));
2688 return E_NOINTERFACE
;
2690 IWinHttpRequest_AddRef( iface
);
2694 static HRESULT WINAPI
winhttp_request_GetTypeInfoCount(
2695 IWinHttpRequest
*iface
,
2698 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2700 TRACE("%p, %p\n", request
, count
);
2707 IWinHttpRequest_tid
,
2711 static ITypeLib
*winhttp_typelib
;
2712 static ITypeInfo
*winhttp_typeinfo
[last_tid
];
2714 static REFIID winhttp_tid_id
[] =
2716 &IID_IWinHttpRequest
2719 static HRESULT
get_typeinfo( enum type_id tid
, ITypeInfo
**ret
)
2723 if (!winhttp_typelib
)
2727 hr
= LoadRegTypeLib( &LIBID_WinHttp
, 5, 1, LOCALE_SYSTEM_DEFAULT
, &typelib
);
2730 ERR("LoadRegTypeLib failed: %08x\n", hr
);
2733 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib
, typelib
, NULL
))
2734 ITypeLib_Release( typelib
);
2736 if (!winhttp_typeinfo
[tid
])
2738 ITypeInfo
*typeinfo
;
2740 hr
= ITypeLib_GetTypeInfoOfGuid( winhttp_typelib
, winhttp_tid_id
[tid
], &typeinfo
);
2743 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id
[tid
]), hr
);
2746 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo
+ tid
), typeinfo
, NULL
))
2747 ITypeInfo_Release( typeinfo
);
2749 *ret
= winhttp_typeinfo
[tid
];
2753 static HRESULT WINAPI
winhttp_request_GetTypeInfo(
2754 IWinHttpRequest
*iface
,
2759 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2760 TRACE("%p, %u, %u, %p\n", request
, index
, lcid
, info
);
2762 return get_typeinfo( IWinHttpRequest_tid
, info
);
2765 static HRESULT WINAPI
winhttp_request_GetIDsOfNames(
2766 IWinHttpRequest
*iface
,
2773 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2774 ITypeInfo
*typeinfo
;
2777 TRACE("%p, %s, %p, %u, %u, %p\n", request
, debugstr_guid(riid
), names
, count
, lcid
, dispid
);
2779 if (!names
|| !count
|| !dispid
) return E_INVALIDARG
;
2781 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
2784 hr
= ITypeInfo_GetIDsOfNames( typeinfo
, names
, count
, dispid
);
2785 ITypeInfo_Release( typeinfo
);
2790 static HRESULT WINAPI
winhttp_request_Invoke(
2791 IWinHttpRequest
*iface
,
2798 EXCEPINFO
*excep_info
,
2801 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2802 ITypeInfo
*typeinfo
;
2805 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request
, member
, debugstr_guid(riid
),
2806 lcid
, flags
, params
, result
, excep_info
, arg_err
);
2808 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
2811 hr
= ITypeInfo_Invoke( typeinfo
, &request
->IWinHttpRequest_iface
, member
, flags
,
2812 params
, result
, excep_info
, arg_err
);
2813 ITypeInfo_Release( typeinfo
);
2818 static HRESULT WINAPI
winhttp_request_SetProxy(
2819 IWinHttpRequest
*iface
,
2820 HTTPREQUEST_PROXY_SETTING proxy_setting
,
2821 VARIANT proxy_server
,
2822 VARIANT bypass_list
)
2824 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2825 DWORD err
= ERROR_SUCCESS
;
2827 TRACE("%p, %u, %s, %s\n", request
, proxy_setting
, debugstr_variant(&proxy_server
),
2828 debugstr_variant(&bypass_list
));
2830 EnterCriticalSection( &request
->cs
);
2831 switch (proxy_setting
)
2833 case HTTPREQUEST_PROXYSETTING_DEFAULT
:
2834 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
2835 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2836 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2837 request
->proxy
.lpszProxy
= NULL
;
2838 request
->proxy
.lpszProxyBypass
= NULL
;
2841 case HTTPREQUEST_PROXYSETTING_DIRECT
:
2842 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NO_PROXY
;
2843 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2844 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2845 request
->proxy
.lpszProxy
= NULL
;
2846 request
->proxy
.lpszProxyBypass
= NULL
;
2849 case HTTPREQUEST_PROXYSETTING_PROXY
:
2850 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
2851 if (V_VT( &proxy_server
) == VT_BSTR
)
2853 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2854 request
->proxy
.lpszProxy
= strdupW( V_BSTR( &proxy_server
) );
2856 if (V_VT( &bypass_list
) == VT_BSTR
)
2858 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2859 request
->proxy
.lpszProxyBypass
= strdupW( V_BSTR( &bypass_list
) );
2864 err
= ERROR_INVALID_PARAMETER
;
2867 LeaveCriticalSection( &request
->cs
);
2868 return HRESULT_FROM_WIN32( err
);
2871 static HRESULT WINAPI
winhttp_request_SetCredentials(
2872 IWinHttpRequest
*iface
,
2875 HTTPREQUEST_SETCREDENTIALS_FLAGS flags
)
2877 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2878 DWORD target
, scheme
= WINHTTP_AUTH_SCHEME_BASIC
; /* FIXME: query supported schemes */
2879 DWORD err
= ERROR_SUCCESS
;
2881 TRACE("%p, %s, %p\n", request
, debugstr_w(username
), password
);
2883 EnterCriticalSection( &request
->cs
);
2884 if (request
->state
< REQUEST_STATE_OPEN
)
2886 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
2891 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
:
2892 target
= WINHTTP_AUTH_TARGET_SERVER
;
2894 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY
:
2895 target
= WINHTTP_AUTH_TARGET_PROXY
;
2898 err
= ERROR_INVALID_PARAMETER
;
2901 if (!WinHttpSetCredentials( request
->hrequest
, target
, scheme
, username
, password
, NULL
))
2903 err
= get_last_error();
2906 LeaveCriticalSection( &request
->cs
);
2907 return HRESULT_FROM_WIN32( err
);
2910 static void initialize_request( struct winhttp_request
*request
)
2912 request
->hrequest
= NULL
;
2913 request
->hconnect
= NULL
;
2914 request
->hsession
= NULL
;
2915 request
->thread
= NULL
;
2916 request
->wait
= NULL
;
2917 request
->cancel
= NULL
;
2918 request
->buffer
= NULL
;
2919 request
->verb
= NULL
;
2920 request
->offset
= 0;
2921 request
->bytes_available
= 0;
2922 request
->bytes_read
= 0;
2923 request
->error
= ERROR_SUCCESS
;
2924 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
2925 request
->disable_feature
= WINHTTP_DISABLE_AUTHENTICATION
;
2926 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
2927 request
->proxy
.lpszProxy
= NULL
;
2928 request
->proxy
.lpszProxyBypass
= NULL
;
2929 request
->resolve_timeout
= 0;
2930 request
->connect_timeout
= 60000;
2931 request
->send_timeout
= 30000;
2932 request
->receive_timeout
= 30000;
2933 VariantInit( &request
->data
);
2934 request
->state
= REQUEST_STATE_INITIALIZED
;
2937 static HRESULT WINAPI
winhttp_request_Open(
2938 IWinHttpRequest
*iface
,
2943 static const WCHAR typeW
[] = {'*','/','*',0};
2944 static const WCHAR
*acceptW
[] = {typeW
, NULL
};
2945 static const WCHAR httpsW
[] = {'h','t','t','p','s'};
2946 static const WCHAR user_agentW
[] = {
2947 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
2948 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
2949 'R','e','q','u','e','s','t','.','5',')',0};
2950 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2951 HINTERNET hsession
= NULL
, hconnect
= NULL
, hrequest
;
2953 WCHAR
*hostname
, *path
= NULL
, *verb
= NULL
;
2954 DWORD err
= ERROR_OUTOFMEMORY
, len
, flags
= 0, request_flags
= 0;
2956 TRACE("%p, %s, %s, %s\n", request
, debugstr_w(method
), debugstr_w(url
),
2957 debugstr_variant(&async
));
2959 if (!method
|| !url
) return E_INVALIDARG
;
2961 memset( &uc
, 0, sizeof(uc
) );
2962 uc
.dwStructSize
= sizeof(uc
);
2963 uc
.dwSchemeLength
= ~0u;
2964 uc
.dwHostNameLength
= ~0u;
2965 uc
.dwUrlPathLength
= ~0u;
2966 uc
.dwExtraInfoLength
= ~0u;
2967 if (!WinHttpCrackUrl( url
, 0, 0, &uc
)) return HRESULT_FROM_WIN32( get_last_error() );
2969 EnterCriticalSection( &request
->cs
);
2970 if (request
->state
!= REQUEST_STATE_INITIALIZED
)
2972 cancel_request( request
);
2973 free_request( request
);
2974 initialize_request( request
);
2976 if (!(hostname
= heap_alloc( (uc
.dwHostNameLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
2977 memcpy( hostname
, uc
.lpszHostName
, uc
.dwHostNameLength
* sizeof(WCHAR
) );
2978 hostname
[uc
.dwHostNameLength
] = 0;
2980 if (!(path
= heap_alloc( (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
2981 memcpy( path
, uc
.lpszUrlPath
, (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
) * sizeof(WCHAR
) );
2982 path
[uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
] = 0;
2984 if (!(verb
= strdupW( method
))) goto error
;
2985 if (V_VT( &async
) == VT_BOOL
&& V_BOOL( &async
)) flags
|= WINHTTP_FLAG_ASYNC
;
2986 if (!(hsession
= WinHttpOpen( user_agentW
, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
, NULL
, NULL
, flags
)))
2988 err
= get_last_error();
2991 if (!(hconnect
= WinHttpConnect( hsession
, hostname
, uc
.nPort
, 0 )))
2993 err
= get_last_error();
2996 len
= sizeof(httpsW
) / sizeof(WCHAR
);
2997 if (uc
.dwSchemeLength
== len
&& !memcmp( uc
.lpszScheme
, httpsW
, len
* sizeof(WCHAR
) ))
2999 request_flags
|= WINHTTP_FLAG_SECURE
;
3001 if (!(hrequest
= WinHttpOpenRequest( hconnect
, method
, path
, NULL
, NULL
, acceptW
, request_flags
)))
3003 err
= get_last_error();
3006 if (flags
& WINHTTP_FLAG_ASYNC
)
3008 request
->wait
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
3009 request
->cancel
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
3010 WinHttpSetOption( hrequest
, WINHTTP_OPTION_CONTEXT_VALUE
, &request
, sizeof(request
) );
3012 request
->state
= REQUEST_STATE_OPEN
;
3013 request
->hsession
= hsession
;
3014 request
->hconnect
= hconnect
;
3015 request
->hrequest
= hrequest
;
3016 request
->verb
= verb
;
3017 heap_free( hostname
);
3019 LeaveCriticalSection( &request
->cs
);
3023 WinHttpCloseHandle( hconnect
);
3024 WinHttpCloseHandle( hsession
);
3025 heap_free( hostname
);
3028 LeaveCriticalSection( &request
->cs
);
3029 return HRESULT_FROM_WIN32( err
);
3032 static HRESULT WINAPI
winhttp_request_SetRequestHeader(
3033 IWinHttpRequest
*iface
,
3037 static const WCHAR fmtW
[] = {'%','s',':',' ','%','s','\r','\n',0};
3038 static const WCHAR emptyW
[] = {0};
3039 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3040 DWORD len
, err
= ERROR_SUCCESS
;
3043 TRACE("%p, %s, %s\n", request
, debugstr_w(header
), debugstr_w(value
));
3045 if (!header
) return E_INVALIDARG
;
3047 EnterCriticalSection( &request
->cs
);
3048 if (request
->state
< REQUEST_STATE_OPEN
)
3050 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
3053 if (request
->state
>= REQUEST_STATE_SENT
)
3055 err
= ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND
;
3058 len
= strlenW( header
) + 4;
3059 if (value
) len
+= strlenW( value
);
3060 if (!(str
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
3062 err
= ERROR_OUTOFMEMORY
;
3065 sprintfW( str
, fmtW
, header
, value
? value
: emptyW
);
3066 if (!WinHttpAddRequestHeaders( request
->hrequest
, str
, len
, WINHTTP_ADDREQ_FLAG_REPLACE
))
3068 err
= get_last_error();
3073 LeaveCriticalSection( &request
->cs
);
3074 return HRESULT_FROM_WIN32( err
);
3077 static HRESULT WINAPI
winhttp_request_GetResponseHeader(
3078 IWinHttpRequest
*iface
,
3082 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3083 DWORD size
, err
= ERROR_SUCCESS
;
3085 TRACE("%p, %p\n", request
, header
);
3087 EnterCriticalSection( &request
->cs
);
3088 if (request
->state
< REQUEST_STATE_SENT
)
3090 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3093 if (!header
|| !value
)
3095 err
= ERROR_INVALID_PARAMETER
;
3099 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, NULL
, &size
, NULL
))
3101 err
= get_last_error();
3102 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3104 if (!(*value
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
3106 err
= ERROR_OUTOFMEMORY
;
3109 err
= ERROR_SUCCESS
;
3110 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, *value
, &size
, NULL
))
3112 err
= get_last_error();
3113 SysFreeString( *value
);
3116 LeaveCriticalSection( &request
->cs
);
3117 return HRESULT_FROM_WIN32( err
);
3120 static HRESULT WINAPI
winhttp_request_GetAllResponseHeaders(
3121 IWinHttpRequest
*iface
,
3124 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3125 DWORD size
, err
= ERROR_SUCCESS
;
3127 TRACE("%p, %p\n", request
, headers
);
3129 if (!headers
) return E_INVALIDARG
;
3131 EnterCriticalSection( &request
->cs
);
3132 if (request
->state
< REQUEST_STATE_SENT
)
3134 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3138 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, NULL
, &size
, NULL
))
3140 err
= get_last_error();
3141 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3143 if (!(*headers
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
3145 err
= ERROR_OUTOFMEMORY
;
3148 err
= ERROR_SUCCESS
;
3149 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, *headers
, &size
, NULL
))
3151 err
= get_last_error();
3152 SysFreeString( *headers
);
3155 LeaveCriticalSection( &request
->cs
);
3156 return HRESULT_FROM_WIN32( err
);
3159 static void CALLBACK
wait_status_callback( HINTERNET handle
, DWORD_PTR context
, DWORD status
, LPVOID buffer
, DWORD size
)
3161 struct winhttp_request
*request
= (struct winhttp_request
*)context
;
3165 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
:
3166 request
->bytes_available
= *(DWORD
*)buffer
;
3167 request
->error
= ERROR_SUCCESS
;
3169 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE
:
3170 request
->bytes_read
= size
;
3171 request
->error
= ERROR_SUCCESS
;
3173 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
:
3175 WINHTTP_ASYNC_RESULT
*result
= (WINHTTP_ASYNC_RESULT
*)buffer
;
3176 request
->error
= result
->dwError
;
3181 SetEvent( request
->wait
);
3184 static void wait_set_status_callback( struct winhttp_request
*request
, DWORD status
)
3186 if (!request
->wait
) return;
3187 status
|= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
;
3188 WinHttpSetStatusCallback( request
->hrequest
, wait_status_callback
, status
, 0 );
3191 static DWORD
wait_for_completion( struct winhttp_request
*request
)
3197 request
->error
= ERROR_SUCCESS
;
3198 return ERROR_SUCCESS
;
3200 handles
[0] = request
->wait
;
3201 handles
[1] = request
->cancel
;
3202 switch (WaitForMultipleObjects( 2, handles
, FALSE
, INFINITE
))
3206 case WAIT_OBJECT_0
+ 1:
3207 request
->error
= ERROR_CANCELLED
;
3210 request
->error
= get_last_error();
3213 return request
->error
;
3216 static HRESULT
request_receive( struct winhttp_request
*request
)
3218 DWORD err
, size
, buflen
= 4096;
3220 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
);
3221 if (!WinHttpReceiveResponse( request
->hrequest
, NULL
))
3223 return HRESULT_FROM_WIN32( get_last_error() );
3225 if ((err
= wait_for_completion( request
))) return HRESULT_FROM_WIN32( err
);
3226 if (!strcmpW( request
->verb
, headW
))
3228 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
3231 if (!(request
->buffer
= heap_alloc( buflen
))) return E_OUTOFMEMORY
;
3232 request
->buffer
[0] = 0;
3236 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
);
3237 if (!WinHttpQueryDataAvailable( request
->hrequest
, &request
->bytes_available
))
3239 err
= get_last_error();
3242 if ((err
= wait_for_completion( request
))) goto error
;
3243 if (!request
->bytes_available
) break;
3244 size
+= request
->bytes_available
;
3248 while (buflen
< size
) buflen
*= 2;
3249 if (!(tmp
= heap_realloc( request
->buffer
, buflen
)))
3251 err
= ERROR_OUTOFMEMORY
;
3254 request
->buffer
= tmp
;
3256 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
);
3257 if (!WinHttpReadData( request
->hrequest
, request
->buffer
+ request
->offset
,
3258 request
->bytes_available
, &request
->bytes_read
))
3260 err
= get_last_error();
3263 if ((err
= wait_for_completion( request
))) goto error
;
3264 request
->offset
+= request
->bytes_read
;
3265 } while (request
->bytes_read
);
3267 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
3271 heap_free( request
->buffer
);
3272 request
->buffer
= NULL
;
3273 return HRESULT_FROM_WIN32( err
);
3276 static DWORD
request_set_parameters( struct winhttp_request
*request
)
3278 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_PROXY
, &request
->proxy
,
3279 sizeof(request
->proxy
) )) return get_last_error();
3281 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_AUTOLOGON_POLICY
, &request
->logon_policy
,
3282 sizeof(request
->logon_policy
) )) return get_last_error();
3284 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_DISABLE_FEATURE
, &request
->disable_feature
,
3285 sizeof(request
->disable_feature
) )) return get_last_error();
3287 if (!WinHttpSetTimeouts( request
->hrequest
,
3288 request
->resolve_timeout
,
3289 request
->connect_timeout
,
3290 request
->send_timeout
,
3291 request
->receive_timeout
)) return get_last_error();
3292 return ERROR_SUCCESS
;
3295 static void request_set_utf8_content_type( struct winhttp_request
*request
)
3297 static const WCHAR fmtW
[] = {'%','s',':',' ','%','s',0};
3298 static const WCHAR text_plainW
[] = {'t','e','x','t','/','p','l','a','i','n',0};
3299 static const WCHAR charset_utf8W
[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3303 len
= sprintfW( headerW
, fmtW
, attr_content_type
, text_plainW
);
3304 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
3305 len
= sprintfW( headerW
, fmtW
, attr_content_type
, charset_utf8W
);
3306 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
);
3309 static HRESULT
request_send( struct winhttp_request
*request
)
3311 SAFEARRAY
*sa
= NULL
;
3318 if ((err
= request_set_parameters( request
))) return HRESULT_FROM_WIN32( err
);
3319 if (strcmpW( request
->verb
, getW
))
3321 VariantInit( &data
);
3322 if (V_VT( &request
->data
) == VT_BSTR
)
3325 const WCHAR
*str
= V_BSTR( &request
->data
);
3326 int i
, len
= strlenW( str
);
3328 for (i
= 0; i
< len
; i
++)
3336 size
= WideCharToMultiByte( cp
, 0, str
, len
, NULL
, 0, NULL
, NULL
);
3337 if (!(ptr
= heap_alloc( size
))) return E_OUTOFMEMORY
;
3338 WideCharToMultiByte( cp
, 0, str
, len
, ptr
, size
, NULL
, NULL
);
3339 if (cp
== CP_UTF8
) request_set_utf8_content_type( request
);
3341 else if (VariantChangeType( &data
, &request
->data
, 0, VT_ARRAY
|VT_UI1
) == S_OK
)
3343 sa
= V_ARRAY( &data
);
3344 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
) return hr
;
3345 if ((hr
= SafeArrayGetUBound( sa
, 1, &size
)) != S_OK
)
3347 SafeArrayUnaccessData( sa
);
3353 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
);
3354 if (!WinHttpSendRequest( request
->hrequest
, NULL
, 0, ptr
, size
, size
, 0 ))
3356 err
= get_last_error();
3359 if ((err
= wait_for_completion( request
))) goto error
;
3360 if (sa
) SafeArrayUnaccessData( sa
);
3361 else heap_free( ptr
);
3362 request
->state
= REQUEST_STATE_SENT
;
3366 if (sa
) SafeArrayUnaccessData( sa
);
3367 else heap_free( ptr
);
3368 return HRESULT_FROM_WIN32( err
);
3371 static HRESULT
request_send_and_receive( struct winhttp_request
*request
)
3373 HRESULT hr
= request_send( request
);
3374 if (hr
== S_OK
) hr
= request_receive( request
);
3378 static DWORD CALLBACK
send_and_receive_proc( void *arg
)
3380 struct winhttp_request
*request
= (struct winhttp_request
*)arg
;
3381 return request_send_and_receive( request
);
3384 static HRESULT WINAPI
winhttp_request_Send(
3385 IWinHttpRequest
*iface
,
3388 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3391 TRACE("%p, %s\n", request
, debugstr_variant(&body
));
3393 EnterCriticalSection( &request
->cs
);
3394 if (request
->state
< REQUEST_STATE_OPEN
)
3396 LeaveCriticalSection( &request
->cs
);
3397 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
);
3399 if (request
->state
>= REQUEST_STATE_SENT
)
3401 LeaveCriticalSection( &request
->cs
);
3404 VariantClear( &request
->data
);
3405 if ((hr
= VariantCopyInd( &request
->data
, &body
)) != S_OK
) {
3406 LeaveCriticalSection( &request
->cs
);
3410 if (request
->wait
) /* async request */
3412 if (!(request
->thread
= CreateThread( NULL
, 0, send_and_receive_proc
, request
, 0, NULL
)))
3414 LeaveCriticalSection( &request
->cs
);
3415 return HRESULT_FROM_WIN32( get_last_error() );
3418 else hr
= request_send_and_receive( request
);
3419 LeaveCriticalSection( &request
->cs
);
3423 static HRESULT WINAPI
winhttp_request_get_Status(
3424 IWinHttpRequest
*iface
,
3427 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3428 DWORD err
= ERROR_SUCCESS
, flags
, status_code
, len
= sizeof(status_code
), index
= 0;
3430 TRACE("%p, %p\n", request
, status
);
3432 if (!status
) return E_INVALIDARG
;
3434 EnterCriticalSection( &request
->cs
);
3435 if (request
->state
< REQUEST_STATE_SENT
)
3437 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3440 flags
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
3441 if (!WinHttpQueryHeaders( request
->hrequest
, flags
, NULL
, &status_code
, &len
, &index
))
3443 err
= get_last_error();
3446 *status
= status_code
;
3449 LeaveCriticalSection( &request
->cs
);
3450 return HRESULT_FROM_WIN32( err
);
3453 static HRESULT WINAPI
winhttp_request_get_StatusText(
3454 IWinHttpRequest
*iface
,
3457 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3458 DWORD err
= ERROR_SUCCESS
, len
= 0, index
= 0;
3460 TRACE("%p, %p\n", request
, status
);
3462 if (!status
) return E_INVALIDARG
;
3464 EnterCriticalSection( &request
->cs
);
3465 if (request
->state
< REQUEST_STATE_SENT
)
3467 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3470 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, NULL
, &len
, &index
))
3472 err
= get_last_error();
3473 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3475 if (!(*status
= SysAllocStringLen( NULL
, len
/ sizeof(WCHAR
) )))
3477 err
= ERROR_OUTOFMEMORY
;
3481 err
= ERROR_SUCCESS
;
3482 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, *status
, &len
, &index
))
3484 err
= get_last_error();
3485 SysFreeString( *status
);
3488 LeaveCriticalSection( &request
->cs
);
3489 return HRESULT_FROM_WIN32( err
);
3492 static DWORD
request_get_codepage( struct winhttp_request
*request
, UINT
*codepage
)
3494 static const WCHAR utf8W
[] = {'u','t','f','-','8',0};
3495 static const WCHAR charsetW
[] = {'c','h','a','r','s','e','t',0};
3500 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, NULL
, &size
, NULL
) &&
3501 get_last_error() == ERROR_INSUFFICIENT_BUFFER
)
3503 if (!(buffer
= heap_alloc( size
))) return ERROR_OUTOFMEMORY
;
3504 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, buffer
, &size
, NULL
))
3506 return get_last_error();
3508 if ((p
= strstrW( buffer
, charsetW
)))
3510 p
+= strlenW( charsetW
);
3511 while (*p
== ' ') p
++;
3514 while (*p
== ' ') p
++;
3515 if (!strcmpiW( p
, utf8W
)) *codepage
= CP_UTF8
;
3518 heap_free( buffer
);
3520 return ERROR_SUCCESS
;
3523 static HRESULT WINAPI
winhttp_request_get_ResponseText(
3524 IWinHttpRequest
*iface
,
3527 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3529 DWORD err
= ERROR_SUCCESS
;
3532 TRACE("%p, %p\n", request
, body
);
3534 if (!body
) return E_INVALIDARG
;
3536 EnterCriticalSection( &request
->cs
);
3537 if (request
->state
< REQUEST_STATE_SENT
)
3539 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3542 if ((err
= request_get_codepage( request
, &codepage
))) goto done
;
3543 len
= MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, NULL
, 0 );
3544 if (!(*body
= SysAllocStringLen( NULL
, len
)))
3546 err
= ERROR_OUTOFMEMORY
;
3549 MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, *body
, len
);
3553 LeaveCriticalSection( &request
->cs
);
3554 return HRESULT_FROM_WIN32( err
);
3557 static HRESULT WINAPI
winhttp_request_get_ResponseBody(
3558 IWinHttpRequest
*iface
,
3561 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3564 DWORD err
= ERROR_SUCCESS
;
3567 TRACE("%p, %p\n", request
, body
);
3569 if (!body
) return E_INVALIDARG
;
3571 EnterCriticalSection( &request
->cs
);
3572 if (!(sa
= SafeArrayCreateVector( VT_UI1
, 0, request
->offset
)))
3574 err
= ERROR_OUTOFMEMORY
;
3577 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
)
3579 SafeArrayDestroy( sa
);
3580 LeaveCriticalSection( &request
->cs
);
3583 memcpy( ptr
, request
->buffer
, request
->offset
);
3584 if ((hr
= SafeArrayUnaccessData( sa
)) != S_OK
)
3586 SafeArrayDestroy( sa
);
3587 LeaveCriticalSection( &request
->cs
);
3590 V_VT( body
) = VT_ARRAY
|VT_UI1
;
3591 V_ARRAY( body
) = sa
;
3594 LeaveCriticalSection( &request
->cs
);
3595 return HRESULT_FROM_WIN32( err
);
3598 static HRESULT WINAPI
winhttp_request_get_ResponseStream(
3599 IWinHttpRequest
*iface
,
3606 static HRESULT WINAPI
winhttp_request_get_Option(
3607 IWinHttpRequest
*iface
,
3608 WinHttpRequestOption option
,
3615 static HRESULT WINAPI
winhttp_request_put_Option(
3616 IWinHttpRequest
*iface
,
3617 WinHttpRequestOption option
,
3620 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3623 TRACE("%p, %u, %s\n", request
, option
, debugstr_variant(&value
));
3625 EnterCriticalSection( &request
->cs
);
3628 case WinHttpRequestOption_EnableRedirects
:
3630 if (V_BOOL( &value
))
3631 request
->disable_feature
&= ~WINHTTP_DISABLE_REDIRECTS
;
3633 request
->disable_feature
|= WINHTTP_DISABLE_REDIRECTS
;
3637 FIXME("unimplemented option %u\n", option
);
3641 LeaveCriticalSection( &request
->cs
);
3645 /* critical section must be held */
3646 static DWORD
wait_for_response( struct winhttp_request
*request
, DWORD timeout
)
3648 HANDLE thread
= request
->thread
;
3651 LeaveCriticalSection( &request
->cs
);
3652 while ((err
= MsgWaitForMultipleObjects( 1, &thread
, FALSE
, timeout
, QS_ALLINPUT
)) == WAIT_OBJECT_0
+ 1)
3655 while (PeekMessageW( &msg
, NULL
, 0, 0, PM_REMOVE
))
3657 TranslateMessage( &msg
);
3658 DispatchMessageW( &msg
);
3664 ret
= ERROR_SUCCESS
;
3667 ret
= ERROR_TIMEOUT
;
3671 ret
= get_last_error();
3674 EnterCriticalSection( &request
->cs
);
3678 static HRESULT WINAPI
winhttp_request_WaitForResponse(
3679 IWinHttpRequest
*iface
,
3681 VARIANT_BOOL
*succeeded
)
3683 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3684 DWORD err
, msecs
= (V_I4(&timeout
) == -1) ? INFINITE
: V_I4(&timeout
) * 1000;
3686 TRACE("%p, %s, %p\n", request
, debugstr_variant(&timeout
), succeeded
);
3688 EnterCriticalSection( &request
->cs
);
3689 if (!request
->thread
)
3691 LeaveCriticalSection( &request
->cs
);
3694 if (request
->state
>= REQUEST_STATE_RESPONSE_RECEIVED
)
3696 LeaveCriticalSection( &request
->cs
);
3699 switch ((err
= wait_for_response( request
, msecs
)))
3702 if (succeeded
) *succeeded
= VARIANT_FALSE
;
3703 err
= ERROR_SUCCESS
;
3707 if (succeeded
) *succeeded
= VARIANT_TRUE
;
3712 LeaveCriticalSection( &request
->cs
);
3713 return HRESULT_FROM_WIN32( err
);
3716 static HRESULT WINAPI
winhttp_request_Abort(
3717 IWinHttpRequest
*iface
)
3719 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3721 TRACE("%p\n", request
);
3723 EnterCriticalSection( &request
->cs
);
3724 cancel_request( request
);
3725 LeaveCriticalSection( &request
->cs
);
3729 static HRESULT WINAPI
winhttp_request_SetTimeouts(
3730 IWinHttpRequest
*iface
,
3731 LONG resolve_timeout
,
3732 LONG connect_timeout
,
3734 LONG receive_timeout
)
3736 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3738 TRACE("%p, %d, %d, %d, %d\n", request
, resolve_timeout
, connect_timeout
, send_timeout
, receive_timeout
);
3740 EnterCriticalSection( &request
->cs
);
3741 request
->resolve_timeout
= resolve_timeout
;
3742 request
->connect_timeout
= connect_timeout
;
3743 request
->send_timeout
= send_timeout
;
3744 request
->receive_timeout
= receive_timeout
;
3745 LeaveCriticalSection( &request
->cs
);
3749 static HRESULT WINAPI
winhttp_request_SetClientCertificate(
3750 IWinHttpRequest
*iface
,
3757 static HRESULT WINAPI
winhttp_request_SetAutoLogonPolicy(
3758 IWinHttpRequest
*iface
,
3759 WinHttpRequestAutoLogonPolicy policy
)
3761 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3764 TRACE("%p, %u\n", request
, policy
);
3766 EnterCriticalSection( &request
->cs
);
3769 case AutoLogonPolicy_Always
:
3770 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW
;
3772 case AutoLogonPolicy_OnlyIfBypassProxy
:
3773 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
3775 case AutoLogonPolicy_Never
:
3776 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH
;
3778 default: hr
= E_INVALIDARG
;
3781 LeaveCriticalSection( &request
->cs
);
3785 static const struct IWinHttpRequestVtbl winhttp_request_vtbl
=
3787 winhttp_request_QueryInterface
,
3788 winhttp_request_AddRef
,
3789 winhttp_request_Release
,
3790 winhttp_request_GetTypeInfoCount
,
3791 winhttp_request_GetTypeInfo
,
3792 winhttp_request_GetIDsOfNames
,
3793 winhttp_request_Invoke
,
3794 winhttp_request_SetProxy
,
3795 winhttp_request_SetCredentials
,
3796 winhttp_request_Open
,
3797 winhttp_request_SetRequestHeader
,
3798 winhttp_request_GetResponseHeader
,
3799 winhttp_request_GetAllResponseHeaders
,
3800 winhttp_request_Send
,
3801 winhttp_request_get_Status
,
3802 winhttp_request_get_StatusText
,
3803 winhttp_request_get_ResponseText
,
3804 winhttp_request_get_ResponseBody
,
3805 winhttp_request_get_ResponseStream
,
3806 winhttp_request_get_Option
,
3807 winhttp_request_put_Option
,
3808 winhttp_request_WaitForResponse
,
3809 winhttp_request_Abort
,
3810 winhttp_request_SetTimeouts
,
3811 winhttp_request_SetClientCertificate
,
3812 winhttp_request_SetAutoLogonPolicy
3815 HRESULT
WinHttpRequest_create( void **obj
)
3817 struct winhttp_request
*request
;
3821 if (!(request
= heap_alloc( sizeof(*request
) ))) return E_OUTOFMEMORY
;
3822 request
->IWinHttpRequest_iface
.lpVtbl
= &winhttp_request_vtbl
;
3824 request
->state
= REQUEST_STATE_UNINITIALIZED
;
3825 request
->proxy
.lpszProxy
= NULL
;
3826 request
->proxy
.lpszProxyBypass
= NULL
;
3827 InitializeCriticalSection( &request
->cs
);
3828 request
->cs
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": winhttp_request.cs");
3830 *obj
= &request
->IWinHttpRequest_iface
;
3831 TRACE("returning iface %p\n", *obj
);