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
24 #include "wine/port.h"
25 #include "wine/debug.h"
29 #ifdef HAVE_ARPA_INET_H
30 # include <arpa/inet.h>
37 #include "httprequest.h"
40 #include "winhttp_private.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(winhttp
);
44 static const WCHAR attr_accept
[] = {'A','c','c','e','p','t',0};
45 static const WCHAR attr_accept_charset
[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
46 static const WCHAR attr_accept_encoding
[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
47 static const WCHAR attr_accept_language
[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
48 static const WCHAR attr_accept_ranges
[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
49 static const WCHAR attr_age
[] = {'A','g','e',0};
50 static const WCHAR attr_allow
[] = {'A','l','l','o','w',0};
51 static const WCHAR attr_authorization
[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
52 static const WCHAR attr_cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
53 static const WCHAR attr_connection
[] = {'C','o','n','n','e','c','t','i','o','n',0};
54 static const WCHAR attr_content_base
[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
55 static const WCHAR attr_content_encoding
[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
56 static const WCHAR attr_content_id
[] = {'C','o','n','t','e','n','t','-','I','D',0};
57 static const WCHAR attr_content_language
[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
58 static const WCHAR attr_content_length
[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
59 static const WCHAR attr_content_location
[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
60 static const WCHAR attr_content_md5
[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
61 static const WCHAR attr_content_range
[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
62 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};
63 static const WCHAR attr_content_type
[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
64 static const WCHAR attr_cookie
[] = {'C','o','o','k','i','e',0};
65 static const WCHAR attr_date
[] = {'D','a','t','e',0};
66 static const WCHAR attr_from
[] = {'F','r','o','m',0};
67 static const WCHAR attr_etag
[] = {'E','T','a','g',0};
68 static const WCHAR attr_expect
[] = {'E','x','p','e','c','t',0};
69 static const WCHAR attr_expires
[] = {'E','x','p','i','r','e','s',0};
70 static const WCHAR attr_host
[] = {'H','o','s','t',0};
71 static const WCHAR attr_if_match
[] = {'I','f','-','M','a','t','c','h',0};
72 static const WCHAR attr_if_modified_since
[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
73 static const WCHAR attr_if_none_match
[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
74 static const WCHAR attr_if_range
[] = {'I','f','-','R','a','n','g','e',0};
75 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};
76 static const WCHAR attr_last_modified
[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
77 static const WCHAR attr_location
[] = {'L','o','c','a','t','i','o','n',0};
78 static const WCHAR attr_max_forwards
[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
79 static const WCHAR attr_mime_version
[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
80 static const WCHAR attr_pragma
[] = {'P','r','a','g','m','a',0};
81 static const WCHAR attr_proxy_authenticate
[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
82 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};
83 static const WCHAR attr_proxy_connection
[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
84 static const WCHAR attr_public
[] = {'P','u','b','l','i','c',0};
85 static const WCHAR attr_range
[] = {'R','a','n','g','e',0};
86 static const WCHAR attr_referer
[] = {'R','e','f','e','r','e','r',0};
87 static const WCHAR attr_retry_after
[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
88 static const WCHAR attr_server
[] = {'S','e','r','v','e','r',0};
89 static const WCHAR attr_set_cookie
[] = {'S','e','t','-','C','o','o','k','i','e',0};
90 static const WCHAR attr_status
[] = {'S','t','a','t','u','s',0};
91 static const WCHAR attr_transfer_encoding
[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
92 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};
93 static const WCHAR attr_upgrade
[] = {'U','p','g','r','a','d','e',0};
94 static const WCHAR attr_uri
[] = {'U','R','I',0};
95 static const WCHAR attr_user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',0};
96 static const WCHAR attr_vary
[] = {'V','a','r','y',0};
97 static const WCHAR attr_via
[] = {'V','i','a',0};
98 static const WCHAR attr_warning
[] = {'W','a','r','n','i','n','g',0};
99 static const WCHAR attr_www_authenticate
[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
101 static const WCHAR
*attribute_table
[] =
103 attr_mime_version
, /* WINHTTP_QUERY_MIME_VERSION = 0 */
104 attr_content_type
, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
105 attr_content_transfer_encoding
, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
106 attr_content_id
, /* WINHTTP_QUERY_CONTENT_ID = 3 */
107 NULL
, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
108 attr_content_length
, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
109 attr_content_language
, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
110 attr_allow
, /* WINHTTP_QUERY_ALLOW = 7 */
111 attr_public
, /* WINHTTP_QUERY_PUBLIC = 8 */
112 attr_date
, /* WINHTTP_QUERY_DATE = 9 */
113 attr_expires
, /* WINHTTP_QUERY_EXPIRES = 10 */
114 attr_last_modified
, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
115 NULL
, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
116 attr_uri
, /* WINHTTP_QUERY_URI = 13 */
117 attr_from
, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
118 NULL
, /* WINHTTP_QUERY_COST = 15 */
119 NULL
, /* WINHTTP_QUERY_LINK = 16 */
120 attr_pragma
, /* WINHTTP_QUERY_PRAGMA = 17 */
121 NULL
, /* WINHTTP_QUERY_VERSION = 18 */
122 attr_status
, /* WINHTTP_QUERY_STATUS_CODE = 19 */
123 NULL
, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
124 NULL
, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
125 NULL
, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
126 attr_connection
, /* WINHTTP_QUERY_CONNECTION = 23 */
127 attr_accept
, /* WINHTTP_QUERY_ACCEPT = 24 */
128 attr_accept_charset
, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
129 attr_accept_encoding
, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
130 attr_accept_language
, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
131 attr_authorization
, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
132 attr_content_encoding
, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
133 NULL
, /* WINHTTP_QUERY_FORWARDED = 30 */
134 NULL
, /* WINHTTP_QUERY_FROM = 31 */
135 attr_if_modified_since
, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
136 attr_location
, /* WINHTTP_QUERY_LOCATION = 33 */
137 NULL
, /* WINHTTP_QUERY_ORIG_URI = 34 */
138 attr_referer
, /* WINHTTP_QUERY_REFERER = 35 */
139 attr_retry_after
, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
140 attr_server
, /* WINHTTP_QUERY_SERVER = 37 */
141 NULL
, /* WINHTTP_TITLE = 38 */
142 attr_user_agent
, /* WINHTTP_QUERY_USER_AGENT = 39 */
143 attr_www_authenticate
, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
144 attr_proxy_authenticate
, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
145 attr_accept_ranges
, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
146 attr_set_cookie
, /* WINHTTP_QUERY_SET_COOKIE = 43 */
147 attr_cookie
, /* WINHTTP_QUERY_COOKIE = 44 */
148 NULL
, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
149 NULL
, /* WINHTTP_QUERY_REFRESH = 46 */
150 NULL
, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
151 attr_age
, /* WINHTTP_QUERY_AGE = 48 */
152 attr_cache_control
, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
153 attr_content_base
, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
154 attr_content_location
, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
155 attr_content_md5
, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
156 attr_content_range
, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
157 attr_etag
, /* WINHTTP_QUERY_ETAG = 54 */
158 attr_host
, /* WINHTTP_QUERY_HOST = 55 */
159 attr_if_match
, /* WINHTTP_QUERY_IF_MATCH = 56 */
160 attr_if_none_match
, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
161 attr_if_range
, /* WINHTTP_QUERY_IF_RANGE = 58 */
162 attr_if_unmodified_since
, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
163 attr_max_forwards
, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
164 attr_proxy_authorization
, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
165 attr_range
, /* WINHTTP_QUERY_RANGE = 62 */
166 attr_transfer_encoding
, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
167 attr_upgrade
, /* WINHTTP_QUERY_UPGRADE = 64 */
168 attr_vary
, /* WINHTTP_QUERY_VARY = 65 */
169 attr_via
, /* WINHTTP_QUERY_VIA = 66 */
170 attr_warning
, /* WINHTTP_QUERY_WARNING = 67 */
171 attr_expect
, /* WINHTTP_QUERY_EXPECT = 68 */
172 attr_proxy_connection
, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
173 attr_unless_modified_since
, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
174 NULL
, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
175 NULL
, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
176 NULL
, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
177 NULL
/* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
180 static DWORD CALLBACK
task_thread( LPVOID param
)
182 task_header_t
*task
= param
;
186 release_object( &task
->request
->hdr
);
188 return ERROR_SUCCESS
;
191 static BOOL
queue_task( task_header_t
*task
)
193 return QueueUserWorkItem( task_thread
, task
, WT_EXECUTELONGFUNCTION
);
196 static void free_header( header_t
*header
)
198 heap_free( header
->field
);
199 heap_free( header
->value
);
203 static BOOL
valid_token_char( WCHAR c
)
205 if (c
< 32 || c
== 127) return FALSE
;
212 case '\\': case '\"':
224 static header_t
*parse_header( LPCWSTR string
)
231 if (!(q
= strchrW( p
, ':' )))
233 WARN("no ':' in line %s\n", debugstr_w(string
));
238 WARN("empty field name in line %s\n", debugstr_w(string
));
243 if (!valid_token_char( *p
))
245 WARN("invalid character in field name %s\n", debugstr_w(string
));
251 if (!(header
= heap_alloc_zero( sizeof(header_t
) ))) return NULL
;
252 if (!(header
->field
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
257 memcpy( header
->field
, string
, len
* sizeof(WCHAR
) );
258 header
->field
[len
] = 0;
260 q
++; /* skip past colon */
261 while (*q
== ' ') q
++;
264 WARN("no value in line %s\n", debugstr_w(string
));
268 if (!(header
->value
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
270 free_header( header
);
273 memcpy( header
->value
, q
, len
* sizeof(WCHAR
) );
274 header
->value
[len
] = 0;
279 static int get_header_index( request_t
*request
, LPCWSTR field
, int requested_index
, BOOL request_only
)
283 TRACE("%s\n", debugstr_w(field
));
285 for (index
= 0; index
< request
->num_headers
; index
++)
287 if (strcmpiW( request
->headers
[index
].field
, field
)) continue;
288 if (request_only
&& !request
->headers
[index
].is_request
) continue;
289 if (!request_only
&& request
->headers
[index
].is_request
) continue;
291 if (!requested_index
) break;
294 if (index
>= request
->num_headers
) index
= -1;
295 TRACE("returning %d\n", index
);
299 static BOOL
insert_header( request_t
*request
, header_t
*header
)
304 count
= request
->num_headers
+ 1;
306 hdrs
= heap_realloc_zero( request
->headers
, sizeof(header_t
) * count
);
308 hdrs
= heap_alloc_zero( sizeof(header_t
) * count
);
312 request
->headers
= hdrs
;
313 request
->headers
[count
- 1].field
= strdupW( header
->field
);
314 request
->headers
[count
- 1].value
= strdupW( header
->value
);
315 request
->headers
[count
- 1].is_request
= header
->is_request
;
316 request
->num_headers
++;
322 static BOOL
delete_header( request_t
*request
, DWORD index
)
324 if (!request
->num_headers
) return FALSE
;
325 if (index
>= request
->num_headers
) return FALSE
;
326 request
->num_headers
--;
328 heap_free( request
->headers
[index
].field
);
329 heap_free( request
->headers
[index
].value
);
331 memmove( &request
->headers
[index
], &request
->headers
[index
+ 1], (request
->num_headers
- index
) * sizeof(header_t
) );
332 memset( &request
->headers
[request
->num_headers
], 0, sizeof(header_t
) );
336 static BOOL
process_header( request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD flags
, BOOL request_only
)
341 TRACE("%s: %s 0x%08x\n", debugstr_w(field
), debugstr_w(value
), flags
);
343 /* replace wins out over add */
344 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
) flags
&= ~WINHTTP_ADDREQ_FLAG_ADD
;
346 if (flags
& WINHTTP_ADDREQ_FLAG_ADD
) index
= -1;
348 index
= get_header_index( request
, field
, 0, request_only
);
352 if (flags
& WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
) return FALSE
;
353 header
= &request
->headers
[index
];
359 hdr
.field
= (LPWSTR
)field
;
360 hdr
.value
= (LPWSTR
)value
;
361 hdr
.is_request
= request_only
;
363 return insert_header( request
, &hdr
);
365 /* no value to delete */
368 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
)
370 delete_header( request
, index
);
375 hdr
.field
= (LPWSTR
)field
;
376 hdr
.value
= (LPWSTR
)value
;
377 hdr
.is_request
= request_only
;
379 return insert_header( request
, &hdr
);
383 else if (flags
& (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
| WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
))
386 int len
, orig_len
, value_len
;
388 orig_len
= strlenW( header
->value
);
389 value_len
= strlenW( value
);
391 if (flags
& WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
) sep
= ',';
394 len
= orig_len
+ value_len
+ 2;
395 if ((tmp
= heap_realloc( header
->value
, (len
+ 1) * sizeof(WCHAR
) )))
399 header
->value
[orig_len
] = sep
;
401 header
->value
[orig_len
] = ' ';
404 memcpy( &header
->value
[orig_len
], value
, value_len
* sizeof(WCHAR
) );
405 header
->value
[len
] = 0;
412 BOOL
add_request_headers( request_t
*request
, LPCWSTR headers
, DWORD len
, DWORD flags
)
415 WCHAR
*buffer
, *p
, *q
;
418 if (len
== ~0u) len
= strlenW( headers
);
419 if (!len
) return TRUE
;
420 if (!(buffer
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
421 strcpyW( buffer
, headers
);
429 if (q
[0] == '\n' && q
[1] == '\r')
434 if (q
[0] == '\r' && q
[1] == '\n') break;
441 q
+= 2; /* jump over \r\n */
443 if ((header
= parse_header( p
)))
445 ret
= process_header( request
, header
->field
, header
->value
, flags
, TRUE
);
446 free_header( header
);
455 /***********************************************************************
456 * WinHttpAddRequestHeaders (winhttp.@)
458 BOOL WINAPI
WinHttpAddRequestHeaders( HINTERNET hrequest
, LPCWSTR headers
, DWORD len
, DWORD flags
)
463 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest
, debugstr_w(headers
), len
, flags
);
467 set_last_error( ERROR_INVALID_PARAMETER
);
470 if (!(request
= (request_t
*)grab_object( hrequest
)))
472 set_last_error( ERROR_INVALID_HANDLE
);
475 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
477 release_object( &request
->hdr
);
478 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
482 ret
= add_request_headers( request
, headers
, len
, flags
);
484 release_object( &request
->hdr
);
488 static WCHAR
*build_request_path( request_t
*request
)
492 if (strcmpiW( request
->connect
->hostname
, request
->connect
->servername
))
494 static const WCHAR http
[] = { 'h','t','t','p',0 };
495 static const WCHAR https
[] = { 'h','t','t','p','s',0 };
496 static const WCHAR fmt
[] = { '%','s',':','/','/','%','s',0 };
497 LPCWSTR scheme
= request
->netconn
.secure
? https
: http
;
500 len
= strlenW( scheme
) + strlenW( request
->connect
->hostname
);
501 /* 3 characters for '://', 1 for NUL. */
503 if (request
->connect
->hostport
)
505 /* 1 for ':' between host and port, up to 5 for port */
509 len
+= strlenW( request
->path
);
510 if ((ret
= heap_alloc( len
* sizeof(WCHAR
) )))
512 sprintfW( ret
, fmt
, scheme
, request
->connect
->hostname
);
513 if (request
->connect
->hostport
)
515 static const WCHAR colonFmt
[] = { ':','%','u',0 };
517 sprintfW( ret
+ strlenW( ret
), colonFmt
,
518 request
->connect
->hostport
);
521 strcatW( ret
, request
->path
);
529 static WCHAR
*build_request_string( request_t
*request
)
531 static const WCHAR space
[] = {' ',0};
532 static const WCHAR crlf
[] = {'\r','\n',0};
533 static const WCHAR colon
[] = {':',' ',0};
534 static const WCHAR twocrlf
[] = {'\r','\n','\r','\n',0};
537 const WCHAR
**headers
, **p
;
538 unsigned int len
, i
= 0, j
;
540 /* allocate space for an array of all the string pointers to be added */
541 len
= request
->num_headers
* 4 + 7;
542 if (!(headers
= heap_alloc( len
* sizeof(LPCWSTR
) ))) return NULL
;
544 path
= build_request_path( request
);
545 headers
[i
++] = request
->verb
;
546 headers
[i
++] = space
;
548 headers
[i
++] = space
;
549 headers
[i
++] = request
->version
;
551 for (j
= 0; j
< request
->num_headers
; j
++)
553 if (request
->headers
[j
].is_request
)
556 headers
[i
++] = request
->headers
[j
].field
;
557 headers
[i
++] = colon
;
558 headers
[i
++] = request
->headers
[j
].value
;
560 TRACE("adding header %s (%s)\n", debugstr_w(request
->headers
[j
].field
),
561 debugstr_w(request
->headers
[j
].value
));
564 headers
[i
++] = twocrlf
;
568 for (p
= headers
; *p
; p
++) len
+= strlenW( *p
);
571 if (!(ret
= heap_alloc( len
* sizeof(WCHAR
) )))
574 for (p
= headers
; *p
; p
++) strcatW( ret
, *p
);
577 if (path
!= request
->path
)
579 heap_free( headers
);
583 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
585 static BOOL
query_headers( request_t
*request
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
587 header_t
*header
= NULL
;
588 BOOL request_only
, ret
= FALSE
;
589 int requested_index
, header_index
= -1;
592 request_only
= level
& WINHTTP_QUERY_FLAG_REQUEST_HEADERS
;
593 requested_index
= index
? *index
: 0;
595 attr
= level
& ~QUERY_MODIFIER_MASK
;
598 case WINHTTP_QUERY_CUSTOM
:
600 header_index
= get_header_index( request
, name
, requested_index
, request_only
);
603 case WINHTTP_QUERY_RAW_HEADERS
:
605 WCHAR
*headers
, *p
, *q
;
608 headers
= build_request_string( request
);
610 headers
= request
->raw_headers
;
612 if (!(p
= headers
)) return FALSE
;
613 for (len
= 0; *p
; p
++) if (*p
!= '\r') len
++;
615 if (!buffer
|| (len
+ 1) * sizeof(WCHAR
) > *buflen
)
618 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
622 for (p
= headers
, q
= buffer
; *p
; p
++, q
++)
624 if (*p
!= '\r') *q
= *p
;
632 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
));
635 *buflen
= len
* sizeof(WCHAR
);
636 if (request_only
) heap_free( headers
);
639 case WINHTTP_QUERY_RAW_HEADERS_CRLF
:
644 headers
= build_request_string( request
);
646 headers
= request
->raw_headers
;
648 if (!headers
) return FALSE
;
649 len
= strlenW( headers
) * sizeof(WCHAR
);
650 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
652 len
+= sizeof(WCHAR
);
653 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
657 memcpy( buffer
, headers
, len
+ sizeof(WCHAR
) );
658 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
/ sizeof(WCHAR
)));
662 if (request_only
) heap_free( headers
);
665 case WINHTTP_QUERY_VERSION
:
666 len
= strlenW( request
->version
) * sizeof(WCHAR
);
667 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
669 len
+= sizeof(WCHAR
);
670 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
674 strcpyW( buffer
, request
->version
);
675 TRACE("returning string: %s\n", debugstr_w(buffer
));
681 case WINHTTP_QUERY_STATUS_TEXT
:
682 len
= strlenW( request
->status_text
) * sizeof(WCHAR
);
683 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
685 len
+= sizeof(WCHAR
);
686 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
690 strcpyW( buffer
, request
->status_text
);
691 TRACE("returning string: %s\n", debugstr_w(buffer
));
698 if (attr
>= sizeof(attribute_table
)/sizeof(attribute_table
[0]) || !attribute_table
[attr
])
700 FIXME("attribute %u not implemented\n", attr
);
703 TRACE("attribute %s\n", debugstr_w(attribute_table
[attr
]));
704 header_index
= get_header_index( request
, attribute_table
[attr
], requested_index
, request_only
);
708 if (header_index
>= 0)
710 header
= &request
->headers
[header_index
];
712 if (!header
|| (request_only
&& !header
->is_request
))
714 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND
);
717 if (index
) *index
+= 1;
718 if (level
& WINHTTP_QUERY_FLAG_NUMBER
)
720 if (!buffer
|| sizeof(int) > *buflen
)
722 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
726 int *number
= buffer
;
727 *number
= atoiW( header
->value
);
728 TRACE("returning number: %d\n", *number
);
731 *buflen
= sizeof(int);
733 else if (level
& WINHTTP_QUERY_FLAG_SYSTEMTIME
)
735 SYSTEMTIME
*st
= buffer
;
736 if (!buffer
|| sizeof(SYSTEMTIME
) > *buflen
)
738 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
740 else if ((ret
= WinHttpTimeToSystemTime( header
->value
, st
)))
742 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
743 st
->wYear
, st
->wMonth
, st
->wDay
, st
->wDayOfWeek
,
744 st
->wHour
, st
->wMinute
, st
->wSecond
, st
->wMilliseconds
);
746 *buflen
= sizeof(SYSTEMTIME
);
748 else if (header
->value
)
750 len
= strlenW( header
->value
) * sizeof(WCHAR
);
751 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
753 len
+= sizeof(WCHAR
);
754 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
758 strcpyW( buffer
, header
->value
);
759 TRACE("returning string: %s\n", debugstr_w(buffer
));
767 /***********************************************************************
768 * WinHttpQueryHeaders (winhttp.@)
770 BOOL WINAPI
WinHttpQueryHeaders( HINTERNET hrequest
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
775 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest
, level
, debugstr_w(name
), buffer
, buflen
, index
);
777 if (!(request
= (request_t
*)grab_object( hrequest
)))
779 set_last_error( ERROR_INVALID_HANDLE
);
782 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
784 release_object( &request
->hdr
);
785 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
789 ret
= query_headers( request
, level
, name
, buffer
, buflen
, index
);
791 release_object( &request
->hdr
);
795 static LPWSTR
concatenate_string_list( LPCWSTR
*list
, int len
)
800 for( t
= list
; *t
; t
++ )
801 len
+= strlenW( *t
);
804 str
= heap_alloc( len
* sizeof(WCHAR
) );
805 if (!str
) return NULL
;
808 for( t
= list
; *t
; t
++ )
814 static LPWSTR
build_header_request_string( request_t
*request
, LPCWSTR verb
,
815 LPCWSTR path
, LPCWSTR version
)
817 static const WCHAR crlf
[] = {'\r','\n',0};
818 static const WCHAR space
[] = { ' ',0 };
819 static const WCHAR colon
[] = { ':',' ',0 };
820 static const WCHAR twocrlf
[] = {'\r','\n','\r','\n', 0};
821 LPWSTR requestString
;
827 /* allocate space for an array of all the string pointers to be added */
828 len
= (request
->num_headers
) * 4 + 10;
829 req
= heap_alloc( len
* sizeof(LPCWSTR
) );
830 if (!req
) return NULL
;
832 /* add the verb, path and HTTP version string */
840 /* Append custom request headers */
841 for (i
= 0; i
< request
->num_headers
; i
++)
843 if (request
->headers
[i
].is_request
)
846 req
[n
++] = request
->headers
[i
].field
;
848 req
[n
++] = request
->headers
[i
].value
;
850 TRACE("Adding custom header %s (%s)\n",
851 debugstr_w(request
->headers
[i
].field
),
852 debugstr_w(request
->headers
[i
].value
));
857 ERR("oops. buffer overrun\n");
860 requestString
= concatenate_string_list( req
, 4 );
862 if (!requestString
) return NULL
;
865 * Set (header) termination string for request
866 * Make sure there are exactly two new lines at the end of the request
868 p
= &requestString
[strlenW(requestString
)-1];
869 while ( (*p
== '\n') || (*p
== '\r') )
871 strcpyW( p
+1, twocrlf
);
873 return requestString
;
876 static BOOL
read_reply( request_t
*request
);
878 static BOOL
secure_proxy_connect( request_t
*request
)
880 static const WCHAR verbConnect
[] = {'C','O','N','N','E','C','T',0};
881 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
884 connect_t
*connect
= request
->connect
;
886 path
= heap_alloc( (strlenW( connect
->hostname
) + 13) * sizeof(WCHAR
) );
889 LPWSTR requestString
;
891 sprintfW( path
, fmt
, connect
->hostname
, connect
->hostport
);
892 requestString
= build_header_request_string( request
, verbConnect
,
897 LPSTR req_ascii
= strdupWA( requestString
);
899 heap_free( requestString
);
902 int len
= strlen( req_ascii
), bytes_sent
;
904 ret
= netconn_send( &request
->netconn
, req_ascii
, len
, &bytes_sent
);
905 heap_free( req_ascii
);
907 ret
= read_reply( request
);
914 #ifndef INET6_ADDRSTRLEN
915 #define INET6_ADDRSTRLEN 46
918 static WCHAR
*addr_to_str( const struct sockaddr
*addr
)
920 char buf
[INET6_ADDRSTRLEN
];
923 switch (addr
->sa_family
)
926 src
= &((struct sockaddr_in
*)addr
)->sin_addr
;
929 src
= &((struct sockaddr_in6
*)addr
)->sin6_addr
;
932 WARN("unsupported address family %d\n", addr
->sa_family
);
935 if (!inet_ntop( addr
->sa_family
, src
, buf
, sizeof(buf
) )) return NULL
;
936 return strdupAW( buf
);
939 static BOOL
open_connection( request_t
*request
)
942 WCHAR
*addressW
= NULL
;
945 struct sockaddr
*saddr
;
948 if (netconn_connected( &request
->netconn
)) goto done
;
950 connect
= request
->connect
;
951 port
= connect
->serverport
? connect
->serverport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
952 saddr
= (struct sockaddr
*)&connect
->sockaddr
;
953 slen
= sizeof(struct sockaddr
);
955 if (!connect
->resolved
)
957 len
= strlenW( connect
->servername
) + 1;
958 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME
, connect
->servername
, len
);
960 if (!netconn_resolve( connect
->servername
, port
, saddr
, &slen
, request
->resolve_timeout
)) return FALSE
;
961 connect
->resolved
= TRUE
;
963 if (!(addressW
= addr_to_str( saddr
))) return FALSE
;
964 len
= strlenW( addressW
) + 1;
965 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED
, addressW
, len
);
967 if (!addressW
&& !(addressW
= addr_to_str( saddr
))) return FALSE
;
968 TRACE("connecting to %s:%u\n", debugstr_w(addressW
), port
);
970 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER
, addressW
, 0 );
972 if (!netconn_create( &request
->netconn
, saddr
->sa_family
, SOCK_STREAM
, 0 ))
974 heap_free( addressW
);
977 netconn_set_timeout( &request
->netconn
, TRUE
, request
->send_timeout
);
978 netconn_set_timeout( &request
->netconn
, FALSE
, request
->recv_timeout
);
979 if (!netconn_connect( &request
->netconn
, saddr
, slen
, request
->connect_timeout
))
981 netconn_close( &request
->netconn
);
982 heap_free( addressW
);
985 if (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
987 if (connect
->session
->proxy_server
&&
988 strcmpiW( connect
->hostname
, connect
->servername
))
990 if (!secure_proxy_connect( request
))
992 heap_free( addressW
);
996 if (!netconn_secure_connect( &request
->netconn
, connect
->servername
))
998 netconn_close( &request
->netconn
);
999 heap_free( addressW
);
1004 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER
, addressW
, strlenW(addressW
) + 1 );
1007 request
->read_pos
= request
->read_size
= 0;
1008 request
->read_chunked
= FALSE
;
1009 request
->read_chunked_size
= ~0u;
1010 request
->read_chunked_eof
= FALSE
;
1011 heap_free( addressW
);
1015 void close_connection( request_t
*request
)
1017 if (!netconn_connected( &request
->netconn
)) return;
1019 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION
, 0, 0 );
1020 netconn_close( &request
->netconn
);
1021 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED
, 0, 0 );
1024 static BOOL
add_host_header( request_t
*request
, DWORD modifier
)
1029 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
1030 connect_t
*connect
= request
->connect
;
1033 port
= connect
->hostport
? connect
->hostport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
1035 if (port
== INTERNET_DEFAULT_HTTP_PORT
|| port
== INTERNET_DEFAULT_HTTPS_PORT
)
1037 return process_header( request
, attr_host
, connect
->hostname
, modifier
, TRUE
);
1039 len
= strlenW( connect
->hostname
) + 7; /* sizeof(":65335") */
1040 if (!(host
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
1041 sprintfW( host
, fmt
, connect
->hostname
, port
);
1042 ret
= process_header( request
, attr_host
, host
, modifier
, TRUE
);
1047 static void clear_response_headers( request_t
*request
)
1051 for (i
= 0; i
< request
->num_headers
; i
++)
1053 if (!request
->headers
[i
].field
) continue;
1054 if (!request
->headers
[i
].value
) continue;
1055 if (request
->headers
[i
].is_request
) continue;
1056 delete_header( request
, i
);
1061 static BOOL
send_request( request_t
*request
, LPCWSTR headers
, DWORD headers_len
, LPVOID optional
,
1062 DWORD optional_len
, DWORD total_len
, DWORD_PTR context
, BOOL async
)
1064 static const WCHAR keep_alive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
1065 static const WCHAR no_cache
[] = {'n','o','-','c','a','c','h','e',0};
1066 static const WCHAR length_fmt
[] = {'%','l','d',0};
1069 connect_t
*connect
= request
->connect
;
1070 session_t
*session
= connect
->session
;
1074 DWORD len
, i
, flags
;
1076 clear_response_headers( request
);
1078 flags
= WINHTTP_ADDREQ_FLAG_ADD
|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
;
1079 for (i
= 0; i
< request
->num_accept_types
; i
++)
1081 process_header( request
, attr_accept
, request
->accept_types
[i
], flags
, TRUE
);
1084 process_header( request
, attr_user_agent
, session
->agent
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1086 if (connect
->hostname
)
1087 add_host_header( request
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
1089 if (total_len
|| (request
->verb
&& !strcmpW( request
->verb
, postW
)))
1091 WCHAR length
[21]; /* decimal long int + null */
1092 sprintfW( length
, length_fmt
, total_len
);
1093 process_header( request
, attr_content_length
, length
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1095 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
))
1097 process_header( request
, attr_connection
, keep_alive
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1099 if (request
->hdr
.flags
& WINHTTP_FLAG_REFRESH
)
1101 process_header( request
, attr_pragma
, no_cache
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1102 process_header( request
, attr_cache_control
, no_cache
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1104 if (headers
&& !add_request_headers( request
, headers
, headers_len
, WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
))
1106 TRACE("failed to add request headers\n");
1109 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
) && !add_cookie_headers( request
))
1111 WARN("failed to add cookie headers\n");
1115 if (context
) request
->hdr
.context
= context
;
1117 if (!(ret
= open_connection( request
))) goto end
;
1118 if (!(req
= build_request_string( request
))) goto end
;
1120 if (!(req_ascii
= strdupWA( req
))) goto end
;
1121 TRACE("full request: %s\n", debugstr_a(req_ascii
));
1122 len
= strlen(req_ascii
);
1124 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST
, NULL
, 0 );
1126 ret
= netconn_send( &request
->netconn
, req_ascii
, len
, &bytes_sent
);
1127 heap_free( req_ascii
);
1132 if (!netconn_send( &request
->netconn
, optional
, optional_len
, &bytes_sent
)) goto end
;
1133 request
->optional
= optional
;
1134 request
->optional_len
= optional_len
;
1135 len
+= optional_len
;
1137 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
, &len
, sizeof(len
) );
1142 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
, NULL
, 0 );
1145 WINHTTP_ASYNC_RESULT result
;
1146 result
.dwResult
= API_SEND_REQUEST
;
1147 result
.dwError
= get_last_error();
1148 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
1155 static void task_send_request( task_header_t
*task
)
1157 send_request_t
*s
= (send_request_t
*)task
;
1158 send_request( s
->hdr
.request
, s
->headers
, s
->headers_len
, s
->optional
, s
->optional_len
, s
->total_len
, s
->context
, TRUE
);
1159 heap_free( s
->headers
);
1162 /***********************************************************************
1163 * WinHttpSendRequest (winhttp.@)
1165 BOOL WINAPI
WinHttpSendRequest( HINTERNET hrequest
, LPCWSTR headers
, DWORD headers_len
,
1166 LPVOID optional
, DWORD optional_len
, DWORD total_len
, DWORD_PTR context
)
1171 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1172 hrequest
, debugstr_w(headers
), headers_len
, optional_len
, total_len
, context
);
1174 if (!(request
= (request_t
*)grab_object( hrequest
)))
1176 set_last_error( ERROR_INVALID_HANDLE
);
1179 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1181 release_object( &request
->hdr
);
1182 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1186 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
1190 if (!(s
= heap_alloc( sizeof(send_request_t
) ))) return FALSE
;
1191 s
->hdr
.request
= request
;
1192 s
->hdr
.proc
= task_send_request
;
1193 s
->headers
= strdupW( headers
);
1194 s
->headers_len
= headers_len
;
1195 s
->optional
= optional
;
1196 s
->optional_len
= optional_len
;
1197 s
->total_len
= total_len
;
1198 s
->context
= context
;
1200 addref_object( &request
->hdr
);
1201 ret
= queue_task( (task_header_t
*)s
);
1204 ret
= send_request( request
, headers
, headers_len
, optional
, optional_len
, total_len
, context
, FALSE
);
1206 release_object( &request
->hdr
);
1210 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1212 static const WCHAR basicW
[] = {'B','a','s','i','c',0};
1213 static const WCHAR ntlmW
[] = {'N','T','L','M',0};
1214 static const WCHAR passportW
[] = {'P','a','s','s','p','o','r','t',0};
1215 static const WCHAR digestW
[] = {'D','i','g','e','s','t',0};
1216 static const WCHAR negotiateW
[] = {'N','e','g','o','t','i','a','t','e',0};
1226 { basicW
, ARRAYSIZE(basicW
) - 1, WINHTTP_AUTH_SCHEME_BASIC
},
1227 { ntlmW
, ARRAYSIZE(ntlmW
) - 1, WINHTTP_AUTH_SCHEME_NTLM
},
1228 { passportW
, ARRAYSIZE(passportW
) - 1, WINHTTP_AUTH_SCHEME_PASSPORT
},
1229 { digestW
, ARRAYSIZE(digestW
) - 1, WINHTTP_AUTH_SCHEME_DIGEST
},
1230 { negotiateW
, ARRAYSIZE(negotiateW
) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE
}
1232 static const unsigned int num_auth_schemes
= sizeof(auth_schemes
)/sizeof(auth_schemes
[0]);
1234 static enum auth_scheme
scheme_from_flag( DWORD flag
)
1238 for (i
= 0; i
< num_auth_schemes
; i
++) if (flag
== auth_schemes
[i
].scheme
) return i
;
1239 return SCHEME_INVALID
;
1242 static DWORD
auth_scheme_from_header( WCHAR
*header
)
1246 for (i
= 0; i
< num_auth_schemes
; i
++)
1248 if (!strncmpiW( header
, auth_schemes
[i
].str
, auth_schemes
[i
].len
) &&
1249 (header
[auth_schemes
[i
].len
] == ' ' || !header
[auth_schemes
[i
].len
])) return auth_schemes
[i
].scheme
;
1254 static BOOL
query_auth_schemes( request_t
*request
, DWORD level
, LPDWORD supported
, LPDWORD first
)
1265 query_headers( request
, level
, NULL
, NULL
, &size
, &index
);
1266 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER
) break;
1269 if (!(buffer
= heap_alloc( size
))) return FALSE
;
1270 if (!query_headers( request
, level
, NULL
, buffer
, &size
, &index
))
1272 heap_free( buffer
);
1275 scheme
= auth_scheme_from_header( buffer
);
1276 heap_free( buffer
);
1279 if (first
&& index
== 1)
1280 *first
= *supported
= scheme
;
1282 *supported
|= scheme
;
1289 /***********************************************************************
1290 * WinHttpQueryAuthSchemes (winhttp.@)
1292 BOOL WINAPI
WinHttpQueryAuthSchemes( HINTERNET hrequest
, LPDWORD supported
, LPDWORD first
, LPDWORD target
)
1297 TRACE("%p, %p, %p, %p\n", hrequest
, supported
, first
, target
);
1299 if (!(request
= (request_t
*)grab_object( hrequest
)))
1301 set_last_error( ERROR_INVALID_HANDLE
);
1304 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1306 release_object( &request
->hdr
);
1307 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1310 if (!supported
|| !first
|| !target
)
1312 release_object( &request
->hdr
);
1313 set_last_error( ERROR_INVALID_PARAMETER
);
1318 if (query_auth_schemes( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, supported
, first
))
1320 *target
= WINHTTP_AUTH_TARGET_SERVER
;
1323 else if (query_auth_schemes( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, supported
, first
))
1325 *target
= WINHTTP_AUTH_TARGET_PROXY
;
1329 release_object( &request
->hdr
);
1333 static UINT
encode_base64( const char *bin
, unsigned int len
, WCHAR
*base64
)
1336 static const char base64enc
[] =
1337 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1341 /* first 6 bits, all from bin[0] */
1342 base64
[n
++] = base64enc
[(bin
[0] & 0xfc) >> 2];
1343 x
= (bin
[0] & 3) << 4;
1345 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1348 base64
[n
++] = base64enc
[x
];
1353 base64
[n
++] = base64enc
[x
| ((bin
[1] & 0xf0) >> 4)];
1354 x
= (bin
[1] & 0x0f) << 2;
1356 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1359 base64
[n
++] = base64enc
[x
];
1363 base64
[n
++] = base64enc
[x
| ((bin
[2] & 0xc0) >> 6)];
1365 /* last 6 bits, all from bin [2] */
1366 base64
[n
++] = base64enc
[bin
[2] & 0x3f];
1374 static inline char decode_char( WCHAR c
)
1376 if (c
>= 'A' && c
<= 'Z') return c
- 'A';
1377 if (c
>= 'a' && c
<= 'z') return c
- 'a' + 26;
1378 if (c
>= '0' && c
<= '9') return c
- '0' + 52;
1379 if (c
== '+') return 62;
1380 if (c
== '/') return 63;
1384 static unsigned int decode_base64( const WCHAR
*base64
, unsigned int len
, char *buf
)
1387 char c0
, c1
, c2
, c3
;
1388 const WCHAR
*p
= base64
;
1392 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1393 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1394 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1395 if ((c3
= decode_char( p
[3] )) > 63) return 0;
1399 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1400 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1401 buf
[i
+ 2] = (c2
<< 6) | c3
;
1409 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1410 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1412 if (buf
) buf
[i
] = (c0
<< 2) | (c1
>> 4);
1415 else if (p
[3] == '=')
1417 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1418 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1419 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1423 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1424 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1430 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1431 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1432 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1433 if ((c3
= decode_char( p
[3] )) > 63) return 0;
1437 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1438 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1439 buf
[i
+ 2] = (c2
<< 6) | c3
;
1446 static struct authinfo
*alloc_authinfo(void)
1448 struct authinfo
*ret
;
1450 if (!(ret
= heap_alloc( sizeof(*ret
) ))) return NULL
;
1452 SecInvalidateHandle( &ret
->cred
);
1453 SecInvalidateHandle( &ret
->ctx
);
1454 memset( &ret
->exp
, 0, sizeof(ret
->exp
) );
1460 ret
->finished
= FALSE
;
1464 void destroy_authinfo( struct authinfo
*authinfo
)
1466 if (!authinfo
) return;
1468 if (SecIsValidHandle( &authinfo
->ctx
))
1469 DeleteSecurityContext( &authinfo
->ctx
);
1470 if (SecIsValidHandle( &authinfo
->cred
))
1471 FreeCredentialsHandle( &authinfo
->cred
);
1473 heap_free( authinfo
->data
);
1474 heap_free( authinfo
);
1477 static BOOL
get_authvalue( request_t
*request
, DWORD level
, DWORD scheme
, WCHAR
*buffer
, DWORD len
)
1479 DWORD size
, index
= 0;
1483 if (!query_headers( request
, level
, NULL
, buffer
, &size
, &index
)) return FALSE
;
1484 if (auth_scheme_from_header( buffer
) == scheme
) break;
1489 static BOOL
do_authorization( request_t
*request
, DWORD target
, DWORD scheme_flag
)
1491 struct authinfo
*authinfo
, **auth_ptr
;
1492 enum auth_scheme scheme
= scheme_from_flag( scheme_flag
);
1493 const WCHAR
*auth_target
, *username
, *password
;
1494 WCHAR auth_value
[2048], *auth_reply
;
1495 DWORD len
= sizeof(auth_value
), len_scheme
, flags
;
1498 if (scheme
== SCHEME_INVALID
) return FALSE
;
1502 case WINHTTP_AUTH_TARGET_SERVER
:
1503 if (!get_authvalue( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1505 auth_ptr
= &request
->authinfo
;
1506 auth_target
= attr_authorization
;
1507 username
= request
->connect
->username
;
1508 password
= request
->connect
->password
;
1511 case WINHTTP_AUTH_TARGET_PROXY
:
1512 if (!get_authvalue( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1514 auth_ptr
= &request
->proxy_authinfo
;
1515 auth_target
= attr_proxy_authorization
;
1516 username
= request
->connect
->session
->proxy_username
;
1517 password
= request
->connect
->session
->proxy_password
;
1521 WARN("unknown target %x\n", target
);
1524 authinfo
= *auth_ptr
;
1530 int userlen
, passlen
;
1532 if (!username
|| !password
) return FALSE
;
1533 if ((!authinfo
&& !(authinfo
= alloc_authinfo())) || authinfo
->finished
) return FALSE
;
1535 userlen
= WideCharToMultiByte( CP_UTF8
, 0, username
, strlenW( username
), NULL
, 0, NULL
, NULL
);
1536 passlen
= WideCharToMultiByte( CP_UTF8
, 0, password
, strlenW( password
), NULL
, 0, NULL
, NULL
);
1538 authinfo
->data_len
= userlen
+ 1 + passlen
;
1539 if (!(authinfo
->data
= heap_alloc( authinfo
->data_len
))) return FALSE
;
1541 WideCharToMultiByte( CP_UTF8
, 0, username
, -1, authinfo
->data
, userlen
, NULL
, NULL
);
1542 authinfo
->data
[userlen
] = ':';
1543 WideCharToMultiByte( CP_UTF8
, 0, password
, -1, authinfo
->data
+ userlen
+ 1, passlen
, NULL
, NULL
);
1545 authinfo
->scheme
= SCHEME_BASIC
;
1546 authinfo
->finished
= TRUE
;
1550 case SCHEME_NEGOTIATE
:
1552 SECURITY_STATUS status
;
1553 SecBufferDesc out_desc
, in_desc
;
1555 ULONG flags
= ISC_REQ_CONNECTION
|ISC_REQ_USE_DCE_STYLE
|ISC_REQ_MUTUAL_AUTH
|ISC_REQ_DELEGATE
;
1562 SEC_WINNT_AUTH_IDENTITY_W id
;
1563 WCHAR
*domain
, *user
;
1565 if (!username
|| !password
|| !(authinfo
= alloc_authinfo())) return FALSE
;
1568 domain
= (WCHAR
*)username
;
1569 user
= strchrW( username
, '\\' );
1574 user
= (WCHAR
*)username
;
1577 id
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1579 id
.UserLength
= strlenW( user
);
1581 id
.DomainLength
= domain
? user
- domain
- 1 : 0;
1582 id
.Password
= (WCHAR
*)password
;
1583 id
.PasswordLength
= strlenW( password
);
1585 status
= AcquireCredentialsHandleW( NULL
, (SEC_WCHAR
*)auth_schemes
[scheme
].str
,
1586 SECPKG_CRED_OUTBOUND
, NULL
, &id
, NULL
, NULL
,
1587 &authinfo
->cred
, &exp
);
1588 if (status
== SEC_E_OK
)
1591 status
= QuerySecurityPackageInfoW( (SEC_WCHAR
*)auth_schemes
[scheme
].str
, &info
);
1592 if (status
== SEC_E_OK
)
1594 authinfo
->max_token
= info
->cbMaxToken
;
1595 FreeContextBuffer( info
);
1598 if (status
!= SEC_E_OK
)
1600 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1601 debugstr_w(auth_schemes
[scheme
].str
), status
);
1602 heap_free( authinfo
);
1605 authinfo
->scheme
= scheme
;
1607 else if (authinfo
->finished
) return FALSE
;
1609 if ((strlenW( auth_value
) < auth_schemes
[authinfo
->scheme
].len
||
1610 strncmpiW( auth_value
, auth_schemes
[authinfo
->scheme
].str
, auth_schemes
[authinfo
->scheme
].len
)))
1612 ERR("authentication scheme changed from %s to %s\n",
1613 debugstr_w(auth_schemes
[authinfo
->scheme
].str
), debugstr_w(auth_value
));
1614 destroy_authinfo( authinfo
);
1618 in
.BufferType
= SECBUFFER_TOKEN
;
1622 in_desc
.ulVersion
= 0;
1623 in_desc
.cBuffers
= 1;
1624 in_desc
.pBuffers
= &in
;
1626 p
= auth_value
+ auth_schemes
[scheme
].len
;
1629 int len
= strlenW( ++p
);
1630 in
.cbBuffer
= decode_base64( p
, len
, NULL
);
1631 if (!(in
.pvBuffer
= heap_alloc( in
.cbBuffer
))) {
1632 destroy_authinfo( authinfo
);
1636 decode_base64( p
, len
, in
.pvBuffer
);
1638 out
.BufferType
= SECBUFFER_TOKEN
;
1639 out
.cbBuffer
= authinfo
->max_token
;
1640 if (!(out
.pvBuffer
= heap_alloc( authinfo
->max_token
)))
1642 heap_free( in
.pvBuffer
);
1643 destroy_authinfo( authinfo
);
1647 out_desc
.ulVersion
= 0;
1648 out_desc
.cBuffers
= 1;
1649 out_desc
.pBuffers
= &out
;
1651 status
= InitializeSecurityContextW( first
? &authinfo
->cred
: NULL
, first
? NULL
: &authinfo
->ctx
,
1652 first
? request
->connect
->servername
: NULL
, flags
, 0,
1653 SECURITY_NETWORK_DREP
, in
.pvBuffer
? &in_desc
: NULL
, 0,
1654 &authinfo
->ctx
, &out_desc
, &authinfo
->attr
, &authinfo
->exp
);
1655 heap_free( in
.pvBuffer
);
1656 if (status
== SEC_E_OK
)
1658 heap_free( authinfo
->data
);
1659 authinfo
->data
= out
.pvBuffer
;
1660 authinfo
->data_len
= out
.cbBuffer
;
1661 authinfo
->finished
= TRUE
;
1662 TRACE("sending last auth packet\n");
1664 else if (status
== SEC_I_CONTINUE_NEEDED
)
1666 heap_free( authinfo
->data
);
1667 authinfo
->data
= out
.pvBuffer
;
1668 authinfo
->data_len
= out
.cbBuffer
;
1669 TRACE("sending next auth packet\n");
1673 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status
);
1674 heap_free( out
.pvBuffer
);
1675 destroy_authinfo( authinfo
);
1682 ERR("invalid scheme %u\n", scheme
);
1685 *auth_ptr
= authinfo
;
1687 len_scheme
= auth_schemes
[authinfo
->scheme
].len
;
1688 len
= len_scheme
+ 1 + ((authinfo
->data_len
+ 2) * 4) / 3;
1689 if (!(auth_reply
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
1691 memcpy( auth_reply
, auth_schemes
[authinfo
->scheme
].str
, len_scheme
* sizeof(WCHAR
) );
1692 auth_reply
[len_scheme
] = ' ';
1693 encode_base64( authinfo
->data
, authinfo
->data_len
, auth_reply
+ len_scheme
+ 1 );
1695 flags
= WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
;
1696 ret
= process_header( request
, auth_target
, auth_reply
, flags
, TRUE
);
1697 heap_free( auth_reply
);
1701 static BOOL
set_credentials( request_t
*request
, DWORD target
, DWORD scheme
, const WCHAR
*username
,
1702 const WCHAR
*password
)
1704 if ((scheme
== WINHTTP_AUTH_SCHEME_BASIC
|| scheme
== WINHTTP_AUTH_SCHEME_DIGEST
) &&
1705 (!username
|| !password
))
1707 set_last_error( ERROR_INVALID_PARAMETER
);
1712 case WINHTTP_AUTH_TARGET_SERVER
:
1714 heap_free( request
->connect
->username
);
1715 if (!username
) request
->connect
->username
= NULL
;
1716 else if (!(request
->connect
->username
= strdupW( username
))) return FALSE
;
1718 heap_free( request
->connect
->password
);
1719 if (!password
) request
->connect
->password
= NULL
;
1720 else if (!(request
->connect
->password
= strdupW( password
))) return FALSE
;
1723 case WINHTTP_AUTH_TARGET_PROXY
:
1725 heap_free( request
->connect
->session
->proxy_username
);
1726 if (!username
) request
->connect
->session
->proxy_username
= NULL
;
1727 else if (!(request
->connect
->session
->proxy_username
= strdupW( username
))) return FALSE
;
1729 heap_free( request
->connect
->session
->proxy_password
);
1730 if (!password
) request
->connect
->session
->proxy_password
= NULL
;
1731 else if (!(request
->connect
->session
->proxy_password
= strdupW( password
))) return FALSE
;
1735 WARN("unknown target %u\n", target
);
1741 /***********************************************************************
1742 * WinHttpSetCredentials (winhttp.@)
1744 BOOL WINAPI
WinHttpSetCredentials( HINTERNET hrequest
, DWORD target
, DWORD scheme
, LPCWSTR username
,
1745 LPCWSTR password
, LPVOID params
)
1750 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest
, target
, scheme
, debugstr_w(username
), password
, params
);
1752 if (!(request
= (request_t
*)grab_object( hrequest
)))
1754 set_last_error( ERROR_INVALID_HANDLE
);
1757 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1759 release_object( &request
->hdr
);
1760 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1764 ret
= set_credentials( request
, target
, scheme
, username
, password
);
1766 release_object( &request
->hdr
);
1770 static BOOL
handle_authorization( request_t
*request
, DWORD status
)
1772 DWORD i
, schemes
, first
, level
, target
;
1776 case HTTP_STATUS_DENIED
:
1777 target
= WINHTTP_AUTH_TARGET_SERVER
;
1778 level
= WINHTTP_QUERY_WWW_AUTHENTICATE
;
1781 case HTTP_STATUS_PROXY_AUTH_REQ
:
1782 target
= WINHTTP_AUTH_TARGET_PROXY
;
1783 level
= WINHTTP_QUERY_PROXY_AUTHENTICATE
;
1787 WARN("unhandled status %u\n", status
);
1791 if (!query_auth_schemes( request
, level
, &schemes
, &first
)) return FALSE
;
1792 if (do_authorization( request
, target
, first
)) return TRUE
;
1795 for (i
= 0; i
< num_auth_schemes
; i
++)
1797 if (!(schemes
& auth_schemes
[i
].scheme
)) continue;
1798 if (do_authorization( request
, target
, auth_schemes
[i
].scheme
)) return TRUE
;
1803 /* set the request content length based on the headers */
1804 static DWORD
set_content_length( request_t
*request
)
1809 buflen
= sizeof(request
->content_length
);
1810 if (!query_headers( request
, WINHTTP_QUERY_CONTENT_LENGTH
|WINHTTP_QUERY_FLAG_NUMBER
,
1811 NULL
, &request
->content_length
, &buflen
, NULL
))
1812 request
->content_length
= ~0u;
1814 buflen
= sizeof(encoding
);
1815 if (query_headers( request
, WINHTTP_QUERY_TRANSFER_ENCODING
, NULL
, encoding
, &buflen
, NULL
) &&
1816 !strcmpiW( encoding
, chunkedW
))
1818 request
->content_length
= ~0u;
1819 request
->read_chunked
= TRUE
;
1820 request
->read_chunked_size
= ~0u;
1821 request
->read_chunked_eof
= FALSE
;
1823 request
->content_read
= 0;
1824 return request
->content_length
;
1827 /* read some more data into the read buffer */
1828 static BOOL
read_more_data( request_t
*request
, int maxlen
, BOOL notify
)
1833 if (request
->read_chunked_eof
) return FALSE
;
1835 if (request
->read_size
&& request
->read_pos
)
1837 /* move existing data to the start of the buffer */
1838 memmove( request
->read_buf
, request
->read_buf
+ request
->read_pos
, request
->read_size
);
1839 request
->read_pos
= 0;
1841 if (maxlen
== -1) maxlen
= sizeof(request
->read_buf
);
1843 if (notify
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE
, NULL
, 0 );
1845 ret
= netconn_recv( &request
->netconn
, request
->read_buf
+ request
->read_size
,
1846 maxlen
- request
->read_size
, 0, &len
);
1848 if (notify
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED
, &len
, sizeof(len
) );
1850 request
->read_size
+= len
;
1854 /* remove some amount of data from the read buffer */
1855 static void remove_data( request_t
*request
, int count
)
1857 if (!(request
->read_size
-= count
)) request
->read_pos
= 0;
1858 else request
->read_pos
+= count
;
1861 static BOOL
read_line( request_t
*request
, char *buffer
, DWORD
*len
)
1863 int count
, bytes_read
, pos
= 0;
1867 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1870 count
= eol
- (request
->read_buf
+ request
->read_pos
);
1871 bytes_read
= count
+ 1;
1873 else count
= bytes_read
= request
->read_size
;
1875 count
= min( count
, *len
- pos
);
1876 memcpy( buffer
+ pos
, request
->read_buf
+ request
->read_pos
, count
);
1878 remove_data( request
, bytes_read
);
1881 if (!read_more_data( request
, -1, TRUE
)) return FALSE
;
1882 if (!request
->read_size
)
1885 TRACE("returning empty string\n");
1891 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
1894 buffer
[*len
- 1] = 0;
1895 TRACE("returning %s\n", debugstr_a(buffer
));
1899 /* discard data contents until we reach end of line */
1900 static BOOL
discard_eol( request_t
*request
, BOOL notify
)
1904 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1907 remove_data( request
, (eol
+ 1) - (request
->read_buf
+ request
->read_pos
) );
1910 request
->read_pos
= request
->read_size
= 0; /* discard everything */
1911 if (!read_more_data( request
, -1, notify
)) return FALSE
;
1912 } while (request
->read_size
);
1916 /* read the size of the next chunk */
1917 static BOOL
start_next_chunk( request_t
*request
, BOOL notify
)
1919 DWORD chunk_size
= 0;
1921 assert(!request
->read_chunked_size
|| request
->read_chunked_size
== ~0u);
1923 if (request
->read_chunked_eof
) return FALSE
;
1925 /* read terminator for the previous chunk */
1926 if (!request
->read_chunked_size
&& !discard_eol( request
, notify
)) return FALSE
;
1930 while (request
->read_size
)
1932 char ch
= request
->read_buf
[request
->read_pos
];
1933 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
1934 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
1935 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
1936 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
1938 TRACE("reading %u byte chunk\n", chunk_size
);
1940 if (request
->content_length
== ~0u) request
->content_length
= chunk_size
;
1941 else request
->content_length
+= chunk_size
;
1943 request
->read_chunked_size
= chunk_size
;
1944 if (!chunk_size
) request
->read_chunked_eof
= TRUE
;
1946 return discard_eol( request
, notify
);
1948 remove_data( request
, 1 );
1950 if (!read_more_data( request
, -1, notify
)) return FALSE
;
1951 if (!request
->read_size
)
1953 request
->content_length
= request
->content_read
= 0;
1954 request
->read_chunked_size
= 0;
1960 /* return the size of data available to be read immediately */
1961 static DWORD
get_available_data( request_t
*request
)
1963 if (request
->read_chunked
) return min( request
->read_chunked_size
, request
->read_size
);
1964 return request
->read_size
;
1967 /* check if we have reached the end of the data to read */
1968 static BOOL
end_of_read_data( request_t
*request
)
1970 if (request
->read_chunked
) return request
->read_chunked_eof
;
1971 if (request
->content_length
== ~0u) return FALSE
;
1972 return (request
->content_length
== request
->content_read
);
1975 static BOOL
refill_buffer( request_t
*request
, BOOL notify
)
1977 int len
= sizeof(request
->read_buf
);
1979 if (request
->read_chunked
)
1981 if (request
->read_chunked_eof
) return FALSE
;
1982 if (request
->read_chunked_size
== ~0u || !request
->read_chunked_size
)
1984 if (!start_next_chunk( request
, notify
)) return FALSE
;
1987 if (!request
->read_chunked
&& request
->content_length
!= ~0u)
1988 len
= min( len
, request
->content_length
- request
->content_read
);
1989 if (len
<= request
->read_size
) return TRUE
;
1990 if (!read_more_data( request
, len
, notify
)) return FALSE
;
1991 if (!request
->read_size
) request
->content_length
= request
->content_read
= 0;
1995 #define MAX_REPLY_LEN 1460
1996 #define INITIAL_HEADER_BUFFER_LEN 512
1998 static BOOL
read_reply( request_t
*request
)
2000 static const WCHAR crlf
[] = {'\r','\n',0};
2002 char buffer
[MAX_REPLY_LEN
];
2003 DWORD buflen
, len
, offset
, received_len
, crlf_len
= 2; /* strlenW(crlf) */
2004 char *status_code
, *status_text
;
2005 WCHAR
*versionW
, *status_textW
, *raw_headers
;
2006 WCHAR status_codeW
[4]; /* sizeof("nnn") */
2008 if (!netconn_connected( &request
->netconn
)) return FALSE
;
2013 buflen
= MAX_REPLY_LEN
;
2014 if (!read_line( request
, buffer
, &buflen
)) return FALSE
;
2015 received_len
+= buflen
;
2017 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
2018 if (!(status_code
= strchr( buffer
, ' ' ))) return FALSE
;
2020 if (!(status_text
= strchr( status_code
, ' ' ))) return FALSE
;
2021 if ((len
= status_text
- status_code
) != sizeof("nnn") - 1) return FALSE
;
2024 TRACE("version [%s] status code [%s] status text [%s]\n",
2025 debugstr_an(buffer
, status_code
- buffer
- 1),
2026 debugstr_an(status_code
, len
),
2027 debugstr_a(status_text
));
2029 } while (!memcmp( status_code
, "100", len
)); /* ignore "100 Continue" responses */
2031 /* we rely on the fact that the protocol is ascii */
2032 MultiByteToWideChar( CP_ACP
, 0, status_code
, len
, status_codeW
, len
);
2033 status_codeW
[len
] = 0;
2034 if (!(process_header( request
, attr_status
, status_codeW
, WINHTTP_ADDREQ_FLAG_REPLACE
, FALSE
))) return FALSE
;
2036 len
= status_code
- buffer
;
2037 if (!(versionW
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2038 MultiByteToWideChar( CP_ACP
, 0, buffer
, len
- 1, versionW
, len
-1 );
2039 versionW
[len
- 1] = 0;
2041 heap_free( request
->version
);
2042 request
->version
= versionW
;
2044 len
= buflen
- (status_text
- buffer
);
2045 if (!(status_textW
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2046 MultiByteToWideChar( CP_ACP
, 0, status_text
, len
, status_textW
, len
);
2048 heap_free( request
->status_text
);
2049 request
->status_text
= status_textW
;
2051 len
= max( buflen
+ crlf_len
, INITIAL_HEADER_BUFFER_LEN
);
2052 if (!(raw_headers
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2053 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
, buflen
);
2054 memcpy( raw_headers
+ buflen
- 1, crlf
, sizeof(crlf
) );
2056 heap_free( request
->raw_headers
);
2057 request
->raw_headers
= raw_headers
;
2059 offset
= buflen
+ crlf_len
- 1;
2064 buflen
= MAX_REPLY_LEN
;
2065 if (!read_line( request
, buffer
, &buflen
)) return TRUE
;
2066 received_len
+= buflen
;
2067 if (!*buffer
) break;
2069 while (len
- offset
< buflen
+ crlf_len
)
2073 if (!(tmp
= heap_realloc( raw_headers
, len
* sizeof(WCHAR
) ))) return FALSE
;
2074 request
->raw_headers
= raw_headers
= tmp
;
2076 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
+ offset
, buflen
);
2078 if (!(header
= parse_header( raw_headers
+ offset
))) break;
2079 if (!(process_header( request
, header
->field
, header
->value
, WINHTTP_ADDREQ_FLAG_ADD
, FALSE
)))
2081 free_header( header
);
2084 free_header( header
);
2085 memcpy( raw_headers
+ offset
+ buflen
- 1, crlf
, sizeof(crlf
) );
2086 offset
+= buflen
+ crlf_len
- 1;
2089 TRACE("raw headers: %s\n", debugstr_w(raw_headers
));
2093 static void finished_reading( request_t
*request
)
2095 static const WCHAR closeW
[] = {'c','l','o','s','e',0};
2098 WCHAR connection
[20];
2099 DWORD size
= sizeof(connection
);
2101 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
) close
= TRUE
;
2102 else if (query_headers( request
, WINHTTP_QUERY_CONNECTION
, NULL
, connection
, &size
, NULL
) ||
2103 query_headers( request
, WINHTTP_QUERY_PROXY_CONNECTION
, NULL
, connection
, &size
, NULL
))
2105 if (!strcmpiW( connection
, closeW
)) close
= TRUE
;
2107 else if (!strcmpW( request
->version
, http1_0
)) close
= TRUE
;
2108 if (close
) close_connection( request
);
2111 static BOOL
read_data( request_t
*request
, void *buffer
, DWORD size
, DWORD
*read
, BOOL async
)
2113 int count
, bytes_read
= 0;
2115 if (end_of_read_data( request
)) goto done
;
2119 if (!(count
= get_available_data( request
)))
2121 if (!refill_buffer( request
, async
)) goto done
;
2122 if (!(count
= get_available_data( request
))) goto done
;
2124 count
= min( count
, size
);
2125 memcpy( (char *)buffer
+ bytes_read
, request
->read_buf
+ request
->read_pos
, count
);
2126 remove_data( request
, count
);
2127 if (request
->read_chunked
) request
->read_chunked_size
-= count
;
2129 bytes_read
+= count
;
2130 request
->content_read
+= count
;
2131 if (end_of_read_data( request
)) goto done
;
2133 if (request
->read_chunked
&& !request
->read_chunked_size
) refill_buffer( request
, async
);
2136 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read
, request
->content_read
, request
->content_length
);
2138 if (async
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
, buffer
, bytes_read
);
2139 if (read
) *read
= bytes_read
;
2140 if (end_of_read_data( request
)) finished_reading( request
);
2144 /* read any content returned by the server so that the connection can be reused */
2145 static void drain_content( request_t
*request
)
2152 if (!read_data( request
, buffer
, sizeof(buffer
), &bytes_read
, FALSE
) || !bytes_read
) return;
2156 static void record_cookies( request_t
*request
)
2160 for (i
= 0; i
< request
->num_headers
; i
++)
2162 header_t
*set_cookie
= &request
->headers
[i
];
2163 if (!strcmpiW( set_cookie
->field
, attr_set_cookie
) && !set_cookie
->is_request
)
2165 set_cookies( request
, set_cookie
->value
);
2170 static WCHAR
*get_redirect_url( request_t
*request
, DWORD
*len
)
2175 query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, NULL
, &size
, NULL
);
2176 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER
) return FALSE
;
2177 if (!(ret
= heap_alloc( size
))) return NULL
;
2178 *len
= size
/ sizeof(WCHAR
);
2179 if (query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, ret
, &size
, NULL
)) return ret
;
2184 static BOOL
handle_redirect( request_t
*request
, DWORD status
)
2189 connect_t
*connect
= request
->connect
;
2191 WCHAR
*hostname
= NULL
, *location
;
2194 if (!(location
= get_redirect_url( request
, &len_url
))) return FALSE
;
2196 memset( &uc
, 0, sizeof(uc
) );
2197 uc
.dwStructSize
= sizeof(uc
);
2198 uc
.dwSchemeLength
= uc
.dwHostNameLength
= uc
.dwUrlPathLength
= uc
.dwExtraInfoLength
= ~0u;
2200 if (!WinHttpCrackUrl( location
, len_url
, 0, &uc
)) /* assume relative redirect */
2204 len
= strlenW( location
) + 1;
2205 if (location
[0] != '/') len
++;
2206 if (!(p
= path
= heap_alloc( len
* sizeof(WCHAR
) ))) goto end
;
2208 if (location
[0] != '/') *p
++ = '/';
2209 strcpyW( p
, location
);
2211 heap_free( request
->path
);
2212 request
->path
= path
;
2214 drain_content( request
);
2215 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_url
+ 1 );
2219 if (uc
.nScheme
== INTERNET_SCHEME_HTTP
&& request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
2221 if (request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP
) goto end
;
2222 TRACE("redirect from secure page to non-secure page\n");
2223 request
->hdr
.flags
&= ~WINHTTP_FLAG_SECURE
;
2225 else if (uc
.nScheme
== INTERNET_SCHEME_HTTPS
&& !(request
->hdr
.flags
& WINHTTP_FLAG_SECURE
))
2227 TRACE("redirect from non-secure page to secure page\n");
2228 request
->hdr
.flags
|= WINHTTP_FLAG_SECURE
;
2231 drain_content( request
);
2232 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_url
+ 1 );
2234 len
= uc
.dwHostNameLength
;
2235 if (!(hostname
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2236 memcpy( hostname
, uc
.lpszHostName
, len
* sizeof(WCHAR
) );
2239 port
= uc
.nPort
? uc
.nPort
: (uc
.nScheme
== INTERNET_SCHEME_HTTPS
? 443 : 80);
2240 if (strcmpiW( connect
->hostname
, hostname
) || connect
->serverport
!= port
)
2242 heap_free( connect
->hostname
);
2243 connect
->hostname
= hostname
;
2244 connect
->hostport
= port
;
2245 if (!(ret
= set_server_for_hostname( connect
, hostname
, port
))) goto end
;
2247 netconn_close( &request
->netconn
);
2248 if (!(ret
= netconn_init( &request
->netconn
))) goto end
;
2249 request
->read_pos
= request
->read_size
= 0;
2250 request
->read_chunked
= FALSE
;
2251 request
->read_chunked_eof
= FALSE
;
2253 if (!(ret
= add_host_header( request
, WINHTTP_ADDREQ_FLAG_REPLACE
))) goto end
;
2254 if (!(ret
= open_connection( request
))) goto end
;
2256 heap_free( request
->path
);
2257 request
->path
= NULL
;
2258 if (uc
.dwUrlPathLength
)
2260 len
= uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
;
2261 if (!(request
->path
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2262 strcpyW( request
->path
, uc
.lpszUrlPath
);
2264 else request
->path
= strdupW( slashW
);
2267 /* remove content-type/length headers */
2268 if ((index
= get_header_index( request
, attr_content_type
, 0, TRUE
)) >= 0) delete_header( request
, index
);
2269 if ((index
= get_header_index( request
, attr_content_length
, 0, TRUE
)) >= 0 ) delete_header( request
, index
);
2271 if (status
!= HTTP_STATUS_REDIRECT_KEEP_VERB
&& !strcmpW( request
->verb
, postW
))
2273 heap_free( request
->verb
);
2274 request
->verb
= strdupW( getW
);
2275 request
->optional
= NULL
;
2276 request
->optional_len
= 0;
2281 if (!ret
) heap_free( hostname
);
2282 heap_free( location
);
2286 static BOOL
receive_response( request_t
*request
, BOOL async
)
2289 DWORD size
, query
, status
;
2293 if (!(ret
= read_reply( request
)))
2295 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE
);
2298 size
= sizeof(DWORD
);
2299 query
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
2300 if (!(ret
= query_headers( request
, query
, NULL
, &status
, &size
, NULL
))) break;
2302 set_content_length( request
);
2304 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
)) record_cookies( request
);
2306 if (status
== HTTP_STATUS_MOVED
|| status
== HTTP_STATUS_REDIRECT
|| status
== HTTP_STATUS_REDIRECT_KEEP_VERB
)
2308 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_REDIRECTS
||
2309 request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_NEVER
) break;
2311 if (!(ret
= handle_redirect( request
, status
))) break;
2313 /* recurse synchronously */
2314 send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
);
2317 else if (status
== HTTP_STATUS_DENIED
|| status
== HTTP_STATUS_PROXY_AUTH_REQ
)
2319 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_AUTHENTICATION
) break;
2321 drain_content( request
);
2322 if (!handle_authorization( request
, status
))
2327 /* recurse synchronously */
2328 send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
);
2334 if (ret
) refill_buffer( request
, FALSE
);
2338 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
, NULL
, 0 );
2341 WINHTTP_ASYNC_RESULT result
;
2342 result
.dwResult
= API_RECEIVE_RESPONSE
;
2343 result
.dwError
= get_last_error();
2344 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2350 static void task_receive_response( task_header_t
*task
)
2352 receive_response_t
*r
= (receive_response_t
*)task
;
2353 receive_response( r
->hdr
.request
, TRUE
);
2356 /***********************************************************************
2357 * WinHttpReceiveResponse (winhttp.@)
2359 BOOL WINAPI
WinHttpReceiveResponse( HINTERNET hrequest
, LPVOID reserved
)
2364 TRACE("%p, %p\n", hrequest
, reserved
);
2366 if (!(request
= (request_t
*)grab_object( hrequest
)))
2368 set_last_error( ERROR_INVALID_HANDLE
);
2371 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2373 release_object( &request
->hdr
);
2374 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2378 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2380 receive_response_t
*r
;
2382 if (!(r
= heap_alloc( sizeof(receive_response_t
) ))) return FALSE
;
2383 r
->hdr
.request
= request
;
2384 r
->hdr
.proc
= task_receive_response
;
2386 addref_object( &request
->hdr
);
2387 ret
= queue_task( (task_header_t
*)r
);
2390 ret
= receive_response( request
, FALSE
);
2392 release_object( &request
->hdr
);
2396 static BOOL
query_data_available( request_t
*request
, DWORD
*available
, BOOL async
)
2398 DWORD count
= get_available_data( request
);
2400 if (!request
->read_chunked
)
2401 count
+= netconn_query_data_available( &request
->netconn
);
2404 refill_buffer( request
, async
);
2405 count
= get_available_data( request
);
2406 if (!request
->read_chunked
)
2407 count
+= netconn_query_data_available( &request
->netconn
);
2410 if (async
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
, &count
, sizeof(count
) );
2411 TRACE("%u bytes available\n", count
);
2412 if (available
) *available
= count
;
2416 static void task_query_data_available( task_header_t
*task
)
2418 query_data_t
*q
= (query_data_t
*)task
;
2419 query_data_available( q
->hdr
.request
, q
->available
, TRUE
);
2422 /***********************************************************************
2423 * WinHttpQueryDataAvailable (winhttp.@)
2425 BOOL WINAPI
WinHttpQueryDataAvailable( HINTERNET hrequest
, LPDWORD available
)
2430 TRACE("%p, %p\n", hrequest
, available
);
2432 if (!(request
= (request_t
*)grab_object( hrequest
)))
2434 set_last_error( ERROR_INVALID_HANDLE
);
2437 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2439 release_object( &request
->hdr
);
2440 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2444 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2448 if (!(q
= heap_alloc( sizeof(query_data_t
) ))) return FALSE
;
2449 q
->hdr
.request
= request
;
2450 q
->hdr
.proc
= task_query_data_available
;
2451 q
->available
= available
;
2453 addref_object( &request
->hdr
);
2454 ret
= queue_task( (task_header_t
*)q
);
2457 ret
= query_data_available( request
, available
, FALSE
);
2459 release_object( &request
->hdr
);
2463 static void task_read_data( task_header_t
*task
)
2465 read_data_t
*r
= (read_data_t
*)task
;
2466 read_data( r
->hdr
.request
, r
->buffer
, r
->to_read
, r
->read
, TRUE
);
2469 /***********************************************************************
2470 * WinHttpReadData (winhttp.@)
2472 BOOL WINAPI
WinHttpReadData( HINTERNET hrequest
, LPVOID buffer
, DWORD to_read
, LPDWORD read
)
2477 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_read
, read
);
2479 if (!(request
= (request_t
*)grab_object( hrequest
)))
2481 set_last_error( ERROR_INVALID_HANDLE
);
2484 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2486 release_object( &request
->hdr
);
2487 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2491 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2495 if (!(r
= heap_alloc( sizeof(read_data_t
) ))) return FALSE
;
2496 r
->hdr
.request
= request
;
2497 r
->hdr
.proc
= task_read_data
;
2499 r
->to_read
= to_read
;
2502 addref_object( &request
->hdr
);
2503 ret
= queue_task( (task_header_t
*)r
);
2506 ret
= read_data( request
, buffer
, to_read
, read
, FALSE
);
2508 release_object( &request
->hdr
);
2512 static BOOL
write_data( request_t
*request
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
, BOOL async
)
2517 ret
= netconn_send( &request
->netconn
, buffer
, to_write
, &num_bytes
);
2521 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
, &num_bytes
, sizeof(num_bytes
) );
2524 WINHTTP_ASYNC_RESULT result
;
2525 result
.dwResult
= API_WRITE_DATA
;
2526 result
.dwError
= get_last_error();
2527 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2530 if (ret
&& written
) *written
= num_bytes
;
2534 static void task_write_data( task_header_t
*task
)
2536 write_data_t
*w
= (write_data_t
*)task
;
2537 write_data( w
->hdr
.request
, w
->buffer
, w
->to_write
, w
->written
, TRUE
);
2540 /***********************************************************************
2541 * WinHttpWriteData (winhttp.@)
2543 BOOL WINAPI
WinHttpWriteData( HINTERNET hrequest
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
)
2548 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_write
, written
);
2550 if (!(request
= (request_t
*)grab_object( hrequest
)))
2552 set_last_error( ERROR_INVALID_HANDLE
);
2555 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2557 release_object( &request
->hdr
);
2558 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2562 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2566 if (!(w
= heap_alloc( sizeof(write_data_t
) ))) return FALSE
;
2567 w
->hdr
.request
= request
;
2568 w
->hdr
.proc
= task_write_data
;
2570 w
->to_write
= to_write
;
2571 w
->written
= written
;
2573 addref_object( &request
->hdr
);
2574 ret
= queue_task( (task_header_t
*)w
);
2577 ret
= write_data( request
, buffer
, to_write
, written
, FALSE
);
2579 release_object( &request
->hdr
);
2585 REQUEST_STATE_UNINITIALIZED
,
2586 REQUEST_STATE_INITIALIZED
,
2587 REQUEST_STATE_CANCELLED
,
2590 REQUEST_STATE_RESPONSE_RECEIVED
2593 struct winhttp_request
2595 IWinHttpRequest IWinHttpRequest_iface
;
2597 CRITICAL_SECTION cs
;
2598 enum request_state state
;
2609 DWORD bytes_available
;
2613 DWORD disable_feature
;
2614 LONG resolve_timeout
;
2615 LONG connect_timeout
;
2617 LONG receive_timeout
;
2618 WINHTTP_PROXY_INFO proxy
;
2621 static inline struct winhttp_request
*impl_from_IWinHttpRequest( IWinHttpRequest
*iface
)
2623 return CONTAINING_RECORD( iface
, struct winhttp_request
, IWinHttpRequest_iface
);
2626 static ULONG WINAPI
winhttp_request_AddRef(
2627 IWinHttpRequest
*iface
)
2629 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2630 return InterlockedIncrement( &request
->refs
);
2633 /* critical section must be held */
2634 static void cancel_request( struct winhttp_request
*request
)
2636 if (request
->state
<= REQUEST_STATE_CANCELLED
) return;
2637 if (request
->thread
) SetEvent( request
->cancel
);
2638 request
->state
= REQUEST_STATE_CANCELLED
;
2641 /* critical section must be held */
2642 static void free_request( struct winhttp_request
*request
)
2644 if (request
->state
< REQUEST_STATE_INITIALIZED
) return;
2645 WinHttpCloseHandle( request
->hrequest
);
2646 WinHttpCloseHandle( request
->hconnect
);
2647 WinHttpCloseHandle( request
->hsession
);
2648 CloseHandle( request
->thread
);
2649 CloseHandle( request
->wait
);
2650 CloseHandle( request
->cancel
);
2651 heap_free( request
->proxy
.lpszProxy
);
2652 heap_free( request
->proxy
.lpszProxyBypass
);
2653 heap_free( request
->buffer
);
2654 heap_free( request
->verb
);
2655 VariantClear( &request
->data
);
2658 static ULONG WINAPI
winhttp_request_Release(
2659 IWinHttpRequest
*iface
)
2661 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2662 LONG refs
= InterlockedDecrement( &request
->refs
);
2665 TRACE("destroying %p\n", request
);
2667 EnterCriticalSection( &request
->cs
);
2668 cancel_request( request
);
2669 free_request( request
);
2670 LeaveCriticalSection( &request
->cs
);
2671 request
->cs
.DebugInfo
->Spare
[0] = 0;
2672 DeleteCriticalSection( &request
->cs
);
2673 heap_free( request
);
2678 static HRESULT WINAPI
winhttp_request_QueryInterface(
2679 IWinHttpRequest
*iface
,
2683 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2685 TRACE("%p, %s, %p\n", request
, debugstr_guid(riid
), obj
);
2687 if (IsEqualGUID( riid
, &IID_IWinHttpRequest
) ||
2688 IsEqualGUID( riid
, &IID_IDispatch
) ||
2689 IsEqualGUID( riid
, &IID_IUnknown
))
2695 FIXME("interface %s not implemented\n", debugstr_guid(riid
));
2696 return E_NOINTERFACE
;
2698 IWinHttpRequest_AddRef( iface
);
2702 static HRESULT WINAPI
winhttp_request_GetTypeInfoCount(
2703 IWinHttpRequest
*iface
,
2706 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2708 TRACE("%p, %p\n", request
, count
);
2715 IWinHttpRequest_tid
,
2719 static ITypeLib
*winhttp_typelib
;
2720 static ITypeInfo
*winhttp_typeinfo
[last_tid
];
2722 static REFIID winhttp_tid_id
[] =
2724 &IID_IWinHttpRequest
2727 static HRESULT
get_typeinfo( enum type_id tid
, ITypeInfo
**ret
)
2731 if (!winhttp_typelib
)
2735 hr
= LoadRegTypeLib( &LIBID_WinHttp
, 5, 1, LOCALE_SYSTEM_DEFAULT
, &typelib
);
2738 ERR("LoadRegTypeLib failed: %08x\n", hr
);
2741 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib
, typelib
, NULL
))
2742 ITypeLib_Release( typelib
);
2744 if (!winhttp_typeinfo
[tid
])
2746 ITypeInfo
*typeinfo
;
2748 hr
= ITypeLib_GetTypeInfoOfGuid( winhttp_typelib
, winhttp_tid_id
[tid
], &typeinfo
);
2751 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id
[tid
]), hr
);
2754 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo
+ tid
), typeinfo
, NULL
))
2755 ITypeInfo_Release( typeinfo
);
2757 *ret
= winhttp_typeinfo
[tid
];
2761 static HRESULT WINAPI
winhttp_request_GetTypeInfo(
2762 IWinHttpRequest
*iface
,
2767 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2768 TRACE("%p, %u, %u, %p\n", request
, index
, lcid
, info
);
2770 return get_typeinfo( IWinHttpRequest_tid
, info
);
2773 static HRESULT WINAPI
winhttp_request_GetIDsOfNames(
2774 IWinHttpRequest
*iface
,
2781 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2782 ITypeInfo
*typeinfo
;
2785 TRACE("%p, %s, %p, %u, %u, %p\n", request
, debugstr_guid(riid
), names
, count
, lcid
, dispid
);
2787 if (!names
|| !count
|| !dispid
) return E_INVALIDARG
;
2789 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
2792 hr
= ITypeInfo_GetIDsOfNames( typeinfo
, names
, count
, dispid
);
2793 ITypeInfo_Release( typeinfo
);
2798 static HRESULT WINAPI
winhttp_request_Invoke(
2799 IWinHttpRequest
*iface
,
2806 EXCEPINFO
*excep_info
,
2809 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2810 ITypeInfo
*typeinfo
;
2813 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request
, member
, debugstr_guid(riid
),
2814 lcid
, flags
, params
, result
, excep_info
, arg_err
);
2816 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
2819 hr
= ITypeInfo_Invoke( typeinfo
, &request
->IWinHttpRequest_iface
, member
, flags
,
2820 params
, result
, excep_info
, arg_err
);
2821 ITypeInfo_Release( typeinfo
);
2826 static HRESULT WINAPI
winhttp_request_SetProxy(
2827 IWinHttpRequest
*iface
,
2828 HTTPREQUEST_PROXY_SETTING proxy_setting
,
2829 VARIANT proxy_server
,
2830 VARIANT bypass_list
)
2832 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2833 DWORD err
= ERROR_SUCCESS
;
2835 TRACE("%p, %u, %s, %s\n", request
, proxy_setting
, debugstr_variant(&proxy_server
),
2836 debugstr_variant(&bypass_list
));
2838 EnterCriticalSection( &request
->cs
);
2839 switch (proxy_setting
)
2841 case HTTPREQUEST_PROXYSETTING_DEFAULT
:
2842 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
2843 heap_free( request
->proxy
.lpszProxy
);
2844 heap_free( request
->proxy
.lpszProxyBypass
);
2845 request
->proxy
.lpszProxy
= NULL
;
2846 request
->proxy
.lpszProxyBypass
= NULL
;
2849 case HTTPREQUEST_PROXYSETTING_DIRECT
:
2850 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NO_PROXY
;
2851 heap_free( request
->proxy
.lpszProxy
);
2852 heap_free( request
->proxy
.lpszProxyBypass
);
2853 request
->proxy
.lpszProxy
= NULL
;
2854 request
->proxy
.lpszProxyBypass
= NULL
;
2857 case HTTPREQUEST_PROXYSETTING_PROXY
:
2858 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
2859 if (V_VT( &proxy_server
) == VT_BSTR
)
2861 heap_free( request
->proxy
.lpszProxy
);
2862 request
->proxy
.lpszProxy
= strdupW( V_BSTR( &proxy_server
) );
2864 if (V_VT( &bypass_list
) == VT_BSTR
)
2866 heap_free( request
->proxy
.lpszProxyBypass
);
2867 request
->proxy
.lpszProxyBypass
= strdupW( V_BSTR( &bypass_list
) );
2872 err
= ERROR_INVALID_PARAMETER
;
2875 LeaveCriticalSection( &request
->cs
);
2876 return HRESULT_FROM_WIN32( err
);
2879 static HRESULT WINAPI
winhttp_request_SetCredentials(
2880 IWinHttpRequest
*iface
,
2883 HTTPREQUEST_SETCREDENTIALS_FLAGS flags
)
2885 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2886 DWORD target
, scheme
= WINHTTP_AUTH_SCHEME_BASIC
; /* FIXME: query supported schemes */
2887 DWORD err
= ERROR_SUCCESS
;
2889 TRACE("%p, %s, %p\n", request
, debugstr_w(username
), password
);
2891 EnterCriticalSection( &request
->cs
);
2892 if (request
->state
< REQUEST_STATE_OPEN
)
2894 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
2899 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
:
2900 target
= WINHTTP_AUTH_TARGET_SERVER
;
2902 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY
:
2903 target
= WINHTTP_AUTH_TARGET_PROXY
;
2906 err
= ERROR_INVALID_PARAMETER
;
2909 if (!WinHttpSetCredentials( request
->hrequest
, target
, scheme
, username
, password
, NULL
))
2911 err
= get_last_error();
2914 LeaveCriticalSection( &request
->cs
);
2915 return HRESULT_FROM_WIN32( err
);
2918 static void initialize_request( struct winhttp_request
*request
)
2920 request
->hrequest
= NULL
;
2921 request
->hconnect
= NULL
;
2922 request
->hsession
= NULL
;
2923 request
->thread
= NULL
;
2924 request
->wait
= NULL
;
2925 request
->cancel
= NULL
;
2926 request
->buffer
= NULL
;
2927 request
->verb
= NULL
;
2928 request
->offset
= 0;
2929 request
->bytes_available
= 0;
2930 request
->bytes_read
= 0;
2931 request
->error
= ERROR_SUCCESS
;
2932 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
2933 request
->disable_feature
= WINHTTP_DISABLE_AUTHENTICATION
;
2934 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
2935 request
->proxy
.lpszProxy
= NULL
;
2936 request
->proxy
.lpszProxyBypass
= NULL
;
2937 request
->resolve_timeout
= 0;
2938 request
->connect_timeout
= 60000;
2939 request
->send_timeout
= 30000;
2940 request
->receive_timeout
= 30000;
2941 VariantInit( &request
->data
);
2942 request
->state
= REQUEST_STATE_INITIALIZED
;
2945 static HRESULT WINAPI
winhttp_request_Open(
2946 IWinHttpRequest
*iface
,
2951 static const WCHAR typeW
[] = {'*','/','*',0};
2952 static const WCHAR
*acceptW
[] = {typeW
, NULL
};
2953 static const WCHAR httpsW
[] = {'h','t','t','p','s'};
2954 static const WCHAR user_agentW
[] = {
2955 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
2956 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
2957 'R','e','q','u','e','s','t','.','5',')',0};
2958 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2959 HINTERNET hsession
= NULL
, hconnect
= NULL
, hrequest
;
2961 WCHAR
*hostname
, *path
= NULL
, *verb
= NULL
;
2962 DWORD err
= ERROR_OUTOFMEMORY
, len
, flags
= 0, request_flags
= 0;
2964 TRACE("%p, %s, %s, %s\n", request
, debugstr_w(method
), debugstr_w(url
),
2965 debugstr_variant(&async
));
2967 if (!method
|| !url
) return E_INVALIDARG
;
2969 memset( &uc
, 0, sizeof(uc
) );
2970 uc
.dwStructSize
= sizeof(uc
);
2971 uc
.dwSchemeLength
= ~0u;
2972 uc
.dwHostNameLength
= ~0u;
2973 uc
.dwUrlPathLength
= ~0u;
2974 uc
.dwExtraInfoLength
= ~0u;
2975 if (!WinHttpCrackUrl( url
, 0, 0, &uc
)) return HRESULT_FROM_WIN32( get_last_error() );
2977 EnterCriticalSection( &request
->cs
);
2978 if (request
->state
!= REQUEST_STATE_INITIALIZED
)
2980 cancel_request( request
);
2981 free_request( request
);
2982 initialize_request( request
);
2984 if (!(hostname
= heap_alloc( (uc
.dwHostNameLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
2985 memcpy( hostname
, uc
.lpszHostName
, uc
.dwHostNameLength
* sizeof(WCHAR
) );
2986 hostname
[uc
.dwHostNameLength
] = 0;
2988 if (!(path
= heap_alloc( (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
2989 memcpy( path
, uc
.lpszUrlPath
, (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
) * sizeof(WCHAR
) );
2990 path
[uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
] = 0;
2992 if (!(verb
= strdupW( method
))) goto error
;
2993 if (V_BOOL( &async
)) flags
|= WINHTTP_FLAG_ASYNC
;
2994 if (!(hsession
= WinHttpOpen( user_agentW
, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
, NULL
, NULL
, flags
)))
2996 err
= get_last_error();
2999 if (!(hconnect
= WinHttpConnect( hsession
, hostname
, uc
.nPort
, 0 )))
3001 err
= get_last_error();
3004 len
= sizeof(httpsW
) / sizeof(WCHAR
);
3005 if (uc
.dwSchemeLength
== len
&& !memcmp( uc
.lpszScheme
, httpsW
, len
* sizeof(WCHAR
) ))
3007 request_flags
|= WINHTTP_FLAG_SECURE
;
3009 if (!(hrequest
= WinHttpOpenRequest( hconnect
, method
, path
, NULL
, NULL
, acceptW
, request_flags
)))
3011 err
= get_last_error();
3014 if (flags
& WINHTTP_FLAG_ASYNC
)
3016 request
->wait
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
3017 request
->cancel
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
3018 WinHttpSetOption( hrequest
, WINHTTP_OPTION_CONTEXT_VALUE
, &request
, sizeof(request
) );
3020 request
->state
= REQUEST_STATE_OPEN
;
3021 request
->hsession
= hsession
;
3022 request
->hconnect
= hconnect
;
3023 request
->hrequest
= hrequest
;
3024 request
->verb
= verb
;
3025 heap_free( hostname
);
3027 LeaveCriticalSection( &request
->cs
);
3031 WinHttpCloseHandle( hconnect
);
3032 WinHttpCloseHandle( hsession
);
3033 heap_free( hostname
);
3036 LeaveCriticalSection( &request
->cs
);
3037 return HRESULT_FROM_WIN32( err
);
3040 static HRESULT WINAPI
winhttp_request_SetRequestHeader(
3041 IWinHttpRequest
*iface
,
3045 static const WCHAR fmtW
[] = {'%','s',':',' ','%','s','\r','\n',0};
3046 static const WCHAR emptyW
[] = {0};
3047 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3048 DWORD len
, err
= ERROR_SUCCESS
;
3051 TRACE("%p, %s, %s\n", request
, debugstr_w(header
), debugstr_w(value
));
3053 if (!header
) return E_INVALIDARG
;
3055 EnterCriticalSection( &request
->cs
);
3056 if (request
->state
< REQUEST_STATE_OPEN
)
3058 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
3061 if (request
->state
>= REQUEST_STATE_SENT
)
3063 err
= ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND
;
3066 len
= strlenW( header
) + 4;
3067 if (value
) len
+= strlenW( value
);
3068 if (!(str
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
3070 err
= ERROR_OUTOFMEMORY
;
3073 sprintfW( str
, fmtW
, header
, value
? value
: emptyW
);
3074 if (!WinHttpAddRequestHeaders( request
->hrequest
, str
, len
, WINHTTP_ADDREQ_FLAG_REPLACE
))
3076 err
= get_last_error();
3081 LeaveCriticalSection( &request
->cs
);
3082 return HRESULT_FROM_WIN32( err
);
3085 static HRESULT WINAPI
winhttp_request_GetResponseHeader(
3086 IWinHttpRequest
*iface
,
3090 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3091 DWORD size
, err
= ERROR_SUCCESS
;
3093 TRACE("%p, %p\n", request
, header
);
3095 EnterCriticalSection( &request
->cs
);
3096 if (request
->state
< REQUEST_STATE_SENT
)
3098 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3101 if (!header
|| !value
)
3103 err
= ERROR_INVALID_PARAMETER
;
3107 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, NULL
, &size
, NULL
))
3109 err
= get_last_error();
3110 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3112 if (!(*value
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
3114 err
= ERROR_OUTOFMEMORY
;
3117 err
= ERROR_SUCCESS
;
3118 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, *value
, &size
, NULL
))
3120 err
= get_last_error();
3121 SysFreeString( *value
);
3124 LeaveCriticalSection( &request
->cs
);
3125 return HRESULT_FROM_WIN32( err
);
3128 static HRESULT WINAPI
winhttp_request_GetAllResponseHeaders(
3129 IWinHttpRequest
*iface
,
3132 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3133 DWORD size
, err
= ERROR_SUCCESS
;
3135 TRACE("%p, %p\n", request
, headers
);
3137 if (!headers
) return E_INVALIDARG
;
3139 EnterCriticalSection( &request
->cs
);
3140 if (request
->state
< REQUEST_STATE_SENT
)
3142 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3146 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, NULL
, &size
, NULL
))
3148 err
= get_last_error();
3149 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3151 if (!(*headers
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
3153 err
= ERROR_OUTOFMEMORY
;
3156 err
= ERROR_SUCCESS
;
3157 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, *headers
, &size
, NULL
))
3159 err
= get_last_error();
3160 SysFreeString( *headers
);
3163 LeaveCriticalSection( &request
->cs
);
3164 return HRESULT_FROM_WIN32( err
);
3167 static void CALLBACK
wait_status_callback( HINTERNET handle
, DWORD_PTR context
, DWORD status
, LPVOID buffer
, DWORD size
)
3169 struct winhttp_request
*request
= (struct winhttp_request
*)context
;
3173 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
:
3174 request
->bytes_available
= *(DWORD
*)buffer
;
3175 request
->error
= ERROR_SUCCESS
;
3177 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE
:
3178 request
->bytes_read
= size
;
3179 request
->error
= ERROR_SUCCESS
;
3181 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
:
3183 WINHTTP_ASYNC_RESULT
*result
= (WINHTTP_ASYNC_RESULT
*)buffer
;
3184 request
->error
= result
->dwError
;
3189 SetEvent( request
->wait
);
3192 static void wait_set_status_callback( struct winhttp_request
*request
, DWORD status
)
3194 if (!request
->wait
) return;
3195 status
|= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
;
3196 WinHttpSetStatusCallback( request
->hrequest
, wait_status_callback
, status
, 0 );
3199 static DWORD
wait_for_completion( struct winhttp_request
*request
)
3205 request
->error
= ERROR_SUCCESS
;
3206 return ERROR_SUCCESS
;
3208 handles
[0] = request
->wait
;
3209 handles
[1] = request
->cancel
;
3210 switch (WaitForMultipleObjects( 2, handles
, FALSE
, INFINITE
))
3214 case WAIT_OBJECT_0
+ 1:
3215 request
->error
= ERROR_CANCELLED
;
3218 request
->error
= get_last_error();
3221 return request
->error
;
3224 static HRESULT
request_receive( struct winhttp_request
*request
)
3226 DWORD err
, size
, buflen
= 4096;
3228 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
);
3229 if (!WinHttpReceiveResponse( request
->hrequest
, NULL
))
3231 return HRESULT_FROM_WIN32( get_last_error() );
3233 if ((err
= wait_for_completion( request
))) return HRESULT_FROM_WIN32( err
);
3234 if (!strcmpW( request
->verb
, headW
))
3236 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
3239 if (!(request
->buffer
= heap_alloc( buflen
))) return E_OUTOFMEMORY
;
3240 request
->buffer
[0] = 0;
3244 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
);
3245 if (!WinHttpQueryDataAvailable( request
->hrequest
, &request
->bytes_available
))
3247 err
= get_last_error();
3250 if ((err
= wait_for_completion( request
))) goto error
;
3251 if (!request
->bytes_available
) break;
3252 size
+= request
->bytes_available
;
3256 while (buflen
< size
) buflen
*= 2;
3257 if (!(tmp
= heap_realloc( request
->buffer
, buflen
)))
3259 err
= ERROR_OUTOFMEMORY
;
3262 request
->buffer
= tmp
;
3264 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
);
3265 if (!WinHttpReadData( request
->hrequest
, request
->buffer
+ request
->offset
,
3266 request
->bytes_available
, &request
->bytes_read
))
3268 err
= get_last_error();
3271 if ((err
= wait_for_completion( request
))) goto error
;
3272 request
->offset
+= request
->bytes_read
;
3273 } while (request
->bytes_read
);
3275 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
3279 heap_free( request
->buffer
);
3280 request
->buffer
= NULL
;
3281 return HRESULT_FROM_WIN32( err
);
3284 static DWORD
request_set_parameters( struct winhttp_request
*request
)
3286 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_PROXY
, &request
->proxy
,
3287 sizeof(request
->proxy
) )) return get_last_error();
3289 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_AUTOLOGON_POLICY
, &request
->logon_policy
,
3290 sizeof(request
->logon_policy
) )) return get_last_error();
3292 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_DISABLE_FEATURE
, &request
->disable_feature
,
3293 sizeof(request
->disable_feature
) )) return get_last_error();
3295 if (!WinHttpSetTimeouts( request
->hrequest
,
3296 request
->resolve_timeout
,
3297 request
->connect_timeout
,
3298 request
->send_timeout
,
3299 request
->receive_timeout
)) return get_last_error();
3300 return ERROR_SUCCESS
;
3303 static void request_set_utf8_content_type( struct winhttp_request
*request
)
3305 static const WCHAR fmtW
[] = {'%','s',':',' ','%','s',0};
3306 static const WCHAR text_plainW
[] = {'t','e','x','t','/','p','l','a','i','n',0};
3307 static const WCHAR charset_utf8W
[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3311 len
= sprintfW( headerW
, fmtW
, attr_content_type
, text_plainW
);
3312 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
3313 len
= sprintfW( headerW
, fmtW
, attr_content_type
, charset_utf8W
);
3314 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
);
3317 static HRESULT
request_send( struct winhttp_request
*request
)
3319 SAFEARRAY
*sa
= NULL
;
3326 if ((err
= request_set_parameters( request
))) return HRESULT_FROM_WIN32( err
);
3327 if (strcmpW( request
->verb
, getW
))
3329 VariantInit( &data
);
3330 if (V_VT( &request
->data
) == VT_BSTR
)
3333 const WCHAR
*str
= V_BSTR( &request
->data
);
3334 int i
, len
= strlenW( str
);
3336 for (i
= 0; i
< len
; i
++)
3344 size
= WideCharToMultiByte( cp
, 0, str
, len
, NULL
, 0, NULL
, NULL
);
3345 if (!(ptr
= heap_alloc( size
))) return E_OUTOFMEMORY
;
3346 WideCharToMultiByte( cp
, 0, str
, len
, ptr
, size
, NULL
, NULL
);
3347 if (cp
== CP_UTF8
) request_set_utf8_content_type( request
);
3349 else if (VariantChangeType( &data
, &request
->data
, 0, VT_ARRAY
|VT_UI1
) == S_OK
)
3351 sa
= V_ARRAY( &data
);
3352 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
) return hr
;
3353 if ((hr
= SafeArrayGetUBound( sa
, 1, &size
) != S_OK
))
3355 SafeArrayUnaccessData( sa
);
3361 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
);
3362 if (!WinHttpSendRequest( request
->hrequest
, NULL
, 0, ptr
, size
, size
, 0 ))
3364 err
= get_last_error();
3367 if ((err
= wait_for_completion( request
))) goto error
;
3368 if (sa
) SafeArrayUnaccessData( sa
);
3369 else heap_free( ptr
);
3370 request
->state
= REQUEST_STATE_SENT
;
3374 if (sa
) SafeArrayUnaccessData( sa
);
3375 else heap_free( ptr
);
3376 return HRESULT_FROM_WIN32( err
);
3379 static HRESULT
request_send_and_receive( struct winhttp_request
*request
)
3381 HRESULT hr
= request_send( request
);
3382 if (hr
== S_OK
) hr
= request_receive( request
);
3386 static DWORD CALLBACK
send_and_receive_proc( void *arg
)
3388 struct winhttp_request
*request
= (struct winhttp_request
*)arg
;
3389 return request_send_and_receive( request
);
3392 static HRESULT WINAPI
winhttp_request_Send(
3393 IWinHttpRequest
*iface
,
3396 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3399 TRACE("%p, %s\n", request
, debugstr_variant(&body
));
3401 EnterCriticalSection( &request
->cs
);
3402 if (request
->state
< REQUEST_STATE_OPEN
)
3404 LeaveCriticalSection( &request
->cs
);
3405 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
);
3407 if (request
->state
>= REQUEST_STATE_SENT
)
3409 LeaveCriticalSection( &request
->cs
);
3412 VariantClear( &request
->data
);
3413 if ((hr
= VariantCopyInd( &request
->data
, &body
)) != S_OK
) {
3414 LeaveCriticalSection( &request
->cs
);
3418 if (request
->wait
) /* async request */
3420 if (!(request
->thread
= CreateThread( NULL
, 0, send_and_receive_proc
, request
, 0, NULL
)))
3422 LeaveCriticalSection( &request
->cs
);
3423 return HRESULT_FROM_WIN32( get_last_error() );
3426 else hr
= request_send_and_receive( request
);
3427 LeaveCriticalSection( &request
->cs
);
3431 static HRESULT WINAPI
winhttp_request_get_Status(
3432 IWinHttpRequest
*iface
,
3435 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3436 DWORD err
= ERROR_SUCCESS
, flags
, status_code
, len
= sizeof(status_code
), index
= 0;
3438 TRACE("%p, %p\n", request
, status
);
3440 if (!status
) return E_INVALIDARG
;
3442 EnterCriticalSection( &request
->cs
);
3443 if (request
->state
< REQUEST_STATE_SENT
)
3445 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3448 flags
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
3449 if (!WinHttpQueryHeaders( request
->hrequest
, flags
, NULL
, &status_code
, &len
, &index
))
3451 err
= get_last_error();
3454 *status
= status_code
;
3457 LeaveCriticalSection( &request
->cs
);
3458 return HRESULT_FROM_WIN32( err
);
3461 static HRESULT WINAPI
winhttp_request_get_StatusText(
3462 IWinHttpRequest
*iface
,
3465 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3466 DWORD err
= ERROR_SUCCESS
, len
= 0, index
= 0;
3468 TRACE("%p, %p\n", request
, status
);
3470 if (!status
) return E_INVALIDARG
;
3472 EnterCriticalSection( &request
->cs
);
3473 if (request
->state
< REQUEST_STATE_SENT
)
3475 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3478 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, NULL
, &len
, &index
))
3480 err
= get_last_error();
3481 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3483 if (!(*status
= SysAllocStringLen( NULL
, len
/ sizeof(WCHAR
) )))
3485 err
= ERROR_OUTOFMEMORY
;
3489 err
= ERROR_SUCCESS
;
3490 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, *status
, &len
, &index
))
3492 err
= get_last_error();
3493 SysFreeString( *status
);
3496 LeaveCriticalSection( &request
->cs
);
3497 return HRESULT_FROM_WIN32( err
);
3500 static DWORD
request_get_codepage( struct winhttp_request
*request
, UINT
*codepage
)
3502 static const WCHAR utf8W
[] = {'u','t','f','-','8',0};
3503 static const WCHAR charsetW
[] = {'c','h','a','r','s','e','t',0};
3508 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, NULL
, &size
, NULL
) &&
3509 get_last_error() == ERROR_INSUFFICIENT_BUFFER
)
3511 if (!(buffer
= heap_alloc( size
))) return ERROR_OUTOFMEMORY
;
3512 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, buffer
, &size
, NULL
))
3514 return get_last_error();
3516 if ((p
= strstrW( buffer
, charsetW
)))
3518 p
+= strlenW( charsetW
);
3519 while (*p
== ' ') p
++;
3522 while (*p
== ' ') p
++;
3523 if (!strcmpiW( p
, utf8W
)) *codepage
= CP_UTF8
;
3526 heap_free( buffer
);
3528 return ERROR_SUCCESS
;
3531 static HRESULT WINAPI
winhttp_request_get_ResponseText(
3532 IWinHttpRequest
*iface
,
3535 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3537 DWORD err
= ERROR_SUCCESS
;
3540 TRACE("%p, %p\n", request
, body
);
3542 if (!body
) return E_INVALIDARG
;
3544 EnterCriticalSection( &request
->cs
);
3545 if (request
->state
< REQUEST_STATE_SENT
)
3547 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3550 if ((err
= request_get_codepage( request
, &codepage
))) goto done
;
3551 len
= MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, NULL
, 0 );
3552 if (!(*body
= SysAllocStringLen( NULL
, len
)))
3554 err
= ERROR_OUTOFMEMORY
;
3557 MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, *body
, len
);
3561 LeaveCriticalSection( &request
->cs
);
3562 return HRESULT_FROM_WIN32( err
);
3565 static HRESULT WINAPI
winhttp_request_get_ResponseBody(
3566 IWinHttpRequest
*iface
,
3569 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3572 DWORD err
= ERROR_SUCCESS
;
3575 TRACE("%p, %p\n", request
, body
);
3577 if (!body
) return E_INVALIDARG
;
3579 EnterCriticalSection( &request
->cs
);
3580 if (!(sa
= SafeArrayCreateVector( VT_UI1
, 0, request
->offset
)))
3582 err
= ERROR_OUTOFMEMORY
;
3585 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
)
3587 SafeArrayDestroy( sa
);
3588 LeaveCriticalSection( &request
->cs
);
3591 memcpy( ptr
, request
->buffer
, request
->offset
);
3592 if ((hr
= SafeArrayUnaccessData( sa
)) != S_OK
)
3594 SafeArrayDestroy( sa
);
3595 LeaveCriticalSection( &request
->cs
);
3598 V_VT( body
) = VT_ARRAY
|VT_UI1
;
3599 V_ARRAY( body
) = sa
;
3602 LeaveCriticalSection( &request
->cs
);
3603 return HRESULT_FROM_WIN32( err
);
3606 static HRESULT WINAPI
winhttp_request_get_ResponseStream(
3607 IWinHttpRequest
*iface
,
3614 static HRESULT WINAPI
winhttp_request_get_Option(
3615 IWinHttpRequest
*iface
,
3616 WinHttpRequestOption option
,
3623 static HRESULT WINAPI
winhttp_request_put_Option(
3624 IWinHttpRequest
*iface
,
3625 WinHttpRequestOption option
,
3628 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3631 TRACE("%p, %u, %s\n", request
, option
, debugstr_variant(&value
));
3633 EnterCriticalSection( &request
->cs
);
3636 case WinHttpRequestOption_EnableRedirects
:
3638 if (V_BOOL( &value
))
3639 request
->disable_feature
&= ~WINHTTP_DISABLE_REDIRECTS
;
3641 request
->disable_feature
|= WINHTTP_DISABLE_REDIRECTS
;
3645 FIXME("unimplemented option %u\n", option
);
3649 LeaveCriticalSection( &request
->cs
);
3653 /* critical section must be held */
3654 static DWORD
wait_for_response( struct winhttp_request
*request
, DWORD timeout
)
3656 HANDLE thread
= request
->thread
;
3659 LeaveCriticalSection( &request
->cs
);
3660 while ((err
= MsgWaitForMultipleObjects( 1, &thread
, FALSE
, timeout
, QS_ALLINPUT
)) == WAIT_OBJECT_0
+ 1)
3663 while (PeekMessageW( &msg
, NULL
, 0, 0, PM_REMOVE
))
3665 TranslateMessage( &msg
);
3666 DispatchMessageW( &msg
);
3672 ret
= ERROR_SUCCESS
;
3675 ret
= ERROR_TIMEOUT
;
3679 ret
= get_last_error();
3682 EnterCriticalSection( &request
->cs
);
3686 static HRESULT WINAPI
winhttp_request_WaitForResponse(
3687 IWinHttpRequest
*iface
,
3689 VARIANT_BOOL
*succeeded
)
3691 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3692 DWORD err
, msecs
= (V_I4(&timeout
) == -1) ? INFINITE
: V_I4(&timeout
) * 1000;
3694 TRACE("%p, %s, %p\n", request
, debugstr_variant(&timeout
), succeeded
);
3696 EnterCriticalSection( &request
->cs
);
3697 if (!request
->thread
)
3699 LeaveCriticalSection( &request
->cs
);
3702 if (request
->state
>= REQUEST_STATE_RESPONSE_RECEIVED
)
3704 LeaveCriticalSection( &request
->cs
);
3707 switch ((err
= wait_for_response( request
, msecs
)))
3710 if (succeeded
) *succeeded
= VARIANT_FALSE
;
3711 err
= ERROR_SUCCESS
;
3715 if (succeeded
) *succeeded
= VARIANT_TRUE
;
3720 LeaveCriticalSection( &request
->cs
);
3721 return HRESULT_FROM_WIN32( err
);
3724 static HRESULT WINAPI
winhttp_request_Abort(
3725 IWinHttpRequest
*iface
)
3727 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3729 TRACE("%p\n", request
);
3731 EnterCriticalSection( &request
->cs
);
3732 cancel_request( request
);
3733 LeaveCriticalSection( &request
->cs
);
3737 static HRESULT WINAPI
winhttp_request_SetTimeouts(
3738 IWinHttpRequest
*iface
,
3739 LONG resolve_timeout
,
3740 LONG connect_timeout
,
3742 LONG receive_timeout
)
3744 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3746 TRACE("%p, %d, %d, %d, %d\n", request
, resolve_timeout
, connect_timeout
, send_timeout
, receive_timeout
);
3748 EnterCriticalSection( &request
->cs
);
3749 request
->resolve_timeout
= resolve_timeout
;
3750 request
->connect_timeout
= connect_timeout
;
3751 request
->send_timeout
= send_timeout
;
3752 request
->receive_timeout
= receive_timeout
;
3753 LeaveCriticalSection( &request
->cs
);
3757 static HRESULT WINAPI
winhttp_request_SetClientCertificate(
3758 IWinHttpRequest
*iface
,
3765 static HRESULT WINAPI
winhttp_request_SetAutoLogonPolicy(
3766 IWinHttpRequest
*iface
,
3767 WinHttpRequestAutoLogonPolicy policy
)
3769 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3772 TRACE("%p, %u\n", request
, policy
);
3774 EnterCriticalSection( &request
->cs
);
3777 case AutoLogonPolicy_Always
:
3778 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW
;
3780 case AutoLogonPolicy_OnlyIfBypassProxy
:
3781 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
3783 case AutoLogonPolicy_Never
:
3784 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH
;
3786 default: hr
= E_INVALIDARG
;
3789 LeaveCriticalSection( &request
->cs
);
3793 static const struct IWinHttpRequestVtbl winhttp_request_vtbl
=
3795 winhttp_request_QueryInterface
,
3796 winhttp_request_AddRef
,
3797 winhttp_request_Release
,
3798 winhttp_request_GetTypeInfoCount
,
3799 winhttp_request_GetTypeInfo
,
3800 winhttp_request_GetIDsOfNames
,
3801 winhttp_request_Invoke
,
3802 winhttp_request_SetProxy
,
3803 winhttp_request_SetCredentials
,
3804 winhttp_request_Open
,
3805 winhttp_request_SetRequestHeader
,
3806 winhttp_request_GetResponseHeader
,
3807 winhttp_request_GetAllResponseHeaders
,
3808 winhttp_request_Send
,
3809 winhttp_request_get_Status
,
3810 winhttp_request_get_StatusText
,
3811 winhttp_request_get_ResponseText
,
3812 winhttp_request_get_ResponseBody
,
3813 winhttp_request_get_ResponseStream
,
3814 winhttp_request_get_Option
,
3815 winhttp_request_put_Option
,
3816 winhttp_request_WaitForResponse
,
3817 winhttp_request_Abort
,
3818 winhttp_request_SetTimeouts
,
3819 winhttp_request_SetClientCertificate
,
3820 winhttp_request_SetAutoLogonPolicy
3823 HRESULT
WinHttpRequest_create( void **obj
)
3825 struct winhttp_request
*request
;
3829 if (!(request
= heap_alloc( sizeof(*request
) ))) return E_OUTOFMEMORY
;
3830 request
->IWinHttpRequest_iface
.lpVtbl
= &winhttp_request_vtbl
;
3832 request
->state
= REQUEST_STATE_UNINITIALIZED
;
3833 request
->proxy
.lpszProxy
= NULL
;
3834 request
->proxy
.lpszProxyBypass
= NULL
;
3835 InitializeCriticalSection( &request
->cs
);
3836 request
->cs
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": winhttp_request.cs");
3838 *obj
= &request
->IWinHttpRequest_iface
;
3839 TRACE("returning iface %p\n", *obj
);