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
51 #define NO_SHLWAPI_STREAM
52 #define NO_SHLWAPI_REG
53 #define NO_SHLWAPI_STRFCNS
54 #define NO_SHLWAPI_GDI
61 #include "wine/debug.h"
62 #include "wine/exception.h"
63 #include "wine/unicode.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
67 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
68 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
69 static const WCHAR szOK
[] = {'O','K',0};
70 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
75 static const WCHAR szGET
[] = { 'G','E','T', 0 };
76 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
78 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
79 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
80 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
81 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
82 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
83 static const WCHAR szAge
[] = { 'A','g','e',0 };
84 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
85 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
86 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
87 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
88 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
89 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
90 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
91 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
92 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
93 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
94 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
95 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
96 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 };
97 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
98 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
99 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
100 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
101 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
102 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
103 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
104 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
106 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
107 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
108 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
109 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
110 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
111 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
112 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
113 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
114 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
115 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
116 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
117 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
118 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
119 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
120 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
121 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
122 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
123 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 };
124 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
125 static const WCHAR szURI
[] = { 'U','R','I',0 };
126 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
127 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
128 static const WCHAR szVia
[] = { 'V','i','a',0 };
129 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
130 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
132 static const WCHAR emptyW
[] = {0};
134 #define HTTP_REFERER szReferer
135 #define HTTP_ACCEPT szAccept
136 #define HTTP_USERAGENT szUser_Agent
138 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
139 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
140 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
141 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
142 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
143 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
144 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
146 #define COLLECT_TIME 60000
148 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
159 unsigned int auth_data_len
;
160 BOOL finished
; /* finished authenticating */
164 typedef struct _basicAuthorizationData
171 UINT authorizationLen
;
172 } basicAuthorizationData
;
174 typedef struct _authorizationData
188 static struct list basicAuthorizationCache
= LIST_INIT(basicAuthorizationCache
);
189 static struct list authorizationCache
= LIST_INIT(authorizationCache
);
191 static CRITICAL_SECTION authcache_cs
;
192 static CRITICAL_SECTION_DEBUG critsect_debug
=
195 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
196 0, 0, { (DWORD_PTR
)(__FILE__
": authcache_cs") }
198 static CRITICAL_SECTION authcache_cs
= { &critsect_debug
, -1, 0, 0, 0, 0 };
200 static DWORD
HTTP_GetResponseHeaders(http_request_t
*req
, INT
*len
);
201 static DWORD
HTTP_ProcessHeader(http_request_t
*req
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
);
202 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
);
203 static DWORD
HTTP_InsertCustomHeader(http_request_t
*req
, LPHTTPHEADERW lpHdr
);
204 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*req
, LPCWSTR lpszField
, INT index
, BOOL Request
);
205 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*req
, DWORD index
);
206 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
);
207 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*, DWORD
, LPVOID
, LPDWORD
, LPDWORD
);
208 static UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
209 static BOOL
drain_content(http_request_t
*,BOOL
);
211 static CRITICAL_SECTION connection_pool_cs
;
212 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
214 0, 0, &connection_pool_cs
,
215 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
216 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
218 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
220 static struct list connection_pool
= LIST_INIT(connection_pool
);
221 static BOOL collector_running
;
223 void server_addref(server_t
*server
)
225 InterlockedIncrement(&server
->ref
);
228 void server_release(server_t
*server
)
230 if(InterlockedDecrement(&server
->ref
))
233 list_remove(&server
->entry
);
235 if(server
->cert_chain
)
236 CertFreeCertificateChain(server
->cert_chain
);
237 heap_free(server
->name
);
238 heap_free(server
->scheme_host_port
);
242 static BOOL
process_host_port(server_t
*server
)
248 static const WCHAR httpW
[] = {'h','t','t','p',0};
249 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
250 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
252 name_len
= strlenW(server
->name
);
253 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
257 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
258 server
->scheme_host_port
= buf
;
260 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
264 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
265 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
269 server_t
*get_server(substr_t name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
271 server_t
*iter
, *server
= NULL
;
273 if(port
== INTERNET_INVALID_PORT_NUMBER
)
274 port
= INTERNET_DEFAULT_HTTP_PORT
;
276 EnterCriticalSection(&connection_pool_cs
);
278 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
279 if(iter
->port
== port
&& name
.len
== strlenW(iter
->name
) && !strncmpW(iter
->name
, name
.str
, name
.len
)
280 && iter
->is_https
== is_https
) {
282 server_addref(server
);
287 if(!server
&& do_create
) {
288 server
= heap_alloc_zero(sizeof(*server
));
290 server
->ref
= 2; /* list reference and return */
292 server
->is_https
= is_https
;
293 list_init(&server
->conn_pool
);
294 server
->name
= heap_strndupW(name
.str
, name
.len
);
295 if(server
->name
&& process_host_port(server
)) {
296 list_add_head(&connection_pool
, &server
->entry
);
304 LeaveCriticalSection(&connection_pool_cs
);
309 BOOL
collect_connections(collect_type_t collect_type
)
311 netconn_t
*netconn
, *netconn_safe
;
312 server_t
*server
, *server_safe
;
313 BOOL remaining
= FALSE
;
316 now
= GetTickCount64();
318 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
319 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
320 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
321 TRACE("freeing %p\n", netconn
);
322 list_remove(&netconn
->pool_entry
);
323 free_netconn(netconn
);
329 if(collect_type
== COLLECT_CLEANUP
) {
330 list_remove(&server
->entry
);
331 list_init(&server
->entry
);
332 server_release(server
);
339 static DWORD WINAPI
collect_connections_proc(void *arg
)
341 BOOL remaining_conns
;
344 /* FIXME: Use more sophisticated method */
347 EnterCriticalSection(&connection_pool_cs
);
349 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
351 collector_running
= FALSE
;
353 LeaveCriticalSection(&connection_pool_cs
);
354 }while(remaining_conns
);
356 FreeLibraryAndExitThread(WININET_hModule
, 0);
359 /***********************************************************************
360 * HTTP_GetHeader (internal)
362 * Headers section must be held
364 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
367 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
368 if (HeaderIndex
== -1)
371 return &req
->custHeaders
[HeaderIndex
];
374 static WCHAR
*get_host_header( http_request_t
*req
)
379 EnterCriticalSection( &req
->headers_section
);
380 if ((header
= HTTP_GetHeader( req
, hostW
))) ret
= heap_strdupW( header
->lpszValue
);
381 else ret
= heap_strdupW( req
->server
->canon_host_port
);
382 LeaveCriticalSection( &req
->headers_section
);
392 struct data_stream_vtbl_t
{
393 DWORD (*get_avail_data
)(data_stream_t
*,http_request_t
*);
394 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
395 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,blocking_mode_t
);
396 BOOL (*drain_content
)(data_stream_t
*,http_request_t
*);
397 void (*destroy
)(data_stream_t
*);
401 data_stream_t data_stream
;
403 BYTE buf
[READ_BUFFER_SIZE
];
409 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
,
410 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
,
411 CHUNKED_STREAM_STATE_READING_CHUNK
,
412 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
,
413 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
,
414 CHUNKED_STREAM_STATE_END_OF_STREAM
418 static inline void destroy_data_stream(data_stream_t
*stream
)
420 stream
->vtbl
->destroy(stream
);
423 static void reset_data_stream(http_request_t
*req
)
425 destroy_data_stream(req
->data_stream
);
426 req
->data_stream
= &req
->netconn_stream
.data_stream
;
427 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
428 req
->read_gzip
= FALSE
;
431 static void remove_header( http_request_t
*request
, const WCHAR
*str
, BOOL from_request
)
434 EnterCriticalSection( &request
->headers_section
);
435 index
= HTTP_GetCustomHeaderIndex( request
, str
, 0, from_request
);
436 if (index
!= -1) HTTP_DeleteCustomHeader( request
, index
);
437 LeaveCriticalSection( &request
->headers_section
);
443 data_stream_t stream
;
444 data_stream_t
*parent_stream
;
446 BYTE buf
[READ_BUFFER_SIZE
];
452 static DWORD
gzip_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
454 /* Allow reading only from read buffer */
458 static BOOL
gzip_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
460 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
461 return gzip_stream
->end_of_data
462 || (!gzip_stream
->buf_size
&& gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
));
465 static DWORD
gzip_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
466 DWORD
*read
, blocking_mode_t blocking_mode
)
468 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
469 z_stream
*zstream
= &gzip_stream
->zstream
;
470 DWORD current_read
, ret_read
= 0;
472 DWORD res
= ERROR_SUCCESS
;
474 TRACE("(%d %d)\n", size
, blocking_mode
);
476 while(size
&& !gzip_stream
->end_of_data
) {
477 if(!gzip_stream
->buf_size
) {
478 if(gzip_stream
->buf_pos
) {
479 if(gzip_stream
->buf_size
)
480 memmove(gzip_stream
->buf
, gzip_stream
->buf
+gzip_stream
->buf_pos
, gzip_stream
->buf_size
);
481 gzip_stream
->buf_pos
= 0;
483 res
= gzip_stream
->parent_stream
->vtbl
->read(gzip_stream
->parent_stream
, req
, gzip_stream
->buf
+gzip_stream
->buf_size
,
484 sizeof(gzip_stream
->buf
)-gzip_stream
->buf_size
, ¤t_read
, blocking_mode
);
485 gzip_stream
->buf_size
+= current_read
;
486 if(res
!= ERROR_SUCCESS
)
490 if(blocking_mode
!= BLOCKING_DISALLOW
) {
491 WARN("unexpected end of data\n");
492 gzip_stream
->end_of_data
= TRUE
;
498 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
499 zstream
->avail_in
= gzip_stream
->buf_size
;
500 zstream
->next_out
= buf
+ret_read
;
501 zstream
->avail_out
= size
;
502 zres
= inflate(&gzip_stream
->zstream
, 0);
503 current_read
= size
- zstream
->avail_out
;
504 size
-= current_read
;
505 ret_read
+= current_read
;
506 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
507 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
508 if(zres
== Z_STREAM_END
) {
509 TRACE("end of data\n");
510 gzip_stream
->end_of_data
= TRUE
;
512 }else if(zres
!= Z_OK
) {
513 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
515 res
= ERROR_INTERNET_DECODING_FAILED
;
519 if(ret_read
&& blocking_mode
== BLOCKING_ALLOW
)
520 blocking_mode
= BLOCKING_DISALLOW
;
523 TRACE("read %u bytes\n", ret_read
);
528 static BOOL
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
)
530 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
531 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
);
534 static void gzip_destroy(data_stream_t
*stream
)
536 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
538 destroy_data_stream(gzip_stream
->parent_stream
);
540 if(!gzip_stream
->end_of_data
)
541 inflateEnd(&gzip_stream
->zstream
);
542 heap_free(gzip_stream
);
545 static const data_stream_vtbl_t gzip_stream_vtbl
= {
553 static voidpf
wininet_zalloc(voidpf opaque
, uInt items
, uInt size
)
555 return heap_alloc(items
*size
);
558 static void wininet_zfree(voidpf opaque
, voidpf address
)
563 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
565 gzip_stream_t
*gzip_stream
;
568 gzip_stream
= heap_alloc_zero(sizeof(gzip_stream_t
));
570 return ERROR_OUTOFMEMORY
;
572 gzip_stream
->stream
.vtbl
= &gzip_stream_vtbl
;
573 gzip_stream
->zstream
.zalloc
= wininet_zalloc
;
574 gzip_stream
->zstream
.zfree
= wininet_zfree
;
576 zres
= inflateInit2(&gzip_stream
->zstream
, is_gzip
? 0x1f : -15);
578 ERR("inflateInit failed: %d\n", zres
);
579 heap_free(gzip_stream
);
580 return ERROR_OUTOFMEMORY
;
583 remove_header(req
, szContent_Length
, FALSE
);
586 memcpy(gzip_stream
->buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
587 gzip_stream
->buf_size
= req
->read_size
;
588 req
->read_pos
= req
->read_size
= 0;
591 req
->read_gzip
= TRUE
;
592 gzip_stream
->parent_stream
= req
->data_stream
;
593 req
->data_stream
= &gzip_stream
->stream
;
594 return ERROR_SUCCESS
;
599 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
601 ERR("gzip stream not supported, missing zlib.\n");
602 return ERROR_SUCCESS
;
607 /***********************************************************************
608 * HTTP_FreeTokens (internal)
610 * Frees table of pointers.
612 static void HTTP_FreeTokens(LPWSTR
* token_array
)
615 for (i
= 0; token_array
[i
]; i
++) heap_free(token_array
[i
]);
616 heap_free(token_array
);
619 static void HTTP_FixURL(http_request_t
*request
)
621 static const WCHAR szSlash
[] = { '/',0 };
622 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/', 0 };
624 /* If we don't have a path we set it to root */
625 if (NULL
== request
->path
)
626 request
->path
= heap_strdupW(szSlash
);
627 else /* remove \r and \n*/
629 int nLen
= strlenW(request
->path
);
630 while ((nLen
>0 ) && ((request
->path
[nLen
-1] == '\r')||(request
->path
[nLen
-1] == '\n')))
633 request
->path
[nLen
]='\0';
635 /* Replace '\' with '/' */
638 if (request
->path
[nLen
] == '\\') request
->path
[nLen
]='/';
642 if(CSTR_EQUAL
!= CompareStringW( LOCALE_INVARIANT
, NORM_IGNORECASE
,
643 request
->path
, strlenW(request
->path
), szHttp
, strlenW(szHttp
) )
644 && request
->path
[0] != '/') /* not an absolute path ?? --> fix it !! */
646 WCHAR
*fixurl
= heap_alloc((strlenW(request
->path
) + 2)*sizeof(WCHAR
));
648 strcpyW(fixurl
+ 1, request
->path
);
649 heap_free( request
->path
);
650 request
->path
= fixurl
;
654 static WCHAR
* build_request_header(http_request_t
*request
, const WCHAR
*verb
,
655 const WCHAR
*path
, const WCHAR
*version
, BOOL use_cr
)
657 static const WCHAR szSpace
[] = {' ',0};
658 static const WCHAR szColon
[] = {':',' ',0};
659 static const WCHAR szCr
[] = {'\r',0};
660 static const WCHAR szLf
[] = {'\n',0};
661 LPWSTR requestString
;
666 EnterCriticalSection( &request
->headers_section
);
668 /* allocate space for an array of all the string pointers to be added */
669 len
= request
->nCustHeaders
* 5 + 10;
670 if (!(req
= heap_alloc( len
* sizeof(const WCHAR
*) )))
672 LeaveCriticalSection( &request
->headers_section
);
676 /* add the verb, path and HTTP version string */
687 /* Append custom request headers */
688 for (i
= 0; i
< request
->nCustHeaders
; i
++)
690 if (request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
692 req
[n
++] = request
->custHeaders
[i
].lpszField
;
694 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
699 TRACE("Adding custom header %s (%s)\n",
700 debugstr_w(request
->custHeaders
[i
].lpszField
),
701 debugstr_w(request
->custHeaders
[i
].lpszValue
));
709 requestString
= HTTP_build_req( req
, 4 );
711 LeaveCriticalSection( &request
->headers_section
);
712 return requestString
;
715 static WCHAR
* build_response_header(http_request_t
*request
, BOOL use_cr
)
717 static const WCHAR colonW
[] = { ':',' ',0 };
718 static const WCHAR crW
[] = { '\r',0 };
719 static const WCHAR lfW
[] = { '\n',0 };
720 static const WCHAR status_fmt
[] = { ' ','%','u',' ',0 };
725 EnterCriticalSection( &request
->headers_section
);
727 if (!(req
= heap_alloc( (request
->nCustHeaders
* 5 + 8) * sizeof(WCHAR
*) )))
729 LeaveCriticalSection( &request
->headers_section
);
733 if (request
->status_code
)
735 req
[n
++] = request
->version
;
736 sprintfW(buf
, status_fmt
, request
->status_code
);
738 req
[n
++] = request
->statusText
;
744 for(i
= 0; i
< request
->nCustHeaders
; i
++)
746 if(!(request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
747 && strcmpW(request
->custHeaders
[i
].lpszField
, szStatus
))
749 req
[n
++] = request
->custHeaders
[i
].lpszField
;
751 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
756 TRACE("Adding custom header %s (%s)\n",
757 debugstr_w(request
->custHeaders
[i
].lpszField
),
758 debugstr_w(request
->custHeaders
[i
].lpszValue
));
766 ret
= HTTP_build_req(req
, 0);
768 LeaveCriticalSection( &request
->headers_section
);
772 static void HTTP_ProcessCookies( http_request_t
*request
)
776 LPHTTPHEADERW setCookieHeader
;
778 if(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
)
781 EnterCriticalSection( &request
->headers_section
);
783 while((HeaderIndex
= HTTP_GetCustomHeaderIndex(request
, szSet_Cookie
, numCookies
++, FALSE
)) != -1)
788 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
790 if (!setCookieHeader
->lpszValue
)
793 data
= strchrW(setCookieHeader
->lpszValue
, '=');
797 name
= substr(setCookieHeader
->lpszValue
, data
- setCookieHeader
->lpszValue
);
799 set_cookie(substrz(request
->server
->name
), substrz(request
->path
), name
, substrz(data
), INTERNET_COOKIE_HTTPONLY
);
802 LeaveCriticalSection( &request
->headers_section
);
805 static void strip_spaces(LPWSTR start
)
814 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
816 end
= start
+ strlenW(start
) - 1;
817 while (end
>= start
&& *end
== ' ')
824 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
826 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
827 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
829 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAYSIZE(szBasic
)) &&
830 ((pszAuthValue
[ARRAYSIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAYSIZE(szBasic
)]);
831 if (is_basic
&& pszRealm
)
834 LPCWSTR ptr
= &pszAuthValue
[ARRAYSIZE(szBasic
)];
838 token
= strchrW(ptr
,'=');
842 while (*realm
== ' ')
844 if(!strncmpiW(realm
, szRealm
, ARRAYSIZE(szRealm
)) &&
845 (realm
[ARRAYSIZE(szRealm
)] == ' ' || realm
[ARRAYSIZE(szRealm
)] == '='))
848 while (*token
== ' ')
852 *pszRealm
= heap_strdupW(token
);
853 strip_spaces(*pszRealm
);
860 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
862 if (!authinfo
) return;
864 if (SecIsValidHandle(&authinfo
->ctx
))
865 DeleteSecurityContext(&authinfo
->ctx
);
866 if (SecIsValidHandle(&authinfo
->cred
))
867 FreeCredentialsHandle(&authinfo
->cred
);
869 heap_free(authinfo
->auth_data
);
870 heap_free(authinfo
->scheme
);
874 static UINT
retrieve_cached_basic_authorization(const WCHAR
*host
, const WCHAR
*realm
, char **auth_data
)
876 basicAuthorizationData
*ad
;
879 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
881 EnterCriticalSection(&authcache_cs
);
882 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
884 if (!strcmpiW(host
, ad
->host
) && (!realm
|| !strcmpW(realm
, ad
->realm
)))
886 TRACE("Authorization found in cache\n");
887 *auth_data
= heap_alloc(ad
->authorizationLen
);
888 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
889 rc
= ad
->authorizationLen
;
893 LeaveCriticalSection(&authcache_cs
);
897 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
900 basicAuthorizationData
* ad
= NULL
;
902 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
904 EnterCriticalSection(&authcache_cs
);
905 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
907 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
908 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
917 TRACE("Found match in cache, replacing\n");
918 heap_free(ad
->authorization
);
919 ad
->authorization
= heap_alloc(auth_data_len
);
920 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
921 ad
->authorizationLen
= auth_data_len
;
925 ad
= heap_alloc(sizeof(basicAuthorizationData
));
926 ad
->host
= heap_strdupW(host
);
927 ad
->realm
= heap_strdupW(realm
);
928 ad
->authorization
= heap_alloc(auth_data_len
);
929 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
930 ad
->authorizationLen
= auth_data_len
;
931 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
932 TRACE("authorization cached\n");
934 LeaveCriticalSection(&authcache_cs
);
937 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
938 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
940 authorizationData
*ad
;
942 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
944 EnterCriticalSection(&authcache_cs
);
945 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
946 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
947 TRACE("Authorization found in cache\n");
949 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
950 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
951 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
952 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
953 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
954 heap_free(nt_auth_identity
->User
);
955 heap_free(nt_auth_identity
->Password
);
956 heap_free(nt_auth_identity
->Domain
);
960 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
961 nt_auth_identity
->UserLength
= ad
->user_len
;
962 nt_auth_identity
->PasswordLength
= ad
->password_len
;
963 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
964 nt_auth_identity
->DomainLength
= ad
->domain_len
;
965 LeaveCriticalSection(&authcache_cs
);
969 LeaveCriticalSection(&authcache_cs
);
974 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
975 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
977 authorizationData
*ad
;
980 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
982 EnterCriticalSection(&authcache_cs
);
983 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
984 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
991 heap_free(ad
->password
);
992 heap_free(ad
->domain
);
994 ad
= heap_alloc(sizeof(authorizationData
));
996 LeaveCriticalSection(&authcache_cs
);
1000 ad
->host
= heap_strdupW(host
);
1001 ad
->scheme
= heap_strdupW(scheme
);
1002 list_add_head(&authorizationCache
, &ad
->entry
);
1005 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
1006 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
1007 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
1008 ad
->user_len
= nt_auth_identity
->UserLength
;
1009 ad
->password_len
= nt_auth_identity
->PasswordLength
;
1010 ad
->domain_len
= nt_auth_identity
->DomainLength
;
1012 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
1013 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
1014 heap_free(ad
->host
);
1015 heap_free(ad
->scheme
);
1016 heap_free(ad
->user
);
1017 heap_free(ad
->password
);
1018 heap_free(ad
->domain
);
1019 list_remove(&ad
->entry
);
1023 LeaveCriticalSection(&authcache_cs
);
1026 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
1027 struct HttpAuthInfo
**ppAuthInfo
,
1028 LPWSTR domain_and_username
, LPWSTR password
,
1031 SECURITY_STATUS sec_status
;
1032 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
1034 LPWSTR szRealm
= NULL
;
1036 TRACE("%s\n", debugstr_w(pszAuthValue
));
1043 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
1047 SecInvalidateHandle(&pAuthInfo
->cred
);
1048 SecInvalidateHandle(&pAuthInfo
->ctx
);
1049 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1050 pAuthInfo
->attr
= 0;
1051 pAuthInfo
->auth_data
= NULL
;
1052 pAuthInfo
->auth_data_len
= 0;
1053 pAuthInfo
->finished
= FALSE
;
1055 if (is_basic_auth_value(pszAuthValue
,NULL
))
1057 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1058 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1059 if (!pAuthInfo
->scheme
)
1061 heap_free(pAuthInfo
);
1068 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1070 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1071 if (!pAuthInfo
->scheme
)
1073 heap_free(pAuthInfo
);
1077 if (domain_and_username
)
1079 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1080 WCHAR
*domain
= domain_and_username
;
1082 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1084 pAuthData
= &nt_auth_identity
;
1089 user
= domain_and_username
;
1093 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1094 nt_auth_identity
.User
= user
;
1095 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1096 nt_auth_identity
.Domain
= domain
;
1097 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1098 nt_auth_identity
.Password
= password
;
1099 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1101 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1103 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1104 pAuthData
= &nt_auth_identity
;
1106 /* use default credentials */
1109 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1110 SECPKG_CRED_OUTBOUND
, NULL
,
1112 NULL
, &pAuthInfo
->cred
,
1115 if(pAuthData
&& !domain_and_username
) {
1116 heap_free(nt_auth_identity
.User
);
1117 heap_free(nt_auth_identity
.Domain
);
1118 heap_free(nt_auth_identity
.Password
);
1121 if (sec_status
== SEC_E_OK
)
1123 PSecPkgInfoW sec_pkg_info
;
1124 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1125 if (sec_status
== SEC_E_OK
)
1127 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1128 FreeContextBuffer(sec_pkg_info
);
1131 if (sec_status
!= SEC_E_OK
)
1133 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1134 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1135 heap_free(pAuthInfo
->scheme
);
1136 heap_free(pAuthInfo
);
1140 *ppAuthInfo
= pAuthInfo
;
1142 else if (pAuthInfo
->finished
)
1145 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1146 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1148 ERR("authentication scheme changed from %s to %s\n",
1149 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1153 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1157 char *auth_data
= NULL
;
1158 UINT auth_data_len
= 0;
1160 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1162 if (!domain_and_username
)
1164 if (host
&& szRealm
)
1165 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1166 if (auth_data_len
== 0)
1174 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1175 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1177 /* length includes a nul terminator, which will be re-used for the ':' */
1178 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1185 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1186 auth_data
[userlen
] = ':';
1187 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1188 auth_data_len
= userlen
+ 1 + passlen
;
1189 if (host
&& szRealm
)
1190 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1193 pAuthInfo
->auth_data
= auth_data
;
1194 pAuthInfo
->auth_data_len
= auth_data_len
;
1195 pAuthInfo
->finished
= TRUE
;
1201 LPCWSTR pszAuthData
;
1202 SecBufferDesc out_desc
, in_desc
;
1204 unsigned char *buffer
;
1205 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1206 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1208 in
.BufferType
= SECBUFFER_TOKEN
;
1212 in_desc
.ulVersion
= 0;
1213 in_desc
.cBuffers
= 1;
1214 in_desc
.pBuffers
= &in
;
1216 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1217 if (*pszAuthData
== ' ')
1220 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1221 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1222 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1225 buffer
= heap_alloc(pAuthInfo
->max_token
);
1227 out
.BufferType
= SECBUFFER_TOKEN
;
1228 out
.cbBuffer
= pAuthInfo
->max_token
;
1229 out
.pvBuffer
= buffer
;
1231 out_desc
.ulVersion
= 0;
1232 out_desc
.cBuffers
= 1;
1233 out_desc
.pBuffers
= &out
;
1235 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1236 first
? NULL
: &pAuthInfo
->ctx
,
1237 first
? request
->server
->name
: NULL
,
1238 context_req
, 0, SECURITY_NETWORK_DREP
,
1239 in
.pvBuffer
? &in_desc
: NULL
,
1240 0, &pAuthInfo
->ctx
, &out_desc
,
1241 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1242 if (sec_status
== SEC_E_OK
)
1244 pAuthInfo
->finished
= TRUE
;
1245 pAuthInfo
->auth_data
= out
.pvBuffer
;
1246 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1247 TRACE("sending last auth packet\n");
1249 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1251 pAuthInfo
->auth_data
= out
.pvBuffer
;
1252 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1253 TRACE("sending next auth packet\n");
1257 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1258 heap_free(out
.pvBuffer
);
1259 destroy_authinfo(pAuthInfo
);
1268 /***********************************************************************
1269 * HTTP_HttpAddRequestHeadersW (internal)
1271 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1272 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1277 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1279 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1281 if( dwHeaderLength
== ~0U )
1282 len
= strlenW(lpszHeader
);
1284 len
= dwHeaderLength
;
1285 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1286 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1292 LPWSTR
* pFieldAndValue
;
1294 lpszEnd
= lpszStart
;
1296 while (*lpszEnd
!= '\0')
1298 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1303 if (*lpszStart
== '\0')
1306 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1309 lpszEnd
++; /* Jump over newline */
1311 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1312 if (*lpszStart
== '\0')
1314 /* Skip 0-length headers */
1315 lpszStart
= lpszEnd
;
1316 res
= ERROR_SUCCESS
;
1319 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1322 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1323 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1324 HTTP_FreeTokens(pFieldAndValue
);
1327 lpszStart
= lpszEnd
;
1328 } while (res
== ERROR_SUCCESS
);
1334 /***********************************************************************
1335 * HttpAddRequestHeadersW (WININET.@)
1337 * Adds one or more HTTP header to the request handler
1340 * On Windows if dwHeaderLength includes the trailing '\0', then
1341 * HttpAddRequestHeadersW() adds it too. However this results in an
1342 * invalid HTTP header which is rejected by some servers so we probably
1343 * don't need to match Windows on that point.
1350 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1351 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1353 http_request_t
*request
;
1354 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1356 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1361 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1362 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1363 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1365 WININET_Release( &request
->hdr
);
1367 if(res
!= ERROR_SUCCESS
)
1369 return res
== ERROR_SUCCESS
;
1372 /***********************************************************************
1373 * HttpAddRequestHeadersA (WININET.@)
1375 * Adds one or more HTTP header to the request handler
1382 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1383 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1385 WCHAR
*headers
= NULL
;
1388 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1391 headers
= heap_strndupAtoW(lpszHeader
, dwHeaderLength
, &dwHeaderLength
);
1393 r
= HttpAddRequestHeadersW(hHttpRequest
, headers
, dwHeaderLength
, dwModifier
);
1399 static void free_accept_types( WCHAR
**accept_types
)
1401 WCHAR
*ptr
, **types
= accept_types
;
1404 while ((ptr
= *types
))
1409 heap_free( accept_types
);
1412 static WCHAR
**convert_accept_types( const char **accept_types
)
1415 const char **types
= accept_types
;
1417 BOOL invalid_pointer
= FALSE
;
1419 if (!types
) return NULL
;
1425 /* find out how many there are */
1426 if (*types
&& **types
)
1428 TRACE("accept type: %s\n", debugstr_a(*types
));
1434 WARN("invalid accept type pointer\n");
1435 invalid_pointer
= TRUE
;
1440 if (invalid_pointer
) return NULL
;
1441 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1443 types
= accept_types
;
1446 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1449 typesW
[count
] = NULL
;
1453 /***********************************************************************
1454 * HttpOpenRequestA (WININET.@)
1456 * Open a HTTP request handle
1459 * HINTERNET a HTTP request handle on success
1463 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1464 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1465 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1466 DWORD dwFlags
, DWORD_PTR dwContext
)
1468 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1469 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1470 HINTERNET rc
= NULL
;
1472 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1473 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1474 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1475 dwFlags
, dwContext
);
1479 szVerb
= heap_strdupAtoW(lpszVerb
);
1486 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1487 if ( !szObjectName
)
1493 szVersion
= heap_strdupAtoW(lpszVersion
);
1500 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1505 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1506 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1507 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1510 free_accept_types(szAcceptTypes
);
1511 heap_free(szReferrer
);
1512 heap_free(szVersion
);
1513 heap_free(szObjectName
);
1518 /***********************************************************************
1521 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1524 static const CHAR HTTP_Base64Enc
[] =
1525 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1529 /* first 6 bits, all from bin[0] */
1530 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1531 x
= (bin
[0] & 3) << 4;
1533 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1536 base64
[n
++] = HTTP_Base64Enc
[x
];
1541 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1542 x
= ( bin
[1] & 0x0f ) << 2;
1544 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1547 base64
[n
++] = HTTP_Base64Enc
[x
];
1551 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1553 /* last 6 bits, all from bin [2] */
1554 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1562 static const signed char HTTP_Base64Dec
[] =
1564 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1565 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1566 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1567 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1568 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1569 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1570 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1571 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1574 /***********************************************************************
1577 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1585 if (base64
[0] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1586 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1587 base64
[1] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1588 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1590 WARN("invalid base64: %s\n", debugstr_w(base64
));
1594 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1597 if ((base64
[2] == '=') && (base64
[3] == '='))
1599 if (base64
[2] > ARRAYSIZE(HTTP_Base64Dec
) ||
1600 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1602 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1606 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1609 if (base64
[3] == '=')
1611 if (base64
[3] > ARRAYSIZE(HTTP_Base64Dec
) ||
1612 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1614 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1618 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1627 static WCHAR
*encode_auth_data( const WCHAR
*scheme
, const char *data
, UINT data_len
)
1630 UINT len
, scheme_len
= strlenW( scheme
);
1632 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1633 len
= scheme_len
+ 1 + ((data_len
+ 2) * 4) / 3;
1634 if (!(ret
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1635 memcpy( ret
, scheme
, scheme_len
* sizeof(WCHAR
) );
1636 ret
[scheme_len
] = ' ';
1637 HTTP_EncodeBase64( data
, data_len
, ret
+ scheme_len
+ 1 );
1642 /***********************************************************************
1643 * HTTP_InsertAuthorization
1645 * Insert or delete the authorization field in the request header.
1647 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1649 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1650 WCHAR
*host
, *authorization
= NULL
;
1654 if (pAuthInfo
->auth_data_len
)
1656 if (!(authorization
= encode_auth_data(pAuthInfo
->scheme
, pAuthInfo
->auth_data
, pAuthInfo
->auth_data_len
)))
1659 /* clear the data as it isn't valid now that it has been sent to the
1660 * server, unless it's Basic authentication which doesn't do
1661 * connection tracking */
1662 if (strcmpiW(pAuthInfo
->scheme
, wszBasic
))
1664 heap_free(pAuthInfo
->auth_data
);
1665 pAuthInfo
->auth_data
= NULL
;
1666 pAuthInfo
->auth_data_len
= 0;
1670 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1672 HTTP_ProcessHeader(request
, header
, authorization
,
1673 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
1674 heap_free(authorization
);
1676 else if (!strcmpW(header
, szAuthorization
) && (host
= get_host_header(request
)))
1681 if ((data_len
= retrieve_cached_basic_authorization(host
, NULL
, &data
)))
1683 TRACE("Found cached basic authorization for %s\n", debugstr_w(host
));
1685 if (!(authorization
= encode_auth_data(wszBasic
, data
, data_len
)))
1692 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1694 HTTP_ProcessHeader(request
, header
, authorization
,
1695 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
1697 heap_free(authorization
);
1704 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1709 len
= strlenW(req
->server
->scheme_host_port
);
1710 size
= len
+ strlenW(req
->path
) + 1;
1711 if(*req
->path
!= '/')
1713 url
= heap_alloc(size
* sizeof(WCHAR
));
1717 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1718 if(*req
->path
!= '/')
1721 strcpyW(url
+len
, req
->path
);
1723 TRACE("url=%s\n", debugstr_w(url
));
1727 static BOOL
HTTP_DomainMatches(LPCWSTR server
, substr_t domain
)
1729 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1730 const WCHAR
*dot
, *ptr
;
1733 if(domain
.len
== sizeof(localW
)/sizeof(WCHAR
)-1 && !strncmpiW(domain
.str
, localW
, domain
.len
) && !strchrW(server
, '.' ))
1736 if(domain
.len
&& *domain
.str
!= '*')
1737 return domain
.len
== strlenW(server
) && !strncmpiW(server
, domain
.str
, domain
.len
);
1739 if(domain
.len
< 2 || domain
.str
[1] != '.')
1742 /* For a hostname to match a wildcard, the last domain must match
1743 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1744 * hostname is www.foo.a.b, it matches, but a.b does not.
1746 dot
= strchrW(server
, '.');
1750 len
= strlenW(dot
+ 1);
1751 if(len
<= domain
.len
- 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
+ 1 + len
- domain
.len
+ 2;
1759 if(!strncmpiW(ptr
, domain
.str
+2, domain
.len
-2))
1760 /* This is only a match if the preceding character is
1761 * a '.', i.e. that it is a matching domain. E.g.
1762 * if domain is '*.b.c' and server is 'www.ab.c' they
1765 return *(ptr
- 1) == '.';
1767 return len
== domain
.len
-2 && !strncmpiW(dot
+ 1, domain
.str
+ 2, len
);
1770 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1775 if (!lpwai
->proxyBypass
) return FALSE
;
1776 ptr
= lpwai
->proxyBypass
;
1780 ptr
= strchrW( ptr
, ';' );
1782 ptr
= strchrW( tmp
, ' ' );
1784 ptr
= tmp
+ strlenW(tmp
);
1785 ret
= HTTP_DomainMatches( server
, substr(tmp
, ptr
-tmp
) );
1793 /***********************************************************************
1794 * HTTP_DealWithProxy
1796 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1798 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1799 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1800 static WCHAR szNul
[] = { 0 };
1801 URL_COMPONENTSW UrlComponents
= { sizeof(UrlComponents
) };
1802 server_t
*new_server
= NULL
;
1805 proxy
= INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
);
1808 if(CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1809 proxy
, strlenW(szHttp
), szHttp
, strlenW(szHttp
))) {
1810 WCHAR
*proxy_url
= heap_alloc(strlenW(proxy
)*sizeof(WCHAR
) + sizeof(szHttp
));
1815 strcpyW(proxy_url
, szHttp
);
1816 strcatW(proxy_url
, proxy
);
1821 UrlComponents
.dwHostNameLength
= 1;
1822 if(InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) && UrlComponents
.dwHostNameLength
) {
1823 if( !request
->path
)
1824 request
->path
= szNul
;
1826 new_server
= get_server(substr(UrlComponents
.lpszHostName
, UrlComponents
.dwHostNameLength
),
1827 UrlComponents
.nPort
, UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
1833 request
->proxy
= new_server
;
1835 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1839 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1841 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1844 if(server
->addr_len
)
1845 return ERROR_SUCCESS
;
1847 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1848 INTERNET_STATUS_RESOLVING_NAME
,
1850 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1852 addr_len
= sizeof(server
->addr
);
1853 if (!GetAddress(server
->name
, server
->port
, (SOCKADDR
*)&server
->addr
, &addr_len
, server
->addr_str
))
1854 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1856 server
->addr_len
= addr_len
;
1857 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1858 INTERNET_STATUS_NAME_RESOLVED
,
1859 server
->addr_str
, strlen(server
->addr_str
)+1);
1861 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1862 return ERROR_SUCCESS
;
1865 static WCHAR
*compose_request_url(http_request_t
*req
)
1867 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1868 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1869 const WCHAR
*host
, *scheme
;
1873 host
= req
->server
->canon_host_port
;
1875 if (req
->server
->is_https
)
1880 len
= strlenW(scheme
) + strlenW(host
) + (req
->path
[0] != '/' ? 1 : 0) + strlenW(req
->path
);
1881 ptr
= buf
= heap_alloc((len
+1) * sizeof(WCHAR
));
1883 strcpyW(ptr
, scheme
);
1884 ptr
+= strlenW(ptr
);
1887 ptr
+= strlenW(ptr
);
1889 if(req
->path
[0] != '/')
1892 strcpyW(ptr
, req
->path
);
1893 ptr
+= strlenW(ptr
);
1901 /***********************************************************************
1902 * HTTPREQ_Destroy (internal)
1904 * Deallocate request handle
1907 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1909 http_request_t
*request
= (http_request_t
*) hdr
;
1914 if(request
->hCacheFile
)
1915 CloseHandle(request
->hCacheFile
);
1916 if(request
->req_file
)
1917 req_file_release(request
->req_file
);
1919 request
->headers_section
.DebugInfo
->Spare
[0] = 0;
1920 DeleteCriticalSection( &request
->headers_section
);
1921 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1922 DeleteCriticalSection( &request
->read_section
);
1923 WININET_Release(&request
->session
->hdr
);
1925 destroy_authinfo(request
->authInfo
);
1926 destroy_authinfo(request
->proxyAuthInfo
);
1929 server_release(request
->server
);
1931 server_release(request
->proxy
);
1933 heap_free(request
->path
);
1934 heap_free(request
->verb
);
1935 heap_free(request
->version
);
1936 heap_free(request
->statusText
);
1938 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1940 heap_free(request
->custHeaders
[i
].lpszField
);
1941 heap_free(request
->custHeaders
[i
].lpszValue
);
1943 destroy_data_stream(request
->data_stream
);
1944 heap_free(request
->custHeaders
);
1947 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1949 TRACE("%p %p %x\n",req
, req
->netconn
, reuse
);
1951 if(!is_valid_netconn(req
->netconn
))
1954 if(reuse
&& req
->netconn
->keep_alive
) {
1957 EnterCriticalSection(&connection_pool_cs
);
1959 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1960 req
->netconn
->keep_until
= GetTickCount64() + COLLECT_TIME
;
1961 req
->netconn
= NULL
;
1963 run_collector
= !collector_running
;
1964 collector_running
= TRUE
;
1966 LeaveCriticalSection(&connection_pool_cs
);
1969 HANDLE thread
= NULL
;
1972 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
1974 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
1976 EnterCriticalSection(&connection_pool_cs
);
1977 collector_running
= FALSE
;
1978 LeaveCriticalSection(&connection_pool_cs
);
1981 FreeLibrary(module
);
1984 CloseHandle(thread
);
1989 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1990 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
1992 close_netconn(req
->netconn
);
1994 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1995 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
1998 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
2000 WCHAR szVersion
[10];
2001 WCHAR szConnectionResponse
[20];
2002 DWORD dwBufferSize
= sizeof(szVersion
);
2003 BOOL keepalive
= FALSE
;
2005 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2006 * the connection is keep-alive by default */
2007 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2008 && !strcmpiW(szVersion
, g_szHttp1_1
))
2013 dwBufferSize
= sizeof(szConnectionResponse
);
2014 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2015 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
2017 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2023 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2025 http_request_t
*req
= (http_request_t
*)hdr
;
2027 http_release_netconn(req
, drain_content(req
, FALSE
));
2030 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2035 WCHAR
*buf
= buffer
;
2037 if (str
) len
= strlenW(str
);
2039 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2041 *size
= (len
+ 1) * sizeof(WCHAR
);
2042 return ERROR_INSUFFICIENT_BUFFER
;
2044 if (str
) strcpyW(buf
, str
);
2048 return ERROR_SUCCESS
;
2054 if (str
) len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
2059 return ERROR_INSUFFICIENT_BUFFER
;
2061 if (str
) WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, *size
, NULL
, NULL
);
2065 return ERROR_SUCCESS
;
2069 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2071 http_request_t
*req
= (http_request_t
*)hdr
;
2074 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2076 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2078 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2080 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2081 return ERROR_INSUFFICIENT_BUFFER
;
2082 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2083 /* FIXME: can't get a SOCKET from our connection since we don't use
2087 /* FIXME: get source port from req->netConnection */
2088 info
->SourcePort
= 0;
2089 info
->DestPort
= req
->server
->port
;
2091 if (HTTP_KeepAlive(req
))
2092 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2094 info
->Flags
|= IDSI_FLAG_PROXY
;
2095 if (is_valid_netconn(req
->netconn
) && req
->netconn
->secure
)
2096 info
->Flags
|= IDSI_FLAG_SECURE
;
2098 return ERROR_SUCCESS
;
2102 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2104 case INTERNET_OPTION_SECURITY_FLAGS
:
2108 if (*size
< sizeof(ULONG
))
2109 return ERROR_INSUFFICIENT_BUFFER
;
2111 *size
= sizeof(DWORD
);
2112 flags
= is_valid_netconn(req
->netconn
) ? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2113 *(DWORD
*)buffer
= flags
;
2115 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2116 return ERROR_SUCCESS
;
2119 case INTERNET_OPTION_HANDLE_TYPE
:
2120 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2122 if (*size
< sizeof(ULONG
))
2123 return ERROR_INSUFFICIENT_BUFFER
;
2125 *size
= sizeof(DWORD
);
2126 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2127 return ERROR_SUCCESS
;
2129 case INTERNET_OPTION_URL
: {
2133 TRACE("INTERNET_OPTION_URL\n");
2135 url
= compose_request_url(req
);
2137 return ERROR_OUTOFMEMORY
;
2139 res
= str_to_buffer(url
, buffer
, size
, unicode
);
2143 case INTERNET_OPTION_USER_AGENT
:
2144 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2145 case INTERNET_OPTION_USERNAME
:
2146 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2147 case INTERNET_OPTION_PASSWORD
:
2148 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2149 case INTERNET_OPTION_PROXY_USERNAME
:
2150 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2151 case INTERNET_OPTION_PROXY_PASSWORD
:
2152 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2154 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2155 INTERNET_CACHE_ENTRY_INFOW
*info
;
2156 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2157 DWORD nbytes
, error
;
2160 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2163 return ERROR_FILE_NOT_FOUND
;
2165 if (*size
< sizeof(*ts
))
2167 *size
= sizeof(*ts
);
2168 return ERROR_INSUFFICIENT_BUFFER
;
2172 ret
= GetUrlCacheEntryInfoW(req
->req_file
->url
, NULL
, &nbytes
);
2173 error
= GetLastError();
2174 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2176 if (!(info
= heap_alloc(nbytes
)))
2177 return ERROR_OUTOFMEMORY
;
2179 GetUrlCacheEntryInfoW(req
->req_file
->url
, info
, &nbytes
);
2181 ts
->ftExpires
= info
->ExpireTime
;
2182 ts
->ftLastModified
= info
->LastModifiedTime
;
2185 *size
= sizeof(*ts
);
2186 return ERROR_SUCCESS
;
2191 case INTERNET_OPTION_DATAFILE_NAME
: {
2194 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2196 if(!req
->req_file
) {
2198 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2202 req_size
= (lstrlenW(req
->req_file
->file_name
)+1) * sizeof(WCHAR
);
2203 if(*size
< req_size
)
2204 return ERROR_INSUFFICIENT_BUFFER
;
2207 memcpy(buffer
, req
->req_file
->file_name
, *size
);
2208 return ERROR_SUCCESS
;
2210 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
, -1, NULL
, 0, NULL
, NULL
);
2211 if (req_size
> *size
)
2212 return ERROR_INSUFFICIENT_BUFFER
;
2214 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
,
2215 -1, buffer
, *size
, NULL
, NULL
);
2216 return ERROR_SUCCESS
;
2220 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2221 PCCERT_CONTEXT context
;
2224 return ERROR_INTERNET_INVALID_OPERATION
;
2226 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2227 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2228 return ERROR_INSUFFICIENT_BUFFER
;
2231 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2233 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2236 memset(info
, 0, sizeof(*info
));
2237 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2238 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2239 len
= CertNameToStrA(context
->dwCertEncodingType
,
2240 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2241 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2242 if(info
->lpszSubjectInfo
)
2243 CertNameToStrA(context
->dwCertEncodingType
,
2244 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2245 info
->lpszSubjectInfo
, len
);
2246 len
= CertNameToStrA(context
->dwCertEncodingType
,
2247 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2248 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2249 if(info
->lpszIssuerInfo
)
2250 CertNameToStrA(context
->dwCertEncodingType
,
2251 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2252 info
->lpszIssuerInfo
, len
);
2253 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2254 CertFreeCertificateContext(context
);
2255 return ERROR_SUCCESS
;
2257 return ERROR_NOT_SUPPORTED
;
2259 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2260 if (*size
< sizeof(DWORD
))
2261 return ERROR_INSUFFICIENT_BUFFER
;
2263 *size
= sizeof(DWORD
);
2264 *(DWORD
*)buffer
= req
->connect_timeout
;
2265 return ERROR_SUCCESS
;
2266 case INTERNET_OPTION_REQUEST_FLAGS
: {
2269 if (*size
< sizeof(DWORD
))
2270 return ERROR_INSUFFICIENT_BUFFER
;
2272 /* FIXME: Add support for:
2273 * INTERNET_REQFLAG_FROM_CACHE
2274 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2278 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2279 if(!req
->status_code
)
2280 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2282 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2284 *size
= sizeof(DWORD
);
2285 *(DWORD
*)buffer
= flags
;
2286 return ERROR_SUCCESS
;
2290 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2293 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2295 http_request_t
*req
= (http_request_t
*)hdr
;
2298 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2299 TRACE("Undocumented option 99\n");
2301 if (!buffer
|| size
!= sizeof(DWORD
))
2302 return ERROR_INVALID_PARAMETER
;
2303 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2304 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2307 case INTERNET_OPTION_SECURITY_FLAGS
:
2311 if (!buffer
|| size
!= sizeof(DWORD
))
2312 return ERROR_INVALID_PARAMETER
;
2313 flags
= *(DWORD
*)buffer
;
2314 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2315 flags
&= SECURITY_SET_MASK
;
2316 req
->security_flags
|= flags
;
2317 if(is_valid_netconn(req
->netconn
))
2318 req
->netconn
->security_flags
|= flags
;
2319 return ERROR_SUCCESS
;
2321 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2322 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2323 req
->connect_timeout
= *(DWORD
*)buffer
;
2324 return ERROR_SUCCESS
;
2326 case INTERNET_OPTION_SEND_TIMEOUT
:
2327 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2328 req
->send_timeout
= *(DWORD
*)buffer
;
2329 return ERROR_SUCCESS
;
2331 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2332 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2333 req
->receive_timeout
= *(DWORD
*)buffer
;
2334 return ERROR_SUCCESS
;
2336 case INTERNET_OPTION_USERNAME
:
2337 heap_free(req
->session
->userName
);
2338 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2339 return ERROR_SUCCESS
;
2341 case INTERNET_OPTION_PASSWORD
:
2342 heap_free(req
->session
->password
);
2343 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2344 return ERROR_SUCCESS
;
2346 case INTERNET_OPTION_PROXY_USERNAME
:
2347 heap_free(req
->session
->appInfo
->proxyUsername
);
2348 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2349 return ERROR_SUCCESS
;
2351 case INTERNET_OPTION_PROXY_PASSWORD
:
2352 heap_free(req
->session
->appInfo
->proxyPassword
);
2353 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2354 return ERROR_SUCCESS
;
2356 case INTERNET_OPTION_HTTP_DECODING
:
2357 if(size
!= sizeof(BOOL
))
2358 return ERROR_INVALID_PARAMETER
;
2359 req
->decoding
= *(BOOL
*)buffer
;
2360 return ERROR_SUCCESS
;
2363 return INET_SetOption(hdr
, option
, buffer
, size
);
2366 static void commit_cache_entry(http_request_t
*req
)
2374 CloseHandle(req
->hCacheFile
);
2375 req
->hCacheFile
= NULL
;
2377 header
= build_response_header(req
, TRUE
);
2378 header_len
= (header
? strlenW(header
) : 0);
2379 res
= CommitUrlCacheEntryW(req
->req_file
->url
, req
->req_file
->file_name
, req
->expires
,
2380 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2381 header
, header_len
, NULL
, 0);
2383 req
->req_file
->is_committed
= TRUE
;
2385 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2389 static void create_cache_entry(http_request_t
*req
)
2391 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2392 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2394 WCHAR file_name
[MAX_PATH
+1];
2398 /* FIXME: We should free previous cache file earlier */
2400 req_file_release(req
->req_file
);
2401 req
->req_file
= NULL
;
2403 if(req
->hCacheFile
) {
2404 CloseHandle(req
->hCacheFile
);
2405 req
->hCacheFile
= NULL
;
2408 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2414 EnterCriticalSection( &req
->headers_section
);
2416 header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2417 if(header_idx
!= -1) {
2420 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2423 while(*ptr
==' ' || *ptr
=='\t')
2426 end
= strchrW(ptr
, ',');
2428 end
= ptr
+ strlenW(ptr
);
2430 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2431 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2442 LeaveCriticalSection( &req
->headers_section
);
2446 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2449 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2452 url
= compose_request_url(req
);
2454 WARN("Could not get URL\n");
2458 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2460 WARN("Could not create cache entry: %08x\n", GetLastError());
2464 create_req_file(file_name
, &req
->req_file
);
2465 req
->req_file
->url
= url
;
2467 req
->hCacheFile
= CreateFileW(file_name
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2468 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2469 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2470 WARN("Could not create file: %u\n", GetLastError());
2471 req
->hCacheFile
= NULL
;
2475 if(req
->read_size
) {
2478 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2480 FIXME("WriteFile failed: %u\n", GetLastError());
2482 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2483 commit_cache_entry(req
);
2487 /* read some more data into the read buffer (the read section must be held) */
2488 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2495 /* move existing data to the start of the buffer */
2497 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2501 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2503 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2504 maxlen
- req
->read_size
, TRUE
, &len
);
2505 if(res
== ERROR_SUCCESS
)
2506 req
->read_size
+= len
;
2511 /* remove some amount of data from the read buffer (the read section must be held) */
2512 static void remove_data( http_request_t
*req
, int count
)
2514 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2515 else req
->read_pos
+= count
;
2518 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2520 int count
, bytes_read
, pos
= 0;
2523 EnterCriticalSection( &req
->read_section
);
2526 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2530 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2531 bytes_read
= count
+ 1;
2533 else count
= bytes_read
= req
->read_size
;
2535 count
= min( count
, *len
- pos
);
2536 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2538 remove_data( req
, bytes_read
);
2541 if ((res
= read_more_data( req
, -1 )))
2543 WARN( "read failed %u\n", res
);
2544 LeaveCriticalSection( &req
->read_section
);
2547 if (!req
->read_size
)
2550 TRACE( "returning empty string\n" );
2551 LeaveCriticalSection( &req
->read_section
);
2552 return ERROR_SUCCESS
;
2555 LeaveCriticalSection( &req
->read_section
);
2559 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2562 buffer
[*len
- 1] = 0;
2563 TRACE( "returning %s\n", debugstr_a(buffer
));
2564 return ERROR_SUCCESS
;
2567 /* check if we have reached the end of the data to read (the read section must be held) */
2568 static BOOL
end_of_read_data( http_request_t
*req
)
2570 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2573 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, blocking_mode_t blocking_mode
)
2577 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, blocking_mode
);
2578 assert(*read
<= size
);
2580 if(req
->hCacheFile
) {
2585 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2587 FIXME("WriteFile failed: %u\n", GetLastError());
2590 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2591 commit_cache_entry(req
);
2597 /* fetch some more data into the read buffer (the read section must be held) */
2598 static DWORD
refill_read_buffer(http_request_t
*req
, blocking_mode_t blocking_mode
, DWORD
*read_bytes
)
2602 if(req
->read_size
== sizeof(req
->read_buf
))
2603 return ERROR_SUCCESS
;
2607 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2611 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2612 &read
, blocking_mode
);
2613 req
->read_size
+= read
;
2615 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2621 /* return the size of data available to be read immediately (the read section must be held) */
2622 static DWORD
get_avail_data( http_request_t
*req
)
2624 DWORD avail
= req
->read_size
;
2627 * Different Windows versions have different limits of returned data, but all
2628 * of them return no more than centrain amount. We use READ_BUFFER_SIZE as a limit.
2630 if(avail
< READ_BUFFER_SIZE
)
2631 avail
+= req
->data_stream
->vtbl
->get_avail_data(req
->data_stream
, req
);
2633 return min(avail
, READ_BUFFER_SIZE
);
2636 static DWORD
netconn_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2638 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2641 if(is_valid_netconn(req
->netconn
))
2642 NETCON_query_data_available(req
->netconn
, &avail
);
2643 return netconn_stream
->content_length
== ~0u
2645 : min(avail
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2648 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2650 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2651 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !is_valid_netconn(req
->netconn
);
2654 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2655 DWORD
*read
, blocking_mode_t blocking_mode
)
2657 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2658 DWORD res
= ERROR_SUCCESS
;
2659 int len
= 0, ret
= 0;
2661 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2663 if(size
&& is_valid_netconn(req
->netconn
)) {
2664 while((res
= NETCON_recv(req
->netconn
, buf
+ret
, size
-ret
, blocking_mode
!= BLOCKING_DISALLOW
, &len
)) == ERROR_SUCCESS
) {
2666 netconn_stream
->content_length
= netconn_stream
->content_read
;
2670 netconn_stream
->content_read
+= len
;
2671 if(blocking_mode
!= BLOCKING_WAITALL
|| size
== ret
)
2675 if(ret
|| (blocking_mode
== BLOCKING_DISALLOW
&& res
== WSAEWOULDBLOCK
))
2676 res
= ERROR_SUCCESS
;
2679 TRACE("read %u bytes\n", ret
);
2684 static BOOL
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2686 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2690 if(netconn_end_of_data(stream
, req
))
2694 if(NETCON_recv(req
->netconn
, buf
, sizeof(buf
), FALSE
, &len
) != ERROR_SUCCESS
)
2697 netconn_stream
->content_read
+= len
;
2698 }while(netconn_stream
->content_read
< netconn_stream
->content_length
);
2703 static void netconn_destroy(data_stream_t
*stream
)
2707 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2708 netconn_get_avail_data
,
2709 netconn_end_of_data
,
2711 netconn_drain_content
,
2715 static char next_chunked_data_char(chunked_stream_t
*stream
)
2717 assert(stream
->buf_size
);
2720 return stream
->buf
[stream
->buf_pos
++];
2723 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2725 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2726 return chunked_stream
->state
== CHUNKED_STREAM_STATE_END_OF_STREAM
;
2729 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2730 DWORD
*read
, blocking_mode_t blocking_mode
)
2732 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2733 DWORD ret_read
= 0, res
= ERROR_SUCCESS
;
2734 BOOL continue_read
= TRUE
;
2739 TRACE("state %d\n", chunked_stream
->state
);
2741 /* Ensure that we have data in the buffer for states that need it. */
2742 if(!chunked_stream
->buf_size
) {
2743 switch(chunked_stream
->state
) {
2744 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
:
2745 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
:
2746 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
:
2747 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2748 chunked_stream
->buf_pos
= 0;
2749 res
= NETCON_recv(req
->netconn
, chunked_stream
->buf
, sizeof(chunked_stream
->buf
), blocking_mode
!= BLOCKING_DISALLOW
, &read_bytes
);
2750 if(res
== ERROR_SUCCESS
&& read_bytes
) {
2751 chunked_stream
->buf_size
+= read_bytes
;
2752 }else if(res
== WSAEWOULDBLOCK
) {
2753 continue_read
= FALSE
;
2756 chunked_stream
->state
= CHUNKED_STREAM_STATE_END_OF_STREAM
;
2764 switch(chunked_stream
->state
) {
2765 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
:
2766 ch
= next_chunked_data_char(chunked_stream
);
2768 if(ch
>= '0' && ch
<= '9') {
2769 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- '0';
2770 }else if(ch
>= 'a' && ch
<= 'f') {
2771 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- 'a' + 10;
2772 }else if (ch
>= 'A' && ch
<= 'F') {
2773 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- 'A' + 10;
2774 }else if (ch
== ';' || ch
== '\r' || ch
== '\n') {
2775 TRACE("reading %u byte chunk\n", chunked_stream
->chunk_size
);
2776 chunked_stream
->buf_size
++;
2777 chunked_stream
->buf_pos
--;
2778 if(req
->contentLength
== ~0u) req
->contentLength
= chunked_stream
->chunk_size
;
2779 else req
->contentLength
+= chunked_stream
->chunk_size
;
2780 chunked_stream
->state
= CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
;
2784 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
:
2785 ch
= next_chunked_data_char(chunked_stream
);
2787 chunked_stream
->state
= chunked_stream
->chunk_size
2788 ? CHUNKED_STREAM_STATE_READING_CHUNK
2789 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
;
2791 WARN("unexpected char '%c'\n", ch
);
2794 case CHUNKED_STREAM_STATE_READING_CHUNK
:
2795 assert(chunked_stream
->chunk_size
);
2797 continue_read
= FALSE
;
2800 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2802 if(chunked_stream
->buf_size
) {
2803 if(read_bytes
> chunked_stream
->buf_size
)
2804 read_bytes
= chunked_stream
->buf_size
;
2806 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2807 chunked_stream
->buf_pos
+= read_bytes
;
2808 chunked_stream
->buf_size
-= read_bytes
;
2810 res
= NETCON_recv(req
->netconn
, (char*)buf
+ret_read
, read_bytes
,
2811 blocking_mode
!= BLOCKING_DISALLOW
, (int*)&read_bytes
);
2812 if(res
!= ERROR_SUCCESS
) {
2813 continue_read
= FALSE
;
2818 chunked_stream
->state
= CHUNKED_STREAM_STATE_END_OF_STREAM
;
2823 chunked_stream
->chunk_size
-= read_bytes
;
2825 ret_read
+= read_bytes
;
2826 if(!chunked_stream
->chunk_size
)
2827 chunked_stream
->state
= CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
;
2828 if(blocking_mode
== BLOCKING_ALLOW
)
2829 blocking_mode
= BLOCKING_DISALLOW
;
2832 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
:
2833 ch
= next_chunked_data_char(chunked_stream
);
2835 chunked_stream
->state
= CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
;
2837 WARN("unexpected char '%c'\n", ch
);
2840 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2841 ch
= next_chunked_data_char(chunked_stream
);
2843 chunked_stream
->state
= CHUNKED_STREAM_STATE_END_OF_STREAM
;
2845 WARN("unexpected char '%c'\n", ch
);
2848 case CHUNKED_STREAM_STATE_END_OF_STREAM
:
2849 continue_read
= FALSE
;
2852 } while(continue_read
);
2855 res
= ERROR_SUCCESS
;
2856 if(res
!= ERROR_SUCCESS
&& res
!= WSAEWOULDBLOCK
)
2859 TRACE("read %d bytes\n", ret_read
);
2861 return ERROR_SUCCESS
;
2864 static DWORD
chunked_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2866 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2869 if(chunked_stream
->state
!= CHUNKED_STREAM_STATE_READING_CHUNK
) {
2872 /* try to process to the next chunk */
2873 res
= chunked_read(stream
, req
, NULL
, 0, &read
, BLOCKING_DISALLOW
);
2874 if(res
!= ERROR_SUCCESS
|| chunked_stream
->state
!= CHUNKED_STREAM_STATE_READING_CHUNK
)
2878 if(is_valid_netconn(req
->netconn
) && chunked_stream
->buf_size
< chunked_stream
->chunk_size
)
2879 NETCON_query_data_available(req
->netconn
, &avail
);
2881 return min(avail
+ chunked_stream
->buf_size
, chunked_stream
->chunk_size
);
2884 static BOOL
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2886 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2887 return chunked_stream
->state
== CHUNKED_STREAM_STATE_END_OF_STREAM
;
2890 static void chunked_destroy(data_stream_t
*stream
)
2892 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2893 heap_free(chunked_stream
);
2896 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2897 chunked_get_avail_data
,
2898 chunked_end_of_data
,
2900 chunked_drain_content
,
2904 /* set the request content length based on the headers */
2905 static DWORD
set_content_length(http_request_t
*request
)
2907 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2908 static const WCHAR headW
[] = {'H','E','A','D',0};
2912 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
|| !strcmpW(request
->verb
, headW
)) {
2913 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2914 return ERROR_SUCCESS
;
2917 size
= sizeof(request
->contentLength
);
2918 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2919 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2920 request
->contentLength
= ~0u;
2921 request
->netconn_stream
.content_length
= request
->contentLength
;
2922 request
->netconn_stream
.content_read
= request
->read_size
;
2924 size
= sizeof(encoding
);
2925 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2926 !strcmpiW(encoding
, szChunked
))
2928 chunked_stream_t
*chunked_stream
;
2930 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2932 return ERROR_OUTOFMEMORY
;
2934 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2935 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2936 chunked_stream
->chunk_size
= 0;
2937 chunked_stream
->state
= CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
;
2939 if(request
->read_size
) {
2940 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2941 chunked_stream
->buf_size
= request
->read_size
;
2942 request
->read_size
= request
->read_pos
= 0;
2945 request
->data_stream
= &chunked_stream
->data_stream
;
2946 request
->contentLength
= ~0u;
2949 if(request
->decoding
) {
2952 static const WCHAR deflateW
[] = {'d','e','f','l','a','t','e',0};
2953 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2955 EnterCriticalSection( &request
->headers_section
);
2957 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2958 if(encoding_idx
!= -1) {
2959 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2960 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2961 LeaveCriticalSection( &request
->headers_section
);
2962 return init_gzip_stream(request
, TRUE
);
2964 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, deflateW
)) {
2965 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2966 LeaveCriticalSection( &request
->headers_section
);
2967 return init_gzip_stream(request
, FALSE
);
2971 LeaveCriticalSection( &request
->headers_section
);
2974 return ERROR_SUCCESS
;
2977 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
2979 INTERNET_ASYNC_RESULT iar
;
2981 iar
.dwResult
= result
;
2982 iar
.dwError
= error
;
2984 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
2985 sizeof(INTERNET_ASYNC_RESULT
));
2988 static void HTTP_ReceiveRequestData(http_request_t
*req
, BOOL first_notif
, DWORD
*ret_size
)
2990 DWORD res
, read
= 0, avail
= 0;
2991 blocking_mode_t mode
;
2995 EnterCriticalSection( &req
->read_section
);
2997 mode
= first_notif
&& req
->read_size
? BLOCKING_DISALLOW
: BLOCKING_ALLOW
;
2998 res
= refill_read_buffer(req
, mode
, &read
);
2999 if(res
== ERROR_SUCCESS
)
3000 avail
= get_avail_data(req
);
3002 LeaveCriticalSection( &req
->read_section
);
3004 if(res
!= ERROR_SUCCESS
|| (mode
!= BLOCKING_DISALLOW
&& !read
)) {
3005 WARN("res %u read %u, closing connection\n", res
, read
);
3006 http_release_netconn(req
, FALSE
);
3009 if(res
!= ERROR_SUCCESS
) {
3010 send_request_complete(req
, 0, res
);
3019 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, avail
);
3022 /* read data from the http connection (the read section must be held) */
3023 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
)
3025 DWORD current_read
= 0, ret_read
= 0;
3026 blocking_mode_t blocking_mode
;
3027 DWORD res
= ERROR_SUCCESS
;
3029 blocking_mode
= req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
? BLOCKING_ALLOW
: BLOCKING_WAITALL
;
3031 EnterCriticalSection( &req
->read_section
);
3033 if(req
->read_size
) {
3034 ret_read
= min(size
, req
->read_size
);
3035 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
3036 req
->read_size
-= ret_read
;
3037 req
->read_pos
+= ret_read
;
3038 if(blocking_mode
== BLOCKING_ALLOW
)
3039 blocking_mode
= BLOCKING_DISALLOW
;
3042 if(ret_read
< size
) {
3043 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, blocking_mode
);
3044 ret_read
+= current_read
;
3047 LeaveCriticalSection( &req
->read_section
);
3050 TRACE( "retrieved %u bytes (%u)\n", ret_read
, req
->contentLength
);
3052 if(size
&& !ret_read
)
3053 http_release_netconn(req
, res
== ERROR_SUCCESS
);
3058 static BOOL
drain_content(http_request_t
*req
, BOOL blocking
)
3062 if(!is_valid_netconn(req
->netconn
) || req
->contentLength
== -1)
3065 if(!strcmpW(req
->verb
, szHEAD
))
3069 return req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
);
3071 EnterCriticalSection( &req
->read_section
);
3074 DWORD bytes_read
, res
;
3077 res
= HTTPREQ_Read(req
, buf
, sizeof(buf
), &bytes_read
);
3078 if(res
!= ERROR_SUCCESS
) {
3088 LeaveCriticalSection( &req
->read_section
);
3097 } read_file_ex_task_t
;
3099 static void AsyncReadFileExProc(task_header_t
*hdr
)
3101 read_file_ex_task_t
*task
= (read_file_ex_task_t
*)hdr
;
3102 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3103 DWORD res
= ERROR_SUCCESS
, read
= 0, buffered
= 0;
3108 res
= HTTPREQ_Read(req
, task
->buf
, task
->size
, &read
);
3109 if(res
== ERROR_SUCCESS
)
3110 res
= refill_read_buffer(req
, task
->ret_read
? BLOCKING_DISALLOW
: BLOCKING_ALLOW
, &buffered
);
3111 if (res
== ERROR_SUCCESS
)
3114 *task
->ret_read
= read
;
3116 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3117 &read
, sizeof(read
));
3120 send_request_complete(req
, res
== ERROR_SUCCESS
, res
);
3123 static DWORD
HTTPREQ_ReadFileEx(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3124 DWORD flags
, DWORD_PTR context
)
3127 http_request_t
*req
= (http_request_t
*)hdr
;
3128 DWORD res
, read
, cread
, error
= ERROR_SUCCESS
;
3130 TRACE("(%p %p %u %x)\n", req
, buf
, size
, flags
);
3132 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3133 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3135 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3137 if (req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
3139 read_file_ex_task_t
*task
;
3141 if (TryEnterCriticalSection( &req
->read_section
))
3143 if (get_avail_data(req
) || end_of_read_data(req
))
3145 res
= HTTPREQ_Read(req
, buf
, size
, &read
);
3146 LeaveCriticalSection( &req
->read_section
);
3149 LeaveCriticalSection( &req
->read_section
);
3152 task
= alloc_async_task(&req
->hdr
, AsyncReadFileExProc
, sizeof(*task
));
3155 task
->ret_read
= (flags
& IRF_NO_WAIT
) ? NULL
: ret_read
;
3157 INTERNET_AsyncCall(&task
->hdr
);
3159 return ERROR_IO_PENDING
;
3164 EnterCriticalSection( &req
->read_section
);
3165 if(hdr
->dwError
== ERROR_SUCCESS
)
3166 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3167 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3168 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3171 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
);
3172 if(res
!= ERROR_SUCCESS
)
3176 if(read
== size
|| end_of_read_data(req
))
3179 LeaveCriticalSection( &req
->read_section
);
3181 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3182 &cread
, sizeof(cread
));
3183 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
3184 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3186 EnterCriticalSection( &req
->read_section
);
3189 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3190 hdr
->dwError
= ERROR_SUCCESS
;
3192 error
= hdr
->dwError
;
3194 LeaveCriticalSection( &req
->read_section
);
3198 if (res
== ERROR_SUCCESS
) {
3199 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3200 &read
, sizeof(read
));
3203 return res
==ERROR_SUCCESS
? error
: res
;
3206 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3209 http_request_t
*request
= (http_request_t
*)hdr
;
3211 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3214 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3215 if (res
== ERROR_SUCCESS
)
3216 request
->bytesWritten
+= *written
;
3218 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3222 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buffer
, DWORD size
, DWORD
*read
)
3224 http_request_t
*req
= (http_request_t
*)hdr
;
3227 if (req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
3229 read_file_ex_task_t
*task
;
3231 if (TryEnterCriticalSection( &req
->read_section
))
3233 if (get_avail_data(req
) || end_of_read_data(req
))
3235 res
= HTTPREQ_Read(req
, buffer
, size
, read
);
3236 LeaveCriticalSection( &req
->read_section
);
3239 LeaveCriticalSection( &req
->read_section
);
3242 task
= alloc_async_task(&req
->hdr
, AsyncReadFileExProc
, sizeof(*task
));
3245 task
->ret_read
= read
;
3248 INTERNET_AsyncCall(&task
->hdr
);
3250 return ERROR_IO_PENDING
;
3253 EnterCriticalSection( &req
->read_section
);
3254 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3255 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3257 res
= HTTPREQ_Read(req
, buffer
, size
, read
);
3258 if(res
== ERROR_SUCCESS
)
3260 LeaveCriticalSection( &req
->read_section
);
3268 } http_data_available_task_t
;
3270 static void AsyncQueryDataAvailableProc(task_header_t
*hdr
)
3272 http_data_available_task_t
*task
= (http_data_available_task_t
*)hdr
;
3274 HTTP_ReceiveRequestData((http_request_t
*)task
->hdr
.hdr
, FALSE
, task
->ret_size
);
3277 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3279 http_request_t
*req
= (http_request_t
*)hdr
;
3281 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3283 if (req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
3285 http_data_available_task_t
*task
;
3287 /* never wait, if we can't enter the section we queue an async request right away */
3288 if (TryEnterCriticalSection( &req
->read_section
))
3290 refill_read_buffer(req
, BLOCKING_DISALLOW
, NULL
);
3291 if ((*available
= get_avail_data( req
))) goto done
;
3292 if (end_of_read_data( req
)) goto done
;
3293 LeaveCriticalSection( &req
->read_section
);
3296 task
= alloc_async_task(&req
->hdr
, AsyncQueryDataAvailableProc
, sizeof(*task
));
3297 task
->ret_size
= available
;
3298 INTERNET_AsyncCall(&task
->hdr
);
3299 return ERROR_IO_PENDING
;
3302 EnterCriticalSection( &req
->read_section
);
3304 if (!(*available
= get_avail_data( req
)) && !end_of_read_data( req
))
3306 refill_read_buffer( req
, BLOCKING_ALLOW
, NULL
);
3307 *available
= get_avail_data( req
);
3311 LeaveCriticalSection( &req
->read_section
);
3313 TRACE( "returning %u\n", *available
);
3314 return ERROR_SUCCESS
;
3317 static DWORD
HTTPREQ_LockRequestFile(object_header_t
*hdr
, req_file_t
**ret
)
3319 http_request_t
*req
= (http_request_t
*)hdr
;
3321 TRACE("(%p)\n", req
);
3323 if(!req
->req_file
) {
3324 WARN("No cache file name available\n");
3325 return ERROR_FILE_NOT_FOUND
;
3328 *ret
= req_file_addref(req
->req_file
);
3329 return ERROR_SUCCESS
;
3332 static const object_vtbl_t HTTPREQVtbl
= {
3334 HTTPREQ_CloseConnection
,
3335 HTTPREQ_QueryOption
,
3340 HTTPREQ_QueryDataAvailable
,
3342 HTTPREQ_LockRequestFile
3345 /***********************************************************************
3346 * HTTP_HttpOpenRequestW (internal)
3348 * Open a HTTP request handle
3351 * HINTERNET a HTTP request handle on success
3355 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3356 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3357 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3358 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3360 appinfo_t
*hIC
= session
->appInfo
;
3361 http_request_t
*request
;
3366 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3368 return ERROR_OUTOFMEMORY
;
3370 request
->hdr
.htype
= WH_HHTTPREQ
;
3371 request
->hdr
.dwFlags
= dwFlags
;
3372 request
->hdr
.dwContext
= dwContext
;
3373 request
->contentLength
= ~0u;
3375 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3376 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3377 request
->connect_timeout
= session
->connect_timeout
;
3378 request
->send_timeout
= session
->send_timeout
;
3379 request
->receive_timeout
= session
->receive_timeout
;
3381 InitializeCriticalSection( &request
->headers_section
);
3382 request
->headers_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.headers_section");
3384 InitializeCriticalSection( &request
->read_section
);
3385 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3387 WININET_AddRef( &session
->hdr
);
3388 request
->session
= session
;
3389 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3391 request
->server
= get_server(substrz(session
->hostName
), session
->hostPort
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3392 if(!request
->server
) {
3393 WININET_Release(&request
->hdr
);
3394 return ERROR_OUTOFMEMORY
;
3397 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3398 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3399 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3400 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3402 if (lpszObjectName
&& *lpszObjectName
) {
3406 rc
= UrlEscapeW(lpszObjectName
, NULL
, &len
, URL_ESCAPE_SPACES_ONLY
);
3407 if (rc
!= E_POINTER
)
3408 len
= strlenW(lpszObjectName
)+1;
3409 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3410 rc
= UrlEscapeW(lpszObjectName
, request
->path
, &len
,
3411 URL_ESCAPE_SPACES_ONLY
);
3414 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3415 strcpyW(request
->path
,lpszObjectName
);
3418 static const WCHAR slashW
[] = {'/',0};
3420 request
->path
= heap_strdupW(slashW
);
3423 if (lpszReferrer
&& *lpszReferrer
)
3424 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3426 if (lpszAcceptTypes
)
3429 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3431 if (!*lpszAcceptTypes
[i
]) continue;
3432 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3433 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3434 HTTP_ADDHDR_FLAG_REQ
|
3435 (i
== 0 ? (HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
) : 0));
3439 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3440 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3442 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3443 HTTP_DealWithProxy( hIC
, session
, request
);
3445 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3446 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3449 TRACE("<-- (%p)\n", request
);
3451 *ret
= request
->hdr
.hInternet
;
3452 return ERROR_SUCCESS
;
3455 /***********************************************************************
3456 * HttpOpenRequestW (WININET.@)
3458 * Open a HTTP request handle
3461 * HINTERNET a HTTP request handle on success
3465 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3466 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3467 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3468 DWORD dwFlags
, DWORD_PTR dwContext
)
3470 http_session_t
*session
;
3471 HINTERNET handle
= NULL
;
3474 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3475 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3476 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3477 dwFlags
, dwContext
);
3478 if(lpszAcceptTypes
!=NULL
)
3481 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3482 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3485 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3486 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3488 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3493 * My tests seem to show that the windows version does not
3494 * become asynchronous until after this point. And anyhow
3495 * if this call was asynchronous then how would you get the
3496 * necessary HINTERNET pointer returned by this function.
3499 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3500 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3501 dwFlags
, dwContext
, &handle
);
3504 WININET_Release( &session
->hdr
);
3505 TRACE("returning %p\n", handle
);
3506 if(res
!= ERROR_SUCCESS
)
3511 static const LPCWSTR header_lookup
[] = {
3512 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3513 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3514 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3515 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3516 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3517 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3518 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3519 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3520 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3521 szDate
, /* HTTP_QUERY_DATE = 9 */
3522 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3523 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3524 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3525 szURI
, /* HTTP_QUERY_URI = 13 */
3526 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3527 NULL
, /* HTTP_QUERY_COST = 15 */
3528 NULL
, /* HTTP_QUERY_LINK = 16 */
3529 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3530 NULL
, /* HTTP_QUERY_VERSION = 18 */
3531 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3532 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3533 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3534 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3535 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3536 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3537 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3538 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3539 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3540 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3541 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3542 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3543 NULL
, /* HTTP_QUERY_FROM = 31 */
3544 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3545 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3546 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3547 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3548 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3549 szServer
, /* HTTP_QUERY_SERVER = 37 */
3550 NULL
, /* HTTP_TITLE = 38 */
3551 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3552 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3553 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3554 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3555 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3556 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3557 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3558 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3559 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3560 szAge
, /* HTTP_QUERY_AGE = 48 */
3561 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3562 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3563 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3564 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3565 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3566 szETag
, /* HTTP_QUERY_ETAG = 54 */
3567 hostW
, /* HTTP_QUERY_HOST = 55 */
3568 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3569 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3570 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3571 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3572 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3573 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3574 szRange
, /* HTTP_QUERY_RANGE = 62 */
3575 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3576 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3577 szVary
, /* HTTP_QUERY_VARY = 65 */
3578 szVia
, /* HTTP_QUERY_VIA = 66 */
3579 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3580 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3581 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3582 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3585 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3587 /***********************************************************************
3588 * HTTP_HttpQueryInfoW (internal)
3590 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3591 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3593 LPHTTPHEADERW lphttpHdr
= NULL
;
3594 BOOL request_only
= !!(dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
);
3595 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3596 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3599 EnterCriticalSection( &request
->headers_section
);
3601 /* Find requested header structure */
3604 case HTTP_QUERY_CUSTOM
:
3607 LeaveCriticalSection( &request
->headers_section
);
3608 return ERROR_INVALID_PARAMETER
;
3610 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3612 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3616 DWORD res
= ERROR_INVALID_PARAMETER
;
3619 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3621 headers
= build_response_header(request
, TRUE
);
3624 LeaveCriticalSection( &request
->headers_section
);
3625 return ERROR_OUTOFMEMORY
;
3628 len
= strlenW(headers
) * sizeof(WCHAR
);
3629 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3631 len
+= sizeof(WCHAR
);
3632 res
= ERROR_INSUFFICIENT_BUFFER
;
3636 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3637 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3638 res
= ERROR_SUCCESS
;
3640 *lpdwBufferLength
= len
;
3643 LeaveCriticalSection( &request
->headers_section
);
3646 case HTTP_QUERY_RAW_HEADERS
:
3652 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3654 headers
= build_response_header(request
, FALSE
);
3658 LeaveCriticalSection( &request
->headers_section
);
3659 return ERROR_OUTOFMEMORY
;
3662 len
= strlenW(headers
) * sizeof(WCHAR
);
3663 if (len
> *lpdwBufferLength
)
3665 *lpdwBufferLength
= len
;
3667 LeaveCriticalSection( &request
->headers_section
);
3668 return ERROR_INSUFFICIENT_BUFFER
;
3675 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3677 for (i
= 0; i
< len
/ sizeof(WCHAR
); i
++)
3679 if (headers
[i
] == '\n')
3682 memcpy(lpBuffer
, headers
, len
);
3684 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3687 LeaveCriticalSection( &request
->headers_section
);
3688 return ERROR_SUCCESS
;
3690 case HTTP_QUERY_STATUS_TEXT
:
3691 if (request
->statusText
)
3693 DWORD len
= strlenW(request
->statusText
);
3694 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3696 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3697 LeaveCriticalSection( &request
->headers_section
);
3698 return ERROR_INSUFFICIENT_BUFFER
;
3702 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3703 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3705 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3706 LeaveCriticalSection( &request
->headers_section
);
3707 return ERROR_SUCCESS
;
3710 case HTTP_QUERY_VERSION
:
3711 if (request
->version
)
3713 DWORD len
= strlenW(request
->version
);
3714 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3716 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3717 LeaveCriticalSection( &request
->headers_section
);
3718 return ERROR_INSUFFICIENT_BUFFER
;
3722 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3723 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3725 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3726 LeaveCriticalSection( &request
->headers_section
);
3727 return ERROR_SUCCESS
;
3730 case HTTP_QUERY_CONTENT_ENCODING
:
3731 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3732 requested_index
,request_only
);
3734 case HTTP_QUERY_STATUS_CODE
: {
3735 DWORD res
= ERROR_SUCCESS
;
3739 LeaveCriticalSection( &request
->headers_section
);
3740 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3746 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3747 if(*lpdwBufferLength
>= sizeof(DWORD
))
3748 *(DWORD
*)lpBuffer
= request
->status_code
;
3750 res
= ERROR_INSUFFICIENT_BUFFER
;
3751 *lpdwBufferLength
= sizeof(DWORD
);
3755 static const WCHAR formatW
[] = {'%','u',0};
3757 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3759 if(size
<= *lpdwBufferLength
) {
3760 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3762 size
+= sizeof(WCHAR
);
3763 res
= ERROR_INSUFFICIENT_BUFFER
;
3766 *lpdwBufferLength
= size
;
3768 LeaveCriticalSection( &request
->headers_section
);
3772 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3774 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3775 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3776 requested_index
,request_only
);
3780 lphttpHdr
= &request
->custHeaders
[index
];
3782 /* Ensure header satisfies requested attributes */
3784 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3785 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3787 LeaveCriticalSection( &request
->headers_section
);
3788 return ERROR_HTTP_HEADER_NOT_FOUND
;
3791 /* coalesce value to requested type */
3792 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3794 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3795 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3797 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3803 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3805 tmpTM
= *gmtime(&tmpTime
);
3806 STHook
= (SYSTEMTIME
*)lpBuffer
;
3807 STHook
->wDay
= tmpTM
.tm_mday
;
3808 STHook
->wHour
= tmpTM
.tm_hour
;
3809 STHook
->wMilliseconds
= 0;
3810 STHook
->wMinute
= tmpTM
.tm_min
;
3811 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3812 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3813 STHook
->wSecond
= tmpTM
.tm_sec
;
3814 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3816 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3817 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3818 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3820 else if (lphttpHdr
->lpszValue
)
3822 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3824 if (len
> *lpdwBufferLength
)
3826 *lpdwBufferLength
= len
;
3827 LeaveCriticalSection( &request
->headers_section
);
3828 return ERROR_INSUFFICIENT_BUFFER
;
3832 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3833 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3835 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3837 if (lpdwIndex
) (*lpdwIndex
)++;
3839 LeaveCriticalSection( &request
->headers_section
);
3840 return ERROR_SUCCESS
;
3843 /***********************************************************************
3844 * HttpQueryInfoW (WININET.@)
3846 * Queries for information about an HTTP request
3853 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3854 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3856 http_request_t
*request
;
3859 if (TRACE_ON(wininet
)) {
3860 #define FE(x) { x, #x }
3861 static const wininet_flag_info query_flags
[] = {
3862 FE(HTTP_QUERY_MIME_VERSION
),
3863 FE(HTTP_QUERY_CONTENT_TYPE
),
3864 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3865 FE(HTTP_QUERY_CONTENT_ID
),
3866 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3867 FE(HTTP_QUERY_CONTENT_LENGTH
),
3868 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3869 FE(HTTP_QUERY_ALLOW
),
3870 FE(HTTP_QUERY_PUBLIC
),
3871 FE(HTTP_QUERY_DATE
),
3872 FE(HTTP_QUERY_EXPIRES
),
3873 FE(HTTP_QUERY_LAST_MODIFIED
),
3874 FE(HTTP_QUERY_MESSAGE_ID
),
3876 FE(HTTP_QUERY_DERIVED_FROM
),
3877 FE(HTTP_QUERY_COST
),
3878 FE(HTTP_QUERY_LINK
),
3879 FE(HTTP_QUERY_PRAGMA
),
3880 FE(HTTP_QUERY_VERSION
),
3881 FE(HTTP_QUERY_STATUS_CODE
),
3882 FE(HTTP_QUERY_STATUS_TEXT
),
3883 FE(HTTP_QUERY_RAW_HEADERS
),
3884 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3885 FE(HTTP_QUERY_CONNECTION
),
3886 FE(HTTP_QUERY_ACCEPT
),
3887 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3888 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3889 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3890 FE(HTTP_QUERY_AUTHORIZATION
),
3891 FE(HTTP_QUERY_CONTENT_ENCODING
),
3892 FE(HTTP_QUERY_FORWARDED
),
3893 FE(HTTP_QUERY_FROM
),
3894 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3895 FE(HTTP_QUERY_LOCATION
),
3896 FE(HTTP_QUERY_ORIG_URI
),
3897 FE(HTTP_QUERY_REFERER
),
3898 FE(HTTP_QUERY_RETRY_AFTER
),
3899 FE(HTTP_QUERY_SERVER
),
3900 FE(HTTP_QUERY_TITLE
),
3901 FE(HTTP_QUERY_USER_AGENT
),
3902 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3903 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3904 FE(HTTP_QUERY_ACCEPT_RANGES
),
3905 FE(HTTP_QUERY_SET_COOKIE
),
3906 FE(HTTP_QUERY_COOKIE
),
3907 FE(HTTP_QUERY_REQUEST_METHOD
),
3908 FE(HTTP_QUERY_REFRESH
),
3909 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3911 FE(HTTP_QUERY_CACHE_CONTROL
),
3912 FE(HTTP_QUERY_CONTENT_BASE
),
3913 FE(HTTP_QUERY_CONTENT_LOCATION
),
3914 FE(HTTP_QUERY_CONTENT_MD5
),
3915 FE(HTTP_QUERY_CONTENT_RANGE
),
3916 FE(HTTP_QUERY_ETAG
),
3917 FE(HTTP_QUERY_HOST
),
3918 FE(HTTP_QUERY_IF_MATCH
),
3919 FE(HTTP_QUERY_IF_NONE_MATCH
),
3920 FE(HTTP_QUERY_IF_RANGE
),
3921 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3922 FE(HTTP_QUERY_MAX_FORWARDS
),
3923 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3924 FE(HTTP_QUERY_RANGE
),
3925 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3926 FE(HTTP_QUERY_UPGRADE
),
3927 FE(HTTP_QUERY_VARY
),
3929 FE(HTTP_QUERY_WARNING
),
3930 FE(HTTP_QUERY_CUSTOM
)
3932 static const wininet_flag_info modifier_flags
[] = {
3933 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3934 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3935 FE(HTTP_QUERY_FLAG_NUMBER
),
3936 FE(HTTP_QUERY_FLAG_COALESCE
)
3939 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3940 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3943 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3944 TRACE(" Attribute:");
3945 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3946 if (query_flags
[i
].val
== info
) {
3947 TRACE(" %s", query_flags
[i
].name
);
3951 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3952 TRACE(" Unknown (%08x)", info
);
3955 TRACE(" Modifier:");
3956 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3957 if (modifier_flags
[i
].val
& info_mod
) {
3958 TRACE(" %s", modifier_flags
[i
].name
);
3959 info_mod
&= ~ modifier_flags
[i
].val
;
3964 TRACE(" Unknown (%08x)", info_mod
);
3969 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3970 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3972 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3976 if (lpBuffer
== NULL
)
3977 *lpdwBufferLength
= 0;
3978 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3979 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3983 WININET_Release( &request
->hdr
);
3985 TRACE("%u <--\n", res
);
3986 if(res
!= ERROR_SUCCESS
)
3988 return res
== ERROR_SUCCESS
;
3991 /***********************************************************************
3992 * HttpQueryInfoA (WININET.@)
3994 * Queries for information about an HTTP request
4001 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
4002 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
4008 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
4010 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
4011 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
4013 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
4014 lpdwBufferLength
, lpdwIndex
);
4020 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
4021 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
4023 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
4029 bufferW
= heap_alloc(alloclen
);
4030 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
4031 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
4032 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
4039 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
4043 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
4044 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
4045 *lpdwBufferLength
= len
- 1;
4047 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
4050 /* since the strings being returned from HttpQueryInfoW should be
4051 * only ASCII characters, it is reasonable to assume that all of
4052 * the Unicode characters can be reduced to a single byte */
4053 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
4055 heap_free( bufferW
);
4059 static WCHAR
*get_redirect_url(http_request_t
*request
)
4061 static WCHAR szHttp
[] = {'h','t','t','p',0};
4062 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
4063 http_session_t
*session
= request
->session
;
4064 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
4065 WCHAR
*orig_url
= NULL
, *redirect_url
= NULL
, *combined_url
= NULL
;
4066 DWORD url_length
= 0, res
;
4070 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
4071 if(res
== ERROR_INSUFFICIENT_BUFFER
) {
4072 redirect_url
= heap_alloc(url_length
);
4073 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
4075 if(res
!= ERROR_SUCCESS
) {
4076 heap_free(redirect_url
);
4080 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
4081 urlComponents
.lpszHostName
= request
->server
->name
;
4082 urlComponents
.nPort
= request
->server
->port
;
4083 urlComponents
.lpszUserName
= session
->userName
;
4084 urlComponents
.lpszUrlPath
= request
->path
;
4086 b
= InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
);
4087 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4088 orig_url
= heap_alloc(url_length
);
4090 /* convert from bytes to characters */
4091 url_length
= url_length
/ sizeof(WCHAR
) - 1;
4092 b
= InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
);
4097 b
= InternetCombineUrlW(orig_url
, redirect_url
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4098 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4099 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
4100 b
= InternetCombineUrlW(orig_url
, redirect_url
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4102 heap_free(combined_url
);
4103 combined_url
= NULL
;
4108 heap_free(orig_url
);
4109 heap_free(redirect_url
);
4110 return combined_url
;
4114 /***********************************************************************
4115 * HTTP_HandleRedirect (internal)
4117 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, LPCWSTR lpszUrl
)
4119 http_session_t
*session
= request
->session
;
4124 /* if it's an absolute path, keep the same session info */
4125 path
= heap_strdupW(lpszUrl
);
4129 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
4130 BOOL custom_port
= FALSE
;
4133 urlComponents
.dwHostNameLength
= 1;
4134 urlComponents
.dwUserNameLength
= 1;
4135 urlComponents
.dwUrlPathLength
= 1;
4136 if(!InternetCrackUrlW(lpszUrl
, strlenW(lpszUrl
), 0, &urlComponents
))
4137 return INTERNET_GetLastError();
4139 if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTP
) {
4140 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4141 TRACE("redirect from secure page to non-secure page\n");
4142 /* FIXME: warn about from secure redirect to non-secure page */
4143 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4146 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
;
4147 }else if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
) {
4148 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4149 TRACE("redirect from non-secure page to secure page\n");
4150 /* FIXME: notify about redirect to secure page */
4151 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4154 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
;
4157 heap_free(session
->hostName
);
4159 session
->hostName
= heap_strndupW(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4160 session
->hostPort
= urlComponents
.nPort
;
4162 heap_free(session
->userName
);
4163 session
->userName
= NULL
;
4164 if (urlComponents
.dwUserNameLength
)
4165 session
->userName
= heap_strndupW(urlComponents
.lpszUserName
, urlComponents
.dwUserNameLength
);
4167 reset_data_stream(request
);
4169 host
= substr(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4171 if(host
.len
!= strlenW(request
->server
->name
) || strncmpiW(request
->server
->name
, host
.str
, host
.len
)
4172 || request
->server
->port
!= urlComponents
.nPort
) {
4173 server_t
*new_server
;
4175 new_server
= get_server(host
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4176 server_release(request
->server
);
4177 request
->server
= new_server
;
4181 HTTP_ProcessHeader(request
, hostW
, request
->server
->host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4183 HTTP_ProcessHeader(request
, hostW
, request
->server
->name
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4185 path
= heap_strndupW(urlComponents
.lpszUrlPath
, urlComponents
.dwUrlPathLength
);
4187 heap_free(request
->path
);
4188 request
->path
= NULL
;
4194 rc
= UrlEscapeW(path
, NULL
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4195 if (rc
== E_POINTER
)
4196 needed
= strlenW(path
)+1;
4197 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4198 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4199 URL_ESCAPE_SPACES_ONLY
);
4202 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4203 strcpyW(request
->path
, path
);
4209 /* Remove custom content-type/length headers on redirects. */
4210 remove_header(request
, szContent_Type
, TRUE
);
4211 remove_header(request
, szContent_Length
, TRUE
);
4213 return ERROR_SUCCESS
;
4216 /***********************************************************************
4217 * HTTP_build_req (internal)
4219 * concatenate all the strings in the request together
4221 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4226 for( t
= list
; *t
; t
++ )
4227 len
+= strlenW( *t
);
4230 str
= heap_alloc(len
*sizeof(WCHAR
));
4233 for( t
= list
; *t
; t
++ )
4239 static void HTTP_InsertCookies(http_request_t
*request
)
4244 res
= get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4245 if(res
!= ERROR_SUCCESS
|| !cookies
)
4248 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
),
4249 HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
4253 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4255 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4263 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4264 if (!strcmpiW(day
, days
[i
]))
4271 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4273 static const WCHAR jan
[] = { 'j','a','n',0 };
4274 static const WCHAR feb
[] = { 'f','e','b',0 };
4275 static const WCHAR mar
[] = { 'm','a','r',0 };
4276 static const WCHAR apr
[] = { 'a','p','r',0 };
4277 static const WCHAR may
[] = { 'm','a','y',0 };
4278 static const WCHAR jun
[] = { 'j','u','n',0 };
4279 static const WCHAR jul
[] = { 'j','u','l',0 };
4280 static const WCHAR aug
[] = { 'a','u','g',0 };
4281 static const WCHAR sep
[] = { 's','e','p',0 };
4282 static const WCHAR oct
[] = { 'o','c','t',0 };
4283 static const WCHAR nov
[] = { 'n','o','v',0 };
4284 static const WCHAR dec
[] = { 'd','e','c',0 };
4286 if (!strcmpiW(month
, jan
)) return 1;
4287 if (!strcmpiW(month
, feb
)) return 2;
4288 if (!strcmpiW(month
, mar
)) return 3;
4289 if (!strcmpiW(month
, apr
)) return 4;
4290 if (!strcmpiW(month
, may
)) return 5;
4291 if (!strcmpiW(month
, jun
)) return 6;
4292 if (!strcmpiW(month
, jul
)) return 7;
4293 if (!strcmpiW(month
, aug
)) return 8;
4294 if (!strcmpiW(month
, sep
)) return 9;
4295 if (!strcmpiW(month
, oct
)) return 10;
4296 if (!strcmpiW(month
, nov
)) return 11;
4297 if (!strcmpiW(month
, dec
)) return 12;
4302 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4303 * optionally preceded by whitespace.
4304 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4305 * st, and sets *str to the first character after the time format.
4307 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4313 while (isspaceW(*ptr
))
4316 num
= strtoulW(ptr
, &nextPtr
, 10);
4317 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4319 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4324 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4328 st
->wHour
= (WORD
)num
;
4329 num
= strtoulW(ptr
, &nextPtr
, 10);
4330 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4332 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4337 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4341 st
->wMinute
= (WORD
)num
;
4342 num
= strtoulW(ptr
, &nextPtr
, 10);
4343 if (!nextPtr
|| nextPtr
<= ptr
)
4345 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4350 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4355 st
->wSecond
= (WORD
)num
;
4359 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4361 static const WCHAR gmt
[]= { 'G','M','T',0 };
4362 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4364 SYSTEMTIME st
= { 0 };
4367 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4368 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4371 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4372 if (st
.wDayOfWeek
>= 7)
4374 ERR("unexpected weekday %s\n", debugstr_w(day
));
4378 while (isspaceW(*ptr
))
4381 for (monthPtr
= month
; !isspace(*ptr
) &&
4382 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4386 st
.wMonth
= HTTP_ParseMonth(month
);
4387 if (!st
.wMonth
|| st
.wMonth
> 12)
4389 ERR("unexpected month %s\n", debugstr_w(month
));
4393 while (isspaceW(*ptr
))
4396 num
= strtoulW(ptr
, &nextPtr
, 10);
4397 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4399 ERR("unexpected day %s\n", debugstr_w(ptr
));
4403 st
.wDay
= (WORD
)num
;
4405 while (isspaceW(*ptr
))
4408 if (!HTTP_ParseTime(&st
, &ptr
))
4411 while (isspaceW(*ptr
))
4414 num
= strtoulW(ptr
, &nextPtr
, 10);
4415 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4417 ERR("unexpected year %s\n", debugstr_w(ptr
));
4421 st
.wYear
= (WORD
)num
;
4423 while (isspaceW(*ptr
))
4426 /* asctime() doesn't report a timezone, but some web servers do, so accept
4427 * with or without GMT.
4429 if (*ptr
&& strcmpW(ptr
, gmt
))
4431 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4434 return SystemTimeToFileTime(&st
, ft
);
4437 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4439 static const WCHAR gmt
[]= { 'G','M','T',0 };
4440 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4443 SYSTEMTIME st
= { 0 };
4445 ptr
= strchrW(value
, ',');
4448 if (ptr
- value
!= 3)
4450 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4453 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4455 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4456 if (st
.wDayOfWeek
> 6)
4458 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4463 while (isspaceW(*ptr
))
4466 num
= strtoulW(ptr
, &nextPtr
, 10);
4467 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4469 WARN("unexpected day %s\n", debugstr_w(value
));
4473 st
.wDay
= (WORD
)num
;
4475 while (isspaceW(*ptr
))
4478 for (monthPtr
= month
; !isspace(*ptr
) &&
4479 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4483 st
.wMonth
= HTTP_ParseMonth(month
);
4484 if (!st
.wMonth
|| st
.wMonth
> 12)
4486 WARN("unexpected month %s\n", debugstr_w(month
));
4490 while (isspaceW(*ptr
))
4493 num
= strtoulW(ptr
, &nextPtr
, 10);
4494 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4496 ERR("unexpected year %s\n", debugstr_w(value
));
4500 st
.wYear
= (WORD
)num
;
4502 if (!HTTP_ParseTime(&st
, &ptr
))
4505 while (isspaceW(*ptr
))
4508 if (strcmpW(ptr
, gmt
))
4510 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4513 return SystemTimeToFileTime(&st
, ft
);
4516 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4518 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4519 { 'm','o','n','d','a','y',0 },
4520 { 't','u','e','s','d','a','y',0 },
4521 { 'w','e','d','n','e','s','d','a','y',0 },
4522 { 't','h','u','r','s','d','a','y',0 },
4523 { 'f','r','i','d','a','y',0 },
4524 { 's','a','t','u','r','d','a','y',0 }};
4526 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4527 if (!strcmpiW(day
, days
[i
]))
4534 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4536 static const WCHAR gmt
[]= { 'G','M','T',0 };
4537 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4540 SYSTEMTIME st
= { 0 };
4542 ptr
= strchrW(value
, ',');
4545 if (ptr
- value
== 3)
4547 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4549 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4550 if (st
.wDayOfWeek
> 6)
4552 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4556 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4558 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4559 day
[ptr
- value
+ 1] = 0;
4560 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4561 if (st
.wDayOfWeek
> 6)
4563 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4569 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4574 while (isspaceW(*ptr
))
4577 num
= strtoulW(ptr
, &nextPtr
, 10);
4578 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4580 ERR("unexpected day %s\n", debugstr_w(value
));
4584 st
.wDay
= (WORD
)num
;
4588 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4593 for (monthPtr
= month
; *ptr
!= '-' &&
4594 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4598 st
.wMonth
= HTTP_ParseMonth(month
);
4599 if (!st
.wMonth
|| st
.wMonth
> 12)
4601 ERR("unexpected month %s\n", debugstr_w(month
));
4607 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4612 num
= strtoulW(ptr
, &nextPtr
, 10);
4613 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4615 ERR("unexpected year %s\n", debugstr_w(value
));
4619 st
.wYear
= (WORD
)num
;
4621 if (!HTTP_ParseTime(&st
, &ptr
))
4624 while (isspaceW(*ptr
))
4627 if (strcmpW(ptr
, gmt
))
4629 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4632 return SystemTimeToFileTime(&st
, ft
);
4635 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4637 static const WCHAR zero
[] = { '0',0 };
4640 if (!strcmpW(value
, zero
))
4642 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4645 else if (strchrW(value
, ','))
4647 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4650 ret
= HTTP_ParseRfc850Date(value
, ft
);
4652 ERR("unexpected date format %s\n", debugstr_w(value
));
4657 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4659 ERR("unexpected date format %s\n", debugstr_w(value
));
4664 static void HTTP_ProcessExpires(http_request_t
*request
)
4666 BOOL expirationFound
= FALSE
;
4669 EnterCriticalSection( &request
->headers_section
);
4671 /* Look for a Cache-Control header with a max-age directive, as it takes
4672 * precedence over the Expires header.
4674 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4675 if (headerIndex
!= -1)
4677 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4680 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4682 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4687 end
= ptr
+ strlenW(ptr
);
4688 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4692 static const WCHAR max_age
[] = {
4693 'm','a','x','-','a','g','e',0 };
4695 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4700 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4701 if (nextPtr
> equal
+ 1)
4705 NtQuerySystemTime( &ft
);
4706 /* Age is in seconds, FILETIME resolution is in
4707 * 100 nanosecond intervals.
4709 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4710 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4711 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4712 expirationFound
= TRUE
;
4719 while (isspaceW(*ptr
))
4726 if (!expirationFound
)
4728 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4729 if (headerIndex
!= -1)
4731 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4734 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4736 expirationFound
= TRUE
;
4737 request
->expires
= ft
;
4741 if (!expirationFound
)
4745 /* With no known age, default to 10 minutes until expiration. */
4746 NtQuerySystemTime( &t
);
4747 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4748 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4749 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4752 LeaveCriticalSection( &request
->headers_section
);
4755 static void HTTP_ProcessLastModified(http_request_t
*request
)
4759 EnterCriticalSection( &request
->headers_section
);
4761 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4762 if (headerIndex
!= -1)
4764 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4767 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4768 request
->last_modified
= ft
;
4771 LeaveCriticalSection( &request
->headers_section
);
4774 static void http_process_keep_alive(http_request_t
*req
)
4778 EnterCriticalSection( &req
->headers_section
);
4780 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4781 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4782 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4783 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4785 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4787 LeaveCriticalSection( &req
->headers_section
);
4790 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4792 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4793 netconn_t
*netconn
= NULL
;
4796 reset_data_stream(request
);
4798 if (request
->netconn
)
4800 if (is_valid_netconn(request
->netconn
) && NETCON_is_alive(request
->netconn
))
4803 return ERROR_SUCCESS
;
4807 free_netconn(request
->netconn
);
4808 request
->netconn
= NULL
;
4812 res
= HTTP_ResolveName(request
);
4813 if(res
!= ERROR_SUCCESS
)
4816 EnterCriticalSection(&connection_pool_cs
);
4818 while(!list_empty(&request
->server
->conn_pool
)) {
4819 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4820 list_remove(&netconn
->pool_entry
);
4822 if(is_valid_netconn(netconn
) && NETCON_is_alive(netconn
))
4825 TRACE("connection %p closed during idle\n", netconn
);
4826 free_netconn(netconn
);
4830 LeaveCriticalSection(&connection_pool_cs
);
4833 TRACE("<-- reusing %p netconn\n", netconn
);
4834 request
->netconn
= netconn
;
4836 return ERROR_SUCCESS
;
4839 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4840 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4842 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4843 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4844 request
->server
->addr_str
,
4845 strlen(request
->server
->addr_str
)+1);
4847 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4848 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4849 request
->connect_timeout
, &netconn
);
4850 if(res
!= ERROR_SUCCESS
) {
4851 ERR("create_netconn failed: %u\n", res
);
4855 request
->netconn
= netconn
;
4857 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4858 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4859 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4862 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4863 return ERROR_SUCCESS
;
4866 static char *build_ascii_request( const WCHAR
*str
, void *data
, DWORD data_len
, DWORD
*out_len
)
4868 int len
= WideCharToMultiByte( CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
4871 if (!(ret
= heap_alloc( len
+ data_len
))) return NULL
;
4872 WideCharToMultiByte( CP_ACP
, 0, str
, -1, ret
, len
, NULL
, NULL
);
4873 if (data_len
) memcpy( ret
+ len
- 1, data
, data_len
);
4874 *out_len
= len
+ data_len
- 1;
4879 static void set_content_length_header( http_request_t
*request
, DWORD len
, DWORD flags
)
4881 static const WCHAR fmtW
[] =
4882 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4883 WCHAR buf
[sizeof(fmtW
)/sizeof(fmtW
[0]) + 10];
4885 sprintfW( buf
, fmtW
, len
);
4886 HTTP_HttpAddRequestHeadersW( request
, buf
, ~0u, flags
);
4889 /***********************************************************************
4890 * HTTP_HttpSendRequestW (internal)
4892 * Sends the specified request to the HTTP server
4895 * ERROR_SUCCESS on success
4896 * win32 error code on failure
4899 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4900 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4901 DWORD dwContentLength
, BOOL bEndRequest
)
4903 BOOL redirected
= FALSE
, secure_proxy_connect
= FALSE
, loop_next
;
4904 LPWSTR requestString
= NULL
;
4905 INT responseLen
, cnt
;
4908 TRACE("--> %p\n", request
);
4910 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4912 /* if the verb is NULL default to GET */
4914 request
->verb
= heap_strdupW(szGET
);
4916 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
,
4917 HTTP_ADDREQ_FLAG_ADD_IF_NEW
| HTTP_ADDHDR_FLAG_REQ
);
4919 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4921 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4922 request
->bytesToWrite
= dwContentLength
;
4924 if (request
->session
->appInfo
->agent
)
4926 WCHAR
*agent_header
;
4927 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4930 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4931 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4932 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4934 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4935 heap_free(agent_header
);
4937 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4939 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4940 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4942 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4944 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4945 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4946 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4949 /* add the headers the caller supplied */
4950 if( lpszHeaders
&& dwHeaderLength
)
4951 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4955 DWORD len
, data_len
= dwOptionalLength
;
4956 BOOL reusing_connection
;
4962 request
->contentLength
= ~0u;
4963 request
->bytesToWrite
= 0;
4966 if (TRACE_ON(wininet
))
4970 EnterCriticalSection( &request
->headers_section
);
4971 host
= HTTP_GetHeader( request
, hostW
);
4972 TRACE("Going to url %s %s\n", debugstr_w(host
->lpszValue
), debugstr_w(request
->path
));
4973 LeaveCriticalSection( &request
->headers_section
);
4976 HTTP_FixURL(request
);
4977 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4979 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
,
4980 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
4982 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4983 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4985 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4986 HTTP_InsertCookies(request
);
4988 res
= open_http_connection(request
, &reusing_connection
);
4989 if (res
!= ERROR_SUCCESS
)
4992 if (!reusing_connection
&& (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4994 if (request
->proxy
) secure_proxy_connect
= TRUE
;
4997 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4998 if (res
!= ERROR_SUCCESS
)
5000 WARN("failed to upgrade to secure connection\n");
5001 http_release_netconn(request
, FALSE
);
5006 if (secure_proxy_connect
)
5008 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
5009 const WCHAR
*target
= request
->server
->host_port
;
5011 if (HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
5012 set_content_length_header(request
, 0, HTTP_ADDREQ_FLAG_REPLACE
);
5014 requestString
= build_request_header(request
, connectW
, target
, g_szHttp1_1
, TRUE
);
5016 else if (request
->proxy
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
5018 WCHAR
*url
= build_proxy_path_url(request
);
5019 requestString
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
5024 if (request
->proxy
&& HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
5025 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_REPLACE
);
5027 requestString
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
5030 TRACE("Request header -> %s\n", debugstr_w(requestString
) );
5032 /* send the request as ASCII, tack on the optional data */
5033 if (!lpOptional
|| redirected
|| secure_proxy_connect
)
5036 ascii_req
= build_ascii_request( requestString
, lpOptional
, data_len
, &len
);
5037 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
5039 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5040 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
5042 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
5043 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
5044 heap_free( ascii_req
);
5045 if(res
!= ERROR_SUCCESS
) {
5046 TRACE("send failed: %u\n", res
);
5047 if(!reusing_connection
)
5049 http_release_netconn(request
, FALSE
);
5054 request
->bytesWritten
= data_len
;
5056 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5057 INTERNET_STATUS_REQUEST_SENT
,
5058 &len
, sizeof(DWORD
));
5064 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5065 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5067 if (HTTP_GetResponseHeaders(request
, &responseLen
))
5069 http_release_netconn(request
, FALSE
);
5070 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
5073 /* FIXME: We should know that connection is closed before sending
5074 * headers. Otherwise wrong callbacks are executed */
5075 if(!responseLen
&& reusing_connection
) {
5076 TRACE("Connection closed by server, reconnecting\n");
5077 http_release_netconn(request
, FALSE
);
5082 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5083 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
5086 http_process_keep_alive(request
);
5087 HTTP_ProcessCookies(request
);
5088 HTTP_ProcessExpires(request
);
5089 HTTP_ProcessLastModified(request
);
5091 res
= set_content_length(request
);
5092 if(res
!= ERROR_SUCCESS
)
5094 if(!request
->contentLength
)
5095 http_release_netconn(request
, TRUE
);
5097 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5101 switch(request
->status_code
) {
5102 case HTTP_STATUS_REDIRECT
:
5103 case HTTP_STATUS_MOVED
:
5104 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5105 case HTTP_STATUS_REDIRECT_METHOD
:
5106 new_url
= get_redirect_url(request
);
5110 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5111 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5113 heap_free(request
->verb
);
5114 request
->verb
= heap_strdupW(szGET
);
5116 http_release_netconn(request
, drain_content(request
, FALSE
));
5117 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5118 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5119 res
= HTTP_HandleRedirect(request
, new_url
);
5121 if (res
== ERROR_SUCCESS
) {
5122 heap_free(requestString
);
5128 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5130 WCHAR szAuthValue
[2048];
5132 if (request
->status_code
== HTTP_STATUS_DENIED
)
5134 WCHAR
*host
= heap_strdupW( request
->server
->canon_host_port
);
5136 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5138 if (HTTP_DoAuthorization(request
, szAuthValue
,
5140 request
->session
->userName
,
5141 request
->session
->password
, host
))
5143 heap_free(requestString
);
5144 if(!drain_content(request
, TRUE
)) {
5145 FIXME("Could not drain content\n");
5146 http_release_netconn(request
, FALSE
);
5155 TRACE("Cleaning wrong authorization data\n");
5156 destroy_authinfo(request
->authInfo
);
5157 request
->authInfo
= NULL
;
5160 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5163 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5165 if (HTTP_DoAuthorization(request
, szAuthValue
,
5166 &request
->proxyAuthInfo
,
5167 request
->session
->appInfo
->proxyUsername
,
5168 request
->session
->appInfo
->proxyPassword
,
5171 heap_free(requestString
);
5172 if(!drain_content(request
, TRUE
)) {
5173 FIXME("Could not drain content\n");
5174 http_release_netconn(request
, FALSE
);
5182 TRACE("Cleaning wrong proxy authorization data\n");
5183 destroy_authinfo(request
->proxyAuthInfo
);
5184 request
->proxyAuthInfo
= NULL
;
5188 if (secure_proxy_connect
&& request
->status_code
== HTTP_STATUS_OK
)
5190 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5191 if (res
!= ERROR_SUCCESS
)
5193 WARN("failed to upgrade to secure proxy connection\n");
5194 http_release_netconn( request
, FALSE
);
5197 remove_header(request
, szProxy_Authorization
, TRUE
);
5198 destroy_authinfo(request
->proxyAuthInfo
);
5199 request
->proxyAuthInfo
= NULL
;
5201 secure_proxy_connect
= FALSE
;
5206 res
= ERROR_SUCCESS
;
5211 heap_free(requestString
);
5213 /* TODO: send notification for P3P header */
5215 if(res
== ERROR_SUCCESS
)
5216 create_cache_entry(request
);
5218 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5220 if (res
== ERROR_SUCCESS
) {
5221 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5222 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5224 send_request_complete(request
,
5225 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5227 send_request_complete(request
, 0, res
);
5243 } send_request_task_t
;
5245 /***********************************************************************
5247 * Helper functions for the HttpSendRequest(Ex) functions
5250 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5252 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5253 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5255 TRACE("%p\n", request
);
5257 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5258 task
->optional_len
, task
->content_len
, task
->end_request
);
5260 heap_free(task
->headers
);
5264 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5267 DWORD res
= ERROR_SUCCESS
;
5269 if(!is_valid_netconn(request
->netconn
)) {
5270 WARN("Not connected\n");
5271 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5272 return ERROR_INTERNET_OPERATION_CANCELLED
;
5275 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5276 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5278 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5279 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5281 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5282 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5284 /* process cookies here. Is this right? */
5285 http_process_keep_alive(request
);
5286 HTTP_ProcessCookies(request
);
5287 HTTP_ProcessExpires(request
);
5288 HTTP_ProcessLastModified(request
);
5290 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5291 if(!request
->contentLength
)
5292 http_release_netconn(request
, TRUE
);
5295 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5297 switch(request
->status_code
) {
5298 case HTTP_STATUS_REDIRECT
:
5299 case HTTP_STATUS_MOVED
:
5300 case HTTP_STATUS_REDIRECT_METHOD
:
5301 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5304 new_url
= get_redirect_url(request
);
5308 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5309 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5311 heap_free(request
->verb
);
5312 request
->verb
= heap_strdupW(szGET
);
5314 http_release_netconn(request
, drain_content(request
, FALSE
));
5315 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5316 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5317 res
= HTTP_HandleRedirect(request
, new_url
);
5319 if (res
== ERROR_SUCCESS
)
5320 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5325 if(res
== ERROR_SUCCESS
)
5326 create_cache_entry(request
);
5328 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5329 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5331 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5336 /***********************************************************************
5337 * HttpEndRequestA (WININET.@)
5339 * Ends an HTTP request that was started by HttpSendRequestEx
5342 * TRUE if successful
5346 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5347 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5349 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5353 SetLastError(ERROR_INVALID_PARAMETER
);
5357 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5364 } end_request_task_t
;
5366 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5368 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5369 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5373 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5376 /***********************************************************************
5377 * HttpEndRequestW (WININET.@)
5379 * Ends an HTTP request that was started by HttpSendRequestEx
5382 * TRUE if successful
5386 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5387 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5389 http_request_t
*request
;
5392 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5396 SetLastError(ERROR_INVALID_PARAMETER
);
5400 request
= (http_request_t
*) get_handle_object( hRequest
);
5402 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5404 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5406 WININET_Release( &request
->hdr
);
5409 request
->hdr
.dwFlags
|= dwFlags
;
5411 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5413 end_request_task_t
*task
;
5415 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5416 task
->flags
= dwFlags
;
5417 task
->context
= dwContext
;
5419 INTERNET_AsyncCall(&task
->hdr
);
5420 res
= ERROR_IO_PENDING
;
5423 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5425 WININET_Release( &request
->hdr
);
5426 TRACE("%u <--\n", res
);
5427 if(res
!= ERROR_SUCCESS
)
5429 return res
== ERROR_SUCCESS
;
5432 /***********************************************************************
5433 * HttpSendRequestExA (WININET.@)
5435 * Sends the specified request to the HTTP server and allows chunked
5440 * Failure: FALSE, call GetLastError() for more information.
5442 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5443 LPINTERNET_BUFFERSA lpBuffersIn
,
5444 LPINTERNET_BUFFERSA lpBuffersOut
,
5445 DWORD dwFlags
, DWORD_PTR dwContext
)
5447 INTERNET_BUFFERSW BuffersInW
;
5450 LPWSTR header
= NULL
;
5452 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5453 lpBuffersOut
, dwFlags
, dwContext
);
5457 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5458 if (lpBuffersIn
->lpcszHeader
)
5460 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5461 lpBuffersIn
->dwHeadersLength
,0,0);
5462 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5463 if (!(BuffersInW
.lpcszHeader
= header
))
5465 SetLastError(ERROR_OUTOFMEMORY
);
5468 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5469 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5473 BuffersInW
.lpcszHeader
= NULL
;
5474 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5475 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5476 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5477 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5478 BuffersInW
.Next
= NULL
;
5481 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5487 /***********************************************************************
5488 * HttpSendRequestExW (WININET.@)
5490 * Sends the specified request to the HTTP server and allows chunked
5495 * Failure: FALSE, call GetLastError() for more information.
5497 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5498 LPINTERNET_BUFFERSW lpBuffersIn
,
5499 LPINTERNET_BUFFERSW lpBuffersOut
,
5500 DWORD dwFlags
, DWORD_PTR dwContext
)
5502 http_request_t
*request
;
5503 http_session_t
*session
;
5507 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5508 lpBuffersOut
, dwFlags
, dwContext
);
5510 request
= (http_request_t
*) get_handle_object( hRequest
);
5512 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5514 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5518 session
= request
->session
;
5519 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5520 hIC
= session
->appInfo
;
5521 assert(hIC
->hdr
.htype
== WH_HINIT
);
5523 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5525 send_request_task_t
*task
;
5527 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5532 if (lpBuffersIn
->lpcszHeader
)
5534 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5535 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5537 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5539 task
->headers
= heap_alloc(size
);
5540 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5542 else task
->headers
= NULL
;
5544 task
->headers_len
= size
/ sizeof(WCHAR
);
5545 task
->optional
= lpBuffersIn
->lpvBuffer
;
5546 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5547 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5551 task
->headers
= NULL
;
5552 task
->headers_len
= 0;
5553 task
->optional
= NULL
;
5554 task
->optional_len
= 0;
5555 task
->content_len
= 0;
5558 task
->end_request
= FALSE
;
5560 INTERNET_AsyncCall(&task
->hdr
);
5561 res
= ERROR_IO_PENDING
;
5566 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5567 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5568 lpBuffersIn
->dwBufferTotal
, FALSE
);
5570 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5575 WININET_Release( &request
->hdr
);
5579 return res
== ERROR_SUCCESS
;
5582 /***********************************************************************
5583 * HttpSendRequestW (WININET.@)
5585 * Sends the specified request to the HTTP server
5592 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5593 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5595 http_request_t
*request
;
5596 http_session_t
*session
= NULL
;
5597 appinfo_t
*hIC
= NULL
;
5598 DWORD res
= ERROR_SUCCESS
;
5600 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5601 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5603 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5604 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5606 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5610 session
= request
->session
;
5611 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5613 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5617 hIC
= session
->appInfo
;
5618 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5620 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5624 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5626 send_request_task_t
*task
;
5628 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5633 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5634 else size
= dwHeaderLength
* sizeof(WCHAR
);
5636 task
->headers
= heap_alloc(size
);
5637 memcpy(task
->headers
, lpszHeaders
, size
);
5640 task
->headers
= NULL
;
5641 task
->headers_len
= dwHeaderLength
;
5642 task
->optional
= lpOptional
;
5643 task
->optional_len
= dwOptionalLength
;
5644 task
->content_len
= dwOptionalLength
;
5645 task
->end_request
= TRUE
;
5647 INTERNET_AsyncCall(&task
->hdr
);
5648 res
= ERROR_IO_PENDING
;
5652 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5653 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5654 dwOptionalLength
, TRUE
);
5658 WININET_Release( &request
->hdr
);
5661 return res
== ERROR_SUCCESS
;
5664 /***********************************************************************
5665 * HttpSendRequestA (WININET.@)
5667 * Sends the specified request to the HTTP server
5674 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5675 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5678 LPWSTR szHeaders
=NULL
;
5679 DWORD nLen
=dwHeaderLength
;
5680 if(lpszHeaders
!=NULL
)
5682 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5683 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5684 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5686 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5687 heap_free(szHeaders
);
5691 /***********************************************************************
5692 * HTTPSESSION_Destroy (internal)
5694 * Deallocate session handle
5697 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5699 http_session_t
*session
= (http_session_t
*) hdr
;
5701 TRACE("%p\n", session
);
5703 WININET_Release(&session
->appInfo
->hdr
);
5705 heap_free(session
->hostName
);
5706 heap_free(session
->password
);
5707 heap_free(session
->userName
);
5710 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5712 http_session_t
*ses
= (http_session_t
*)hdr
;
5715 case INTERNET_OPTION_HANDLE_TYPE
:
5716 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5718 if (*size
< sizeof(ULONG
))
5719 return ERROR_INSUFFICIENT_BUFFER
;
5721 *size
= sizeof(DWORD
);
5722 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5723 return ERROR_SUCCESS
;
5724 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5725 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5727 if (*size
< sizeof(DWORD
))
5728 return ERROR_INSUFFICIENT_BUFFER
;
5730 *size
= sizeof(DWORD
);
5731 *(DWORD
*)buffer
= ses
->connect_timeout
;
5732 return ERROR_SUCCESS
;
5734 case INTERNET_OPTION_SEND_TIMEOUT
:
5735 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5737 if (*size
< sizeof(DWORD
))
5738 return ERROR_INSUFFICIENT_BUFFER
;
5740 *size
= sizeof(DWORD
);
5741 *(DWORD
*)buffer
= ses
->send_timeout
;
5742 return ERROR_SUCCESS
;
5744 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5745 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5747 if (*size
< sizeof(DWORD
))
5748 return ERROR_INSUFFICIENT_BUFFER
;
5750 *size
= sizeof(DWORD
);
5751 *(DWORD
*)buffer
= ses
->receive_timeout
;
5752 return ERROR_SUCCESS
;
5755 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5758 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5760 http_session_t
*ses
= (http_session_t
*)hdr
;
5763 case INTERNET_OPTION_USERNAME
:
5765 heap_free(ses
->userName
);
5766 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5767 return ERROR_SUCCESS
;
5769 case INTERNET_OPTION_PASSWORD
:
5771 heap_free(ses
->password
);
5772 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5773 return ERROR_SUCCESS
;
5775 case INTERNET_OPTION_PROXY_USERNAME
:
5777 heap_free(ses
->appInfo
->proxyUsername
);
5778 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5779 return ERROR_SUCCESS
;
5781 case INTERNET_OPTION_PROXY_PASSWORD
:
5783 heap_free(ses
->appInfo
->proxyPassword
);
5784 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5785 return ERROR_SUCCESS
;
5787 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5789 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5790 ses
->connect_timeout
= *(DWORD
*)buffer
;
5791 return ERROR_SUCCESS
;
5793 case INTERNET_OPTION_SEND_TIMEOUT
:
5795 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5796 ses
->send_timeout
= *(DWORD
*)buffer
;
5797 return ERROR_SUCCESS
;
5799 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5801 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5802 ses
->receive_timeout
= *(DWORD
*)buffer
;
5803 return ERROR_SUCCESS
;
5808 return INET_SetOption(hdr
, option
, buffer
, size
);
5811 static const object_vtbl_t HTTPSESSIONVtbl
= {
5812 HTTPSESSION_Destroy
,
5814 HTTPSESSION_QueryOption
,
5815 HTTPSESSION_SetOption
,
5824 /***********************************************************************
5825 * HTTP_Connect (internal)
5827 * Create http session handle
5830 * HINTERNET a session handle on success
5834 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5835 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5836 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5837 DWORD dwInternalFlags
, HINTERNET
*ret
)
5839 http_session_t
*session
= NULL
;
5843 if (!lpszServerName
|| !lpszServerName
[0])
5844 return ERROR_INVALID_PARAMETER
;
5846 assert( hIC
->hdr
.htype
== WH_HINIT
);
5848 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5850 return ERROR_OUTOFMEMORY
;
5853 * According to my tests. The name is not resolved until a request is sent
5856 session
->hdr
.htype
= WH_HHTTPSESSION
;
5857 session
->hdr
.dwFlags
= dwFlags
;
5858 session
->hdr
.dwContext
= dwContext
;
5859 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5861 WININET_AddRef( &hIC
->hdr
);
5862 session
->appInfo
= hIC
;
5863 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5865 session
->hostName
= heap_strdupW(lpszServerName
);
5866 if (lpszUserName
&& lpszUserName
[0])
5867 session
->userName
= heap_strdupW(lpszUserName
);
5868 if (lpszPassword
&& lpszPassword
[0])
5869 session
->password
= heap_strdupW(lpszPassword
);
5870 session
->hostPort
= serverPort
;
5871 session
->connect_timeout
= hIC
->connect_timeout
;
5872 session
->send_timeout
= 0;
5873 session
->receive_timeout
= 0;
5875 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5876 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5878 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5879 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5884 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5888 TRACE("%p --> %p\n", hIC
, session
);
5890 *ret
= session
->hdr
.hInternet
;
5891 return ERROR_SUCCESS
;
5894 /***********************************************************************
5895 * HTTP_clear_response_headers (internal)
5897 * clear out any old response headers
5899 static void HTTP_clear_response_headers( http_request_t
*request
)
5903 EnterCriticalSection( &request
->headers_section
);
5905 for( i
=0; i
<request
->nCustHeaders
; i
++)
5907 if( !request
->custHeaders
[i
].lpszField
)
5909 if( !request
->custHeaders
[i
].lpszValue
)
5911 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5913 HTTP_DeleteCustomHeader( request
, i
);
5917 LeaveCriticalSection( &request
->headers_section
);
5920 /***********************************************************************
5921 * HTTP_GetResponseHeaders (internal)
5923 * Read server response
5930 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5933 WCHAR buffer
[MAX_REPLY_LEN
];
5934 DWORD buflen
= MAX_REPLY_LEN
;
5936 char bufferA
[MAX_REPLY_LEN
];
5937 LPWSTR status_code
= NULL
, status_text
= NULL
;
5938 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5939 BOOL codeHundred
= FALSE
;
5943 if(!is_valid_netconn(request
->netconn
))
5946 /* clear old response headers (eg. from a redirect response) */
5947 HTTP_clear_response_headers( request
);
5949 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5952 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5954 buflen
= MAX_REPLY_LEN
;
5955 if ((res
= read_line(request
, bufferA
, &buflen
)))
5958 if (!buflen
) goto lend
;
5961 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5962 /* check is this a status code line? */
5963 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5965 /* split the version from the status code */
5966 status_code
= strchrW( buffer
, ' ' );
5971 /* split the status code from the status text */
5972 status_text
= strchrW( status_code
, ' ' );
5976 request
->status_code
= atoiW(status_code
);
5978 TRACE("version [%s] status code [%s] status text [%s]\n",
5979 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5981 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5983 else if (!codeHundred
)
5985 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5987 heap_free(request
->version
);
5988 heap_free(request
->statusText
);
5990 request
->status_code
= HTTP_STATUS_OK
;
5991 request
->version
= heap_strdupW(g_szHttp1_0
);
5992 request
->statusText
= heap_strdupW(szOK
);
5996 } while (codeHundred
);
5998 /* Add status code */
5999 HTTP_ProcessHeader(request
, szStatus
, status_code
,
6000 HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
6002 heap_free(request
->version
);
6003 heap_free(request
->statusText
);
6005 request
->version
= heap_strdupW(buffer
);
6006 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
6008 /* Restore the spaces */
6009 *(status_code
-1) = ' ';
6011 *(status_text
-1) = ' ';
6013 /* Parse each response line */
6016 buflen
= MAX_REPLY_LEN
;
6017 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
6019 LPWSTR
* pFieldAndValue
;
6021 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
6023 if (!bufferA
[0]) break;
6024 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
6026 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
6029 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
6030 HTTP_ADDREQ_FLAG_ADD
);
6031 HTTP_FreeTokens(pFieldAndValue
);
6042 res
= ERROR_SUCCESS
;
6051 /***********************************************************************
6052 * HTTP_InterpretHttpHeader (internal)
6054 * Parse server response
6058 * Pointer to array of field, value, NULL on success.
6061 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
6063 LPWSTR
* pTokenPair
;
6067 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
6069 pszColon
= strchrW(buffer
, ':');
6070 /* must have two tokens */
6073 HTTP_FreeTokens(pTokenPair
);
6075 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
6079 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
6082 HTTP_FreeTokens(pTokenPair
);
6085 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
6086 pTokenPair
[0][pszColon
- buffer
] = '\0';
6090 len
= strlenW(pszColon
);
6091 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
6094 HTTP_FreeTokens(pTokenPair
);
6097 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
6099 strip_spaces(pTokenPair
[0]);
6100 strip_spaces(pTokenPair
[1]);
6102 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
6106 /***********************************************************************
6107 * HTTP_ProcessHeader (internal)
6109 * Stuff header into header tables according to <dwModifier>
6113 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6115 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6117 LPHTTPHEADERW lphttpHdr
= NULL
;
6119 BOOL request_only
= !!(dwModifier
& HTTP_ADDHDR_FLAG_REQ
);
6120 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6122 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6124 EnterCriticalSection( &request
->headers_section
);
6126 /* REPLACE wins out over ADD */
6127 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6128 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6130 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6133 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6137 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6139 LeaveCriticalSection( &request
->headers_section
);
6140 return ERROR_HTTP_INVALID_HEADER
;
6142 lphttpHdr
= &request
->custHeaders
[index
];
6148 hdr
.lpszField
= (LPWSTR
)field
;
6149 hdr
.lpszValue
= (LPWSTR
)value
;
6150 hdr
.wFlags
= hdr
.wCount
= 0;
6152 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6153 hdr
.wFlags
|= HDR_ISREQUEST
;
6155 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6156 LeaveCriticalSection( &request
->headers_section
);
6159 /* no value to delete */
6162 LeaveCriticalSection( &request
->headers_section
);
6163 return ERROR_SUCCESS
;
6166 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6167 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6169 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6171 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6173 HTTP_DeleteCustomHeader( request
, index
);
6175 if (value
&& value
[0])
6179 hdr
.lpszField
= (LPWSTR
)field
;
6180 hdr
.lpszValue
= (LPWSTR
)value
;
6181 hdr
.wFlags
= hdr
.wCount
= 0;
6183 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6184 hdr
.wFlags
|= HDR_ISREQUEST
;
6186 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6187 LeaveCriticalSection( &request
->headers_section
);
6191 LeaveCriticalSection( &request
->headers_section
);
6192 return ERROR_SUCCESS
;
6194 else if (dwModifier
& COALESCEFLAGS
)
6199 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6200 INT valuelen
= strlenW(value
);
6202 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6205 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6207 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6210 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6213 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6215 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6218 lphttpHdr
->lpszValue
= lpsztmp
;
6219 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6222 lphttpHdr
->lpszValue
[origlen
] = ch
;
6224 lphttpHdr
->lpszValue
[origlen
] = ' ';
6228 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6229 lphttpHdr
->lpszValue
[len
] = '\0';
6230 res
= ERROR_SUCCESS
;
6234 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6235 res
= ERROR_OUTOFMEMORY
;
6238 TRACE("<-- %d\n", res
);
6239 LeaveCriticalSection( &request
->headers_section
);
6243 /***********************************************************************
6244 * HTTP_GetCustomHeaderIndex (internal)
6246 * Return index of custom header from header array
6247 * Headers section must be held
6249 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6250 int requested_index
, BOOL request_only
)
6254 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6256 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6258 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6261 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6264 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6267 if (requested_index
== 0)
6272 if (index
>= request
->nCustHeaders
)
6275 TRACE("Return: %d\n", index
);
6280 /***********************************************************************
6281 * HTTP_InsertCustomHeader (internal)
6283 * Insert header into array
6284 * Headers section must be held
6286 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6289 LPHTTPHEADERW lph
= NULL
;
6291 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6292 count
= request
->nCustHeaders
+ 1;
6294 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6296 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6299 return ERROR_OUTOFMEMORY
;
6301 request
->custHeaders
= lph
;
6302 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6303 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6304 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6305 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6306 request
->nCustHeaders
++;
6308 return ERROR_SUCCESS
;
6312 /***********************************************************************
6313 * HTTP_DeleteCustomHeader (internal)
6315 * Delete header from array
6316 * If this function is called, the index may change.
6317 * Headers section must be held
6319 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6321 if( request
->nCustHeaders
<= 0 )
6323 if( index
>= request
->nCustHeaders
)
6325 request
->nCustHeaders
--;
6327 heap_free(request
->custHeaders
[index
].lpszField
);
6328 heap_free(request
->custHeaders
[index
].lpszValue
);
6330 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6331 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6332 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6338 /***********************************************************************
6339 * IsHostInProxyBypassList (@)
6344 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6346 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);