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
49 #define NO_SHLWAPI_STREAM
50 #define NO_SHLWAPI_REG
51 #define NO_SHLWAPI_STRFCNS
52 #define NO_SHLWAPI_GDI
59 #include "wine/debug.h"
60 #include "wine/exception.h"
61 #include "wine/unicode.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
65 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
66 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
67 static const WCHAR szOK
[] = {'O','K',0};
68 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
69 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
70 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
71 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
72 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
73 static const WCHAR szGET
[] = { 'G','E','T', 0 };
74 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
76 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
77 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
78 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
79 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
80 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
81 static const WCHAR szAge
[] = { 'A','g','e',0 };
82 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
83 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
84 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
85 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
86 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
87 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
88 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
89 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
90 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
91 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
92 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
93 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
94 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 };
95 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
96 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
97 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
98 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
99 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
100 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
101 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
102 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
103 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
104 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
106 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
107 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
108 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
109 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
110 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
111 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
112 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
113 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
114 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
115 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
116 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
117 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
118 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
119 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
120 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
121 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 };
122 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
123 static const WCHAR szURI
[] = { 'U','R','I',0 };
124 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
125 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
126 static const WCHAR szVia
[] = { 'V','i','a',0 };
127 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
128 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
130 static const WCHAR emptyW
[] = {0};
132 #define HTTP_REFERER szReferer
133 #define HTTP_ACCEPT szAccept
134 #define HTTP_USERAGENT szUser_Agent
136 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
137 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
138 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
139 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
140 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
141 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
142 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
144 #define COLLECT_TIME 60000
146 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
157 unsigned int auth_data_len
;
158 BOOL finished
; /* finished authenticating */
162 typedef struct _basicAuthorizationData
169 UINT authorizationLen
;
170 } basicAuthorizationData
;
172 typedef struct _authorizationData
186 static struct list basicAuthorizationCache
= LIST_INIT(basicAuthorizationCache
);
187 static struct list authorizationCache
= LIST_INIT(authorizationCache
);
189 static CRITICAL_SECTION authcache_cs
;
190 static CRITICAL_SECTION_DEBUG critsect_debug
=
193 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
194 0, 0, { (DWORD_PTR
)(__FILE__
": authcache_cs") }
196 static CRITICAL_SECTION authcache_cs
= { &critsect_debug
, -1, 0, 0, 0, 0 };
198 static DWORD
HTTP_GetResponseHeaders(http_request_t
*req
, INT
*len
);
199 static DWORD
HTTP_ProcessHeader(http_request_t
*req
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
);
200 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
);
201 static DWORD
HTTP_InsertCustomHeader(http_request_t
*req
, LPHTTPHEADERW lpHdr
);
202 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*req
, LPCWSTR lpszField
, INT index
, BOOL Request
);
203 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*req
, DWORD index
);
204 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
);
205 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*, DWORD
, LPVOID
, LPDWORD
, LPDWORD
);
206 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*req
, LPCWSTR lpszUrl
);
207 static UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
208 static BOOL
drain_content(http_request_t
*,BOOL
);
210 static CRITICAL_SECTION connection_pool_cs
;
211 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
213 0, 0, &connection_pool_cs
,
214 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
215 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
217 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
219 static struct list connection_pool
= LIST_INIT(connection_pool
);
220 static BOOL collector_running
;
222 void server_addref(server_t
*server
)
224 InterlockedIncrement(&server
->ref
);
227 void server_release(server_t
*server
)
229 if(InterlockedDecrement(&server
->ref
))
232 list_remove(&server
->entry
);
234 if(server
->cert_chain
)
235 CertFreeCertificateChain(server
->cert_chain
);
236 heap_free(server
->name
);
237 heap_free(server
->scheme_host_port
);
241 static BOOL
process_host_port(server_t
*server
)
247 static const WCHAR httpW
[] = {'h','t','t','p',0};
248 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
249 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
251 name_len
= strlenW(server
->name
);
252 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
256 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
257 server
->scheme_host_port
= buf
;
259 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
263 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
264 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
268 server_t
*get_server(const WCHAR
*name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
270 server_t
*iter
, *server
= NULL
;
272 if(port
== INTERNET_INVALID_PORT_NUMBER
)
273 port
= INTERNET_DEFAULT_HTTP_PORT
;
275 EnterCriticalSection(&connection_pool_cs
);
277 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
278 if(iter
->port
== port
&& !strcmpW(iter
->name
, name
) && iter
->is_https
== is_https
) {
280 server_addref(server
);
285 if(!server
&& do_create
) {
286 server
= heap_alloc_zero(sizeof(*server
));
288 server
->ref
= 2; /* list reference and return */
290 server
->is_https
= is_https
;
291 list_init(&server
->conn_pool
);
292 server
->name
= heap_strdupW(name
);
293 if(server
->name
&& process_host_port(server
)) {
294 list_add_head(&connection_pool
, &server
->entry
);
302 LeaveCriticalSection(&connection_pool_cs
);
307 BOOL
collect_connections(collect_type_t collect_type
)
309 netconn_t
*netconn
, *netconn_safe
;
310 server_t
*server
, *server_safe
;
311 BOOL remaining
= FALSE
;
314 now
= GetTickCount64();
316 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
317 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
318 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
319 TRACE("freeing %p\n", netconn
);
320 list_remove(&netconn
->pool_entry
);
321 free_netconn(netconn
);
327 if(collect_type
== COLLECT_CLEANUP
) {
328 list_remove(&server
->entry
);
329 list_init(&server
->entry
);
330 server_release(server
);
337 static DWORD WINAPI
collect_connections_proc(void *arg
)
339 BOOL remaining_conns
;
342 /* FIXME: Use more sophisticated method */
345 EnterCriticalSection(&connection_pool_cs
);
347 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
349 collector_running
= FALSE
;
351 LeaveCriticalSection(&connection_pool_cs
);
352 }while(remaining_conns
);
354 FreeLibraryAndExitThread(WININET_hModule
, 0);
357 /***********************************************************************
358 * HTTP_GetHeader (internal)
360 * Headers section must be held
362 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
365 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
366 if (HeaderIndex
== -1)
369 return &req
->custHeaders
[HeaderIndex
];
372 static WCHAR
*get_host_header( http_request_t
*req
)
377 EnterCriticalSection( &req
->headers_section
);
378 if ((header
= HTTP_GetHeader( req
, hostW
))) ret
= heap_strdupW( header
->lpszValue
);
379 else ret
= heap_strdupW( req
->server
->canon_host_port
);
380 LeaveCriticalSection( &req
->headers_section
);
390 struct data_stream_vtbl_t
{
391 DWORD (*get_avail_data
)(data_stream_t
*,http_request_t
*);
392 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
393 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,blocking_mode_t
);
394 BOOL (*drain_content
)(data_stream_t
*,http_request_t
*);
395 void (*destroy
)(data_stream_t
*);
399 data_stream_t data_stream
;
401 BYTE buf
[READ_BUFFER_SIZE
];
408 static inline void destroy_data_stream(data_stream_t
*stream
)
410 stream
->vtbl
->destroy(stream
);
413 static void reset_data_stream(http_request_t
*req
)
415 destroy_data_stream(req
->data_stream
);
416 req
->data_stream
= &req
->netconn_stream
.data_stream
;
417 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
418 req
->read_gzip
= FALSE
;
421 static void remove_header( http_request_t
*request
, const WCHAR
*str
, BOOL from_request
)
424 EnterCriticalSection( &request
->headers_section
);
425 index
= HTTP_GetCustomHeaderIndex( request
, str
, 0, from_request
);
426 if (index
!= -1) HTTP_DeleteCustomHeader( request
, index
);
427 LeaveCriticalSection( &request
->headers_section
);
433 data_stream_t stream
;
434 data_stream_t
*parent_stream
;
436 BYTE buf
[READ_BUFFER_SIZE
];
442 static DWORD
gzip_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
444 /* Allow reading only from read buffer */
448 static BOOL
gzip_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
450 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
451 return gzip_stream
->end_of_data
452 || (!gzip_stream
->buf_size
&& gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
));
455 static DWORD
gzip_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
456 DWORD
*read
, blocking_mode_t blocking_mode
)
458 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
459 z_stream
*zstream
= &gzip_stream
->zstream
;
460 DWORD current_read
, ret_read
= 0;
462 DWORD res
= ERROR_SUCCESS
;
464 TRACE("(%d %d)\n", size
, blocking_mode
);
466 while(size
&& !gzip_stream
->end_of_data
) {
467 if(!gzip_stream
->buf_size
) {
468 if(gzip_stream
->buf_pos
) {
469 if(gzip_stream
->buf_size
)
470 memmove(gzip_stream
->buf
, gzip_stream
->buf
+gzip_stream
->buf_pos
, gzip_stream
->buf_size
);
471 gzip_stream
->buf_pos
= 0;
473 res
= gzip_stream
->parent_stream
->vtbl
->read(gzip_stream
->parent_stream
, req
, gzip_stream
->buf
+gzip_stream
->buf_size
,
474 sizeof(gzip_stream
->buf
)-gzip_stream
->buf_size
, ¤t_read
, blocking_mode
);
475 gzip_stream
->buf_size
+= current_read
;
476 if(res
!= ERROR_SUCCESS
)
480 if(blocking_mode
!= BLOCKING_DISALLOW
) {
481 WARN("unexpected end of data\n");
482 gzip_stream
->end_of_data
= TRUE
;
488 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
489 zstream
->avail_in
= gzip_stream
->buf_size
;
490 zstream
->next_out
= buf
+ret_read
;
491 zstream
->avail_out
= size
;
492 zres
= inflate(&gzip_stream
->zstream
, 0);
493 current_read
= size
- zstream
->avail_out
;
494 size
-= current_read
;
495 ret_read
+= current_read
;
496 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
497 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
498 if(zres
== Z_STREAM_END
) {
499 TRACE("end of data\n");
500 gzip_stream
->end_of_data
= TRUE
;
502 }else if(zres
!= Z_OK
) {
503 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
505 res
= ERROR_INTERNET_DECODING_FAILED
;
509 if(ret_read
&& blocking_mode
== BLOCKING_ALLOW
)
510 blocking_mode
= BLOCKING_DISALLOW
;
513 TRACE("read %u bytes\n", ret_read
);
518 static BOOL
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
)
520 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
521 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
);
524 static void gzip_destroy(data_stream_t
*stream
)
526 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
528 destroy_data_stream(gzip_stream
->parent_stream
);
530 if(!gzip_stream
->end_of_data
)
531 inflateEnd(&gzip_stream
->zstream
);
532 heap_free(gzip_stream
);
535 static const data_stream_vtbl_t gzip_stream_vtbl
= {
543 static voidpf
wininet_zalloc(voidpf opaque
, uInt items
, uInt size
)
545 return heap_alloc(items
*size
);
548 static void wininet_zfree(voidpf opaque
, voidpf address
)
553 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
555 gzip_stream_t
*gzip_stream
;
558 gzip_stream
= heap_alloc_zero(sizeof(gzip_stream_t
));
560 return ERROR_OUTOFMEMORY
;
562 gzip_stream
->stream
.vtbl
= &gzip_stream_vtbl
;
563 gzip_stream
->zstream
.zalloc
= wininet_zalloc
;
564 gzip_stream
->zstream
.zfree
= wininet_zfree
;
566 zres
= inflateInit2(&gzip_stream
->zstream
, is_gzip
? 0x1f : -15);
568 ERR("inflateInit failed: %d\n", zres
);
569 heap_free(gzip_stream
);
570 return ERROR_OUTOFMEMORY
;
573 remove_header(req
, szContent_Length
, FALSE
);
576 memcpy(gzip_stream
->buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
577 gzip_stream
->buf_size
= req
->read_size
;
578 req
->read_pos
= req
->read_size
= 0;
581 req
->read_gzip
= TRUE
;
582 gzip_stream
->parent_stream
= req
->data_stream
;
583 req
->data_stream
= &gzip_stream
->stream
;
584 return ERROR_SUCCESS
;
589 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
591 ERR("gzip stream not supported, missing zlib.\n");
592 return ERROR_SUCCESS
;
597 /***********************************************************************
598 * HTTP_FreeTokens (internal)
600 * Frees table of pointers.
602 static void HTTP_FreeTokens(LPWSTR
* token_array
)
605 for (i
= 0; token_array
[i
]; i
++) heap_free(token_array
[i
]);
606 heap_free(token_array
);
609 static void HTTP_FixURL(http_request_t
*request
)
611 static const WCHAR szSlash
[] = { '/',0 };
612 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/', 0 };
614 /* If we don't have a path we set it to root */
615 if (NULL
== request
->path
)
616 request
->path
= heap_strdupW(szSlash
);
617 else /* remove \r and \n*/
619 int nLen
= strlenW(request
->path
);
620 while ((nLen
>0 ) && ((request
->path
[nLen
-1] == '\r')||(request
->path
[nLen
-1] == '\n')))
623 request
->path
[nLen
]='\0';
625 /* Replace '\' with '/' */
628 if (request
->path
[nLen
] == '\\') request
->path
[nLen
]='/';
632 if(CSTR_EQUAL
!= CompareStringW( LOCALE_INVARIANT
, NORM_IGNORECASE
,
633 request
->path
, strlenW(request
->path
), szHttp
, strlenW(szHttp
) )
634 && request
->path
[0] != '/') /* not an absolute path ?? --> fix it !! */
636 WCHAR
*fixurl
= heap_alloc((strlenW(request
->path
) + 2)*sizeof(WCHAR
));
638 strcpyW(fixurl
+ 1, request
->path
);
639 heap_free( request
->path
);
640 request
->path
= fixurl
;
644 static WCHAR
* build_request_header(http_request_t
*request
, const WCHAR
*verb
,
645 const WCHAR
*path
, const WCHAR
*version
, BOOL use_cr
)
647 static const WCHAR szSpace
[] = {' ',0};
648 static const WCHAR szColon
[] = {':',' ',0};
649 static const WCHAR szCr
[] = {'\r',0};
650 static const WCHAR szLf
[] = {'\n',0};
651 LPWSTR requestString
;
656 EnterCriticalSection( &request
->headers_section
);
658 /* allocate space for an array of all the string pointers to be added */
659 len
= request
->nCustHeaders
* 5 + 10;
660 if (!(req
= heap_alloc( len
* sizeof(const WCHAR
*) )))
662 LeaveCriticalSection( &request
->headers_section
);
666 /* add the verb, path and HTTP version string */
677 /* Append custom request headers */
678 for (i
= 0; i
< request
->nCustHeaders
; i
++)
680 if (request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
682 req
[n
++] = request
->custHeaders
[i
].lpszField
;
684 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
689 TRACE("Adding custom header %s (%s)\n",
690 debugstr_w(request
->custHeaders
[i
].lpszField
),
691 debugstr_w(request
->custHeaders
[i
].lpszValue
));
699 requestString
= HTTP_build_req( req
, 4 );
701 LeaveCriticalSection( &request
->headers_section
);
702 return requestString
;
705 static WCHAR
* build_response_header(http_request_t
*request
, BOOL use_cr
)
707 static const WCHAR colonW
[] = { ':',' ',0 };
708 static const WCHAR crW
[] = { '\r',0 };
709 static const WCHAR lfW
[] = { '\n',0 };
710 static const WCHAR status_fmt
[] = { ' ','%','u',' ',0 };
715 EnterCriticalSection( &request
->headers_section
);
717 if (!(req
= heap_alloc( (request
->nCustHeaders
* 5 + 8) * sizeof(WCHAR
*) )))
719 LeaveCriticalSection( &request
->headers_section
);
723 if (request
->status_code
)
725 req
[n
++] = request
->version
;
726 sprintfW(buf
, status_fmt
, request
->status_code
);
728 req
[n
++] = request
->statusText
;
734 for(i
= 0; i
< request
->nCustHeaders
; i
++)
736 if(!(request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
737 && strcmpW(request
->custHeaders
[i
].lpszField
, szStatus
))
739 req
[n
++] = request
->custHeaders
[i
].lpszField
;
741 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
746 TRACE("Adding custom header %s (%s)\n",
747 debugstr_w(request
->custHeaders
[i
].lpszField
),
748 debugstr_w(request
->custHeaders
[i
].lpszValue
));
756 ret
= HTTP_build_req(req
, 0);
758 LeaveCriticalSection( &request
->headers_section
);
762 static void HTTP_ProcessCookies( http_request_t
*request
)
766 LPHTTPHEADERW setCookieHeader
;
768 if(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
)
771 EnterCriticalSection( &request
->headers_section
);
773 while((HeaderIndex
= HTTP_GetCustomHeaderIndex(request
, szSet_Cookie
, numCookies
++, FALSE
)) != -1)
778 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
780 if (!setCookieHeader
->lpszValue
)
783 data
= strchrW(setCookieHeader
->lpszValue
, '=');
787 name
= heap_strndupW(setCookieHeader
->lpszValue
, data
-setCookieHeader
->lpszValue
);
792 set_cookie(request
->server
->name
, request
->path
, name
, data
, INTERNET_COOKIE_HTTPONLY
);
796 LeaveCriticalSection( &request
->headers_section
);
799 static void strip_spaces(LPWSTR start
)
808 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
810 end
= start
+ strlenW(start
) - 1;
811 while (end
>= start
&& *end
== ' ')
818 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
820 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
821 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
823 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAYSIZE(szBasic
)) &&
824 ((pszAuthValue
[ARRAYSIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAYSIZE(szBasic
)]);
825 if (is_basic
&& pszRealm
)
828 LPCWSTR ptr
= &pszAuthValue
[ARRAYSIZE(szBasic
)];
832 token
= strchrW(ptr
,'=');
836 while (*realm
== ' ')
838 if(!strncmpiW(realm
, szRealm
, ARRAYSIZE(szRealm
)) &&
839 (realm
[ARRAYSIZE(szRealm
)] == ' ' || realm
[ARRAYSIZE(szRealm
)] == '='))
842 while (*token
== ' ')
846 *pszRealm
= heap_strdupW(token
);
847 strip_spaces(*pszRealm
);
854 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
856 if (!authinfo
) return;
858 if (SecIsValidHandle(&authinfo
->ctx
))
859 DeleteSecurityContext(&authinfo
->ctx
);
860 if (SecIsValidHandle(&authinfo
->cred
))
861 FreeCredentialsHandle(&authinfo
->cred
);
863 heap_free(authinfo
->auth_data
);
864 heap_free(authinfo
->scheme
);
868 static UINT
retrieve_cached_basic_authorization(const WCHAR
*host
, const WCHAR
*realm
, char **auth_data
)
870 basicAuthorizationData
*ad
;
873 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
875 EnterCriticalSection(&authcache_cs
);
876 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
878 if (!strcmpiW(host
, ad
->host
) && (!realm
|| !strcmpW(realm
, ad
->realm
)))
880 TRACE("Authorization found in cache\n");
881 *auth_data
= heap_alloc(ad
->authorizationLen
);
882 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
883 rc
= ad
->authorizationLen
;
887 LeaveCriticalSection(&authcache_cs
);
891 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
894 basicAuthorizationData
* ad
= NULL
;
896 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
898 EnterCriticalSection(&authcache_cs
);
899 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
901 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
902 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
911 TRACE("Found match in cache, replacing\n");
912 heap_free(ad
->authorization
);
913 ad
->authorization
= heap_alloc(auth_data_len
);
914 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
915 ad
->authorizationLen
= auth_data_len
;
919 ad
= heap_alloc(sizeof(basicAuthorizationData
));
920 ad
->host
= heap_strdupW(host
);
921 ad
->realm
= heap_strdupW(realm
);
922 ad
->authorization
= heap_alloc(auth_data_len
);
923 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
924 ad
->authorizationLen
= auth_data_len
;
925 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
926 TRACE("authorization cached\n");
928 LeaveCriticalSection(&authcache_cs
);
931 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
932 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
934 authorizationData
*ad
;
936 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
938 EnterCriticalSection(&authcache_cs
);
939 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
940 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
941 TRACE("Authorization found in cache\n");
943 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
944 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
945 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
946 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
947 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
948 heap_free(nt_auth_identity
->User
);
949 heap_free(nt_auth_identity
->Password
);
950 heap_free(nt_auth_identity
->Domain
);
954 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
955 nt_auth_identity
->UserLength
= ad
->user_len
;
956 nt_auth_identity
->PasswordLength
= ad
->password_len
;
957 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
958 nt_auth_identity
->DomainLength
= ad
->domain_len
;
959 LeaveCriticalSection(&authcache_cs
);
963 LeaveCriticalSection(&authcache_cs
);
968 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
969 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
971 authorizationData
*ad
;
974 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
976 EnterCriticalSection(&authcache_cs
);
977 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
978 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
985 heap_free(ad
->password
);
986 heap_free(ad
->domain
);
988 ad
= heap_alloc(sizeof(authorizationData
));
990 LeaveCriticalSection(&authcache_cs
);
994 ad
->host
= heap_strdupW(host
);
995 ad
->scheme
= heap_strdupW(scheme
);
996 list_add_head(&authorizationCache
, &ad
->entry
);
999 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
1000 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
1001 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
1002 ad
->user_len
= nt_auth_identity
->UserLength
;
1003 ad
->password_len
= nt_auth_identity
->PasswordLength
;
1004 ad
->domain_len
= nt_auth_identity
->DomainLength
;
1006 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
1007 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
1008 heap_free(ad
->host
);
1009 heap_free(ad
->scheme
);
1010 heap_free(ad
->user
);
1011 heap_free(ad
->password
);
1012 heap_free(ad
->domain
);
1013 list_remove(&ad
->entry
);
1017 LeaveCriticalSection(&authcache_cs
);
1020 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
1021 struct HttpAuthInfo
**ppAuthInfo
,
1022 LPWSTR domain_and_username
, LPWSTR password
,
1025 SECURITY_STATUS sec_status
;
1026 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
1028 LPWSTR szRealm
= NULL
;
1030 TRACE("%s\n", debugstr_w(pszAuthValue
));
1037 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
1041 SecInvalidateHandle(&pAuthInfo
->cred
);
1042 SecInvalidateHandle(&pAuthInfo
->ctx
);
1043 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1044 pAuthInfo
->attr
= 0;
1045 pAuthInfo
->auth_data
= NULL
;
1046 pAuthInfo
->auth_data_len
= 0;
1047 pAuthInfo
->finished
= FALSE
;
1049 if (is_basic_auth_value(pszAuthValue
,NULL
))
1051 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1052 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1053 if (!pAuthInfo
->scheme
)
1055 heap_free(pAuthInfo
);
1062 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1064 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1065 if (!pAuthInfo
->scheme
)
1067 heap_free(pAuthInfo
);
1071 if (domain_and_username
)
1073 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1074 WCHAR
*domain
= domain_and_username
;
1076 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1078 pAuthData
= &nt_auth_identity
;
1083 user
= domain_and_username
;
1087 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1088 nt_auth_identity
.User
= user
;
1089 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1090 nt_auth_identity
.Domain
= domain
;
1091 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1092 nt_auth_identity
.Password
= password
;
1093 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1095 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1097 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1098 pAuthData
= &nt_auth_identity
;
1100 /* use default credentials */
1103 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1104 SECPKG_CRED_OUTBOUND
, NULL
,
1106 NULL
, &pAuthInfo
->cred
,
1109 if(pAuthData
&& !domain_and_username
) {
1110 heap_free(nt_auth_identity
.User
);
1111 heap_free(nt_auth_identity
.Domain
);
1112 heap_free(nt_auth_identity
.Password
);
1115 if (sec_status
== SEC_E_OK
)
1117 PSecPkgInfoW sec_pkg_info
;
1118 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1119 if (sec_status
== SEC_E_OK
)
1121 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1122 FreeContextBuffer(sec_pkg_info
);
1125 if (sec_status
!= SEC_E_OK
)
1127 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1128 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1129 heap_free(pAuthInfo
->scheme
);
1130 heap_free(pAuthInfo
);
1134 *ppAuthInfo
= pAuthInfo
;
1136 else if (pAuthInfo
->finished
)
1139 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1140 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1142 ERR("authentication scheme changed from %s to %s\n",
1143 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1147 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1151 char *auth_data
= NULL
;
1152 UINT auth_data_len
= 0;
1154 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1156 if (!domain_and_username
)
1158 if (host
&& szRealm
)
1159 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1160 if (auth_data_len
== 0)
1168 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1169 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1171 /* length includes a nul terminator, which will be re-used for the ':' */
1172 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1179 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1180 auth_data
[userlen
] = ':';
1181 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1182 auth_data_len
= userlen
+ 1 + passlen
;
1183 if (host
&& szRealm
)
1184 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1187 pAuthInfo
->auth_data
= auth_data
;
1188 pAuthInfo
->auth_data_len
= auth_data_len
;
1189 pAuthInfo
->finished
= TRUE
;
1195 LPCWSTR pszAuthData
;
1196 SecBufferDesc out_desc
, in_desc
;
1198 unsigned char *buffer
;
1199 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1200 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1202 in
.BufferType
= SECBUFFER_TOKEN
;
1206 in_desc
.ulVersion
= 0;
1207 in_desc
.cBuffers
= 1;
1208 in_desc
.pBuffers
= &in
;
1210 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1211 if (*pszAuthData
== ' ')
1214 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1215 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1216 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1219 buffer
= heap_alloc(pAuthInfo
->max_token
);
1221 out
.BufferType
= SECBUFFER_TOKEN
;
1222 out
.cbBuffer
= pAuthInfo
->max_token
;
1223 out
.pvBuffer
= buffer
;
1225 out_desc
.ulVersion
= 0;
1226 out_desc
.cBuffers
= 1;
1227 out_desc
.pBuffers
= &out
;
1229 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1230 first
? NULL
: &pAuthInfo
->ctx
,
1231 first
? request
->server
->name
: NULL
,
1232 context_req
, 0, SECURITY_NETWORK_DREP
,
1233 in
.pvBuffer
? &in_desc
: NULL
,
1234 0, &pAuthInfo
->ctx
, &out_desc
,
1235 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1236 if (sec_status
== SEC_E_OK
)
1238 pAuthInfo
->finished
= TRUE
;
1239 pAuthInfo
->auth_data
= out
.pvBuffer
;
1240 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1241 TRACE("sending last auth packet\n");
1243 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1245 pAuthInfo
->auth_data
= out
.pvBuffer
;
1246 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1247 TRACE("sending next auth packet\n");
1251 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1252 heap_free(out
.pvBuffer
);
1253 destroy_authinfo(pAuthInfo
);
1262 /***********************************************************************
1263 * HTTP_HttpAddRequestHeadersW (internal)
1265 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1266 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1271 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1273 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1275 if( dwHeaderLength
== ~0U )
1276 len
= strlenW(lpszHeader
);
1278 len
= dwHeaderLength
;
1279 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1280 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1286 LPWSTR
* pFieldAndValue
;
1288 lpszEnd
= lpszStart
;
1290 while (*lpszEnd
!= '\0')
1292 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1297 if (*lpszStart
== '\0')
1300 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1303 lpszEnd
++; /* Jump over newline */
1305 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1306 if (*lpszStart
== '\0')
1308 /* Skip 0-length headers */
1309 lpszStart
= lpszEnd
;
1310 res
= ERROR_SUCCESS
;
1313 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1316 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1317 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1318 HTTP_FreeTokens(pFieldAndValue
);
1321 lpszStart
= lpszEnd
;
1322 } while (res
== ERROR_SUCCESS
);
1328 /***********************************************************************
1329 * HttpAddRequestHeadersW (WININET.@)
1331 * Adds one or more HTTP header to the request handler
1334 * On Windows if dwHeaderLength includes the trailing '\0', then
1335 * HttpAddRequestHeadersW() adds it too. However this results in an
1336 * invalid HTTP header which is rejected by some servers so we probably
1337 * don't need to match Windows on that point.
1344 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1345 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1347 http_request_t
*request
;
1348 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1350 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1355 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1356 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1357 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1359 WININET_Release( &request
->hdr
);
1361 if(res
!= ERROR_SUCCESS
)
1363 return res
== ERROR_SUCCESS
;
1366 /***********************************************************************
1367 * HttpAddRequestHeadersA (WININET.@)
1369 * Adds one or more HTTP header to the request handler
1376 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1377 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1383 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1385 len
= MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, NULL
, 0 );
1386 hdr
= heap_alloc(len
*sizeof(WCHAR
));
1387 MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, hdr
, len
);
1388 if( dwHeaderLength
!= ~0U )
1389 dwHeaderLength
= len
;
1391 r
= HttpAddRequestHeadersW( hHttpRequest
, hdr
, dwHeaderLength
, dwModifier
);
1397 static void free_accept_types( WCHAR
**accept_types
)
1399 WCHAR
*ptr
, **types
= accept_types
;
1402 while ((ptr
= *types
))
1407 heap_free( accept_types
);
1410 static WCHAR
**convert_accept_types( const char **accept_types
)
1413 const char **types
= accept_types
;
1415 BOOL invalid_pointer
= FALSE
;
1417 if (!types
) return NULL
;
1423 /* find out how many there are */
1424 if (*types
&& **types
)
1426 TRACE("accept type: %s\n", debugstr_a(*types
));
1432 WARN("invalid accept type pointer\n");
1433 invalid_pointer
= TRUE
;
1438 if (invalid_pointer
) return NULL
;
1439 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1441 types
= accept_types
;
1444 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1447 typesW
[count
] = NULL
;
1451 /***********************************************************************
1452 * HttpOpenRequestA (WININET.@)
1454 * Open a HTTP request handle
1457 * HINTERNET a HTTP request handle on success
1461 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1462 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1463 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1464 DWORD dwFlags
, DWORD_PTR dwContext
)
1466 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1467 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1468 HINTERNET rc
= NULL
;
1470 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1471 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1472 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1473 dwFlags
, dwContext
);
1477 szVerb
= heap_strdupAtoW(lpszVerb
);
1484 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1485 if ( !szObjectName
)
1491 szVersion
= heap_strdupAtoW(lpszVersion
);
1498 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1503 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1504 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1505 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1508 free_accept_types(szAcceptTypes
);
1509 heap_free(szReferrer
);
1510 heap_free(szVersion
);
1511 heap_free(szObjectName
);
1516 /***********************************************************************
1519 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1522 static const CHAR HTTP_Base64Enc
[] =
1523 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1527 /* first 6 bits, all from bin[0] */
1528 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1529 x
= (bin
[0] & 3) << 4;
1531 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1534 base64
[n
++] = HTTP_Base64Enc
[x
];
1539 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1540 x
= ( bin
[1] & 0x0f ) << 2;
1542 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1545 base64
[n
++] = HTTP_Base64Enc
[x
];
1549 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1551 /* last 6 bits, all from bin [2] */
1552 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1560 static const signed char HTTP_Base64Dec
[] =
1562 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1563 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1564 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1565 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1566 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1567 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1568 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1569 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1572 /***********************************************************************
1575 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1583 if (base64
[0] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1584 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1585 base64
[1] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1586 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1588 WARN("invalid base64: %s\n", debugstr_w(base64
));
1592 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1595 if ((base64
[2] == '=') && (base64
[3] == '='))
1597 if (base64
[2] > ARRAYSIZE(HTTP_Base64Dec
) ||
1598 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1600 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1604 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1607 if (base64
[3] == '=')
1609 if (base64
[3] > ARRAYSIZE(HTTP_Base64Dec
) ||
1610 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1612 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1616 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1625 static WCHAR
*encode_auth_data( const WCHAR
*scheme
, const char *data
, UINT data_len
)
1628 UINT len
, scheme_len
= strlenW( scheme
);
1630 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1631 len
= scheme_len
+ 1 + ((data_len
+ 2) * 4) / 3;
1632 if (!(ret
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1633 memcpy( ret
, scheme
, scheme_len
* sizeof(WCHAR
) );
1634 ret
[scheme_len
] = ' ';
1635 HTTP_EncodeBase64( data
, data_len
, ret
+ scheme_len
+ 1 );
1640 /***********************************************************************
1641 * HTTP_InsertAuthorization
1643 * Insert or delete the authorization field in the request header.
1645 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1647 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1648 WCHAR
*host
, *authorization
= NULL
;
1652 if (pAuthInfo
->auth_data_len
)
1654 if (!(authorization
= encode_auth_data(pAuthInfo
->scheme
, pAuthInfo
->auth_data
, pAuthInfo
->auth_data_len
)))
1657 /* clear the data as it isn't valid now that it has been sent to the
1658 * server, unless it's Basic authentication which doesn't do
1659 * connection tracking */
1660 if (strcmpiW(pAuthInfo
->scheme
, wszBasic
))
1662 heap_free(pAuthInfo
->auth_data
);
1663 pAuthInfo
->auth_data
= NULL
;
1664 pAuthInfo
->auth_data_len
= 0;
1668 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1670 HTTP_ProcessHeader(request
, header
, authorization
,
1671 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
1672 heap_free(authorization
);
1674 else if (!strcmpW(header
, szAuthorization
) && (host
= get_host_header(request
)))
1679 if ((data_len
= retrieve_cached_basic_authorization(host
, NULL
, &data
)))
1681 TRACE("Found cached basic authorization for %s\n", debugstr_w(host
));
1683 if (!(authorization
= encode_auth_data(wszBasic
, data
, data_len
)))
1690 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1692 HTTP_ProcessHeader(request
, header
, authorization
,
1693 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
1695 heap_free(authorization
);
1702 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1707 len
= strlenW(req
->server
->scheme_host_port
);
1708 size
= len
+ strlenW(req
->path
) + 1;
1709 if(*req
->path
!= '/')
1711 url
= heap_alloc(size
* sizeof(WCHAR
));
1715 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1716 if(*req
->path
!= '/')
1719 strcpyW(url
+len
, req
->path
);
1721 TRACE("url=%s\n", debugstr_w(url
));
1725 static BOOL
HTTP_DomainMatches(LPCWSTR server
, LPCWSTR domain
)
1727 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1730 if (!strcmpiW( domain
, localW
) && !strchrW( server
, '.' ))
1732 else if (*domain
== '*')
1734 if (domain
[1] == '.')
1738 /* For a hostname to match a wildcard, the last domain must match
1739 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1740 * hostname is www.foo.a.b, it matches, but a.b does not.
1742 dot
= strchrW( server
, '.' );
1745 int len
= strlenW( dot
+ 1 );
1747 if (len
> strlenW( domain
+ 2 ))
1751 /* The server's domain is longer than the wildcard, so it
1752 * could be a subdomain. Compare the last portion of the
1755 ptr
= dot
+ len
+ 1 - strlenW( domain
+ 2 );
1756 if (!strcmpiW( ptr
, domain
+ 2 ))
1758 /* This is only a match if the preceding character is
1759 * a '.', i.e. that it is a matching domain. E.g.
1760 * if domain is '*.b.c' and server is 'www.ab.c' they
1763 ret
= *(ptr
- 1) == '.';
1767 ret
= !strcmpiW( dot
+ 1, domain
+ 2 );
1772 ret
= !strcmpiW( server
, domain
);
1776 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1781 if (!lpwai
->proxyBypass
) return FALSE
;
1782 ptr
= lpwai
->proxyBypass
;
1786 ptr
= strchrW( ptr
, ';' );
1788 ptr
= strchrW( tmp
, ' ' );
1791 if (ptr
- tmp
< INTERNET_MAX_HOST_NAME_LENGTH
)
1793 WCHAR domain
[INTERNET_MAX_HOST_NAME_LENGTH
];
1795 memcpy( domain
, tmp
, (ptr
- tmp
) * sizeof(WCHAR
) );
1796 domain
[ptr
- tmp
] = 0;
1797 ret
= HTTP_DomainMatches( server
, domain
);
1802 ret
= HTTP_DomainMatches( server
, tmp
);
1803 } while (ptr
&& !ret
);
1807 /***********************************************************************
1808 * HTTP_DealWithProxy
1810 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1812 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1813 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1814 static const WCHAR szFormat
[] = { 'h','t','t','p',':','/','/','%','s',0 };
1815 WCHAR buf
[INTERNET_MAX_HOST_NAME_LENGTH
];
1816 WCHAR protoProxy
[INTERNET_MAX_URL_LENGTH
];
1817 DWORD protoProxyLen
= INTERNET_MAX_URL_LENGTH
;
1818 WCHAR proxy
[INTERNET_MAX_URL_LENGTH
];
1819 static WCHAR szNul
[] = { 0 };
1820 URL_COMPONENTSW UrlComponents
;
1821 server_t
*new_server
;
1824 memset( &UrlComponents
, 0, sizeof UrlComponents
);
1825 UrlComponents
.dwStructSize
= sizeof UrlComponents
;
1826 UrlComponents
.lpszHostName
= buf
;
1827 UrlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
1829 if (!INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
, protoProxy
, &protoProxyLen
))
1831 if( CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1832 protoProxy
,strlenW(szHttp
),szHttp
,strlenW(szHttp
)) )
1833 sprintfW(proxy
, szFormat
, protoProxy
);
1835 strcpyW(proxy
, protoProxy
);
1836 if( !InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) )
1838 if( UrlComponents
.dwHostNameLength
== 0 )
1841 if( !request
->path
)
1842 request
->path
= szNul
;
1844 is_https
= (UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
);
1845 if (is_https
&& UrlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
1846 UrlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
1848 new_server
= get_server(UrlComponents
.lpszHostName
, UrlComponents
.nPort
, is_https
, TRUE
);
1852 request
->proxy
= new_server
;
1854 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1858 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1860 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1863 if(server
->addr_len
)
1864 return ERROR_SUCCESS
;
1866 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1867 INTERNET_STATUS_RESOLVING_NAME
,
1869 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1871 addr_len
= sizeof(server
->addr
);
1872 if (!GetAddress(server
->name
, server
->port
, (SOCKADDR
*)&server
->addr
, &addr_len
, server
->addr_str
))
1873 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1875 server
->addr_len
= addr_len
;
1876 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1877 INTERNET_STATUS_NAME_RESOLVED
,
1878 server
->addr_str
, strlen(server
->addr_str
)+1);
1880 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1881 return ERROR_SUCCESS
;
1884 static BOOL
HTTP_GetRequestURL(http_request_t
*req
, LPWSTR buf
)
1886 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1887 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1888 static const WCHAR slash
[] = { '/',0 };
1889 LPHTTPHEADERW host_header
;
1893 EnterCriticalSection( &req
->headers_section
);
1895 host_header
= HTTP_GetHeader(req
, hostW
);
1896 if (host_header
) host
= host_header
->lpszValue
;
1897 else host
= req
->server
->canon_host_port
;
1899 if (req
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)
1903 strcpyW(buf
, scheme
);
1905 if (req
->path
[0] != '/')
1906 strcatW(buf
, slash
);
1907 strcatW(buf
, req
->path
);
1909 LeaveCriticalSection( &req
->headers_section
);
1914 /***********************************************************************
1915 * HTTPREQ_Destroy (internal)
1917 * Deallocate request handle
1920 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1922 http_request_t
*request
= (http_request_t
*) hdr
;
1927 if(request
->hCacheFile
)
1928 CloseHandle(request
->hCacheFile
);
1929 if(request
->req_file
)
1930 req_file_release(request
->req_file
);
1932 request
->headers_section
.DebugInfo
->Spare
[0] = 0;
1933 DeleteCriticalSection( &request
->headers_section
);
1934 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1935 DeleteCriticalSection( &request
->read_section
);
1936 WININET_Release(&request
->session
->hdr
);
1938 destroy_authinfo(request
->authInfo
);
1939 destroy_authinfo(request
->proxyAuthInfo
);
1942 server_release(request
->server
);
1944 server_release(request
->proxy
);
1946 heap_free(request
->path
);
1947 heap_free(request
->verb
);
1948 heap_free(request
->version
);
1949 heap_free(request
->statusText
);
1951 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1953 heap_free(request
->custHeaders
[i
].lpszField
);
1954 heap_free(request
->custHeaders
[i
].lpszValue
);
1956 destroy_data_stream(request
->data_stream
);
1957 heap_free(request
->custHeaders
);
1960 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1962 TRACE("%p %p %x\n",req
, req
->netconn
, reuse
);
1964 if(!is_valid_netconn(req
->netconn
))
1967 if(reuse
&& req
->netconn
->keep_alive
) {
1970 EnterCriticalSection(&connection_pool_cs
);
1972 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1973 req
->netconn
->keep_until
= GetTickCount64() + COLLECT_TIME
;
1974 req
->netconn
= NULL
;
1976 run_collector
= !collector_running
;
1977 collector_running
= TRUE
;
1979 LeaveCriticalSection(&connection_pool_cs
);
1982 HANDLE thread
= NULL
;
1985 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
1987 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
1989 EnterCriticalSection(&connection_pool_cs
);
1990 collector_running
= FALSE
;
1991 LeaveCriticalSection(&connection_pool_cs
);
1994 FreeLibrary(module
);
1997 CloseHandle(thread
);
2002 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
2003 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
2005 close_netconn(req
->netconn
);
2007 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
2008 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
2011 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
2013 WCHAR szVersion
[10];
2014 WCHAR szConnectionResponse
[20];
2015 DWORD dwBufferSize
= sizeof(szVersion
);
2016 BOOL keepalive
= FALSE
;
2018 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2019 * the connection is keep-alive by default */
2020 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2021 && !strcmpiW(szVersion
, g_szHttp1_1
))
2026 dwBufferSize
= sizeof(szConnectionResponse
);
2027 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2028 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
2030 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2036 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2038 http_request_t
*req
= (http_request_t
*)hdr
;
2040 http_release_netconn(req
, drain_content(req
, FALSE
));
2043 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2048 WCHAR
*buf
= buffer
;
2050 if (str
) len
= strlenW(str
);
2052 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2054 *size
= (len
+ 1) * sizeof(WCHAR
);
2055 return ERROR_INSUFFICIENT_BUFFER
;
2057 if (str
) strcpyW(buf
, str
);
2061 return ERROR_SUCCESS
;
2067 if (str
) len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
2072 return ERROR_INSUFFICIENT_BUFFER
;
2074 if (str
) WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, *size
, NULL
, NULL
);
2078 return ERROR_SUCCESS
;
2082 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2084 http_request_t
*req
= (http_request_t
*)hdr
;
2087 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2089 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2091 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2093 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2094 return ERROR_INSUFFICIENT_BUFFER
;
2095 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2096 /* FIXME: can't get a SOCKET from our connection since we don't use
2100 /* FIXME: get source port from req->netConnection */
2101 info
->SourcePort
= 0;
2102 info
->DestPort
= req
->server
->port
;
2104 if (HTTP_KeepAlive(req
))
2105 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2107 info
->Flags
|= IDSI_FLAG_PROXY
;
2108 if (is_valid_netconn(req
->netconn
) && req
->netconn
->secure
)
2109 info
->Flags
|= IDSI_FLAG_SECURE
;
2111 return ERROR_SUCCESS
;
2115 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2117 case INTERNET_OPTION_SECURITY_FLAGS
:
2121 if (*size
< sizeof(ULONG
))
2122 return ERROR_INSUFFICIENT_BUFFER
;
2124 *size
= sizeof(DWORD
);
2125 flags
= is_valid_netconn(req
->netconn
) ? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2126 *(DWORD
*)buffer
= flags
;
2128 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2129 return ERROR_SUCCESS
;
2132 case INTERNET_OPTION_HANDLE_TYPE
:
2133 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2135 if (*size
< sizeof(ULONG
))
2136 return ERROR_INSUFFICIENT_BUFFER
;
2138 *size
= sizeof(DWORD
);
2139 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2140 return ERROR_SUCCESS
;
2142 case INTERNET_OPTION_URL
: {
2143 static const WCHAR httpW
[] = {'h','t','t','p',':','/','/',0};
2144 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2146 TRACE("INTERNET_OPTION_URL\n");
2148 strcpyW(url
, httpW
);
2149 strcatW(url
, req
->server
->canon_host_port
);
2150 strcatW(url
, req
->path
);
2152 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url
));
2153 return str_to_buffer(url
, buffer
, size
, unicode
);
2155 case INTERNET_OPTION_USER_AGENT
:
2156 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2157 case INTERNET_OPTION_USERNAME
:
2158 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2159 case INTERNET_OPTION_PASSWORD
:
2160 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2161 case INTERNET_OPTION_PROXY_USERNAME
:
2162 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2163 case INTERNET_OPTION_PROXY_PASSWORD
:
2164 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2166 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2167 INTERNET_CACHE_ENTRY_INFOW
*info
;
2168 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2169 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2170 DWORD nbytes
, error
;
2173 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2175 if (*size
< sizeof(*ts
))
2177 *size
= sizeof(*ts
);
2178 return ERROR_INSUFFICIENT_BUFFER
;
2181 HTTP_GetRequestURL(req
, url
);
2182 ret
= GetUrlCacheEntryInfoW(url
, NULL
, &nbytes
);
2183 error
= GetLastError();
2184 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2186 if (!(info
= heap_alloc(nbytes
)))
2187 return ERROR_OUTOFMEMORY
;
2189 GetUrlCacheEntryInfoW(url
, info
, &nbytes
);
2191 ts
->ftExpires
= info
->ExpireTime
;
2192 ts
->ftLastModified
= info
->LastModifiedTime
;
2195 *size
= sizeof(*ts
);
2196 return ERROR_SUCCESS
;
2201 case INTERNET_OPTION_DATAFILE_NAME
: {
2204 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2206 if(!req
->req_file
) {
2208 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2212 req_size
= (lstrlenW(req
->req_file
->file_name
)+1) * sizeof(WCHAR
);
2213 if(*size
< req_size
)
2214 return ERROR_INSUFFICIENT_BUFFER
;
2217 memcpy(buffer
, req
->req_file
->file_name
, *size
);
2218 return ERROR_SUCCESS
;
2220 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
, -1, NULL
, 0, NULL
, NULL
);
2221 if (req_size
> *size
)
2222 return ERROR_INSUFFICIENT_BUFFER
;
2224 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
,
2225 -1, buffer
, *size
, NULL
, NULL
);
2226 return ERROR_SUCCESS
;
2230 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2231 PCCERT_CONTEXT context
;
2234 return ERROR_INTERNET_INVALID_OPERATION
;
2236 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2237 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2238 return ERROR_INSUFFICIENT_BUFFER
;
2241 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2243 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2246 memset(info
, 0, sizeof(*info
));
2247 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2248 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2249 len
= CertNameToStrA(context
->dwCertEncodingType
,
2250 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2251 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2252 if(info
->lpszSubjectInfo
)
2253 CertNameToStrA(context
->dwCertEncodingType
,
2254 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2255 info
->lpszSubjectInfo
, len
);
2256 len
= CertNameToStrA(context
->dwCertEncodingType
,
2257 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2258 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2259 if(info
->lpszIssuerInfo
)
2260 CertNameToStrA(context
->dwCertEncodingType
,
2261 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2262 info
->lpszIssuerInfo
, len
);
2263 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2264 CertFreeCertificateContext(context
);
2265 return ERROR_SUCCESS
;
2267 return ERROR_NOT_SUPPORTED
;
2269 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2270 if (*size
< sizeof(DWORD
))
2271 return ERROR_INSUFFICIENT_BUFFER
;
2273 *size
= sizeof(DWORD
);
2274 *(DWORD
*)buffer
= req
->connect_timeout
;
2275 return ERROR_SUCCESS
;
2276 case INTERNET_OPTION_REQUEST_FLAGS
: {
2279 if (*size
< sizeof(DWORD
))
2280 return ERROR_INSUFFICIENT_BUFFER
;
2282 /* FIXME: Add support for:
2283 * INTERNET_REQFLAG_FROM_CACHE
2284 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2288 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2289 if(!req
->status_code
)
2290 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2292 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2294 *size
= sizeof(DWORD
);
2295 *(DWORD
*)buffer
= flags
;
2296 return ERROR_SUCCESS
;
2300 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2303 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2305 http_request_t
*req
= (http_request_t
*)hdr
;
2308 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2309 TRACE("Undocumented option 99\n");
2311 if (!buffer
|| size
!= sizeof(DWORD
))
2312 return ERROR_INVALID_PARAMETER
;
2313 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2314 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2317 case INTERNET_OPTION_SECURITY_FLAGS
:
2321 if (!buffer
|| size
!= sizeof(DWORD
))
2322 return ERROR_INVALID_PARAMETER
;
2323 flags
= *(DWORD
*)buffer
;
2324 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2325 flags
&= SECURITY_SET_MASK
;
2326 req
->security_flags
|= flags
;
2327 if(is_valid_netconn(req
->netconn
))
2328 req
->netconn
->security_flags
|= flags
;
2329 return ERROR_SUCCESS
;
2331 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2332 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2333 req
->connect_timeout
= *(DWORD
*)buffer
;
2334 return ERROR_SUCCESS
;
2336 case INTERNET_OPTION_SEND_TIMEOUT
:
2337 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2338 req
->send_timeout
= *(DWORD
*)buffer
;
2339 return ERROR_SUCCESS
;
2341 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2342 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2343 req
->receive_timeout
= *(DWORD
*)buffer
;
2344 return ERROR_SUCCESS
;
2346 case INTERNET_OPTION_USERNAME
:
2347 heap_free(req
->session
->userName
);
2348 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2349 return ERROR_SUCCESS
;
2351 case INTERNET_OPTION_PASSWORD
:
2352 heap_free(req
->session
->password
);
2353 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2354 return ERROR_SUCCESS
;
2356 case INTERNET_OPTION_PROXY_USERNAME
:
2357 heap_free(req
->session
->appInfo
->proxyUsername
);
2358 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2359 return ERROR_SUCCESS
;
2361 case INTERNET_OPTION_PROXY_PASSWORD
:
2362 heap_free(req
->session
->appInfo
->proxyPassword
);
2363 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2364 return ERROR_SUCCESS
;
2366 case INTERNET_OPTION_HTTP_DECODING
:
2367 if(size
!= sizeof(BOOL
))
2368 return ERROR_INVALID_PARAMETER
;
2369 req
->decoding
= *(BOOL
*)buffer
;
2370 return ERROR_SUCCESS
;
2373 return INET_SetOption(hdr
, option
, buffer
, size
);
2376 static void commit_cache_entry(http_request_t
*req
)
2378 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2382 CloseHandle(req
->hCacheFile
);
2383 req
->hCacheFile
= NULL
;
2385 if(HTTP_GetRequestURL(req
, url
)) {
2390 header
= build_response_header(req
, TRUE
);
2391 header_len
= (header
? strlenW(header
) : 0);
2392 res
= CommitUrlCacheEntryW(url
, req
->req_file
->file_name
, req
->expires
,
2393 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2394 header
, header_len
, NULL
, 0);
2396 req
->req_file
->is_committed
= TRUE
;
2398 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2403 static void create_cache_entry(http_request_t
*req
)
2405 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2406 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2408 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2409 WCHAR file_name
[MAX_PATH
+1];
2412 /* FIXME: We should free previous cache file earlier */
2414 req_file_release(req
->req_file
);
2415 req
->req_file
= NULL
;
2417 if(req
->hCacheFile
) {
2418 CloseHandle(req
->hCacheFile
);
2419 req
->hCacheFile
= NULL
;
2422 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2428 EnterCriticalSection( &req
->headers_section
);
2430 header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2431 if(header_idx
!= -1) {
2434 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2437 while(*ptr
==' ' || *ptr
=='\t')
2440 end
= strchrW(ptr
, ',');
2442 end
= ptr
+ strlenW(ptr
);
2444 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2445 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2456 LeaveCriticalSection( &req
->headers_section
);
2460 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2463 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2466 b
= HTTP_GetRequestURL(req
, url
);
2468 WARN("Could not get URL\n");
2472 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2474 WARN("Could not create cache entry: %08x\n", GetLastError());
2478 create_req_file(file_name
, &req
->req_file
);
2480 req
->hCacheFile
= CreateFileW(file_name
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2481 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2482 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2483 WARN("Could not create file: %u\n", GetLastError());
2484 req
->hCacheFile
= NULL
;
2488 if(req
->read_size
) {
2491 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2493 FIXME("WriteFile failed: %u\n", GetLastError());
2495 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2496 commit_cache_entry(req
);
2500 /* read some more data into the read buffer (the read section must be held) */
2501 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2508 /* move existing data to the start of the buffer */
2510 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2514 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2516 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2517 maxlen
- req
->read_size
, TRUE
, &len
);
2518 if(res
== ERROR_SUCCESS
)
2519 req
->read_size
+= len
;
2524 /* remove some amount of data from the read buffer (the read section must be held) */
2525 static void remove_data( http_request_t
*req
, int count
)
2527 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2528 else req
->read_pos
+= count
;
2531 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2533 int count
, bytes_read
, pos
= 0;
2536 EnterCriticalSection( &req
->read_section
);
2539 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2543 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2544 bytes_read
= count
+ 1;
2546 else count
= bytes_read
= req
->read_size
;
2548 count
= min( count
, *len
- pos
);
2549 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2551 remove_data( req
, bytes_read
);
2554 if ((res
= read_more_data( req
, -1 )))
2556 WARN( "read failed %u\n", res
);
2557 LeaveCriticalSection( &req
->read_section
);
2560 if (!req
->read_size
)
2563 TRACE( "returning empty string\n" );
2564 LeaveCriticalSection( &req
->read_section
);
2565 return ERROR_SUCCESS
;
2568 LeaveCriticalSection( &req
->read_section
);
2572 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2575 buffer
[*len
- 1] = 0;
2576 TRACE( "returning %s\n", debugstr_a(buffer
));
2577 return ERROR_SUCCESS
;
2580 /* check if we have reached the end of the data to read (the read section must be held) */
2581 static BOOL
end_of_read_data( http_request_t
*req
)
2583 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2586 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, blocking_mode_t blocking_mode
)
2590 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, blocking_mode
);
2591 assert(*read
<= size
);
2593 if(req
->hCacheFile
) {
2598 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2600 FIXME("WriteFile failed: %u\n", GetLastError());
2603 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2604 commit_cache_entry(req
);
2610 /* fetch some more data into the read buffer (the read section must be held) */
2611 static DWORD
refill_read_buffer(http_request_t
*req
, blocking_mode_t blocking_mode
, DWORD
*read_bytes
)
2615 if(req
->read_size
== sizeof(req
->read_buf
))
2616 return ERROR_SUCCESS
;
2620 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2624 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2625 &read
, blocking_mode
);
2626 req
->read_size
+= read
;
2628 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2634 /* return the size of data available to be read immediately (the read section must be held) */
2635 static DWORD
get_avail_data( http_request_t
*req
)
2637 return req
->read_size
+ req
->data_stream
->vtbl
->get_avail_data(req
->data_stream
, req
);
2640 static DWORD
netconn_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2642 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2645 if(is_valid_netconn(req
->netconn
))
2646 NETCON_query_data_available(req
->netconn
, &avail
);
2647 return netconn_stream
->content_length
== ~0u
2649 : min(avail
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2652 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2654 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2655 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !is_valid_netconn(req
->netconn
);
2658 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2659 DWORD
*read
, blocking_mode_t blocking_mode
)
2661 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2662 DWORD res
= ERROR_SUCCESS
;
2663 int len
= 0, ret
= 0;
2665 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2667 if(size
&& is_valid_netconn(req
->netconn
)) {
2668 while((res
= NETCON_recv(req
->netconn
, buf
+ret
, size
-ret
, blocking_mode
!= BLOCKING_DISALLOW
, &len
)) == ERROR_SUCCESS
) {
2670 netconn_stream
->content_length
= netconn_stream
->content_read
;
2674 netconn_stream
->content_read
+= len
;
2675 if(blocking_mode
!= BLOCKING_WAITALL
|| size
== ret
)
2679 if(ret
|| (blocking_mode
== BLOCKING_DISALLOW
&& res
== WSAEWOULDBLOCK
))
2680 res
= ERROR_SUCCESS
;
2683 TRACE("read %u bytes\n", ret
);
2688 static BOOL
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2690 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2694 if(netconn_end_of_data(stream
, req
))
2698 if(NETCON_recv(req
->netconn
, buf
, sizeof(buf
), FALSE
, &len
) != ERROR_SUCCESS
)
2701 netconn_stream
->content_read
+= len
;
2702 }while(netconn_stream
->content_read
< netconn_stream
->content_length
);
2707 static void netconn_destroy(data_stream_t
*stream
)
2711 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2712 netconn_get_avail_data
,
2713 netconn_end_of_data
,
2715 netconn_drain_content
,
2719 /* read some more data into the read buffer (the read section must be held) */
2720 static DWORD
read_more_chunked_data(chunked_stream_t
*stream
, http_request_t
*req
, int maxlen
)
2725 assert(!stream
->end_of_data
);
2727 if (stream
->buf_pos
)
2729 /* move existing data to the start of the buffer */
2730 if(stream
->buf_size
)
2731 memmove(stream
->buf
, stream
->buf
+ stream
->buf_pos
, stream
->buf_size
);
2732 stream
->buf_pos
= 0;
2735 if (maxlen
== -1) maxlen
= sizeof(stream
->buf
);
2737 res
= NETCON_recv( req
->netconn
, stream
->buf
+ stream
->buf_size
,
2738 maxlen
- stream
->buf_size
, TRUE
, &len
);
2739 if(res
== ERROR_SUCCESS
)
2740 stream
->buf_size
+= len
;
2745 /* remove some amount of data from the read buffer (the read section must be held) */
2746 static void remove_chunked_data(chunked_stream_t
*stream
, int count
)
2748 if (!(stream
->buf_size
-= count
)) stream
->buf_pos
= 0;
2749 else stream
->buf_pos
+= count
;
2752 /* discard data contents until we reach end of line (the read section must be held) */
2753 static DWORD
discard_chunked_eol(chunked_stream_t
*stream
, http_request_t
*req
)
2759 BYTE
*eol
= memchr(stream
->buf
+ stream
->buf_pos
, '\n', stream
->buf_size
);
2762 remove_chunked_data(stream
, (eol
+ 1) - (stream
->buf
+ stream
->buf_pos
));
2765 stream
->buf_pos
= stream
->buf_size
= 0; /* discard everything */
2766 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2767 } while (stream
->buf_size
);
2768 return ERROR_SUCCESS
;
2771 /* read the size of the next chunk (the read section must be held) */
2772 static DWORD
start_next_chunk(chunked_stream_t
*stream
, http_request_t
*req
)
2774 DWORD chunk_size
= 0, res
;
2776 assert(!stream
->chunk_size
|| stream
->chunk_size
== ~0u);
2778 if (stream
->end_of_data
) return ERROR_SUCCESS
;
2780 /* read terminator for the previous chunk */
2781 if(!stream
->chunk_size
&& (res
= discard_chunked_eol(stream
, req
)) != ERROR_SUCCESS
)
2786 while (stream
->buf_size
)
2788 char ch
= stream
->buf
[stream
->buf_pos
];
2789 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
2790 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
2791 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
2792 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
2794 TRACE( "reading %u byte chunk\n", chunk_size
);
2795 stream
->chunk_size
= chunk_size
;
2796 if (req
->contentLength
== ~0u) req
->contentLength
= chunk_size
;
2797 else req
->contentLength
+= chunk_size
;
2799 /* eat the rest of this line */
2800 if ((res
= discard_chunked_eol(stream
, req
)) != ERROR_SUCCESS
)
2803 /* if there's chunk data, return now */
2804 if (chunk_size
) return ERROR_SUCCESS
;
2806 /* otherwise, eat the terminator for this chunk */
2807 if ((res
= discard_chunked_eol(stream
, req
)) != ERROR_SUCCESS
)
2810 stream
->end_of_data
= TRUE
;
2811 return ERROR_SUCCESS
;
2813 remove_chunked_data(stream
, 1);
2815 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2816 if (!stream
->buf_size
)
2818 stream
->chunk_size
= 0;
2819 return ERROR_SUCCESS
;
2824 static DWORD
chunked_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2826 /* Allow reading only from read buffer */
2830 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2832 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2833 return chunked_stream
->end_of_data
;
2836 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2837 DWORD
*read
, blocking_mode_t blocking_mode
)
2839 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2840 DWORD read_bytes
= 0, ret_read
= 0, res
= ERROR_SUCCESS
;
2842 if(!chunked_stream
->chunk_size
|| chunked_stream
->chunk_size
== ~0u) {
2843 res
= start_next_chunk(chunked_stream
, req
);
2844 if(res
!= ERROR_SUCCESS
)
2848 while(size
&& chunked_stream
->chunk_size
&& !chunked_stream
->end_of_data
) {
2849 if(chunked_stream
->buf_size
) {
2850 read_bytes
= min(size
, min(chunked_stream
->buf_size
, chunked_stream
->chunk_size
));
2852 /* this could block */
2853 if(blocking_mode
== BLOCKING_DISALLOW
&& read_bytes
== chunked_stream
->chunk_size
)
2856 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2857 remove_chunked_data(chunked_stream
, read_bytes
);
2859 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2861 if(blocking_mode
== BLOCKING_DISALLOW
) {
2864 if(!is_valid_netconn(req
->netconn
) || !NETCON_query_data_available(req
->netconn
, &avail
) || !avail
)
2866 if(read_bytes
> avail
)
2869 /* this could block */
2870 if(read_bytes
== chunked_stream
->chunk_size
)
2874 res
= NETCON_recv(req
->netconn
, (char *)buf
+ret_read
, read_bytes
, TRUE
, (int*)&read_bytes
);
2875 if(res
!= ERROR_SUCCESS
)
2879 chunked_stream
->chunk_size
-= read_bytes
;
2881 ret_read
+= read_bytes
;
2882 if(size
&& !chunked_stream
->chunk_size
) {
2883 assert(blocking_mode
!= BLOCKING_DISALLOW
);
2884 res
= start_next_chunk(chunked_stream
, req
);
2885 if(res
!= ERROR_SUCCESS
)
2889 if(blocking_mode
== BLOCKING_ALLOW
)
2890 blocking_mode
= BLOCKING_DISALLOW
;
2893 TRACE("read %u bytes\n", ret_read
);
2898 static BOOL
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2900 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2902 remove_chunked_data(chunked_stream
, chunked_stream
->buf_size
);
2903 return chunked_stream
->end_of_data
;
2906 static void chunked_destroy(data_stream_t
*stream
)
2908 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2909 heap_free(chunked_stream
);
2912 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2913 chunked_get_avail_data
,
2914 chunked_end_of_data
,
2916 chunked_drain_content
,
2920 /* set the request content length based on the headers */
2921 static DWORD
set_content_length(http_request_t
*request
)
2923 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2924 static const WCHAR headW
[] = {'H','E','A','D',0};
2928 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
|| !strcmpW(request
->verb
, headW
)) {
2929 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2930 return ERROR_SUCCESS
;
2933 size
= sizeof(request
->contentLength
);
2934 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2935 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2936 request
->contentLength
= ~0u;
2937 request
->netconn_stream
.content_length
= request
->contentLength
;
2938 request
->netconn_stream
.content_read
= request
->read_size
;
2940 size
= sizeof(encoding
);
2941 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2942 !strcmpiW(encoding
, szChunked
))
2944 chunked_stream_t
*chunked_stream
;
2946 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2948 return ERROR_OUTOFMEMORY
;
2950 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2951 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2952 chunked_stream
->chunk_size
= ~0u;
2953 chunked_stream
->end_of_data
= FALSE
;
2955 if(request
->read_size
) {
2956 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2957 chunked_stream
->buf_size
= request
->read_size
;
2958 request
->read_size
= request
->read_pos
= 0;
2961 request
->data_stream
= &chunked_stream
->data_stream
;
2962 request
->contentLength
= ~0u;
2965 if(request
->decoding
) {
2968 static const WCHAR deflateW
[] = {'d','e','f','l','a','t','e',0};
2969 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2971 EnterCriticalSection( &request
->headers_section
);
2973 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2974 if(encoding_idx
!= -1) {
2975 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2976 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2977 LeaveCriticalSection( &request
->headers_section
);
2978 return init_gzip_stream(request
, TRUE
);
2980 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, deflateW
)) {
2981 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2982 LeaveCriticalSection( &request
->headers_section
);
2983 return init_gzip_stream(request
, FALSE
);
2987 LeaveCriticalSection( &request
->headers_section
);
2990 return ERROR_SUCCESS
;
2993 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
2995 INTERNET_ASYNC_RESULT iar
;
2997 iar
.dwResult
= result
;
2998 iar
.dwError
= error
;
3000 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
3001 sizeof(INTERNET_ASYNC_RESULT
));
3004 static void HTTP_ReceiveRequestData(http_request_t
*req
, BOOL first_notif
, DWORD
*ret_size
)
3006 DWORD res
, read
= 0, avail
= 0;
3007 blocking_mode_t mode
;
3011 EnterCriticalSection( &req
->read_section
);
3013 mode
= first_notif
&& req
->read_size
? BLOCKING_DISALLOW
: BLOCKING_ALLOW
;
3014 res
= refill_read_buffer(req
, mode
, &read
);
3015 if(res
== ERROR_SUCCESS
)
3016 avail
= get_avail_data(req
);
3018 LeaveCriticalSection( &req
->read_section
);
3020 if(res
!= ERROR_SUCCESS
|| (mode
!= BLOCKING_DISALLOW
&& !read
)) {
3021 WARN("res %u read %u, closing connection\n", res
, read
);
3022 http_release_netconn(req
, FALSE
);
3025 if(res
!= ERROR_SUCCESS
) {
3026 send_request_complete(req
, 0, res
);
3035 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, avail
);
3038 /* read data from the http connection (the read section must be held) */
3039 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
, BOOL sync
)
3041 DWORD current_read
= 0, ret_read
= 0;
3042 blocking_mode_t blocking_mode
;
3043 DWORD res
= ERROR_SUCCESS
;
3045 blocking_mode
= req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
? BLOCKING_ALLOW
: BLOCKING_WAITALL
;
3047 EnterCriticalSection( &req
->read_section
);
3049 if(req
->read_size
) {
3050 ret_read
= min(size
, req
->read_size
);
3051 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
3052 req
->read_size
-= ret_read
;
3053 req
->read_pos
+= ret_read
;
3054 if(blocking_mode
== BLOCKING_ALLOW
)
3055 blocking_mode
= BLOCKING_DISALLOW
;
3058 if(ret_read
< size
) {
3059 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, blocking_mode
);
3060 ret_read
+= current_read
;
3063 LeaveCriticalSection( &req
->read_section
);
3066 TRACE( "retrieved %u bytes (%u)\n", ret_read
, req
->contentLength
);
3068 if(size
&& !ret_read
)
3069 http_release_netconn(req
, res
== ERROR_SUCCESS
);
3074 static BOOL
drain_content(http_request_t
*req
, BOOL blocking
)
3078 if(!is_valid_netconn(req
->netconn
) || req
->contentLength
== -1)
3081 if(!strcmpW(req
->verb
, szHEAD
))
3085 return req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
);
3087 EnterCriticalSection( &req
->read_section
);
3090 DWORD bytes_read
, res
;
3093 res
= HTTPREQ_Read(req
, buf
, sizeof(buf
), &bytes_read
, TRUE
);
3094 if(res
!= ERROR_SUCCESS
) {
3104 LeaveCriticalSection( &req
->read_section
);
3108 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buffer
, DWORD size
, DWORD
*read
)
3110 http_request_t
*req
= (http_request_t
*)hdr
;
3113 EnterCriticalSection( &req
->read_section
);
3114 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3115 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3117 res
= HTTPREQ_Read(req
, buffer
, size
, read
, TRUE
);
3118 if(res
== ERROR_SUCCESS
)
3120 LeaveCriticalSection( &req
->read_section
);
3130 } read_file_ex_task_t
;
3132 static void AsyncReadFileExProc(task_header_t
*hdr
)
3134 read_file_ex_task_t
*task
= (read_file_ex_task_t
*)hdr
;
3135 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3138 TRACE("INTERNETREADFILEEXW %p\n", task
->hdr
.hdr
);
3140 res
= HTTPREQ_Read(req
, task
->buf
, task
->size
, task
->ret_read
, TRUE
);
3141 send_request_complete(req
, res
== ERROR_SUCCESS
, res
);
3144 static DWORD
HTTPREQ_ReadFileEx(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3145 DWORD flags
, DWORD_PTR context
)
3148 http_request_t
*req
= (http_request_t
*)hdr
;
3149 DWORD res
, read
, cread
, error
= ERROR_SUCCESS
;
3151 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3152 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3154 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3156 if (hdr
->dwFlags
& INTERNET_FLAG_ASYNC
)
3158 read_file_ex_task_t
*task
;
3160 if (TryEnterCriticalSection( &req
->read_section
))
3162 if (get_avail_data(req
))
3164 res
= HTTPREQ_Read(req
, buf
, size
, &read
, FALSE
);
3165 LeaveCriticalSection( &req
->read_section
);
3168 LeaveCriticalSection( &req
->read_section
);
3171 task
= alloc_async_task(&req
->hdr
, AsyncReadFileExProc
, sizeof(*task
));
3174 task
->ret_read
= ret_read
;
3176 INTERNET_AsyncCall(&task
->hdr
);
3178 return ERROR_IO_PENDING
;
3183 EnterCriticalSection( &req
->read_section
);
3184 if(hdr
->dwError
== ERROR_SUCCESS
)
3185 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3186 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3187 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3190 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
, !(flags
& IRF_NO_WAIT
));
3191 if(res
!= ERROR_SUCCESS
)
3195 if(read
== size
|| end_of_read_data(req
))
3198 LeaveCriticalSection( &req
->read_section
);
3200 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3201 &cread
, sizeof(cread
));
3202 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
3203 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3205 EnterCriticalSection( &req
->read_section
);
3208 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3209 hdr
->dwError
= ERROR_SUCCESS
;
3211 error
= hdr
->dwError
;
3213 LeaveCriticalSection( &req
->read_section
);
3217 if (res
== ERROR_SUCCESS
) {
3218 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3219 &read
, sizeof(read
));
3222 return res
==ERROR_SUCCESS
? error
: res
;
3225 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3228 http_request_t
*request
= (http_request_t
*)hdr
;
3230 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3233 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3234 if (res
== ERROR_SUCCESS
)
3235 request
->bytesWritten
+= *written
;
3237 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3244 } http_data_available_task_t
;
3246 static void AsyncQueryDataAvailableProc(task_header_t
*hdr
)
3248 http_data_available_task_t
*task
= (http_data_available_task_t
*)hdr
;
3250 HTTP_ReceiveRequestData((http_request_t
*)task
->hdr
.hdr
, FALSE
, task
->ret_size
);
3253 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3255 http_request_t
*req
= (http_request_t
*)hdr
;
3257 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3259 if (req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
3261 http_data_available_task_t
*task
;
3263 /* never wait, if we can't enter the section we queue an async request right away */
3264 if (TryEnterCriticalSection( &req
->read_section
))
3266 refill_read_buffer(req
, BLOCKING_DISALLOW
, NULL
);
3267 if ((*available
= get_avail_data( req
))) goto done
;
3268 if (end_of_read_data( req
)) goto done
;
3269 LeaveCriticalSection( &req
->read_section
);
3272 task
= alloc_async_task(&req
->hdr
, AsyncQueryDataAvailableProc
, sizeof(*task
));
3273 task
->ret_size
= available
;
3274 INTERNET_AsyncCall(&task
->hdr
);
3275 return ERROR_IO_PENDING
;
3278 EnterCriticalSection( &req
->read_section
);
3280 if (!(*available
= get_avail_data( req
)) && !end_of_read_data( req
))
3282 refill_read_buffer( req
, BLOCKING_ALLOW
, NULL
);
3283 *available
= get_avail_data( req
);
3287 LeaveCriticalSection( &req
->read_section
);
3289 TRACE( "returning %u\n", *available
);
3290 return ERROR_SUCCESS
;
3293 static DWORD
HTTPREQ_LockRequestFile(object_header_t
*hdr
, req_file_t
**ret
)
3295 http_request_t
*req
= (http_request_t
*)hdr
;
3297 TRACE("(%p)\n", req
);
3299 if(!req
->req_file
) {
3300 WARN("No cache file name available\n");
3301 return ERROR_FILE_NOT_FOUND
;
3304 *ret
= req_file_addref(req
->req_file
);
3305 return ERROR_SUCCESS
;
3308 static const object_vtbl_t HTTPREQVtbl
= {
3310 HTTPREQ_CloseConnection
,
3311 HTTPREQ_QueryOption
,
3316 HTTPREQ_QueryDataAvailable
,
3318 HTTPREQ_LockRequestFile
3321 /***********************************************************************
3322 * HTTP_HttpOpenRequestW (internal)
3324 * Open a HTTP request handle
3327 * HINTERNET a HTTP request handle on success
3331 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3332 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3333 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3334 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3336 appinfo_t
*hIC
= session
->appInfo
;
3337 http_request_t
*request
;
3342 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3344 return ERROR_OUTOFMEMORY
;
3346 request
->hdr
.htype
= WH_HHTTPREQ
;
3347 request
->hdr
.dwFlags
= dwFlags
;
3348 request
->hdr
.dwContext
= dwContext
;
3349 request
->contentLength
= ~0u;
3351 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3352 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3353 request
->connect_timeout
= session
->connect_timeout
;
3354 request
->send_timeout
= session
->send_timeout
;
3355 request
->receive_timeout
= session
->receive_timeout
;
3357 InitializeCriticalSection( &request
->headers_section
);
3358 request
->headers_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.headers_section");
3360 InitializeCriticalSection( &request
->read_section
);
3361 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3363 WININET_AddRef( &session
->hdr
);
3364 request
->session
= session
;
3365 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3367 request
->server
= get_server(session
->hostName
, session
->hostPort
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3368 if(!request
->server
) {
3369 WININET_Release(&request
->hdr
);
3370 return ERROR_OUTOFMEMORY
;
3373 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3374 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3375 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3376 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3378 if (lpszObjectName
&& *lpszObjectName
) {
3382 rc
= UrlEscapeW(lpszObjectName
, NULL
, &len
, URL_ESCAPE_SPACES_ONLY
);
3383 if (rc
!= E_POINTER
)
3384 len
= strlenW(lpszObjectName
)+1;
3385 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3386 rc
= UrlEscapeW(lpszObjectName
, request
->path
, &len
,
3387 URL_ESCAPE_SPACES_ONLY
);
3390 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3391 strcpyW(request
->path
,lpszObjectName
);
3394 static const WCHAR slashW
[] = {'/',0};
3396 request
->path
= heap_strdupW(slashW
);
3399 if (lpszReferrer
&& *lpszReferrer
)
3400 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3402 if (lpszAcceptTypes
)
3405 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3407 if (!*lpszAcceptTypes
[i
]) continue;
3408 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3409 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3410 HTTP_ADDHDR_FLAG_REQ
|
3411 (i
== 0 ? (HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
) : 0));
3415 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3416 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3418 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3419 HTTP_DealWithProxy( hIC
, session
, request
);
3421 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3422 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3425 TRACE("<-- (%p)\n", request
);
3427 *ret
= request
->hdr
.hInternet
;
3428 return ERROR_SUCCESS
;
3431 /***********************************************************************
3432 * HttpOpenRequestW (WININET.@)
3434 * Open a HTTP request handle
3437 * HINTERNET a HTTP request handle on success
3441 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3442 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3443 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3444 DWORD dwFlags
, DWORD_PTR dwContext
)
3446 http_session_t
*session
;
3447 HINTERNET handle
= NULL
;
3450 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3451 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3452 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3453 dwFlags
, dwContext
);
3454 if(lpszAcceptTypes
!=NULL
)
3457 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3458 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3461 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3462 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3464 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3469 * My tests seem to show that the windows version does not
3470 * become asynchronous until after this point. And anyhow
3471 * if this call was asynchronous then how would you get the
3472 * necessary HINTERNET pointer returned by this function.
3475 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3476 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3477 dwFlags
, dwContext
, &handle
);
3480 WININET_Release( &session
->hdr
);
3481 TRACE("returning %p\n", handle
);
3482 if(res
!= ERROR_SUCCESS
)
3487 static const LPCWSTR header_lookup
[] = {
3488 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3489 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3490 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3491 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3492 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3493 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3494 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3495 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3496 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3497 szDate
, /* HTTP_QUERY_DATE = 9 */
3498 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3499 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3500 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3501 szURI
, /* HTTP_QUERY_URI = 13 */
3502 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3503 NULL
, /* HTTP_QUERY_COST = 15 */
3504 NULL
, /* HTTP_QUERY_LINK = 16 */
3505 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3506 NULL
, /* HTTP_QUERY_VERSION = 18 */
3507 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3508 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3509 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3510 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3511 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3512 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3513 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3514 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3515 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3516 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3517 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3518 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3519 NULL
, /* HTTP_QUERY_FROM = 31 */
3520 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3521 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3522 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3523 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3524 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3525 szServer
, /* HTTP_QUERY_SERVER = 37 */
3526 NULL
, /* HTTP_TITLE = 38 */
3527 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3528 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3529 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3530 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3531 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3532 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3533 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3534 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3535 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3536 szAge
, /* HTTP_QUERY_AGE = 48 */
3537 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3538 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3539 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3540 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3541 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3542 szETag
, /* HTTP_QUERY_ETAG = 54 */
3543 hostW
, /* HTTP_QUERY_HOST = 55 */
3544 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3545 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3546 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3547 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3548 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3549 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3550 szRange
, /* HTTP_QUERY_RANGE = 62 */
3551 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3552 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3553 szVary
, /* HTTP_QUERY_VARY = 65 */
3554 szVia
, /* HTTP_QUERY_VIA = 66 */
3555 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3556 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3557 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3558 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3561 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3563 /***********************************************************************
3564 * HTTP_HttpQueryInfoW (internal)
3566 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3567 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3569 LPHTTPHEADERW lphttpHdr
= NULL
;
3570 BOOL request_only
= !!(dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
);
3571 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3572 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3575 EnterCriticalSection( &request
->headers_section
);
3577 /* Find requested header structure */
3580 case HTTP_QUERY_CUSTOM
:
3583 LeaveCriticalSection( &request
->headers_section
);
3584 return ERROR_INVALID_PARAMETER
;
3586 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3588 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3592 DWORD res
= ERROR_INVALID_PARAMETER
;
3595 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3597 headers
= build_response_header(request
, TRUE
);
3600 LeaveCriticalSection( &request
->headers_section
);
3601 return ERROR_OUTOFMEMORY
;
3604 len
= strlenW(headers
) * sizeof(WCHAR
);
3605 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3607 len
+= sizeof(WCHAR
);
3608 res
= ERROR_INSUFFICIENT_BUFFER
;
3612 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3613 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3614 res
= ERROR_SUCCESS
;
3616 *lpdwBufferLength
= len
;
3619 LeaveCriticalSection( &request
->headers_section
);
3622 case HTTP_QUERY_RAW_HEADERS
:
3628 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3630 headers
= build_response_header(request
, FALSE
);
3634 LeaveCriticalSection( &request
->headers_section
);
3635 return ERROR_OUTOFMEMORY
;
3638 len
= strlenW(headers
) * sizeof(WCHAR
);
3639 if (len
> *lpdwBufferLength
)
3641 *lpdwBufferLength
= len
;
3643 LeaveCriticalSection( &request
->headers_section
);
3644 return ERROR_INSUFFICIENT_BUFFER
;
3651 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3653 for (i
= 0; i
< len
/ sizeof(WCHAR
); i
++)
3655 if (headers
[i
] == '\n')
3658 memcpy(lpBuffer
, headers
, len
);
3660 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3663 LeaveCriticalSection( &request
->headers_section
);
3664 return ERROR_SUCCESS
;
3666 case HTTP_QUERY_STATUS_TEXT
:
3667 if (request
->statusText
)
3669 DWORD len
= strlenW(request
->statusText
);
3670 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3672 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3673 LeaveCriticalSection( &request
->headers_section
);
3674 return ERROR_INSUFFICIENT_BUFFER
;
3678 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3679 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3681 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3682 LeaveCriticalSection( &request
->headers_section
);
3683 return ERROR_SUCCESS
;
3686 case HTTP_QUERY_VERSION
:
3687 if (request
->version
)
3689 DWORD len
= strlenW(request
->version
);
3690 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3692 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3693 LeaveCriticalSection( &request
->headers_section
);
3694 return ERROR_INSUFFICIENT_BUFFER
;
3698 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3699 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3701 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3702 LeaveCriticalSection( &request
->headers_section
);
3703 return ERROR_SUCCESS
;
3706 case HTTP_QUERY_CONTENT_ENCODING
:
3707 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3708 requested_index
,request_only
);
3710 case HTTP_QUERY_STATUS_CODE
: {
3711 DWORD res
= ERROR_SUCCESS
;
3715 LeaveCriticalSection( &request
->headers_section
);
3716 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3722 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3723 if(*lpdwBufferLength
>= sizeof(DWORD
))
3724 *(DWORD
*)lpBuffer
= request
->status_code
;
3726 res
= ERROR_INSUFFICIENT_BUFFER
;
3727 *lpdwBufferLength
= sizeof(DWORD
);
3731 static const WCHAR formatW
[] = {'%','u',0};
3733 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3735 if(size
<= *lpdwBufferLength
) {
3736 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3738 size
+= sizeof(WCHAR
);
3739 res
= ERROR_INSUFFICIENT_BUFFER
;
3742 *lpdwBufferLength
= size
;
3744 LeaveCriticalSection( &request
->headers_section
);
3748 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3750 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3751 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3752 requested_index
,request_only
);
3756 lphttpHdr
= &request
->custHeaders
[index
];
3758 /* Ensure header satisfies requested attributes */
3760 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3761 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3763 LeaveCriticalSection( &request
->headers_section
);
3764 return ERROR_HTTP_HEADER_NOT_FOUND
;
3767 /* coalesce value to requested type */
3768 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3770 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3771 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3773 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3779 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3781 tmpTM
= *gmtime(&tmpTime
);
3782 STHook
= (SYSTEMTIME
*)lpBuffer
;
3783 STHook
->wDay
= tmpTM
.tm_mday
;
3784 STHook
->wHour
= tmpTM
.tm_hour
;
3785 STHook
->wMilliseconds
= 0;
3786 STHook
->wMinute
= tmpTM
.tm_min
;
3787 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3788 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3789 STHook
->wSecond
= tmpTM
.tm_sec
;
3790 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3792 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3793 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3794 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3796 else if (lphttpHdr
->lpszValue
)
3798 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3800 if (len
> *lpdwBufferLength
)
3802 *lpdwBufferLength
= len
;
3803 LeaveCriticalSection( &request
->headers_section
);
3804 return ERROR_INSUFFICIENT_BUFFER
;
3808 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3809 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3811 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3813 if (lpdwIndex
) (*lpdwIndex
)++;
3815 LeaveCriticalSection( &request
->headers_section
);
3816 return ERROR_SUCCESS
;
3819 /***********************************************************************
3820 * HttpQueryInfoW (WININET.@)
3822 * Queries for information about an HTTP request
3829 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3830 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3832 http_request_t
*request
;
3835 if (TRACE_ON(wininet
)) {
3836 #define FE(x) { x, #x }
3837 static const wininet_flag_info query_flags
[] = {
3838 FE(HTTP_QUERY_MIME_VERSION
),
3839 FE(HTTP_QUERY_CONTENT_TYPE
),
3840 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3841 FE(HTTP_QUERY_CONTENT_ID
),
3842 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3843 FE(HTTP_QUERY_CONTENT_LENGTH
),
3844 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3845 FE(HTTP_QUERY_ALLOW
),
3846 FE(HTTP_QUERY_PUBLIC
),
3847 FE(HTTP_QUERY_DATE
),
3848 FE(HTTP_QUERY_EXPIRES
),
3849 FE(HTTP_QUERY_LAST_MODIFIED
),
3850 FE(HTTP_QUERY_MESSAGE_ID
),
3852 FE(HTTP_QUERY_DERIVED_FROM
),
3853 FE(HTTP_QUERY_COST
),
3854 FE(HTTP_QUERY_LINK
),
3855 FE(HTTP_QUERY_PRAGMA
),
3856 FE(HTTP_QUERY_VERSION
),
3857 FE(HTTP_QUERY_STATUS_CODE
),
3858 FE(HTTP_QUERY_STATUS_TEXT
),
3859 FE(HTTP_QUERY_RAW_HEADERS
),
3860 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3861 FE(HTTP_QUERY_CONNECTION
),
3862 FE(HTTP_QUERY_ACCEPT
),
3863 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3864 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3865 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3866 FE(HTTP_QUERY_AUTHORIZATION
),
3867 FE(HTTP_QUERY_CONTENT_ENCODING
),
3868 FE(HTTP_QUERY_FORWARDED
),
3869 FE(HTTP_QUERY_FROM
),
3870 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3871 FE(HTTP_QUERY_LOCATION
),
3872 FE(HTTP_QUERY_ORIG_URI
),
3873 FE(HTTP_QUERY_REFERER
),
3874 FE(HTTP_QUERY_RETRY_AFTER
),
3875 FE(HTTP_QUERY_SERVER
),
3876 FE(HTTP_QUERY_TITLE
),
3877 FE(HTTP_QUERY_USER_AGENT
),
3878 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3879 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3880 FE(HTTP_QUERY_ACCEPT_RANGES
),
3881 FE(HTTP_QUERY_SET_COOKIE
),
3882 FE(HTTP_QUERY_COOKIE
),
3883 FE(HTTP_QUERY_REQUEST_METHOD
),
3884 FE(HTTP_QUERY_REFRESH
),
3885 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3887 FE(HTTP_QUERY_CACHE_CONTROL
),
3888 FE(HTTP_QUERY_CONTENT_BASE
),
3889 FE(HTTP_QUERY_CONTENT_LOCATION
),
3890 FE(HTTP_QUERY_CONTENT_MD5
),
3891 FE(HTTP_QUERY_CONTENT_RANGE
),
3892 FE(HTTP_QUERY_ETAG
),
3893 FE(HTTP_QUERY_HOST
),
3894 FE(HTTP_QUERY_IF_MATCH
),
3895 FE(HTTP_QUERY_IF_NONE_MATCH
),
3896 FE(HTTP_QUERY_IF_RANGE
),
3897 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3898 FE(HTTP_QUERY_MAX_FORWARDS
),
3899 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3900 FE(HTTP_QUERY_RANGE
),
3901 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3902 FE(HTTP_QUERY_UPGRADE
),
3903 FE(HTTP_QUERY_VARY
),
3905 FE(HTTP_QUERY_WARNING
),
3906 FE(HTTP_QUERY_CUSTOM
)
3908 static const wininet_flag_info modifier_flags
[] = {
3909 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3910 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3911 FE(HTTP_QUERY_FLAG_NUMBER
),
3912 FE(HTTP_QUERY_FLAG_COALESCE
)
3915 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3916 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3919 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3920 TRACE(" Attribute:");
3921 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3922 if (query_flags
[i
].val
== info
) {
3923 TRACE(" %s", query_flags
[i
].name
);
3927 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3928 TRACE(" Unknown (%08x)", info
);
3931 TRACE(" Modifier:");
3932 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3933 if (modifier_flags
[i
].val
& info_mod
) {
3934 TRACE(" %s", modifier_flags
[i
].name
);
3935 info_mod
&= ~ modifier_flags
[i
].val
;
3940 TRACE(" Unknown (%08x)", info_mod
);
3945 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3946 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3948 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3952 if (lpBuffer
== NULL
)
3953 *lpdwBufferLength
= 0;
3954 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3955 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3959 WININET_Release( &request
->hdr
);
3961 TRACE("%u <--\n", res
);
3962 if(res
!= ERROR_SUCCESS
)
3964 return res
== ERROR_SUCCESS
;
3967 /***********************************************************************
3968 * HttpQueryInfoA (WININET.@)
3970 * Queries for information about an HTTP request
3977 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3978 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3984 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
3986 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3987 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3989 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3990 lpdwBufferLength
, lpdwIndex
);
3996 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
3997 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3999 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
4005 bufferW
= heap_alloc(alloclen
);
4006 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
4007 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
4008 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
4015 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
4019 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
4020 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
4021 *lpdwBufferLength
= len
- 1;
4023 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
4026 /* since the strings being returned from HttpQueryInfoW should be
4027 * only ASCII characters, it is reasonable to assume that all of
4028 * the Unicode characters can be reduced to a single byte */
4029 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
4031 heap_free( bufferW
);
4035 /***********************************************************************
4036 * HTTP_GetRedirectURL (internal)
4038 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*request
, LPCWSTR lpszUrl
)
4040 static WCHAR szHttp
[] = {'h','t','t','p',0};
4041 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
4042 http_session_t
*session
= request
->session
;
4043 URL_COMPONENTSW urlComponents
;
4044 DWORD url_length
= 0;
4046 LPWSTR combined_url
;
4048 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
4049 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
4050 urlComponents
.dwSchemeLength
= 0;
4051 urlComponents
.lpszHostName
= request
->server
->name
;
4052 urlComponents
.dwHostNameLength
= 0;
4053 urlComponents
.nPort
= request
->server
->port
;
4054 urlComponents
.lpszUserName
= session
->userName
;
4055 urlComponents
.dwUserNameLength
= 0;
4056 urlComponents
.lpszPassword
= NULL
;
4057 urlComponents
.dwPasswordLength
= 0;
4058 urlComponents
.lpszUrlPath
= request
->path
;
4059 urlComponents
.dwUrlPathLength
= 0;
4060 urlComponents
.lpszExtraInfo
= NULL
;
4061 urlComponents
.dwExtraInfoLength
= 0;
4063 if (!InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
) &&
4064 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
4067 orig_url
= heap_alloc(url_length
);
4069 /* convert from bytes to characters */
4070 url_length
= url_length
/ sizeof(WCHAR
) - 1;
4071 if (!InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
))
4073 heap_free(orig_url
);
4078 if (!InternetCombineUrlW(orig_url
, lpszUrl
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
) &&
4079 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
4081 heap_free(orig_url
);
4084 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
4086 if (!InternetCombineUrlW(orig_url
, lpszUrl
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
))
4088 heap_free(orig_url
);
4089 heap_free(combined_url
);
4092 heap_free(orig_url
);
4093 return combined_url
;
4097 /***********************************************************************
4098 * HTTP_HandleRedirect (internal)
4100 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, LPCWSTR lpszUrl
)
4102 http_session_t
*session
= request
->session
;
4103 WCHAR path
[INTERNET_MAX_PATH_LENGTH
];
4107 /* if it's an absolute path, keep the same session info */
4108 lstrcpynW(path
, lpszUrl
, INTERNET_MAX_URL_LENGTH
);
4112 URL_COMPONENTSW urlComponents
;
4113 WCHAR protocol
[INTERNET_MAX_SCHEME_LENGTH
];
4114 WCHAR hostName
[INTERNET_MAX_HOST_NAME_LENGTH
];
4115 WCHAR userName
[INTERNET_MAX_USER_NAME_LENGTH
];
4116 BOOL custom_port
= FALSE
;
4118 static const WCHAR httpW
[] = {'h','t','t','p',0};
4119 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
4125 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
4126 urlComponents
.lpszScheme
= protocol
;
4127 urlComponents
.dwSchemeLength
= INTERNET_MAX_SCHEME_LENGTH
;
4128 urlComponents
.lpszHostName
= hostName
;
4129 urlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
4130 urlComponents
.lpszUserName
= userName
;
4131 urlComponents
.dwUserNameLength
= INTERNET_MAX_USER_NAME_LENGTH
;
4132 urlComponents
.lpszPassword
= NULL
;
4133 urlComponents
.dwPasswordLength
= 0;
4134 urlComponents
.lpszUrlPath
= path
;
4135 urlComponents
.dwUrlPathLength
= INTERNET_MAX_PATH_LENGTH
;
4136 urlComponents
.lpszExtraInfo
= NULL
;
4137 urlComponents
.dwExtraInfoLength
= 0;
4138 if(!InternetCrackUrlW(lpszUrl
, strlenW(lpszUrl
), 0, &urlComponents
))
4139 return INTERNET_GetLastError();
4141 if(!strcmpiW(protocol
, httpW
)) {
4142 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4143 TRACE("redirect from secure page to non-secure page\n");
4144 /* FIXME: warn about from secure redirect to non-secure page */
4145 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4148 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4149 urlComponents
.nPort
= INTERNET_DEFAULT_HTTP_PORT
;
4150 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
)
4152 }else if(!strcmpiW(protocol
, httpsW
)) {
4153 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4154 TRACE("redirect from non-secure page to secure page\n");
4155 /* FIXME: notify about redirect to secure page */
4156 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4159 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4160 urlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
4161 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
)
4165 heap_free(session
->hostName
);
4167 session
->hostName
= heap_strdupW(hostName
);
4168 session
->hostPort
= urlComponents
.nPort
;
4170 heap_free(session
->userName
);
4171 session
->userName
= NULL
;
4173 session
->userName
= heap_strdupW(userName
);
4175 reset_data_stream(request
);
4177 if(strcmpiW(request
->server
->name
, hostName
) || request
->server
->port
!= urlComponents
.nPort
) {
4178 server_t
*new_server
;
4180 new_server
= get_server(hostName
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4181 server_release(request
->server
);
4182 request
->server
= new_server
;
4186 HTTP_ProcessHeader(request
, hostW
, request
->server
->host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4188 HTTP_ProcessHeader(request
, hostW
, request
->server
->name
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4190 heap_free(request
->path
);
4197 rc
= UrlEscapeW(path
, NULL
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4198 if (rc
!= E_POINTER
)
4199 needed
= strlenW(path
)+1;
4200 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4201 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4202 URL_ESCAPE_SPACES_ONLY
);
4205 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4206 strcpyW(request
->path
,path
);
4210 /* Remove custom content-type/length headers on redirects. */
4211 remove_header(request
, szContent_Type
, TRUE
);
4212 remove_header(request
, szContent_Length
, TRUE
);
4214 return ERROR_SUCCESS
;
4217 /***********************************************************************
4218 * HTTP_build_req (internal)
4220 * concatenate all the strings in the request together
4222 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4227 for( t
= list
; *t
; t
++ )
4228 len
+= strlenW( *t
);
4231 str
= heap_alloc(len
*sizeof(WCHAR
));
4234 for( t
= list
; *t
; t
++ )
4240 static void HTTP_InsertCookies(http_request_t
*request
)
4245 res
= get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4246 if(res
!= ERROR_SUCCESS
|| !cookies
)
4249 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
),
4250 HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
4254 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4256 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4264 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4265 if (!strcmpiW(day
, days
[i
]))
4272 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4274 static const WCHAR jan
[] = { 'j','a','n',0 };
4275 static const WCHAR feb
[] = { 'f','e','b',0 };
4276 static const WCHAR mar
[] = { 'm','a','r',0 };
4277 static const WCHAR apr
[] = { 'a','p','r',0 };
4278 static const WCHAR may
[] = { 'm','a','y',0 };
4279 static const WCHAR jun
[] = { 'j','u','n',0 };
4280 static const WCHAR jul
[] = { 'j','u','l',0 };
4281 static const WCHAR aug
[] = { 'a','u','g',0 };
4282 static const WCHAR sep
[] = { 's','e','p',0 };
4283 static const WCHAR oct
[] = { 'o','c','t',0 };
4284 static const WCHAR nov
[] = { 'n','o','v',0 };
4285 static const WCHAR dec
[] = { 'd','e','c',0 };
4287 if (!strcmpiW(month
, jan
)) return 1;
4288 if (!strcmpiW(month
, feb
)) return 2;
4289 if (!strcmpiW(month
, mar
)) return 3;
4290 if (!strcmpiW(month
, apr
)) return 4;
4291 if (!strcmpiW(month
, may
)) return 5;
4292 if (!strcmpiW(month
, jun
)) return 6;
4293 if (!strcmpiW(month
, jul
)) return 7;
4294 if (!strcmpiW(month
, aug
)) return 8;
4295 if (!strcmpiW(month
, sep
)) return 9;
4296 if (!strcmpiW(month
, oct
)) return 10;
4297 if (!strcmpiW(month
, nov
)) return 11;
4298 if (!strcmpiW(month
, dec
)) return 12;
4303 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4304 * optionally preceded by whitespace.
4305 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4306 * st, and sets *str to the first character after the time format.
4308 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4314 while (isspaceW(*ptr
))
4317 num
= strtoulW(ptr
, &nextPtr
, 10);
4318 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4320 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4325 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4329 st
->wHour
= (WORD
)num
;
4330 num
= strtoulW(ptr
, &nextPtr
, 10);
4331 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4333 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4338 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4342 st
->wMinute
= (WORD
)num
;
4343 num
= strtoulW(ptr
, &nextPtr
, 10);
4344 if (!nextPtr
|| nextPtr
<= ptr
)
4346 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4351 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4356 st
->wSecond
= (WORD
)num
;
4360 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4362 static const WCHAR gmt
[]= { 'G','M','T',0 };
4363 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4365 SYSTEMTIME st
= { 0 };
4368 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4369 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4372 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4373 if (st
.wDayOfWeek
>= 7)
4375 ERR("unexpected weekday %s\n", debugstr_w(day
));
4379 while (isspaceW(*ptr
))
4382 for (monthPtr
= month
; !isspace(*ptr
) &&
4383 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4387 st
.wMonth
= HTTP_ParseMonth(month
);
4388 if (!st
.wMonth
|| st
.wMonth
> 12)
4390 ERR("unexpected month %s\n", debugstr_w(month
));
4394 while (isspaceW(*ptr
))
4397 num
= strtoulW(ptr
, &nextPtr
, 10);
4398 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4400 ERR("unexpected day %s\n", debugstr_w(ptr
));
4404 st
.wDay
= (WORD
)num
;
4406 while (isspaceW(*ptr
))
4409 if (!HTTP_ParseTime(&st
, &ptr
))
4412 while (isspaceW(*ptr
))
4415 num
= strtoulW(ptr
, &nextPtr
, 10);
4416 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4418 ERR("unexpected year %s\n", debugstr_w(ptr
));
4422 st
.wYear
= (WORD
)num
;
4424 while (isspaceW(*ptr
))
4427 /* asctime() doesn't report a timezone, but some web servers do, so accept
4428 * with or without GMT.
4430 if (*ptr
&& strcmpW(ptr
, gmt
))
4432 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4435 return SystemTimeToFileTime(&st
, ft
);
4438 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4440 static const WCHAR gmt
[]= { 'G','M','T',0 };
4441 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4444 SYSTEMTIME st
= { 0 };
4446 ptr
= strchrW(value
, ',');
4449 if (ptr
- value
!= 3)
4451 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4454 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4456 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4457 if (st
.wDayOfWeek
> 6)
4459 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4464 while (isspaceW(*ptr
))
4467 num
= strtoulW(ptr
, &nextPtr
, 10);
4468 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4470 WARN("unexpected day %s\n", debugstr_w(value
));
4474 st
.wDay
= (WORD
)num
;
4476 while (isspaceW(*ptr
))
4479 for (monthPtr
= month
; !isspace(*ptr
) &&
4480 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4484 st
.wMonth
= HTTP_ParseMonth(month
);
4485 if (!st
.wMonth
|| st
.wMonth
> 12)
4487 WARN("unexpected month %s\n", debugstr_w(month
));
4491 while (isspaceW(*ptr
))
4494 num
= strtoulW(ptr
, &nextPtr
, 10);
4495 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4497 ERR("unexpected year %s\n", debugstr_w(value
));
4501 st
.wYear
= (WORD
)num
;
4503 if (!HTTP_ParseTime(&st
, &ptr
))
4506 while (isspaceW(*ptr
))
4509 if (strcmpW(ptr
, gmt
))
4511 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4514 return SystemTimeToFileTime(&st
, ft
);
4517 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4519 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4520 { 'm','o','n','d','a','y',0 },
4521 { 't','u','e','s','d','a','y',0 },
4522 { 'w','e','d','n','e','s','d','a','y',0 },
4523 { 't','h','u','r','s','d','a','y',0 },
4524 { 'f','r','i','d','a','y',0 },
4525 { 's','a','t','u','r','d','a','y',0 }};
4527 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4528 if (!strcmpiW(day
, days
[i
]))
4535 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4537 static const WCHAR gmt
[]= { 'G','M','T',0 };
4538 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4541 SYSTEMTIME st
= { 0 };
4543 ptr
= strchrW(value
, ',');
4546 if (ptr
- value
== 3)
4548 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4550 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4551 if (st
.wDayOfWeek
> 6)
4553 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4557 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4559 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4560 day
[ptr
- value
+ 1] = 0;
4561 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4562 if (st
.wDayOfWeek
> 6)
4564 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4570 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4575 while (isspaceW(*ptr
))
4578 num
= strtoulW(ptr
, &nextPtr
, 10);
4579 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4581 ERR("unexpected day %s\n", debugstr_w(value
));
4585 st
.wDay
= (WORD
)num
;
4589 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4594 for (monthPtr
= month
; *ptr
!= '-' &&
4595 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4599 st
.wMonth
= HTTP_ParseMonth(month
);
4600 if (!st
.wMonth
|| st
.wMonth
> 12)
4602 ERR("unexpected month %s\n", debugstr_w(month
));
4608 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4613 num
= strtoulW(ptr
, &nextPtr
, 10);
4614 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4616 ERR("unexpected year %s\n", debugstr_w(value
));
4620 st
.wYear
= (WORD
)num
;
4622 if (!HTTP_ParseTime(&st
, &ptr
))
4625 while (isspaceW(*ptr
))
4628 if (strcmpW(ptr
, gmt
))
4630 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4633 return SystemTimeToFileTime(&st
, ft
);
4636 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4638 static const WCHAR zero
[] = { '0',0 };
4641 if (!strcmpW(value
, zero
))
4643 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4646 else if (strchrW(value
, ','))
4648 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4651 ret
= HTTP_ParseRfc850Date(value
, ft
);
4653 ERR("unexpected date format %s\n", debugstr_w(value
));
4658 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4660 ERR("unexpected date format %s\n", debugstr_w(value
));
4665 static void HTTP_ProcessExpires(http_request_t
*request
)
4667 BOOL expirationFound
= FALSE
;
4670 EnterCriticalSection( &request
->headers_section
);
4672 /* Look for a Cache-Control header with a max-age directive, as it takes
4673 * precedence over the Expires header.
4675 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4676 if (headerIndex
!= -1)
4678 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4681 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4683 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4688 end
= ptr
+ strlenW(ptr
);
4689 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4693 static const WCHAR max_age
[] = {
4694 'm','a','x','-','a','g','e',0 };
4696 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4701 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4702 if (nextPtr
> equal
+ 1)
4706 NtQuerySystemTime( &ft
);
4707 /* Age is in seconds, FILETIME resolution is in
4708 * 100 nanosecond intervals.
4710 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4711 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4712 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4713 expirationFound
= TRUE
;
4720 while (isspaceW(*ptr
))
4727 if (!expirationFound
)
4729 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4730 if (headerIndex
!= -1)
4732 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4735 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4737 expirationFound
= TRUE
;
4738 request
->expires
= ft
;
4742 if (!expirationFound
)
4746 /* With no known age, default to 10 minutes until expiration. */
4747 NtQuerySystemTime( &t
);
4748 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4749 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4750 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4753 LeaveCriticalSection( &request
->headers_section
);
4756 static void HTTP_ProcessLastModified(http_request_t
*request
)
4760 EnterCriticalSection( &request
->headers_section
);
4762 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4763 if (headerIndex
!= -1)
4765 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4768 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4769 request
->last_modified
= ft
;
4772 LeaveCriticalSection( &request
->headers_section
);
4775 static void http_process_keep_alive(http_request_t
*req
)
4779 EnterCriticalSection( &req
->headers_section
);
4781 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4782 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4783 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4784 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4786 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4788 LeaveCriticalSection( &req
->headers_section
);
4791 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4793 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4794 netconn_t
*netconn
= NULL
;
4797 reset_data_stream(request
);
4799 if (request
->netconn
)
4801 if (is_valid_netconn(request
->netconn
) && NETCON_is_alive(request
->netconn
))
4804 return ERROR_SUCCESS
;
4808 free_netconn(request
->netconn
);
4809 request
->netconn
= NULL
;
4813 res
= HTTP_ResolveName(request
);
4814 if(res
!= ERROR_SUCCESS
)
4817 EnterCriticalSection(&connection_pool_cs
);
4819 while(!list_empty(&request
->server
->conn_pool
)) {
4820 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4821 list_remove(&netconn
->pool_entry
);
4823 if(is_valid_netconn(netconn
) && NETCON_is_alive(netconn
))
4826 TRACE("connection %p closed during idle\n", netconn
);
4827 free_netconn(netconn
);
4831 LeaveCriticalSection(&connection_pool_cs
);
4834 TRACE("<-- reusing %p netconn\n", netconn
);
4835 request
->netconn
= netconn
;
4837 return ERROR_SUCCESS
;
4840 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4841 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4843 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4844 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4845 request
->server
->addr_str
,
4846 strlen(request
->server
->addr_str
)+1);
4848 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4849 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4850 request
->connect_timeout
, &netconn
);
4851 if(res
!= ERROR_SUCCESS
) {
4852 ERR("create_netconn failed: %u\n", res
);
4856 request
->netconn
= netconn
;
4858 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4859 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4860 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4863 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4864 return ERROR_SUCCESS
;
4867 static char *build_ascii_request( const WCHAR
*str
, void *data
, DWORD data_len
, DWORD
*out_len
)
4869 int len
= WideCharToMultiByte( CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
4872 if (!(ret
= heap_alloc( len
+ data_len
))) return NULL
;
4873 WideCharToMultiByte( CP_ACP
, 0, str
, -1, ret
, len
, NULL
, NULL
);
4874 if (data_len
) memcpy( ret
+ len
- 1, data
, data_len
);
4875 *out_len
= len
+ data_len
- 1;
4880 static void set_content_length_header( http_request_t
*request
, DWORD len
, DWORD flags
)
4882 static const WCHAR fmtW
[] =
4883 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4884 WCHAR buf
[sizeof(fmtW
)/sizeof(fmtW
[0]) + 10];
4886 sprintfW( buf
, fmtW
, len
);
4887 HTTP_HttpAddRequestHeadersW( request
, buf
, ~0u, flags
);
4890 /***********************************************************************
4891 * HTTP_HttpSendRequestW (internal)
4893 * Sends the specified request to the HTTP server
4896 * ERROR_SUCCESS on success
4897 * win32 error code on failure
4900 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4901 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4902 DWORD dwContentLength
, BOOL bEndRequest
)
4904 BOOL redirected
= FALSE
, secure_proxy_connect
= FALSE
, loop_next
;
4905 LPWSTR requestString
= NULL
;
4906 INT responseLen
, cnt
;
4909 TRACE("--> %p\n", request
);
4911 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4913 /* if the verb is NULL default to GET */
4915 request
->verb
= heap_strdupW(szGET
);
4917 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
,
4918 HTTP_ADDREQ_FLAG_ADD_IF_NEW
| HTTP_ADDHDR_FLAG_REQ
);
4920 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4922 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4923 request
->bytesToWrite
= dwContentLength
;
4925 if (request
->session
->appInfo
->agent
)
4927 WCHAR
*agent_header
;
4928 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4931 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4932 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4933 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4935 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4936 heap_free(agent_header
);
4938 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4940 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4941 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4943 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4945 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4946 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4947 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4950 /* add the headers the caller supplied */
4951 if( lpszHeaders
&& dwHeaderLength
)
4952 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4956 DWORD len
, data_len
= dwOptionalLength
;
4957 BOOL reusing_connection
;
4963 request
->contentLength
= ~0u;
4964 request
->bytesToWrite
= 0;
4967 if (TRACE_ON(wininet
))
4971 EnterCriticalSection( &request
->headers_section
);
4972 host
= HTTP_GetHeader( request
, hostW
);
4973 TRACE("Going to url %s %s\n", debugstr_w(host
->lpszValue
), debugstr_w(request
->path
));
4974 LeaveCriticalSection( &request
->headers_section
);
4977 HTTP_FixURL(request
);
4978 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4980 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
,
4981 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
4983 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4984 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4986 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4987 HTTP_InsertCookies(request
);
4989 res
= open_http_connection(request
, &reusing_connection
);
4990 if (res
!= ERROR_SUCCESS
)
4993 if (!reusing_connection
&& (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4995 if (request
->proxy
) secure_proxy_connect
= TRUE
;
4998 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4999 if (res
!= ERROR_SUCCESS
)
5001 WARN("failed to upgrade to secure connection\n");
5002 http_release_netconn(request
, FALSE
);
5007 if (secure_proxy_connect
)
5009 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
5010 const WCHAR
*target
= request
->server
->host_port
;
5012 if (HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
5013 set_content_length_header(request
, 0, HTTP_ADDREQ_FLAG_REPLACE
);
5015 requestString
= build_request_header(request
, connectW
, target
, g_szHttp1_1
, TRUE
);
5017 else if (request
->proxy
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
5019 WCHAR
*url
= build_proxy_path_url(request
);
5020 requestString
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
5025 if (request
->proxy
&& HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
5026 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_REPLACE
);
5028 requestString
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
5031 TRACE("Request header -> %s\n", debugstr_w(requestString
) );
5033 /* send the request as ASCII, tack on the optional data */
5034 if (!lpOptional
|| redirected
|| secure_proxy_connect
)
5037 ascii_req
= build_ascii_request( requestString
, lpOptional
, data_len
, &len
);
5038 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
5040 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5041 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
5043 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
5044 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
5045 heap_free( ascii_req
);
5046 if(res
!= ERROR_SUCCESS
) {
5047 TRACE("send failed: %u\n", res
);
5048 if(!reusing_connection
)
5050 http_release_netconn(request
, FALSE
);
5055 request
->bytesWritten
= data_len
;
5057 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5058 INTERNET_STATUS_REQUEST_SENT
,
5059 &len
, sizeof(DWORD
));
5065 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5066 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5068 if (HTTP_GetResponseHeaders(request
, &responseLen
))
5070 http_release_netconn(request
, FALSE
);
5071 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
5074 /* FIXME: We should know that connection is closed before sending
5075 * headers. Otherwise wrong callbacks are executed */
5076 if(!responseLen
&& reusing_connection
) {
5077 TRACE("Connection closed by server, reconnecting\n");
5078 http_release_netconn(request
, FALSE
);
5083 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5084 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
5087 http_process_keep_alive(request
);
5088 HTTP_ProcessCookies(request
);
5089 HTTP_ProcessExpires(request
);
5090 HTTP_ProcessLastModified(request
);
5092 res
= set_content_length(request
);
5093 if(res
!= ERROR_SUCCESS
)
5095 if(!request
->contentLength
)
5096 http_release_netconn(request
, TRUE
);
5098 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5100 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5101 dwBufferSize
=sizeof(szNewLocation
);
5102 switch(request
->status_code
) {
5103 case HTTP_STATUS_REDIRECT
:
5104 case HTTP_STATUS_MOVED
:
5105 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5106 case HTTP_STATUS_REDIRECT_METHOD
:
5107 if(HTTP_HttpQueryInfoW(request
,HTTP_QUERY_LOCATION
,szNewLocation
,&dwBufferSize
,NULL
) != ERROR_SUCCESS
)
5110 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5111 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5113 heap_free(request
->verb
);
5114 request
->verb
= heap_strdupW(szGET
);
5116 http_release_netconn(request
, drain_content(request
, FALSE
));
5117 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5119 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5120 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5121 res
= HTTP_HandleRedirect(request
, new_url
);
5122 if (res
== ERROR_SUCCESS
)
5124 heap_free(requestString
);
5127 heap_free( new_url
);
5132 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5134 WCHAR szAuthValue
[2048];
5136 if (request
->status_code
== HTTP_STATUS_DENIED
)
5138 WCHAR
*host
= heap_strdupW( request
->server
->canon_host_port
);
5140 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5142 if (HTTP_DoAuthorization(request
, szAuthValue
,
5144 request
->session
->userName
,
5145 request
->session
->password
, host
))
5147 heap_free(requestString
);
5148 if(!drain_content(request
, TRUE
)) {
5149 FIXME("Could not drain content\n");
5150 http_release_netconn(request
, FALSE
);
5159 TRACE("Cleaning wrong authorization data\n");
5160 destroy_authinfo(request
->authInfo
);
5161 request
->authInfo
= NULL
;
5164 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5167 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5169 if (HTTP_DoAuthorization(request
, szAuthValue
,
5170 &request
->proxyAuthInfo
,
5171 request
->session
->appInfo
->proxyUsername
,
5172 request
->session
->appInfo
->proxyPassword
,
5175 heap_free(requestString
);
5176 if(!drain_content(request
, TRUE
)) {
5177 FIXME("Could not drain content\n");
5178 http_release_netconn(request
, FALSE
);
5186 TRACE("Cleaning wrong proxy authorization data\n");
5187 destroy_authinfo(request
->proxyAuthInfo
);
5188 request
->proxyAuthInfo
= NULL
;
5192 if (secure_proxy_connect
&& request
->status_code
== HTTP_STATUS_OK
)
5194 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5195 if (res
!= ERROR_SUCCESS
)
5197 WARN("failed to upgrade to secure proxy connection\n");
5198 http_release_netconn( request
, FALSE
);
5201 remove_header(request
, szProxy_Authorization
, TRUE
);
5202 destroy_authinfo(request
->proxyAuthInfo
);
5203 request
->proxyAuthInfo
= NULL
;
5205 secure_proxy_connect
= FALSE
;
5210 res
= ERROR_SUCCESS
;
5215 heap_free(requestString
);
5217 /* TODO: send notification for P3P header */
5219 if(res
== ERROR_SUCCESS
)
5220 create_cache_entry(request
);
5222 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5224 if (res
== ERROR_SUCCESS
) {
5225 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5226 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5228 send_request_complete(request
,
5229 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5231 send_request_complete(request
, 0, res
);
5247 } send_request_task_t
;
5249 /***********************************************************************
5251 * Helper functions for the HttpSendRequest(Ex) functions
5254 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5256 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5257 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5259 TRACE("%p\n", request
);
5261 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5262 task
->optional_len
, task
->content_len
, task
->end_request
);
5264 heap_free(task
->headers
);
5268 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5272 DWORD res
= ERROR_SUCCESS
;
5274 if(!is_valid_netconn(request
->netconn
)) {
5275 WARN("Not connected\n");
5276 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5277 return ERROR_INTERNET_OPERATION_CANCELLED
;
5280 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5281 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5283 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5284 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5286 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5287 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5289 /* process cookies here. Is this right? */
5290 http_process_keep_alive(request
);
5291 HTTP_ProcessCookies(request
);
5292 HTTP_ProcessExpires(request
);
5293 HTTP_ProcessLastModified(request
);
5295 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5296 if(!request
->contentLength
)
5297 http_release_netconn(request
, TRUE
);
5300 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5302 switch(request
->status_code
) {
5303 case HTTP_STATUS_REDIRECT
:
5304 case HTTP_STATUS_MOVED
:
5305 case HTTP_STATUS_REDIRECT_METHOD
:
5306 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5307 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5308 dwBufferSize
=sizeof(szNewLocation
);
5309 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, szNewLocation
, &dwBufferSize
, NULL
) != ERROR_SUCCESS
)
5312 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5313 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5315 heap_free(request
->verb
);
5316 request
->verb
= heap_strdupW(szGET
);
5318 http_release_netconn(request
, drain_content(request
, FALSE
));
5319 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5321 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5322 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5323 res
= HTTP_HandleRedirect(request
, new_url
);
5324 if (res
== ERROR_SUCCESS
)
5325 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5326 heap_free( new_url
);
5332 if(res
== ERROR_SUCCESS
)
5333 create_cache_entry(request
);
5335 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5336 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5338 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5343 /***********************************************************************
5344 * HttpEndRequestA (WININET.@)
5346 * Ends an HTTP request that was started by HttpSendRequestEx
5349 * TRUE if successful
5353 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5354 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5356 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5360 SetLastError(ERROR_INVALID_PARAMETER
);
5364 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5371 } end_request_task_t
;
5373 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5375 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5376 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5380 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5383 /***********************************************************************
5384 * HttpEndRequestW (WININET.@)
5386 * Ends an HTTP request that was started by HttpSendRequestEx
5389 * TRUE if successful
5393 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5394 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5396 http_request_t
*request
;
5399 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5403 SetLastError(ERROR_INVALID_PARAMETER
);
5407 request
= (http_request_t
*) get_handle_object( hRequest
);
5409 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5411 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5413 WININET_Release( &request
->hdr
);
5416 request
->hdr
.dwFlags
|= dwFlags
;
5418 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5420 end_request_task_t
*task
;
5422 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5423 task
->flags
= dwFlags
;
5424 task
->context
= dwContext
;
5426 INTERNET_AsyncCall(&task
->hdr
);
5427 res
= ERROR_IO_PENDING
;
5430 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5432 WININET_Release( &request
->hdr
);
5433 TRACE("%u <--\n", res
);
5434 if(res
!= ERROR_SUCCESS
)
5436 return res
== ERROR_SUCCESS
;
5439 /***********************************************************************
5440 * HttpSendRequestExA (WININET.@)
5442 * Sends the specified request to the HTTP server and allows chunked
5447 * Failure: FALSE, call GetLastError() for more information.
5449 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5450 LPINTERNET_BUFFERSA lpBuffersIn
,
5451 LPINTERNET_BUFFERSA lpBuffersOut
,
5452 DWORD dwFlags
, DWORD_PTR dwContext
)
5454 INTERNET_BUFFERSW BuffersInW
;
5457 LPWSTR header
= NULL
;
5459 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5460 lpBuffersOut
, dwFlags
, dwContext
);
5464 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5465 if (lpBuffersIn
->lpcszHeader
)
5467 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5468 lpBuffersIn
->dwHeadersLength
,0,0);
5469 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5470 if (!(BuffersInW
.lpcszHeader
= header
))
5472 SetLastError(ERROR_OUTOFMEMORY
);
5475 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5476 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5480 BuffersInW
.lpcszHeader
= NULL
;
5481 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5482 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5483 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5484 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5485 BuffersInW
.Next
= NULL
;
5488 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5494 /***********************************************************************
5495 * HttpSendRequestExW (WININET.@)
5497 * Sends the specified request to the HTTP server and allows chunked
5502 * Failure: FALSE, call GetLastError() for more information.
5504 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5505 LPINTERNET_BUFFERSW lpBuffersIn
,
5506 LPINTERNET_BUFFERSW lpBuffersOut
,
5507 DWORD dwFlags
, DWORD_PTR dwContext
)
5509 http_request_t
*request
;
5510 http_session_t
*session
;
5514 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5515 lpBuffersOut
, dwFlags
, dwContext
);
5517 request
= (http_request_t
*) get_handle_object( hRequest
);
5519 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5521 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5525 session
= request
->session
;
5526 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5527 hIC
= session
->appInfo
;
5528 assert(hIC
->hdr
.htype
== WH_HINIT
);
5530 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5532 send_request_task_t
*task
;
5534 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5539 if (lpBuffersIn
->lpcszHeader
)
5541 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5542 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5544 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5546 task
->headers
= heap_alloc(size
);
5547 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5549 else task
->headers
= NULL
;
5551 task
->headers_len
= size
/ sizeof(WCHAR
);
5552 task
->optional
= lpBuffersIn
->lpvBuffer
;
5553 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5554 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5558 task
->headers
= NULL
;
5559 task
->headers_len
= 0;
5560 task
->optional
= NULL
;
5561 task
->optional_len
= 0;
5562 task
->content_len
= 0;
5565 task
->end_request
= FALSE
;
5567 INTERNET_AsyncCall(&task
->hdr
);
5568 res
= ERROR_IO_PENDING
;
5573 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5574 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5575 lpBuffersIn
->dwBufferTotal
, FALSE
);
5577 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5582 WININET_Release( &request
->hdr
);
5586 return res
== ERROR_SUCCESS
;
5589 /***********************************************************************
5590 * HttpSendRequestW (WININET.@)
5592 * Sends the specified request to the HTTP server
5599 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5600 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5602 http_request_t
*request
;
5603 http_session_t
*session
= NULL
;
5604 appinfo_t
*hIC
= NULL
;
5605 DWORD res
= ERROR_SUCCESS
;
5607 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5608 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5610 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5611 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5613 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5617 session
= request
->session
;
5618 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5620 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5624 hIC
= session
->appInfo
;
5625 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5627 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5631 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5633 send_request_task_t
*task
;
5635 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5640 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5641 else size
= dwHeaderLength
* sizeof(WCHAR
);
5643 task
->headers
= heap_alloc(size
);
5644 memcpy(task
->headers
, lpszHeaders
, size
);
5647 task
->headers
= NULL
;
5648 task
->headers_len
= dwHeaderLength
;
5649 task
->optional
= lpOptional
;
5650 task
->optional_len
= dwOptionalLength
;
5651 task
->content_len
= dwOptionalLength
;
5652 task
->end_request
= TRUE
;
5654 INTERNET_AsyncCall(&task
->hdr
);
5655 res
= ERROR_IO_PENDING
;
5659 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5660 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5661 dwOptionalLength
, TRUE
);
5665 WININET_Release( &request
->hdr
);
5668 return res
== ERROR_SUCCESS
;
5671 /***********************************************************************
5672 * HttpSendRequestA (WININET.@)
5674 * Sends the specified request to the HTTP server
5681 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5682 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5685 LPWSTR szHeaders
=NULL
;
5686 DWORD nLen
=dwHeaderLength
;
5687 if(lpszHeaders
!=NULL
)
5689 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5690 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5691 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5693 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5694 heap_free(szHeaders
);
5698 /***********************************************************************
5699 * HTTPSESSION_Destroy (internal)
5701 * Deallocate session handle
5704 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5706 http_session_t
*session
= (http_session_t
*) hdr
;
5708 TRACE("%p\n", session
);
5710 WININET_Release(&session
->appInfo
->hdr
);
5712 heap_free(session
->hostName
);
5713 heap_free(session
->password
);
5714 heap_free(session
->userName
);
5717 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5719 http_session_t
*ses
= (http_session_t
*)hdr
;
5722 case INTERNET_OPTION_HANDLE_TYPE
:
5723 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5725 if (*size
< sizeof(ULONG
))
5726 return ERROR_INSUFFICIENT_BUFFER
;
5728 *size
= sizeof(DWORD
);
5729 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5730 return ERROR_SUCCESS
;
5731 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5732 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5734 if (*size
< sizeof(DWORD
))
5735 return ERROR_INSUFFICIENT_BUFFER
;
5737 *size
= sizeof(DWORD
);
5738 *(DWORD
*)buffer
= ses
->connect_timeout
;
5739 return ERROR_SUCCESS
;
5741 case INTERNET_OPTION_SEND_TIMEOUT
:
5742 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5744 if (*size
< sizeof(DWORD
))
5745 return ERROR_INSUFFICIENT_BUFFER
;
5747 *size
= sizeof(DWORD
);
5748 *(DWORD
*)buffer
= ses
->send_timeout
;
5749 return ERROR_SUCCESS
;
5751 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5752 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5754 if (*size
< sizeof(DWORD
))
5755 return ERROR_INSUFFICIENT_BUFFER
;
5757 *size
= sizeof(DWORD
);
5758 *(DWORD
*)buffer
= ses
->receive_timeout
;
5759 return ERROR_SUCCESS
;
5762 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5765 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5767 http_session_t
*ses
= (http_session_t
*)hdr
;
5770 case INTERNET_OPTION_USERNAME
:
5772 heap_free(ses
->userName
);
5773 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5774 return ERROR_SUCCESS
;
5776 case INTERNET_OPTION_PASSWORD
:
5778 heap_free(ses
->password
);
5779 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5780 return ERROR_SUCCESS
;
5782 case INTERNET_OPTION_PROXY_USERNAME
:
5784 heap_free(ses
->appInfo
->proxyUsername
);
5785 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5786 return ERROR_SUCCESS
;
5788 case INTERNET_OPTION_PROXY_PASSWORD
:
5790 heap_free(ses
->appInfo
->proxyPassword
);
5791 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5792 return ERROR_SUCCESS
;
5794 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5796 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5797 ses
->connect_timeout
= *(DWORD
*)buffer
;
5798 return ERROR_SUCCESS
;
5800 case INTERNET_OPTION_SEND_TIMEOUT
:
5802 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5803 ses
->send_timeout
= *(DWORD
*)buffer
;
5804 return ERROR_SUCCESS
;
5806 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5808 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5809 ses
->receive_timeout
= *(DWORD
*)buffer
;
5810 return ERROR_SUCCESS
;
5815 return INET_SetOption(hdr
, option
, buffer
, size
);
5818 static const object_vtbl_t HTTPSESSIONVtbl
= {
5819 HTTPSESSION_Destroy
,
5821 HTTPSESSION_QueryOption
,
5822 HTTPSESSION_SetOption
,
5831 /***********************************************************************
5832 * HTTP_Connect (internal)
5834 * Create http session handle
5837 * HINTERNET a session handle on success
5841 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5842 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5843 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5844 DWORD dwInternalFlags
, HINTERNET
*ret
)
5846 http_session_t
*session
= NULL
;
5850 if (!lpszServerName
|| !lpszServerName
[0])
5851 return ERROR_INVALID_PARAMETER
;
5853 assert( hIC
->hdr
.htype
== WH_HINIT
);
5855 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5857 return ERROR_OUTOFMEMORY
;
5860 * According to my tests. The name is not resolved until a request is sent
5863 session
->hdr
.htype
= WH_HHTTPSESSION
;
5864 session
->hdr
.dwFlags
= dwFlags
;
5865 session
->hdr
.dwContext
= dwContext
;
5866 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5868 WININET_AddRef( &hIC
->hdr
);
5869 session
->appInfo
= hIC
;
5870 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5872 session
->hostName
= heap_strdupW(lpszServerName
);
5873 if (lpszUserName
&& lpszUserName
[0])
5874 session
->userName
= heap_strdupW(lpszUserName
);
5875 if (lpszPassword
&& lpszPassword
[0])
5876 session
->password
= heap_strdupW(lpszPassword
);
5877 session
->hostPort
= serverPort
;
5878 session
->connect_timeout
= hIC
->connect_timeout
;
5879 session
->send_timeout
= 0;
5880 session
->receive_timeout
= 0;
5882 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5883 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5885 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5886 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5891 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5895 TRACE("%p --> %p\n", hIC
, session
);
5897 *ret
= session
->hdr
.hInternet
;
5898 return ERROR_SUCCESS
;
5901 /***********************************************************************
5902 * HTTP_clear_response_headers (internal)
5904 * clear out any old response headers
5906 static void HTTP_clear_response_headers( http_request_t
*request
)
5910 EnterCriticalSection( &request
->headers_section
);
5912 for( i
=0; i
<request
->nCustHeaders
; i
++)
5914 if( !request
->custHeaders
[i
].lpszField
)
5916 if( !request
->custHeaders
[i
].lpszValue
)
5918 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5920 HTTP_DeleteCustomHeader( request
, i
);
5924 LeaveCriticalSection( &request
->headers_section
);
5927 /***********************************************************************
5928 * HTTP_GetResponseHeaders (internal)
5930 * Read server response
5937 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5940 WCHAR buffer
[MAX_REPLY_LEN
];
5941 DWORD buflen
= MAX_REPLY_LEN
;
5943 char bufferA
[MAX_REPLY_LEN
];
5944 LPWSTR status_code
= NULL
, status_text
= NULL
;
5945 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5946 BOOL codeHundred
= FALSE
;
5950 if(!is_valid_netconn(request
->netconn
))
5953 /* clear old response headers (eg. from a redirect response) */
5954 HTTP_clear_response_headers( request
);
5956 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5959 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5961 buflen
= MAX_REPLY_LEN
;
5962 if ((res
= read_line(request
, bufferA
, &buflen
)))
5965 if (!buflen
) goto lend
;
5968 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5969 /* check is this a status code line? */
5970 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5972 /* split the version from the status code */
5973 status_code
= strchrW( buffer
, ' ' );
5978 /* split the status code from the status text */
5979 status_text
= strchrW( status_code
, ' ' );
5983 request
->status_code
= atoiW(status_code
);
5985 TRACE("version [%s] status code [%s] status text [%s]\n",
5986 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5988 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5990 else if (!codeHundred
)
5992 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5994 heap_free(request
->version
);
5995 heap_free(request
->statusText
);
5997 request
->status_code
= HTTP_STATUS_OK
;
5998 request
->version
= heap_strdupW(g_szHttp1_0
);
5999 request
->statusText
= heap_strdupW(szOK
);
6003 } while (codeHundred
);
6005 /* Add status code */
6006 HTTP_ProcessHeader(request
, szStatus
, status_code
,
6007 HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
6009 heap_free(request
->version
);
6010 heap_free(request
->statusText
);
6012 request
->version
= heap_strdupW(buffer
);
6013 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
6015 /* Restore the spaces */
6016 *(status_code
-1) = ' ';
6018 *(status_text
-1) = ' ';
6020 /* Parse each response line */
6023 buflen
= MAX_REPLY_LEN
;
6024 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
6026 LPWSTR
* pFieldAndValue
;
6028 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
6030 if (!bufferA
[0]) break;
6031 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
6033 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
6036 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
6037 HTTP_ADDREQ_FLAG_ADD
);
6038 HTTP_FreeTokens(pFieldAndValue
);
6049 res
= ERROR_SUCCESS
;
6058 /***********************************************************************
6059 * HTTP_InterpretHttpHeader (internal)
6061 * Parse server response
6065 * Pointer to array of field, value, NULL on success.
6068 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
6070 LPWSTR
* pTokenPair
;
6074 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
6076 pszColon
= strchrW(buffer
, ':');
6077 /* must have two tokens */
6080 HTTP_FreeTokens(pTokenPair
);
6082 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
6086 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
6089 HTTP_FreeTokens(pTokenPair
);
6092 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
6093 pTokenPair
[0][pszColon
- buffer
] = '\0';
6097 len
= strlenW(pszColon
);
6098 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
6101 HTTP_FreeTokens(pTokenPair
);
6104 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
6106 strip_spaces(pTokenPair
[0]);
6107 strip_spaces(pTokenPair
[1]);
6109 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
6113 /***********************************************************************
6114 * HTTP_ProcessHeader (internal)
6116 * Stuff header into header tables according to <dwModifier>
6120 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6122 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6124 LPHTTPHEADERW lphttpHdr
= NULL
;
6126 BOOL request_only
= !!(dwModifier
& HTTP_ADDHDR_FLAG_REQ
);
6127 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6129 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6131 EnterCriticalSection( &request
->headers_section
);
6133 /* REPLACE wins out over ADD */
6134 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6135 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6137 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6140 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6144 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6146 LeaveCriticalSection( &request
->headers_section
);
6147 return ERROR_HTTP_INVALID_HEADER
;
6149 lphttpHdr
= &request
->custHeaders
[index
];
6155 hdr
.lpszField
= (LPWSTR
)field
;
6156 hdr
.lpszValue
= (LPWSTR
)value
;
6157 hdr
.wFlags
= hdr
.wCount
= 0;
6159 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6160 hdr
.wFlags
|= HDR_ISREQUEST
;
6162 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6163 LeaveCriticalSection( &request
->headers_section
);
6166 /* no value to delete */
6169 LeaveCriticalSection( &request
->headers_section
);
6170 return ERROR_SUCCESS
;
6173 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6174 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6176 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6178 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6180 HTTP_DeleteCustomHeader( request
, index
);
6182 if (value
&& value
[0])
6186 hdr
.lpszField
= (LPWSTR
)field
;
6187 hdr
.lpszValue
= (LPWSTR
)value
;
6188 hdr
.wFlags
= hdr
.wCount
= 0;
6190 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6191 hdr
.wFlags
|= HDR_ISREQUEST
;
6193 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6194 LeaveCriticalSection( &request
->headers_section
);
6198 LeaveCriticalSection( &request
->headers_section
);
6199 return ERROR_SUCCESS
;
6201 else if (dwModifier
& COALESCEFLAGS
)
6206 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6207 INT valuelen
= strlenW(value
);
6209 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6212 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6214 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6217 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6220 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6222 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6225 lphttpHdr
->lpszValue
= lpsztmp
;
6226 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6229 lphttpHdr
->lpszValue
[origlen
] = ch
;
6231 lphttpHdr
->lpszValue
[origlen
] = ' ';
6235 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6236 lphttpHdr
->lpszValue
[len
] = '\0';
6237 res
= ERROR_SUCCESS
;
6241 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6242 res
= ERROR_OUTOFMEMORY
;
6245 TRACE("<-- %d\n", res
);
6246 LeaveCriticalSection( &request
->headers_section
);
6250 /***********************************************************************
6251 * HTTP_GetCustomHeaderIndex (internal)
6253 * Return index of custom header from header array
6254 * Headers section must be held
6256 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6257 int requested_index
, BOOL request_only
)
6261 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6263 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6265 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6268 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6271 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6274 if (requested_index
== 0)
6279 if (index
>= request
->nCustHeaders
)
6282 TRACE("Return: %d\n", index
);
6287 /***********************************************************************
6288 * HTTP_InsertCustomHeader (internal)
6290 * Insert header into array
6291 * Headers section must be held
6293 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6296 LPHTTPHEADERW lph
= NULL
;
6298 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6299 count
= request
->nCustHeaders
+ 1;
6301 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6303 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6306 return ERROR_OUTOFMEMORY
;
6308 request
->custHeaders
= lph
;
6309 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6310 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6311 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6312 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6313 request
->nCustHeaders
++;
6315 return ERROR_SUCCESS
;
6319 /***********************************************************************
6320 * HTTP_DeleteCustomHeader (internal)
6322 * Delete header from array
6323 * If this function is called, the index may change.
6324 * Headers section must be held
6326 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6328 if( request
->nCustHeaders
<= 0 )
6330 if( index
>= request
->nCustHeaders
)
6332 request
->nCustHeaders
--;
6334 heap_free(request
->custHeaders
[index
].lpszField
);
6335 heap_free(request
->custHeaders
[index
].lpszValue
);
6337 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6338 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6339 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6345 /***********************************************************************
6346 * IsHostInProxyBypassList (@)
6351 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6353 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);