2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
31 #include "wine/port.h"
33 #if defined(__MINGW32__) || defined (_MSC_VER)
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
41 #ifdef HAVE_ARPA_INET_H
42 # include <arpa/inet.h>
61 #define NO_SHLWAPI_STREAM
62 #define NO_SHLWAPI_REG
63 #define NO_SHLWAPI_STRFCNS
64 #define NO_SHLWAPI_GDI
71 #include "wine/debug.h"
72 #include "wine/exception.h"
73 #include "wine/unicode.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
77 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
78 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
79 static const WCHAR szOK
[] = {'O','K',0};
80 static const WCHAR szDefaultHeader
[] = {'H','T','T','P','/','1','.','0',' ','2','0','0',' ','O','K',0};
81 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
82 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
83 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
84 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
85 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
86 static const WCHAR szGET
[] = { 'G','E','T', 0 };
87 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
88 static const WCHAR szCrLf
[] = {'\r','\n', 0};
90 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
91 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
92 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
93 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
94 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
95 static const WCHAR szAge
[] = { 'A','g','e',0 };
96 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
97 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
98 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
99 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
100 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
101 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
102 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
103 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
104 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
105 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
106 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
107 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
108 static const WCHAR szContent_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 };
109 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
110 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
111 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
112 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
113 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
114 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
115 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
116 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
117 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
118 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
119 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
120 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
121 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
122 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
123 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
124 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
125 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
126 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
127 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
128 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
129 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
130 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
131 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
132 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
133 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
134 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
135 static const WCHAR szUnless_Modified_Since
[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
136 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
137 static const WCHAR szURI
[] = { 'U','R','I',0 };
138 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
139 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
140 static const WCHAR szVia
[] = { 'V','i','a',0 };
141 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
142 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
144 static const WCHAR emptyW
[] = {0};
146 #define HTTP_REFERER szReferer
147 #define HTTP_ACCEPT szAccept
148 #define HTTP_USERAGENT szUser_Agent
150 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
151 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
152 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
153 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
154 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
155 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
156 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
158 #define COLLECT_TIME 60000
160 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
171 unsigned int auth_data_len
;
172 BOOL finished
; /* finished authenticating */
176 typedef struct _basicAuthorizationData
183 UINT authorizationLen
;
184 } basicAuthorizationData
;
186 typedef struct _authorizationData
200 static struct list basicAuthorizationCache
= LIST_INIT(basicAuthorizationCache
);
201 static struct list authorizationCache
= LIST_INIT(authorizationCache
);
203 static CRITICAL_SECTION authcache_cs
;
204 static CRITICAL_SECTION_DEBUG critsect_debug
=
207 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
208 0, 0, { (DWORD_PTR
)(__FILE__
": authcache_cs") }
210 static CRITICAL_SECTION authcache_cs
= { &critsect_debug
, -1, 0, 0, 0, 0 };
212 static DWORD
HTTP_GetResponseHeaders(http_request_t
*req
, INT
*len
);
213 static DWORD
HTTP_ProcessHeader(http_request_t
*req
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
);
214 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
);
215 static DWORD
HTTP_InsertCustomHeader(http_request_t
*req
, LPHTTPHEADERW lpHdr
);
216 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*req
, LPCWSTR lpszField
, INT index
, BOOL Request
);
217 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*req
, DWORD index
);
218 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
);
219 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*, DWORD
, LPVOID
, LPDWORD
, LPDWORD
);
220 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*req
, LPCWSTR lpszUrl
);
221 static UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
222 static BOOL
HTTP_VerifyValidHeader(http_request_t
*req
, LPCWSTR field
);
223 static BOOL
drain_content(http_request_t
*,BOOL
);
225 static CRITICAL_SECTION connection_pool_cs
;
226 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
228 0, 0, &connection_pool_cs
,
229 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
230 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
232 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
234 static struct list connection_pool
= LIST_INIT(connection_pool
);
235 static BOOL collector_running
;
237 void server_addref(server_t
*server
)
239 InterlockedIncrement(&server
->ref
);
242 void server_release(server_t
*server
)
244 if(InterlockedDecrement(&server
->ref
))
247 list_remove(&server
->entry
);
249 if(server
->cert_chain
)
250 CertFreeCertificateChain(server
->cert_chain
);
251 heap_free(server
->name
);
252 heap_free(server
->scheme_host_port
);
256 static BOOL
process_host_port(server_t
*server
)
262 static const WCHAR httpW
[] = {'h','t','t','p',0};
263 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
264 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
266 name_len
= strlenW(server
->name
);
267 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
271 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
272 server
->scheme_host_port
= buf
;
274 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
278 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
279 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
283 server_t
*get_server(const WCHAR
*name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
285 server_t
*iter
, *server
= NULL
;
287 if(port
== INTERNET_INVALID_PORT_NUMBER
)
288 port
= INTERNET_DEFAULT_HTTP_PORT
;
290 EnterCriticalSection(&connection_pool_cs
);
292 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
293 if(iter
->port
== port
&& !strcmpW(iter
->name
, name
) && iter
->is_https
== is_https
) {
295 server_addref(server
);
300 if(!server
&& do_create
) {
301 server
= heap_alloc_zero(sizeof(*server
));
303 server
->ref
= 2; /* list reference and return */
305 server
->is_https
= is_https
;
306 list_init(&server
->conn_pool
);
307 server
->name
= heap_strdupW(name
);
308 if(server
->name
&& process_host_port(server
)) {
309 list_add_head(&connection_pool
, &server
->entry
);
317 LeaveCriticalSection(&connection_pool_cs
);
322 BOOL
collect_connections(collect_type_t collect_type
)
324 netconn_t
*netconn
, *netconn_safe
;
325 server_t
*server
, *server_safe
;
326 BOOL remaining
= FALSE
;
329 now
= GetTickCount64();
331 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
332 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
333 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
334 TRACE("freeing %p\n", netconn
);
335 list_remove(&netconn
->pool_entry
);
336 free_netconn(netconn
);
342 if(collect_type
== COLLECT_CLEANUP
) {
343 list_remove(&server
->entry
);
344 list_init(&server
->entry
);
345 server_release(server
);
352 static DWORD WINAPI
collect_connections_proc(void *arg
)
354 BOOL remaining_conns
;
357 /* FIXME: Use more sophisticated method */
360 EnterCriticalSection(&connection_pool_cs
);
362 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
364 collector_running
= FALSE
;
366 LeaveCriticalSection(&connection_pool_cs
);
367 }while(remaining_conns
);
369 FreeLibraryAndExitThread(WININET_hModule
, 0);
372 /***********************************************************************
373 * HTTP_GetHeader (internal)
375 * Headers section must be held
377 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
380 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
381 if (HeaderIndex
== -1)
384 return &req
->custHeaders
[HeaderIndex
];
387 static WCHAR
*get_host_header( http_request_t
*req
)
392 EnterCriticalSection( &req
->headers_section
);
393 if ((header
= HTTP_GetHeader( req
, hostW
))) ret
= heap_strdupW( header
->lpszValue
);
394 LeaveCriticalSection( &req
->headers_section
);
398 struct data_stream_vtbl_t
{
399 DWORD (*get_avail_data
)(data_stream_t
*,http_request_t
*);
400 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
401 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,blocking_mode_t
);
402 BOOL (*drain_content
)(data_stream_t
*,http_request_t
*);
403 void (*destroy
)(data_stream_t
*);
407 data_stream_t data_stream
;
409 BYTE buf
[READ_BUFFER_SIZE
];
416 static inline void destroy_data_stream(data_stream_t
*stream
)
418 stream
->vtbl
->destroy(stream
);
421 static void reset_data_stream(http_request_t
*req
)
423 destroy_data_stream(req
->data_stream
);
424 req
->data_stream
= &req
->netconn_stream
.data_stream
;
425 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
426 req
->read_chunked
= req
->read_gzip
= FALSE
;
432 data_stream_t stream
;
433 data_stream_t
*parent_stream
;
435 BYTE buf
[READ_BUFFER_SIZE
];
441 static DWORD
gzip_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
443 /* Allow reading only from read buffer */
447 static BOOL
gzip_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
449 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
450 return gzip_stream
->end_of_data
451 || (!gzip_stream
->buf_size
&& gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
));
454 static DWORD
gzip_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
455 DWORD
*read
, blocking_mode_t blocking_mode
)
457 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
458 z_stream
*zstream
= &gzip_stream
->zstream
;
459 DWORD current_read
, ret_read
= 0;
461 DWORD res
= ERROR_SUCCESS
;
463 TRACE("(%d %d)\n", size
, blocking_mode
);
465 while(size
&& !gzip_stream
->end_of_data
) {
466 if(!gzip_stream
->buf_size
) {
467 if(gzip_stream
->buf_pos
) {
468 if(gzip_stream
->buf_size
)
469 memmove(gzip_stream
->buf
, gzip_stream
->buf
+gzip_stream
->buf_pos
, gzip_stream
->buf_size
);
470 gzip_stream
->buf_pos
= 0;
472 res
= gzip_stream
->parent_stream
->vtbl
->read(gzip_stream
->parent_stream
, req
, gzip_stream
->buf
+gzip_stream
->buf_size
,
473 sizeof(gzip_stream
->buf
)-gzip_stream
->buf_size
, ¤t_read
, blocking_mode
);
474 gzip_stream
->buf_size
+= current_read
;
475 if(res
!= ERROR_SUCCESS
)
479 if(blocking_mode
!= BLOCKING_DISALLOW
) {
480 WARN("unexpected end of data\n");
481 gzip_stream
->end_of_data
= TRUE
;
487 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
488 zstream
->avail_in
= gzip_stream
->buf_size
;
489 zstream
->next_out
= buf
+ret_read
;
490 zstream
->avail_out
= size
;
491 zres
= inflate(&gzip_stream
->zstream
, 0);
492 current_read
= size
- zstream
->avail_out
;
493 size
-= current_read
;
494 ret_read
+= current_read
;
495 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
496 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
497 if(zres
== Z_STREAM_END
) {
498 TRACE("end of data\n");
499 gzip_stream
->end_of_data
= TRUE
;
501 }else if(zres
!= Z_OK
) {
502 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
504 res
= ERROR_INTERNET_DECODING_FAILED
;
508 if(ret_read
&& blocking_mode
== BLOCKING_ALLOW
)
509 blocking_mode
= BLOCKING_DISALLOW
;
512 TRACE("read %u bytes\n", ret_read
);
517 static BOOL
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
)
519 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
520 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
);
523 static void gzip_destroy(data_stream_t
*stream
)
525 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
527 destroy_data_stream(gzip_stream
->parent_stream
);
529 if(!gzip_stream
->end_of_data
)
530 inflateEnd(&gzip_stream
->zstream
);
531 heap_free(gzip_stream
);
534 static const data_stream_vtbl_t gzip_stream_vtbl
= {
542 static voidpf
wininet_zalloc(voidpf opaque
, uInt items
, uInt size
)
544 return heap_alloc(items
*size
);
547 static void wininet_zfree(voidpf opaque
, voidpf address
)
552 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
554 gzip_stream_t
*gzip_stream
;
557 gzip_stream
= heap_alloc_zero(sizeof(gzip_stream_t
));
559 return ERROR_OUTOFMEMORY
;
561 gzip_stream
->stream
.vtbl
= &gzip_stream_vtbl
;
562 gzip_stream
->zstream
.zalloc
= wininet_zalloc
;
563 gzip_stream
->zstream
.zfree
= wininet_zfree
;
565 zres
= inflateInit2(&gzip_stream
->zstream
, is_gzip
? 0x1f : -15);
567 ERR("inflateInit failed: %d\n", zres
);
568 heap_free(gzip_stream
);
569 return ERROR_OUTOFMEMORY
;
572 EnterCriticalSection( &req
->headers_section
);
573 index
= HTTP_GetCustomHeaderIndex(req
, szContent_Length
, 0, FALSE
);
575 HTTP_DeleteCustomHeader(req
, index
);
576 LeaveCriticalSection( &req
->headers_section
);
579 memcpy(gzip_stream
->buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
580 gzip_stream
->buf_size
= req
->read_size
;
581 req
->read_pos
= req
->read_size
= 0;
584 req
->read_gzip
= TRUE
;
585 gzip_stream
->parent_stream
= req
->data_stream
;
586 req
->data_stream
= &gzip_stream
->stream
;
587 return ERROR_SUCCESS
;
592 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
594 ERR("gzip stream not supported, missing zlib.\n");
595 return ERROR_SUCCESS
;
600 /***********************************************************************
601 * HTTP_FreeTokens (internal)
603 * Frees table of pointers.
605 static void HTTP_FreeTokens(LPWSTR
* token_array
)
608 for (i
= 0; token_array
[i
]; i
++) heap_free(token_array
[i
]);
609 heap_free(token_array
);
612 static void HTTP_FixURL(http_request_t
*request
)
614 static const WCHAR szSlash
[] = { '/',0 };
615 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/', 0 };
617 /* If we don't have a path we set it to root */
618 if (NULL
== request
->path
)
619 request
->path
= heap_strdupW(szSlash
);
620 else /* remove \r and \n*/
622 int nLen
= strlenW(request
->path
);
623 while ((nLen
>0 ) && ((request
->path
[nLen
-1] == '\r')||(request
->path
[nLen
-1] == '\n')))
626 request
->path
[nLen
]='\0';
628 /* Replace '\' with '/' */
631 if (request
->path
[nLen
] == '\\') request
->path
[nLen
]='/';
635 if(CSTR_EQUAL
!= CompareStringW( LOCALE_INVARIANT
, NORM_IGNORECASE
,
636 request
->path
, strlenW(request
->path
), szHttp
, strlenW(szHttp
) )
637 && request
->path
[0] != '/') /* not an absolute path ?? --> fix it !! */
639 WCHAR
*fixurl
= heap_alloc((strlenW(request
->path
) + 2)*sizeof(WCHAR
));
641 strcpyW(fixurl
+ 1, request
->path
);
642 heap_free( request
->path
);
643 request
->path
= fixurl
;
647 static WCHAR
* build_request_header(http_request_t
*request
, const WCHAR
*verb
,
648 const WCHAR
*path
, const WCHAR
*version
, BOOL use_cr
)
650 static const WCHAR szSpace
[] = {' ',0};
651 static const WCHAR szColon
[] = {':',' ',0};
652 static const WCHAR szCr
[] = {'\r',0};
653 static const WCHAR szLf
[] = {'\n',0};
654 LPWSTR requestString
;
659 EnterCriticalSection( &request
->headers_section
);
661 /* allocate space for an array of all the string pointers to be added */
662 len
= request
->nCustHeaders
* 5 + 10;
663 if (!(req
= heap_alloc( len
* sizeof(const WCHAR
*) )))
665 LeaveCriticalSection( &request
->headers_section
);
669 /* add the verb, path and HTTP version string */
680 /* Append custom request headers */
681 for (i
= 0; i
< request
->nCustHeaders
; i
++)
683 if (request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
685 req
[n
++] = request
->custHeaders
[i
].lpszField
;
687 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
692 TRACE("Adding custom header %s (%s)\n",
693 debugstr_w(request
->custHeaders
[i
].lpszField
),
694 debugstr_w(request
->custHeaders
[i
].lpszValue
));
702 requestString
= HTTP_build_req( req
, 4 );
704 LeaveCriticalSection( &request
->headers_section
);
705 return requestString
;
708 static WCHAR
* build_response_header(http_request_t
*request
, BOOL use_cr
)
710 static const WCHAR colonW
[] = { ':',' ',0 };
711 static const WCHAR crW
[] = { '\r',0 };
712 static const WCHAR lfW
[] = { '\n',0 };
713 static const WCHAR status_fmt
[] = { ' ','%','u',' ',0 };
718 EnterCriticalSection( &request
->headers_section
);
720 if (!(req
= heap_alloc( (request
->nCustHeaders
* 5 + 8) * sizeof(WCHAR
*) )))
722 LeaveCriticalSection( &request
->headers_section
);
726 if (request
->status_code
)
728 req
[n
++] = request
->version
;
729 sprintfW(buf
, status_fmt
, request
->status_code
);
731 req
[n
++] = request
->statusText
;
737 for(i
= 0; i
< request
->nCustHeaders
; i
++)
739 if(!(request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
740 && strcmpW(request
->custHeaders
[i
].lpszField
, szStatus
))
742 req
[n
++] = request
->custHeaders
[i
].lpszField
;
744 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
749 TRACE("Adding custom header %s (%s)\n",
750 debugstr_w(request
->custHeaders
[i
].lpszField
),
751 debugstr_w(request
->custHeaders
[i
].lpszValue
));
759 ret
= HTTP_build_req(req
, 0);
761 LeaveCriticalSection( &request
->headers_section
);
765 static void HTTP_ProcessCookies( http_request_t
*request
)
769 LPHTTPHEADERW setCookieHeader
;
771 if(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
)
774 EnterCriticalSection( &request
->headers_section
);
776 while((HeaderIndex
= HTTP_GetCustomHeaderIndex(request
, szSet_Cookie
, numCookies
++, FALSE
)) != -1)
782 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
784 if (!setCookieHeader
->lpszValue
)
787 host
= HTTP_GetHeader(request
, hostW
);
791 data
= strchrW(setCookieHeader
->lpszValue
, '=');
795 name
= heap_strndupW(setCookieHeader
->lpszValue
, data
-setCookieHeader
->lpszValue
);
800 set_cookie(host
->lpszValue
, request
->path
, name
, data
, INTERNET_COOKIE_HTTPONLY
);
804 LeaveCriticalSection( &request
->headers_section
);
807 static void strip_spaces(LPWSTR start
)
812 while (*str
== ' ' && *str
!= '\0')
816 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
818 end
= start
+ strlenW(start
) - 1;
819 while (end
>= start
&& *end
== ' ')
826 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
828 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
829 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
831 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAYSIZE(szBasic
)) &&
832 ((pszAuthValue
[ARRAYSIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAYSIZE(szBasic
)]);
833 if (is_basic
&& pszRealm
)
836 LPCWSTR ptr
= &pszAuthValue
[ARRAYSIZE(szBasic
)];
840 token
= strchrW(ptr
,'=');
844 while (*realm
== ' ' && *realm
!= '\0')
846 if(!strncmpiW(realm
, szRealm
, ARRAYSIZE(szRealm
)) &&
847 (realm
[ARRAYSIZE(szRealm
)] == ' ' || realm
[ARRAYSIZE(szRealm
)] == '='))
850 while (*token
== ' ' && *token
!= '\0')
854 *pszRealm
= heap_strdupW(token
);
855 strip_spaces(*pszRealm
);
862 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
864 if (!authinfo
) return;
866 if (SecIsValidHandle(&authinfo
->ctx
))
867 DeleteSecurityContext(&authinfo
->ctx
);
868 if (SecIsValidHandle(&authinfo
->cred
))
869 FreeCredentialsHandle(&authinfo
->cred
);
871 heap_free(authinfo
->auth_data
);
872 heap_free(authinfo
->scheme
);
876 static UINT
retrieve_cached_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR
*auth_data
)
878 basicAuthorizationData
*ad
;
881 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
883 EnterCriticalSection(&authcache_cs
);
884 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
886 if (!strcmpiW(host
,ad
->host
) && !strcmpW(realm
,ad
->realm
))
888 TRACE("Authorization found in cache\n");
889 *auth_data
= heap_alloc(ad
->authorizationLen
);
890 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
891 rc
= ad
->authorizationLen
;
895 LeaveCriticalSection(&authcache_cs
);
899 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
902 basicAuthorizationData
* ad
= NULL
;
904 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
906 EnterCriticalSection(&authcache_cs
);
907 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
909 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
910 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
919 TRACE("Found match in cache, replacing\n");
920 heap_free(ad
->authorization
);
921 ad
->authorization
= heap_alloc(auth_data_len
);
922 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
923 ad
->authorizationLen
= auth_data_len
;
927 ad
= heap_alloc(sizeof(basicAuthorizationData
));
928 ad
->host
= heap_strdupW(host
);
929 ad
->realm
= heap_strdupW(realm
);
930 ad
->authorization
= heap_alloc(auth_data_len
);
931 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
932 ad
->authorizationLen
= auth_data_len
;
933 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
934 TRACE("authorization cached\n");
936 LeaveCriticalSection(&authcache_cs
);
939 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
940 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
942 authorizationData
*ad
;
944 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
946 EnterCriticalSection(&authcache_cs
);
947 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
948 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
949 TRACE("Authorization found in cache\n");
951 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
952 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
953 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
954 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
955 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
956 heap_free(nt_auth_identity
->User
);
957 heap_free(nt_auth_identity
->Password
);
958 heap_free(nt_auth_identity
->Domain
);
962 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
963 nt_auth_identity
->UserLength
= ad
->user_len
;
964 nt_auth_identity
->PasswordLength
= ad
->password_len
;
965 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
966 nt_auth_identity
->DomainLength
= ad
->domain_len
;
967 LeaveCriticalSection(&authcache_cs
);
971 LeaveCriticalSection(&authcache_cs
);
976 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
977 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
979 authorizationData
*ad
;
982 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
984 EnterCriticalSection(&authcache_cs
);
985 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
986 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
993 heap_free(ad
->password
);
994 heap_free(ad
->domain
);
996 ad
= heap_alloc(sizeof(authorizationData
));
998 LeaveCriticalSection(&authcache_cs
);
1002 ad
->host
= heap_strdupW(host
);
1003 ad
->scheme
= heap_strdupW(scheme
);
1004 list_add_head(&authorizationCache
, &ad
->entry
);
1007 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
1008 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
1009 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
1010 ad
->user_len
= nt_auth_identity
->UserLength
;
1011 ad
->password_len
= nt_auth_identity
->PasswordLength
;
1012 ad
->domain_len
= nt_auth_identity
->DomainLength
;
1014 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
1015 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
1016 heap_free(ad
->host
);
1017 heap_free(ad
->scheme
);
1018 heap_free(ad
->user
);
1019 heap_free(ad
->password
);
1020 heap_free(ad
->domain
);
1021 list_remove(&ad
->entry
);
1025 LeaveCriticalSection(&authcache_cs
);
1028 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
1029 struct HttpAuthInfo
**ppAuthInfo
,
1030 LPWSTR domain_and_username
, LPWSTR password
,
1033 SECURITY_STATUS sec_status
;
1034 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
1036 LPWSTR szRealm
= NULL
;
1038 TRACE("%s\n", debugstr_w(pszAuthValue
));
1045 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
1049 SecInvalidateHandle(&pAuthInfo
->cred
);
1050 SecInvalidateHandle(&pAuthInfo
->ctx
);
1051 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1052 pAuthInfo
->attr
= 0;
1053 pAuthInfo
->auth_data
= NULL
;
1054 pAuthInfo
->auth_data_len
= 0;
1055 pAuthInfo
->finished
= FALSE
;
1057 if (is_basic_auth_value(pszAuthValue
,NULL
))
1059 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1060 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1061 if (!pAuthInfo
->scheme
)
1063 heap_free(pAuthInfo
);
1070 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1072 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1073 if (!pAuthInfo
->scheme
)
1075 heap_free(pAuthInfo
);
1079 if (domain_and_username
)
1081 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1082 WCHAR
*domain
= domain_and_username
;
1084 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1086 pAuthData
= &nt_auth_identity
;
1091 user
= domain_and_username
;
1095 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1096 nt_auth_identity
.User
= user
;
1097 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1098 nt_auth_identity
.Domain
= domain
;
1099 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1100 nt_auth_identity
.Password
= password
;
1101 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1103 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1105 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1106 pAuthData
= &nt_auth_identity
;
1108 /* use default credentials */
1111 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1112 SECPKG_CRED_OUTBOUND
, NULL
,
1114 NULL
, &pAuthInfo
->cred
,
1117 if(pAuthData
&& !domain_and_username
) {
1118 heap_free(nt_auth_identity
.User
);
1119 heap_free(nt_auth_identity
.Domain
);
1120 heap_free(nt_auth_identity
.Password
);
1123 if (sec_status
== SEC_E_OK
)
1125 PSecPkgInfoW sec_pkg_info
;
1126 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1127 if (sec_status
== SEC_E_OK
)
1129 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1130 FreeContextBuffer(sec_pkg_info
);
1133 if (sec_status
!= SEC_E_OK
)
1135 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1136 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1137 heap_free(pAuthInfo
->scheme
);
1138 heap_free(pAuthInfo
);
1142 *ppAuthInfo
= pAuthInfo
;
1144 else if (pAuthInfo
->finished
)
1147 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1148 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1150 ERR("authentication scheme changed from %s to %s\n",
1151 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1155 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1159 char *auth_data
= NULL
;
1160 UINT auth_data_len
= 0;
1162 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1164 if (!domain_and_username
)
1166 if (host
&& szRealm
)
1167 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1168 if (auth_data_len
== 0)
1176 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1177 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1179 /* length includes a nul terminator, which will be re-used for the ':' */
1180 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1187 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1188 auth_data
[userlen
] = ':';
1189 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1190 auth_data_len
= userlen
+ 1 + passlen
;
1191 if (host
&& szRealm
)
1192 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1195 pAuthInfo
->auth_data
= auth_data
;
1196 pAuthInfo
->auth_data_len
= auth_data_len
;
1197 pAuthInfo
->finished
= TRUE
;
1203 LPCWSTR pszAuthData
;
1204 SecBufferDesc out_desc
, in_desc
;
1206 unsigned char *buffer
;
1207 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1208 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1210 in
.BufferType
= SECBUFFER_TOKEN
;
1214 in_desc
.ulVersion
= 0;
1215 in_desc
.cBuffers
= 1;
1216 in_desc
.pBuffers
= &in
;
1218 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1219 if (*pszAuthData
== ' ')
1222 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1223 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1224 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1227 buffer
= heap_alloc(pAuthInfo
->max_token
);
1229 out
.BufferType
= SECBUFFER_TOKEN
;
1230 out
.cbBuffer
= pAuthInfo
->max_token
;
1231 out
.pvBuffer
= buffer
;
1233 out_desc
.ulVersion
= 0;
1234 out_desc
.cBuffers
= 1;
1235 out_desc
.pBuffers
= &out
;
1237 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1238 first
? NULL
: &pAuthInfo
->ctx
,
1239 first
? request
->server
->name
: NULL
,
1240 context_req
, 0, SECURITY_NETWORK_DREP
,
1241 in
.pvBuffer
? &in_desc
: NULL
,
1242 0, &pAuthInfo
->ctx
, &out_desc
,
1243 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1244 if (sec_status
== SEC_E_OK
)
1246 pAuthInfo
->finished
= TRUE
;
1247 pAuthInfo
->auth_data
= out
.pvBuffer
;
1248 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1249 TRACE("sending last auth packet\n");
1251 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1253 pAuthInfo
->auth_data
= out
.pvBuffer
;
1254 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1255 TRACE("sending next auth packet\n");
1259 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1260 heap_free(out
.pvBuffer
);
1261 destroy_authinfo(pAuthInfo
);
1270 /***********************************************************************
1271 * HTTP_HttpAddRequestHeadersW (internal)
1273 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1274 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1279 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1281 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1283 if( dwHeaderLength
== ~0U )
1284 len
= strlenW(lpszHeader
);
1286 len
= dwHeaderLength
;
1287 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1288 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1294 LPWSTR
* pFieldAndValue
;
1296 lpszEnd
= lpszStart
;
1298 while (*lpszEnd
!= '\0')
1300 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1305 if (*lpszStart
== '\0')
1308 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1311 lpszEnd
++; /* Jump over newline */
1313 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1314 if (*lpszStart
== '\0')
1316 /* Skip 0-length headers */
1317 lpszStart
= lpszEnd
;
1318 res
= ERROR_SUCCESS
;
1321 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1324 res
= HTTP_VerifyValidHeader(request
, pFieldAndValue
[0]);
1325 if (res
== ERROR_SUCCESS
)
1326 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1327 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1328 HTTP_FreeTokens(pFieldAndValue
);
1331 lpszStart
= lpszEnd
;
1332 } while (res
== ERROR_SUCCESS
);
1338 /***********************************************************************
1339 * HttpAddRequestHeadersW (WININET.@)
1341 * Adds one or more HTTP header to the request handler
1344 * On Windows if dwHeaderLength includes the trailing '\0', then
1345 * HttpAddRequestHeadersW() adds it too. However this results in an
1346 * invalid HTTP header which is rejected by some servers so we probably
1347 * don't need to match Windows on that point.
1354 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1355 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1357 http_request_t
*request
;
1358 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1360 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1365 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1366 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1367 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1369 WININET_Release( &request
->hdr
);
1371 if(res
!= ERROR_SUCCESS
)
1373 return res
== ERROR_SUCCESS
;
1376 /***********************************************************************
1377 * HttpAddRequestHeadersA (WININET.@)
1379 * Adds one or more HTTP header to the request handler
1386 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1387 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1393 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1395 len
= MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, NULL
, 0 );
1396 hdr
= heap_alloc(len
*sizeof(WCHAR
));
1397 MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, hdr
, len
);
1398 if( dwHeaderLength
!= ~0U )
1399 dwHeaderLength
= len
;
1401 r
= HttpAddRequestHeadersW( hHttpRequest
, hdr
, dwHeaderLength
, dwModifier
);
1407 static void free_accept_types( WCHAR
**accept_types
)
1409 WCHAR
*ptr
, **types
= accept_types
;
1412 while ((ptr
= *types
))
1417 heap_free( accept_types
);
1420 static WCHAR
**convert_accept_types( const char **accept_types
)
1423 const char **types
= accept_types
;
1425 BOOL invalid_pointer
= FALSE
;
1427 if (!types
) return NULL
;
1433 /* find out how many there are */
1434 if (*types
&& **types
)
1436 TRACE("accept type: %s\n", debugstr_a(*types
));
1442 WARN("invalid accept type pointer\n");
1443 invalid_pointer
= TRUE
;
1448 if (invalid_pointer
) return NULL
;
1449 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1451 types
= accept_types
;
1454 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1457 typesW
[count
] = NULL
;
1461 /***********************************************************************
1462 * HttpOpenRequestA (WININET.@)
1464 * Open a HTTP request handle
1467 * HINTERNET a HTTP request handle on success
1471 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1472 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1473 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1474 DWORD dwFlags
, DWORD_PTR dwContext
)
1476 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1477 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1478 HINTERNET rc
= NULL
;
1480 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1481 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1482 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1483 dwFlags
, dwContext
);
1487 szVerb
= heap_strdupAtoW(lpszVerb
);
1494 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1495 if ( !szObjectName
)
1501 szVersion
= heap_strdupAtoW(lpszVersion
);
1508 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1513 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1514 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1515 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1518 free_accept_types(szAcceptTypes
);
1519 heap_free(szReferrer
);
1520 heap_free(szVersion
);
1521 heap_free(szObjectName
);
1526 /***********************************************************************
1529 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1532 static const CHAR HTTP_Base64Enc
[] =
1533 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1537 /* first 6 bits, all from bin[0] */
1538 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1539 x
= (bin
[0] & 3) << 4;
1541 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1544 base64
[n
++] = HTTP_Base64Enc
[x
];
1549 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1550 x
= ( bin
[1] & 0x0f ) << 2;
1552 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1555 base64
[n
++] = HTTP_Base64Enc
[x
];
1559 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1561 /* last 6 bits, all from bin [2] */
1562 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1570 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1571 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1572 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1573 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1574 static const signed char HTTP_Base64Dec
[256] =
1576 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1577 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1578 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1579 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1580 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1581 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1582 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1583 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1584 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1585 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1586 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1587 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1588 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1589 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1590 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1591 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1592 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1593 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1594 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1595 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1596 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1597 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1598 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1599 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1600 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1601 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1605 /***********************************************************************
1608 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1616 if (base64
[0] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1617 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1618 base64
[1] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1619 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1621 WARN("invalid base64: %s\n", debugstr_w(base64
));
1625 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1628 if ((base64
[2] == '=') && (base64
[3] == '='))
1630 if (base64
[2] > ARRAYSIZE(HTTP_Base64Dec
) ||
1631 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1633 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1637 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1640 if (base64
[3] == '=')
1642 if (base64
[3] > ARRAYSIZE(HTTP_Base64Dec
) ||
1643 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1645 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1649 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1658 /***********************************************************************
1659 * HTTP_InsertAuthorization
1661 * Insert or delete the authorization field in the request header.
1663 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1667 static const WCHAR wszSpace
[] = {' ',0};
1668 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1670 WCHAR
*authorization
= NULL
;
1672 if (pAuthInfo
->auth_data_len
)
1674 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1675 len
= strlenW(pAuthInfo
->scheme
)+1+((pAuthInfo
->auth_data_len
+2)*4)/3;
1676 authorization
= heap_alloc((len
+1)*sizeof(WCHAR
));
1680 strcpyW(authorization
, pAuthInfo
->scheme
);
1681 strcatW(authorization
, wszSpace
);
1682 HTTP_EncodeBase64(pAuthInfo
->auth_data
,
1683 pAuthInfo
->auth_data_len
,
1684 authorization
+strlenW(authorization
));
1686 /* clear the data as it isn't valid now that it has been sent to the
1687 * server, unless it's Basic authentication which doesn't do
1688 * connection tracking */
1689 if (strcmpiW(pAuthInfo
->scheme
, wszBasic
))
1691 heap_free(pAuthInfo
->auth_data
);
1692 pAuthInfo
->auth_data
= NULL
;
1693 pAuthInfo
->auth_data_len
= 0;
1697 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1699 HTTP_ProcessHeader(request
, header
, authorization
, HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
);
1700 heap_free(authorization
);
1705 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1710 len
= strlenW(req
->server
->scheme_host_port
);
1711 size
= len
+ strlenW(req
->path
) + 1;
1712 if(*req
->path
!= '/')
1714 url
= heap_alloc(size
* sizeof(WCHAR
));
1718 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1719 if(*req
->path
!= '/')
1722 strcpyW(url
+len
, req
->path
);
1724 TRACE("url=%s\n", debugstr_w(url
));
1728 static BOOL
HTTP_DomainMatches(LPCWSTR server
, LPCWSTR domain
)
1730 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1733 if (!strcmpiW( domain
, localW
) && !strchrW( server
, '.' ))
1735 else if (*domain
== '*')
1737 if (domain
[1] == '.')
1741 /* For a hostname to match a wildcard, the last domain must match
1742 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1743 * hostname is www.foo.a.b, it matches, but a.b does not.
1745 dot
= strchrW( server
, '.' );
1748 int len
= strlenW( dot
+ 1 );
1750 if (len
> strlenW( domain
+ 2 ))
1754 /* The server's domain is longer than the wildcard, so it
1755 * could be a subdomain. Compare the last portion of the
1758 ptr
= dot
+ len
+ 1 - strlenW( domain
+ 2 );
1759 if (!strcmpiW( ptr
, domain
+ 2 ))
1761 /* This is only a match if the preceding character is
1762 * a '.', i.e. that it is a matching domain. E.g.
1763 * if domain is '*.b.c' and server is 'www.ab.c' they
1766 ret
= *(ptr
- 1) == '.';
1770 ret
= !strcmpiW( dot
+ 1, domain
+ 2 );
1775 ret
= !strcmpiW( server
, domain
);
1779 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1784 if (!lpwai
->proxyBypass
) return FALSE
;
1785 ptr
= lpwai
->proxyBypass
;
1789 ptr
= strchrW( ptr
, ';' );
1791 ptr
= strchrW( tmp
, ' ' );
1794 if (ptr
- tmp
< INTERNET_MAX_HOST_NAME_LENGTH
)
1796 WCHAR domain
[INTERNET_MAX_HOST_NAME_LENGTH
];
1798 memcpy( domain
, tmp
, (ptr
- tmp
) * sizeof(WCHAR
) );
1799 domain
[ptr
- tmp
] = 0;
1800 ret
= HTTP_DomainMatches( server
, domain
);
1805 ret
= HTTP_DomainMatches( server
, tmp
);
1806 } while (ptr
&& !ret
);
1810 /***********************************************************************
1811 * HTTP_DealWithProxy
1813 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1815 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1816 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1817 static const WCHAR szFormat
[] = { 'h','t','t','p',':','/','/','%','s',0 };
1818 WCHAR buf
[INTERNET_MAX_HOST_NAME_LENGTH
];
1819 WCHAR protoProxy
[INTERNET_MAX_URL_LENGTH
];
1820 DWORD protoProxyLen
= INTERNET_MAX_URL_LENGTH
;
1821 WCHAR proxy
[INTERNET_MAX_URL_LENGTH
];
1822 static WCHAR szNul
[] = { 0 };
1823 URL_COMPONENTSW UrlComponents
;
1824 server_t
*new_server
;
1827 memset( &UrlComponents
, 0, sizeof UrlComponents
);
1828 UrlComponents
.dwStructSize
= sizeof UrlComponents
;
1829 UrlComponents
.lpszHostName
= buf
;
1830 UrlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
1832 if (!INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
, protoProxy
, &protoProxyLen
))
1834 if( CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1835 protoProxy
,strlenW(szHttp
),szHttp
,strlenW(szHttp
)) )
1836 sprintfW(proxy
, szFormat
, protoProxy
);
1838 strcpyW(proxy
, protoProxy
);
1839 if( !InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) )
1841 if( UrlComponents
.dwHostNameLength
== 0 )
1844 if( !request
->path
)
1845 request
->path
= szNul
;
1847 is_https
= (UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
);
1848 if (is_https
&& UrlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
1849 UrlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
1851 new_server
= get_server(UrlComponents
.lpszHostName
, UrlComponents
.nPort
, is_https
, TRUE
);
1855 request
->proxy
= new_server
;
1857 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1861 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1863 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1867 if(server
->addr_len
)
1868 return ERROR_SUCCESS
;
1870 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1871 INTERNET_STATUS_RESOLVING_NAME
,
1873 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1875 addr_len
= sizeof(server
->addr
);
1876 if (!GetAddress(server
->name
, server
->port
, (struct sockaddr
*)&server
->addr
, &addr_len
))
1877 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1879 switch(server
->addr
.ss_family
) {
1881 addr
= &((struct sockaddr_in
*)&server
->addr
)->sin_addr
;
1884 addr
= &((struct sockaddr_in6
*)&server
->addr
)->sin6_addr
;
1887 WARN("unsupported family %d\n", server
->addr
.ss_family
);
1888 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1891 server
->addr_len
= addr_len
;
1892 inet_ntop(server
->addr
.ss_family
, addr
, server
->addr_str
, sizeof(server
->addr_str
));
1893 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1894 INTERNET_STATUS_NAME_RESOLVED
,
1895 server
->addr_str
, strlen(server
->addr_str
)+1);
1897 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1898 return ERROR_SUCCESS
;
1901 static BOOL
HTTP_GetRequestURL(http_request_t
*req
, LPWSTR buf
)
1903 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1904 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1905 static const WCHAR slash
[] = { '/',0 };
1906 LPHTTPHEADERW host_header
;
1909 host_header
= HTTP_GetHeader(req
, hostW
);
1913 EnterCriticalSection( &req
->headers_section
);
1915 if (req
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)
1919 strcpyW(buf
, scheme
);
1920 strcatW(buf
, host_header
->lpszValue
);
1921 if (req
->path
[0] != '/')
1922 strcatW(buf
, slash
);
1923 strcatW(buf
, req
->path
);
1925 LeaveCriticalSection( &req
->headers_section
);
1930 /***********************************************************************
1931 * HTTPREQ_Destroy (internal)
1933 * Deallocate request handle
1936 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1938 http_request_t
*request
= (http_request_t
*) hdr
;
1943 if(request
->hCacheFile
)
1944 CloseHandle(request
->hCacheFile
);
1945 if(request
->req_file
)
1946 req_file_release(request
->req_file
);
1948 request
->headers_section
.DebugInfo
->Spare
[0] = 0;
1949 DeleteCriticalSection( &request
->headers_section
);
1950 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1951 DeleteCriticalSection( &request
->read_section
);
1952 WININET_Release(&request
->session
->hdr
);
1954 destroy_authinfo(request
->authInfo
);
1955 destroy_authinfo(request
->proxyAuthInfo
);
1958 server_release(request
->server
);
1960 server_release(request
->proxy
);
1962 heap_free(request
->path
);
1963 heap_free(request
->verb
);
1964 heap_free(request
->version
);
1965 heap_free(request
->statusText
);
1967 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1969 heap_free(request
->custHeaders
[i
].lpszField
);
1970 heap_free(request
->custHeaders
[i
].lpszValue
);
1972 destroy_data_stream(request
->data_stream
);
1973 heap_free(request
->custHeaders
);
1976 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1978 TRACE("%p %p %x\n",req
, req
->netconn
, reuse
);
1980 if(!is_valid_netconn(req
->netconn
))
1983 if(reuse
&& req
->netconn
->keep_alive
) {
1986 EnterCriticalSection(&connection_pool_cs
);
1988 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1989 req
->netconn
->keep_until
= GetTickCount64() + COLLECT_TIME
;
1990 req
->netconn
= NULL
;
1992 run_collector
= !collector_running
;
1993 collector_running
= TRUE
;
1995 LeaveCriticalSection(&connection_pool_cs
);
1998 HANDLE thread
= NULL
;
2001 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
2003 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
2005 EnterCriticalSection(&connection_pool_cs
);
2006 collector_running
= FALSE
;
2007 LeaveCriticalSection(&connection_pool_cs
);
2010 FreeLibrary(module
);
2013 CloseHandle(thread
);
2018 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
2019 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
2021 close_netconn(req
->netconn
);
2023 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
2024 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
2027 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
2029 WCHAR szVersion
[10];
2030 WCHAR szConnectionResponse
[20];
2031 DWORD dwBufferSize
= sizeof(szVersion
);
2032 BOOL keepalive
= FALSE
;
2034 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2035 * the connection is keep-alive by default */
2036 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2037 && !strcmpiW(szVersion
, g_szHttp1_1
))
2042 dwBufferSize
= sizeof(szConnectionResponse
);
2043 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2044 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
2046 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2052 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2054 http_request_t
*req
= (http_request_t
*)hdr
;
2056 http_release_netconn(req
, drain_content(req
, FALSE
));
2059 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2064 WCHAR
*buf
= buffer
;
2066 if (str
) len
= strlenW(str
);
2068 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2070 *size
= (len
+ 1) * sizeof(WCHAR
);
2071 return ERROR_INSUFFICIENT_BUFFER
;
2073 if (str
) strcpyW(buf
, str
);
2077 return ERROR_SUCCESS
;
2083 if (str
) len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
2088 return ERROR_INSUFFICIENT_BUFFER
;
2090 if (str
) WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, *size
, NULL
, NULL
);
2094 return ERROR_SUCCESS
;
2098 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2100 http_request_t
*req
= (http_request_t
*)hdr
;
2103 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2105 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2107 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2109 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2110 return ERROR_INSUFFICIENT_BUFFER
;
2111 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2112 /* FIXME: can't get a SOCKET from our connection since we don't use
2116 /* FIXME: get source port from req->netConnection */
2117 info
->SourcePort
= 0;
2118 info
->DestPort
= req
->server
->port
;
2120 if (HTTP_KeepAlive(req
))
2121 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2123 info
->Flags
|= IDSI_FLAG_PROXY
;
2124 if (is_valid_netconn(req
->netconn
) && req
->netconn
->secure
)
2125 info
->Flags
|= IDSI_FLAG_SECURE
;
2127 return ERROR_SUCCESS
;
2131 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2133 case INTERNET_OPTION_SECURITY_FLAGS
:
2137 if (*size
< sizeof(ULONG
))
2138 return ERROR_INSUFFICIENT_BUFFER
;
2140 *size
= sizeof(DWORD
);
2141 flags
= is_valid_netconn(req
->netconn
) ? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2142 *(DWORD
*)buffer
= flags
;
2144 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2145 return ERROR_SUCCESS
;
2148 case INTERNET_OPTION_HANDLE_TYPE
:
2149 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2151 if (*size
< sizeof(ULONG
))
2152 return ERROR_INSUFFICIENT_BUFFER
;
2154 *size
= sizeof(DWORD
);
2155 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2156 return ERROR_SUCCESS
;
2158 case INTERNET_OPTION_URL
: {
2159 static const WCHAR httpW
[] = {'h','t','t','p',':','/','/',0};
2160 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2163 TRACE("INTERNET_OPTION_URL\n");
2165 EnterCriticalSection( &req
->headers_section
);
2166 host
= HTTP_GetHeader(req
, hostW
);
2167 strcpyW(url
, httpW
);
2168 strcatW(url
, host
->lpszValue
);
2169 strcatW(url
, req
->path
);
2170 LeaveCriticalSection( &req
->headers_section
);
2172 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url
));
2173 return str_to_buffer(url
, buffer
, size
, unicode
);
2175 case INTERNET_OPTION_USER_AGENT
:
2176 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2177 case INTERNET_OPTION_USERNAME
:
2178 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2179 case INTERNET_OPTION_PASSWORD
:
2180 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2181 case INTERNET_OPTION_PROXY_USERNAME
:
2182 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2183 case INTERNET_OPTION_PROXY_PASSWORD
:
2184 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2186 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2187 INTERNET_CACHE_ENTRY_INFOW
*info
;
2188 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2189 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2190 DWORD nbytes
, error
;
2193 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2195 if (*size
< sizeof(*ts
))
2197 *size
= sizeof(*ts
);
2198 return ERROR_INSUFFICIENT_BUFFER
;
2201 HTTP_GetRequestURL(req
, url
);
2202 ret
= GetUrlCacheEntryInfoW(url
, NULL
, &nbytes
);
2203 error
= GetLastError();
2204 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2206 if (!(info
= heap_alloc(nbytes
)))
2207 return ERROR_OUTOFMEMORY
;
2209 GetUrlCacheEntryInfoW(url
, info
, &nbytes
);
2211 ts
->ftExpires
= info
->ExpireTime
;
2212 ts
->ftLastModified
= info
->LastModifiedTime
;
2215 *size
= sizeof(*ts
);
2216 return ERROR_SUCCESS
;
2221 case INTERNET_OPTION_DATAFILE_NAME
: {
2224 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2226 if(!req
->req_file
) {
2228 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2232 req_size
= (lstrlenW(req
->req_file
->file_name
)+1) * sizeof(WCHAR
);
2233 if(*size
< req_size
)
2234 return ERROR_INSUFFICIENT_BUFFER
;
2237 memcpy(buffer
, req
->req_file
->file_name
, *size
);
2238 return ERROR_SUCCESS
;
2240 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
, -1, NULL
, 0, NULL
, NULL
);
2241 if (req_size
> *size
)
2242 return ERROR_INSUFFICIENT_BUFFER
;
2244 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
,
2245 -1, buffer
, *size
, NULL
, NULL
);
2246 return ERROR_SUCCESS
;
2250 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2251 PCCERT_CONTEXT context
;
2254 return ERROR_INTERNET_INVALID_OPERATION
;
2256 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2257 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2258 return ERROR_INSUFFICIENT_BUFFER
;
2261 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2263 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2266 memset(info
, 0, sizeof(*info
));
2267 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2268 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2269 len
= CertNameToStrA(context
->dwCertEncodingType
,
2270 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2271 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2272 if(info
->lpszSubjectInfo
)
2273 CertNameToStrA(context
->dwCertEncodingType
,
2274 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2275 info
->lpszSubjectInfo
, len
);
2276 len
= CertNameToStrA(context
->dwCertEncodingType
,
2277 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2278 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2279 if(info
->lpszIssuerInfo
)
2280 CertNameToStrA(context
->dwCertEncodingType
,
2281 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2282 info
->lpszIssuerInfo
, len
);
2283 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2284 CertFreeCertificateContext(context
);
2285 return ERROR_SUCCESS
;
2287 return ERROR_NOT_SUPPORTED
;
2289 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2290 if (*size
< sizeof(DWORD
))
2291 return ERROR_INSUFFICIENT_BUFFER
;
2293 *size
= sizeof(DWORD
);
2294 *(DWORD
*)buffer
= req
->connect_timeout
;
2295 return ERROR_SUCCESS
;
2296 case INTERNET_OPTION_REQUEST_FLAGS
: {
2299 if (*size
< sizeof(DWORD
))
2300 return ERROR_INSUFFICIENT_BUFFER
;
2302 /* FIXME: Add support for:
2303 * INTERNET_REQFLAG_FROM_CACHE
2304 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2308 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2309 if(!req
->status_code
)
2310 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2312 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2314 *size
= sizeof(DWORD
);
2315 *(DWORD
*)buffer
= flags
;
2316 return ERROR_SUCCESS
;
2320 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2323 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2325 http_request_t
*req
= (http_request_t
*)hdr
;
2328 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2329 TRACE("Undocumented option 99\n");
2331 if (!buffer
|| size
!= sizeof(DWORD
))
2332 return ERROR_INVALID_PARAMETER
;
2333 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2334 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2337 case INTERNET_OPTION_SECURITY_FLAGS
:
2341 if (!buffer
|| size
!= sizeof(DWORD
))
2342 return ERROR_INVALID_PARAMETER
;
2343 flags
= *(DWORD
*)buffer
;
2344 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2345 flags
&= SECURITY_SET_MASK
;
2346 req
->security_flags
|= flags
;
2347 if(is_valid_netconn(req
->netconn
))
2348 req
->netconn
->security_flags
|= flags
;
2349 return ERROR_SUCCESS
;
2351 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2352 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2353 req
->connect_timeout
= *(DWORD
*)buffer
;
2354 return ERROR_SUCCESS
;
2356 case INTERNET_OPTION_SEND_TIMEOUT
:
2357 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2358 req
->send_timeout
= *(DWORD
*)buffer
;
2359 return ERROR_SUCCESS
;
2361 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2362 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2363 req
->receive_timeout
= *(DWORD
*)buffer
;
2364 return ERROR_SUCCESS
;
2366 case INTERNET_OPTION_USERNAME
:
2367 heap_free(req
->session
->userName
);
2368 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2369 return ERROR_SUCCESS
;
2371 case INTERNET_OPTION_PASSWORD
:
2372 heap_free(req
->session
->password
);
2373 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2374 return ERROR_SUCCESS
;
2376 case INTERNET_OPTION_PROXY_USERNAME
:
2377 heap_free(req
->session
->appInfo
->proxyUsername
);
2378 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2379 return ERROR_SUCCESS
;
2381 case INTERNET_OPTION_PROXY_PASSWORD
:
2382 heap_free(req
->session
->appInfo
->proxyPassword
);
2383 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2384 return ERROR_SUCCESS
;
2386 case INTERNET_OPTION_HTTP_DECODING
:
2387 if(size
!= sizeof(BOOL
))
2388 return ERROR_INVALID_PARAMETER
;
2389 req
->decoding
= *(BOOL
*)buffer
;
2390 return ERROR_SUCCESS
;
2393 return INET_SetOption(hdr
, option
, buffer
, size
);
2396 static void commit_cache_entry(http_request_t
*req
)
2398 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2402 CloseHandle(req
->hCacheFile
);
2403 req
->hCacheFile
= NULL
;
2405 if(HTTP_GetRequestURL(req
, url
)) {
2410 header
= build_response_header(req
, TRUE
);
2411 header_len
= (header
? strlenW(header
) : 0);
2412 res
= CommitUrlCacheEntryW(url
, req
->req_file
->file_name
, req
->expires
,
2413 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2414 header
, header_len
, NULL
, 0);
2416 req
->req_file
->is_committed
= TRUE
;
2418 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2423 static void create_cache_entry(http_request_t
*req
)
2425 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2426 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2428 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2429 WCHAR file_name
[MAX_PATH
+1];
2432 /* FIXME: We should free previous cache file earlier */
2434 req_file_release(req
->req_file
);
2435 req
->req_file
= NULL
;
2437 if(req
->hCacheFile
) {
2438 CloseHandle(req
->hCacheFile
);
2439 req
->hCacheFile
= NULL
;
2442 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2448 EnterCriticalSection( &req
->headers_section
);
2450 header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2451 if(header_idx
!= -1) {
2454 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2457 while(*ptr
==' ' || *ptr
=='\t')
2460 end
= strchrW(ptr
, ',');
2462 end
= ptr
+ strlenW(ptr
);
2464 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2465 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2476 LeaveCriticalSection( &req
->headers_section
);
2480 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2483 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2486 b
= HTTP_GetRequestURL(req
, url
);
2488 WARN("Could not get URL\n");
2492 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2494 WARN("Could not create cache entry: %08x\n", GetLastError());
2498 create_req_file(file_name
, &req
->req_file
);
2500 req
->hCacheFile
= CreateFileW(file_name
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2501 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2502 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2503 WARN("Could not create file: %u\n", GetLastError());
2504 req
->hCacheFile
= NULL
;
2508 if(req
->read_size
) {
2511 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2513 FIXME("WriteFile failed: %u\n", GetLastError());
2515 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2516 commit_cache_entry(req
);
2520 /* read some more data into the read buffer (the read section must be held) */
2521 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2528 /* move existing data to the start of the buffer */
2530 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2534 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2536 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2537 maxlen
- req
->read_size
, BLOCKING_ALLOW
, &len
);
2538 if(res
== ERROR_SUCCESS
)
2539 req
->read_size
+= len
;
2544 /* remove some amount of data from the read buffer (the read section must be held) */
2545 static void remove_data( http_request_t
*req
, int count
)
2547 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2548 else req
->read_pos
+= count
;
2551 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2553 int count
, bytes_read
, pos
= 0;
2556 EnterCriticalSection( &req
->read_section
);
2559 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2563 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2564 bytes_read
= count
+ 1;
2566 else count
= bytes_read
= req
->read_size
;
2568 count
= min( count
, *len
- pos
);
2569 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2571 remove_data( req
, bytes_read
);
2574 if ((res
= read_more_data( req
, -1 )))
2576 WARN( "read failed %u\n", res
);
2577 LeaveCriticalSection( &req
->read_section
);
2580 if (!req
->read_size
)
2583 TRACE( "returning empty string\n" );
2584 LeaveCriticalSection( &req
->read_section
);
2585 return ERROR_SUCCESS
;
2588 LeaveCriticalSection( &req
->read_section
);
2592 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2595 buffer
[*len
- 1] = 0;
2596 TRACE( "returning %s\n", debugstr_a(buffer
));
2597 return ERROR_SUCCESS
;
2600 /* check if we have reached the end of the data to read (the read section must be held) */
2601 static BOOL
end_of_read_data( http_request_t
*req
)
2603 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2606 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, blocking_mode_t blocking_mode
)
2610 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, blocking_mode
);
2611 assert(*read
<= size
);
2613 if(req
->hCacheFile
) {
2618 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2620 FIXME("WriteFile failed: %u\n", GetLastError());
2623 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2624 commit_cache_entry(req
);
2630 /* fetch some more data into the read buffer (the read section must be held) */
2631 static DWORD
refill_read_buffer(http_request_t
*req
, blocking_mode_t blocking_mode
, DWORD
*read_bytes
)
2635 if(req
->read_size
== sizeof(req
->read_buf
))
2636 return ERROR_SUCCESS
;
2640 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2644 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2645 &read
, blocking_mode
);
2646 req
->read_size
+= read
;
2648 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2654 /* return the size of data available to be read immediately (the read section must be held) */
2655 static DWORD
get_avail_data( http_request_t
*req
)
2657 return req
->read_size
+ req
->data_stream
->vtbl
->get_avail_data(req
->data_stream
, req
);
2660 static DWORD
netconn_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2662 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2665 if(is_valid_netconn(req
->netconn
))
2666 NETCON_query_data_available(req
->netconn
, &avail
);
2667 return netconn_stream
->content_length
== ~0u
2669 : min(avail
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2672 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2674 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2675 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !is_valid_netconn(req
->netconn
);
2678 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2679 DWORD
*read
, blocking_mode_t blocking_mode
)
2681 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2682 DWORD res
= ERROR_SUCCESS
;
2685 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2687 if(size
&& is_valid_netconn(req
->netconn
)) {
2688 if((res
= NETCON_recv(req
->netconn
, buf
, size
, blocking_mode
, &len
))) {
2690 if(blocking_mode
== BLOCKING_DISALLOW
&& res
== WSAEWOULDBLOCK
)
2691 res
= ERROR_SUCCESS
;
2693 netconn_stream
->content_length
= netconn_stream
->content_read
;
2695 netconn_stream
->content_length
= netconn_stream
->content_read
;
2699 netconn_stream
->content_read
+= *read
= len
;
2700 TRACE("read %u bytes\n", len
);
2704 static BOOL
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2706 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2710 if(netconn_end_of_data(stream
, req
))
2714 if(NETCON_recv(req
->netconn
, buf
, sizeof(buf
), BLOCKING_DISALLOW
, &len
) != ERROR_SUCCESS
)
2717 netconn_stream
->content_read
+= len
;
2718 }while(netconn_stream
->content_read
< netconn_stream
->content_length
);
2723 static void netconn_destroy(data_stream_t
*stream
)
2727 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2728 netconn_get_avail_data
,
2729 netconn_end_of_data
,
2731 netconn_drain_content
,
2735 /* read some more data into the read buffer (the read section must be held) */
2736 static DWORD
read_more_chunked_data(chunked_stream_t
*stream
, http_request_t
*req
, int maxlen
)
2741 assert(!stream
->end_of_data
);
2743 if (stream
->buf_pos
)
2745 /* move existing data to the start of the buffer */
2746 if(stream
->buf_size
)
2747 memmove(stream
->buf
, stream
->buf
+ stream
->buf_pos
, stream
->buf_size
);
2748 stream
->buf_pos
= 0;
2751 if (maxlen
== -1) maxlen
= sizeof(stream
->buf
);
2753 res
= NETCON_recv( req
->netconn
, stream
->buf
+ stream
->buf_size
,
2754 maxlen
- stream
->buf_size
, BLOCKING_ALLOW
, &len
);
2755 if(res
== ERROR_SUCCESS
)
2756 stream
->buf_size
+= len
;
2761 /* remove some amount of data from the read buffer (the read section must be held) */
2762 static void remove_chunked_data(chunked_stream_t
*stream
, int count
)
2764 if (!(stream
->buf_size
-= count
)) stream
->buf_pos
= 0;
2765 else stream
->buf_pos
+= count
;
2768 /* discard data contents until we reach end of line (the read section must be held) */
2769 static DWORD
discard_chunked_eol(chunked_stream_t
*stream
, http_request_t
*req
)
2775 BYTE
*eol
= memchr(stream
->buf
+ stream
->buf_pos
, '\n', stream
->buf_size
);
2778 remove_chunked_data(stream
, (eol
+ 1) - (stream
->buf
+ stream
->buf_pos
));
2781 stream
->buf_pos
= stream
->buf_size
= 0; /* discard everything */
2782 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2783 } while (stream
->buf_size
);
2784 return ERROR_SUCCESS
;
2787 /* read the size of the next chunk (the read section must be held) */
2788 static DWORD
start_next_chunk(chunked_stream_t
*stream
, http_request_t
*req
)
2790 DWORD chunk_size
= 0, res
;
2792 assert(!stream
->chunk_size
|| stream
->chunk_size
== ~0u);
2794 if (stream
->end_of_data
) return ERROR_SUCCESS
;
2796 /* read terminator for the previous chunk */
2797 if(!stream
->chunk_size
&& (res
= discard_chunked_eol(stream
, req
)) != ERROR_SUCCESS
)
2802 while (stream
->buf_size
)
2804 char ch
= stream
->buf
[stream
->buf_pos
];
2805 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
2806 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
2807 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
2808 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
2810 TRACE( "reading %u byte chunk\n", chunk_size
);
2811 stream
->chunk_size
= chunk_size
;
2812 if (req
->contentLength
== ~0u) req
->contentLength
= chunk_size
;
2813 else req
->contentLength
+= chunk_size
;
2815 if (!chunk_size
) stream
->end_of_data
= TRUE
;
2816 return discard_chunked_eol(stream
, req
);
2818 remove_chunked_data(stream
, 1);
2820 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2821 if (!stream
->buf_size
)
2823 stream
->chunk_size
= 0;
2824 return ERROR_SUCCESS
;
2829 static DWORD
chunked_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2831 /* Allow reading only from read buffer */
2835 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2837 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2838 return chunked_stream
->end_of_data
;
2841 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2842 DWORD
*read
, blocking_mode_t blocking_mode
)
2844 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2845 DWORD read_bytes
= 0, ret_read
= 0, res
= ERROR_SUCCESS
;
2847 if(!chunked_stream
->chunk_size
|| chunked_stream
->chunk_size
== ~0u) {
2848 res
= start_next_chunk(chunked_stream
, req
);
2849 if(res
!= ERROR_SUCCESS
)
2853 while(size
&& chunked_stream
->chunk_size
&& !chunked_stream
->end_of_data
) {
2854 if(chunked_stream
->buf_size
) {
2855 read_bytes
= min(size
, min(chunked_stream
->buf_size
, chunked_stream
->chunk_size
));
2857 /* this could block */
2858 if(blocking_mode
== BLOCKING_DISALLOW
&& read_bytes
== chunked_stream
->chunk_size
)
2861 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2862 remove_chunked_data(chunked_stream
, read_bytes
);
2864 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2866 if(blocking_mode
== BLOCKING_DISALLOW
) {
2869 if(!is_valid_netconn(req
->netconn
) || !NETCON_query_data_available(req
->netconn
, &avail
) || !avail
)
2871 if(read_bytes
> avail
)
2874 /* this could block */
2875 if(read_bytes
== chunked_stream
->chunk_size
)
2879 res
= NETCON_recv(req
->netconn
, (char *)buf
+ret_read
, read_bytes
, BLOCKING_ALLOW
, (int*)&read_bytes
);
2880 if(res
!= ERROR_SUCCESS
)
2884 chunked_stream
->chunk_size
-= read_bytes
;
2886 ret_read
+= read_bytes
;
2887 if(size
&& !chunked_stream
->chunk_size
) {
2888 assert(blocking_mode
!= BLOCKING_DISALLOW
);
2889 res
= start_next_chunk(chunked_stream
, req
);
2890 if(res
!= ERROR_SUCCESS
)
2894 if(blocking_mode
== BLOCKING_ALLOW
)
2895 blocking_mode
= BLOCKING_DISALLOW
;
2898 TRACE("read %u bytes\n", ret_read
);
2903 static BOOL
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2905 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2907 remove_chunked_data(chunked_stream
, chunked_stream
->buf_size
);
2908 return chunked_stream
->end_of_data
;
2911 static void chunked_destroy(data_stream_t
*stream
)
2913 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2914 heap_free(chunked_stream
);
2917 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2918 chunked_get_avail_data
,
2919 chunked_end_of_data
,
2921 chunked_drain_content
,
2925 /* set the request content length based on the headers */
2926 static DWORD
set_content_length(http_request_t
*request
)
2928 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2929 static const WCHAR headW
[] = {'H','E','A','D',0};
2933 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
|| !strcmpW(request
->verb
, headW
)) {
2934 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2935 return ERROR_SUCCESS
;
2938 size
= sizeof(request
->contentLength
);
2939 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2940 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2941 request
->contentLength
= ~0u;
2942 request
->netconn_stream
.content_length
= request
->contentLength
;
2943 request
->netconn_stream
.content_read
= request
->read_size
;
2945 size
= sizeof(encoding
);
2946 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2947 !strcmpiW(encoding
, szChunked
))
2949 chunked_stream_t
*chunked_stream
;
2951 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2953 return ERROR_OUTOFMEMORY
;
2955 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2956 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2957 chunked_stream
->chunk_size
= ~0u;
2958 chunked_stream
->end_of_data
= FALSE
;
2960 if(request
->read_size
) {
2961 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2962 chunked_stream
->buf_size
= request
->read_size
;
2963 request
->read_size
= request
->read_pos
= 0;
2966 request
->data_stream
= &chunked_stream
->data_stream
;
2967 request
->contentLength
= ~0u;
2968 request
->read_chunked
= TRUE
;
2971 if(request
->decoding
) {
2974 static const WCHAR deflateW
[] = {'d','e','f','l','a','t','e',0};
2975 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2977 EnterCriticalSection( &request
->headers_section
);
2979 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2980 if(encoding_idx
!= -1) {
2981 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2982 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2983 LeaveCriticalSection( &request
->headers_section
);
2984 return init_gzip_stream(request
, TRUE
);
2986 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, deflateW
)) {
2987 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2988 LeaveCriticalSection( &request
->headers_section
);
2989 return init_gzip_stream(request
, FALSE
);
2993 LeaveCriticalSection( &request
->headers_section
);
2996 return ERROR_SUCCESS
;
2999 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
3001 INTERNET_ASYNC_RESULT iar
;
3003 iar
.dwResult
= result
;
3004 iar
.dwError
= error
;
3006 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
3007 sizeof(INTERNET_ASYNC_RESULT
));
3010 static void HTTP_ReceiveRequestData(http_request_t
*req
, BOOL first_notif
, DWORD
*ret_size
)
3012 DWORD res
, read
= 0, avail
= 0;
3013 blocking_mode_t mode
;
3017 EnterCriticalSection( &req
->read_section
);
3019 mode
= first_notif
&& req
->read_size
? BLOCKING_DISALLOW
: BLOCKING_ALLOW
;
3020 res
= refill_read_buffer(req
, mode
, &read
);
3021 if(res
== ERROR_SUCCESS
)
3022 avail
= get_avail_data(req
);
3024 LeaveCriticalSection( &req
->read_section
);
3026 if(res
!= ERROR_SUCCESS
|| (mode
!= BLOCKING_DISALLOW
&& !read
)) {
3027 WARN("res %u read %u, closing connection\n", res
, read
);
3028 http_release_netconn(req
, FALSE
);
3031 if(res
!= ERROR_SUCCESS
) {
3032 send_request_complete(req
, 0, res
);
3041 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, avail
);
3044 /* read data from the http connection (the read section must be held) */
3045 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
, BOOL sync
)
3047 DWORD current_read
= 0, ret_read
= 0;
3048 blocking_mode_t blocking_mode
;
3049 DWORD res
= ERROR_SUCCESS
;
3051 blocking_mode
= req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
? BLOCKING_ALLOW
: BLOCKING_WAITALL
;
3053 EnterCriticalSection( &req
->read_section
);
3055 if(req
->read_size
) {
3056 ret_read
= min(size
, req
->read_size
);
3057 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
3058 req
->read_size
-= ret_read
;
3059 req
->read_pos
+= ret_read
;
3060 if(blocking_mode
== BLOCKING_ALLOW
)
3061 blocking_mode
= BLOCKING_DISALLOW
;
3064 if(ret_read
< size
) {
3065 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, blocking_mode
);
3066 ret_read
+= current_read
;
3069 LeaveCriticalSection( &req
->read_section
);
3072 TRACE( "retrieved %u bytes (%u)\n", ret_read
, req
->contentLength
);
3074 if(size
&& !ret_read
)
3075 http_release_netconn(req
, res
== ERROR_SUCCESS
);
3080 static BOOL
drain_content(http_request_t
*req
, BOOL blocking
)
3084 if(!is_valid_netconn(req
->netconn
) || req
->contentLength
== -1)
3087 if(!strcmpW(req
->verb
, szHEAD
))
3091 return req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
);
3093 EnterCriticalSection( &req
->read_section
);
3096 DWORD bytes_read
, res
;
3099 res
= HTTPREQ_Read(req
, buf
, sizeof(buf
), &bytes_read
, TRUE
);
3100 if(res
!= ERROR_SUCCESS
) {
3110 LeaveCriticalSection( &req
->read_section
);
3114 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buffer
, DWORD size
, DWORD
*read
)
3116 http_request_t
*req
= (http_request_t
*)hdr
;
3119 EnterCriticalSection( &req
->read_section
);
3120 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3121 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3123 res
= HTTPREQ_Read(req
, buffer
, size
, read
, TRUE
);
3124 if(res
== ERROR_SUCCESS
)
3126 LeaveCriticalSection( &req
->read_section
);
3136 } read_file_ex_task_t
;
3138 static void AsyncReadFileExProc(task_header_t
*hdr
)
3140 read_file_ex_task_t
*task
= (read_file_ex_task_t
*)hdr
;
3141 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3144 TRACE("INTERNETREADFILEEXW %p\n", task
->hdr
.hdr
);
3146 res
= HTTPREQ_Read(req
, task
->buf
, task
->size
, task
->ret_read
, TRUE
);
3147 send_request_complete(req
, res
== ERROR_SUCCESS
, res
);
3150 static DWORD
HTTPREQ_ReadFileEx(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3151 DWORD flags
, DWORD_PTR context
)
3154 http_request_t
*req
= (http_request_t
*)hdr
;
3155 DWORD res
, read
, cread
, error
= ERROR_SUCCESS
;
3157 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3158 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3160 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3162 if (hdr
->dwFlags
& INTERNET_FLAG_ASYNC
)
3164 read_file_ex_task_t
*task
;
3166 if (TryEnterCriticalSection( &req
->read_section
))
3168 if (get_avail_data(req
))
3170 res
= HTTPREQ_Read(req
, buf
, size
, &read
, FALSE
);
3171 LeaveCriticalSection( &req
->read_section
);
3174 LeaveCriticalSection( &req
->read_section
);
3177 task
= alloc_async_task(&req
->hdr
, AsyncReadFileExProc
, sizeof(*task
));
3180 task
->ret_read
= ret_read
;
3182 INTERNET_AsyncCall(&task
->hdr
);
3184 return ERROR_IO_PENDING
;
3189 EnterCriticalSection( &req
->read_section
);
3190 if(hdr
->dwError
== ERROR_SUCCESS
)
3191 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3192 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3193 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3196 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
, !(flags
& IRF_NO_WAIT
));
3197 if(res
!= ERROR_SUCCESS
)
3201 if(read
== size
|| end_of_read_data(req
))
3204 LeaveCriticalSection( &req
->read_section
);
3206 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3207 &cread
, sizeof(cread
));
3208 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
3209 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3211 EnterCriticalSection( &req
->read_section
);
3214 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3215 hdr
->dwError
= ERROR_SUCCESS
;
3217 error
= hdr
->dwError
;
3219 LeaveCriticalSection( &req
->read_section
);
3223 if (res
== ERROR_SUCCESS
) {
3224 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3225 &read
, sizeof(read
));
3228 return res
==ERROR_SUCCESS
? error
: res
;
3231 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3234 http_request_t
*request
= (http_request_t
*)hdr
;
3236 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3239 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3240 if (res
== ERROR_SUCCESS
)
3241 request
->bytesWritten
+= *written
;
3243 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3250 } http_data_available_task_t
;
3252 static void AsyncQueryDataAvailableProc(task_header_t
*hdr
)
3254 http_data_available_task_t
*task
= (http_data_available_task_t
*)hdr
;
3256 HTTP_ReceiveRequestData((http_request_t
*)task
->hdr
.hdr
, FALSE
, task
->ret_size
);
3259 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3261 http_request_t
*req
= (http_request_t
*)hdr
;
3263 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3265 if (req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
3267 http_data_available_task_t
*task
;
3269 /* never wait, if we can't enter the section we queue an async request right away */
3270 if (TryEnterCriticalSection( &req
->read_section
))
3272 refill_read_buffer(req
, BLOCKING_DISALLOW
, NULL
);
3273 if ((*available
= get_avail_data( req
))) goto done
;
3274 if (end_of_read_data( req
)) goto done
;
3275 LeaveCriticalSection( &req
->read_section
);
3278 task
= alloc_async_task(&req
->hdr
, AsyncQueryDataAvailableProc
, sizeof(*task
));
3279 task
->ret_size
= available
;
3280 INTERNET_AsyncCall(&task
->hdr
);
3281 return ERROR_IO_PENDING
;
3284 EnterCriticalSection( &req
->read_section
);
3286 if (!(*available
= get_avail_data( req
)) && !end_of_read_data( req
))
3288 refill_read_buffer( req
, BLOCKING_ALLOW
, NULL
);
3289 *available
= get_avail_data( req
);
3293 LeaveCriticalSection( &req
->read_section
);
3295 TRACE( "returning %u\n", *available
);
3296 return ERROR_SUCCESS
;
3299 static DWORD
HTTPREQ_LockRequestFile(object_header_t
*hdr
, req_file_t
**ret
)
3301 http_request_t
*req
= (http_request_t
*)hdr
;
3303 TRACE("(%p)\n", req
);
3305 if(!req
->req_file
) {
3306 WARN("No cache file name available\n");
3307 return ERROR_FILE_NOT_FOUND
;
3310 *ret
= req_file_addref(req
->req_file
);
3311 return ERROR_SUCCESS
;
3314 static const object_vtbl_t HTTPREQVtbl
= {
3316 HTTPREQ_CloseConnection
,
3317 HTTPREQ_QueryOption
,
3322 HTTPREQ_QueryDataAvailable
,
3324 HTTPREQ_LockRequestFile
3327 /***********************************************************************
3328 * HTTP_HttpOpenRequestW (internal)
3330 * Open a HTTP request handle
3333 * HINTERNET a HTTP request handle on success
3337 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3338 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3339 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3340 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3342 appinfo_t
*hIC
= session
->appInfo
;
3343 http_request_t
*request
;
3348 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3350 return ERROR_OUTOFMEMORY
;
3352 request
->hdr
.htype
= WH_HHTTPREQ
;
3353 request
->hdr
.dwFlags
= dwFlags
;
3354 request
->hdr
.dwContext
= dwContext
;
3355 request
->contentLength
= ~0u;
3357 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3358 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3359 request
->connect_timeout
= session
->connect_timeout
;
3360 request
->send_timeout
= session
->send_timeout
;
3361 request
->receive_timeout
= session
->receive_timeout
;
3363 InitializeCriticalSection( &request
->headers_section
);
3364 request
->headers_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.headers_section");
3366 InitializeCriticalSection( &request
->read_section
);
3367 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3369 WININET_AddRef( &session
->hdr
);
3370 request
->session
= session
;
3371 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3373 request
->server
= get_server(session
->hostName
, session
->hostPort
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3374 if(!request
->server
) {
3375 WININET_Release(&request
->hdr
);
3376 return ERROR_OUTOFMEMORY
;
3379 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3380 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3381 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3382 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3384 if (lpszObjectName
&& *lpszObjectName
) {
3388 rc
= UrlEscapeW(lpszObjectName
, NULL
, &len
, URL_ESCAPE_SPACES_ONLY
);
3389 if (rc
!= E_POINTER
)
3390 len
= strlenW(lpszObjectName
)+1;
3391 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3392 rc
= UrlEscapeW(lpszObjectName
, request
->path
, &len
,
3393 URL_ESCAPE_SPACES_ONLY
);
3396 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3397 strcpyW(request
->path
,lpszObjectName
);
3400 static const WCHAR slashW
[] = {'/',0};
3402 request
->path
= heap_strdupW(slashW
);
3405 if (lpszReferrer
&& *lpszReferrer
)
3406 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3408 if (lpszAcceptTypes
)
3411 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3413 if (!*lpszAcceptTypes
[i
]) continue;
3414 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3415 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3416 HTTP_ADDHDR_FLAG_REQ
|
3417 (i
== 0 ? HTTP_ADDHDR_FLAG_REPLACE
: 0));
3421 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3422 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3424 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3426 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3427 HTTP_DealWithProxy( hIC
, session
, request
);
3429 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3430 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3433 TRACE("<-- (%p)\n", request
);
3435 *ret
= request
->hdr
.hInternet
;
3436 return ERROR_SUCCESS
;
3439 /***********************************************************************
3440 * HttpOpenRequestW (WININET.@)
3442 * Open a HTTP request handle
3445 * HINTERNET a HTTP request handle on success
3449 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3450 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3451 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3452 DWORD dwFlags
, DWORD_PTR dwContext
)
3454 http_session_t
*session
;
3455 HINTERNET handle
= NULL
;
3458 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3459 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3460 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3461 dwFlags
, dwContext
);
3462 if(lpszAcceptTypes
!=NULL
)
3465 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3466 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3469 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3470 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3472 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3477 * My tests seem to show that the windows version does not
3478 * become asynchronous until after this point. And anyhow
3479 * if this call was asynchronous then how would you get the
3480 * necessary HINTERNET pointer returned by this function.
3483 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3484 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3485 dwFlags
, dwContext
, &handle
);
3488 WININET_Release( &session
->hdr
);
3489 TRACE("returning %p\n", handle
);
3490 if(res
!= ERROR_SUCCESS
)
3495 static const LPCWSTR header_lookup
[] = {
3496 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3497 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3498 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3499 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3500 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3501 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3502 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3503 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3504 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3505 szDate
, /* HTTP_QUERY_DATE = 9 */
3506 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3507 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3508 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3509 szURI
, /* HTTP_QUERY_URI = 13 */
3510 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3511 NULL
, /* HTTP_QUERY_COST = 15 */
3512 NULL
, /* HTTP_QUERY_LINK = 16 */
3513 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3514 NULL
, /* HTTP_QUERY_VERSION = 18 */
3515 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3516 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3517 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3518 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3519 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3520 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3521 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3522 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3523 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3524 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3525 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3526 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3527 NULL
, /* HTTP_QUERY_FROM = 31 */
3528 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3529 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3530 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3531 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3532 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3533 szServer
, /* HTTP_QUERY_SERVER = 37 */
3534 NULL
, /* HTTP_TITLE = 38 */
3535 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3536 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3537 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3538 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3539 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3540 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3541 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3542 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3543 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3544 szAge
, /* HTTP_QUERY_AGE = 48 */
3545 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3546 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3547 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3548 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3549 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3550 szETag
, /* HTTP_QUERY_ETAG = 54 */
3551 hostW
, /* HTTP_QUERY_HOST = 55 */
3552 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3553 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3554 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3555 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3556 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3557 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3558 szRange
, /* HTTP_QUERY_RANGE = 62 */
3559 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3560 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3561 szVary
, /* HTTP_QUERY_VARY = 65 */
3562 szVia
, /* HTTP_QUERY_VIA = 66 */
3563 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3564 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3565 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3566 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3569 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3571 /***********************************************************************
3572 * HTTP_HttpQueryInfoW (internal)
3574 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3575 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3577 LPHTTPHEADERW lphttpHdr
= NULL
;
3578 BOOL request_only
= dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
;
3579 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3580 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3583 EnterCriticalSection( &request
->headers_section
);
3585 /* Find requested header structure */
3588 case HTTP_QUERY_CUSTOM
:
3591 LeaveCriticalSection( &request
->headers_section
);
3592 return ERROR_INVALID_PARAMETER
;
3594 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3596 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3600 DWORD res
= ERROR_INVALID_PARAMETER
;
3603 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3605 headers
= build_response_header(request
, TRUE
);
3608 LeaveCriticalSection( &request
->headers_section
);
3609 return ERROR_OUTOFMEMORY
;
3612 len
= strlenW(headers
) * sizeof(WCHAR
);
3613 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3615 len
+= sizeof(WCHAR
);
3616 res
= ERROR_INSUFFICIENT_BUFFER
;
3620 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3621 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3622 res
= ERROR_SUCCESS
;
3624 *lpdwBufferLength
= len
;
3627 LeaveCriticalSection( &request
->headers_section
);
3630 case HTTP_QUERY_RAW_HEADERS
:
3636 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3638 headers
= build_response_header(request
, FALSE
);
3642 LeaveCriticalSection( &request
->headers_section
);
3643 return ERROR_OUTOFMEMORY
;
3646 len
= strlenW(headers
) * sizeof(WCHAR
);
3647 if (len
> *lpdwBufferLength
)
3649 *lpdwBufferLength
= len
;
3651 LeaveCriticalSection( &request
->headers_section
);
3652 return ERROR_INSUFFICIENT_BUFFER
;
3659 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3661 for (i
= 0; i
< len
/ sizeof(WCHAR
); i
++)
3663 if (headers
[i
] == '\n')
3666 memcpy(lpBuffer
, headers
, len
);
3668 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3671 LeaveCriticalSection( &request
->headers_section
);
3672 return ERROR_SUCCESS
;
3674 case HTTP_QUERY_STATUS_TEXT
:
3675 if (request
->statusText
)
3677 DWORD len
= strlenW(request
->statusText
);
3678 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3680 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3681 LeaveCriticalSection( &request
->headers_section
);
3682 return ERROR_INSUFFICIENT_BUFFER
;
3686 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3687 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3689 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3690 LeaveCriticalSection( &request
->headers_section
);
3691 return ERROR_SUCCESS
;
3694 case HTTP_QUERY_VERSION
:
3695 if (request
->version
)
3697 DWORD len
= strlenW(request
->version
);
3698 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3700 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3701 LeaveCriticalSection( &request
->headers_section
);
3702 return ERROR_INSUFFICIENT_BUFFER
;
3706 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3707 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3709 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3710 LeaveCriticalSection( &request
->headers_section
);
3711 return ERROR_SUCCESS
;
3714 case HTTP_QUERY_CONTENT_ENCODING
:
3715 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3716 requested_index
,request_only
);
3718 case HTTP_QUERY_STATUS_CODE
: {
3719 DWORD res
= ERROR_SUCCESS
;
3723 LeaveCriticalSection( &request
->headers_section
);
3724 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3730 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3731 if(*lpdwBufferLength
>= sizeof(DWORD
))
3732 *(DWORD
*)lpBuffer
= request
->status_code
;
3734 res
= ERROR_INSUFFICIENT_BUFFER
;
3735 *lpdwBufferLength
= sizeof(DWORD
);
3739 static const WCHAR formatW
[] = {'%','u',0};
3741 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3743 if(size
<= *lpdwBufferLength
) {
3744 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3746 size
+= sizeof(WCHAR
);
3747 res
= ERROR_INSUFFICIENT_BUFFER
;
3750 *lpdwBufferLength
= size
;
3752 LeaveCriticalSection( &request
->headers_section
);
3756 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3758 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3759 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3760 requested_index
,request_only
);
3764 lphttpHdr
= &request
->custHeaders
[index
];
3766 /* Ensure header satisfies requested attributes */
3768 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3769 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3771 LeaveCriticalSection( &request
->headers_section
);
3772 return ERROR_HTTP_HEADER_NOT_FOUND
;
3775 /* coalesce value to requested type */
3776 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3778 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3779 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3781 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3787 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3789 tmpTM
= *gmtime(&tmpTime
);
3790 STHook
= (SYSTEMTIME
*)lpBuffer
;
3791 STHook
->wDay
= tmpTM
.tm_mday
;
3792 STHook
->wHour
= tmpTM
.tm_hour
;
3793 STHook
->wMilliseconds
= 0;
3794 STHook
->wMinute
= tmpTM
.tm_min
;
3795 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3796 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3797 STHook
->wSecond
= tmpTM
.tm_sec
;
3798 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3800 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3801 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3802 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3804 else if (lphttpHdr
->lpszValue
)
3806 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3808 if (len
> *lpdwBufferLength
)
3810 *lpdwBufferLength
= len
;
3811 LeaveCriticalSection( &request
->headers_section
);
3812 return ERROR_INSUFFICIENT_BUFFER
;
3816 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3817 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3819 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3821 if (lpdwIndex
) (*lpdwIndex
)++;
3823 LeaveCriticalSection( &request
->headers_section
);
3824 return ERROR_SUCCESS
;
3827 /***********************************************************************
3828 * HttpQueryInfoW (WININET.@)
3830 * Queries for information about an HTTP request
3837 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3838 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3840 http_request_t
*request
;
3843 if (TRACE_ON(wininet
)) {
3844 #define FE(x) { x, #x }
3845 static const wininet_flag_info query_flags
[] = {
3846 FE(HTTP_QUERY_MIME_VERSION
),
3847 FE(HTTP_QUERY_CONTENT_TYPE
),
3848 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3849 FE(HTTP_QUERY_CONTENT_ID
),
3850 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3851 FE(HTTP_QUERY_CONTENT_LENGTH
),
3852 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3853 FE(HTTP_QUERY_ALLOW
),
3854 FE(HTTP_QUERY_PUBLIC
),
3855 FE(HTTP_QUERY_DATE
),
3856 FE(HTTP_QUERY_EXPIRES
),
3857 FE(HTTP_QUERY_LAST_MODIFIED
),
3858 FE(HTTP_QUERY_MESSAGE_ID
),
3860 FE(HTTP_QUERY_DERIVED_FROM
),
3861 FE(HTTP_QUERY_COST
),
3862 FE(HTTP_QUERY_LINK
),
3863 FE(HTTP_QUERY_PRAGMA
),
3864 FE(HTTP_QUERY_VERSION
),
3865 FE(HTTP_QUERY_STATUS_CODE
),
3866 FE(HTTP_QUERY_STATUS_TEXT
),
3867 FE(HTTP_QUERY_RAW_HEADERS
),
3868 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3869 FE(HTTP_QUERY_CONNECTION
),
3870 FE(HTTP_QUERY_ACCEPT
),
3871 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3872 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3873 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3874 FE(HTTP_QUERY_AUTHORIZATION
),
3875 FE(HTTP_QUERY_CONTENT_ENCODING
),
3876 FE(HTTP_QUERY_FORWARDED
),
3877 FE(HTTP_QUERY_FROM
),
3878 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3879 FE(HTTP_QUERY_LOCATION
),
3880 FE(HTTP_QUERY_ORIG_URI
),
3881 FE(HTTP_QUERY_REFERER
),
3882 FE(HTTP_QUERY_RETRY_AFTER
),
3883 FE(HTTP_QUERY_SERVER
),
3884 FE(HTTP_QUERY_TITLE
),
3885 FE(HTTP_QUERY_USER_AGENT
),
3886 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3887 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3888 FE(HTTP_QUERY_ACCEPT_RANGES
),
3889 FE(HTTP_QUERY_SET_COOKIE
),
3890 FE(HTTP_QUERY_COOKIE
),
3891 FE(HTTP_QUERY_REQUEST_METHOD
),
3892 FE(HTTP_QUERY_REFRESH
),
3893 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3895 FE(HTTP_QUERY_CACHE_CONTROL
),
3896 FE(HTTP_QUERY_CONTENT_BASE
),
3897 FE(HTTP_QUERY_CONTENT_LOCATION
),
3898 FE(HTTP_QUERY_CONTENT_MD5
),
3899 FE(HTTP_QUERY_CONTENT_RANGE
),
3900 FE(HTTP_QUERY_ETAG
),
3901 FE(HTTP_QUERY_HOST
),
3902 FE(HTTP_QUERY_IF_MATCH
),
3903 FE(HTTP_QUERY_IF_NONE_MATCH
),
3904 FE(HTTP_QUERY_IF_RANGE
),
3905 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3906 FE(HTTP_QUERY_MAX_FORWARDS
),
3907 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3908 FE(HTTP_QUERY_RANGE
),
3909 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3910 FE(HTTP_QUERY_UPGRADE
),
3911 FE(HTTP_QUERY_VARY
),
3913 FE(HTTP_QUERY_WARNING
),
3914 FE(HTTP_QUERY_CUSTOM
)
3916 static const wininet_flag_info modifier_flags
[] = {
3917 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3918 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3919 FE(HTTP_QUERY_FLAG_NUMBER
),
3920 FE(HTTP_QUERY_FLAG_COALESCE
)
3923 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3924 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3927 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3928 TRACE(" Attribute:");
3929 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3930 if (query_flags
[i
].val
== info
) {
3931 TRACE(" %s", query_flags
[i
].name
);
3935 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3936 TRACE(" Unknown (%08x)", info
);
3939 TRACE(" Modifier:");
3940 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3941 if (modifier_flags
[i
].val
& info_mod
) {
3942 TRACE(" %s", modifier_flags
[i
].name
);
3943 info_mod
&= ~ modifier_flags
[i
].val
;
3948 TRACE(" Unknown (%08x)", info_mod
);
3953 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3954 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3956 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3960 if (lpBuffer
== NULL
)
3961 *lpdwBufferLength
= 0;
3962 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3963 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3967 WININET_Release( &request
->hdr
);
3969 TRACE("%u <--\n", res
);
3970 if(res
!= ERROR_SUCCESS
)
3972 return res
== ERROR_SUCCESS
;
3975 /***********************************************************************
3976 * HttpQueryInfoA (WININET.@)
3978 * Queries for information about an HTTP request
3985 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3986 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3992 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
3994 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3995 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3997 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3998 lpdwBufferLength
, lpdwIndex
);
4004 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
4005 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
4007 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
4013 bufferW
= heap_alloc(alloclen
);
4014 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
4015 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
4016 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
4023 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
4027 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
4028 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
4029 *lpdwBufferLength
= len
- 1;
4031 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
4034 /* since the strings being returned from HttpQueryInfoW should be
4035 * only ASCII characters, it is reasonable to assume that all of
4036 * the Unicode characters can be reduced to a single byte */
4037 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
4039 heap_free( bufferW
);
4043 /***********************************************************************
4044 * HTTP_GetRedirectURL (internal)
4046 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*request
, LPCWSTR lpszUrl
)
4048 static WCHAR szHttp
[] = {'h','t','t','p',0};
4049 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
4050 http_session_t
*session
= request
->session
;
4051 URL_COMPONENTSW urlComponents
;
4052 DWORD url_length
= 0;
4054 LPWSTR combined_url
;
4056 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
4057 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
4058 urlComponents
.dwSchemeLength
= 0;
4059 urlComponents
.lpszHostName
= request
->server
->name
;
4060 urlComponents
.dwHostNameLength
= 0;
4061 urlComponents
.nPort
= request
->server
->port
;
4062 urlComponents
.lpszUserName
= session
->userName
;
4063 urlComponents
.dwUserNameLength
= 0;
4064 urlComponents
.lpszPassword
= NULL
;
4065 urlComponents
.dwPasswordLength
= 0;
4066 urlComponents
.lpszUrlPath
= request
->path
;
4067 urlComponents
.dwUrlPathLength
= 0;
4068 urlComponents
.lpszExtraInfo
= NULL
;
4069 urlComponents
.dwExtraInfoLength
= 0;
4071 if (!InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
) &&
4072 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
4075 orig_url
= heap_alloc(url_length
);
4077 /* convert from bytes to characters */
4078 url_length
= url_length
/ sizeof(WCHAR
) - 1;
4079 if (!InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
))
4081 heap_free(orig_url
);
4086 if (!InternetCombineUrlW(orig_url
, lpszUrl
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
) &&
4087 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
4089 heap_free(orig_url
);
4092 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
4094 if (!InternetCombineUrlW(orig_url
, lpszUrl
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
))
4096 heap_free(orig_url
);
4097 heap_free(combined_url
);
4100 heap_free(orig_url
);
4101 return combined_url
;
4105 /***********************************************************************
4106 * HTTP_HandleRedirect (internal)
4108 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, LPCWSTR lpszUrl
)
4110 http_session_t
*session
= request
->session
;
4111 WCHAR path
[INTERNET_MAX_PATH_LENGTH
];
4116 /* if it's an absolute path, keep the same session info */
4117 lstrcpynW(path
, lpszUrl
, INTERNET_MAX_URL_LENGTH
);
4121 URL_COMPONENTSW urlComponents
;
4122 WCHAR protocol
[INTERNET_MAX_SCHEME_LENGTH
];
4123 WCHAR hostName
[INTERNET_MAX_HOST_NAME_LENGTH
];
4124 WCHAR userName
[INTERNET_MAX_USER_NAME_LENGTH
];
4125 BOOL custom_port
= FALSE
;
4127 static const WCHAR httpW
[] = {'h','t','t','p',0};
4128 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
4134 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
4135 urlComponents
.lpszScheme
= protocol
;
4136 urlComponents
.dwSchemeLength
= INTERNET_MAX_SCHEME_LENGTH
;
4137 urlComponents
.lpszHostName
= hostName
;
4138 urlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
4139 urlComponents
.lpszUserName
= userName
;
4140 urlComponents
.dwUserNameLength
= INTERNET_MAX_USER_NAME_LENGTH
;
4141 urlComponents
.lpszPassword
= NULL
;
4142 urlComponents
.dwPasswordLength
= 0;
4143 urlComponents
.lpszUrlPath
= path
;
4144 urlComponents
.dwUrlPathLength
= INTERNET_MAX_PATH_LENGTH
;
4145 urlComponents
.lpszExtraInfo
= NULL
;
4146 urlComponents
.dwExtraInfoLength
= 0;
4147 if(!InternetCrackUrlW(lpszUrl
, strlenW(lpszUrl
), 0, &urlComponents
))
4148 return INTERNET_GetLastError();
4150 if(!strcmpiW(protocol
, httpW
)) {
4151 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4152 TRACE("redirect from secure page to non-secure page\n");
4153 /* FIXME: warn about from secure redirect to non-secure page */
4154 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4157 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4158 urlComponents
.nPort
= INTERNET_DEFAULT_HTTP_PORT
;
4159 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
)
4161 }else if(!strcmpiW(protocol
, httpsW
)) {
4162 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4163 TRACE("redirect from non-secure page to secure page\n");
4164 /* FIXME: notify about redirect to secure page */
4165 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4168 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4169 urlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
4170 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
)
4174 heap_free(session
->hostName
);
4178 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
4179 len
= lstrlenW(hostName
);
4180 len
+= 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4181 session
->hostName
= heap_alloc(len
*sizeof(WCHAR
));
4182 sprintfW(session
->hostName
, fmt
, hostName
, urlComponents
.nPort
);
4185 session
->hostName
= heap_strdupW(hostName
);
4186 session
->hostPort
= urlComponents
.nPort
;
4188 HTTP_ProcessHeader(request
, hostW
, session
->hostName
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4190 heap_free(session
->userName
);
4191 session
->userName
= NULL
;
4193 session
->userName
= heap_strdupW(userName
);
4195 reset_data_stream(request
);
4197 if(strcmpiW(request
->server
->name
, hostName
) || request
->server
->port
!= urlComponents
.nPort
) {
4198 server_t
*new_server
;
4200 new_server
= get_server(hostName
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4201 server_release(request
->server
);
4202 request
->server
= new_server
;
4205 heap_free(request
->path
);
4212 rc
= UrlEscapeW(path
, NULL
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4213 if (rc
!= E_POINTER
)
4214 needed
= strlenW(path
)+1;
4215 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4216 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4217 URL_ESCAPE_SPACES_ONLY
);
4220 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4221 strcpyW(request
->path
,path
);
4225 EnterCriticalSection( &request
->headers_section
);
4227 /* Remove custom content-type/length headers on redirects. */
4228 index
= HTTP_GetCustomHeaderIndex(request
, szContent_Type
, 0, TRUE
);
4229 if (index
!= -1) HTTP_DeleteCustomHeader(request
, index
);
4230 index
= HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
);
4231 if (index
!= -1) HTTP_DeleteCustomHeader(request
, index
);
4233 LeaveCriticalSection( &request
->headers_section
);
4235 return ERROR_SUCCESS
;
4238 /***********************************************************************
4239 * HTTP_build_req (internal)
4241 * concatenate all the strings in the request together
4243 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4248 for( t
= list
; *t
; t
++ )
4249 len
+= strlenW( *t
);
4252 str
= heap_alloc(len
*sizeof(WCHAR
));
4255 for( t
= list
; *t
; t
++ )
4261 static void HTTP_InsertCookies(http_request_t
*request
)
4266 res
= get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4267 if(res
!= ERROR_SUCCESS
|| !cookies
)
4270 get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4271 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
), HTTP_ADDREQ_FLAG_REPLACE
);
4275 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4277 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4285 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4286 if (!strcmpiW(day
, days
[i
]))
4293 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4295 static const WCHAR jan
[] = { 'j','a','n',0 };
4296 static const WCHAR feb
[] = { 'f','e','b',0 };
4297 static const WCHAR mar
[] = { 'm','a','r',0 };
4298 static const WCHAR apr
[] = { 'a','p','r',0 };
4299 static const WCHAR may
[] = { 'm','a','y',0 };
4300 static const WCHAR jun
[] = { 'j','u','n',0 };
4301 static const WCHAR jul
[] = { 'j','u','l',0 };
4302 static const WCHAR aug
[] = { 'a','u','g',0 };
4303 static const WCHAR sep
[] = { 's','e','p',0 };
4304 static const WCHAR oct
[] = { 'o','c','t',0 };
4305 static const WCHAR nov
[] = { 'n','o','v',0 };
4306 static const WCHAR dec
[] = { 'd','e','c',0 };
4308 if (!strcmpiW(month
, jan
)) return 1;
4309 if (!strcmpiW(month
, feb
)) return 2;
4310 if (!strcmpiW(month
, mar
)) return 3;
4311 if (!strcmpiW(month
, apr
)) return 4;
4312 if (!strcmpiW(month
, may
)) return 5;
4313 if (!strcmpiW(month
, jun
)) return 6;
4314 if (!strcmpiW(month
, jul
)) return 7;
4315 if (!strcmpiW(month
, aug
)) return 8;
4316 if (!strcmpiW(month
, sep
)) return 9;
4317 if (!strcmpiW(month
, oct
)) return 10;
4318 if (!strcmpiW(month
, nov
)) return 11;
4319 if (!strcmpiW(month
, dec
)) return 12;
4324 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4325 * optionally preceded by whitespace.
4326 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4327 * st, and sets *str to the first character after the time format.
4329 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4335 while (isspaceW(*ptr
))
4338 num
= strtoulW(ptr
, &nextPtr
, 10);
4339 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4341 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4346 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4350 st
->wHour
= (WORD
)num
;
4351 num
= strtoulW(ptr
, &nextPtr
, 10);
4352 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4354 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4359 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4363 st
->wMinute
= (WORD
)num
;
4364 num
= strtoulW(ptr
, &nextPtr
, 10);
4365 if (!nextPtr
|| nextPtr
<= ptr
)
4367 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4372 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4377 st
->wSecond
= (WORD
)num
;
4381 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4383 static const WCHAR gmt
[]= { 'G','M','T',0 };
4384 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4386 SYSTEMTIME st
= { 0 };
4389 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4390 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4393 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4394 if (st
.wDayOfWeek
>= 7)
4396 ERR("unexpected weekday %s\n", debugstr_w(day
));
4400 while (isspaceW(*ptr
))
4403 for (monthPtr
= month
; !isspace(*ptr
) &&
4404 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4408 st
.wMonth
= HTTP_ParseMonth(month
);
4409 if (!st
.wMonth
|| st
.wMonth
> 12)
4411 ERR("unexpected month %s\n", debugstr_w(month
));
4415 while (isspaceW(*ptr
))
4418 num
= strtoulW(ptr
, &nextPtr
, 10);
4419 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4421 ERR("unexpected day %s\n", debugstr_w(ptr
));
4425 st
.wDay
= (WORD
)num
;
4427 while (isspaceW(*ptr
))
4430 if (!HTTP_ParseTime(&st
, &ptr
))
4433 while (isspaceW(*ptr
))
4436 num
= strtoulW(ptr
, &nextPtr
, 10);
4437 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4439 ERR("unexpected year %s\n", debugstr_w(ptr
));
4443 st
.wYear
= (WORD
)num
;
4445 while (isspaceW(*ptr
))
4448 /* asctime() doesn't report a timezone, but some web servers do, so accept
4449 * with or without GMT.
4451 if (*ptr
&& strcmpW(ptr
, gmt
))
4453 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4456 return SystemTimeToFileTime(&st
, ft
);
4459 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4461 static const WCHAR gmt
[]= { 'G','M','T',0 };
4462 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4465 SYSTEMTIME st
= { 0 };
4467 ptr
= strchrW(value
, ',');
4470 if (ptr
- value
!= 3)
4472 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4475 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4477 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4478 if (st
.wDayOfWeek
> 6)
4480 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4485 while (isspaceW(*ptr
))
4488 num
= strtoulW(ptr
, &nextPtr
, 10);
4489 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4491 WARN("unexpected day %s\n", debugstr_w(value
));
4495 st
.wDay
= (WORD
)num
;
4497 while (isspaceW(*ptr
))
4500 for (monthPtr
= month
; !isspace(*ptr
) &&
4501 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4505 st
.wMonth
= HTTP_ParseMonth(month
);
4506 if (!st
.wMonth
|| st
.wMonth
> 12)
4508 WARN("unexpected month %s\n", debugstr_w(month
));
4512 while (isspaceW(*ptr
))
4515 num
= strtoulW(ptr
, &nextPtr
, 10);
4516 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4518 ERR("unexpected year %s\n", debugstr_w(value
));
4522 st
.wYear
= (WORD
)num
;
4524 if (!HTTP_ParseTime(&st
, &ptr
))
4527 while (isspaceW(*ptr
))
4530 if (strcmpW(ptr
, gmt
))
4532 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4535 return SystemTimeToFileTime(&st
, ft
);
4538 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4540 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4541 { 'm','o','n','d','a','y',0 },
4542 { 't','u','e','s','d','a','y',0 },
4543 { 'w','e','d','n','e','s','d','a','y',0 },
4544 { 't','h','u','r','s','d','a','y',0 },
4545 { 'f','r','i','d','a','y',0 },
4546 { 's','a','t','u','r','d','a','y',0 }};
4548 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4549 if (!strcmpiW(day
, days
[i
]))
4556 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4558 static const WCHAR gmt
[]= { 'G','M','T',0 };
4559 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4562 SYSTEMTIME st
= { 0 };
4564 ptr
= strchrW(value
, ',');
4567 if (ptr
- value
== 3)
4569 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4571 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4572 if (st
.wDayOfWeek
> 6)
4574 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4578 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4580 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4581 day
[ptr
- value
+ 1] = 0;
4582 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4583 if (st
.wDayOfWeek
> 6)
4585 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4591 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4596 while (isspaceW(*ptr
))
4599 num
= strtoulW(ptr
, &nextPtr
, 10);
4600 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4602 ERR("unexpected day %s\n", debugstr_w(value
));
4606 st
.wDay
= (WORD
)num
;
4610 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4615 for (monthPtr
= month
; *ptr
!= '-' &&
4616 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4620 st
.wMonth
= HTTP_ParseMonth(month
);
4621 if (!st
.wMonth
|| st
.wMonth
> 12)
4623 ERR("unexpected month %s\n", debugstr_w(month
));
4629 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4634 num
= strtoulW(ptr
, &nextPtr
, 10);
4635 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4637 ERR("unexpected year %s\n", debugstr_w(value
));
4641 st
.wYear
= (WORD
)num
;
4643 if (!HTTP_ParseTime(&st
, &ptr
))
4646 while (isspaceW(*ptr
))
4649 if (strcmpW(ptr
, gmt
))
4651 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4654 return SystemTimeToFileTime(&st
, ft
);
4657 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4659 static const WCHAR zero
[] = { '0',0 };
4662 if (!strcmpW(value
, zero
))
4664 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4667 else if (strchrW(value
, ','))
4669 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4672 ret
= HTTP_ParseRfc850Date(value
, ft
);
4674 ERR("unexpected date format %s\n", debugstr_w(value
));
4679 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4681 ERR("unexpected date format %s\n", debugstr_w(value
));
4686 static void HTTP_ProcessExpires(http_request_t
*request
)
4688 BOOL expirationFound
= FALSE
;
4691 EnterCriticalSection( &request
->headers_section
);
4693 /* Look for a Cache-Control header with a max-age directive, as it takes
4694 * precedence over the Expires header.
4696 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4697 if (headerIndex
!= -1)
4699 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4702 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4704 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4709 end
= ptr
+ strlenW(ptr
);
4710 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4714 static const WCHAR max_age
[] = {
4715 'm','a','x','-','a','g','e',0 };
4717 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4722 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4723 if (nextPtr
> equal
+ 1)
4727 NtQuerySystemTime( &ft
);
4728 /* Age is in seconds, FILETIME resolution is in
4729 * 100 nanosecond intervals.
4731 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4732 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4733 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4734 expirationFound
= TRUE
;
4741 while (isspaceW(*ptr
))
4748 if (!expirationFound
)
4750 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4751 if (headerIndex
!= -1)
4753 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4756 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4758 expirationFound
= TRUE
;
4759 request
->expires
= ft
;
4763 if (!expirationFound
)
4767 /* With no known age, default to 10 minutes until expiration. */
4768 NtQuerySystemTime( &t
);
4769 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4770 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4771 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4774 LeaveCriticalSection( &request
->headers_section
);
4777 static void HTTP_ProcessLastModified(http_request_t
*request
)
4781 EnterCriticalSection( &request
->headers_section
);
4783 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4784 if (headerIndex
!= -1)
4786 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4789 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4790 request
->last_modified
= ft
;
4793 LeaveCriticalSection( &request
->headers_section
);
4796 static void http_process_keep_alive(http_request_t
*req
)
4800 EnterCriticalSection( &req
->headers_section
);
4802 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4803 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4804 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4805 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4807 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4809 LeaveCriticalSection( &req
->headers_section
);
4812 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4814 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4815 netconn_t
*netconn
= NULL
;
4818 reset_data_stream(request
);
4820 if (request
->netconn
)
4822 if (is_valid_netconn(request
->netconn
) && NETCON_is_alive(request
->netconn
))
4825 return ERROR_SUCCESS
;
4829 free_netconn(request
->netconn
);
4830 request
->netconn
= NULL
;
4834 res
= HTTP_ResolveName(request
);
4835 if(res
!= ERROR_SUCCESS
)
4838 EnterCriticalSection(&connection_pool_cs
);
4840 while(!list_empty(&request
->server
->conn_pool
)) {
4841 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4842 list_remove(&netconn
->pool_entry
);
4844 if(is_valid_netconn(netconn
) && NETCON_is_alive(netconn
))
4847 TRACE("connection %p closed during idle\n", netconn
);
4848 free_netconn(netconn
);
4852 LeaveCriticalSection(&connection_pool_cs
);
4855 TRACE("<-- reusing %p netconn\n", netconn
);
4856 request
->netconn
= netconn
;
4858 return ERROR_SUCCESS
;
4861 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4862 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4864 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4865 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4866 request
->server
->addr_str
,
4867 strlen(request
->server
->addr_str
)+1);
4869 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4870 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4871 request
->connect_timeout
, &netconn
);
4872 if(res
!= ERROR_SUCCESS
) {
4873 ERR("create_netconn failed: %u\n", res
);
4877 request
->netconn
= netconn
;
4879 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4880 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4881 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4884 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4885 return ERROR_SUCCESS
;
4888 static char *build_ascii_request( const WCHAR
*str
, void *data
, DWORD data_len
, DWORD
*out_len
)
4890 int len
= WideCharToMultiByte( CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
4893 if (!(ret
= heap_alloc( len
+ data_len
))) return NULL
;
4894 WideCharToMultiByte( CP_ACP
, 0, str
, -1, ret
, len
, NULL
, NULL
);
4895 if (data_len
) memcpy( ret
+ len
- 1, data
, data_len
);
4896 *out_len
= len
+ data_len
- 1;
4901 /***********************************************************************
4902 * HTTP_HttpSendRequestW (internal)
4904 * Sends the specified request to the HTTP server
4907 * ERROR_SUCCESS on success
4908 * win32 error code on failure
4911 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4912 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4913 DWORD dwContentLength
, BOOL bEndRequest
)
4915 static const WCHAR szContentLength
[] =
4916 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4917 BOOL redirected
= FALSE
, secure_proxy_connect
= FALSE
, loop_next
;
4918 LPWSTR requestString
= NULL
;
4919 INT responseLen
, cnt
;
4920 WCHAR contentLengthStr
[sizeof szContentLength
/2 /* includes \r\n */ + 20 /* int */ ];
4923 TRACE("--> %p\n", request
);
4925 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4927 /* if the verb is NULL default to GET */
4929 request
->verb
= heap_strdupW(szGET
);
4931 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4933 sprintfW(contentLengthStr
, szContentLength
, dwContentLength
);
4934 HTTP_HttpAddRequestHeadersW(request
, contentLengthStr
, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4935 request
->bytesToWrite
= dwContentLength
;
4937 if (request
->session
->appInfo
->agent
)
4939 WCHAR
*agent_header
;
4940 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4943 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4944 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4945 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4947 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4948 heap_free(agent_header
);
4950 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4952 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4953 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4955 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4957 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4958 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4959 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4962 /* add the headers the caller supplied */
4963 if( lpszHeaders
&& dwHeaderLength
)
4964 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4968 DWORD len
, data_len
= dwOptionalLength
;
4969 BOOL reusing_connection
;
4975 request
->contentLength
= ~0u;
4976 request
->bytesToWrite
= 0;
4979 if (TRACE_ON(wininet
))
4983 EnterCriticalSection( &request
->headers_section
);
4984 host
= HTTP_GetHeader( request
, hostW
);
4985 TRACE("Going to url %s %s\n", debugstr_w(host
->lpszValue
), debugstr_w(request
->path
));
4986 LeaveCriticalSection( &request
->headers_section
);
4989 HTTP_FixURL(request
);
4990 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4992 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
, HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
);
4994 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4995 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4997 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4998 HTTP_InsertCookies(request
);
5000 res
= open_http_connection(request
, &reusing_connection
);
5001 if (res
!= ERROR_SUCCESS
)
5004 if (!reusing_connection
&& (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
5006 if (request
->proxy
) secure_proxy_connect
= TRUE
;
5009 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5010 if (res
!= ERROR_SUCCESS
)
5012 WARN("failed to upgrade to secure connection\n");
5013 http_release_netconn(request
, FALSE
);
5018 if (secure_proxy_connect
)
5020 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
5021 const WCHAR
*target
= request
->server
->host_port
;
5022 requestString
= build_request_header(request
, connectW
, target
, g_szHttp1_1
, TRUE
);
5024 else if (request
->proxy
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
5026 WCHAR
*url
= build_proxy_path_url(request
);
5027 requestString
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
5031 requestString
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
5033 TRACE("Request header -> %s\n", debugstr_w(requestString
) );
5035 /* send the request as ASCII, tack on the optional data */
5036 if (!lpOptional
|| redirected
|| secure_proxy_connect
)
5039 ascii_req
= build_ascii_request( requestString
, lpOptional
, data_len
, &len
);
5040 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
5042 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5043 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
5045 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
5046 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
5047 heap_free( ascii_req
);
5048 if(res
!= ERROR_SUCCESS
) {
5049 TRACE("send failed: %u\n", res
);
5050 if(!reusing_connection
)
5052 http_release_netconn(request
, FALSE
);
5057 request
->bytesWritten
= data_len
;
5059 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5060 INTERNET_STATUS_REQUEST_SENT
,
5061 &len
, sizeof(DWORD
));
5067 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5068 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5070 if (HTTP_GetResponseHeaders(request
, &responseLen
))
5072 http_release_netconn(request
, FALSE
);
5073 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
5076 /* FIXME: We should know that connection is closed before sending
5077 * headers. Otherwise wrong callbacks are executed */
5078 if(!responseLen
&& reusing_connection
) {
5079 TRACE("Connection closed by server, reconnecting\n");
5080 http_release_netconn(request
, FALSE
);
5085 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5086 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
5089 http_process_keep_alive(request
);
5090 HTTP_ProcessCookies(request
);
5091 HTTP_ProcessExpires(request
);
5092 HTTP_ProcessLastModified(request
);
5094 res
= set_content_length(request
);
5095 if(res
!= ERROR_SUCCESS
)
5097 if(!request
->contentLength
)
5098 http_release_netconn(request
, TRUE
);
5100 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5102 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5103 dwBufferSize
=sizeof(szNewLocation
);
5104 switch(request
->status_code
) {
5105 case HTTP_STATUS_REDIRECT
:
5106 case HTTP_STATUS_MOVED
:
5107 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5108 case HTTP_STATUS_REDIRECT_METHOD
:
5109 if(HTTP_HttpQueryInfoW(request
,HTTP_QUERY_LOCATION
,szNewLocation
,&dwBufferSize
,NULL
) != ERROR_SUCCESS
)
5112 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5113 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5115 heap_free(request
->verb
);
5116 request
->verb
= heap_strdupW(szGET
);
5118 http_release_netconn(request
, drain_content(request
, FALSE
));
5119 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5121 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5122 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5123 res
= HTTP_HandleRedirect(request
, new_url
);
5124 if (res
== ERROR_SUCCESS
)
5126 heap_free(requestString
);
5129 heap_free( new_url
);
5134 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5136 WCHAR szAuthValue
[2048];
5138 if (request
->status_code
== HTTP_STATUS_DENIED
)
5140 WCHAR
*host
= get_host_header( request
);
5142 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5144 if (HTTP_DoAuthorization(request
, szAuthValue
,
5146 request
->session
->userName
,
5147 request
->session
->password
, host
))
5149 heap_free(requestString
);
5150 if(!drain_content(request
, TRUE
)) {
5151 FIXME("Could not drain content\n");
5152 http_release_netconn(request
, FALSE
);
5161 TRACE("Cleaning wrong authorization data\n");
5162 destroy_authinfo(request
->authInfo
);
5163 request
->authInfo
= NULL
;
5166 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5169 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5171 if (HTTP_DoAuthorization(request
, szAuthValue
,
5172 &request
->proxyAuthInfo
,
5173 request
->session
->appInfo
->proxyUsername
,
5174 request
->session
->appInfo
->proxyPassword
,
5177 heap_free(requestString
);
5178 if(!drain_content(request
, TRUE
)) {
5179 FIXME("Could not drain content\n");
5180 http_release_netconn(request
, FALSE
);
5188 TRACE("Cleaning wrong proxy authorization data\n");
5189 destroy_authinfo(request
->proxyAuthInfo
);
5190 request
->proxyAuthInfo
= NULL
;
5194 if (secure_proxy_connect
&& request
->status_code
== HTTP_STATUS_OK
)
5198 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5199 if (res
!= ERROR_SUCCESS
)
5201 WARN("failed to upgrade to secure proxy connection\n");
5202 http_release_netconn( request
, FALSE
);
5205 EnterCriticalSection( &request
->headers_section
);
5206 index
= HTTP_GetCustomHeaderIndex(request
, szProxy_Authorization
, 0, TRUE
);
5207 if (index
!= -1) HTTP_DeleteCustomHeader(request
, index
);
5208 LeaveCriticalSection( &request
->headers_section
);
5210 destroy_authinfo(request
->proxyAuthInfo
);
5211 request
->proxyAuthInfo
= NULL
;
5213 secure_proxy_connect
= FALSE
;
5218 res
= ERROR_SUCCESS
;
5223 heap_free(requestString
);
5225 /* TODO: send notification for P3P header */
5227 if(res
== ERROR_SUCCESS
)
5228 create_cache_entry(request
);
5230 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5232 if (res
== ERROR_SUCCESS
) {
5233 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5234 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5236 send_request_complete(request
,
5237 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5239 send_request_complete(request
, 0, res
);
5255 } send_request_task_t
;
5257 /***********************************************************************
5259 * Helper functions for the HttpSendRequest(Ex) functions
5262 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5264 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5265 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5267 TRACE("%p\n", request
);
5269 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5270 task
->optional_len
, task
->content_len
, task
->end_request
);
5272 heap_free(task
->headers
);
5276 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5280 DWORD res
= ERROR_SUCCESS
;
5282 if(!is_valid_netconn(request
->netconn
)) {
5283 WARN("Not connected\n");
5284 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5285 return ERROR_INTERNET_OPERATION_CANCELLED
;
5288 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5289 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5291 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5292 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5294 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5295 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5297 /* process cookies here. Is this right? */
5298 http_process_keep_alive(request
);
5299 HTTP_ProcessCookies(request
);
5300 HTTP_ProcessExpires(request
);
5301 HTTP_ProcessLastModified(request
);
5303 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5304 if(!request
->contentLength
)
5305 http_release_netconn(request
, TRUE
);
5308 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5310 switch(request
->status_code
) {
5311 case HTTP_STATUS_REDIRECT
:
5312 case HTTP_STATUS_MOVED
:
5313 case HTTP_STATUS_REDIRECT_METHOD
:
5314 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5315 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5316 dwBufferSize
=sizeof(szNewLocation
);
5317 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, szNewLocation
, &dwBufferSize
, NULL
) != ERROR_SUCCESS
)
5320 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5321 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5323 heap_free(request
->verb
);
5324 request
->verb
= heap_strdupW(szGET
);
5326 http_release_netconn(request
, drain_content(request
, FALSE
));
5327 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5329 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5330 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5331 res
= HTTP_HandleRedirect(request
, new_url
);
5332 if (res
== ERROR_SUCCESS
)
5333 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5334 heap_free( new_url
);
5340 if(res
== ERROR_SUCCESS
)
5341 create_cache_entry(request
);
5343 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5344 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5346 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5351 /***********************************************************************
5352 * HttpEndRequestA (WININET.@)
5354 * Ends an HTTP request that was started by HttpSendRequestEx
5357 * TRUE if successful
5361 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5362 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5364 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5368 SetLastError(ERROR_INVALID_PARAMETER
);
5372 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5379 } end_request_task_t
;
5381 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5383 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5384 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5388 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5391 /***********************************************************************
5392 * HttpEndRequestW (WININET.@)
5394 * Ends an HTTP request that was started by HttpSendRequestEx
5397 * TRUE if successful
5401 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5402 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5404 http_request_t
*request
;
5407 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5411 SetLastError(ERROR_INVALID_PARAMETER
);
5415 request
= (http_request_t
*) get_handle_object( hRequest
);
5417 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5419 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5421 WININET_Release( &request
->hdr
);
5424 request
->hdr
.dwFlags
|= dwFlags
;
5426 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5428 end_request_task_t
*task
;
5430 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5431 task
->flags
= dwFlags
;
5432 task
->context
= dwContext
;
5434 INTERNET_AsyncCall(&task
->hdr
);
5435 res
= ERROR_IO_PENDING
;
5438 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5440 WININET_Release( &request
->hdr
);
5441 TRACE("%u <--\n", res
);
5442 if(res
!= ERROR_SUCCESS
)
5444 return res
== ERROR_SUCCESS
;
5447 /***********************************************************************
5448 * HttpSendRequestExA (WININET.@)
5450 * Sends the specified request to the HTTP server and allows chunked
5455 * Failure: FALSE, call GetLastError() for more information.
5457 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5458 LPINTERNET_BUFFERSA lpBuffersIn
,
5459 LPINTERNET_BUFFERSA lpBuffersOut
,
5460 DWORD dwFlags
, DWORD_PTR dwContext
)
5462 INTERNET_BUFFERSW BuffersInW
;
5465 LPWSTR header
= NULL
;
5467 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5468 lpBuffersOut
, dwFlags
, dwContext
);
5472 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5473 if (lpBuffersIn
->lpcszHeader
)
5475 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5476 lpBuffersIn
->dwHeadersLength
,0,0);
5477 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5478 if (!(BuffersInW
.lpcszHeader
= header
))
5480 SetLastError(ERROR_OUTOFMEMORY
);
5483 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5484 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5488 BuffersInW
.lpcszHeader
= NULL
;
5489 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5490 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5491 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5492 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5493 BuffersInW
.Next
= NULL
;
5496 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5502 /***********************************************************************
5503 * HttpSendRequestExW (WININET.@)
5505 * Sends the specified request to the HTTP server and allows chunked
5510 * Failure: FALSE, call GetLastError() for more information.
5512 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5513 LPINTERNET_BUFFERSW lpBuffersIn
,
5514 LPINTERNET_BUFFERSW lpBuffersOut
,
5515 DWORD dwFlags
, DWORD_PTR dwContext
)
5517 http_request_t
*request
;
5518 http_session_t
*session
;
5522 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5523 lpBuffersOut
, dwFlags
, dwContext
);
5525 request
= (http_request_t
*) get_handle_object( hRequest
);
5527 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5529 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5533 session
= request
->session
;
5534 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5535 hIC
= session
->appInfo
;
5536 assert(hIC
->hdr
.htype
== WH_HINIT
);
5538 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5540 send_request_task_t
*task
;
5542 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5547 if (lpBuffersIn
->lpcszHeader
)
5549 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5550 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5552 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5554 task
->headers
= heap_alloc(size
);
5555 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5557 else task
->headers
= NULL
;
5559 task
->headers_len
= size
/ sizeof(WCHAR
);
5560 task
->optional
= lpBuffersIn
->lpvBuffer
;
5561 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5562 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5566 task
->headers
= NULL
;
5567 task
->headers_len
= 0;
5568 task
->optional
= NULL
;
5569 task
->optional_len
= 0;
5570 task
->content_len
= 0;
5573 task
->end_request
= FALSE
;
5575 INTERNET_AsyncCall(&task
->hdr
);
5576 res
= ERROR_IO_PENDING
;
5581 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5582 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5583 lpBuffersIn
->dwBufferTotal
, FALSE
);
5585 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5590 WININET_Release( &request
->hdr
);
5594 return res
== ERROR_SUCCESS
;
5597 /***********************************************************************
5598 * HttpSendRequestW (WININET.@)
5600 * Sends the specified request to the HTTP server
5607 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5608 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5610 http_request_t
*request
;
5611 http_session_t
*session
= NULL
;
5612 appinfo_t
*hIC
= NULL
;
5613 DWORD res
= ERROR_SUCCESS
;
5615 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5616 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5618 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5619 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5621 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5625 session
= request
->session
;
5626 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5628 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5632 hIC
= session
->appInfo
;
5633 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5635 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5639 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5641 send_request_task_t
*task
;
5643 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5648 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5649 else size
= dwHeaderLength
* sizeof(WCHAR
);
5651 task
->headers
= heap_alloc(size
);
5652 memcpy(task
->headers
, lpszHeaders
, size
);
5655 task
->headers
= NULL
;
5656 task
->headers_len
= dwHeaderLength
;
5657 task
->optional
= lpOptional
;
5658 task
->optional_len
= dwOptionalLength
;
5659 task
->content_len
= dwOptionalLength
;
5660 task
->end_request
= TRUE
;
5662 INTERNET_AsyncCall(&task
->hdr
);
5663 res
= ERROR_IO_PENDING
;
5667 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5668 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5669 dwOptionalLength
, TRUE
);
5673 WININET_Release( &request
->hdr
);
5676 return res
== ERROR_SUCCESS
;
5679 /***********************************************************************
5680 * HttpSendRequestA (WININET.@)
5682 * Sends the specified request to the HTTP server
5689 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5690 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5693 LPWSTR szHeaders
=NULL
;
5694 DWORD nLen
=dwHeaderLength
;
5695 if(lpszHeaders
!=NULL
)
5697 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5698 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5699 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5701 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5702 heap_free(szHeaders
);
5706 /***********************************************************************
5707 * HTTPSESSION_Destroy (internal)
5709 * Deallocate session handle
5712 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5714 http_session_t
*session
= (http_session_t
*) hdr
;
5716 TRACE("%p\n", session
);
5718 WININET_Release(&session
->appInfo
->hdr
);
5720 heap_free(session
->hostName
);
5721 heap_free(session
->password
);
5722 heap_free(session
->userName
);
5725 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5727 http_session_t
*ses
= (http_session_t
*)hdr
;
5730 case INTERNET_OPTION_HANDLE_TYPE
:
5731 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5733 if (*size
< sizeof(ULONG
))
5734 return ERROR_INSUFFICIENT_BUFFER
;
5736 *size
= sizeof(DWORD
);
5737 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5738 return ERROR_SUCCESS
;
5739 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5740 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5742 if (*size
< sizeof(DWORD
))
5743 return ERROR_INSUFFICIENT_BUFFER
;
5745 *size
= sizeof(DWORD
);
5746 *(DWORD
*)buffer
= ses
->connect_timeout
;
5747 return ERROR_SUCCESS
;
5749 case INTERNET_OPTION_SEND_TIMEOUT
:
5750 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5752 if (*size
< sizeof(DWORD
))
5753 return ERROR_INSUFFICIENT_BUFFER
;
5755 *size
= sizeof(DWORD
);
5756 *(DWORD
*)buffer
= ses
->send_timeout
;
5757 return ERROR_SUCCESS
;
5759 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5760 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5762 if (*size
< sizeof(DWORD
))
5763 return ERROR_INSUFFICIENT_BUFFER
;
5765 *size
= sizeof(DWORD
);
5766 *(DWORD
*)buffer
= ses
->receive_timeout
;
5767 return ERROR_SUCCESS
;
5770 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5773 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5775 http_session_t
*ses
= (http_session_t
*)hdr
;
5778 case INTERNET_OPTION_USERNAME
:
5780 heap_free(ses
->userName
);
5781 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5782 return ERROR_SUCCESS
;
5784 case INTERNET_OPTION_PASSWORD
:
5786 heap_free(ses
->password
);
5787 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5788 return ERROR_SUCCESS
;
5790 case INTERNET_OPTION_PROXY_USERNAME
:
5792 heap_free(ses
->appInfo
->proxyUsername
);
5793 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5794 return ERROR_SUCCESS
;
5796 case INTERNET_OPTION_PROXY_PASSWORD
:
5798 heap_free(ses
->appInfo
->proxyPassword
);
5799 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5800 return ERROR_SUCCESS
;
5802 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5804 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5805 ses
->connect_timeout
= *(DWORD
*)buffer
;
5806 return ERROR_SUCCESS
;
5808 case INTERNET_OPTION_SEND_TIMEOUT
:
5810 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5811 ses
->send_timeout
= *(DWORD
*)buffer
;
5812 return ERROR_SUCCESS
;
5814 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5816 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5817 ses
->receive_timeout
= *(DWORD
*)buffer
;
5818 return ERROR_SUCCESS
;
5823 return INET_SetOption(hdr
, option
, buffer
, size
);
5826 static const object_vtbl_t HTTPSESSIONVtbl
= {
5827 HTTPSESSION_Destroy
,
5829 HTTPSESSION_QueryOption
,
5830 HTTPSESSION_SetOption
,
5839 /***********************************************************************
5840 * HTTP_Connect (internal)
5842 * Create http session handle
5845 * HINTERNET a session handle on success
5849 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5850 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5851 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5852 DWORD dwInternalFlags
, HINTERNET
*ret
)
5854 http_session_t
*session
= NULL
;
5858 if (!lpszServerName
|| !lpszServerName
[0])
5859 return ERROR_INVALID_PARAMETER
;
5861 assert( hIC
->hdr
.htype
== WH_HINIT
);
5863 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5865 return ERROR_OUTOFMEMORY
;
5868 * According to my tests. The name is not resolved until a request is sent
5871 session
->hdr
.htype
= WH_HHTTPSESSION
;
5872 session
->hdr
.dwFlags
= dwFlags
;
5873 session
->hdr
.dwContext
= dwContext
;
5874 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5876 WININET_AddRef( &hIC
->hdr
);
5877 session
->appInfo
= hIC
;
5878 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5880 session
->hostName
= heap_strdupW(lpszServerName
);
5881 if (lpszUserName
&& lpszUserName
[0])
5882 session
->userName
= heap_strdupW(lpszUserName
);
5883 if (lpszPassword
&& lpszPassword
[0])
5884 session
->password
= heap_strdupW(lpszPassword
);
5885 session
->hostPort
= serverPort
;
5886 session
->connect_timeout
= hIC
->connect_timeout
;
5887 session
->send_timeout
= INFINITE
;
5888 session
->receive_timeout
= INFINITE
;
5890 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5891 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5893 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5894 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5899 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5903 TRACE("%p --> %p\n", hIC
, session
);
5905 *ret
= session
->hdr
.hInternet
;
5906 return ERROR_SUCCESS
;
5909 /***********************************************************************
5910 * HTTP_clear_response_headers (internal)
5912 * clear out any old response headers
5914 static void HTTP_clear_response_headers( http_request_t
*request
)
5918 EnterCriticalSection( &request
->headers_section
);
5920 for( i
=0; i
<request
->nCustHeaders
; i
++)
5922 if( !request
->custHeaders
[i
].lpszField
)
5924 if( !request
->custHeaders
[i
].lpszValue
)
5926 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5928 HTTP_DeleteCustomHeader( request
, i
);
5932 LeaveCriticalSection( &request
->headers_section
);
5935 /***********************************************************************
5936 * HTTP_GetResponseHeaders (internal)
5938 * Read server response
5945 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5948 WCHAR buffer
[MAX_REPLY_LEN
];
5949 DWORD buflen
= MAX_REPLY_LEN
;
5951 char bufferA
[MAX_REPLY_LEN
];
5952 LPWSTR status_code
= NULL
, status_text
= NULL
;
5953 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5954 BOOL codeHundred
= FALSE
;
5958 if(!is_valid_netconn(request
->netconn
))
5961 /* clear old response headers (eg. from a redirect response) */
5962 HTTP_clear_response_headers( request
);
5964 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5967 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5969 buflen
= MAX_REPLY_LEN
;
5970 if ((res
= read_line(request
, bufferA
, &buflen
)))
5973 if (!buflen
) goto lend
;
5976 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5977 /* check is this a status code line? */
5978 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5980 /* split the version from the status code */
5981 status_code
= strchrW( buffer
, ' ' );
5986 /* split the status code from the status text */
5987 status_text
= strchrW( status_code
, ' ' );
5991 request
->status_code
= atoiW(status_code
);
5993 TRACE("version [%s] status code [%s] status text [%s]\n",
5994 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5996 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5998 else if (!codeHundred
)
6000 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
6002 heap_free(request
->version
);
6003 heap_free(request
->statusText
);
6005 request
->status_code
= HTTP_STATUS_OK
;
6006 request
->version
= heap_strdupW(g_szHttp1_0
);
6007 request
->statusText
= heap_strdupW(szOK
);
6011 } while (codeHundred
);
6013 /* Add status code */
6014 HTTP_ProcessHeader(request
, szStatus
, status_code
,
6015 HTTP_ADDHDR_FLAG_REPLACE
);
6017 heap_free(request
->version
);
6018 heap_free(request
->statusText
);
6020 request
->version
= heap_strdupW(buffer
);
6021 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
6023 /* Restore the spaces */
6024 *(status_code
-1) = ' ';
6026 *(status_text
-1) = ' ';
6028 /* Parse each response line */
6031 buflen
= MAX_REPLY_LEN
;
6032 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
6034 LPWSTR
* pFieldAndValue
;
6036 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
6038 if (!bufferA
[0]) break;
6039 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
6041 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
6044 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
6045 HTTP_ADDREQ_FLAG_ADD
);
6046 HTTP_FreeTokens(pFieldAndValue
);
6057 res
= ERROR_SUCCESS
;
6066 /***********************************************************************
6067 * HTTP_InterpretHttpHeader (internal)
6069 * Parse server response
6073 * Pointer to array of field, value, NULL on success.
6076 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
6078 LPWSTR
* pTokenPair
;
6082 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
6084 pszColon
= strchrW(buffer
, ':');
6085 /* must have two tokens */
6088 HTTP_FreeTokens(pTokenPair
);
6090 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
6094 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
6097 HTTP_FreeTokens(pTokenPair
);
6100 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
6101 pTokenPair
[0][pszColon
- buffer
] = '\0';
6105 len
= strlenW(pszColon
);
6106 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
6109 HTTP_FreeTokens(pTokenPair
);
6112 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
6114 strip_spaces(pTokenPair
[0]);
6115 strip_spaces(pTokenPair
[1]);
6117 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
6121 /***********************************************************************
6122 * HTTP_ProcessHeader (internal)
6124 * Stuff header into header tables according to <dwModifier>
6128 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6130 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6132 LPHTTPHEADERW lphttpHdr
= NULL
;
6134 BOOL request_only
= dwModifier
& HTTP_ADDHDR_FLAG_REQ
;
6135 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6137 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6139 EnterCriticalSection( &request
->headers_section
);
6141 /* REPLACE wins out over ADD */
6142 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6143 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6145 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6148 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6152 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6154 LeaveCriticalSection( &request
->headers_section
);
6155 return ERROR_HTTP_INVALID_HEADER
;
6157 lphttpHdr
= &request
->custHeaders
[index
];
6163 hdr
.lpszField
= (LPWSTR
)field
;
6164 hdr
.lpszValue
= (LPWSTR
)value
;
6165 hdr
.wFlags
= hdr
.wCount
= 0;
6167 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6168 hdr
.wFlags
|= HDR_ISREQUEST
;
6170 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6171 LeaveCriticalSection( &request
->headers_section
);
6174 /* no value to delete */
6177 LeaveCriticalSection( &request
->headers_section
);
6178 return ERROR_SUCCESS
;
6181 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6182 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6184 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6186 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6188 HTTP_DeleteCustomHeader( request
, index
);
6190 if (value
&& value
[0])
6194 hdr
.lpszField
= (LPWSTR
)field
;
6195 hdr
.lpszValue
= (LPWSTR
)value
;
6196 hdr
.wFlags
= hdr
.wCount
= 0;
6198 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6199 hdr
.wFlags
|= HDR_ISREQUEST
;
6201 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6202 LeaveCriticalSection( &request
->headers_section
);
6206 LeaveCriticalSection( &request
->headers_section
);
6207 return ERROR_SUCCESS
;
6209 else if (dwModifier
& COALESCEFLAGS
)
6214 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6215 INT valuelen
= strlenW(value
);
6217 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6220 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6222 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6225 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6228 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6230 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6233 lphttpHdr
->lpszValue
= lpsztmp
;
6234 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6237 lphttpHdr
->lpszValue
[origlen
] = ch
;
6239 lphttpHdr
->lpszValue
[origlen
] = ' ';
6243 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6244 lphttpHdr
->lpszValue
[len
] = '\0';
6245 res
= ERROR_SUCCESS
;
6249 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6250 res
= ERROR_OUTOFMEMORY
;
6253 TRACE("<-- %d\n", res
);
6254 LeaveCriticalSection( &request
->headers_section
);
6258 /***********************************************************************
6259 * HTTP_GetCustomHeaderIndex (internal)
6261 * Return index of custom header from header array
6262 * Headers section must be held
6264 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6265 int requested_index
, BOOL request_only
)
6269 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6271 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6273 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6276 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6279 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6282 if (requested_index
== 0)
6287 if (index
>= request
->nCustHeaders
)
6290 TRACE("Return: %d\n", index
);
6295 /***********************************************************************
6296 * HTTP_InsertCustomHeader (internal)
6298 * Insert header into array
6299 * Headers section must be held
6301 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6304 LPHTTPHEADERW lph
= NULL
;
6306 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6307 count
= request
->nCustHeaders
+ 1;
6309 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6311 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6314 return ERROR_OUTOFMEMORY
;
6316 request
->custHeaders
= lph
;
6317 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6318 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6319 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6320 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6321 request
->nCustHeaders
++;
6323 return ERROR_SUCCESS
;
6327 /***********************************************************************
6328 * HTTP_DeleteCustomHeader (internal)
6330 * Delete header from array
6331 * If this function is called, the index may change.
6332 * Headers section must be held
6334 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6336 if( request
->nCustHeaders
<= 0 )
6338 if( index
>= request
->nCustHeaders
)
6340 request
->nCustHeaders
--;
6342 heap_free(request
->custHeaders
[index
].lpszField
);
6343 heap_free(request
->custHeaders
[index
].lpszValue
);
6345 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6346 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6347 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6353 /***********************************************************************
6354 * HTTP_VerifyValidHeader (internal)
6356 * Verify the given header is not invalid for the given http request
6359 static BOOL
HTTP_VerifyValidHeader(http_request_t
*request
, LPCWSTR field
)
6361 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6362 if (!strcmpW(request
->version
, g_szHttp1_0
) && !strcmpiW(field
, szAccept_Encoding
))
6363 return ERROR_HTTP_INVALID_HEADER
;
6365 return ERROR_SUCCESS
;
6368 /***********************************************************************
6369 * IsHostInProxyBypassList (@)
6374 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6376 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);