2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
31 #include "wine/port.h"
33 #if defined(__MINGW32__) || defined (_MSC_VER)
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
41 #ifdef HAVE_ARPA_INET_H
42 # include <arpa/inet.h>
61 #define NO_SHLWAPI_STREAM
62 #define NO_SHLWAPI_REG
63 #define NO_SHLWAPI_STRFCNS
64 #define NO_SHLWAPI_GDI
71 #include "wine/debug.h"
72 #include "wine/exception.h"
73 #include "wine/unicode.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
77 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
78 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
79 static const WCHAR szOK
[] = {'O','K',0};
80 static const WCHAR szDefaultHeader
[] = {'H','T','T','P','/','1','.','0',' ','2','0','0',' ','O','K',0};
81 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
82 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
83 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
84 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
85 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
86 static const WCHAR szGET
[] = { 'G','E','T', 0 };
87 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
88 static const WCHAR szCrLf
[] = {'\r','\n', 0};
90 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
91 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
92 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
93 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
94 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
95 static const WCHAR szAge
[] = { 'A','g','e',0 };
96 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
97 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
98 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
99 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
100 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
101 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
102 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
103 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
104 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
105 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
106 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
107 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
108 static const WCHAR szContent_Transfer_Encoding
[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
109 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
110 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
111 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
112 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
113 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
114 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
115 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
116 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
117 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
118 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
119 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
120 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
121 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
122 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
123 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
124 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
125 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
126 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
127 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
128 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
129 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
130 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
131 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
132 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
133 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
134 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
135 static const WCHAR szUnless_Modified_Since
[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
136 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
137 static const WCHAR szURI
[] = { 'U','R','I',0 };
138 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
139 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
140 static const WCHAR szVia
[] = { 'V','i','a',0 };
141 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
142 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
144 #define HTTP_REFERER szReferer
145 #define HTTP_ACCEPT szAccept
146 #define HTTP_USERAGENT szUser_Agent
148 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
149 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
150 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
151 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
152 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
153 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
154 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
156 #define COLLECT_TIME 60000
158 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
169 unsigned int auth_data_len
;
170 BOOL finished
; /* finished authenticating */
174 typedef struct _basicAuthorizationData
181 UINT authorizationLen
;
182 } basicAuthorizationData
;
184 typedef struct _authorizationData
198 static struct list basicAuthorizationCache
= LIST_INIT(basicAuthorizationCache
);
199 static struct list authorizationCache
= LIST_INIT(authorizationCache
);
201 static CRITICAL_SECTION authcache_cs
;
202 static CRITICAL_SECTION_DEBUG critsect_debug
=
205 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
206 0, 0, { (DWORD_PTR
)(__FILE__
": authcache_cs") }
208 static CRITICAL_SECTION authcache_cs
= { &critsect_debug
, -1, 0, 0, 0, 0 };
210 static DWORD
HTTP_GetResponseHeaders(http_request_t
*req
, INT
*len
);
211 static DWORD
HTTP_ProcessHeader(http_request_t
*req
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
);
212 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
);
213 static DWORD
HTTP_InsertCustomHeader(http_request_t
*req
, LPHTTPHEADERW lpHdr
);
214 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*req
, LPCWSTR lpszField
, INT index
, BOOL Request
);
215 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*req
, DWORD index
);
216 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
);
217 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*, DWORD
, LPVOID
, LPDWORD
, LPDWORD
);
218 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*req
, LPCWSTR lpszUrl
);
219 static UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
220 static BOOL
HTTP_VerifyValidHeader(http_request_t
*req
, LPCWSTR field
);
221 static BOOL
drain_content(http_request_t
*,BOOL
);
223 static CRITICAL_SECTION connection_pool_cs
;
224 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
226 0, 0, &connection_pool_cs
,
227 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
228 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
230 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
232 static struct list connection_pool
= LIST_INIT(connection_pool
);
233 static BOOL collector_running
;
235 void server_addref(server_t
*server
)
237 InterlockedIncrement(&server
->ref
);
240 void server_release(server_t
*server
)
242 if(InterlockedDecrement(&server
->ref
))
245 list_remove(&server
->entry
);
247 if(server
->cert_chain
)
248 CertFreeCertificateChain(server
->cert_chain
);
249 heap_free(server
->name
);
250 heap_free(server
->scheme_host_port
);
254 static BOOL
process_host_port(server_t
*server
)
260 static const WCHAR httpW
[] = {'h','t','t','p',0};
261 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
262 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
264 name_len
= strlenW(server
->name
);
265 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
269 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
270 server
->scheme_host_port
= buf
;
272 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
276 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
277 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
281 server_t
*get_server(const WCHAR
*name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
283 server_t
*iter
, *server
= NULL
;
285 if(port
== INTERNET_INVALID_PORT_NUMBER
)
286 port
= INTERNET_DEFAULT_HTTP_PORT
;
288 EnterCriticalSection(&connection_pool_cs
);
290 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
291 if(iter
->port
== port
&& !strcmpW(iter
->name
, name
) && iter
->is_https
== is_https
) {
293 server_addref(server
);
298 if(!server
&& do_create
) {
299 server
= heap_alloc_zero(sizeof(*server
));
301 server
->ref
= 2; /* list reference and return */
303 server
->is_https
= is_https
;
304 list_init(&server
->conn_pool
);
305 server
->name
= heap_strdupW(name
);
306 if(server
->name
&& process_host_port(server
)) {
307 list_add_head(&connection_pool
, &server
->entry
);
315 LeaveCriticalSection(&connection_pool_cs
);
320 BOOL
collect_connections(collect_type_t collect_type
)
322 netconn_t
*netconn
, *netconn_safe
;
323 server_t
*server
, *server_safe
;
324 BOOL remaining
= FALSE
;
327 now
= GetTickCount64();
329 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
330 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
331 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
332 TRACE("freeing %p\n", netconn
);
333 list_remove(&netconn
->pool_entry
);
334 free_netconn(netconn
);
340 if(collect_type
== COLLECT_CLEANUP
) {
341 list_remove(&server
->entry
);
342 list_init(&server
->entry
);
343 server_release(server
);
350 static DWORD WINAPI
collect_connections_proc(void *arg
)
352 BOOL remaining_conns
;
355 /* FIXME: Use more sophisticated method */
358 EnterCriticalSection(&connection_pool_cs
);
360 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
362 collector_running
= FALSE
;
364 LeaveCriticalSection(&connection_pool_cs
);
365 }while(remaining_conns
);
367 FreeLibraryAndExitThread(WININET_hModule
, 0);
370 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
373 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
374 if (HeaderIndex
== -1)
377 return &req
->custHeaders
[HeaderIndex
];
386 struct data_stream_vtbl_t
{
387 DWORD (*get_avail_data
)(data_stream_t
*,http_request_t
*);
388 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
389 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,read_mode_t
);
390 BOOL (*drain_content
)(data_stream_t
*,http_request_t
*);
391 void (*destroy
)(data_stream_t
*);
395 data_stream_t data_stream
;
397 BYTE buf
[READ_BUFFER_SIZE
];
403 static inline void destroy_data_stream(data_stream_t
*stream
)
405 stream
->vtbl
->destroy(stream
);
408 static void reset_data_stream(http_request_t
*req
)
410 destroy_data_stream(req
->data_stream
);
411 req
->data_stream
= &req
->netconn_stream
.data_stream
;
412 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
413 req
->read_chunked
= req
->read_gzip
= FALSE
;
419 data_stream_t stream
;
420 data_stream_t
*parent_stream
;
422 BYTE buf
[READ_BUFFER_SIZE
];
428 static DWORD
gzip_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
430 /* Allow reading only from read buffer */
434 static BOOL
gzip_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
436 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
437 return gzip_stream
->end_of_data
;
440 static DWORD
gzip_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
441 DWORD
*read
, read_mode_t read_mode
)
443 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
444 z_stream
*zstream
= &gzip_stream
->zstream
;
445 DWORD current_read
, ret_read
= 0;
448 DWORD res
= ERROR_SUCCESS
;
450 while(size
&& !gzip_stream
->end_of_data
) {
451 end
= gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
);
453 if(gzip_stream
->buf_size
<= 64 && !end
) {
454 if(gzip_stream
->buf_pos
) {
455 if(gzip_stream
->buf_size
)
456 memmove(gzip_stream
->buf
, gzip_stream
->buf
+gzip_stream
->buf_pos
, gzip_stream
->buf_size
);
457 gzip_stream
->buf_pos
= 0;
459 res
= gzip_stream
->parent_stream
->vtbl
->read(gzip_stream
->parent_stream
, req
, gzip_stream
->buf
+gzip_stream
->buf_size
,
460 sizeof(gzip_stream
->buf
)-gzip_stream
->buf_size
, ¤t_read
, read_mode
);
461 gzip_stream
->buf_size
+= current_read
;
462 if(res
!= ERROR_SUCCESS
)
464 end
= gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
);
465 if(!current_read
&& !end
) {
466 if(read_mode
!= READMODE_NOBLOCK
) {
467 WARN("unexpected end of data\n");
468 gzip_stream
->end_of_data
= TRUE
;
472 if(gzip_stream
->buf_size
<= 64 && !end
)
476 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
477 zstream
->avail_in
= gzip_stream
->buf_size
-(end
? 0 : 64);
478 zstream
->next_out
= buf
+ret_read
;
479 zstream
->avail_out
= size
;
480 zres
= inflate(&gzip_stream
->zstream
, 0);
481 current_read
= size
- zstream
->avail_out
;
482 size
-= current_read
;
483 ret_read
+= current_read
;
484 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
485 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
486 if(zres
== Z_STREAM_END
) {
487 TRACE("end of data\n");
488 gzip_stream
->end_of_data
= TRUE
;
490 }else if(zres
!= Z_OK
) {
491 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
493 res
= ERROR_INTERNET_DECODING_FAILED
;
497 if(ret_read
&& read_mode
== READMODE_ASYNC
)
498 read_mode
= READMODE_NOBLOCK
;
501 TRACE("read %u bytes\n", ret_read
);
506 static BOOL
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
)
508 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
509 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
);
512 static void gzip_destroy(data_stream_t
*stream
)
514 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
516 destroy_data_stream(gzip_stream
->parent_stream
);
518 if(!gzip_stream
->end_of_data
)
519 inflateEnd(&gzip_stream
->zstream
);
520 heap_free(gzip_stream
);
523 static const data_stream_vtbl_t gzip_stream_vtbl
= {
531 static voidpf
wininet_zalloc(voidpf opaque
, uInt items
, uInt size
)
533 return heap_alloc(items
*size
);
536 static void wininet_zfree(voidpf opaque
, voidpf address
)
541 static DWORD
init_gzip_stream(http_request_t
*req
)
543 gzip_stream_t
*gzip_stream
;
546 gzip_stream
= heap_alloc_zero(sizeof(gzip_stream_t
));
548 return ERROR_OUTOFMEMORY
;
550 gzip_stream
->stream
.vtbl
= &gzip_stream_vtbl
;
551 gzip_stream
->zstream
.zalloc
= wininet_zalloc
;
552 gzip_stream
->zstream
.zfree
= wininet_zfree
;
554 zres
= inflateInit2(&gzip_stream
->zstream
, 0x1f);
556 ERR("inflateInit failed: %d\n", zres
);
557 heap_free(gzip_stream
);
558 return ERROR_OUTOFMEMORY
;
561 index
= HTTP_GetCustomHeaderIndex(req
, szContent_Length
, 0, FALSE
);
563 HTTP_DeleteCustomHeader(req
, index
);
566 memcpy(gzip_stream
->buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
567 gzip_stream
->buf_size
= req
->read_size
;
568 req
->read_pos
= req
->read_size
= 0;
571 req
->read_gzip
= TRUE
;
572 gzip_stream
->parent_stream
= req
->data_stream
;
573 req
->data_stream
= &gzip_stream
->stream
;
574 return ERROR_SUCCESS
;
579 static DWORD
init_gzip_stream(http_request_t
*req
)
581 ERR("gzip stream not supported, missing zlib.\n");
582 return ERROR_SUCCESS
;
587 /***********************************************************************
588 * HTTP_FreeTokens (internal)
590 * Frees table of pointers.
592 static void HTTP_FreeTokens(LPWSTR
* token_array
)
595 for (i
= 0; token_array
[i
]; i
++) heap_free(token_array
[i
]);
596 heap_free(token_array
);
599 static void HTTP_FixURL(http_request_t
*request
)
601 static const WCHAR szSlash
[] = { '/',0 };
602 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/', 0 };
604 /* If we don't have a path we set it to root */
605 if (NULL
== request
->path
)
606 request
->path
= heap_strdupW(szSlash
);
607 else /* remove \r and \n*/
609 int nLen
= strlenW(request
->path
);
610 while ((nLen
>0 ) && ((request
->path
[nLen
-1] == '\r')||(request
->path
[nLen
-1] == '\n')))
613 request
->path
[nLen
]='\0';
615 /* Replace '\' with '/' */
618 if (request
->path
[nLen
] == '\\') request
->path
[nLen
]='/';
622 if(CSTR_EQUAL
!= CompareStringW( LOCALE_INVARIANT
, NORM_IGNORECASE
,
623 request
->path
, strlenW(request
->path
), szHttp
, strlenW(szHttp
) )
624 && request
->path
[0] != '/') /* not an absolute path ?? --> fix it !! */
626 WCHAR
*fixurl
= heap_alloc((strlenW(request
->path
) + 2)*sizeof(WCHAR
));
628 strcpyW(fixurl
+ 1, request
->path
);
629 heap_free( request
->path
);
630 request
->path
= fixurl
;
634 static WCHAR
* build_request_header(http_request_t
*request
, const WCHAR
*verb
,
635 const WCHAR
*path
, const WCHAR
*version
, BOOL use_cr
)
637 LPWSTR requestString
;
642 static const WCHAR szSpace
[] = { ' ',0 };
643 static const WCHAR szColon
[] = { ':',' ',0 };
644 static const WCHAR szCr
[] = { '\r',0 };
645 static const WCHAR szLf
[] = { '\n',0 };
647 /* allocate space for an array of all the string pointers to be added */
648 len
= (request
->nCustHeaders
)*5 + 10;
649 req
= heap_alloc(len
*sizeof(LPCWSTR
));
651 /* add the verb, path and HTTP version string */
662 /* Append custom request headers */
663 for (i
= 0; i
< request
->nCustHeaders
; i
++)
665 if (request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
667 req
[n
++] = request
->custHeaders
[i
].lpszField
;
669 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
674 TRACE("Adding custom header %s (%s)\n",
675 debugstr_w(request
->custHeaders
[i
].lpszField
),
676 debugstr_w(request
->custHeaders
[i
].lpszValue
));
684 requestString
= HTTP_build_req( req
, 4 );
686 return requestString
;
689 static WCHAR
* build_response_header(http_request_t
*request
, BOOL use_cr
)
691 static const WCHAR colonW
[] = { ':',' ',0 };
692 static const WCHAR crW
[] = { '\r',0 };
693 static const WCHAR lfW
[] = { '\n',0 };
694 static const WCHAR status_fmt
[] = { ' ','%','u',' ',0 };
700 req
= heap_alloc((request
->nCustHeaders
*5+8)*sizeof(WCHAR
*));
704 if (request
->status_code
)
706 req
[n
++] = request
->version
;
707 sprintfW(buf
, status_fmt
, request
->status_code
);
709 req
[n
++] = request
->statusText
;
715 for(i
= 0; i
< request
->nCustHeaders
; i
++)
717 if(!(request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
718 && strcmpW(request
->custHeaders
[i
].lpszField
, szStatus
))
720 req
[n
++] = request
->custHeaders
[i
].lpszField
;
722 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
727 TRACE("Adding custom header %s (%s)\n",
728 debugstr_w(request
->custHeaders
[i
].lpszField
),
729 debugstr_w(request
->custHeaders
[i
].lpszValue
));
737 ret
= HTTP_build_req(req
, 0);
742 static void HTTP_ProcessCookies( http_request_t
*request
)
746 LPHTTPHEADERW setCookieHeader
;
748 if(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
)
751 while((HeaderIndex
= HTTP_GetCustomHeaderIndex(request
, szSet_Cookie
, numCookies
++, FALSE
)) != -1)
757 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
759 if (!setCookieHeader
->lpszValue
)
762 host
= HTTP_GetHeader(request
, hostW
);
766 data
= strchrW(setCookieHeader
->lpszValue
, '=');
770 name
= heap_strndupW(setCookieHeader
->lpszValue
, data
-setCookieHeader
->lpszValue
);
775 set_cookie(host
->lpszValue
, request
->path
, name
, data
);
780 static void strip_spaces(LPWSTR start
)
785 while (*str
== ' ' && *str
!= '\0')
789 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
791 end
= start
+ strlenW(start
) - 1;
792 while (end
>= start
&& *end
== ' ')
799 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
801 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
802 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
804 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAYSIZE(szBasic
)) &&
805 ((pszAuthValue
[ARRAYSIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAYSIZE(szBasic
)]);
806 if (is_basic
&& pszRealm
)
809 LPCWSTR ptr
= &pszAuthValue
[ARRAYSIZE(szBasic
)];
813 token
= strchrW(ptr
,'=');
817 while (*realm
== ' ' && *realm
!= '\0')
819 if(!strncmpiW(realm
, szRealm
, ARRAYSIZE(szRealm
)) &&
820 (realm
[ARRAYSIZE(szRealm
)] == ' ' || realm
[ARRAYSIZE(szRealm
)] == '='))
823 while (*token
== ' ' && *token
!= '\0')
827 *pszRealm
= heap_strdupW(token
);
828 strip_spaces(*pszRealm
);
835 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
837 if (!authinfo
) return;
839 if (SecIsValidHandle(&authinfo
->ctx
))
840 DeleteSecurityContext(&authinfo
->ctx
);
841 if (SecIsValidHandle(&authinfo
->cred
))
842 FreeCredentialsHandle(&authinfo
->cred
);
844 heap_free(authinfo
->auth_data
);
845 heap_free(authinfo
->scheme
);
849 static UINT
retrieve_cached_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR
*auth_data
)
851 basicAuthorizationData
*ad
;
854 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
856 EnterCriticalSection(&authcache_cs
);
857 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
859 if (!strcmpiW(host
,ad
->host
) && !strcmpW(realm
,ad
->realm
))
861 TRACE("Authorization found in cache\n");
862 *auth_data
= heap_alloc(ad
->authorizationLen
);
863 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
864 rc
= ad
->authorizationLen
;
868 LeaveCriticalSection(&authcache_cs
);
872 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
875 basicAuthorizationData
* ad
= NULL
;
877 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
879 EnterCriticalSection(&authcache_cs
);
880 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
882 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
883 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
892 TRACE("Found match in cache, replacing\n");
893 heap_free(ad
->authorization
);
894 ad
->authorization
= heap_alloc(auth_data_len
);
895 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
896 ad
->authorizationLen
= auth_data_len
;
900 ad
= heap_alloc(sizeof(basicAuthorizationData
));
901 ad
->host
= heap_strdupW(host
);
902 ad
->realm
= heap_strdupW(realm
);
903 ad
->authorization
= heap_alloc(auth_data_len
);
904 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
905 ad
->authorizationLen
= auth_data_len
;
906 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
907 TRACE("authorization cached\n");
909 LeaveCriticalSection(&authcache_cs
);
912 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
913 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
915 authorizationData
*ad
;
917 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
919 EnterCriticalSection(&authcache_cs
);
920 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
921 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
922 TRACE("Authorization found in cache\n");
924 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
925 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
926 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
927 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
928 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
929 heap_free(nt_auth_identity
->User
);
930 heap_free(nt_auth_identity
->Password
);
931 heap_free(nt_auth_identity
->Domain
);
935 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
936 nt_auth_identity
->UserLength
= ad
->user_len
;
937 nt_auth_identity
->PasswordLength
= ad
->password_len
;
938 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
939 nt_auth_identity
->DomainLength
= ad
->domain_len
;
940 LeaveCriticalSection(&authcache_cs
);
944 LeaveCriticalSection(&authcache_cs
);
949 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
950 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
952 authorizationData
*ad
;
955 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
957 EnterCriticalSection(&authcache_cs
);
958 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
959 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
966 heap_free(ad
->password
);
967 heap_free(ad
->domain
);
969 ad
= heap_alloc(sizeof(authorizationData
));
971 LeaveCriticalSection(&authcache_cs
);
975 ad
->host
= heap_strdupW(host
);
976 ad
->scheme
= heap_strdupW(scheme
);
977 list_add_head(&authorizationCache
, &ad
->entry
);
980 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
981 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
982 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
983 ad
->user_len
= nt_auth_identity
->UserLength
;
984 ad
->password_len
= nt_auth_identity
->PasswordLength
;
985 ad
->domain_len
= nt_auth_identity
->DomainLength
;
987 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
988 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
990 heap_free(ad
->scheme
);
992 heap_free(ad
->password
);
993 heap_free(ad
->domain
);
994 list_remove(&ad
->entry
);
998 LeaveCriticalSection(&authcache_cs
);
1001 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
1002 struct HttpAuthInfo
**ppAuthInfo
,
1003 LPWSTR domain_and_username
, LPWSTR password
,
1006 SECURITY_STATUS sec_status
;
1007 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
1009 LPWSTR szRealm
= NULL
;
1011 TRACE("%s\n", debugstr_w(pszAuthValue
));
1018 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
1022 SecInvalidateHandle(&pAuthInfo
->cred
);
1023 SecInvalidateHandle(&pAuthInfo
->ctx
);
1024 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1025 pAuthInfo
->attr
= 0;
1026 pAuthInfo
->auth_data
= NULL
;
1027 pAuthInfo
->auth_data_len
= 0;
1028 pAuthInfo
->finished
= FALSE
;
1030 if (is_basic_auth_value(pszAuthValue
,NULL
))
1032 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1033 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1034 if (!pAuthInfo
->scheme
)
1036 heap_free(pAuthInfo
);
1043 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1045 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1046 if (!pAuthInfo
->scheme
)
1048 heap_free(pAuthInfo
);
1052 if (domain_and_username
)
1054 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1055 WCHAR
*domain
= domain_and_username
;
1057 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1059 pAuthData
= &nt_auth_identity
;
1064 user
= domain_and_username
;
1068 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1069 nt_auth_identity
.User
= user
;
1070 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1071 nt_auth_identity
.Domain
= domain
;
1072 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1073 nt_auth_identity
.Password
= password
;
1074 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1076 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1078 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1079 pAuthData
= &nt_auth_identity
;
1081 /* use default credentials */
1084 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1085 SECPKG_CRED_OUTBOUND
, NULL
,
1087 NULL
, &pAuthInfo
->cred
,
1090 if(pAuthData
&& !domain_and_username
) {
1091 heap_free(nt_auth_identity
.User
);
1092 heap_free(nt_auth_identity
.Domain
);
1093 heap_free(nt_auth_identity
.Password
);
1096 if (sec_status
== SEC_E_OK
)
1098 PSecPkgInfoW sec_pkg_info
;
1099 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1100 if (sec_status
== SEC_E_OK
)
1102 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1103 FreeContextBuffer(sec_pkg_info
);
1106 if (sec_status
!= SEC_E_OK
)
1108 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1109 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1110 heap_free(pAuthInfo
->scheme
);
1111 heap_free(pAuthInfo
);
1115 *ppAuthInfo
= pAuthInfo
;
1117 else if (pAuthInfo
->finished
)
1120 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1121 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1123 ERR("authentication scheme changed from %s to %s\n",
1124 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1128 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1132 char *auth_data
= NULL
;
1133 UINT auth_data_len
= 0;
1135 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1137 if (!domain_and_username
)
1139 if (host
&& szRealm
)
1140 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1141 if (auth_data_len
== 0)
1149 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1150 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1152 /* length includes a nul terminator, which will be re-used for the ':' */
1153 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1160 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1161 auth_data
[userlen
] = ':';
1162 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1163 auth_data_len
= userlen
+ 1 + passlen
;
1164 if (host
&& szRealm
)
1165 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1168 pAuthInfo
->auth_data
= auth_data
;
1169 pAuthInfo
->auth_data_len
= auth_data_len
;
1170 pAuthInfo
->finished
= TRUE
;
1176 LPCWSTR pszAuthData
;
1177 SecBufferDesc out_desc
, in_desc
;
1179 unsigned char *buffer
;
1180 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1181 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1183 in
.BufferType
= SECBUFFER_TOKEN
;
1187 in_desc
.ulVersion
= 0;
1188 in_desc
.cBuffers
= 1;
1189 in_desc
.pBuffers
= &in
;
1191 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1192 if (*pszAuthData
== ' ')
1195 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1196 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1197 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1200 buffer
= heap_alloc(pAuthInfo
->max_token
);
1202 out
.BufferType
= SECBUFFER_TOKEN
;
1203 out
.cbBuffer
= pAuthInfo
->max_token
;
1204 out
.pvBuffer
= buffer
;
1206 out_desc
.ulVersion
= 0;
1207 out_desc
.cBuffers
= 1;
1208 out_desc
.pBuffers
= &out
;
1210 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1211 first
? NULL
: &pAuthInfo
->ctx
,
1212 first
? request
->server
->name
: NULL
,
1213 context_req
, 0, SECURITY_NETWORK_DREP
,
1214 in
.pvBuffer
? &in_desc
: NULL
,
1215 0, &pAuthInfo
->ctx
, &out_desc
,
1216 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1217 if (sec_status
== SEC_E_OK
)
1219 pAuthInfo
->finished
= TRUE
;
1220 pAuthInfo
->auth_data
= out
.pvBuffer
;
1221 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1222 TRACE("sending last auth packet\n");
1224 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1226 pAuthInfo
->auth_data
= out
.pvBuffer
;
1227 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1228 TRACE("sending next auth packet\n");
1232 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1233 heap_free(out
.pvBuffer
);
1234 destroy_authinfo(pAuthInfo
);
1243 /***********************************************************************
1244 * HTTP_HttpAddRequestHeadersW (internal)
1246 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1247 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1252 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1254 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1256 if( dwHeaderLength
== ~0U )
1257 len
= strlenW(lpszHeader
);
1259 len
= dwHeaderLength
;
1260 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1261 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1267 LPWSTR
* pFieldAndValue
;
1269 lpszEnd
= lpszStart
;
1271 while (*lpszEnd
!= '\0')
1273 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1278 if (*lpszStart
== '\0')
1281 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1284 lpszEnd
++; /* Jump over newline */
1286 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1287 if (*lpszStart
== '\0')
1289 /* Skip 0-length headers */
1290 lpszStart
= lpszEnd
;
1291 res
= ERROR_SUCCESS
;
1294 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1297 res
= HTTP_VerifyValidHeader(request
, pFieldAndValue
[0]);
1298 if (res
== ERROR_SUCCESS
)
1299 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1300 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1301 HTTP_FreeTokens(pFieldAndValue
);
1304 lpszStart
= lpszEnd
;
1305 } while (res
== ERROR_SUCCESS
);
1311 /***********************************************************************
1312 * HttpAddRequestHeadersW (WININET.@)
1314 * Adds one or more HTTP header to the request handler
1317 * On Windows if dwHeaderLength includes the trailing '\0', then
1318 * HttpAddRequestHeadersW() adds it too. However this results in an
1319 * invalid HTTP header which is rejected by some servers so we probably
1320 * don't need to match Windows on that point.
1327 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1328 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1330 http_request_t
*request
;
1331 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1333 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1338 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1339 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1340 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1342 WININET_Release( &request
->hdr
);
1344 if(res
!= ERROR_SUCCESS
)
1346 return res
== ERROR_SUCCESS
;
1349 /***********************************************************************
1350 * HttpAddRequestHeadersA (WININET.@)
1352 * Adds one or more HTTP header to the request handler
1359 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1360 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1366 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1368 len
= MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, NULL
, 0 );
1369 hdr
= heap_alloc(len
*sizeof(WCHAR
));
1370 MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, hdr
, len
);
1371 if( dwHeaderLength
!= ~0U )
1372 dwHeaderLength
= len
;
1374 r
= HttpAddRequestHeadersW( hHttpRequest
, hdr
, dwHeaderLength
, dwModifier
);
1380 static void free_accept_types( WCHAR
**accept_types
)
1382 WCHAR
*ptr
, **types
= accept_types
;
1385 while ((ptr
= *types
))
1390 heap_free( accept_types
);
1393 static WCHAR
**convert_accept_types( const char **accept_types
)
1396 const char **types
= accept_types
;
1398 BOOL invalid_pointer
= FALSE
;
1400 if (!types
) return NULL
;
1406 /* find out how many there are */
1407 if (*types
&& **types
)
1409 TRACE("accept type: %s\n", debugstr_a(*types
));
1415 WARN("invalid accept type pointer\n");
1416 invalid_pointer
= TRUE
;
1421 if (invalid_pointer
) return NULL
;
1422 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1424 types
= accept_types
;
1427 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1430 typesW
[count
] = NULL
;
1434 /***********************************************************************
1435 * HttpOpenRequestA (WININET.@)
1437 * Open a HTTP request handle
1440 * HINTERNET a HTTP request handle on success
1444 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1445 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1446 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1447 DWORD dwFlags
, DWORD_PTR dwContext
)
1449 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1450 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1451 HINTERNET rc
= FALSE
;
1453 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1454 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1455 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1456 dwFlags
, dwContext
);
1460 szVerb
= heap_strdupAtoW(lpszVerb
);
1467 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1468 if ( !szObjectName
)
1474 szVersion
= heap_strdupAtoW(lpszVersion
);
1481 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1486 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1487 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1488 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1491 free_accept_types(szAcceptTypes
);
1492 heap_free(szReferrer
);
1493 heap_free(szVersion
);
1494 heap_free(szObjectName
);
1499 /***********************************************************************
1502 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1505 static const CHAR HTTP_Base64Enc
[] =
1506 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1510 /* first 6 bits, all from bin[0] */
1511 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1512 x
= (bin
[0] & 3) << 4;
1514 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1517 base64
[n
++] = HTTP_Base64Enc
[x
];
1522 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1523 x
= ( bin
[1] & 0x0f ) << 2;
1525 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1528 base64
[n
++] = HTTP_Base64Enc
[x
];
1532 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1534 /* last 6 bits, all from bin [2] */
1535 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1543 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1544 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1545 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1546 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1547 static const signed char HTTP_Base64Dec
[256] =
1549 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1550 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1551 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1552 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1553 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1554 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1555 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1556 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1557 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1558 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1559 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1560 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1561 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1562 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1563 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1564 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1565 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1566 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1567 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1568 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1569 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1570 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1571 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1572 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1573 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1574 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1578 /***********************************************************************
1581 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1589 if (base64
[0] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1590 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1591 base64
[1] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1592 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1594 WARN("invalid base64: %s\n", debugstr_w(base64
));
1598 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1601 if ((base64
[2] == '=') && (base64
[3] == '='))
1603 if (base64
[2] > ARRAYSIZE(HTTP_Base64Dec
) ||
1604 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1606 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1610 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1613 if (base64
[3] == '=')
1615 if (base64
[3] > ARRAYSIZE(HTTP_Base64Dec
) ||
1616 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1618 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1622 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1631 /***********************************************************************
1632 * HTTP_InsertAuthorization
1634 * Insert or delete the authorization field in the request header.
1636 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1640 static const WCHAR wszSpace
[] = {' ',0};
1641 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1643 WCHAR
*authorization
= NULL
;
1645 if (pAuthInfo
->auth_data_len
)
1647 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1648 len
= strlenW(pAuthInfo
->scheme
)+1+((pAuthInfo
->auth_data_len
+2)*4)/3;
1649 authorization
= heap_alloc((len
+1)*sizeof(WCHAR
));
1653 strcpyW(authorization
, pAuthInfo
->scheme
);
1654 strcatW(authorization
, wszSpace
);
1655 HTTP_EncodeBase64(pAuthInfo
->auth_data
,
1656 pAuthInfo
->auth_data_len
,
1657 authorization
+strlenW(authorization
));
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
, HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
);
1673 heap_free(authorization
);
1678 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1683 len
= strlenW(req
->server
->scheme_host_port
);
1684 size
= len
+ strlenW(req
->path
) + 1;
1685 if(*req
->path
!= '/')
1687 url
= heap_alloc(size
* sizeof(WCHAR
));
1691 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1692 if(*req
->path
!= '/')
1695 strcpyW(url
+len
, req
->path
);
1697 TRACE("url=%s\n", debugstr_w(url
));
1701 static BOOL
HTTP_DomainMatches(LPCWSTR server
, LPCWSTR domain
)
1703 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1706 if (!strcmpiW( domain
, localW
) && !strchrW( server
, '.' ))
1708 else if (*domain
== '*')
1710 if (domain
[1] == '.')
1714 /* For a hostname to match a wildcard, the last domain must match
1715 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1716 * hostname is www.foo.a.b, it matches, but a.b does not.
1718 dot
= strchrW( server
, '.' );
1721 int len
= strlenW( dot
+ 1 );
1723 if (len
> strlenW( domain
+ 2 ))
1727 /* The server's domain is longer than the wildcard, so it
1728 * could be a subdomain. Compare the last portion of the
1731 ptr
= dot
+ len
+ 1 - strlenW( domain
+ 2 );
1732 if (!strcmpiW( ptr
, domain
+ 2 ))
1734 /* This is only a match if the preceding character is
1735 * a '.', i.e. that it is a matching domain. E.g.
1736 * if domain is '*.b.c' and server is 'www.ab.c' they
1739 ret
= *(ptr
- 1) == '.';
1743 ret
= !strcmpiW( dot
+ 1, domain
+ 2 );
1748 ret
= !strcmpiW( server
, domain
);
1752 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1757 if (!lpwai
->proxyBypass
) return FALSE
;
1758 ptr
= lpwai
->proxyBypass
;
1762 ptr
= strchrW( ptr
, ';' );
1764 ptr
= strchrW( tmp
, ' ' );
1767 if (ptr
- tmp
< INTERNET_MAX_HOST_NAME_LENGTH
)
1769 WCHAR domain
[INTERNET_MAX_HOST_NAME_LENGTH
];
1771 memcpy( domain
, tmp
, (ptr
- tmp
) * sizeof(WCHAR
) );
1772 domain
[ptr
- tmp
] = 0;
1773 ret
= HTTP_DomainMatches( server
, domain
);
1778 ret
= HTTP_DomainMatches( server
, tmp
);
1779 } while (ptr
&& !ret
);
1783 /***********************************************************************
1784 * HTTP_DealWithProxy
1786 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1788 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1789 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1790 static const WCHAR szFormat
[] = { 'h','t','t','p',':','/','/','%','s',0 };
1791 WCHAR buf
[INTERNET_MAX_HOST_NAME_LENGTH
];
1792 WCHAR protoProxy
[INTERNET_MAX_URL_LENGTH
];
1793 DWORD protoProxyLen
= INTERNET_MAX_URL_LENGTH
;
1794 WCHAR proxy
[INTERNET_MAX_URL_LENGTH
];
1795 static WCHAR szNul
[] = { 0 };
1796 URL_COMPONENTSW UrlComponents
;
1797 server_t
*new_server
;
1800 memset( &UrlComponents
, 0, sizeof UrlComponents
);
1801 UrlComponents
.dwStructSize
= sizeof UrlComponents
;
1802 UrlComponents
.lpszHostName
= buf
;
1803 UrlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
1805 if (!INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
, protoProxy
, &protoProxyLen
))
1807 if( CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1808 protoProxy
,strlenW(szHttp
),szHttp
,strlenW(szHttp
)) )
1809 sprintfW(proxy
, szFormat
, protoProxy
);
1811 strcpyW(proxy
, protoProxy
);
1812 if( !InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) )
1814 if( UrlComponents
.dwHostNameLength
== 0 )
1817 if( !request
->path
)
1818 request
->path
= szNul
;
1820 is_https
= (UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
);
1821 if (is_https
&& UrlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
1822 UrlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
1824 new_server
= get_server(UrlComponents
.lpszHostName
, UrlComponents
.nPort
, is_https
, TRUE
);
1828 request
->proxy
= new_server
;
1830 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1834 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1836 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1840 if(server
->addr_len
)
1841 return ERROR_SUCCESS
;
1843 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1844 INTERNET_STATUS_RESOLVING_NAME
,
1846 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1848 addr_len
= sizeof(server
->addr
);
1849 if (!GetAddress(server
->name
, server
->port
, (struct sockaddr
*)&server
->addr
, &addr_len
))
1850 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1852 switch(server
->addr
.ss_family
) {
1854 addr
= &((struct sockaddr_in
*)&server
->addr
)->sin_addr
;
1857 addr
= &((struct sockaddr_in6
*)&server
->addr
)->sin6_addr
;
1860 WARN("unsupported family %d\n", server
->addr
.ss_family
);
1861 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1864 server
->addr_len
= addr_len
;
1865 inet_ntop(server
->addr
.ss_family
, addr
, server
->addr_str
, sizeof(server
->addr_str
));
1866 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1867 INTERNET_STATUS_NAME_RESOLVED
,
1868 server
->addr_str
, strlen(server
->addr_str
)+1);
1870 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1871 return ERROR_SUCCESS
;
1874 static BOOL
HTTP_GetRequestURL(http_request_t
*req
, LPWSTR buf
)
1876 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1877 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1878 static const WCHAR slash
[] = { '/',0 };
1879 LPHTTPHEADERW host_header
;
1882 host_header
= HTTP_GetHeader(req
, hostW
);
1886 if (req
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)
1890 strcpyW(buf
, scheme
);
1891 strcatW(buf
, host_header
->lpszValue
);
1892 if (req
->path
[0] != '/')
1893 strcatW(buf
, slash
);
1894 strcatW(buf
, req
->path
);
1899 /***********************************************************************
1900 * HTTPREQ_Destroy (internal)
1902 * Deallocate request handle
1905 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1907 http_request_t
*request
= (http_request_t
*) hdr
;
1912 if(request
->hCacheFile
) {
1913 CloseHandle(request
->hCacheFile
);
1914 DeleteFileW(request
->cacheFile
);
1916 heap_free(request
->cacheFile
);
1918 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1919 DeleteCriticalSection( &request
->read_section
);
1920 WININET_Release(&request
->session
->hdr
);
1922 destroy_authinfo(request
->authInfo
);
1923 destroy_authinfo(request
->proxyAuthInfo
);
1926 server_release(request
->server
);
1928 server_release(request
->proxy
);
1930 heap_free(request
->path
);
1931 heap_free(request
->verb
);
1932 heap_free(request
->version
);
1933 heap_free(request
->statusText
);
1935 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1937 heap_free(request
->custHeaders
[i
].lpszField
);
1938 heap_free(request
->custHeaders
[i
].lpszValue
);
1940 destroy_data_stream(request
->data_stream
);
1941 heap_free(request
->custHeaders
);
1944 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1946 TRACE("%p %p\n",req
, req
->netconn
);
1951 if(reuse
&& req
->netconn
->keep_alive
) {
1954 EnterCriticalSection(&connection_pool_cs
);
1956 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1957 req
->netconn
->keep_until
= GetTickCount64() + COLLECT_TIME
;
1958 req
->netconn
= NULL
;
1960 run_collector
= !collector_running
;
1961 collector_running
= TRUE
;
1963 LeaveCriticalSection(&connection_pool_cs
);
1966 HANDLE thread
= NULL
;
1969 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
1971 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
1973 EnterCriticalSection(&connection_pool_cs
);
1974 collector_running
= FALSE
;
1975 LeaveCriticalSection(&connection_pool_cs
);
1978 FreeLibrary(module
);
1981 CloseHandle(thread
);
1986 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1987 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
1989 free_netconn(req
->netconn
);
1990 req
->netconn
= NULL
;
1992 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1993 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
1996 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
1998 WCHAR szVersion
[10];
1999 WCHAR szConnectionResponse
[20];
2000 DWORD dwBufferSize
= sizeof(szVersion
);
2001 BOOL keepalive
= FALSE
;
2003 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2004 * the connection is keep-alive by default */
2005 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2006 && !strcmpiW(szVersion
, g_szHttp1_1
))
2011 dwBufferSize
= sizeof(szConnectionResponse
);
2012 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2013 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
2015 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2021 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2023 http_request_t
*req
= (http_request_t
*)hdr
;
2025 http_release_netconn(req
, drain_content(req
, FALSE
));
2028 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2034 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2036 *size
= (len
+ 1) * sizeof(WCHAR
);
2037 return ERROR_INSUFFICIENT_BUFFER
;
2039 strcpyW(buffer
, str
);
2041 return ERROR_SUCCESS
;
2045 len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, buffer
, *size
, NULL
, NULL
);
2049 return ERROR_INSUFFICIENT_BUFFER
;
2052 return ERROR_SUCCESS
;
2056 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2058 http_request_t
*req
= (http_request_t
*)hdr
;
2061 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2063 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2065 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2067 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2068 return ERROR_INSUFFICIENT_BUFFER
;
2069 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2070 /* FIXME: can't get a SOCKET from our connection since we don't use
2074 /* FIXME: get source port from req->netConnection */
2075 info
->SourcePort
= 0;
2076 info
->DestPort
= req
->server
->port
;
2078 if (HTTP_KeepAlive(req
))
2079 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2081 info
->Flags
|= IDSI_FLAG_PROXY
;
2082 if (req
->netconn
&& req
->netconn
->secure
)
2083 info
->Flags
|= IDSI_FLAG_SECURE
;
2085 return ERROR_SUCCESS
;
2089 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2091 case INTERNET_OPTION_SECURITY_FLAGS
:
2095 if (*size
< sizeof(ULONG
))
2096 return ERROR_INSUFFICIENT_BUFFER
;
2098 *size
= sizeof(DWORD
);
2099 flags
= req
->netconn
? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2100 *(DWORD
*)buffer
= flags
;
2102 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2103 return ERROR_SUCCESS
;
2106 case INTERNET_OPTION_HANDLE_TYPE
:
2107 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2109 if (*size
< sizeof(ULONG
))
2110 return ERROR_INSUFFICIENT_BUFFER
;
2112 *size
= sizeof(DWORD
);
2113 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2114 return ERROR_SUCCESS
;
2116 case INTERNET_OPTION_URL
: {
2117 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2120 static const WCHAR httpW
[] = {'h','t','t','p',':','/','/',0};
2122 TRACE("INTERNET_OPTION_URL\n");
2124 host
= HTTP_GetHeader(req
, hostW
);
2125 strcpyW(url
, httpW
);
2126 strcatW(url
, host
->lpszValue
);
2127 strcatW(url
, req
->path
);
2129 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url
));
2130 return str_to_buffer(url
, buffer
, size
, unicode
);
2132 case INTERNET_OPTION_USER_AGENT
:
2133 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2134 case INTERNET_OPTION_USERNAME
:
2135 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2136 case INTERNET_OPTION_PASSWORD
:
2137 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2138 case INTERNET_OPTION_PROXY_USERNAME
:
2139 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2140 case INTERNET_OPTION_PROXY_PASSWORD
:
2141 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2143 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2144 INTERNET_CACHE_ENTRY_INFOW
*info
;
2145 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2146 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2147 DWORD nbytes
, error
;
2150 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2152 if (*size
< sizeof(*ts
))
2154 *size
= sizeof(*ts
);
2155 return ERROR_INSUFFICIENT_BUFFER
;
2158 HTTP_GetRequestURL(req
, url
);
2159 ret
= GetUrlCacheEntryInfoW(url
, NULL
, &nbytes
);
2160 error
= GetLastError();
2161 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2163 if (!(info
= heap_alloc(nbytes
)))
2164 return ERROR_OUTOFMEMORY
;
2166 GetUrlCacheEntryInfoW(url
, info
, &nbytes
);
2168 ts
->ftExpires
= info
->ExpireTime
;
2169 ts
->ftLastModified
= info
->LastModifiedTime
;
2172 *size
= sizeof(*ts
);
2173 return ERROR_SUCCESS
;
2178 case INTERNET_OPTION_DATAFILE_NAME
: {
2181 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2183 if(!req
->cacheFile
) {
2185 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2189 req_size
= (lstrlenW(req
->cacheFile
)+1) * sizeof(WCHAR
);
2190 if(*size
< req_size
)
2191 return ERROR_INSUFFICIENT_BUFFER
;
2194 memcpy(buffer
, req
->cacheFile
, *size
);
2195 return ERROR_SUCCESS
;
2197 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->cacheFile
, -1, NULL
, 0, NULL
, NULL
);
2198 if (req_size
> *size
)
2199 return ERROR_INSUFFICIENT_BUFFER
;
2201 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->cacheFile
,
2202 -1, buffer
, *size
, NULL
, NULL
);
2203 return ERROR_SUCCESS
;
2207 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2208 PCCERT_CONTEXT context
;
2211 return ERROR_INTERNET_INVALID_OPERATION
;
2213 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2214 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2215 return ERROR_INSUFFICIENT_BUFFER
;
2218 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2220 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2223 memset(info
, 0, sizeof(*info
));
2224 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2225 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2226 len
= CertNameToStrA(context
->dwCertEncodingType
,
2227 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2228 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2229 if(info
->lpszSubjectInfo
)
2230 CertNameToStrA(context
->dwCertEncodingType
,
2231 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2232 info
->lpszSubjectInfo
, len
);
2233 len
= CertNameToStrA(context
->dwCertEncodingType
,
2234 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2235 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2236 if(info
->lpszIssuerInfo
)
2237 CertNameToStrA(context
->dwCertEncodingType
,
2238 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2239 info
->lpszIssuerInfo
, len
);
2240 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2241 CertFreeCertificateContext(context
);
2242 return ERROR_SUCCESS
;
2244 return ERROR_NOT_SUPPORTED
;
2246 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2247 if (*size
< sizeof(DWORD
))
2248 return ERROR_INSUFFICIENT_BUFFER
;
2250 *size
= sizeof(DWORD
);
2251 *(DWORD
*)buffer
= req
->connect_timeout
;
2252 return ERROR_SUCCESS
;
2253 case INTERNET_OPTION_REQUEST_FLAGS
: {
2256 if (*size
< sizeof(DWORD
))
2257 return ERROR_INSUFFICIENT_BUFFER
;
2259 /* FIXME: Add support for:
2260 * INTERNET_REQFLAG_FROM_CACHE
2261 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2265 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2266 if(!req
->status_code
)
2267 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2269 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2271 *size
= sizeof(DWORD
);
2272 *(DWORD
*)buffer
= flags
;
2273 return ERROR_SUCCESS
;
2277 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2280 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2282 http_request_t
*req
= (http_request_t
*)hdr
;
2285 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2286 TRACE("Undocumented option 99\n");
2288 if (!buffer
|| size
!= sizeof(DWORD
))
2289 return ERROR_INVALID_PARAMETER
;
2290 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2291 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2294 case INTERNET_OPTION_SECURITY_FLAGS
:
2298 if (!buffer
|| size
!= sizeof(DWORD
))
2299 return ERROR_INVALID_PARAMETER
;
2300 flags
= *(DWORD
*)buffer
;
2301 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2302 flags
&= SECURITY_SET_MASK
;
2303 req
->security_flags
|= flags
;
2305 req
->netconn
->security_flags
|= flags
;
2306 return ERROR_SUCCESS
;
2308 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2309 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2310 req
->connect_timeout
= *(DWORD
*)buffer
;
2311 return ERROR_SUCCESS
;
2313 case INTERNET_OPTION_SEND_TIMEOUT
:
2314 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2315 req
->send_timeout
= *(DWORD
*)buffer
;
2316 return ERROR_SUCCESS
;
2318 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2319 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2320 req
->receive_timeout
= *(DWORD
*)buffer
;
2321 return ERROR_SUCCESS
;
2323 case INTERNET_OPTION_USERNAME
:
2324 heap_free(req
->session
->userName
);
2325 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2326 return ERROR_SUCCESS
;
2328 case INTERNET_OPTION_PASSWORD
:
2329 heap_free(req
->session
->password
);
2330 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2331 return ERROR_SUCCESS
;
2333 case INTERNET_OPTION_PROXY_USERNAME
:
2334 heap_free(req
->session
->appInfo
->proxyUsername
);
2335 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2336 return ERROR_SUCCESS
;
2338 case INTERNET_OPTION_PROXY_PASSWORD
:
2339 heap_free(req
->session
->appInfo
->proxyPassword
);
2340 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2341 return ERROR_SUCCESS
;
2343 case INTERNET_OPTION_HTTP_DECODING
:
2344 if(size
!= sizeof(BOOL
))
2345 return ERROR_INVALID_PARAMETER
;
2346 req
->decoding
= *(BOOL
*)buffer
;
2347 return ERROR_SUCCESS
;
2350 return INET_SetOption(hdr
, option
, buffer
, size
);
2353 static void commit_cache_entry(http_request_t
*req
)
2355 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2359 CloseHandle(req
->hCacheFile
);
2360 req
->hCacheFile
= NULL
;
2362 if(HTTP_GetRequestURL(req
, url
)) {
2366 header
= build_response_header(req
, TRUE
);
2367 header_len
= (header
? strlenW(header
) : 0);
2368 CommitUrlCacheEntryW(url
, req
->cacheFile
, req
->expires
,
2369 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2370 header
, header_len
, NULL
, 0);
2375 static void create_cache_entry(http_request_t
*req
)
2377 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2378 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2380 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2381 WCHAR file_name
[MAX_PATH
+1];
2384 /* FIXME: We should free previous cache file earlier */
2385 heap_free(req
->cacheFile
);
2386 CloseHandle(req
->hCacheFile
);
2387 req
->hCacheFile
= NULL
;
2389 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2393 int header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2394 if(header_idx
!= -1) {
2397 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2400 while(*ptr
==' ' || *ptr
=='\t')
2403 end
= strchrW(ptr
, ',');
2405 end
= ptr
+ strlenW(ptr
);
2407 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2408 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2421 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2424 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2427 b
= HTTP_GetRequestURL(req
, url
);
2429 WARN("Could not get URL\n");
2433 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2435 WARN("Could not create cache entry: %08x\n", GetLastError());
2439 req
->cacheFile
= heap_strdupW(file_name
);
2440 req
->hCacheFile
= CreateFileW(req
->cacheFile
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2441 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2442 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2443 WARN("Could not create file: %u\n", GetLastError());
2444 req
->hCacheFile
= NULL
;
2448 if(req
->read_size
) {
2451 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2453 FIXME("WriteFile failed: %u\n", GetLastError());
2455 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2456 commit_cache_entry(req
);
2460 /* read some more data into the read buffer (the read section must be held) */
2461 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2468 /* move existing data to the start of the buffer */
2470 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2474 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2476 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2477 maxlen
- req
->read_size
, 0, &len
);
2478 if(res
== ERROR_SUCCESS
)
2479 req
->read_size
+= len
;
2484 /* remove some amount of data from the read buffer (the read section must be held) */
2485 static void remove_data( http_request_t
*req
, int count
)
2487 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2488 else req
->read_pos
+= count
;
2491 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2493 int count
, bytes_read
, pos
= 0;
2496 EnterCriticalSection( &req
->read_section
);
2499 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2503 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2504 bytes_read
= count
+ 1;
2506 else count
= bytes_read
= req
->read_size
;
2508 count
= min( count
, *len
- pos
);
2509 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2511 remove_data( req
, bytes_read
);
2514 if ((res
= read_more_data( req
, -1 )))
2516 WARN( "read failed %u\n", res
);
2517 LeaveCriticalSection( &req
->read_section
);
2520 if (!req
->read_size
)
2523 TRACE( "returning empty string\n" );
2524 LeaveCriticalSection( &req
->read_section
);
2525 return ERROR_SUCCESS
;
2528 LeaveCriticalSection( &req
->read_section
);
2532 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2535 buffer
[*len
- 1] = 0;
2536 TRACE( "returning %s\n", debugstr_a(buffer
));
2537 return ERROR_SUCCESS
;
2540 /* check if we have reached the end of the data to read (the read section must be held) */
2541 static BOOL
end_of_read_data( http_request_t
*req
)
2543 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2546 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, read_mode_t read_mode
)
2550 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, read_mode
);
2551 assert(*read
<= size
);
2553 if(req
->hCacheFile
) {
2558 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2560 FIXME("WriteFile failed: %u\n", GetLastError());
2563 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2564 commit_cache_entry(req
);
2570 /* fetch some more data into the read buffer (the read section must be held) */
2571 static DWORD
refill_read_buffer(http_request_t
*req
, read_mode_t read_mode
, DWORD
*read_bytes
)
2575 if(req
->read_size
== sizeof(req
->read_buf
))
2576 return ERROR_SUCCESS
;
2580 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2584 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2586 req
->read_size
+= read
;
2588 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2594 /* return the size of data available to be read immediately (the read section must be held) */
2595 static DWORD
get_avail_data( http_request_t
*req
)
2597 return req
->read_size
+ req
->data_stream
->vtbl
->get_avail_data(req
->data_stream
, req
);
2600 static DWORD
netconn_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2602 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2606 NETCON_query_data_available(req
->netconn
, &avail
);
2607 return netconn_stream
->content_length
== ~0u
2609 : min(avail
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2612 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2614 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2615 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !req
->netconn
;
2618 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2619 DWORD
*read
, read_mode_t read_mode
)
2621 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2622 DWORD res
= ERROR_SUCCESS
;
2625 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2627 if(read_mode
== READMODE_NOBLOCK
) {
2628 DWORD avail
= netconn_get_avail_data(stream
, req
);
2633 if(size
&& req
->netconn
) {
2634 if((res
= NETCON_recv(req
->netconn
, buf
, size
, read_mode
== READMODE_SYNC
? MSG_WAITALL
: 0, &len
)))
2637 netconn_stream
->content_length
= netconn_stream
->content_read
;
2640 netconn_stream
->content_read
+= *read
= len
;
2641 TRACE("read %u bytes\n", len
);
2645 static BOOL
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2647 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2652 if(netconn_end_of_data(stream
, req
))
2656 avail
= netconn_get_avail_data(stream
, req
);
2660 if(NETCON_recv(req
->netconn
, buf
, min(avail
, sizeof(buf
)), 0, &len
) != ERROR_SUCCESS
)
2663 netconn_stream
->content_read
+= len
;
2664 }while(netconn_stream
->content_read
< netconn_stream
->content_length
);
2669 static void netconn_destroy(data_stream_t
*stream
)
2673 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2674 netconn_get_avail_data
,
2675 netconn_end_of_data
,
2677 netconn_drain_content
,
2681 /* read some more data into the read buffer (the read section must be held) */
2682 static DWORD
read_more_chunked_data(chunked_stream_t
*stream
, http_request_t
*req
, int maxlen
)
2687 if (stream
->buf_pos
)
2689 /* move existing data to the start of the buffer */
2690 if(stream
->buf_size
)
2691 memmove(stream
->buf
, stream
->buf
+ stream
->buf_pos
, stream
->buf_size
);
2692 stream
->buf_pos
= 0;
2695 if (maxlen
== -1) maxlen
= sizeof(stream
->buf
);
2697 res
= NETCON_recv( req
->netconn
, stream
->buf
+ stream
->buf_size
,
2698 maxlen
- stream
->buf_size
, 0, &len
);
2699 if(res
== ERROR_SUCCESS
)
2700 stream
->buf_size
+= len
;
2705 /* remove some amount of data from the read buffer (the read section must be held) */
2706 static void remove_chunked_data(chunked_stream_t
*stream
, int count
)
2708 if (!(stream
->buf_size
-= count
)) stream
->buf_pos
= 0;
2709 else stream
->buf_pos
+= count
;
2712 /* discard data contents until we reach end of line (the read section must be held) */
2713 static DWORD
discard_chunked_eol(chunked_stream_t
*stream
, http_request_t
*req
)
2719 BYTE
*eol
= memchr(stream
->buf
+ stream
->buf_pos
, '\n', stream
->buf_size
);
2722 remove_chunked_data(stream
, (eol
+ 1) - (stream
->buf
+ stream
->buf_pos
));
2725 stream
->buf_pos
= stream
->buf_size
= 0; /* discard everything */
2726 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2727 } while (stream
->buf_size
);
2728 return ERROR_SUCCESS
;
2731 /* read the size of the next chunk (the read section must be held) */
2732 static DWORD
start_next_chunk(chunked_stream_t
*stream
, http_request_t
*req
)
2735 DWORD chunk_size
= 0, res
;
2737 if(stream
->chunk_size
!= ~0u && (res
= discard_chunked_eol(stream
, req
)) != ERROR_SUCCESS
)
2742 while (stream
->buf_size
)
2744 char ch
= stream
->buf
[stream
->buf_pos
];
2745 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
2746 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
2747 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
2748 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
2750 TRACE( "reading %u byte chunk\n", chunk_size
);
2751 stream
->chunk_size
= chunk_size
;
2752 req
->contentLength
+= chunk_size
;
2753 return discard_chunked_eol(stream
, req
);
2755 remove_chunked_data(stream
, 1);
2757 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2758 if (!stream
->buf_size
)
2760 stream
->chunk_size
= 0;
2761 return ERROR_SUCCESS
;
2766 static DWORD
chunked_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2768 /* Allow reading only from read buffer */
2772 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2774 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2775 return !chunked_stream
->chunk_size
;
2778 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2779 DWORD
*read
, read_mode_t read_mode
)
2781 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2782 DWORD read_bytes
= 0, ret_read
= 0, res
= ERROR_SUCCESS
;
2784 if(chunked_stream
->chunk_size
== ~0u) {
2785 res
= start_next_chunk(chunked_stream
, req
);
2786 if(res
!= ERROR_SUCCESS
)
2790 while(size
&& chunked_stream
->chunk_size
) {
2791 if(chunked_stream
->buf_size
) {
2792 read_bytes
= min(size
, min(chunked_stream
->buf_size
, chunked_stream
->chunk_size
));
2794 /* this could block */
2795 if(read_mode
== READMODE_NOBLOCK
&& read_bytes
== chunked_stream
->chunk_size
)
2798 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2799 remove_chunked_data(chunked_stream
, read_bytes
);
2801 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2803 if(read_mode
== READMODE_NOBLOCK
) {
2806 if(!req
->netconn
|| !NETCON_query_data_available(req
->netconn
, &avail
) || !avail
)
2808 if(read_bytes
> avail
)
2811 /* this could block */
2812 if(read_bytes
== chunked_stream
->chunk_size
)
2816 res
= NETCON_recv(req
->netconn
, (char *)buf
+ret_read
, read_bytes
, 0, (int*)&read_bytes
);
2817 if(res
!= ERROR_SUCCESS
)
2821 chunked_stream
->chunk_size
-= read_bytes
;
2823 ret_read
+= read_bytes
;
2824 if(!chunked_stream
->chunk_size
) {
2825 assert(read_mode
!= READMODE_NOBLOCK
);
2826 res
= start_next_chunk(chunked_stream
, req
);
2827 if(res
!= ERROR_SUCCESS
)
2831 if(read_mode
== READMODE_ASYNC
)
2832 read_mode
= READMODE_NOBLOCK
;
2835 TRACE("read %u bytes\n", ret_read
);
2840 static BOOL
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2842 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2844 /* FIXME: we can do better */
2845 return !chunked_stream
->chunk_size
;
2848 static void chunked_destroy(data_stream_t
*stream
)
2850 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2851 heap_free(chunked_stream
);
2854 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2855 chunked_get_avail_data
,
2856 chunked_end_of_data
,
2858 chunked_drain_content
,
2862 /* set the request content length based on the headers */
2863 static DWORD
set_content_length(http_request_t
*request
)
2865 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2869 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
) {
2870 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2871 return ERROR_SUCCESS
;
2874 size
= sizeof(request
->contentLength
);
2875 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2876 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2877 request
->contentLength
= ~0u;
2878 request
->netconn_stream
.content_length
= request
->contentLength
;
2879 request
->netconn_stream
.content_read
= request
->read_size
;
2881 size
= sizeof(encoding
);
2882 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2883 !strcmpiW(encoding
, szChunked
))
2885 chunked_stream_t
*chunked_stream
;
2887 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2889 return ERROR_OUTOFMEMORY
;
2891 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2892 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2893 chunked_stream
->chunk_size
= ~0u;
2895 if(request
->read_size
) {
2896 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2897 chunked_stream
->buf_size
= request
->read_size
;
2898 request
->read_size
= request
->read_pos
= 0;
2901 request
->data_stream
= &chunked_stream
->data_stream
;
2902 request
->contentLength
= ~0u;
2903 request
->read_chunked
= TRUE
;
2906 if(request
->decoding
) {
2909 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2911 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2912 if(encoding_idx
!= -1 && !strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2913 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2914 return init_gzip_stream(request
);
2918 return ERROR_SUCCESS
;
2921 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
2923 INTERNET_ASYNC_RESULT iar
;
2925 iar
.dwResult
= result
;
2926 iar
.dwError
= error
;
2928 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
2929 sizeof(INTERNET_ASYNC_RESULT
));
2932 static void HTTP_ReceiveRequestData(http_request_t
*req
, BOOL first_notif
, DWORD
*ret_size
)
2934 DWORD res
, read
= 0, avail
= 0;
2939 EnterCriticalSection( &req
->read_section
);
2941 mode
= first_notif
&& req
->read_size
? READMODE_NOBLOCK
: READMODE_ASYNC
;
2942 res
= refill_read_buffer(req
, mode
, &read
);
2943 if(res
== ERROR_SUCCESS
)
2944 avail
= get_avail_data(req
);
2946 LeaveCriticalSection( &req
->read_section
);
2948 if(res
!= ERROR_SUCCESS
|| (mode
!= READMODE_NOBLOCK
&& !read
)) {
2949 WARN("res %u read %u, closing connection\n", res
, read
);
2950 http_release_netconn(req
, FALSE
);
2953 if(res
!= ERROR_SUCCESS
) {
2954 send_request_complete(req
, 0, res
);
2963 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, avail
);
2966 /* read data from the http connection (the read section must be held) */
2967 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
, BOOL sync
)
2969 DWORD current_read
= 0, ret_read
= 0;
2970 read_mode_t read_mode
;
2971 DWORD res
= ERROR_SUCCESS
;
2973 read_mode
= req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
? READMODE_ASYNC
: READMODE_SYNC
;
2975 EnterCriticalSection( &req
->read_section
);
2977 if(req
->read_size
) {
2978 ret_read
= min(size
, req
->read_size
);
2979 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
2980 req
->read_size
-= ret_read
;
2981 req
->read_pos
+= ret_read
;
2982 if(read_mode
== READMODE_ASYNC
)
2983 read_mode
= READMODE_NOBLOCK
;
2986 if(ret_read
< size
) {
2987 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, read_mode
);
2988 ret_read
+= current_read
;
2991 LeaveCriticalSection( &req
->read_section
);
2994 TRACE( "retrieved %u bytes (%u)\n", ret_read
, req
->contentLength
);
2996 if(size
&& !ret_read
)
2997 http_release_netconn(req
, res
== ERROR_SUCCESS
);
3002 static BOOL
drain_content(http_request_t
*req
, BOOL blocking
)
3006 if(!req
->netconn
|| req
->contentLength
== -1)
3009 if(!strcmpW(req
->verb
, szHEAD
))
3013 return req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
);
3015 EnterCriticalSection( &req
->read_section
);
3018 DWORD bytes_read
, res
;
3021 res
= HTTPREQ_Read(req
, buf
, sizeof(buf
), &bytes_read
, TRUE
);
3022 if(res
!= ERROR_SUCCESS
) {
3032 LeaveCriticalSection( &req
->read_section
);
3036 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buffer
, DWORD size
, DWORD
*read
)
3038 http_request_t
*req
= (http_request_t
*)hdr
;
3041 EnterCriticalSection( &req
->read_section
);
3042 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3043 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3045 res
= HTTPREQ_Read(req
, buffer
, size
, read
, TRUE
);
3046 if(res
== ERROR_SUCCESS
)
3048 LeaveCriticalSection( &req
->read_section
);
3058 } read_file_ex_task_t
;
3060 static void AsyncReadFileExProc(task_header_t
*hdr
)
3062 read_file_ex_task_t
*task
= (read_file_ex_task_t
*)hdr
;
3063 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3066 TRACE("INTERNETREADFILEEXW %p\n", task
->hdr
.hdr
);
3068 res
= HTTPREQ_Read(req
, task
->buf
, task
->size
, task
->ret_read
, TRUE
);
3069 send_request_complete(req
, res
== ERROR_SUCCESS
, res
);
3072 static DWORD
HTTPREQ_ReadFileEx(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3073 DWORD flags
, DWORD_PTR context
)
3076 http_request_t
*req
= (http_request_t
*)hdr
;
3077 DWORD res
, read
, cread
, error
= ERROR_SUCCESS
;
3079 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3080 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3082 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3084 if (hdr
->dwFlags
& INTERNET_FLAG_ASYNC
)
3086 read_file_ex_task_t
*task
;
3088 if (TryEnterCriticalSection( &req
->read_section
))
3090 if (get_avail_data(req
))
3092 res
= HTTPREQ_Read(req
, buf
, size
, &read
, FALSE
);
3093 LeaveCriticalSection( &req
->read_section
);
3096 LeaveCriticalSection( &req
->read_section
);
3099 task
= alloc_async_task(&req
->hdr
, AsyncReadFileExProc
, sizeof(*task
));
3102 task
->ret_read
= ret_read
;
3104 INTERNET_AsyncCall(&task
->hdr
);
3106 return ERROR_IO_PENDING
;
3111 EnterCriticalSection( &req
->read_section
);
3112 if(hdr
->dwError
== ERROR_SUCCESS
)
3113 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3114 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3115 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3118 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
, !(flags
& IRF_NO_WAIT
));
3119 if(res
!= ERROR_SUCCESS
)
3123 if(read
== size
|| end_of_read_data(req
))
3126 LeaveCriticalSection( &req
->read_section
);
3128 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3129 &cread
, sizeof(cread
));
3130 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
3131 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3133 EnterCriticalSection( &req
->read_section
);
3136 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3137 hdr
->dwError
= ERROR_SUCCESS
;
3139 error
= hdr
->dwError
;
3141 LeaveCriticalSection( &req
->read_section
);
3145 if (res
== ERROR_SUCCESS
) {
3146 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3147 &read
, sizeof(read
));
3150 return res
==ERROR_SUCCESS
? error
: res
;
3153 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3156 http_request_t
*request
= (http_request_t
*)hdr
;
3158 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3161 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3162 if (res
== ERROR_SUCCESS
)
3163 request
->bytesWritten
+= *written
;
3165 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3172 } http_data_available_task_t
;
3174 static void AsyncQueryDataAvailableProc(task_header_t
*hdr
)
3176 http_data_available_task_t
*task
= (http_data_available_task_t
*)hdr
;
3178 HTTP_ReceiveRequestData((http_request_t
*)task
->hdr
.hdr
, FALSE
, task
->ret_size
);
3181 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3183 http_request_t
*req
= (http_request_t
*)hdr
;
3185 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3187 if (req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
3189 http_data_available_task_t
*task
;
3191 /* never wait, if we can't enter the section we queue an async request right away */
3192 if (TryEnterCriticalSection( &req
->read_section
))
3194 refill_read_buffer(req
, READMODE_NOBLOCK
, NULL
);
3195 if ((*available
= get_avail_data( req
))) goto done
;
3196 if (end_of_read_data( req
)) goto done
;
3197 LeaveCriticalSection( &req
->read_section
);
3200 task
= alloc_async_task(&req
->hdr
, AsyncQueryDataAvailableProc
, sizeof(*task
));
3201 task
->ret_size
= available
;
3202 INTERNET_AsyncCall(&task
->hdr
);
3203 return ERROR_IO_PENDING
;
3206 EnterCriticalSection( &req
->read_section
);
3208 if (!(*available
= get_avail_data( req
)) && !end_of_read_data( req
))
3210 refill_read_buffer( req
, READMODE_ASYNC
, NULL
);
3211 *available
= get_avail_data( req
);
3215 LeaveCriticalSection( &req
->read_section
);
3217 TRACE( "returning %u\n", *available
);
3218 return ERROR_SUCCESS
;
3221 static const object_vtbl_t HTTPREQVtbl
= {
3223 HTTPREQ_CloseConnection
,
3224 HTTPREQ_QueryOption
,
3229 HTTPREQ_QueryDataAvailable
,
3233 /***********************************************************************
3234 * HTTP_HttpOpenRequestW (internal)
3236 * Open a HTTP request handle
3239 * HINTERNET a HTTP request handle on success
3243 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3244 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3245 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3246 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3248 appinfo_t
*hIC
= session
->appInfo
;
3249 http_request_t
*request
;
3250 DWORD len
, res
= ERROR_SUCCESS
;
3254 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3256 return ERROR_OUTOFMEMORY
;
3258 request
->hdr
.htype
= WH_HHTTPREQ
;
3259 request
->hdr
.dwFlags
= dwFlags
;
3260 request
->hdr
.dwContext
= dwContext
;
3261 request
->contentLength
= ~0u;
3263 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3264 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3265 request
->connect_timeout
= session
->connect_timeout
;
3266 request
->send_timeout
= session
->send_timeout
;
3267 request
->receive_timeout
= session
->receive_timeout
;
3269 InitializeCriticalSection( &request
->read_section
);
3270 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3272 WININET_AddRef( &session
->hdr
);
3273 request
->session
= session
;
3274 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3276 request
->server
= get_server(session
->hostName
, session
->hostPort
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3277 if(!request
->server
) {
3278 WININET_Release(&request
->hdr
);
3279 return ERROR_OUTOFMEMORY
;
3282 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3283 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3284 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3285 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3287 if (lpszObjectName
&& *lpszObjectName
) {
3291 rc
= UrlEscapeW(lpszObjectName
, NULL
, &len
, URL_ESCAPE_SPACES_ONLY
);
3292 if (rc
!= E_POINTER
)
3293 len
= strlenW(lpszObjectName
)+1;
3294 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3295 rc
= UrlEscapeW(lpszObjectName
, request
->path
, &len
,
3296 URL_ESCAPE_SPACES_ONLY
);
3299 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3300 strcpyW(request
->path
,lpszObjectName
);
3303 static const WCHAR slashW
[] = {'/',0};
3305 request
->path
= heap_strdupW(slashW
);
3308 if (lpszReferrer
&& *lpszReferrer
)
3309 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3311 if (lpszAcceptTypes
)
3314 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3316 if (!*lpszAcceptTypes
[i
]) continue;
3317 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3318 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3319 HTTP_ADDHDR_FLAG_REQ
|
3320 (i
== 0 ? HTTP_ADDHDR_FLAG_REPLACE
: 0));
3324 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3325 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3327 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3329 if (session
->hostPort
== INTERNET_INVALID_PORT_NUMBER
)
3330 session
->hostPort
= INTERNET_DEFAULT_HTTP_PORT
;
3332 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3333 HTTP_DealWithProxy( hIC
, session
, request
);
3335 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3336 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3339 TRACE("<-- %u (%p)\n", res
, request
);
3341 if(res
!= ERROR_SUCCESS
) {
3342 WININET_Release( &request
->hdr
);
3347 *ret
= request
->hdr
.hInternet
;
3348 return ERROR_SUCCESS
;
3351 /***********************************************************************
3352 * HttpOpenRequestW (WININET.@)
3354 * Open a HTTP request handle
3357 * HINTERNET a HTTP request handle on success
3361 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3362 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3363 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3364 DWORD dwFlags
, DWORD_PTR dwContext
)
3366 http_session_t
*session
;
3367 HINTERNET handle
= NULL
;
3370 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3371 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3372 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3373 dwFlags
, dwContext
);
3374 if(lpszAcceptTypes
!=NULL
)
3377 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3378 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3381 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3382 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3384 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3389 * My tests seem to show that the windows version does not
3390 * become asynchronous until after this point. And anyhow
3391 * if this call was asynchronous then how would you get the
3392 * necessary HINTERNET pointer returned by this function.
3395 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3396 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3397 dwFlags
, dwContext
, &handle
);
3400 WININET_Release( &session
->hdr
);
3401 TRACE("returning %p\n", handle
);
3402 if(res
!= ERROR_SUCCESS
)
3407 static const LPCWSTR header_lookup
[] = {
3408 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3409 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3410 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3411 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3412 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3413 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3414 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3415 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3416 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3417 szDate
, /* HTTP_QUERY_DATE = 9 */
3418 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3419 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3420 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3421 szURI
, /* HTTP_QUERY_URI = 13 */
3422 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3423 NULL
, /* HTTP_QUERY_COST = 15 */
3424 NULL
, /* HTTP_QUERY_LINK = 16 */
3425 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3426 NULL
, /* HTTP_QUERY_VERSION = 18 */
3427 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3428 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3429 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3430 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3431 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3432 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3433 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3434 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3435 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3436 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3437 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3438 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3439 NULL
, /* HTTP_QUERY_FROM = 31 */
3440 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3441 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3442 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3443 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3444 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3445 szServer
, /* HTTP_QUERY_SERVER = 37 */
3446 NULL
, /* HTTP_TITLE = 38 */
3447 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3448 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3449 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3450 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3451 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3452 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3453 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3454 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3455 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3456 szAge
, /* HTTP_QUERY_AGE = 48 */
3457 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3458 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3459 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3460 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3461 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3462 szETag
, /* HTTP_QUERY_ETAG = 54 */
3463 hostW
, /* HTTP_QUERY_HOST = 55 */
3464 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3465 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3466 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3467 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3468 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3469 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3470 szRange
, /* HTTP_QUERY_RANGE = 62 */
3471 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3472 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3473 szVary
, /* HTTP_QUERY_VARY = 65 */
3474 szVia
, /* HTTP_QUERY_VIA = 66 */
3475 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3476 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3477 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3478 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3481 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3483 /***********************************************************************
3484 * HTTP_HttpQueryInfoW (internal)
3486 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3487 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3489 LPHTTPHEADERW lphttpHdr
= NULL
;
3490 BOOL request_only
= dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
;
3491 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3492 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3495 /* Find requested header structure */
3498 case HTTP_QUERY_CUSTOM
:
3499 if (!lpBuffer
) return ERROR_INVALID_PARAMETER
;
3500 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3502 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3506 DWORD res
= ERROR_INVALID_PARAMETER
;
3509 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3511 headers
= build_response_header(request
, TRUE
);
3513 return ERROR_OUTOFMEMORY
;
3515 len
= strlenW(headers
) * sizeof(WCHAR
);
3516 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3518 len
+= sizeof(WCHAR
);
3519 res
= ERROR_INSUFFICIENT_BUFFER
;
3523 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3524 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3525 res
= ERROR_SUCCESS
;
3527 *lpdwBufferLength
= len
;
3532 case HTTP_QUERY_RAW_HEADERS
:
3538 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3540 headers
= build_response_header(request
, FALSE
);
3542 return ERROR_OUTOFMEMORY
;
3544 len
= strlenW(headers
) * sizeof(WCHAR
);
3545 if (len
> *lpdwBufferLength
)
3547 *lpdwBufferLength
= len
;
3549 return ERROR_INSUFFICIENT_BUFFER
;
3556 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3558 for (i
=0; i
<len
; i
++)
3560 if (headers
[i
] == '\n')
3563 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3565 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3568 return ERROR_SUCCESS
;
3570 case HTTP_QUERY_STATUS_TEXT
:
3571 if (request
->statusText
)
3573 DWORD len
= strlenW(request
->statusText
);
3574 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3576 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3577 return ERROR_INSUFFICIENT_BUFFER
;
3581 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3582 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3584 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3585 return ERROR_SUCCESS
;
3588 case HTTP_QUERY_VERSION
:
3589 if (request
->version
)
3591 DWORD len
= strlenW(request
->version
);
3592 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3594 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3595 return ERROR_INSUFFICIENT_BUFFER
;
3599 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3600 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3602 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3603 return ERROR_SUCCESS
;
3606 case HTTP_QUERY_CONTENT_ENCODING
:
3607 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3608 requested_index
,request_only
);
3610 case HTTP_QUERY_STATUS_CODE
: {
3611 DWORD res
= ERROR_SUCCESS
;
3614 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3619 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3620 if(*lpdwBufferLength
>= sizeof(DWORD
))
3621 *(DWORD
*)lpBuffer
= request
->status_code
;
3623 res
= ERROR_INSUFFICIENT_BUFFER
;
3624 *lpdwBufferLength
= sizeof(DWORD
);
3628 static const WCHAR formatW
[] = {'%','u',0};
3630 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3632 if(size
<= *lpdwBufferLength
) {
3633 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3635 size
+= sizeof(WCHAR
);
3636 res
= ERROR_INSUFFICIENT_BUFFER
;
3639 *lpdwBufferLength
= size
;
3644 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3646 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3647 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3648 requested_index
,request_only
);
3652 lphttpHdr
= &request
->custHeaders
[index
];
3654 /* Ensure header satisfies requested attributes */
3656 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3657 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3659 return ERROR_HTTP_HEADER_NOT_FOUND
;
3662 if (lpdwIndex
) (*lpdwIndex
)++;
3664 /* coalesce value to requested type */
3665 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3667 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3668 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3670 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3676 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3678 tmpTM
= *gmtime(&tmpTime
);
3679 STHook
= (SYSTEMTIME
*)lpBuffer
;
3680 STHook
->wDay
= tmpTM
.tm_mday
;
3681 STHook
->wHour
= tmpTM
.tm_hour
;
3682 STHook
->wMilliseconds
= 0;
3683 STHook
->wMinute
= tmpTM
.tm_min
;
3684 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3685 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3686 STHook
->wSecond
= tmpTM
.tm_sec
;
3687 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3689 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3690 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3691 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3693 else if (lphttpHdr
->lpszValue
)
3695 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3697 if (len
> *lpdwBufferLength
)
3699 *lpdwBufferLength
= len
;
3700 return ERROR_INSUFFICIENT_BUFFER
;
3704 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3705 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3707 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3709 return ERROR_SUCCESS
;
3712 /***********************************************************************
3713 * HttpQueryInfoW (WININET.@)
3715 * Queries for information about an HTTP request
3722 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3723 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3725 http_request_t
*request
;
3728 if (TRACE_ON(wininet
)) {
3729 #define FE(x) { x, #x }
3730 static const wininet_flag_info query_flags
[] = {
3731 FE(HTTP_QUERY_MIME_VERSION
),
3732 FE(HTTP_QUERY_CONTENT_TYPE
),
3733 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3734 FE(HTTP_QUERY_CONTENT_ID
),
3735 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3736 FE(HTTP_QUERY_CONTENT_LENGTH
),
3737 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3738 FE(HTTP_QUERY_ALLOW
),
3739 FE(HTTP_QUERY_PUBLIC
),
3740 FE(HTTP_QUERY_DATE
),
3741 FE(HTTP_QUERY_EXPIRES
),
3742 FE(HTTP_QUERY_LAST_MODIFIED
),
3743 FE(HTTP_QUERY_MESSAGE_ID
),
3745 FE(HTTP_QUERY_DERIVED_FROM
),
3746 FE(HTTP_QUERY_COST
),
3747 FE(HTTP_QUERY_LINK
),
3748 FE(HTTP_QUERY_PRAGMA
),
3749 FE(HTTP_QUERY_VERSION
),
3750 FE(HTTP_QUERY_STATUS_CODE
),
3751 FE(HTTP_QUERY_STATUS_TEXT
),
3752 FE(HTTP_QUERY_RAW_HEADERS
),
3753 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3754 FE(HTTP_QUERY_CONNECTION
),
3755 FE(HTTP_QUERY_ACCEPT
),
3756 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3757 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3758 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3759 FE(HTTP_QUERY_AUTHORIZATION
),
3760 FE(HTTP_QUERY_CONTENT_ENCODING
),
3761 FE(HTTP_QUERY_FORWARDED
),
3762 FE(HTTP_QUERY_FROM
),
3763 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3764 FE(HTTP_QUERY_LOCATION
),
3765 FE(HTTP_QUERY_ORIG_URI
),
3766 FE(HTTP_QUERY_REFERER
),
3767 FE(HTTP_QUERY_RETRY_AFTER
),
3768 FE(HTTP_QUERY_SERVER
),
3769 FE(HTTP_QUERY_TITLE
),
3770 FE(HTTP_QUERY_USER_AGENT
),
3771 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3772 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3773 FE(HTTP_QUERY_ACCEPT_RANGES
),
3774 FE(HTTP_QUERY_SET_COOKIE
),
3775 FE(HTTP_QUERY_COOKIE
),
3776 FE(HTTP_QUERY_REQUEST_METHOD
),
3777 FE(HTTP_QUERY_REFRESH
),
3778 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3780 FE(HTTP_QUERY_CACHE_CONTROL
),
3781 FE(HTTP_QUERY_CONTENT_BASE
),
3782 FE(HTTP_QUERY_CONTENT_LOCATION
),
3783 FE(HTTP_QUERY_CONTENT_MD5
),
3784 FE(HTTP_QUERY_CONTENT_RANGE
),
3785 FE(HTTP_QUERY_ETAG
),
3786 FE(HTTP_QUERY_HOST
),
3787 FE(HTTP_QUERY_IF_MATCH
),
3788 FE(HTTP_QUERY_IF_NONE_MATCH
),
3789 FE(HTTP_QUERY_IF_RANGE
),
3790 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3791 FE(HTTP_QUERY_MAX_FORWARDS
),
3792 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3793 FE(HTTP_QUERY_RANGE
),
3794 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3795 FE(HTTP_QUERY_UPGRADE
),
3796 FE(HTTP_QUERY_VARY
),
3798 FE(HTTP_QUERY_WARNING
),
3799 FE(HTTP_QUERY_CUSTOM
)
3801 static const wininet_flag_info modifier_flags
[] = {
3802 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3803 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3804 FE(HTTP_QUERY_FLAG_NUMBER
),
3805 FE(HTTP_QUERY_FLAG_COALESCE
)
3808 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3809 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3812 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3813 TRACE(" Attribute:");
3814 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3815 if (query_flags
[i
].val
== info
) {
3816 TRACE(" %s", query_flags
[i
].name
);
3820 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3821 TRACE(" Unknown (%08x)", info
);
3824 TRACE(" Modifier:");
3825 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3826 if (modifier_flags
[i
].val
& info_mod
) {
3827 TRACE(" %s", modifier_flags
[i
].name
);
3828 info_mod
&= ~ modifier_flags
[i
].val
;
3833 TRACE(" Unknown (%08x)", info_mod
);
3838 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3839 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3841 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3845 if (lpBuffer
== NULL
)
3846 *lpdwBufferLength
= 0;
3847 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3848 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3852 WININET_Release( &request
->hdr
);
3854 TRACE("%u <--\n", res
);
3855 if(res
!= ERROR_SUCCESS
)
3857 return res
== ERROR_SUCCESS
;
3860 /***********************************************************************
3861 * HttpQueryInfoA (WININET.@)
3863 * Queries for information about an HTTP request
3870 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3871 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3877 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3878 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3880 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3881 lpdwBufferLength
, lpdwIndex
);
3887 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
3888 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3890 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
3896 bufferW
= heap_alloc(alloclen
);
3897 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3898 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3899 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
3906 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
3910 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
3911 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
3912 *lpdwBufferLength
= len
- 1;
3914 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
3917 /* since the strings being returned from HttpQueryInfoW should be
3918 * only ASCII characters, it is reasonable to assume that all of
3919 * the Unicode characters can be reduced to a single byte */
3920 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
3922 heap_free( bufferW
);
3926 /***********************************************************************
3927 * HTTP_GetRedirectURL (internal)
3929 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*request
, LPCWSTR lpszUrl
)
3931 static WCHAR szHttp
[] = {'h','t','t','p',0};
3932 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
3933 http_session_t
*session
= request
->session
;
3934 URL_COMPONENTSW urlComponents
;
3935 DWORD url_length
= 0;
3937 LPWSTR combined_url
;
3939 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
3940 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
3941 urlComponents
.dwSchemeLength
= 0;
3942 urlComponents
.lpszHostName
= session
->hostName
;
3943 urlComponents
.dwHostNameLength
= 0;
3944 urlComponents
.nPort
= session
->hostPort
;
3945 urlComponents
.lpszUserName
= session
->userName
;
3946 urlComponents
.dwUserNameLength
= 0;
3947 urlComponents
.lpszPassword
= NULL
;
3948 urlComponents
.dwPasswordLength
= 0;
3949 urlComponents
.lpszUrlPath
= request
->path
;
3950 urlComponents
.dwUrlPathLength
= 0;
3951 urlComponents
.lpszExtraInfo
= NULL
;
3952 urlComponents
.dwExtraInfoLength
= 0;
3954 if (!InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
) &&
3955 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
3958 orig_url
= heap_alloc(url_length
);
3960 /* convert from bytes to characters */
3961 url_length
= url_length
/ sizeof(WCHAR
) - 1;
3962 if (!InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
))
3964 heap_free(orig_url
);
3969 if (!InternetCombineUrlW(orig_url
, lpszUrl
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
) &&
3970 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
3972 heap_free(orig_url
);
3975 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
3977 if (!InternetCombineUrlW(orig_url
, lpszUrl
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
))
3979 heap_free(orig_url
);
3980 heap_free(combined_url
);
3983 heap_free(orig_url
);
3984 return combined_url
;
3988 /***********************************************************************
3989 * HTTP_HandleRedirect (internal)
3991 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, LPCWSTR lpszUrl
)
3993 http_session_t
*session
= request
->session
;
3994 WCHAR path
[INTERNET_MAX_PATH_LENGTH
];
3999 /* if it's an absolute path, keep the same session info */
4000 lstrcpynW(path
, lpszUrl
, INTERNET_MAX_URL_LENGTH
);
4004 URL_COMPONENTSW urlComponents
;
4005 WCHAR protocol
[INTERNET_MAX_SCHEME_LENGTH
];
4006 WCHAR hostName
[INTERNET_MAX_HOST_NAME_LENGTH
];
4007 WCHAR userName
[INTERNET_MAX_USER_NAME_LENGTH
];
4008 BOOL custom_port
= FALSE
;
4010 static WCHAR httpW
[] = {'h','t','t','p',0};
4011 static WCHAR httpsW
[] = {'h','t','t','p','s',0};
4017 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
4018 urlComponents
.lpszScheme
= protocol
;
4019 urlComponents
.dwSchemeLength
= INTERNET_MAX_SCHEME_LENGTH
;
4020 urlComponents
.lpszHostName
= hostName
;
4021 urlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
4022 urlComponents
.lpszUserName
= userName
;
4023 urlComponents
.dwUserNameLength
= INTERNET_MAX_USER_NAME_LENGTH
;
4024 urlComponents
.lpszPassword
= NULL
;
4025 urlComponents
.dwPasswordLength
= 0;
4026 urlComponents
.lpszUrlPath
= path
;
4027 urlComponents
.dwUrlPathLength
= INTERNET_MAX_PATH_LENGTH
;
4028 urlComponents
.lpszExtraInfo
= NULL
;
4029 urlComponents
.dwExtraInfoLength
= 0;
4030 if(!InternetCrackUrlW(lpszUrl
, strlenW(lpszUrl
), 0, &urlComponents
))
4031 return INTERNET_GetLastError();
4033 if(!strcmpiW(protocol
, httpW
)) {
4034 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4035 TRACE("redirect from secure page to non-secure page\n");
4036 /* FIXME: warn about from secure redirect to non-secure page */
4037 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4040 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4041 urlComponents
.nPort
= INTERNET_DEFAULT_HTTP_PORT
;
4042 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
)
4044 }else if(!strcmpiW(protocol
, httpsW
)) {
4045 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4046 TRACE("redirect from non-secure page to secure page\n");
4047 /* FIXME: notify about redirect to secure page */
4048 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4051 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4052 urlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
4053 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
)
4057 heap_free(session
->hostName
);
4061 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
4062 len
= lstrlenW(hostName
);
4063 len
+= 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4064 session
->hostName
= heap_alloc(len
*sizeof(WCHAR
));
4065 sprintfW(session
->hostName
, fmt
, hostName
, urlComponents
.nPort
);
4068 session
->hostName
= heap_strdupW(hostName
);
4070 HTTP_ProcessHeader(request
, hostW
, session
->hostName
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4072 heap_free(session
->userName
);
4073 session
->userName
= NULL
;
4075 session
->userName
= heap_strdupW(userName
);
4077 reset_data_stream(request
);
4079 if(strcmpiW(request
->server
->name
, hostName
) || request
->server
->port
!= urlComponents
.nPort
) {
4080 server_t
*new_server
;
4082 new_server
= get_server(hostName
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4083 server_release(request
->server
);
4084 request
->server
= new_server
;
4087 heap_free(request
->path
);
4094 rc
= UrlEscapeW(path
, NULL
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4095 if (rc
!= E_POINTER
)
4096 needed
= strlenW(path
)+1;
4097 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4098 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4099 URL_ESCAPE_SPACES_ONLY
);
4102 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4103 strcpyW(request
->path
,path
);
4107 /* Remove custom content-type/length headers on redirects. */
4108 index
= HTTP_GetCustomHeaderIndex(request
, szContent_Type
, 0, TRUE
);
4110 HTTP_DeleteCustomHeader(request
, index
);
4111 index
= HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
);
4113 HTTP_DeleteCustomHeader(request
, index
);
4115 return ERROR_SUCCESS
;
4118 /***********************************************************************
4119 * HTTP_build_req (internal)
4121 * concatenate all the strings in the request together
4123 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4128 for( t
= list
; *t
; t
++ )
4129 len
+= strlenW( *t
);
4132 str
= heap_alloc(len
*sizeof(WCHAR
));
4135 for( t
= list
; *t
; t
++ )
4141 static DWORD
HTTP_SecureProxyConnect(http_request_t
*request
)
4143 server_t
*server
= request
->server
;
4144 LPWSTR requestString
;
4151 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
4155 requestString
= build_request_header( request
, connectW
, server
->host_port
, g_szHttp1_1
, TRUE
);
4157 len
= WideCharToMultiByte( CP_ACP
, 0, requestString
, -1,
4158 NULL
, 0, NULL
, NULL
);
4159 len
--; /* the nul terminator isn't needed */
4160 ascii_req
= heap_alloc(len
);
4161 WideCharToMultiByte( CP_ACP
, 0, requestString
, -1, ascii_req
, len
, NULL
, NULL
);
4162 heap_free( requestString
);
4164 TRACE("full request -> %s\n", debugstr_an( ascii_req
, len
) );
4166 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
4167 res
= NETCON_send( request
->netconn
, ascii_req
, len
, 0, &cnt
);
4168 heap_free( ascii_req
);
4169 if (res
!= ERROR_SUCCESS
)
4172 if (HTTP_GetResponseHeaders( request
, &responseLen
) || !responseLen
)
4173 return ERROR_HTTP_INVALID_HEADER
;
4175 return ERROR_SUCCESS
;
4178 static void HTTP_InsertCookies(http_request_t
*request
)
4180 DWORD cookie_size
, size
, cnt
= 0;
4184 static const WCHAR cookieW
[] = {'C','o','o','k','i','e',':',' ',0};
4186 host
= HTTP_GetHeader(request
, hostW
);
4190 if(get_cookie(host
->lpszValue
, request
->path
, NULL
, &cookie_size
) != ERROR_SUCCESS
)
4193 size
= sizeof(cookieW
) + cookie_size
* sizeof(WCHAR
) + sizeof(szCrLf
);
4194 if(!(cookies
= heap_alloc(size
)))
4197 cnt
+= sprintfW(cookies
, cookieW
);
4198 get_cookie(host
->lpszValue
, request
->path
, cookies
+cnt
, &cookie_size
);
4199 strcatW(cookies
, szCrLf
);
4201 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
), HTTP_ADDREQ_FLAG_REPLACE
);
4206 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4208 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4216 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4217 if (!strcmpiW(day
, days
[i
]))
4224 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4226 static const WCHAR jan
[] = { 'j','a','n',0 };
4227 static const WCHAR feb
[] = { 'f','e','b',0 };
4228 static const WCHAR mar
[] = { 'm','a','r',0 };
4229 static const WCHAR apr
[] = { 'a','p','r',0 };
4230 static const WCHAR may
[] = { 'm','a','y',0 };
4231 static const WCHAR jun
[] = { 'j','u','n',0 };
4232 static const WCHAR jul
[] = { 'j','u','l',0 };
4233 static const WCHAR aug
[] = { 'a','u','g',0 };
4234 static const WCHAR sep
[] = { 's','e','p',0 };
4235 static const WCHAR oct
[] = { 'o','c','t',0 };
4236 static const WCHAR nov
[] = { 'n','o','v',0 };
4237 static const WCHAR dec
[] = { 'd','e','c',0 };
4239 if (!strcmpiW(month
, jan
)) return 1;
4240 if (!strcmpiW(month
, feb
)) return 2;
4241 if (!strcmpiW(month
, mar
)) return 3;
4242 if (!strcmpiW(month
, apr
)) return 4;
4243 if (!strcmpiW(month
, may
)) return 5;
4244 if (!strcmpiW(month
, jun
)) return 6;
4245 if (!strcmpiW(month
, jul
)) return 7;
4246 if (!strcmpiW(month
, aug
)) return 8;
4247 if (!strcmpiW(month
, sep
)) return 9;
4248 if (!strcmpiW(month
, oct
)) return 10;
4249 if (!strcmpiW(month
, nov
)) return 11;
4250 if (!strcmpiW(month
, dec
)) return 12;
4255 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4256 * optionally preceded by whitespace.
4257 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4258 * st, and sets *str to the first character after the time format.
4260 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4266 while (isspaceW(*ptr
))
4269 num
= strtoulW(ptr
, &nextPtr
, 10);
4270 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4272 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4277 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4281 st
->wHour
= (WORD
)num
;
4282 num
= strtoulW(ptr
, &nextPtr
, 10);
4283 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4285 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4290 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4294 st
->wMinute
= (WORD
)num
;
4295 num
= strtoulW(ptr
, &nextPtr
, 10);
4296 if (!nextPtr
|| nextPtr
<= ptr
)
4298 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4303 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4308 st
->wSecond
= (WORD
)num
;
4312 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4314 static const WCHAR gmt
[]= { 'G','M','T',0 };
4315 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4317 SYSTEMTIME st
= { 0 };
4320 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4321 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4324 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4325 if (st
.wDayOfWeek
>= 7)
4327 ERR("unexpected weekday %s\n", debugstr_w(day
));
4331 while (isspaceW(*ptr
))
4334 for (monthPtr
= month
; !isspace(*ptr
) &&
4335 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4339 st
.wMonth
= HTTP_ParseMonth(month
);
4340 if (!st
.wMonth
|| st
.wMonth
> 12)
4342 ERR("unexpected month %s\n", debugstr_w(month
));
4346 while (isspaceW(*ptr
))
4349 num
= strtoulW(ptr
, &nextPtr
, 10);
4350 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4352 ERR("unexpected day %s\n", debugstr_w(ptr
));
4356 st
.wDay
= (WORD
)num
;
4358 while (isspaceW(*ptr
))
4361 if (!HTTP_ParseTime(&st
, &ptr
))
4364 while (isspaceW(*ptr
))
4367 num
= strtoulW(ptr
, &nextPtr
, 10);
4368 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4370 ERR("unexpected year %s\n", debugstr_w(ptr
));
4374 st
.wYear
= (WORD
)num
;
4376 while (isspaceW(*ptr
))
4379 /* asctime() doesn't report a timezone, but some web servers do, so accept
4380 * with or without GMT.
4382 if (*ptr
&& strcmpW(ptr
, gmt
))
4384 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4387 return SystemTimeToFileTime(&st
, ft
);
4390 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4392 static const WCHAR gmt
[]= { 'G','M','T',0 };
4393 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4396 SYSTEMTIME st
= { 0 };
4398 ptr
= strchrW(value
, ',');
4401 if (ptr
- value
!= 3)
4403 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4406 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4408 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4409 if (st
.wDayOfWeek
> 6)
4411 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4416 while (isspaceW(*ptr
))
4419 num
= strtoulW(ptr
, &nextPtr
, 10);
4420 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4422 WARN("unexpected day %s\n", debugstr_w(value
));
4426 st
.wDay
= (WORD
)num
;
4428 while (isspaceW(*ptr
))
4431 for (monthPtr
= month
; !isspace(*ptr
) &&
4432 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4436 st
.wMonth
= HTTP_ParseMonth(month
);
4437 if (!st
.wMonth
|| st
.wMonth
> 12)
4439 WARN("unexpected month %s\n", debugstr_w(month
));
4443 while (isspaceW(*ptr
))
4446 num
= strtoulW(ptr
, &nextPtr
, 10);
4447 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4449 ERR("unexpected year %s\n", debugstr_w(value
));
4453 st
.wYear
= (WORD
)num
;
4455 if (!HTTP_ParseTime(&st
, &ptr
))
4458 while (isspaceW(*ptr
))
4461 if (strcmpW(ptr
, gmt
))
4463 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4466 return SystemTimeToFileTime(&st
, ft
);
4469 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4471 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4472 { 'm','o','n','d','a','y',0 },
4473 { 't','u','e','s','d','a','y',0 },
4474 { 'w','e','d','n','e','s','d','a','y',0 },
4475 { 't','h','u','r','s','d','a','y',0 },
4476 { 'f','r','i','d','a','y',0 },
4477 { 's','a','t','u','r','d','a','y',0 }};
4479 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4480 if (!strcmpiW(day
, days
[i
]))
4487 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4489 static const WCHAR gmt
[]= { 'G','M','T',0 };
4490 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4493 SYSTEMTIME st
= { 0 };
4495 ptr
= strchrW(value
, ',');
4498 if (ptr
- value
== 3)
4500 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4502 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4503 if (st
.wDayOfWeek
> 6)
4505 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4509 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4511 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4512 day
[ptr
- value
+ 1] = 0;
4513 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4514 if (st
.wDayOfWeek
> 6)
4516 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4522 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4527 while (isspaceW(*ptr
))
4530 num
= strtoulW(ptr
, &nextPtr
, 10);
4531 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4533 ERR("unexpected day %s\n", debugstr_w(value
));
4537 st
.wDay
= (WORD
)num
;
4541 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4546 for (monthPtr
= month
; *ptr
!= '-' &&
4547 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4551 st
.wMonth
= HTTP_ParseMonth(month
);
4552 if (!st
.wMonth
|| st
.wMonth
> 12)
4554 ERR("unexpected month %s\n", debugstr_w(month
));
4560 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4565 num
= strtoulW(ptr
, &nextPtr
, 10);
4566 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4568 ERR("unexpected year %s\n", debugstr_w(value
));
4572 st
.wYear
= (WORD
)num
;
4574 if (!HTTP_ParseTime(&st
, &ptr
))
4577 while (isspaceW(*ptr
))
4580 if (strcmpW(ptr
, gmt
))
4582 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4585 return SystemTimeToFileTime(&st
, ft
);
4588 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4590 static const WCHAR zero
[] = { '0',0 };
4593 if (!strcmpW(value
, zero
))
4595 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4598 else if (strchrW(value
, ','))
4600 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4603 ret
= HTTP_ParseRfc850Date(value
, ft
);
4605 ERR("unexpected date format %s\n", debugstr_w(value
));
4610 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4612 ERR("unexpected date format %s\n", debugstr_w(value
));
4617 static void HTTP_ProcessExpires(http_request_t
*request
)
4619 BOOL expirationFound
= FALSE
;
4622 /* Look for a Cache-Control header with a max-age directive, as it takes
4623 * precedence over the Expires header.
4625 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4626 if (headerIndex
!= -1)
4628 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4631 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4633 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4638 end
= ptr
+ strlenW(ptr
);
4639 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4643 static const WCHAR max_age
[] = {
4644 'm','a','x','-','a','g','e',0 };
4646 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4651 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4652 if (nextPtr
> equal
+ 1)
4656 NtQuerySystemTime( &ft
);
4657 /* Age is in seconds, FILETIME resolution is in
4658 * 100 nanosecond intervals.
4660 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4661 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4662 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4663 expirationFound
= TRUE
;
4670 while (isspaceW(*ptr
))
4677 if (!expirationFound
)
4679 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4680 if (headerIndex
!= -1)
4682 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4685 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4687 expirationFound
= TRUE
;
4688 request
->expires
= ft
;
4692 if (!expirationFound
)
4696 /* With no known age, default to 10 minutes until expiration. */
4697 NtQuerySystemTime( &t
);
4698 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4699 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4700 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4704 static void HTTP_ProcessLastModified(http_request_t
*request
)
4708 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4709 if (headerIndex
!= -1)
4711 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4714 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4715 request
->last_modified
= ft
;
4719 static void http_process_keep_alive(http_request_t
*req
)
4723 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4724 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4725 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4726 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4728 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4731 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4733 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4734 netconn_t
*netconn
= NULL
;
4737 assert(!request
->netconn
);
4738 reset_data_stream(request
);
4740 res
= HTTP_ResolveName(request
);
4741 if(res
!= ERROR_SUCCESS
)
4744 EnterCriticalSection(&connection_pool_cs
);
4746 while(!list_empty(&request
->server
->conn_pool
)) {
4747 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4748 list_remove(&netconn
->pool_entry
);
4750 if(NETCON_is_alive(netconn
))
4753 TRACE("connection %p closed during idle\n", netconn
);
4754 free_netconn(netconn
);
4758 LeaveCriticalSection(&connection_pool_cs
);
4761 TRACE("<-- reusing %p netconn\n", netconn
);
4762 request
->netconn
= netconn
;
4764 return ERROR_SUCCESS
;
4767 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4768 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4770 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4771 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4772 request
->server
->addr_str
,
4773 strlen(request
->server
->addr_str
)+1);
4775 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4776 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4777 request
->connect_timeout
, &netconn
);
4778 if(res
!= ERROR_SUCCESS
) {
4779 ERR("create_netconn failed: %u\n", res
);
4783 request
->netconn
= netconn
;
4785 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4786 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4787 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4790 /* Note: we differ from Microsoft's WinINet here. they seem to have
4791 * a bug that causes no status callbacks to be sent when starting
4792 * a tunnel to a proxy server using the CONNECT verb. i believe our
4793 * behaviour to be more correct and to not cause any incompatibilities
4794 * because using a secure connection through a proxy server is a rare
4795 * case that would be hard for anyone to depend on */
4797 res
= HTTP_SecureProxyConnect(request
);
4798 if(res
== ERROR_SUCCESS
)
4799 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4802 if(res
!= ERROR_SUCCESS
) {
4803 http_release_netconn(request
, FALSE
);
4808 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4809 return ERROR_SUCCESS
;
4812 /***********************************************************************
4813 * HTTP_HttpSendRequestW (internal)
4815 * Sends the specified request to the HTTP server
4818 * ERROR_SUCCESS on success
4819 * win32 error code on failure
4822 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4823 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4824 DWORD dwContentLength
, BOOL bEndRequest
)
4827 BOOL redirected
= FALSE
;
4828 LPWSTR requestString
= NULL
;
4831 static const WCHAR szPost
[] = { 'P','O','S','T',0 };
4832 static const WCHAR szContentLength
[] =
4833 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4834 WCHAR contentLengthStr
[sizeof szContentLength
/2 /* includes \r\n */ + 20 /* int */ ];
4837 TRACE("--> %p\n", request
);
4839 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4841 /* if the verb is NULL default to GET */
4843 request
->verb
= heap_strdupW(szGET
);
4845 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4847 sprintfW(contentLengthStr
, szContentLength
, dwContentLength
);
4848 HTTP_HttpAddRequestHeadersW(request
, contentLengthStr
, -1L, HTTP_ADDREQ_FLAG_REPLACE
);
4849 request
->bytesToWrite
= dwContentLength
;
4851 if (request
->session
->appInfo
->agent
)
4853 WCHAR
*agent_header
;
4854 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4857 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4858 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4859 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4861 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4862 heap_free(agent_header
);
4864 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4866 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4867 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4869 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && !strcmpW(request
->verb
, szPost
))
4871 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4872 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4873 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4876 /* add the headers the caller supplied */
4877 if( lpszHeaders
&& dwHeaderLength
)
4878 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4883 BOOL reusing_connection
;
4887 reusing_connection
= request
->netconn
!= NULL
;
4890 request
->contentLength
= ~0u;
4891 request
->bytesToWrite
= 0;
4894 if (TRACE_ON(wininet
))
4896 LPHTTPHEADERW Host
= HTTP_GetHeader(request
, hostW
);
4897 TRACE("Going to url %s %s\n", debugstr_w(Host
->lpszValue
), debugstr_w(request
->path
));
4900 HTTP_FixURL(request
);
4901 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4903 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
, HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
);
4905 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4906 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4908 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4909 HTTP_InsertCookies(request
);
4913 WCHAR
*url
= build_proxy_path_url(request
);
4914 requestString
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
4918 requestString
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
4921 TRACE("Request header -> %s\n", debugstr_w(requestString
) );
4923 if (!reusing_connection
&& (res
= open_http_connection(request
, &reusing_connection
)) != ERROR_SUCCESS
)
4926 /* send the request as ASCII, tack on the optional data */
4927 if (!lpOptional
|| redirected
)
4928 dwOptionalLength
= 0;
4929 len
= WideCharToMultiByte( CP_ACP
, 0, requestString
, -1,
4930 NULL
, 0, NULL
, NULL
);
4931 ascii_req
= heap_alloc(len
+ dwOptionalLength
);
4932 WideCharToMultiByte( CP_ACP
, 0, requestString
, -1,
4933 ascii_req
, len
, NULL
, NULL
);
4935 memcpy( &ascii_req
[len
-1], lpOptional
, dwOptionalLength
);
4936 len
= (len
+ dwOptionalLength
- 1);
4938 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
4940 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4941 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
4943 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
4944 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
4945 heap_free( ascii_req
);
4946 if(res
!= ERROR_SUCCESS
) {
4947 TRACE("send failed: %u\n", res
);
4948 if(!reusing_connection
)
4950 http_release_netconn(request
, FALSE
);
4955 request
->bytesWritten
= dwOptionalLength
;
4957 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4958 INTERNET_STATUS_REQUEST_SENT
,
4959 &len
, sizeof(DWORD
));
4965 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4966 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
4968 if (HTTP_GetResponseHeaders(request
, &responseLen
))
4970 http_release_netconn(request
, FALSE
);
4971 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
4974 /* FIXME: We should know that connection is closed before sending
4975 * headers. Otherwise wrong callbacks are executed */
4976 if(!responseLen
&& reusing_connection
) {
4977 TRACE("Connection closed by server, reconnecting\n");
4978 http_release_netconn(request
, FALSE
);
4983 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4984 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
4987 http_process_keep_alive(request
);
4988 HTTP_ProcessCookies(request
);
4989 HTTP_ProcessExpires(request
);
4990 HTTP_ProcessLastModified(request
);
4992 res
= set_content_length(request
);
4993 if(res
!= ERROR_SUCCESS
)
4995 if(!request
->contentLength
)
4996 http_release_netconn(request
, TRUE
);
4998 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5000 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5001 dwBufferSize
=sizeof(szNewLocation
);
5002 switch(request
->status_code
) {
5003 case HTTP_STATUS_REDIRECT
:
5004 case HTTP_STATUS_MOVED
:
5005 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5006 case HTTP_STATUS_REDIRECT_METHOD
:
5007 if(HTTP_HttpQueryInfoW(request
,HTTP_QUERY_LOCATION
,szNewLocation
,&dwBufferSize
,NULL
) != ERROR_SUCCESS
)
5010 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5011 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5013 heap_free(request
->verb
);
5014 request
->verb
= heap_strdupW(szGET
);
5016 http_release_netconn(request
, drain_content(request
, FALSE
));
5017 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5019 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5020 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5021 res
= HTTP_HandleRedirect(request
, new_url
);
5022 if (res
== ERROR_SUCCESS
)
5024 heap_free(requestString
);
5027 heap_free( new_url
);
5032 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5034 WCHAR szAuthValue
[2048];
5036 if (request
->status_code
== HTTP_STATUS_DENIED
)
5038 LPHTTPHEADERW Host
= HTTP_GetHeader(request
, hostW
);
5040 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5042 if (HTTP_DoAuthorization(request
, szAuthValue
,
5044 request
->session
->userName
,
5045 request
->session
->password
,
5048 heap_free(requestString
);
5049 if(!drain_content(request
, TRUE
)) {
5050 FIXME("Could not drain content\n");
5051 http_release_netconn(request
, FALSE
);
5059 TRACE("Cleaning wrong authorization data\n");
5060 destroy_authinfo(request
->authInfo
);
5061 request
->authInfo
= NULL
;
5064 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5067 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5069 if (HTTP_DoAuthorization(request
, szAuthValue
,
5070 &request
->proxyAuthInfo
,
5071 request
->session
->appInfo
->proxyUsername
,
5072 request
->session
->appInfo
->proxyPassword
,
5075 heap_free(requestString
);
5076 if(!drain_content(request
, TRUE
)) {
5077 FIXME("Could not drain content\n");
5078 http_release_netconn(request
, FALSE
);
5086 TRACE("Cleaning wrong proxy authorization data\n");
5087 destroy_authinfo(request
->proxyAuthInfo
);
5088 request
->proxyAuthInfo
= NULL
;
5094 res
= ERROR_SUCCESS
;
5099 heap_free(requestString
);
5101 /* TODO: send notification for P3P header */
5103 if(res
== ERROR_SUCCESS
)
5104 create_cache_entry(request
);
5106 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5108 if (res
== ERROR_SUCCESS
) {
5109 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5110 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5112 send_request_complete(request
,
5113 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5115 send_request_complete(request
, 0, res
);
5131 } send_request_task_t
;
5133 /***********************************************************************
5135 * Helper functions for the HttpSendRequest(Ex) functions
5138 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5140 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5141 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5143 TRACE("%p\n", request
);
5145 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5146 task
->optional_len
, task
->content_len
, task
->end_request
);
5148 heap_free(task
->headers
);
5152 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5156 DWORD res
= ERROR_SUCCESS
;
5158 if(!request
->netconn
) {
5159 WARN("Not connected\n");
5160 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5161 return ERROR_INTERNET_OPERATION_CANCELLED
;
5164 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5165 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5167 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5168 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5170 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5171 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5173 /* process cookies here. Is this right? */
5174 http_process_keep_alive(request
);
5175 HTTP_ProcessCookies(request
);
5176 HTTP_ProcessExpires(request
);
5177 HTTP_ProcessLastModified(request
);
5179 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5180 if(!request
->contentLength
)
5181 http_release_netconn(request
, TRUE
);
5184 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5186 switch(request
->status_code
) {
5187 case HTTP_STATUS_REDIRECT
:
5188 case HTTP_STATUS_MOVED
:
5189 case HTTP_STATUS_REDIRECT_METHOD
:
5190 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5191 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5192 dwBufferSize
=sizeof(szNewLocation
);
5193 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, szNewLocation
, &dwBufferSize
, NULL
) != ERROR_SUCCESS
)
5196 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5197 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5199 heap_free(request
->verb
);
5200 request
->verb
= heap_strdupW(szGET
);
5202 http_release_netconn(request
, drain_content(request
, FALSE
));
5203 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5205 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5206 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5207 res
= HTTP_HandleRedirect(request
, new_url
);
5208 if (res
== ERROR_SUCCESS
)
5209 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5210 heap_free( new_url
);
5216 if(res
== ERROR_SUCCESS
)
5217 create_cache_entry(request
);
5219 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5220 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5222 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5227 /***********************************************************************
5228 * HttpEndRequestA (WININET.@)
5230 * Ends an HTTP request that was started by HttpSendRequestEx
5233 * TRUE if successful
5237 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5238 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5240 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5244 SetLastError(ERROR_INVALID_PARAMETER
);
5248 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5255 } end_request_task_t
;
5257 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5259 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5260 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5264 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5267 /***********************************************************************
5268 * HttpEndRequestW (WININET.@)
5270 * Ends an HTTP request that was started by HttpSendRequestEx
5273 * TRUE if successful
5277 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5278 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5280 http_request_t
*request
;
5283 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5287 SetLastError(ERROR_INVALID_PARAMETER
);
5291 request
= (http_request_t
*) get_handle_object( hRequest
);
5293 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5295 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5297 WININET_Release( &request
->hdr
);
5300 request
->hdr
.dwFlags
|= dwFlags
;
5302 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5304 end_request_task_t
*task
;
5306 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5307 task
->flags
= dwFlags
;
5308 task
->context
= dwContext
;
5310 INTERNET_AsyncCall(&task
->hdr
);
5311 res
= ERROR_IO_PENDING
;
5314 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5316 WININET_Release( &request
->hdr
);
5317 TRACE("%u <--\n", res
);
5318 if(res
!= ERROR_SUCCESS
)
5320 return res
== ERROR_SUCCESS
;
5323 /***********************************************************************
5324 * HttpSendRequestExA (WININET.@)
5326 * Sends the specified request to the HTTP server and allows chunked
5331 * Failure: FALSE, call GetLastError() for more information.
5333 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5334 LPINTERNET_BUFFERSA lpBuffersIn
,
5335 LPINTERNET_BUFFERSA lpBuffersOut
,
5336 DWORD dwFlags
, DWORD_PTR dwContext
)
5338 INTERNET_BUFFERSW BuffersInW
;
5341 LPWSTR header
= NULL
;
5343 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5344 lpBuffersOut
, dwFlags
, dwContext
);
5348 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5349 if (lpBuffersIn
->lpcszHeader
)
5351 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5352 lpBuffersIn
->dwHeadersLength
,0,0);
5353 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5354 if (!(BuffersInW
.lpcszHeader
= header
))
5356 SetLastError(ERROR_OUTOFMEMORY
);
5359 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5360 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5364 BuffersInW
.lpcszHeader
= NULL
;
5365 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5366 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5367 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5368 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5369 BuffersInW
.Next
= NULL
;
5372 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5378 /***********************************************************************
5379 * HttpSendRequestExW (WININET.@)
5381 * Sends the specified request to the HTTP server and allows chunked
5386 * Failure: FALSE, call GetLastError() for more information.
5388 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5389 LPINTERNET_BUFFERSW lpBuffersIn
,
5390 LPINTERNET_BUFFERSW lpBuffersOut
,
5391 DWORD dwFlags
, DWORD_PTR dwContext
)
5393 http_request_t
*request
;
5394 http_session_t
*session
;
5398 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5399 lpBuffersOut
, dwFlags
, dwContext
);
5401 request
= (http_request_t
*) get_handle_object( hRequest
);
5403 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5405 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5409 session
= request
->session
;
5410 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5411 hIC
= session
->appInfo
;
5412 assert(hIC
->hdr
.htype
== WH_HINIT
);
5414 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5416 send_request_task_t
*task
;
5418 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5423 if (lpBuffersIn
->lpcszHeader
)
5425 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5426 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5428 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5430 task
->headers
= heap_alloc(size
);
5431 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5433 else task
->headers
= NULL
;
5435 task
->headers_len
= size
/ sizeof(WCHAR
);
5436 task
->optional
= lpBuffersIn
->lpvBuffer
;
5437 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5438 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5442 task
->headers
= NULL
;
5443 task
->headers_len
= 0;
5444 task
->optional
= NULL
;
5445 task
->optional_len
= 0;
5446 task
->content_len
= 0;
5449 task
->end_request
= FALSE
;
5451 INTERNET_AsyncCall(&task
->hdr
);
5452 res
= ERROR_IO_PENDING
;
5457 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5458 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5459 lpBuffersIn
->dwBufferTotal
, FALSE
);
5461 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5466 WININET_Release( &request
->hdr
);
5470 return res
== ERROR_SUCCESS
;
5473 /***********************************************************************
5474 * HttpSendRequestW (WININET.@)
5476 * Sends the specified request to the HTTP server
5483 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5484 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5486 http_request_t
*request
;
5487 http_session_t
*session
= NULL
;
5488 appinfo_t
*hIC
= NULL
;
5489 DWORD res
= ERROR_SUCCESS
;
5491 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5492 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5494 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5495 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5497 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5501 session
= request
->session
;
5502 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5504 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5508 hIC
= session
->appInfo
;
5509 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5511 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5515 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5517 send_request_task_t
*task
;
5519 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5524 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5525 else size
= dwHeaderLength
* sizeof(WCHAR
);
5527 task
->headers
= heap_alloc(size
);
5528 memcpy(task
->headers
, lpszHeaders
, size
);
5531 task
->headers
= NULL
;
5532 task
->headers_len
= dwHeaderLength
;
5533 task
->optional
= lpOptional
;
5534 task
->optional_len
= dwOptionalLength
;
5535 task
->content_len
= dwOptionalLength
;
5536 task
->end_request
= TRUE
;
5538 INTERNET_AsyncCall(&task
->hdr
);
5539 res
= ERROR_IO_PENDING
;
5543 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5544 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5545 dwOptionalLength
, TRUE
);
5549 WININET_Release( &request
->hdr
);
5552 return res
== ERROR_SUCCESS
;
5555 /***********************************************************************
5556 * HttpSendRequestA (WININET.@)
5558 * Sends the specified request to the HTTP server
5565 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5566 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5569 LPWSTR szHeaders
=NULL
;
5570 DWORD nLen
=dwHeaderLength
;
5571 if(lpszHeaders
!=NULL
)
5573 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5574 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5575 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5577 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5578 heap_free(szHeaders
);
5582 /***********************************************************************
5583 * HTTPSESSION_Destroy (internal)
5585 * Deallocate session handle
5588 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5590 http_session_t
*session
= (http_session_t
*) hdr
;
5592 TRACE("%p\n", session
);
5594 WININET_Release(&session
->appInfo
->hdr
);
5596 heap_free(session
->hostName
);
5597 heap_free(session
->password
);
5598 heap_free(session
->userName
);
5601 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5603 http_session_t
*ses
= (http_session_t
*)hdr
;
5606 case INTERNET_OPTION_HANDLE_TYPE
:
5607 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5609 if (*size
< sizeof(ULONG
))
5610 return ERROR_INSUFFICIENT_BUFFER
;
5612 *size
= sizeof(DWORD
);
5613 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5614 return ERROR_SUCCESS
;
5615 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5616 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5618 if (*size
< sizeof(DWORD
))
5619 return ERROR_INSUFFICIENT_BUFFER
;
5621 *size
= sizeof(DWORD
);
5622 *(DWORD
*)buffer
= ses
->connect_timeout
;
5623 return ERROR_SUCCESS
;
5625 case INTERNET_OPTION_SEND_TIMEOUT
:
5626 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5628 if (*size
< sizeof(DWORD
))
5629 return ERROR_INSUFFICIENT_BUFFER
;
5631 *size
= sizeof(DWORD
);
5632 *(DWORD
*)buffer
= ses
->send_timeout
;
5633 return ERROR_SUCCESS
;
5635 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5636 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5638 if (*size
< sizeof(DWORD
))
5639 return ERROR_INSUFFICIENT_BUFFER
;
5641 *size
= sizeof(DWORD
);
5642 *(DWORD
*)buffer
= ses
->receive_timeout
;
5643 return ERROR_SUCCESS
;
5646 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5649 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5651 http_session_t
*ses
= (http_session_t
*)hdr
;
5654 case INTERNET_OPTION_USERNAME
:
5656 heap_free(ses
->userName
);
5657 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5658 return ERROR_SUCCESS
;
5660 case INTERNET_OPTION_PASSWORD
:
5662 heap_free(ses
->password
);
5663 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5664 return ERROR_SUCCESS
;
5666 case INTERNET_OPTION_PROXY_USERNAME
:
5668 heap_free(ses
->appInfo
->proxyUsername
);
5669 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5670 return ERROR_SUCCESS
;
5672 case INTERNET_OPTION_PROXY_PASSWORD
:
5674 heap_free(ses
->appInfo
->proxyPassword
);
5675 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5676 return ERROR_SUCCESS
;
5678 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5680 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5681 ses
->connect_timeout
= *(DWORD
*)buffer
;
5682 return ERROR_SUCCESS
;
5684 case INTERNET_OPTION_SEND_TIMEOUT
:
5686 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5687 ses
->send_timeout
= *(DWORD
*)buffer
;
5688 return ERROR_SUCCESS
;
5690 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5692 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5693 ses
->receive_timeout
= *(DWORD
*)buffer
;
5694 return ERROR_SUCCESS
;
5699 return INET_SetOption(hdr
, option
, buffer
, size
);
5702 static const object_vtbl_t HTTPSESSIONVtbl
= {
5703 HTTPSESSION_Destroy
,
5705 HTTPSESSION_QueryOption
,
5706 HTTPSESSION_SetOption
,
5715 /***********************************************************************
5716 * HTTP_Connect (internal)
5718 * Create http session handle
5721 * HINTERNET a session handle on success
5725 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5726 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5727 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5728 DWORD dwInternalFlags
, HINTERNET
*ret
)
5730 http_session_t
*session
= NULL
;
5734 if (!lpszServerName
|| !lpszServerName
[0])
5735 return ERROR_INVALID_PARAMETER
;
5737 assert( hIC
->hdr
.htype
== WH_HINIT
);
5739 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5741 return ERROR_OUTOFMEMORY
;
5744 * According to my tests. The name is not resolved until a request is sent
5747 session
->hdr
.htype
= WH_HHTTPSESSION
;
5748 session
->hdr
.dwFlags
= dwFlags
;
5749 session
->hdr
.dwContext
= dwContext
;
5750 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5752 WININET_AddRef( &hIC
->hdr
);
5753 session
->appInfo
= hIC
;
5754 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5756 session
->hostName
= heap_strdupW(lpszServerName
);
5757 if (lpszUserName
&& lpszUserName
[0])
5758 session
->userName
= heap_strdupW(lpszUserName
);
5759 if (lpszPassword
&& lpszPassword
[0])
5760 session
->password
= heap_strdupW(lpszPassword
);
5761 session
->hostPort
= serverPort
;
5762 session
->connect_timeout
= hIC
->connect_timeout
;
5763 session
->send_timeout
= INFINITE
;
5764 session
->receive_timeout
= INFINITE
;
5766 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5767 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5769 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5770 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5775 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5779 TRACE("%p --> %p\n", hIC
, session
);
5781 *ret
= session
->hdr
.hInternet
;
5782 return ERROR_SUCCESS
;
5785 /***********************************************************************
5786 * HTTP_clear_response_headers (internal)
5788 * clear out any old response headers
5790 static void HTTP_clear_response_headers( http_request_t
*request
)
5794 for( i
=0; i
<request
->nCustHeaders
; i
++)
5796 if( !request
->custHeaders
[i
].lpszField
)
5798 if( !request
->custHeaders
[i
].lpszValue
)
5800 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5802 HTTP_DeleteCustomHeader( request
, i
);
5807 /***********************************************************************
5808 * HTTP_GetResponseHeaders (internal)
5810 * Read server response
5817 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5820 WCHAR buffer
[MAX_REPLY_LEN
];
5821 DWORD buflen
= MAX_REPLY_LEN
;
5823 char bufferA
[MAX_REPLY_LEN
];
5824 LPWSTR status_code
= NULL
, status_text
= NULL
;
5825 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5826 BOOL codeHundred
= FALSE
;
5830 if(!request
->netconn
)
5833 /* clear old response headers (eg. from a redirect response) */
5834 HTTP_clear_response_headers( request
);
5836 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5839 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5841 buflen
= MAX_REPLY_LEN
;
5842 if ((res
= read_line(request
, bufferA
, &buflen
)))
5845 if (!buflen
) goto lend
;
5848 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5849 /* check is this a status code line? */
5850 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5852 /* split the version from the status code */
5853 status_code
= strchrW( buffer
, ' ' );
5858 /* split the status code from the status text */
5859 status_text
= strchrW( status_code
, ' ' );
5864 request
->status_code
= atoiW(status_code
);
5866 TRACE("version [%s] status code [%s] status text [%s]\n",
5867 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5869 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5871 else if (!codeHundred
)
5873 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5875 heap_free(request
->version
);
5876 heap_free(request
->statusText
);
5878 request
->status_code
= HTTP_STATUS_OK
;
5879 request
->version
= heap_strdupW(g_szHttp1_0
);
5880 request
->statusText
= heap_strdupW(szOK
);
5884 } while (codeHundred
);
5886 /* Add status code */
5887 HTTP_ProcessHeader(request
, szStatus
, status_code
,
5888 HTTP_ADDHDR_FLAG_REPLACE
);
5890 heap_free(request
->version
);
5891 heap_free(request
->statusText
);
5893 request
->version
= heap_strdupW(buffer
);
5894 request
->statusText
= heap_strdupW(status_text
);
5896 /* Restore the spaces */
5897 *(status_code
-1) = ' ';
5898 *(status_text
-1) = ' ';
5900 /* Parse each response line */
5903 buflen
= MAX_REPLY_LEN
;
5904 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
5906 LPWSTR
* pFieldAndValue
;
5908 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
5910 if (!bufferA
[0]) break;
5911 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5913 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
5916 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
5917 HTTP_ADDREQ_FLAG_ADD
);
5918 HTTP_FreeTokens(pFieldAndValue
);
5929 res
= ERROR_SUCCESS
;
5938 /***********************************************************************
5939 * HTTP_InterpretHttpHeader (internal)
5941 * Parse server response
5945 * Pointer to array of field, value, NULL on success.
5948 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
5950 LPWSTR
* pTokenPair
;
5954 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
5956 pszColon
= strchrW(buffer
, ':');
5957 /* must have two tokens */
5960 HTTP_FreeTokens(pTokenPair
);
5962 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
5966 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
5969 HTTP_FreeTokens(pTokenPair
);
5972 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
5973 pTokenPair
[0][pszColon
- buffer
] = '\0';
5977 len
= strlenW(pszColon
);
5978 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
5981 HTTP_FreeTokens(pTokenPair
);
5984 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
5986 strip_spaces(pTokenPair
[0]);
5987 strip_spaces(pTokenPair
[1]);
5989 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
5993 /***********************************************************************
5994 * HTTP_ProcessHeader (internal)
5996 * Stuff header into header tables according to <dwModifier>
6000 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6002 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6004 LPHTTPHEADERW lphttpHdr
= NULL
;
6006 BOOL request_only
= dwModifier
& HTTP_ADDHDR_FLAG_REQ
;
6007 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6009 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6011 /* REPLACE wins out over ADD */
6012 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6013 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6015 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6018 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6022 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6023 return ERROR_HTTP_INVALID_HEADER
;
6024 lphttpHdr
= &request
->custHeaders
[index
];
6030 hdr
.lpszField
= (LPWSTR
)field
;
6031 hdr
.lpszValue
= (LPWSTR
)value
;
6032 hdr
.wFlags
= hdr
.wCount
= 0;
6034 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6035 hdr
.wFlags
|= HDR_ISREQUEST
;
6037 return HTTP_InsertCustomHeader(request
, &hdr
);
6039 /* no value to delete */
6040 else return ERROR_SUCCESS
;
6042 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6043 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6045 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6047 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6049 HTTP_DeleteCustomHeader( request
, index
);
6055 hdr
.lpszField
= (LPWSTR
)field
;
6056 hdr
.lpszValue
= (LPWSTR
)value
;
6057 hdr
.wFlags
= hdr
.wCount
= 0;
6059 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6060 hdr
.wFlags
|= HDR_ISREQUEST
;
6062 return HTTP_InsertCustomHeader(request
, &hdr
);
6065 return ERROR_SUCCESS
;
6067 else if (dwModifier
& COALESCEFLAGS
)
6072 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6073 INT valuelen
= strlenW(value
);
6075 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6078 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6080 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6083 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6086 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6088 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6091 lphttpHdr
->lpszValue
= lpsztmp
;
6092 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6095 lphttpHdr
->lpszValue
[origlen
] = ch
;
6097 lphttpHdr
->lpszValue
[origlen
] = ' ';
6101 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6102 lphttpHdr
->lpszValue
[len
] = '\0';
6103 res
= ERROR_SUCCESS
;
6107 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6108 res
= ERROR_OUTOFMEMORY
;
6111 TRACE("<-- %d\n", res
);
6115 /***********************************************************************
6116 * HTTP_GetCustomHeaderIndex (internal)
6118 * Return index of custom header from header array
6121 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6122 int requested_index
, BOOL request_only
)
6126 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6128 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6130 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6133 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6136 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6139 if (requested_index
== 0)
6144 if (index
>= request
->nCustHeaders
)
6147 TRACE("Return: %d\n", index
);
6152 /***********************************************************************
6153 * HTTP_InsertCustomHeader (internal)
6155 * Insert header into array
6158 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6161 LPHTTPHEADERW lph
= NULL
;
6163 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6164 count
= request
->nCustHeaders
+ 1;
6166 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6168 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6171 return ERROR_OUTOFMEMORY
;
6173 request
->custHeaders
= lph
;
6174 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6175 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6176 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6177 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6178 request
->nCustHeaders
++;
6180 return ERROR_SUCCESS
;
6184 /***********************************************************************
6185 * HTTP_DeleteCustomHeader (internal)
6187 * Delete header from array
6188 * If this function is called, the indexs may change.
6190 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6192 if( request
->nCustHeaders
<= 0 )
6194 if( index
>= request
->nCustHeaders
)
6196 request
->nCustHeaders
--;
6198 heap_free(request
->custHeaders
[index
].lpszField
);
6199 heap_free(request
->custHeaders
[index
].lpszValue
);
6201 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6202 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6203 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6209 /***********************************************************************
6210 * HTTP_VerifyValidHeader (internal)
6212 * Verify the given header is not invalid for the given http request
6215 static BOOL
HTTP_VerifyValidHeader(http_request_t
*request
, LPCWSTR field
)
6217 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6218 if (!strcmpW(request
->version
, g_szHttp1_0
) && !strcmpiW(field
, szAccept_Encoding
))
6219 return ERROR_HTTP_INVALID_HEADER
;
6221 return ERROR_SUCCESS
;
6224 /***********************************************************************
6225 * IsHostInProxyBypassList (@)
6230 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6232 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);