2 * Copyright 2004 Mike McCormack for CodeWeavers
3 * Copyright 2006 Rob Shearman for CodeWeavers
4 * Copyright 2008, 2011 Hans Leidekker for CodeWeavers
5 * Copyright 2009 Juan Lang
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #define WIN32_NO_STATUS
24 #define COM_NO_WINDOWS_H
28 //#include "wine/port.h"
29 #include <wine/debug.h>
32 #ifdef HAVE_ARPA_INET_H
33 # include <arpa/inet.h>
39 //#include "initguid.h"
40 #include <httprequest.h>
43 #include "winhttp_private.h"
45 #include "inet_ntop.c"
47 WINE_DEFAULT_DEBUG_CHANNEL(winhttp
);
49 static const WCHAR attr_accept
[] = {'A','c','c','e','p','t',0};
50 static const WCHAR attr_accept_charset
[] = {'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0};
51 static const WCHAR attr_accept_encoding
[] = {'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0};
52 static const WCHAR attr_accept_language
[] = {'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0};
53 static const WCHAR attr_accept_ranges
[] = {'A','c','c','e','p','t','-','R','a','n','g','e','s',0};
54 static const WCHAR attr_age
[] = {'A','g','e',0};
55 static const WCHAR attr_allow
[] = {'A','l','l','o','w',0};
56 static const WCHAR attr_authorization
[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',0};
57 static const WCHAR attr_cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',0};
58 static const WCHAR attr_connection
[] = {'C','o','n','n','e','c','t','i','o','n',0};
59 static const WCHAR attr_content_base
[] = {'C','o','n','t','e','n','t','-','B','a','s','e',0};
60 static const WCHAR attr_content_encoding
[] = {'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0};
61 static const WCHAR attr_content_id
[] = {'C','o','n','t','e','n','t','-','I','D',0};
62 static const WCHAR attr_content_language
[] = {'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0};
63 static const WCHAR attr_content_length
[] = {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
64 static const WCHAR attr_content_location
[] = {'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0};
65 static const WCHAR attr_content_md5
[] = {'C','o','n','t','e','n','t','-','M','D','5',0};
66 static const WCHAR attr_content_range
[] = {'C','o','n','t','e','n','t','-','R','a','n','g','e',0};
67 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};
68 static const WCHAR attr_content_type
[] = {'C','o','n','t','e','n','t','-','T','y','p','e',0};
69 static const WCHAR attr_cookie
[] = {'C','o','o','k','i','e',0};
70 static const WCHAR attr_date
[] = {'D','a','t','e',0};
71 static const WCHAR attr_from
[] = {'F','r','o','m',0};
72 static const WCHAR attr_etag
[] = {'E','T','a','g',0};
73 static const WCHAR attr_expect
[] = {'E','x','p','e','c','t',0};
74 static const WCHAR attr_expires
[] = {'E','x','p','i','r','e','s',0};
75 static const WCHAR attr_host
[] = {'H','o','s','t',0};
76 static const WCHAR attr_if_match
[] = {'I','f','-','M','a','t','c','h',0};
77 static const WCHAR attr_if_modified_since
[] = {'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0};
78 static const WCHAR attr_if_none_match
[] = {'I','f','-','N','o','n','e','-','M','a','t','c','h',0};
79 static const WCHAR attr_if_range
[] = {'I','f','-','R','a','n','g','e',0};
80 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};
81 static const WCHAR attr_last_modified
[] = {'L','a','s','t','-','M','o','d','i','f','i','e','d',0};
82 static const WCHAR attr_location
[] = {'L','o','c','a','t','i','o','n',0};
83 static const WCHAR attr_max_forwards
[] = {'M','a','x','-','F','o','r','w','a','r','d','s',0};
84 static const WCHAR attr_mime_version
[] = {'M','i','m','e','-','V','e','r','s','i','o','n',0};
85 static const WCHAR attr_pragma
[] = {'P','r','a','g','m','a',0};
86 static const WCHAR attr_proxy_authenticate
[] = {'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
87 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};
88 static const WCHAR attr_proxy_connection
[] = {'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0};
89 static const WCHAR attr_public
[] = {'P','u','b','l','i','c',0};
90 static const WCHAR attr_range
[] = {'R','a','n','g','e',0};
91 static const WCHAR attr_referer
[] = {'R','e','f','e','r','e','r',0};
92 static const WCHAR attr_retry_after
[] = {'R','e','t','r','y','-','A','f','t','e','r',0};
93 static const WCHAR attr_server
[] = {'S','e','r','v','e','r',0};
94 static const WCHAR attr_set_cookie
[] = {'S','e','t','-','C','o','o','k','i','e',0};
95 static const WCHAR attr_status
[] = {'S','t','a','t','u','s',0};
96 static const WCHAR attr_transfer_encoding
[] = {'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0};
97 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};
98 static const WCHAR attr_upgrade
[] = {'U','p','g','r','a','d','e',0};
99 static const WCHAR attr_uri
[] = {'U','R','I',0};
100 static const WCHAR attr_user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',0};
101 static const WCHAR attr_vary
[] = {'V','a','r','y',0};
102 static const WCHAR attr_via
[] = {'V','i','a',0};
103 static const WCHAR attr_warning
[] = {'W','a','r','n','i','n','g',0};
104 static const WCHAR attr_www_authenticate
[] = {'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0};
106 static const WCHAR
*attribute_table
[] =
108 attr_mime_version
, /* WINHTTP_QUERY_MIME_VERSION = 0 */
109 attr_content_type
, /* WINHTTP_QUERY_CONTENT_TYPE = 1 */
110 attr_content_transfer_encoding
, /* WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
111 attr_content_id
, /* WINHTTP_QUERY_CONTENT_ID = 3 */
112 NULL
, /* WINHTTP_QUERY_CONTENT_DESCRIPTION = 4 */
113 attr_content_length
, /* WINHTTP_QUERY_CONTENT_LENGTH = 5 */
114 attr_content_language
, /* WINHTTP_QUERY_CONTENT_LANGUAGE = 6 */
115 attr_allow
, /* WINHTTP_QUERY_ALLOW = 7 */
116 attr_public
, /* WINHTTP_QUERY_PUBLIC = 8 */
117 attr_date
, /* WINHTTP_QUERY_DATE = 9 */
118 attr_expires
, /* WINHTTP_QUERY_EXPIRES = 10 */
119 attr_last_modified
, /* WINHTTP_QUERY_LAST_MODIFIEDcw = 11 */
120 NULL
, /* WINHTTP_QUERY_MESSAGE_ID = 12 */
121 attr_uri
, /* WINHTTP_QUERY_URI = 13 */
122 attr_from
, /* WINHTTP_QUERY_DERIVED_FROM = 14 */
123 NULL
, /* WINHTTP_QUERY_COST = 15 */
124 NULL
, /* WINHTTP_QUERY_LINK = 16 */
125 attr_pragma
, /* WINHTTP_QUERY_PRAGMA = 17 */
126 NULL
, /* WINHTTP_QUERY_VERSION = 18 */
127 attr_status
, /* WINHTTP_QUERY_STATUS_CODE = 19 */
128 NULL
, /* WINHTTP_QUERY_STATUS_TEXT = 20 */
129 NULL
, /* WINHTTP_QUERY_RAW_HEADERS = 21 */
130 NULL
, /* WINHTTP_QUERY_RAW_HEADERS_CRLF = 22 */
131 attr_connection
, /* WINHTTP_QUERY_CONNECTION = 23 */
132 attr_accept
, /* WINHTTP_QUERY_ACCEPT = 24 */
133 attr_accept_charset
, /* WINHTTP_QUERY_ACCEPT_CHARSET = 25 */
134 attr_accept_encoding
, /* WINHTTP_QUERY_ACCEPT_ENCODING = 26 */
135 attr_accept_language
, /* WINHTTP_QUERY_ACCEPT_LANGUAGE = 27 */
136 attr_authorization
, /* WINHTTP_QUERY_AUTHORIZATION = 28 */
137 attr_content_encoding
, /* WINHTTP_QUERY_CONTENT_ENCODING = 29 */
138 NULL
, /* WINHTTP_QUERY_FORWARDED = 30 */
139 NULL
, /* WINHTTP_QUERY_FROM = 31 */
140 attr_if_modified_since
, /* WINHTTP_QUERY_IF_MODIFIED_SINCE = 32 */
141 attr_location
, /* WINHTTP_QUERY_LOCATION = 33 */
142 NULL
, /* WINHTTP_QUERY_ORIG_URI = 34 */
143 attr_referer
, /* WINHTTP_QUERY_REFERER = 35 */
144 attr_retry_after
, /* WINHTTP_QUERY_RETRY_AFTER = 36 */
145 attr_server
, /* WINHTTP_QUERY_SERVER = 37 */
146 NULL
, /* WINHTTP_TITLE = 38 */
147 attr_user_agent
, /* WINHTTP_QUERY_USER_AGENT = 39 */
148 attr_www_authenticate
, /* WINHTTP_QUERY_WWW_AUTHENTICATE = 40 */
149 attr_proxy_authenticate
, /* WINHTTP_QUERY_PROXY_AUTHENTICATE = 41 */
150 attr_accept_ranges
, /* WINHTTP_QUERY_ACCEPT_RANGES = 42 */
151 attr_set_cookie
, /* WINHTTP_QUERY_SET_COOKIE = 43 */
152 attr_cookie
, /* WINHTTP_QUERY_COOKIE = 44 */
153 NULL
, /* WINHTTP_QUERY_REQUEST_METHOD = 45 */
154 NULL
, /* WINHTTP_QUERY_REFRESH = 46 */
155 NULL
, /* WINHTTP_QUERY_CONTENT_DISPOSITION = 47 */
156 attr_age
, /* WINHTTP_QUERY_AGE = 48 */
157 attr_cache_control
, /* WINHTTP_QUERY_CACHE_CONTROL = 49 */
158 attr_content_base
, /* WINHTTP_QUERY_CONTENT_BASE = 50 */
159 attr_content_location
, /* WINHTTP_QUERY_CONTENT_LOCATION = 51 */
160 attr_content_md5
, /* WINHTTP_QUERY_CONTENT_MD5 = 52 */
161 attr_content_range
, /* WINHTTP_QUERY_CONTENT_RANGE = 53 */
162 attr_etag
, /* WINHTTP_QUERY_ETAG = 54 */
163 attr_host
, /* WINHTTP_QUERY_HOST = 55 */
164 attr_if_match
, /* WINHTTP_QUERY_IF_MATCH = 56 */
165 attr_if_none_match
, /* WINHTTP_QUERY_IF_NONE_MATCH = 57 */
166 attr_if_range
, /* WINHTTP_QUERY_IF_RANGE = 58 */
167 attr_if_unmodified_since
, /* WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
168 attr_max_forwards
, /* WINHTTP_QUERY_MAX_FORWARDS = 60 */
169 attr_proxy_authorization
, /* WINHTTP_QUERY_PROXY_AUTHORIZATION = 61 */
170 attr_range
, /* WINHTTP_QUERY_RANGE = 62 */
171 attr_transfer_encoding
, /* WINHTTP_QUERY_TRANSFER_ENCODING = 63 */
172 attr_upgrade
, /* WINHTTP_QUERY_UPGRADE = 64 */
173 attr_vary
, /* WINHTTP_QUERY_VARY = 65 */
174 attr_via
, /* WINHTTP_QUERY_VIA = 66 */
175 attr_warning
, /* WINHTTP_QUERY_WARNING = 67 */
176 attr_expect
, /* WINHTTP_QUERY_EXPECT = 68 */
177 attr_proxy_connection
, /* WINHTTP_QUERY_PROXY_CONNECTION = 69 */
178 attr_unless_modified_since
, /* WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
179 NULL
, /* WINHTTP_QUERY_PROXY_SUPPORT = 75 */
180 NULL
, /* WINHTTP_QUERY_AUTHENTICATION_INFO = 76 */
181 NULL
, /* WINHTTP_QUERY_PASSPORT_URLS = 77 */
182 NULL
/* WINHTTP_QUERY_PASSPORT_CONFIG = 78 */
185 static DWORD CALLBACK
task_thread( LPVOID param
)
187 task_header_t
*task
= param
;
191 release_object( &task
->request
->hdr
);
193 return ERROR_SUCCESS
;
196 static BOOL
queue_task( task_header_t
*task
)
198 return QueueUserWorkItem( task_thread
, task
, WT_EXECUTELONGFUNCTION
);
201 static void free_header( header_t
*header
)
203 heap_free( header
->field
);
204 heap_free( header
->value
);
208 static BOOL
valid_token_char( WCHAR c
)
210 if (c
< 32 || c
== 127) return FALSE
;
217 case '\\': case '\"':
229 static header_t
*parse_header( LPCWSTR string
)
236 if (!(q
= strchrW( p
, ':' )))
238 WARN("no ':' in line %s\n", debugstr_w(string
));
243 WARN("empty field name in line %s\n", debugstr_w(string
));
248 if (!valid_token_char( *p
))
250 WARN("invalid character in field name %s\n", debugstr_w(string
));
256 if (!(header
= heap_alloc_zero( sizeof(header_t
) ))) return NULL
;
257 if (!(header
->field
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
262 memcpy( header
->field
, string
, len
* sizeof(WCHAR
) );
263 header
->field
[len
] = 0;
265 q
++; /* skip past colon */
266 while (*q
== ' ') q
++;
269 WARN("no value in line %s\n", debugstr_w(string
));
273 if (!(header
->value
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
275 free_header( header
);
278 memcpy( header
->value
, q
, len
* sizeof(WCHAR
) );
279 header
->value
[len
] = 0;
284 static int get_header_index( request_t
*request
, LPCWSTR field
, int requested_index
, BOOL request_only
)
288 TRACE("%s\n", debugstr_w(field
));
290 for (index
= 0; index
< request
->num_headers
; index
++)
292 if (strcmpiW( request
->headers
[index
].field
, field
)) continue;
293 if (request_only
&& !request
->headers
[index
].is_request
) continue;
294 if (!request_only
&& request
->headers
[index
].is_request
) continue;
296 if (!requested_index
) break;
299 if (index
>= request
->num_headers
) index
= -1;
300 TRACE("returning %d\n", index
);
304 static BOOL
insert_header( request_t
*request
, header_t
*header
)
309 count
= request
->num_headers
+ 1;
311 hdrs
= heap_realloc_zero( request
->headers
, sizeof(header_t
) * count
);
313 hdrs
= heap_alloc_zero( sizeof(header_t
) * count
);
317 request
->headers
= hdrs
;
318 request
->headers
[count
- 1].field
= strdupW( header
->field
);
319 request
->headers
[count
- 1].value
= strdupW( header
->value
);
320 request
->headers
[count
- 1].is_request
= header
->is_request
;
321 request
->num_headers
++;
327 static BOOL
delete_header( request_t
*request
, DWORD index
)
329 if (!request
->num_headers
) return FALSE
;
330 if (index
>= request
->num_headers
) return FALSE
;
331 request
->num_headers
--;
333 heap_free( request
->headers
[index
].field
);
334 heap_free( request
->headers
[index
].value
);
336 memmove( &request
->headers
[index
], &request
->headers
[index
+ 1], (request
->num_headers
- index
) * sizeof(header_t
) );
337 memset( &request
->headers
[request
->num_headers
], 0, sizeof(header_t
) );
341 static BOOL
process_header( request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD flags
, BOOL request_only
)
346 TRACE("%s: %s 0x%08x\n", debugstr_w(field
), debugstr_w(value
), flags
);
348 /* replace wins out over add */
349 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
) flags
&= ~WINHTTP_ADDREQ_FLAG_ADD
;
351 if (flags
& WINHTTP_ADDREQ_FLAG_ADD
) index
= -1;
353 index
= get_header_index( request
, field
, 0, request_only
);
357 if (flags
& WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
) return FALSE
;
358 header
= &request
->headers
[index
];
364 hdr
.field
= (LPWSTR
)field
;
365 hdr
.value
= (LPWSTR
)value
;
366 hdr
.is_request
= request_only
;
368 return insert_header( request
, &hdr
);
370 /* no value to delete */
373 if (flags
& WINHTTP_ADDREQ_FLAG_REPLACE
)
375 delete_header( request
, index
);
380 hdr
.field
= (LPWSTR
)field
;
381 hdr
.value
= (LPWSTR
)value
;
382 hdr
.is_request
= request_only
;
384 return insert_header( request
, &hdr
);
388 else if (flags
& (WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
| WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
))
391 int len
, orig_len
, value_len
;
393 orig_len
= strlenW( header
->value
);
394 value_len
= strlenW( value
);
396 if (flags
& WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
) sep
= ',';
399 len
= orig_len
+ value_len
+ 2;
400 if ((tmp
= heap_realloc( header
->value
, (len
+ 1) * sizeof(WCHAR
) )))
404 header
->value
[orig_len
] = sep
;
406 header
->value
[orig_len
] = ' ';
409 memcpy( &header
->value
[orig_len
], value
, value_len
* sizeof(WCHAR
) );
410 header
->value
[len
] = 0;
417 BOOL
add_request_headers( request_t
*request
, LPCWSTR headers
, DWORD len
, DWORD flags
)
420 WCHAR
*buffer
, *p
, *q
;
423 if (len
== ~0u) len
= strlenW( headers
);
424 if (!len
) return TRUE
;
425 if (!(buffer
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
426 strcpyW( buffer
, headers
);
434 if (q
[0] == '\n' && q
[1] == '\r')
439 if (q
[0] == '\r' && q
[1] == '\n') break;
446 q
+= 2; /* jump over \r\n */
448 if ((header
= parse_header( p
)))
450 ret
= process_header( request
, header
->field
, header
->value
, flags
, TRUE
);
451 free_header( header
);
460 /***********************************************************************
461 * WinHttpAddRequestHeaders (winhttp.@)
463 BOOL WINAPI
WinHttpAddRequestHeaders( HINTERNET hrequest
, LPCWSTR headers
, DWORD len
, DWORD flags
)
468 TRACE("%p, %s, 0x%x, 0x%08x\n", hrequest
, debugstr_w(headers
), len
, flags
);
472 set_last_error( ERROR_INVALID_PARAMETER
);
475 if (!(request
= (request_t
*)grab_object( hrequest
)))
477 set_last_error( ERROR_INVALID_HANDLE
);
480 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
482 release_object( &request
->hdr
);
483 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
487 ret
= add_request_headers( request
, headers
, len
, flags
);
489 release_object( &request
->hdr
);
493 static WCHAR
*build_request_path( request_t
*request
)
497 if (strcmpiW( request
->connect
->hostname
, request
->connect
->servername
))
499 static const WCHAR http
[] = { 'h','t','t','p',0 };
500 static const WCHAR https
[] = { 'h','t','t','p','s',0 };
501 static const WCHAR fmt
[] = { '%','s',':','/','/','%','s',0 };
502 LPCWSTR scheme
= request
->netconn
.secure
? https
: http
;
505 len
= strlenW( scheme
) + strlenW( request
->connect
->hostname
);
506 /* 3 characters for '://', 1 for NUL. */
508 if (request
->connect
->hostport
)
510 /* 1 for ':' between host and port, up to 5 for port */
514 len
+= strlenW( request
->path
);
515 if ((ret
= heap_alloc( len
* sizeof(WCHAR
) )))
517 sprintfW( ret
, fmt
, scheme
, request
->connect
->hostname
);
518 if (request
->connect
->hostport
)
520 static const WCHAR colonFmt
[] = { ':','%','u',0 };
522 sprintfW( ret
+ strlenW( ret
), colonFmt
,
523 request
->connect
->hostport
);
526 strcatW( ret
, request
->path
);
534 static WCHAR
*build_request_string( request_t
*request
)
536 static const WCHAR space
[] = {' ',0};
537 static const WCHAR crlf
[] = {'\r','\n',0};
538 static const WCHAR colon
[] = {':',' ',0};
539 static const WCHAR twocrlf
[] = {'\r','\n','\r','\n',0};
542 const WCHAR
**headers
, **p
;
543 unsigned int len
, i
= 0, j
;
545 /* allocate space for an array of all the string pointers to be added */
546 len
= request
->num_headers
* 4 + 7;
547 if (!(headers
= heap_alloc( len
* sizeof(LPCWSTR
) ))) return NULL
;
549 path
= build_request_path( request
);
550 headers
[i
++] = request
->verb
;
551 headers
[i
++] = space
;
553 headers
[i
++] = space
;
554 headers
[i
++] = request
->version
;
556 for (j
= 0; j
< request
->num_headers
; j
++)
558 if (request
->headers
[j
].is_request
)
561 headers
[i
++] = request
->headers
[j
].field
;
562 headers
[i
++] = colon
;
563 headers
[i
++] = request
->headers
[j
].value
;
565 TRACE("adding header %s (%s)\n", debugstr_w(request
->headers
[j
].field
),
566 debugstr_w(request
->headers
[j
].value
));
569 headers
[i
++] = twocrlf
;
573 for (p
= headers
; *p
; p
++) len
+= strlenW( *p
);
576 if (!(ret
= heap_alloc( len
* sizeof(WCHAR
) )))
579 for (p
= headers
; *p
; p
++) strcatW( ret
, *p
);
582 if (path
!= request
->path
)
584 heap_free( headers
);
588 #define QUERY_MODIFIER_MASK (WINHTTP_QUERY_FLAG_REQUEST_HEADERS | WINHTTP_QUERY_FLAG_SYSTEMTIME | WINHTTP_QUERY_FLAG_NUMBER)
590 static BOOL
query_headers( request_t
*request
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
592 header_t
*header
= NULL
;
593 BOOL request_only
, ret
= FALSE
;
594 int requested_index
, header_index
= -1;
597 request_only
= level
& WINHTTP_QUERY_FLAG_REQUEST_HEADERS
;
598 requested_index
= index
? *index
: 0;
600 attr
= level
& ~QUERY_MODIFIER_MASK
;
603 case WINHTTP_QUERY_CUSTOM
:
605 header_index
= get_header_index( request
, name
, requested_index
, request_only
);
608 case WINHTTP_QUERY_RAW_HEADERS
:
610 WCHAR
*headers
, *p
, *q
;
613 headers
= build_request_string( request
);
615 headers
= request
->raw_headers
;
617 if (!(p
= headers
)) return FALSE
;
618 for (len
= 0; *p
; p
++) if (*p
!= '\r') len
++;
620 if (!buffer
|| (len
+ 1) * sizeof(WCHAR
) > *buflen
)
623 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
627 for (p
= headers
, q
= buffer
; *p
; p
++, q
++)
629 if (*p
!= '\r') *q
= *p
;
637 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
));
640 *buflen
= len
* sizeof(WCHAR
);
641 if (request_only
) heap_free( headers
);
644 case WINHTTP_QUERY_RAW_HEADERS_CRLF
:
649 headers
= build_request_string( request
);
651 headers
= request
->raw_headers
;
653 if (!headers
) return FALSE
;
654 len
= strlenW( headers
) * sizeof(WCHAR
);
655 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
657 len
+= sizeof(WCHAR
);
658 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
662 memcpy( buffer
, headers
, len
+ sizeof(WCHAR
) );
663 TRACE("returning data: %s\n", debugstr_wn(buffer
, len
/ sizeof(WCHAR
)));
667 if (request_only
) heap_free( headers
);
670 case WINHTTP_QUERY_VERSION
:
671 len
= strlenW( request
->version
) * sizeof(WCHAR
);
672 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
674 len
+= sizeof(WCHAR
);
675 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
679 strcpyW( buffer
, request
->version
);
680 TRACE("returning string: %s\n", debugstr_w(buffer
));
686 case WINHTTP_QUERY_STATUS_TEXT
:
687 len
= strlenW( request
->status_text
) * sizeof(WCHAR
);
688 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
690 len
+= sizeof(WCHAR
);
691 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
695 strcpyW( buffer
, request
->status_text
);
696 TRACE("returning string: %s\n", debugstr_w(buffer
));
703 if (attr
>= sizeof(attribute_table
)/sizeof(attribute_table
[0]) || !attribute_table
[attr
])
705 FIXME("attribute %u not implemented\n", attr
);
708 TRACE("attribute %s\n", debugstr_w(attribute_table
[attr
]));
709 header_index
= get_header_index( request
, attribute_table
[attr
], requested_index
, request_only
);
713 if (header_index
>= 0)
715 header
= &request
->headers
[header_index
];
717 if (!header
|| (request_only
&& !header
->is_request
))
719 set_last_error( ERROR_WINHTTP_HEADER_NOT_FOUND
);
722 if (index
) *index
+= 1;
723 if (level
& WINHTTP_QUERY_FLAG_NUMBER
)
725 if (!buffer
|| sizeof(int) > *buflen
)
727 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
731 int *number
= buffer
;
732 *number
= atoiW( header
->value
);
733 TRACE("returning number: %d\n", *number
);
736 *buflen
= sizeof(int);
738 else if (level
& WINHTTP_QUERY_FLAG_SYSTEMTIME
)
740 SYSTEMTIME
*st
= buffer
;
741 if (!buffer
|| sizeof(SYSTEMTIME
) > *buflen
)
743 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
745 else if ((ret
= WinHttpTimeToSystemTime( header
->value
, st
)))
747 TRACE("returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
748 st
->wYear
, st
->wMonth
, st
->wDay
, st
->wDayOfWeek
,
749 st
->wHour
, st
->wMinute
, st
->wSecond
, st
->wMilliseconds
);
751 *buflen
= sizeof(SYSTEMTIME
);
753 else if (header
->value
)
755 len
= strlenW( header
->value
) * sizeof(WCHAR
);
756 if (!buffer
|| len
+ sizeof(WCHAR
) > *buflen
)
758 len
+= sizeof(WCHAR
);
759 set_last_error( ERROR_INSUFFICIENT_BUFFER
);
763 strcpyW( buffer
, header
->value
);
764 TRACE("returning string: %s\n", debugstr_w(buffer
));
772 /***********************************************************************
773 * WinHttpQueryHeaders (winhttp.@)
775 BOOL WINAPI
WinHttpQueryHeaders( HINTERNET hrequest
, DWORD level
, LPCWSTR name
, LPVOID buffer
, LPDWORD buflen
, LPDWORD index
)
780 TRACE("%p, 0x%08x, %s, %p, %p, %p\n", hrequest
, level
, debugstr_w(name
), buffer
, buflen
, index
);
782 if (!(request
= (request_t
*)grab_object( hrequest
)))
784 set_last_error( ERROR_INVALID_HANDLE
);
787 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
789 release_object( &request
->hdr
);
790 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
794 ret
= query_headers( request
, level
, name
, buffer
, buflen
, index
);
796 release_object( &request
->hdr
);
800 static LPWSTR
concatenate_string_list( LPCWSTR
*list
, int len
)
805 for( t
= list
; *t
; t
++ )
806 len
+= strlenW( *t
);
809 str
= heap_alloc( len
* sizeof(WCHAR
) );
810 if (!str
) return NULL
;
813 for( t
= list
; *t
; t
++ )
819 static LPWSTR
build_header_request_string( request_t
*request
, LPCWSTR verb
,
820 LPCWSTR path
, LPCWSTR version
)
822 static const WCHAR crlf
[] = {'\r','\n',0};
823 static const WCHAR space
[] = { ' ',0 };
824 static const WCHAR colon
[] = { ':',' ',0 };
825 static const WCHAR twocrlf
[] = {'\r','\n','\r','\n', 0};
826 LPWSTR requestString
;
832 /* allocate space for an array of all the string pointers to be added */
833 len
= (request
->num_headers
) * 4 + 10;
834 req
= heap_alloc( len
* sizeof(LPCWSTR
) );
835 if (!req
) return NULL
;
837 /* add the verb, path and HTTP version string */
845 /* Append custom request headers */
846 for (i
= 0; i
< request
->num_headers
; i
++)
848 if (request
->headers
[i
].is_request
)
851 req
[n
++] = request
->headers
[i
].field
;
853 req
[n
++] = request
->headers
[i
].value
;
855 TRACE("Adding custom header %s (%s)\n",
856 debugstr_w(request
->headers
[i
].field
),
857 debugstr_w(request
->headers
[i
].value
));
862 ERR("oops. buffer overrun\n");
865 requestString
= concatenate_string_list( req
, 4 );
867 if (!requestString
) return NULL
;
870 * Set (header) termination string for request
871 * Make sure there's exactly two new lines at the end of the request
873 p
= &requestString
[strlenW(requestString
)-1];
874 while ( (*p
== '\n') || (*p
== '\r') )
876 strcpyW( p
+1, twocrlf
);
878 return requestString
;
881 static BOOL
read_reply( request_t
*request
);
883 static BOOL
secure_proxy_connect( request_t
*request
)
885 static const WCHAR verbConnect
[] = {'C','O','N','N','E','C','T',0};
886 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
889 connect_t
*connect
= request
->connect
;
891 path
= heap_alloc( (strlenW( connect
->hostname
) + 13) * sizeof(WCHAR
) );
894 LPWSTR requestString
;
896 sprintfW( path
, fmt
, connect
->hostname
, connect
->hostport
);
897 requestString
= build_header_request_string( request
, verbConnect
,
902 LPSTR req_ascii
= strdupWA( requestString
);
904 heap_free( requestString
);
907 int len
= strlen( req_ascii
), bytes_sent
;
909 ret
= netconn_send( &request
->netconn
, req_ascii
, len
, &bytes_sent
);
910 heap_free( req_ascii
);
912 ret
= read_reply( request
);
919 #ifndef INET6_ADDRSTRLEN
920 #define INET6_ADDRSTRLEN 46
923 static WCHAR
*addr_to_str( const struct sockaddr
*addr
)
925 char buf
[INET6_ADDRSTRLEN
];
928 switch (addr
->sa_family
)
931 src
= &((struct sockaddr_in
*)addr
)->sin_addr
;
934 src
= &((struct sockaddr_in6
*)addr
)->sin6_addr
;
937 WARN("unsupported address family %d\n", addr
->sa_family
);
940 if (!inet_ntop( addr
->sa_family
, src
, buf
, sizeof(buf
) )) return NULL
;
941 return strdupAW( buf
);
944 static BOOL
open_connection( request_t
*request
)
947 WCHAR
*addressW
= NULL
;
950 struct sockaddr
*saddr
;
953 if (netconn_connected( &request
->netconn
)) goto done
;
955 connect
= request
->connect
;
956 port
= connect
->serverport
? connect
->serverport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
957 saddr
= (struct sockaddr
*)&connect
->sockaddr
;
958 slen
= sizeof(struct sockaddr
);
960 if (!connect
->resolved
)
962 len
= strlenW( connect
->servername
) + 1;
963 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESOLVING_NAME
, connect
->servername
, len
);
965 if (!netconn_resolve( connect
->servername
, port
, saddr
, &slen
, request
->resolve_timeout
)) return FALSE
;
966 connect
->resolved
= TRUE
;
968 if (!(addressW
= addr_to_str( saddr
))) return FALSE
;
969 len
= strlenW( addressW
) + 1;
970 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_NAME_RESOLVED
, addressW
, len
);
972 if (!addressW
&& !(addressW
= addr_to_str( saddr
))) return FALSE
;
973 TRACE("connecting to %s:%u\n", debugstr_w(addressW
), port
);
975 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER
, addressW
, 0 );
977 if (!netconn_create( &request
->netconn
, saddr
->sa_family
, SOCK_STREAM
, 0 ))
979 heap_free( addressW
);
982 netconn_set_timeout( &request
->netconn
, TRUE
, request
->send_timeout
);
983 netconn_set_timeout( &request
->netconn
, FALSE
, request
->recv_timeout
);
984 if (!netconn_connect( &request
->netconn
, saddr
, slen
, request
->connect_timeout
))
986 netconn_close( &request
->netconn
);
987 heap_free( addressW
);
990 if (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
992 if (connect
->session
->proxy_server
&&
993 strcmpiW( connect
->hostname
, connect
->servername
))
995 if (!secure_proxy_connect( request
))
997 heap_free( addressW
);
1001 if (!netconn_secure_connect( &request
->netconn
, connect
->servername
))
1003 netconn_close( &request
->netconn
);
1004 heap_free( addressW
);
1009 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER
, addressW
, strlenW(addressW
) + 1 );
1012 request
->read_pos
= request
->read_size
= 0;
1013 request
->read_chunked
= FALSE
;
1014 heap_free( addressW
);
1018 void close_connection( request_t
*request
)
1020 if (!netconn_connected( &request
->netconn
)) return;
1022 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION
, 0, 0 );
1023 netconn_close( &request
->netconn
);
1024 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED
, 0, 0 );
1027 static BOOL
add_host_header( request_t
*request
, DWORD modifier
)
1032 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
1033 connect_t
*connect
= request
->connect
;
1036 port
= connect
->hostport
? connect
->hostport
: (request
->hdr
.flags
& WINHTTP_FLAG_SECURE
? 443 : 80);
1038 if (port
== INTERNET_DEFAULT_HTTP_PORT
|| port
== INTERNET_DEFAULT_HTTPS_PORT
)
1040 return process_header( request
, attr_host
, connect
->hostname
, modifier
, TRUE
);
1042 len
= strlenW( connect
->hostname
) + 7; /* sizeof(":65335") */
1043 if (!(host
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
1044 sprintfW( host
, fmt
, connect
->hostname
, port
);
1045 ret
= process_header( request
, attr_host
, host
, modifier
, TRUE
);
1050 static void clear_response_headers( request_t
*request
)
1054 for (i
= 0; i
< request
->num_headers
; i
++)
1056 if (!request
->headers
[i
].field
) continue;
1057 if (!request
->headers
[i
].value
) continue;
1058 if (request
->headers
[i
].is_request
) continue;
1059 delete_header( request
, i
);
1064 static BOOL
send_request( request_t
*request
, LPCWSTR headers
, DWORD headers_len
, LPVOID optional
,
1065 DWORD optional_len
, DWORD total_len
, DWORD_PTR context
, BOOL async
)
1067 static const WCHAR keep_alive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
1068 static const WCHAR no_cache
[] = {'n','o','-','c','a','c','h','e',0};
1069 static const WCHAR length_fmt
[] = {'%','l','d',0};
1072 connect_t
*connect
= request
->connect
;
1073 session_t
*session
= connect
->session
;
1077 DWORD len
, i
, flags
;
1079 clear_response_headers( request
);
1081 flags
= WINHTTP_ADDREQ_FLAG_ADD
|WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
;
1082 for (i
= 0; i
< request
->num_accept_types
; i
++)
1084 process_header( request
, attr_accept
, request
->accept_types
[i
], flags
, TRUE
);
1087 process_header( request
, attr_user_agent
, session
->agent
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1089 if (connect
->hostname
)
1090 add_host_header( request
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
1092 if (total_len
|| (request
->verb
&& !strcmpW( request
->verb
, postW
)))
1094 WCHAR length
[21]; /* decimal long int + null */
1095 sprintfW( length
, length_fmt
, total_len
);
1096 process_header( request
, attr_content_length
, length
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1098 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
))
1100 process_header( request
, attr_connection
, keep_alive
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1102 if (request
->hdr
.flags
& WINHTTP_FLAG_REFRESH
)
1104 process_header( request
, attr_pragma
, no_cache
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1105 process_header( request
, attr_cache_control
, no_cache
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
, TRUE
);
1107 if (headers
&& !add_request_headers( request
, headers
, headers_len
, WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
))
1109 TRACE("failed to add request headers\n");
1112 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
) && !add_cookie_headers( request
))
1114 WARN("failed to add cookie headers\n");
1118 if (context
) request
->hdr
.context
= context
;
1120 if (!(ret
= open_connection( request
))) goto end
;
1121 if (!(req
= build_request_string( request
))) goto end
;
1123 if (!(req_ascii
= strdupWA( req
))) goto end
;
1124 TRACE("full request: %s\n", debugstr_a(req_ascii
));
1125 len
= strlen(req_ascii
);
1127 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDING_REQUEST
, NULL
, 0 );
1129 ret
= netconn_send( &request
->netconn
, req_ascii
, len
, &bytes_sent
);
1130 heap_free( req_ascii
);
1135 if (!netconn_send( &request
->netconn
, optional
, optional_len
, &bytes_sent
)) goto end
;
1136 request
->optional
= optional
;
1137 request
->optional_len
= optional_len
;
1138 len
+= optional_len
;
1140 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
, &len
, sizeof(DWORD
) );
1145 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
, NULL
, 0 );
1148 WINHTTP_ASYNC_RESULT result
;
1149 result
.dwResult
= API_SEND_REQUEST
;
1150 result
.dwError
= get_last_error();
1151 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
1158 static void task_send_request( task_header_t
*task
)
1160 send_request_t
*s
= (send_request_t
*)task
;
1161 send_request( s
->hdr
.request
, s
->headers
, s
->headers_len
, s
->optional
, s
->optional_len
, s
->total_len
, s
->context
, TRUE
);
1162 heap_free( s
->headers
);
1165 /***********************************************************************
1166 * WinHttpSendRequest (winhttp.@)
1168 BOOL WINAPI
WinHttpSendRequest( HINTERNET hrequest
, LPCWSTR headers
, DWORD headers_len
,
1169 LPVOID optional
, DWORD optional_len
, DWORD total_len
, DWORD_PTR context
)
1174 TRACE("%p, %s, 0x%x, %u, %u, %lx\n",
1175 hrequest
, debugstr_w(headers
), headers_len
, optional_len
, total_len
, context
);
1177 if (!(request
= (request_t
*)grab_object( hrequest
)))
1179 set_last_error( ERROR_INVALID_HANDLE
);
1182 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1184 release_object( &request
->hdr
);
1185 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1189 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
1193 if (!(s
= heap_alloc( sizeof(send_request_t
) ))) return FALSE
;
1194 s
->hdr
.request
= request
;
1195 s
->hdr
.proc
= task_send_request
;
1196 s
->headers
= strdupW( headers
);
1197 s
->headers_len
= headers_len
;
1198 s
->optional
= optional
;
1199 s
->optional_len
= optional_len
;
1200 s
->total_len
= total_len
;
1201 s
->context
= context
;
1203 addref_object( &request
->hdr
);
1204 ret
= queue_task( (task_header_t
*)s
);
1207 ret
= send_request( request
, headers
, headers_len
, optional
, optional_len
, total_len
, context
, FALSE
);
1209 release_object( &request
->hdr
);
1213 #define ARRAYSIZE(array) (sizeof(array) / sizeof((array)[0]))
1215 static const WCHAR basicW
[] = {'B','a','s','i','c',0};
1216 static const WCHAR ntlmW
[] = {'N','T','L','M',0};
1217 static const WCHAR passportW
[] = {'P','a','s','s','p','o','r','t',0};
1218 static const WCHAR digestW
[] = {'D','i','g','e','s','t',0};
1219 static const WCHAR negotiateW
[] = {'N','e','g','o','t','i','a','t','e',0};
1229 { basicW
, ARRAYSIZE(basicW
) - 1, WINHTTP_AUTH_SCHEME_BASIC
},
1230 { ntlmW
, ARRAYSIZE(ntlmW
) - 1, WINHTTP_AUTH_SCHEME_NTLM
},
1231 { passportW
, ARRAYSIZE(passportW
) - 1, WINHTTP_AUTH_SCHEME_PASSPORT
},
1232 { digestW
, ARRAYSIZE(digestW
) - 1, WINHTTP_AUTH_SCHEME_DIGEST
},
1233 { negotiateW
, ARRAYSIZE(negotiateW
) - 1, WINHTTP_AUTH_SCHEME_NEGOTIATE
}
1235 static const unsigned int num_auth_schemes
= sizeof(auth_schemes
)/sizeof(auth_schemes
[0]);
1237 static enum auth_scheme
scheme_from_flag( DWORD flag
)
1241 for (i
= 0; i
< num_auth_schemes
; i
++) if (flag
== auth_schemes
[i
].scheme
) return i
;
1242 return SCHEME_INVALID
;
1245 static DWORD
auth_scheme_from_header( WCHAR
*header
)
1249 for (i
= 0; i
< num_auth_schemes
; i
++)
1251 if (!strncmpiW( header
, auth_schemes
[i
].str
, auth_schemes
[i
].len
) &&
1252 (header
[auth_schemes
[i
].len
] == ' ' || !header
[auth_schemes
[i
].len
])) return auth_schemes
[i
].scheme
;
1257 static BOOL
query_auth_schemes( request_t
*request
, DWORD level
, LPDWORD supported
, LPDWORD first
)
1268 query_headers( request
, level
, NULL
, NULL
, &size
, &index
);
1269 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER
) break;
1272 if (!(buffer
= heap_alloc( size
))) return FALSE
;
1273 if (!query_headers( request
, level
, NULL
, buffer
, &size
, &index
))
1275 heap_free( buffer
);
1278 scheme
= auth_scheme_from_header( buffer
);
1279 heap_free( buffer
);
1282 if (first
&& index
== 1)
1283 *first
= *supported
= scheme
;
1285 *supported
|= scheme
;
1292 /***********************************************************************
1293 * WinHttpQueryAuthSchemes (winhttp.@)
1295 BOOL WINAPI
WinHttpQueryAuthSchemes( HINTERNET hrequest
, LPDWORD supported
, LPDWORD first
, LPDWORD target
)
1300 TRACE("%p, %p, %p, %p\n", hrequest
, supported
, first
, target
);
1302 if (!(request
= (request_t
*)grab_object( hrequest
)))
1304 set_last_error( ERROR_INVALID_HANDLE
);
1307 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1309 release_object( &request
->hdr
);
1310 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1313 if (!supported
|| !first
|| !target
)
1315 release_object( &request
->hdr
);
1316 set_last_error( ERROR_INVALID_PARAMETER
);
1321 if (query_auth_schemes( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, supported
, first
))
1323 *target
= WINHTTP_AUTH_TARGET_SERVER
;
1326 else if (query_auth_schemes( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, supported
, first
))
1328 *target
= WINHTTP_AUTH_TARGET_PROXY
;
1332 release_object( &request
->hdr
);
1336 static UINT
encode_base64( const char *bin
, unsigned int len
, WCHAR
*base64
)
1339 static const char base64enc
[] =
1340 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1344 /* first 6 bits, all from bin[0] */
1345 base64
[n
++] = base64enc
[(bin
[0] & 0xfc) >> 2];
1346 x
= (bin
[0] & 3) << 4;
1348 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1351 base64
[n
++] = base64enc
[x
];
1356 base64
[n
++] = base64enc
[x
| ((bin
[1] & 0xf0) >> 4)];
1357 x
= (bin
[1] & 0x0f) << 2;
1359 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1362 base64
[n
++] = base64enc
[x
];
1366 base64
[n
++] = base64enc
[x
| ((bin
[2] & 0xc0) >> 6)];
1368 /* last 6 bits, all from bin [2] */
1369 base64
[n
++] = base64enc
[bin
[2] & 0x3f];
1377 static inline char decode_char( WCHAR c
)
1379 if (c
>= 'A' && c
<= 'Z') return c
- 'A';
1380 if (c
>= 'a' && c
<= 'z') return c
- 'a' + 26;
1381 if (c
>= '0' && c
<= '9') return c
- '0' + 52;
1382 if (c
== '+') return 62;
1383 if (c
== '/') return 63;
1387 static unsigned int decode_base64( const WCHAR
*base64
, unsigned int len
, char *buf
)
1390 char c0
, c1
, c2
, c3
;
1391 const WCHAR
*p
= base64
;
1395 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1396 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1397 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1398 if ((c3
= decode_char( p
[3] )) > 63) return 0;
1402 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1403 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1404 buf
[i
+ 2] = (c2
<< 6) | c3
;
1412 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1413 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1415 if (buf
) buf
[i
] = (c0
<< 2) | (c1
>> 4);
1418 else if (p
[3] == '=')
1420 if ((c0
= decode_char( p
[0] )) > 63) return 0;
1421 if ((c1
= decode_char( p
[1] )) > 63) return 0;
1422 if ((c2
= decode_char( p
[2] )) > 63) return 0;
1426 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
1427 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
1434 static struct authinfo
*alloc_authinfo(void)
1436 struct authinfo
*ret
;
1438 if (!(ret
= heap_alloc( sizeof(*ret
) ))) return NULL
;
1440 SecInvalidateHandle( &ret
->cred
);
1441 SecInvalidateHandle( &ret
->ctx
);
1442 memset( &ret
->exp
, 0, sizeof(ret
->exp
) );
1448 ret
->finished
= FALSE
;
1452 void destroy_authinfo( struct authinfo
*authinfo
)
1454 if (!authinfo
) return;
1456 if (SecIsValidHandle( &authinfo
->ctx
))
1457 DeleteSecurityContext( &authinfo
->ctx
);
1458 if (SecIsValidHandle( &authinfo
->cred
))
1459 FreeCredentialsHandle( &authinfo
->cred
);
1461 heap_free( authinfo
->data
);
1462 heap_free( authinfo
);
1465 static BOOL
get_authvalue( request_t
*request
, DWORD level
, DWORD scheme
, WCHAR
*buffer
, DWORD len
)
1467 DWORD size
, index
= 0;
1471 if (!query_headers( request
, level
, NULL
, buffer
, &size
, &index
)) return FALSE
;
1472 if (auth_scheme_from_header( buffer
) == scheme
) break;
1477 static BOOL
do_authorization( request_t
*request
, DWORD target
, DWORD scheme_flag
)
1479 struct authinfo
*authinfo
, **auth_ptr
;
1480 enum auth_scheme scheme
= scheme_from_flag( scheme_flag
);
1481 const WCHAR
*auth_target
, *username
, *password
;
1482 WCHAR auth_value
[2048], *auth_reply
;
1483 DWORD len
= sizeof(auth_value
), len_scheme
, flags
;
1486 if (scheme
== SCHEME_INVALID
) return FALSE
;
1490 case WINHTTP_AUTH_TARGET_SERVER
:
1491 if (!get_authvalue( request
, WINHTTP_QUERY_WWW_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1493 auth_ptr
= &request
->authinfo
;
1494 auth_target
= attr_authorization
;
1495 username
= request
->connect
->username
;
1496 password
= request
->connect
->password
;
1499 case WINHTTP_AUTH_TARGET_PROXY
:
1500 if (!get_authvalue( request
, WINHTTP_QUERY_PROXY_AUTHENTICATE
, scheme_flag
, auth_value
, len
))
1502 auth_ptr
= &request
->proxy_authinfo
;
1503 auth_target
= attr_proxy_authorization
;
1504 username
= request
->connect
->session
->proxy_username
;
1505 password
= request
->connect
->session
->proxy_password
;
1509 WARN("unknown target %x\n", target
);
1512 authinfo
= *auth_ptr
;
1518 int userlen
, passlen
;
1520 if (!username
|| !password
) return FALSE
;
1521 if ((!authinfo
&& !(authinfo
= alloc_authinfo())) || authinfo
->finished
) return FALSE
;
1523 userlen
= WideCharToMultiByte( CP_UTF8
, 0, username
, strlenW( username
), NULL
, 0, NULL
, NULL
);
1524 passlen
= WideCharToMultiByte( CP_UTF8
, 0, password
, strlenW( password
), NULL
, 0, NULL
, NULL
);
1526 authinfo
->data_len
= userlen
+ 1 + passlen
;
1527 if (!(authinfo
->data
= heap_alloc( authinfo
->data_len
))) return FALSE
;
1529 WideCharToMultiByte( CP_UTF8
, 0, username
, -1, authinfo
->data
, userlen
, NULL
, NULL
);
1530 authinfo
->data
[userlen
] = ':';
1531 WideCharToMultiByte( CP_UTF8
, 0, password
, -1, authinfo
->data
+ userlen
+ 1, passlen
, NULL
, NULL
);
1533 authinfo
->scheme
= SCHEME_BASIC
;
1534 authinfo
->finished
= TRUE
;
1538 case SCHEME_NEGOTIATE
:
1540 SECURITY_STATUS status
;
1541 SecBufferDesc out_desc
, in_desc
;
1543 ULONG flags
= ISC_REQ_CONNECTION
|ISC_REQ_USE_DCE_STYLE
|ISC_REQ_MUTUAL_AUTH
|ISC_REQ_DELEGATE
;
1550 SEC_WINNT_AUTH_IDENTITY_W id
;
1551 WCHAR
*domain
, *user
;
1553 if (!username
|| !password
|| !(authinfo
= alloc_authinfo())) return FALSE
;
1556 domain
= (WCHAR
*)username
;
1557 user
= strchrW( username
, '\\' );
1562 user
= (WCHAR
*)username
;
1565 id
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1567 id
.UserLength
= strlenW( user
);
1569 id
.DomainLength
= domain
? user
- domain
- 1 : 0;
1570 id
.Password
= (WCHAR
*)password
;
1571 id
.PasswordLength
= strlenW( password
);
1573 status
= AcquireCredentialsHandleW( NULL
, (SEC_WCHAR
*)auth_schemes
[scheme
].str
,
1574 SECPKG_CRED_OUTBOUND
, NULL
, &id
, NULL
, NULL
,
1575 &authinfo
->cred
, &exp
);
1576 if (status
== SEC_E_OK
)
1579 status
= QuerySecurityPackageInfoW( (SEC_WCHAR
*)auth_schemes
[scheme
].str
, &info
);
1580 if (status
== SEC_E_OK
)
1582 authinfo
->max_token
= info
->cbMaxToken
;
1583 FreeContextBuffer( info
);
1586 if (status
!= SEC_E_OK
)
1588 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1589 debugstr_w(auth_schemes
[scheme
].str
), status
);
1590 heap_free( authinfo
);
1593 authinfo
->scheme
= scheme
;
1595 else if (authinfo
->finished
) return FALSE
;
1597 if ((strlenW( auth_value
) < auth_schemes
[authinfo
->scheme
].len
||
1598 strncmpiW( auth_value
, auth_schemes
[authinfo
->scheme
].str
, auth_schemes
[authinfo
->scheme
].len
)))
1600 ERR("authentication scheme changed from %s to %s\n",
1601 debugstr_w(auth_schemes
[authinfo
->scheme
].str
), debugstr_w(auth_value
));
1602 destroy_authinfo( authinfo
);
1606 in
.BufferType
= SECBUFFER_TOKEN
;
1610 in_desc
.ulVersion
= 0;
1611 in_desc
.cBuffers
= 1;
1612 in_desc
.pBuffers
= &in
;
1614 p
= auth_value
+ auth_schemes
[scheme
].len
;
1617 int len
= strlenW( ++p
);
1618 in
.cbBuffer
= decode_base64( p
, len
, NULL
);
1619 if (!(in
.pvBuffer
= heap_alloc( in
.cbBuffer
))) return FALSE
;
1620 decode_base64( p
, len
, in
.pvBuffer
);
1622 out
.BufferType
= SECBUFFER_TOKEN
;
1623 out
.cbBuffer
= authinfo
->max_token
;
1624 if (!(out
.pvBuffer
= heap_alloc( authinfo
->max_token
)))
1626 heap_free( in
.pvBuffer
);
1629 out_desc
.ulVersion
= 0;
1630 out_desc
.cBuffers
= 1;
1631 out_desc
.pBuffers
= &out
;
1633 status
= InitializeSecurityContextW( first
? &authinfo
->cred
: NULL
, first
? NULL
: &authinfo
->ctx
,
1634 first
? request
->connect
->servername
: NULL
, flags
, 0,
1635 SECURITY_NETWORK_DREP
, in
.pvBuffer
? &in_desc
: NULL
, 0,
1636 &authinfo
->ctx
, &out_desc
, &authinfo
->attr
, &authinfo
->exp
);
1637 heap_free( in
.pvBuffer
);
1638 if (status
== SEC_E_OK
)
1640 heap_free( authinfo
->data
);
1641 authinfo
->data
= out
.pvBuffer
;
1642 authinfo
->data_len
= out
.cbBuffer
;
1643 authinfo
->finished
= TRUE
;
1644 TRACE("sending last auth packet\n");
1646 else if (status
== SEC_I_CONTINUE_NEEDED
)
1648 heap_free( authinfo
->data
);
1649 authinfo
->data
= out
.pvBuffer
;
1650 authinfo
->data_len
= out
.cbBuffer
;
1651 TRACE("sending next auth packet\n");
1655 ERR("InitializeSecurityContextW failed with error 0x%08x\n", status
);
1656 heap_free( out
.pvBuffer
);
1657 destroy_authinfo( authinfo
);
1664 ERR("invalid scheme %u\n", scheme
);
1667 *auth_ptr
= authinfo
;
1669 len_scheme
= auth_schemes
[authinfo
->scheme
].len
;
1670 len
= len_scheme
+ 1 + ((authinfo
->data_len
+ 2) * 4) / 3;
1671 if (!(auth_reply
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return FALSE
;
1673 memcpy( auth_reply
, auth_schemes
[authinfo
->scheme
].str
, len_scheme
* sizeof(WCHAR
) );
1674 auth_reply
[len_scheme
] = ' ';
1675 encode_base64( authinfo
->data
, authinfo
->data_len
, auth_reply
+ len_scheme
+ 1 );
1677 flags
= WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
;
1678 ret
= process_header( request
, auth_target
, auth_reply
, flags
, TRUE
);
1679 heap_free( auth_reply
);
1683 static BOOL
set_credentials( request_t
*request
, DWORD target
, DWORD scheme
, const WCHAR
*username
,
1684 const WCHAR
*password
)
1686 if ((scheme
== WINHTTP_AUTH_SCHEME_BASIC
|| scheme
== WINHTTP_AUTH_SCHEME_DIGEST
) &&
1687 (!username
|| !password
))
1689 set_last_error( ERROR_INVALID_PARAMETER
);
1694 case WINHTTP_AUTH_TARGET_SERVER
:
1696 heap_free( request
->connect
->username
);
1697 if (!username
) request
->connect
->username
= NULL
;
1698 else if (!(request
->connect
->username
= strdupW( username
))) return FALSE
;
1700 heap_free( request
->connect
->password
);
1701 if (!password
) request
->connect
->password
= NULL
;
1702 else if (!(request
->connect
->password
= strdupW( password
))) return FALSE
;
1705 case WINHTTP_AUTH_TARGET_PROXY
:
1707 heap_free( request
->connect
->session
->proxy_username
);
1708 if (!username
) request
->connect
->session
->proxy_username
= NULL
;
1709 else if (!(request
->connect
->session
->proxy_username
= strdupW( username
))) return FALSE
;
1711 heap_free( request
->connect
->session
->proxy_password
);
1712 if (!password
) request
->connect
->session
->proxy_password
= NULL
;
1713 else if (!(request
->connect
->session
->proxy_password
= strdupW( password
))) return FALSE
;
1717 WARN("unknown target %u\n", target
);
1723 /***********************************************************************
1724 * WinHttpSetCredentials (winhttp.@)
1726 BOOL WINAPI
WinHttpSetCredentials( HINTERNET hrequest
, DWORD target
, DWORD scheme
, LPCWSTR username
,
1727 LPCWSTR password
, LPVOID params
)
1732 TRACE("%p, %x, 0x%08x, %s, %p, %p\n", hrequest
, target
, scheme
, debugstr_w(username
), password
, params
);
1734 if (!(request
= (request_t
*)grab_object( hrequest
)))
1736 set_last_error( ERROR_INVALID_HANDLE
);
1739 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
1741 release_object( &request
->hdr
);
1742 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
1746 ret
= set_credentials( request
, target
, scheme
, username
, password
);
1748 release_object( &request
->hdr
);
1752 static BOOL
handle_authorization( request_t
*request
, DWORD status
)
1754 DWORD i
, schemes
, first
, level
, target
;
1758 case HTTP_STATUS_DENIED
:
1759 target
= WINHTTP_AUTH_TARGET_SERVER
;
1760 level
= WINHTTP_QUERY_WWW_AUTHENTICATE
;
1763 case HTTP_STATUS_PROXY_AUTH_REQ
:
1764 target
= WINHTTP_AUTH_TARGET_PROXY
;
1765 level
= WINHTTP_QUERY_PROXY_AUTHENTICATE
;
1769 WARN("unhandled status %u\n", status
);
1773 if (!query_auth_schemes( request
, level
, &schemes
, &first
)) return FALSE
;
1774 if (do_authorization( request
, target
, first
)) return TRUE
;
1777 for (i
= 0; i
< num_auth_schemes
; i
++)
1779 if (!(schemes
& auth_schemes
[i
].scheme
)) continue;
1780 if (do_authorization( request
, target
, auth_schemes
[i
].scheme
)) return TRUE
;
1785 /* set the request content length based on the headers */
1786 static DWORD
set_content_length( request_t
*request
)
1791 buflen
= sizeof(request
->content_length
);
1792 if (!query_headers( request
, WINHTTP_QUERY_CONTENT_LENGTH
|WINHTTP_QUERY_FLAG_NUMBER
,
1793 NULL
, &request
->content_length
, &buflen
, NULL
))
1794 request
->content_length
= ~0u;
1796 buflen
= sizeof(encoding
);
1797 if (query_headers( request
, WINHTTP_QUERY_TRANSFER_ENCODING
, NULL
, encoding
, &buflen
, NULL
) &&
1798 !strcmpiW( encoding
, chunkedW
))
1800 request
->content_length
= ~0u;
1801 request
->read_chunked
= TRUE
;
1803 request
->content_read
= 0;
1804 return request
->content_length
;
1807 /* read some more data into the read buffer */
1808 static BOOL
read_more_data( request_t
*request
, int maxlen
)
1812 if (request
->read_size
&& request
->read_pos
)
1814 /* move existing data to the start of the buffer */
1815 memmove( request
->read_buf
, request
->read_buf
+ request
->read_pos
, request
->read_size
);
1816 request
->read_pos
= 0;
1818 if (maxlen
== -1) maxlen
= sizeof(request
->read_buf
);
1819 if (!netconn_recv( &request
->netconn
, request
->read_buf
+ request
->read_size
,
1820 maxlen
- request
->read_size
, 0, &len
)) return FALSE
;
1821 request
->read_size
+= len
;
1825 /* remove some amount of data from the read buffer */
1826 static void remove_data( request_t
*request
, int count
)
1828 if (!(request
->read_size
-= count
)) request
->read_pos
= 0;
1829 else request
->read_pos
+= count
;
1832 static BOOL
read_line( request_t
*request
, char *buffer
, DWORD
*len
)
1834 int count
, bytes_read
, pos
= 0;
1838 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1841 count
= eol
- (request
->read_buf
+ request
->read_pos
);
1842 bytes_read
= count
+ 1;
1844 else count
= bytes_read
= request
->read_size
;
1846 count
= min( count
, *len
- pos
);
1847 memcpy( buffer
+ pos
, request
->read_buf
+ request
->read_pos
, count
);
1849 remove_data( request
, bytes_read
);
1852 if (!read_more_data( request
, -1 )) return FALSE
;
1853 if (!request
->read_size
)
1856 TRACE("returning empty string\n");
1862 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
1865 buffer
[*len
- 1] = 0;
1866 TRACE("returning %s\n", debugstr_a(buffer
));
1870 /* discard data contents until we reach end of line */
1871 static BOOL
discard_eol( request_t
*request
)
1875 char *eol
= memchr( request
->read_buf
+ request
->read_pos
, '\n', request
->read_size
);
1878 remove_data( request
, (eol
+ 1) - (request
->read_buf
+ request
->read_pos
) );
1881 request
->read_pos
= request
->read_size
= 0; /* discard everything */
1882 if (!read_more_data( request
, -1 )) return FALSE
;
1883 } while (request
->read_size
);
1887 /* read the size of the next chunk */
1888 static BOOL
start_next_chunk( request_t
*request
)
1890 DWORD chunk_size
= 0;
1892 if (!request
->content_length
) return TRUE
;
1893 if (request
->content_length
== request
->content_read
)
1895 /* read terminator for the previous chunk */
1896 if (!discard_eol( request
)) return FALSE
;
1897 request
->content_length
= ~0u;
1898 request
->content_read
= 0;
1902 while (request
->read_size
)
1904 char ch
= request
->read_buf
[request
->read_pos
];
1905 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
1906 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
1907 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
1908 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
1910 TRACE("reading %u byte chunk\n", chunk_size
);
1911 request
->content_length
= chunk_size
;
1912 request
->content_read
= 0;
1913 if (!discard_eol( request
)) return FALSE
;
1916 remove_data( request
, 1 );
1918 if (!read_more_data( request
, -1 )) return FALSE
;
1919 if (!request
->read_size
)
1921 request
->content_length
= request
->content_read
= 0;
1927 /* return the size of data available to be read immediately */
1928 static DWORD
get_available_data( request_t
*request
)
1930 if (request
->read_chunked
&&
1931 (request
->content_length
== ~0u || request
->content_length
== request
->content_read
))
1933 return min( request
->read_size
, request
->content_length
- request
->content_read
);
1936 /* check if we have reached the end of the data to read */
1937 static BOOL
end_of_read_data( request_t
*request
)
1939 if (request
->read_chunked
) return (request
->content_length
== 0);
1940 if (request
->content_length
== ~0u) return FALSE
;
1941 return (request
->content_length
== request
->content_read
);
1944 static BOOL
refill_buffer( request_t
*request
)
1946 int len
= sizeof(request
->read_buf
);
1948 if (request
->read_chunked
&&
1949 (request
->content_length
== ~0u || request
->content_length
== request
->content_read
))
1951 if (!start_next_chunk( request
)) return FALSE
;
1953 if (request
->content_length
!= ~0u) len
= min( len
, request
->content_length
- request
->content_read
);
1954 if (len
<= request
->read_size
) return TRUE
;
1955 if (!read_more_data( request
, len
)) return FALSE
;
1956 if (!request
->read_size
) request
->content_length
= request
->content_read
= 0;
1960 #define MAX_REPLY_LEN 1460
1961 #define INITIAL_HEADER_BUFFER_LEN 512
1963 static BOOL
read_reply( request_t
*request
)
1965 static const WCHAR crlf
[] = {'\r','\n',0};
1967 char buffer
[MAX_REPLY_LEN
];
1968 DWORD buflen
, len
, offset
, received_len
, crlf_len
= 2; /* strlenW(crlf) */
1969 char *status_code
, *status_text
;
1970 WCHAR
*versionW
, *status_textW
, *raw_headers
;
1971 WCHAR status_codeW
[4]; /* sizeof("nnn") */
1973 if (!netconn_connected( &request
->netconn
)) return FALSE
;
1975 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE
, NULL
, 0 );
1980 buflen
= MAX_REPLY_LEN
;
1981 if (!read_line( request
, buffer
, &buflen
)) return FALSE
;
1982 received_len
+= buflen
;
1984 /* first line should look like 'HTTP/1.x nnn OK' where nnn is the status code */
1985 if (!(status_code
= strchr( buffer
, ' ' ))) return FALSE
;
1987 if (!(status_text
= strchr( status_code
, ' ' ))) return FALSE
;
1988 if ((len
= status_text
- status_code
) != sizeof("nnn") - 1) return FALSE
;
1991 TRACE("version [%s] status code [%s] status text [%s]\n",
1992 debugstr_an(buffer
, status_code
- buffer
- 1),
1993 debugstr_an(status_code
, len
),
1994 debugstr_a(status_text
));
1996 } while (!memcmp( status_code
, "100", len
)); /* ignore "100 Continue" responses */
1998 /* we rely on the fact that the protocol is ascii */
1999 MultiByteToWideChar( CP_ACP
, 0, status_code
, len
, status_codeW
, len
);
2000 status_codeW
[len
] = 0;
2001 if (!(process_header( request
, attr_status
, status_codeW
, WINHTTP_ADDREQ_FLAG_REPLACE
, FALSE
))) return FALSE
;
2003 len
= status_code
- buffer
;
2004 if (!(versionW
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2005 MultiByteToWideChar( CP_ACP
, 0, buffer
, len
- 1, versionW
, len
-1 );
2006 versionW
[len
- 1] = 0;
2008 heap_free( request
->version
);
2009 request
->version
= versionW
;
2011 len
= buflen
- (status_text
- buffer
);
2012 if (!(status_textW
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2013 MultiByteToWideChar( CP_ACP
, 0, status_text
, len
, status_textW
, len
);
2015 heap_free( request
->status_text
);
2016 request
->status_text
= status_textW
;
2018 len
= max( buflen
+ crlf_len
, INITIAL_HEADER_BUFFER_LEN
);
2019 if (!(raw_headers
= heap_alloc( len
* sizeof(WCHAR
) ))) return FALSE
;
2020 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
, buflen
);
2021 memcpy( raw_headers
+ buflen
- 1, crlf
, sizeof(crlf
) );
2023 heap_free( request
->raw_headers
);
2024 request
->raw_headers
= raw_headers
;
2026 offset
= buflen
+ crlf_len
- 1;
2031 buflen
= MAX_REPLY_LEN
;
2032 if (!read_line( request
, buffer
, &buflen
)) goto end
;
2033 received_len
+= buflen
;
2034 if (!*buffer
) break;
2036 while (len
- offset
< buflen
+ crlf_len
)
2040 if (!(tmp
= heap_realloc( raw_headers
, len
* sizeof(WCHAR
) ))) return FALSE
;
2041 request
->raw_headers
= raw_headers
= tmp
;
2043 MultiByteToWideChar( CP_ACP
, 0, buffer
, buflen
, raw_headers
+ offset
, buflen
);
2045 if (!(header
= parse_header( raw_headers
+ offset
))) break;
2046 if (!(process_header( request
, header
->field
, header
->value
, WINHTTP_ADDREQ_FLAG_ADD
, FALSE
)))
2048 free_header( header
);
2051 free_header( header
);
2052 memcpy( raw_headers
+ offset
+ buflen
- 1, crlf
, sizeof(crlf
) );
2053 offset
+= buflen
+ crlf_len
- 1;
2056 TRACE("raw headers: %s\n", debugstr_w(raw_headers
));
2059 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED
, &received_len
, sizeof(DWORD
) );
2063 static void finished_reading( request_t
*request
)
2065 static const WCHAR closeW
[] = {'c','l','o','s','e',0};
2068 WCHAR connection
[20];
2069 DWORD size
= sizeof(connection
);
2071 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_KEEP_ALIVE
) close
= TRUE
;
2072 else if (query_headers( request
, WINHTTP_QUERY_CONNECTION
, NULL
, connection
, &size
, NULL
) ||
2073 query_headers( request
, WINHTTP_QUERY_PROXY_CONNECTION
, NULL
, connection
, &size
, NULL
))
2075 if (!strcmpiW( connection
, closeW
)) close
= TRUE
;
2077 else if (!strcmpW( request
->version
, http1_0
)) close
= TRUE
;
2078 if (close
) close_connection( request
);
2081 static BOOL
read_data( request_t
*request
, void *buffer
, DWORD size
, DWORD
*read
, BOOL async
)
2084 int len
, bytes_read
= 0;
2086 if (request
->read_chunked
&&
2087 (request
->content_length
== ~0u || request
->content_length
== request
->content_read
))
2089 if (!start_next_chunk( request
)) goto done
;
2091 if (request
->content_length
!= ~0u) size
= min( size
, request
->content_length
- request
->content_read
);
2093 if (request
->read_size
)
2095 bytes_read
= min( request
->read_size
, size
);
2096 memcpy( buffer
, request
->read_buf
+ request
->read_pos
, bytes_read
);
2097 remove_data( request
, bytes_read
);
2099 if (size
> bytes_read
&& (!bytes_read
|| !async
))
2101 if ((ret
= netconn_recv( &request
->netconn
, (char *)buffer
+ bytes_read
, size
- bytes_read
,
2102 async
? 0 : MSG_WAITALL
, &len
)))
2107 request
->content_read
+= bytes_read
;
2108 TRACE( "retrieved %u bytes (%u/%u)\n", bytes_read
, request
->content_read
, request
->content_length
);
2111 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
, buffer
, bytes_read
);
2114 WINHTTP_ASYNC_RESULT result
;
2115 result
.dwResult
= API_READ_DATA
;
2116 result
.dwError
= get_last_error();
2117 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2120 if (read
) *read
= bytes_read
;
2121 if (!bytes_read
&& request
->content_read
== request
->content_length
) finished_reading( request
);
2125 /* read any content returned by the server so that the connection can be reused */
2126 static void drain_content( request_t
*request
)
2131 if (request
->content_length
== ~0u)
2133 finished_reading( request
);
2138 if (!read_data( request
, buffer
, sizeof(buffer
), &bytes_read
, FALSE
) || !bytes_read
) return;
2142 static void record_cookies( request_t
*request
)
2146 for (i
= 0; i
< request
->num_headers
; i
++)
2148 header_t
*set_cookie
= &request
->headers
[i
];
2149 if (!strcmpiW( set_cookie
->field
, attr_set_cookie
) && !set_cookie
->is_request
)
2151 set_cookies( request
, set_cookie
->value
);
2156 static WCHAR
*get_redirect_url( request_t
*request
, DWORD
*len
)
2161 query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, NULL
, &size
, NULL
);
2162 if (get_last_error() != ERROR_INSUFFICIENT_BUFFER
) return FALSE
;
2163 if (!(ret
= heap_alloc( size
))) return NULL
;
2164 *len
= size
/ sizeof(WCHAR
);
2165 if (query_headers( request
, WINHTTP_QUERY_LOCATION
, NULL
, ret
, &size
, NULL
)) return ret
;
2170 static BOOL
handle_redirect( request_t
*request
, DWORD status
)
2175 connect_t
*connect
= request
->connect
;
2177 WCHAR
*hostname
= NULL
, *location
;
2180 if (!(location
= get_redirect_url( request
, &len_url
))) return FALSE
;
2182 memset( &uc
, 0, sizeof(uc
) );
2183 uc
.dwStructSize
= sizeof(uc
);
2184 uc
.dwSchemeLength
= uc
.dwHostNameLength
= uc
.dwUrlPathLength
= uc
.dwExtraInfoLength
= ~0u;
2186 if (!WinHttpCrackUrl( location
, len_url
, 0, &uc
)) /* assume relative redirect */
2190 len
= strlenW( location
) + 1;
2191 if (location
[0] != '/') len
++;
2192 if (!(p
= path
= heap_alloc( len
* sizeof(WCHAR
) ))) goto end
;
2194 if (location
[0] != '/') *p
++ = '/';
2195 strcpyW( p
, location
);
2197 heap_free( request
->path
);
2198 request
->path
= path
;
2200 drain_content( request
);
2201 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_url
+ 1 );
2205 if (uc
.nScheme
== INTERNET_SCHEME_HTTP
&& request
->hdr
.flags
& WINHTTP_FLAG_SECURE
)
2207 if (request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP
) goto end
;
2208 TRACE("redirect from secure page to non-secure page\n");
2209 request
->hdr
.flags
&= ~WINHTTP_FLAG_SECURE
;
2211 else if (uc
.nScheme
== INTERNET_SCHEME_HTTPS
&& !(request
->hdr
.flags
& WINHTTP_FLAG_SECURE
))
2213 TRACE("redirect from non-secure page to secure page\n");
2214 request
->hdr
.flags
|= WINHTTP_FLAG_SECURE
;
2217 drain_content( request
);
2218 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REDIRECT
, location
, len_url
+ 1 );
2220 len
= uc
.dwHostNameLength
;
2221 if (!(hostname
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2222 memcpy( hostname
, uc
.lpszHostName
, len
* sizeof(WCHAR
) );
2225 port
= uc
.nPort
? uc
.nPort
: (uc
.nScheme
== INTERNET_SCHEME_HTTPS
? 443 : 80);
2226 if (strcmpiW( connect
->hostname
, hostname
) || connect
->serverport
!= port
)
2228 heap_free( connect
->hostname
);
2229 connect
->hostname
= hostname
;
2230 connect
->hostport
= port
;
2231 if (!(ret
= set_server_for_hostname( connect
, hostname
, port
))) goto end
;
2233 netconn_close( &request
->netconn
);
2234 if (!(ret
= netconn_init( &request
->netconn
))) goto end
;
2235 request
->read_pos
= request
->read_size
= 0;
2236 request
->read_chunked
= FALSE
;
2238 if (!(ret
= add_host_header( request
, WINHTTP_ADDREQ_FLAG_REPLACE
))) goto end
;
2239 if (!(ret
= open_connection( request
))) goto end
;
2241 heap_free( request
->path
);
2242 request
->path
= NULL
;
2243 if (uc
.dwUrlPathLength
)
2245 len
= uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
;
2246 if (!(request
->path
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) goto end
;
2247 strcpyW( request
->path
, uc
.lpszUrlPath
);
2249 else request
->path
= strdupW( slashW
);
2252 /* remove content-type/length headers */
2253 if ((index
= get_header_index( request
, attr_content_type
, 0, TRUE
)) >= 0) delete_header( request
, index
);
2254 if ((index
= get_header_index( request
, attr_content_length
, 0, TRUE
)) >= 0 ) delete_header( request
, index
);
2256 if (status
!= HTTP_STATUS_REDIRECT_KEEP_VERB
&& !strcmpW( request
->verb
, postW
))
2258 heap_free( request
->verb
);
2259 request
->verb
= strdupW( getW
);
2260 request
->optional
= NULL
;
2261 request
->optional_len
= 0;
2266 if (!ret
) heap_free( hostname
);
2267 heap_free( location
);
2271 static BOOL
receive_response( request_t
*request
, BOOL async
)
2274 DWORD size
, query
, status
;
2278 if (!(ret
= read_reply( request
)))
2280 set_last_error( ERROR_WINHTTP_INVALID_SERVER_RESPONSE
);
2283 size
= sizeof(DWORD
);
2284 query
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
2285 if (!(ret
= query_headers( request
, query
, NULL
, &status
, &size
, NULL
))) break;
2287 set_content_length( request
);
2289 if (!(request
->hdr
.disable_flags
& WINHTTP_DISABLE_COOKIES
)) record_cookies( request
);
2291 if (status
== HTTP_STATUS_MOVED
|| status
== HTTP_STATUS_REDIRECT
|| status
== HTTP_STATUS_REDIRECT_KEEP_VERB
)
2293 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_REDIRECTS
||
2294 request
->hdr
.redirect_policy
== WINHTTP_OPTION_REDIRECT_POLICY_NEVER
) break;
2296 if (!(ret
= handle_redirect( request
, status
))) break;
2298 /* recurse synchronously */
2299 send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
);
2302 else if (status
== HTTP_STATUS_DENIED
|| status
== HTTP_STATUS_PROXY_AUTH_REQ
)
2304 if (request
->hdr
.disable_flags
& WINHTTP_DISABLE_AUTHENTICATION
) break;
2306 drain_content( request
);
2307 if (!handle_authorization( request
, status
))
2312 /* recurse synchronously */
2313 send_request( request
, NULL
, 0, request
->optional
, request
->optional_len
, 0, 0, FALSE
);
2321 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
, NULL
, 0 );
2324 WINHTTP_ASYNC_RESULT result
;
2325 result
.dwResult
= API_RECEIVE_RESPONSE
;
2326 result
.dwError
= get_last_error();
2327 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2333 static void task_receive_response( task_header_t
*task
)
2335 receive_response_t
*r
= (receive_response_t
*)task
;
2336 receive_response( r
->hdr
.request
, TRUE
);
2339 /***********************************************************************
2340 * WinHttpReceiveResponse (winhttp.@)
2342 BOOL WINAPI
WinHttpReceiveResponse( HINTERNET hrequest
, LPVOID reserved
)
2347 TRACE("%p, %p\n", hrequest
, reserved
);
2349 if (!(request
= (request_t
*)grab_object( hrequest
)))
2351 set_last_error( ERROR_INVALID_HANDLE
);
2354 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2356 release_object( &request
->hdr
);
2357 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2361 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2363 receive_response_t
*r
;
2365 if (!(r
= heap_alloc( sizeof(receive_response_t
) ))) return FALSE
;
2366 r
->hdr
.request
= request
;
2367 r
->hdr
.proc
= task_receive_response
;
2369 addref_object( &request
->hdr
);
2370 ret
= queue_task( (task_header_t
*)r
);
2373 ret
= receive_response( request
, FALSE
);
2375 release_object( &request
->hdr
);
2379 static BOOL
query_data_available( request_t
*request
, DWORD
*available
, BOOL async
)
2384 if (!(count
= get_available_data( request
)))
2386 if (end_of_read_data( request
))
2388 if (available
) *available
= 0;
2392 refill_buffer( request
);
2393 count
= get_available_data( request
);
2395 if (count
== sizeof(request
->read_buf
)) /* check if we have even more pending in the socket */
2398 if ((ret
= netconn_query_data_available( &request
->netconn
, &extra
)))
2400 count
= min( count
+ extra
, request
->content_length
- request
->content_read
);
2405 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
, &count
, sizeof(count
) );
2408 WINHTTP_ASYNC_RESULT result
;
2409 result
.dwResult
= API_QUERY_DATA_AVAILABLE
;
2410 result
.dwError
= get_last_error();
2411 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2416 TRACE("%u bytes available\n", count
);
2417 if (available
) *available
= count
;
2422 static void task_query_data_available( task_header_t
*task
)
2424 query_data_t
*q
= (query_data_t
*)task
;
2425 query_data_available( q
->hdr
.request
, q
->available
, TRUE
);
2428 /***********************************************************************
2429 * WinHttpQueryDataAvailable (winhttp.@)
2431 BOOL WINAPI
WinHttpQueryDataAvailable( HINTERNET hrequest
, LPDWORD available
)
2436 TRACE("%p, %p\n", hrequest
, available
);
2438 if (!(request
= (request_t
*)grab_object( hrequest
)))
2440 set_last_error( ERROR_INVALID_HANDLE
);
2443 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2445 release_object( &request
->hdr
);
2446 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2450 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2454 if (!(q
= heap_alloc( sizeof(query_data_t
) ))) return FALSE
;
2455 q
->hdr
.request
= request
;
2456 q
->hdr
.proc
= task_query_data_available
;
2457 q
->available
= available
;
2459 addref_object( &request
->hdr
);
2460 ret
= queue_task( (task_header_t
*)q
);
2463 ret
= query_data_available( request
, available
, FALSE
);
2465 release_object( &request
->hdr
);
2469 static void task_read_data( task_header_t
*task
)
2471 read_data_t
*r
= (read_data_t
*)task
;
2472 read_data( r
->hdr
.request
, r
->buffer
, r
->to_read
, r
->read
, TRUE
);
2475 /***********************************************************************
2476 * WinHttpReadData (winhttp.@)
2478 BOOL WINAPI
WinHttpReadData( HINTERNET hrequest
, LPVOID buffer
, DWORD to_read
, LPDWORD read
)
2483 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_read
, read
);
2485 if (!(request
= (request_t
*)grab_object( hrequest
)))
2487 set_last_error( ERROR_INVALID_HANDLE
);
2490 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2492 release_object( &request
->hdr
);
2493 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2497 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2501 if (!(r
= heap_alloc( sizeof(read_data_t
) ))) return FALSE
;
2502 r
->hdr
.request
= request
;
2503 r
->hdr
.proc
= task_read_data
;
2505 r
->to_read
= to_read
;
2508 addref_object( &request
->hdr
);
2509 ret
= queue_task( (task_header_t
*)r
);
2512 ret
= read_data( request
, buffer
, to_read
, read
, FALSE
);
2514 release_object( &request
->hdr
);
2518 static BOOL
write_data( request_t
*request
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
, BOOL async
)
2523 ret
= netconn_send( &request
->netconn
, buffer
, to_write
, &num_bytes
);
2527 if (ret
) send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
, &num_bytes
, sizeof(DWORD
) );
2530 WINHTTP_ASYNC_RESULT result
;
2531 result
.dwResult
= API_WRITE_DATA
;
2532 result
.dwError
= get_last_error();
2533 send_callback( &request
->hdr
, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
, &result
, sizeof(result
) );
2536 if (ret
&& written
) *written
= num_bytes
;
2540 static void task_write_data( task_header_t
*task
)
2542 write_data_t
*w
= (write_data_t
*)task
;
2543 write_data( w
->hdr
.request
, w
->buffer
, w
->to_write
, w
->written
, TRUE
);
2546 /***********************************************************************
2547 * WinHttpWriteData (winhttp.@)
2549 BOOL WINAPI
WinHttpWriteData( HINTERNET hrequest
, LPCVOID buffer
, DWORD to_write
, LPDWORD written
)
2554 TRACE("%p, %p, %d, %p\n", hrequest
, buffer
, to_write
, written
);
2556 if (!(request
= (request_t
*)grab_object( hrequest
)))
2558 set_last_error( ERROR_INVALID_HANDLE
);
2561 if (request
->hdr
.type
!= WINHTTP_HANDLE_TYPE_REQUEST
)
2563 release_object( &request
->hdr
);
2564 set_last_error( ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
);
2568 if (request
->connect
->hdr
.flags
& WINHTTP_FLAG_ASYNC
)
2572 if (!(w
= heap_alloc( sizeof(write_data_t
) ))) return FALSE
;
2573 w
->hdr
.request
= request
;
2574 w
->hdr
.proc
= task_write_data
;
2576 w
->to_write
= to_write
;
2577 w
->written
= written
;
2579 addref_object( &request
->hdr
);
2580 ret
= queue_task( (task_header_t
*)w
);
2583 ret
= write_data( request
, buffer
, to_write
, written
, FALSE
);
2585 release_object( &request
->hdr
);
2591 REQUEST_STATE_UNINITIALIZED
,
2592 REQUEST_STATE_INITIALIZED
,
2593 REQUEST_STATE_CANCELLED
,
2596 REQUEST_STATE_RESPONSE_RECEIVED
2599 struct winhttp_request
2601 IWinHttpRequest IWinHttpRequest_iface
;
2603 CRITICAL_SECTION cs
;
2604 enum request_state state
;
2615 DWORD bytes_available
;
2619 DWORD disable_feature
;
2620 LONG resolve_timeout
;
2621 LONG connect_timeout
;
2623 LONG receive_timeout
;
2624 WINHTTP_PROXY_INFO proxy
;
2627 static inline struct winhttp_request
*impl_from_IWinHttpRequest( IWinHttpRequest
*iface
)
2629 return CONTAINING_RECORD( iface
, struct winhttp_request
, IWinHttpRequest_iface
);
2632 static ULONG WINAPI
winhttp_request_AddRef(
2633 IWinHttpRequest
*iface
)
2635 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2636 return InterlockedIncrement( &request
->refs
);
2639 /* critical section must be held */
2640 static void cancel_request( struct winhttp_request
*request
)
2642 if (request
->state
<= REQUEST_STATE_CANCELLED
) return;
2643 if (request
->thread
) SetEvent( request
->cancel
);
2644 request
->state
= REQUEST_STATE_CANCELLED
;
2647 /* critical section must be held */
2648 static void free_request( struct winhttp_request
*request
)
2650 if (request
->state
< REQUEST_STATE_INITIALIZED
) return;
2651 WinHttpCloseHandle( request
->hrequest
);
2652 WinHttpCloseHandle( request
->hconnect
);
2653 WinHttpCloseHandle( request
->hsession
);
2654 CloseHandle( request
->thread
);
2655 CloseHandle( request
->wait
);
2656 CloseHandle( request
->cancel
);
2657 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2658 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2659 heap_free( request
->buffer
);
2660 heap_free( request
->verb
);
2661 VariantClear( &request
->data
);
2664 static ULONG WINAPI
winhttp_request_Release(
2665 IWinHttpRequest
*iface
)
2667 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2668 LONG refs
= InterlockedDecrement( &request
->refs
);
2671 TRACE("destroying %p\n", request
);
2673 EnterCriticalSection( &request
->cs
);
2674 cancel_request( request
);
2675 free_request( request
);
2676 LeaveCriticalSection( &request
->cs
);
2677 request
->cs
.DebugInfo
->Spare
[0] = 0;
2678 DeleteCriticalSection( &request
->cs
);
2679 heap_free( request
);
2684 static HRESULT WINAPI
winhttp_request_QueryInterface(
2685 IWinHttpRequest
*iface
,
2689 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2691 TRACE("%p, %s, %p\n", request
, debugstr_guid(riid
), obj
);
2693 if (IsEqualGUID( riid
, &IID_IWinHttpRequest
) ||
2694 IsEqualGUID( riid
, &IID_IDispatch
) ||
2695 IsEqualGUID( riid
, &IID_IUnknown
))
2701 FIXME("interface %s not implemented\n", debugstr_guid(riid
));
2702 return E_NOINTERFACE
;
2704 IWinHttpRequest_AddRef( iface
);
2708 static HRESULT WINAPI
winhttp_request_GetTypeInfoCount(
2709 IWinHttpRequest
*iface
,
2712 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2714 TRACE("%p, %p\n", request
, count
);
2721 IWinHttpRequest_tid
,
2725 static ITypeLib
*winhttp_typelib
;
2726 static ITypeInfo
*winhttp_typeinfo
[last_tid
];
2728 static REFIID winhttp_tid_id
[] =
2730 &IID_IWinHttpRequest
2733 static HRESULT
get_typeinfo( enum type_id tid
, ITypeInfo
**ret
)
2737 if (!winhttp_typelib
)
2741 hr
= LoadRegTypeLib( &LIBID_WinHttp
, 5, 1, LOCALE_SYSTEM_DEFAULT
, &typelib
);
2744 ERR("LoadRegTypeLib failed: %08x\n", hr
);
2747 if (InterlockedCompareExchangePointer( (void **)&winhttp_typelib
, typelib
, NULL
))
2748 ITypeLib_Release( typelib
);
2750 if (!winhttp_typeinfo
[tid
])
2752 ITypeInfo
*typeinfo
;
2754 hr
= ITypeLib_GetTypeInfoOfGuid( winhttp_typelib
, winhttp_tid_id
[tid
], &typeinfo
);
2757 ERR("GetTypeInfoOfGuid(%s) failed: %08x\n", debugstr_guid(winhttp_tid_id
[tid
]), hr
);
2760 if (InterlockedCompareExchangePointer( (void **)(winhttp_typeinfo
+ tid
), typeinfo
, NULL
))
2761 ITypeInfo_Release( typeinfo
);
2763 *ret
= winhttp_typeinfo
[tid
];
2767 static HRESULT WINAPI
winhttp_request_GetTypeInfo(
2768 IWinHttpRequest
*iface
,
2773 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2774 TRACE("%p, %u, %u, %p\n", request
, index
, lcid
, info
);
2776 return get_typeinfo( IWinHttpRequest_tid
, info
);
2779 static HRESULT WINAPI
winhttp_request_GetIDsOfNames(
2780 IWinHttpRequest
*iface
,
2787 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2788 ITypeInfo
*typeinfo
;
2791 TRACE("%p, %s, %p, %u, %u, %p\n", request
, debugstr_guid(riid
), names
, count
, lcid
, dispid
);
2793 if (!names
|| !count
|| !dispid
) return E_INVALIDARG
;
2795 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
2798 hr
= ITypeInfo_GetIDsOfNames( typeinfo
, names
, count
, dispid
);
2799 ITypeInfo_Release( typeinfo
);
2804 static HRESULT WINAPI
winhttp_request_Invoke(
2805 IWinHttpRequest
*iface
,
2812 EXCEPINFO
*excep_info
,
2815 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2816 ITypeInfo
*typeinfo
;
2819 TRACE("%p, %d, %s, %d, %d, %p, %p, %p, %p\n", request
, member
, debugstr_guid(riid
),
2820 lcid
, flags
, params
, result
, excep_info
, arg_err
);
2822 hr
= get_typeinfo( IWinHttpRequest_tid
, &typeinfo
);
2825 hr
= ITypeInfo_Invoke( typeinfo
, &request
->IWinHttpRequest_iface
, member
, flags
,
2826 params
, result
, excep_info
, arg_err
);
2827 ITypeInfo_Release( typeinfo
);
2832 static HRESULT WINAPI
winhttp_request_SetProxy(
2833 IWinHttpRequest
*iface
,
2834 HTTPREQUEST_PROXY_SETTING proxy_setting
,
2835 VARIANT proxy_server
,
2836 VARIANT bypass_list
)
2838 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2839 DWORD err
= ERROR_SUCCESS
;
2841 TRACE("%p, %u, %s, %s\n", request
, proxy_setting
, debugstr_variant(&proxy_server
),
2842 debugstr_variant(&bypass_list
));
2844 EnterCriticalSection( &request
->cs
);
2845 switch (proxy_setting
)
2847 case HTTPREQUEST_PROXYSETTING_DEFAULT
:
2848 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
2849 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2850 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2851 request
->proxy
.lpszProxy
= NULL
;
2852 request
->proxy
.lpszProxyBypass
= NULL
;
2855 case HTTPREQUEST_PROXYSETTING_DIRECT
:
2856 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NO_PROXY
;
2857 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2858 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2859 request
->proxy
.lpszProxy
= NULL
;
2860 request
->proxy
.lpszProxyBypass
= NULL
;
2863 case HTTPREQUEST_PROXYSETTING_PROXY
:
2864 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
2865 if (V_VT( &proxy_server
) == VT_BSTR
)
2867 heap_free( (WCHAR
*)request
->proxy
.lpszProxy
);
2868 request
->proxy
.lpszProxy
= strdupW( V_BSTR( &proxy_server
) );
2870 if (V_VT( &bypass_list
) == VT_BSTR
)
2872 heap_free( (WCHAR
*)request
->proxy
.lpszProxyBypass
);
2873 request
->proxy
.lpszProxyBypass
= strdupW( V_BSTR( &bypass_list
) );
2878 err
= ERROR_INVALID_PARAMETER
;
2881 LeaveCriticalSection( &request
->cs
);
2882 return HRESULT_FROM_WIN32( err
);
2885 static HRESULT WINAPI
winhttp_request_SetCredentials(
2886 IWinHttpRequest
*iface
,
2889 HTTPREQUEST_SETCREDENTIALS_FLAGS flags
)
2891 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2892 DWORD target
, scheme
= WINHTTP_AUTH_SCHEME_BASIC
; /* FIXME: query supported schemes */
2893 DWORD err
= ERROR_SUCCESS
;
2895 TRACE("%p, %s, %p\n", request
, debugstr_w(username
), password
);
2897 EnterCriticalSection( &request
->cs
);
2898 if (request
->state
< REQUEST_STATE_OPEN
)
2900 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
2905 case HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
:
2906 target
= WINHTTP_AUTH_TARGET_SERVER
;
2908 case HTTPREQUEST_SETCREDENTIALS_FOR_PROXY
:
2909 target
= WINHTTP_AUTH_TARGET_PROXY
;
2912 err
= ERROR_INVALID_PARAMETER
;
2915 if (!WinHttpSetCredentials( request
->hrequest
, target
, scheme
, username
, password
, NULL
))
2917 err
= get_last_error();
2920 LeaveCriticalSection( &request
->cs
);
2921 return HRESULT_FROM_WIN32( err
);
2924 static void initialize_request( struct winhttp_request
*request
)
2926 request
->hrequest
= NULL
;
2927 request
->hconnect
= NULL
;
2928 request
->hsession
= NULL
;
2929 request
->thread
= NULL
;
2930 request
->wait
= NULL
;
2931 request
->cancel
= NULL
;
2932 request
->buffer
= NULL
;
2933 request
->verb
= NULL
;
2934 request
->offset
= 0;
2935 request
->bytes_available
= 0;
2936 request
->bytes_read
= 0;
2937 request
->error
= ERROR_SUCCESS
;
2938 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
2939 request
->disable_feature
= WINHTTP_DISABLE_AUTHENTICATION
;
2940 request
->proxy
.dwAccessType
= WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
;
2941 request
->proxy
.lpszProxy
= NULL
;
2942 request
->proxy
.lpszProxyBypass
= NULL
;
2943 request
->resolve_timeout
= 0;
2944 request
->connect_timeout
= 60000;
2945 request
->send_timeout
= 30000;
2946 request
->receive_timeout
= 30000;
2947 VariantInit( &request
->data
);
2948 request
->state
= REQUEST_STATE_INITIALIZED
;
2951 static HRESULT WINAPI
winhttp_request_Open(
2952 IWinHttpRequest
*iface
,
2957 static const WCHAR typeW
[] = {'*','/','*',0};
2958 static const WCHAR
*acceptW
[] = {typeW
, NULL
};
2959 static const WCHAR httpsW
[] = {'h','t','t','p','s'};
2960 static const WCHAR user_agentW
[] = {
2961 'M','o','z','i','l','l','a','/','4','.','0',' ','(','c','o','m','p','a','t','i','b','l','e',';',' ',
2962 'W','i','n','3','2',';',' ','W','i','n','H','t','t','p','.','W','i','n','H','t','t','p',
2963 'R','e','q','u','e','s','t','.','5',')',0};
2964 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
2965 HINTERNET hsession
= NULL
, hconnect
= NULL
, hrequest
;
2967 WCHAR
*hostname
, *path
= NULL
, *verb
= NULL
;
2968 DWORD err
= ERROR_OUTOFMEMORY
, len
, flags
= 0, request_flags
= 0;
2970 TRACE("%p, %s, %s, %s\n", request
, debugstr_w(method
), debugstr_w(url
),
2971 debugstr_variant(&async
));
2973 if (!method
|| !url
) return E_INVALIDARG
;
2975 memset( &uc
, 0, sizeof(uc
) );
2976 uc
.dwStructSize
= sizeof(uc
);
2977 uc
.dwSchemeLength
= ~0u;
2978 uc
.dwHostNameLength
= ~0u;
2979 uc
.dwUrlPathLength
= ~0u;
2980 uc
.dwExtraInfoLength
= ~0u;
2981 if (!WinHttpCrackUrl( url
, 0, 0, &uc
)) return HRESULT_FROM_WIN32( get_last_error() );
2983 EnterCriticalSection( &request
->cs
);
2984 if (request
->state
!= REQUEST_STATE_INITIALIZED
)
2986 cancel_request( request
);
2987 free_request( request
);
2988 initialize_request( request
);
2990 if (!(hostname
= heap_alloc( (uc
.dwHostNameLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
2991 memcpy( hostname
, uc
.lpszHostName
, uc
.dwHostNameLength
* sizeof(WCHAR
) );
2992 hostname
[uc
.dwHostNameLength
] = 0;
2994 if (!(path
= heap_alloc( (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
+ 1) * sizeof(WCHAR
) ))) goto error
;
2995 memcpy( path
, uc
.lpszUrlPath
, (uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
) * sizeof(WCHAR
) );
2996 path
[uc
.dwUrlPathLength
+ uc
.dwExtraInfoLength
] = 0;
2998 if (!(verb
= strdupW( method
))) goto error
;
2999 if (V_BOOL( &async
)) flags
|= WINHTTP_FLAG_ASYNC
;
3000 if (!(hsession
= WinHttpOpen( user_agentW
, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
, NULL
, NULL
, flags
)))
3002 err
= get_last_error();
3005 if (!(hconnect
= WinHttpConnect( hsession
, hostname
, uc
.nPort
, 0 )))
3007 err
= get_last_error();
3010 len
= sizeof(httpsW
) / sizeof(WCHAR
);
3011 if (uc
.dwSchemeLength
== len
&& !memcmp( uc
.lpszScheme
, httpsW
, len
* sizeof(WCHAR
) ))
3013 request_flags
|= WINHTTP_FLAG_SECURE
;
3015 if (!(hrequest
= WinHttpOpenRequest( hconnect
, method
, path
, NULL
, NULL
, acceptW
, request_flags
)))
3017 err
= get_last_error();
3020 if (flags
& WINHTTP_FLAG_ASYNC
)
3022 request
->wait
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
3023 request
->cancel
= CreateEventW( NULL
, FALSE
, FALSE
, NULL
);
3024 WinHttpSetOption( hrequest
, WINHTTP_OPTION_CONTEXT_VALUE
, &request
, sizeof(request
) );
3026 request
->state
= REQUEST_STATE_OPEN
;
3027 request
->hsession
= hsession
;
3028 request
->hconnect
= hconnect
;
3029 request
->hrequest
= hrequest
;
3030 request
->verb
= verb
;
3031 heap_free( hostname
);
3033 LeaveCriticalSection( &request
->cs
);
3037 WinHttpCloseHandle( hconnect
);
3038 WinHttpCloseHandle( hsession
);
3039 heap_free( hostname
);
3042 LeaveCriticalSection( &request
->cs
);
3043 return HRESULT_FROM_WIN32( err
);
3046 static HRESULT WINAPI
winhttp_request_SetRequestHeader(
3047 IWinHttpRequest
*iface
,
3051 static const WCHAR fmtW
[] = {'%','s',':',' ','%','s','\r','\n',0};
3052 static const WCHAR emptyW
[] = {0};
3053 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3054 DWORD len
, err
= ERROR_SUCCESS
;
3057 TRACE("%p, %s, %s\n", request
, debugstr_w(header
), debugstr_w(value
));
3059 if (!header
) return E_INVALIDARG
;
3061 EnterCriticalSection( &request
->cs
);
3062 if (request
->state
< REQUEST_STATE_OPEN
)
3064 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
;
3067 if (request
->state
>= REQUEST_STATE_SENT
)
3069 err
= ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND
;
3072 len
= strlenW( header
) + 4;
3073 if (value
) len
+= strlenW( value
);
3074 if (!(str
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) )))
3076 err
= ERROR_OUTOFMEMORY
;
3079 sprintfW( str
, fmtW
, header
, value
? value
: emptyW
);
3080 if (!WinHttpAddRequestHeaders( request
->hrequest
, str
, len
, WINHTTP_ADDREQ_FLAG_REPLACE
))
3082 err
= get_last_error();
3087 LeaveCriticalSection( &request
->cs
);
3088 return HRESULT_FROM_WIN32( err
);
3091 static HRESULT WINAPI
winhttp_request_GetResponseHeader(
3092 IWinHttpRequest
*iface
,
3096 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3097 DWORD size
, err
= ERROR_SUCCESS
;
3099 TRACE("%p, %p\n", request
, header
);
3101 EnterCriticalSection( &request
->cs
);
3102 if (request
->state
< REQUEST_STATE_SENT
)
3104 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3107 if (!header
|| !value
)
3109 err
= ERROR_INVALID_PARAMETER
;
3113 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, NULL
, &size
, NULL
))
3115 err
= get_last_error();
3116 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3118 if (!(*value
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
3120 err
= ERROR_OUTOFMEMORY
;
3123 err
= ERROR_SUCCESS
;
3124 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CUSTOM
, header
, *value
, &size
, NULL
))
3126 err
= get_last_error();
3127 SysFreeString( *value
);
3130 LeaveCriticalSection( &request
->cs
);
3131 return HRESULT_FROM_WIN32( err
);
3134 static HRESULT WINAPI
winhttp_request_GetAllResponseHeaders(
3135 IWinHttpRequest
*iface
,
3138 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3139 DWORD size
, err
= ERROR_SUCCESS
;
3141 TRACE("%p, %p\n", request
, headers
);
3143 if (!headers
) return E_INVALIDARG
;
3145 EnterCriticalSection( &request
->cs
);
3146 if (request
->state
< REQUEST_STATE_SENT
)
3148 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3152 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, NULL
, &size
, NULL
))
3154 err
= get_last_error();
3155 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3157 if (!(*headers
= SysAllocStringLen( NULL
, size
/ sizeof(WCHAR
) )))
3159 err
= ERROR_OUTOFMEMORY
;
3162 err
= ERROR_SUCCESS
;
3163 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_RAW_HEADERS_CRLF
, NULL
, *headers
, &size
, NULL
))
3165 err
= get_last_error();
3166 SysFreeString( *headers
);
3169 LeaveCriticalSection( &request
->cs
);
3170 return HRESULT_FROM_WIN32( err
);
3173 static void CALLBACK
wait_status_callback( HINTERNET handle
, DWORD_PTR context
, DWORD status
, LPVOID buffer
, DWORD size
)
3175 struct winhttp_request
*request
= (struct winhttp_request
*)context
;
3179 case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
:
3180 request
->bytes_available
= *(DWORD
*)buffer
;
3181 request
->error
= ERROR_SUCCESS
;
3183 case WINHTTP_CALLBACK_STATUS_READ_COMPLETE
:
3184 request
->bytes_read
= size
;
3185 request
->error
= ERROR_SUCCESS
;
3187 case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
:
3189 WINHTTP_ASYNC_RESULT
*result
= (WINHTTP_ASYNC_RESULT
*)buffer
;
3190 request
->error
= result
->dwError
;
3195 SetEvent( request
->wait
);
3198 static void wait_set_status_callback( struct winhttp_request
*request
, DWORD status
)
3200 if (!request
->wait
) return;
3201 status
|= WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
;
3202 WinHttpSetStatusCallback( request
->hrequest
, wait_status_callback
, status
, 0 );
3205 static DWORD
wait_for_completion( struct winhttp_request
*request
)
3211 request
->error
= ERROR_SUCCESS
;
3212 return ERROR_SUCCESS
;
3214 handles
[0] = request
->wait
;
3215 handles
[1] = request
->cancel
;
3216 switch (WaitForMultipleObjects( 2, handles
, FALSE
, INFINITE
))
3220 case WAIT_OBJECT_0
+ 1:
3221 request
->error
= ERROR_CANCELLED
;
3224 request
->error
= get_last_error();
3227 return request
->error
;
3230 static HRESULT
request_receive( struct winhttp_request
*request
)
3232 DWORD err
, size
, buflen
= 4096;
3234 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
);
3235 if (!WinHttpReceiveResponse( request
->hrequest
, NULL
))
3237 return HRESULT_FROM_WIN32( get_last_error() );
3239 if ((err
= wait_for_completion( request
))) return HRESULT_FROM_WIN32( err
);
3240 if (!strcmpW( request
->verb
, headW
))
3242 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
3245 if (!(request
->buffer
= heap_alloc( buflen
))) return E_OUTOFMEMORY
;
3246 request
->buffer
[0] = 0;
3250 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
);
3251 if (!WinHttpQueryDataAvailable( request
->hrequest
, &request
->bytes_available
))
3253 err
= get_last_error();
3256 if ((err
= wait_for_completion( request
))) goto error
;
3257 if (!request
->bytes_available
) break;
3258 size
+= request
->bytes_available
;
3262 while (buflen
< size
) buflen
*= 2;
3263 if (!(tmp
= heap_realloc( request
->buffer
, buflen
)))
3265 err
= ERROR_OUTOFMEMORY
;
3268 request
->buffer
= tmp
;
3270 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_READ_COMPLETE
);
3271 if (!WinHttpReadData( request
->hrequest
, request
->buffer
+ request
->offset
,
3272 request
->bytes_available
, &request
->bytes_read
))
3274 err
= get_last_error();
3277 if ((err
= wait_for_completion( request
))) goto error
;
3278 request
->offset
+= request
->bytes_read
;
3279 } while (request
->bytes_read
);
3281 request
->state
= REQUEST_STATE_RESPONSE_RECEIVED
;
3285 heap_free( request
->buffer
);
3286 request
->buffer
= NULL
;
3287 return HRESULT_FROM_WIN32( err
);
3290 static DWORD
request_set_parameters( struct winhttp_request
*request
)
3292 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_PROXY
, &request
->proxy
,
3293 sizeof(request
->proxy
) )) return get_last_error();
3295 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_AUTOLOGON_POLICY
, &request
->logon_policy
,
3296 sizeof(request
->logon_policy
) )) return get_last_error();
3298 if (!WinHttpSetOption( request
->hrequest
, WINHTTP_OPTION_DISABLE_FEATURE
, &request
->disable_feature
,
3299 sizeof(request
->disable_feature
) )) return get_last_error();
3301 if (!WinHttpSetTimeouts( request
->hrequest
,
3302 request
->resolve_timeout
,
3303 request
->connect_timeout
,
3304 request
->send_timeout
,
3305 request
->receive_timeout
)) return get_last_error();
3306 return ERROR_SUCCESS
;
3309 static void request_set_utf8_content_type( struct winhttp_request
*request
)
3311 static const WCHAR fmtW
[] = {'%','s',':',' ','%','s',0};
3312 static const WCHAR text_plainW
[] = {'t','e','x','t','/','p','l','a','i','n',0};
3313 static const WCHAR charset_utf8W
[] = {'c','h','a','r','s','e','t','=','u','t','f','-','8',0};
3317 len
= sprintfW( headerW
, fmtW
, attr_content_type
, text_plainW
);
3318 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_ADD_IF_NEW
);
3319 len
= sprintfW( headerW
, fmtW
, attr_content_type
, charset_utf8W
);
3320 WinHttpAddRequestHeaders( request
->hrequest
, headerW
, len
, WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON
);
3323 static HRESULT
request_send( struct winhttp_request
*request
)
3325 SAFEARRAY
*sa
= NULL
;
3332 if ((err
= request_set_parameters( request
))) return HRESULT_FROM_WIN32( err
);
3333 if (strcmpW( request
->verb
, getW
))
3335 VariantInit( &data
);
3336 if (V_VT( &request
->data
) == VT_BSTR
)
3339 const WCHAR
*str
= V_BSTR( &request
->data
);
3340 int i
, len
= strlenW( str
);
3342 for (i
= 0; i
< len
; i
++)
3350 size
= WideCharToMultiByte( cp
, 0, str
, len
, NULL
, 0, NULL
, NULL
);
3351 if (!(ptr
= heap_alloc( size
))) return E_OUTOFMEMORY
;
3352 WideCharToMultiByte( cp
, 0, str
, len
, ptr
, size
, NULL
, NULL
);
3353 if (cp
== CP_UTF8
) request_set_utf8_content_type( request
);
3355 else if (VariantChangeType( &data
, &request
->data
, 0, VT_ARRAY
|VT_UI1
) == S_OK
)
3357 sa
= V_ARRAY( &data
);
3358 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
) return hr
;
3359 if ((hr
= SafeArrayGetUBound( sa
, 1, &size
) != S_OK
))
3361 SafeArrayUnaccessData( sa
);
3367 wait_set_status_callback( request
, WINHTTP_CALLBACK_STATUS_REQUEST_SENT
);
3368 if (!WinHttpSendRequest( request
->hrequest
, NULL
, 0, ptr
, size
, size
, 0 ))
3370 err
= get_last_error();
3373 if ((err
= wait_for_completion( request
))) goto error
;
3374 if (sa
) SafeArrayUnaccessData( sa
);
3375 else heap_free( ptr
);
3376 request
->state
= REQUEST_STATE_SENT
;
3380 if (sa
) SafeArrayUnaccessData( sa
);
3381 else heap_free( ptr
);
3382 return HRESULT_FROM_WIN32( err
);
3385 static HRESULT
request_send_and_receive( struct winhttp_request
*request
)
3387 HRESULT hr
= request_send( request
);
3388 if (hr
== S_OK
) hr
= request_receive( request
);
3392 static DWORD CALLBACK
send_and_receive_proc( void *arg
)
3394 struct winhttp_request
*request
= (struct winhttp_request
*)arg
;
3395 return request_send_and_receive( request
);
3398 static HRESULT WINAPI
winhttp_request_Send(
3399 IWinHttpRequest
*iface
,
3402 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3405 TRACE("%p, %s\n", request
, debugstr_variant(&body
));
3407 EnterCriticalSection( &request
->cs
);
3408 if (request
->state
< REQUEST_STATE_OPEN
)
3410 LeaveCriticalSection( &request
->cs
);
3411 return HRESULT_FROM_WIN32( ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN
);
3413 if (request
->state
>= REQUEST_STATE_SENT
)
3415 LeaveCriticalSection( &request
->cs
);
3418 VariantClear( &request
->data
);
3419 if ((hr
= VariantCopyInd( &request
->data
, &body
)) != S_OK
) {
3420 LeaveCriticalSection( &request
->cs
);
3424 if (request
->wait
) /* async request */
3426 if (!(request
->thread
= CreateThread( NULL
, 0, send_and_receive_proc
, request
, 0, NULL
)))
3428 LeaveCriticalSection( &request
->cs
);
3429 return HRESULT_FROM_WIN32( get_last_error() );
3432 else hr
= request_send_and_receive( request
);
3433 LeaveCriticalSection( &request
->cs
);
3437 static HRESULT WINAPI
winhttp_request_get_Status(
3438 IWinHttpRequest
*iface
,
3441 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3442 DWORD err
= ERROR_SUCCESS
, flags
, status_code
, len
= sizeof(status_code
), index
= 0;
3444 TRACE("%p, %p\n", request
, status
);
3446 if (!status
) return E_INVALIDARG
;
3448 EnterCriticalSection( &request
->cs
);
3449 if (request
->state
< REQUEST_STATE_SENT
)
3451 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3454 flags
= WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
;
3455 if (!WinHttpQueryHeaders( request
->hrequest
, flags
, NULL
, &status_code
, &len
, &index
))
3457 err
= get_last_error();
3460 *status
= status_code
;
3463 LeaveCriticalSection( &request
->cs
);
3464 return HRESULT_FROM_WIN32( err
);
3467 static HRESULT WINAPI
winhttp_request_get_StatusText(
3468 IWinHttpRequest
*iface
,
3471 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3472 DWORD err
= ERROR_SUCCESS
, len
= 0, index
= 0;
3474 TRACE("%p, %p\n", request
, status
);
3476 if (!status
) return E_INVALIDARG
;
3478 EnterCriticalSection( &request
->cs
);
3479 if (request
->state
< REQUEST_STATE_SENT
)
3481 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3484 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, NULL
, &len
, &index
))
3486 err
= get_last_error();
3487 if (err
!= ERROR_INSUFFICIENT_BUFFER
) goto done
;
3489 if (!(*status
= SysAllocStringLen( NULL
, len
/ sizeof(WCHAR
) )))
3491 err
= ERROR_OUTOFMEMORY
;
3495 err
= ERROR_SUCCESS
;
3496 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_STATUS_TEXT
, NULL
, *status
, &len
, &index
))
3498 err
= get_last_error();
3499 SysFreeString( *status
);
3502 LeaveCriticalSection( &request
->cs
);
3503 return HRESULT_FROM_WIN32( err
);
3506 static DWORD
request_get_codepage( struct winhttp_request
*request
, UINT
*codepage
)
3508 static const WCHAR utf8W
[] = {'u','t','f','-','8',0};
3509 static const WCHAR charsetW
[] = {'c','h','a','r','s','e','t',0};
3514 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, NULL
, &size
, NULL
) &&
3515 get_last_error() == ERROR_INSUFFICIENT_BUFFER
)
3517 if (!(buffer
= heap_alloc( size
))) return ERROR_OUTOFMEMORY
;
3518 if (!WinHttpQueryHeaders( request
->hrequest
, WINHTTP_QUERY_CONTENT_TYPE
, NULL
, buffer
, &size
, NULL
))
3520 return get_last_error();
3522 if ((p
= strstrW( buffer
, charsetW
)))
3524 p
+= strlenW( charsetW
);
3525 while (*p
== ' ') p
++;
3528 while (*p
== ' ') p
++;
3529 if (!strcmpiW( p
, utf8W
)) *codepage
= CP_UTF8
;
3532 heap_free( buffer
);
3534 return ERROR_SUCCESS
;
3537 static HRESULT WINAPI
winhttp_request_get_ResponseText(
3538 IWinHttpRequest
*iface
,
3541 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3543 DWORD err
= ERROR_SUCCESS
;
3546 TRACE("%p, %p\n", request
, body
);
3548 if (!body
) return E_INVALIDARG
;
3550 EnterCriticalSection( &request
->cs
);
3551 if (request
->state
< REQUEST_STATE_SENT
)
3553 err
= ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND
;
3556 if ((err
= request_get_codepage( request
, &codepage
))) goto done
;
3557 len
= MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, NULL
, 0 );
3558 if (!(*body
= SysAllocStringLen( NULL
, len
)))
3560 err
= ERROR_OUTOFMEMORY
;
3563 MultiByteToWideChar( codepage
, 0, request
->buffer
, request
->offset
, *body
, len
);
3567 LeaveCriticalSection( &request
->cs
);
3568 return HRESULT_FROM_WIN32( err
);
3571 static HRESULT WINAPI
winhttp_request_get_ResponseBody(
3572 IWinHttpRequest
*iface
,
3575 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3578 DWORD err
= ERROR_SUCCESS
;
3581 TRACE("%p, %p\n", request
, body
);
3583 if (!body
) return E_INVALIDARG
;
3585 EnterCriticalSection( &request
->cs
);
3586 if (!(sa
= SafeArrayCreateVector( VT_UI1
, 0, request
->offset
)))
3588 err
= ERROR_OUTOFMEMORY
;
3591 if ((hr
= SafeArrayAccessData( sa
, (void **)&ptr
)) != S_OK
)
3593 SafeArrayDestroy( sa
);
3594 LeaveCriticalSection( &request
->cs
);
3597 memcpy( ptr
, request
->buffer
, request
->offset
);
3598 if ((hr
= SafeArrayUnaccessData( sa
)) != S_OK
)
3600 SafeArrayDestroy( sa
);
3601 LeaveCriticalSection( &request
->cs
);
3604 V_VT( body
) = VT_ARRAY
|VT_UI1
;
3605 V_ARRAY( body
) = sa
;
3608 LeaveCriticalSection( &request
->cs
);
3609 return HRESULT_FROM_WIN32( err
);
3612 static HRESULT WINAPI
winhttp_request_get_ResponseStream(
3613 IWinHttpRequest
*iface
,
3620 static HRESULT WINAPI
winhttp_request_get_Option(
3621 IWinHttpRequest
*iface
,
3622 WinHttpRequestOption option
,
3629 static HRESULT WINAPI
winhttp_request_put_Option(
3630 IWinHttpRequest
*iface
,
3631 WinHttpRequestOption option
,
3634 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3637 TRACE("%p, %u, %s\n", request
, option
, debugstr_variant(&value
));
3639 EnterCriticalSection( &request
->cs
);
3642 case WinHttpRequestOption_EnableRedirects
:
3644 if (V_BOOL( &value
))
3645 request
->disable_feature
&= ~WINHTTP_DISABLE_REDIRECTS
;
3647 request
->disable_feature
|= WINHTTP_DISABLE_REDIRECTS
;
3651 FIXME("unimplemented option %u\n", option
);
3655 LeaveCriticalSection( &request
->cs
);
3659 /* critical section must be held */
3660 static DWORD
wait_for_response( struct winhttp_request
*request
, DWORD timeout
)
3662 HANDLE thread
= request
->thread
;
3665 LeaveCriticalSection( &request
->cs
);
3666 while ((err
= MsgWaitForMultipleObjects( 1, &thread
, FALSE
, timeout
, QS_ALLINPUT
)) == WAIT_OBJECT_0
+ 1)
3669 while (PeekMessageW( &msg
, NULL
, 0, 0, PM_REMOVE
))
3671 TranslateMessage( &msg
);
3672 DispatchMessageW( &msg
);
3678 ret
= ERROR_SUCCESS
;
3681 ret
= ERROR_TIMEOUT
;
3685 ret
= get_last_error();
3688 EnterCriticalSection( &request
->cs
);
3692 static HRESULT WINAPI
winhttp_request_WaitForResponse(
3693 IWinHttpRequest
*iface
,
3695 VARIANT_BOOL
*succeeded
)
3697 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3698 DWORD err
, msecs
= (V_I4(&timeout
) == -1) ? INFINITE
: V_I4(&timeout
) * 1000;
3700 TRACE("%p, %s, %p\n", request
, debugstr_variant(&timeout
), succeeded
);
3702 EnterCriticalSection( &request
->cs
);
3703 if (!request
->thread
)
3705 LeaveCriticalSection( &request
->cs
);
3708 if (request
->state
>= REQUEST_STATE_RESPONSE_RECEIVED
)
3710 LeaveCriticalSection( &request
->cs
);
3713 switch ((err
= wait_for_response( request
, msecs
)))
3716 if (succeeded
) *succeeded
= VARIANT_FALSE
;
3717 err
= ERROR_SUCCESS
;
3721 if (succeeded
) *succeeded
= VARIANT_TRUE
;
3726 LeaveCriticalSection( &request
->cs
);
3727 return HRESULT_FROM_WIN32( err
);
3730 static HRESULT WINAPI
winhttp_request_Abort(
3731 IWinHttpRequest
*iface
)
3733 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3735 TRACE("%p\n", request
);
3737 EnterCriticalSection( &request
->cs
);
3738 cancel_request( request
);
3739 LeaveCriticalSection( &request
->cs
);
3743 static HRESULT WINAPI
winhttp_request_SetTimeouts(
3744 IWinHttpRequest
*iface
,
3745 LONG resolve_timeout
,
3746 LONG connect_timeout
,
3748 LONG receive_timeout
)
3750 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3752 TRACE("%p, %d, %d, %d, %d\n", request
, resolve_timeout
, connect_timeout
, send_timeout
, receive_timeout
);
3754 EnterCriticalSection( &request
->cs
);
3755 request
->resolve_timeout
= resolve_timeout
;
3756 request
->connect_timeout
= connect_timeout
;
3757 request
->send_timeout
= send_timeout
;
3758 request
->receive_timeout
= receive_timeout
;
3759 LeaveCriticalSection( &request
->cs
);
3763 static HRESULT WINAPI
winhttp_request_SetClientCertificate(
3764 IWinHttpRequest
*iface
,
3771 static HRESULT WINAPI
winhttp_request_SetAutoLogonPolicy(
3772 IWinHttpRequest
*iface
,
3773 WinHttpRequestAutoLogonPolicy policy
)
3775 struct winhttp_request
*request
= impl_from_IWinHttpRequest( iface
);
3778 TRACE("%p, %u\n", request
, policy
);
3780 EnterCriticalSection( &request
->cs
);
3783 case AutoLogonPolicy_Always
:
3784 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW
;
3786 case AutoLogonPolicy_OnlyIfBypassProxy
:
3787 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM
;
3789 case AutoLogonPolicy_Never
:
3790 request
->logon_policy
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH
;
3792 default: hr
= E_INVALIDARG
;
3795 LeaveCriticalSection( &request
->cs
);
3799 static const struct IWinHttpRequestVtbl winhttp_request_vtbl
=
3801 winhttp_request_QueryInterface
,
3802 winhttp_request_AddRef
,
3803 winhttp_request_Release
,
3804 winhttp_request_GetTypeInfoCount
,
3805 winhttp_request_GetTypeInfo
,
3806 winhttp_request_GetIDsOfNames
,
3807 winhttp_request_Invoke
,
3808 winhttp_request_SetProxy
,
3809 winhttp_request_SetCredentials
,
3810 winhttp_request_Open
,
3811 winhttp_request_SetRequestHeader
,
3812 winhttp_request_GetResponseHeader
,
3813 winhttp_request_GetAllResponseHeaders
,
3814 winhttp_request_Send
,
3815 winhttp_request_get_Status
,
3816 winhttp_request_get_StatusText
,
3817 winhttp_request_get_ResponseText
,
3818 winhttp_request_get_ResponseBody
,
3819 winhttp_request_get_ResponseStream
,
3820 winhttp_request_get_Option
,
3821 winhttp_request_put_Option
,
3822 winhttp_request_WaitForResponse
,
3823 winhttp_request_Abort
,
3824 winhttp_request_SetTimeouts
,
3825 winhttp_request_SetClientCertificate
,
3826 winhttp_request_SetAutoLogonPolicy
3829 HRESULT
WinHttpRequest_create( IUnknown
*unknown
, void **obj
)
3831 struct winhttp_request
*request
;
3833 TRACE("%p, %p\n", unknown
, obj
);
3835 if (!(request
= heap_alloc( sizeof(*request
) ))) return E_OUTOFMEMORY
;
3836 request
->IWinHttpRequest_iface
.lpVtbl
= &winhttp_request_vtbl
;
3838 request
->state
= REQUEST_STATE_UNINITIALIZED
;
3839 request
->proxy
.lpszProxy
= NULL
;
3840 request
->proxy
.lpszProxyBypass
= NULL
;
3841 InitializeCriticalSection( &request
->cs
);
3842 request
->cs
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": winhttp_request.cs");
3844 *obj
= &request
->IWinHttpRequest_iface
;
3845 TRACE("returning iface %p\n", *obj
);