2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
51 #define NO_SHLWAPI_STREAM
52 #define NO_SHLWAPI_REG
53 #define NO_SHLWAPI_STRFCNS
54 #define NO_SHLWAPI_GDI
61 #include "wine/debug.h"
62 #include "wine/exception.h"
63 #include "wine/unicode.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
67 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
68 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
69 static const WCHAR szOK
[] = {'O','K',0};
70 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
75 static const WCHAR szGET
[] = { 'G','E','T', 0 };
76 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
78 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
79 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
80 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
81 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
82 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
83 static const WCHAR szAge
[] = { 'A','g','e',0 };
84 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
85 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
86 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
87 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
88 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
89 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
90 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
91 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
92 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
93 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
94 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
95 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
96 static const WCHAR szContent_Transfer_Encoding
[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
97 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
98 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
99 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
100 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
101 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
102 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
103 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
104 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
106 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
107 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
108 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
109 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
110 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
111 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
112 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
113 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
114 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
115 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
116 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
117 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
118 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
119 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
120 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
121 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
122 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
123 static const WCHAR szUnless_Modified_Since
[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
124 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
125 static const WCHAR szURI
[] = { 'U','R','I',0 };
126 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
127 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
128 static const WCHAR szVia
[] = { 'V','i','a',0 };
129 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
130 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
132 static const WCHAR emptyW
[] = {0};
134 #define HTTP_REFERER szReferer
135 #define HTTP_ACCEPT szAccept
136 #define HTTP_USERAGENT szUser_Agent
138 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
139 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
140 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
141 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
142 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
143 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
144 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
146 #define COLLECT_TIME 60000
149 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
160 unsigned int auth_data_len
;
161 BOOL finished
; /* finished authenticating */
165 typedef struct _basicAuthorizationData
172 UINT authorizationLen
;
173 } basicAuthorizationData
;
175 typedef struct _authorizationData
189 static struct list basicAuthorizationCache
= LIST_INIT(basicAuthorizationCache
);
190 static struct list authorizationCache
= LIST_INIT(authorizationCache
);
192 static CRITICAL_SECTION authcache_cs
;
193 static CRITICAL_SECTION_DEBUG critsect_debug
=
196 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
197 0, 0, { (DWORD_PTR
)(__FILE__
": authcache_cs") }
199 static CRITICAL_SECTION authcache_cs
= { &critsect_debug
, -1, 0, 0, 0, 0 };
201 static DWORD
HTTP_GetResponseHeaders(http_request_t
*req
, INT
*len
);
202 static DWORD
HTTP_ProcessHeader(http_request_t
*req
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
);
203 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
);
204 static DWORD
HTTP_InsertCustomHeader(http_request_t
*req
, LPHTTPHEADERW lpHdr
);
205 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*req
, LPCWSTR lpszField
, INT index
, BOOL Request
);
206 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*req
, DWORD index
);
207 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
);
208 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*, DWORD
, LPVOID
, LPDWORD
, LPDWORD
);
209 static UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
210 static DWORD
drain_content(http_request_t
*,BOOL
);
212 static CRITICAL_SECTION connection_pool_cs
;
213 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
215 0, 0, &connection_pool_cs
,
216 { &connection_pool_debug
.ProcessLocksList
, &connection_pool_debug
.ProcessLocksList
},
217 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
219 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
221 static struct list connection_pool
= LIST_INIT(connection_pool
);
222 static BOOL collector_running
;
224 void server_addref(server_t
*server
)
226 InterlockedIncrement(&server
->ref
);
229 void server_release(server_t
*server
)
231 if(InterlockedDecrement(&server
->ref
))
235 EnterCriticalSection(&connection_pool_cs
);
237 list_remove(&server
->entry
);
239 LeaveCriticalSection(&connection_pool_cs
);
242 if(server
->cert_chain
)
243 CertFreeCertificateChain(server
->cert_chain
);
244 heap_free(server
->name
);
245 heap_free(server
->scheme_host_port
);
249 static BOOL
process_host_port(server_t
*server
)
255 static const WCHAR httpW
[] = {'h','t','t','p',0};
256 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
257 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
259 name_len
= strlenW(server
->name
);
260 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
264 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
265 server
->scheme_host_port
= buf
;
267 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
271 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
272 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
276 server_t
*get_server(substr_t name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
278 server_t
*iter
, *server
= NULL
;
280 EnterCriticalSection(&connection_pool_cs
);
282 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
283 if(iter
->port
== port
&& name
.len
== strlenW(iter
->name
) && !strncmpiW(iter
->name
, name
.str
, name
.len
)
284 && iter
->is_https
== is_https
) {
286 server_addref(server
);
291 if(!server
&& do_create
) {
292 server
= heap_alloc_zero(sizeof(*server
));
294 server
->ref
= 2; /* list reference and return */
296 server
->is_https
= is_https
;
297 list_init(&server
->conn_pool
);
298 server
->name
= heap_strndupW(name
.str
, name
.len
);
299 if(server
->name
&& process_host_port(server
)) {
300 list_add_head(&connection_pool
, &server
->entry
);
308 LeaveCriticalSection(&connection_pool_cs
);
313 BOOL
collect_connections(collect_type_t collect_type
)
315 netconn_t
*netconn
, *netconn_safe
;
316 server_t
*server
, *server_safe
;
317 BOOL remaining
= FALSE
;
321 now
= GetTickCount();
323 now
= GetTickCount64();
326 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
327 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
328 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
329 TRACE("freeing %p\n", netconn
);
330 list_remove(&netconn
->pool_entry
);
331 free_netconn(netconn
);
337 if(collect_type
== COLLECT_CLEANUP
) {
338 list_remove(&server
->entry
);
339 list_init(&server
->entry
);
340 server_release(server
);
347 static DWORD WINAPI
collect_connections_proc(void *arg
)
349 BOOL remaining_conns
;
352 /* FIXME: Use more sophisticated method */
355 EnterCriticalSection(&connection_pool_cs
);
357 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
359 collector_running
= FALSE
;
361 LeaveCriticalSection(&connection_pool_cs
);
362 }while(remaining_conns
);
364 FreeLibraryAndExitThread(WININET_hModule
, 0);
367 /***********************************************************************
368 * HTTP_GetHeader (internal)
370 * Headers section must be held
372 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
375 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
376 if (HeaderIndex
== -1)
379 return &req
->custHeaders
[HeaderIndex
];
382 static WCHAR
*get_host_header( http_request_t
*req
)
387 EnterCriticalSection( &req
->headers_section
);
388 if ((header
= HTTP_GetHeader( req
, hostW
))) ret
= heap_strdupW( header
->lpszValue
);
389 else ret
= heap_strdupW( req
->server
->canon_host_port
);
390 LeaveCriticalSection( &req
->headers_section
);
394 struct data_stream_vtbl_t
{
395 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
396 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,BOOL
);
397 DWORD (*drain_content
)(data_stream_t
*,http_request_t
*,BOOL
);
398 void (*destroy
)(data_stream_t
*);
402 data_stream_t data_stream
;
404 BYTE buf
[READ_BUFFER_SIZE
];
410 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
,
411 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
,
412 CHUNKED_STREAM_STATE_READING_CHUNK
,
413 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
,
414 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
,
415 CHUNKED_STREAM_STATE_END_OF_STREAM
,
416 CHUNKED_STREAM_STATE_ERROR
420 static inline void destroy_data_stream(data_stream_t
*stream
)
422 stream
->vtbl
->destroy(stream
);
425 static void reset_data_stream(http_request_t
*req
)
427 destroy_data_stream(req
->data_stream
);
428 req
->data_stream
= &req
->netconn_stream
.data_stream
;
429 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
430 req
->read_gzip
= FALSE
;
433 static void remove_header( http_request_t
*request
, const WCHAR
*str
, BOOL from_request
)
436 EnterCriticalSection( &request
->headers_section
);
437 index
= HTTP_GetCustomHeaderIndex( request
, str
, 0, from_request
);
438 if (index
!= -1) HTTP_DeleteCustomHeader( request
, index
);
439 LeaveCriticalSection( &request
->headers_section
);
445 data_stream_t stream
;
446 data_stream_t
*parent_stream
;
448 BYTE buf
[READ_BUFFER_SIZE
];
454 static BOOL
gzip_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
456 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
457 return gzip_stream
->end_of_data
458 || (!gzip_stream
->buf_size
&& gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
));
461 static DWORD
gzip_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
462 DWORD
*read
, BOOL allow_blocking
)
464 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
465 z_stream
*zstream
= &gzip_stream
->zstream
;
466 DWORD current_read
, ret_read
= 0;
468 DWORD res
= ERROR_SUCCESS
;
470 TRACE("(%d %x)\n", size
, allow_blocking
);
472 while(size
&& !gzip_stream
->end_of_data
) {
473 if(!gzip_stream
->buf_size
) {
474 if(gzip_stream
->buf_pos
) {
475 if(gzip_stream
->buf_size
)
476 memmove(gzip_stream
->buf
, gzip_stream
->buf
+gzip_stream
->buf_pos
, gzip_stream
->buf_size
);
477 gzip_stream
->buf_pos
= 0;
479 res
= gzip_stream
->parent_stream
->vtbl
->read(gzip_stream
->parent_stream
, req
, gzip_stream
->buf
+gzip_stream
->buf_size
,
480 sizeof(gzip_stream
->buf
)-gzip_stream
->buf_size
, ¤t_read
, allow_blocking
);
481 if(res
!= ERROR_SUCCESS
)
484 gzip_stream
->buf_size
+= current_read
;
486 WARN("unexpected end of data\n");
487 gzip_stream
->end_of_data
= TRUE
;
492 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
493 zstream
->avail_in
= gzip_stream
->buf_size
;
494 zstream
->next_out
= buf
+ret_read
;
495 zstream
->avail_out
= size
;
496 zres
= inflate(&gzip_stream
->zstream
, 0);
497 current_read
= size
- zstream
->avail_out
;
498 size
-= current_read
;
499 ret_read
+= current_read
;
500 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
501 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
502 if(zres
== Z_STREAM_END
) {
503 TRACE("end of data\n");
504 gzip_stream
->end_of_data
= TRUE
;
506 }else if(zres
!= Z_OK
) {
507 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
509 res
= ERROR_INTERNET_DECODING_FAILED
;
514 allow_blocking
= FALSE
;
517 TRACE("read %u bytes\n", ret_read
);
524 static DWORD
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
, BOOL allow_blocking
)
526 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
527 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
, allow_blocking
);
530 static void gzip_destroy(data_stream_t
*stream
)
532 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
534 destroy_data_stream(gzip_stream
->parent_stream
);
536 if(!gzip_stream
->end_of_data
)
537 inflateEnd(&gzip_stream
->zstream
);
538 heap_free(gzip_stream
);
541 static const data_stream_vtbl_t gzip_stream_vtbl
= {
548 static voidpf
wininet_zalloc(voidpf opaque
, uInt items
, uInt size
)
550 return heap_alloc(items
*size
);
553 static void wininet_zfree(voidpf opaque
, voidpf address
)
558 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
560 gzip_stream_t
*gzip_stream
;
563 gzip_stream
= heap_alloc_zero(sizeof(gzip_stream_t
));
565 return ERROR_OUTOFMEMORY
;
567 gzip_stream
->stream
.vtbl
= &gzip_stream_vtbl
;
568 gzip_stream
->zstream
.zalloc
= wininet_zalloc
;
569 gzip_stream
->zstream
.zfree
= wininet_zfree
;
571 zres
= inflateInit2(&gzip_stream
->zstream
, is_gzip
? 0x1f : -15);
573 ERR("inflateInit failed: %d\n", zres
);
574 heap_free(gzip_stream
);
575 return ERROR_OUTOFMEMORY
;
578 remove_header(req
, szContent_Length
, FALSE
);
581 memcpy(gzip_stream
->buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
582 gzip_stream
->buf_size
= req
->read_size
;
583 req
->read_pos
= req
->read_size
= 0;
586 req
->read_gzip
= TRUE
;
587 gzip_stream
->parent_stream
= req
->data_stream
;
588 req
->data_stream
= &gzip_stream
->stream
;
589 return ERROR_SUCCESS
;
594 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
596 ERR("gzip stream not supported, missing zlib.\n");
597 return ERROR_SUCCESS
;
602 /***********************************************************************
603 * HTTP_FreeTokens (internal)
605 * Frees table of pointers.
607 static void HTTP_FreeTokens(LPWSTR
* token_array
)
610 for (i
= 0; token_array
[i
]; i
++) heap_free(token_array
[i
]);
611 heap_free(token_array
);
614 static void HTTP_FixURL(http_request_t
*request
)
616 static const WCHAR szSlash
[] = { '/',0 };
617 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/', 0 };
619 /* If we don't have a path we set it to root */
620 if (NULL
== request
->path
)
621 request
->path
= heap_strdupW(szSlash
);
622 else /* remove \r and \n*/
624 int nLen
= strlenW(request
->path
);
625 while ((nLen
>0 ) && ((request
->path
[nLen
-1] == '\r')||(request
->path
[nLen
-1] == '\n')))
628 request
->path
[nLen
]='\0';
630 /* Replace '\' with '/' */
633 if (request
->path
[nLen
] == '\\') request
->path
[nLen
]='/';
637 if(CSTR_EQUAL
!= CompareStringW( LOCALE_INVARIANT
, NORM_IGNORECASE
,
638 request
->path
, strlenW(request
->path
), szHttp
, strlenW(szHttp
) )
639 && request
->path
[0] != '/') /* not an absolute path ?? --> fix it !! */
641 WCHAR
*fixurl
= heap_alloc((strlenW(request
->path
) + 2)*sizeof(WCHAR
));
643 strcpyW(fixurl
+ 1, request
->path
);
644 heap_free( request
->path
);
645 request
->path
= fixurl
;
649 static WCHAR
* build_request_header(http_request_t
*request
, const WCHAR
*verb
,
650 const WCHAR
*path
, const WCHAR
*version
, BOOL use_cr
)
652 static const WCHAR szSpace
[] = {' ',0};
653 static const WCHAR szColon
[] = {':',' ',0};
654 static const WCHAR szCr
[] = {'\r',0};
655 static const WCHAR szLf
[] = {'\n',0};
656 LPWSTR requestString
;
661 EnterCriticalSection( &request
->headers_section
);
663 /* allocate space for an array of all the string pointers to be added */
664 len
= request
->nCustHeaders
* 5 + 10;
665 if (!(req
= heap_alloc( len
* sizeof(const WCHAR
*) )))
667 LeaveCriticalSection( &request
->headers_section
);
671 /* add the verb, path and HTTP version string */
682 /* Append custom request headers */
683 for (i
= 0; i
< request
->nCustHeaders
; i
++)
685 if (request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
687 req
[n
++] = request
->custHeaders
[i
].lpszField
;
689 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
694 TRACE("Adding custom header %s (%s)\n",
695 debugstr_w(request
->custHeaders
[i
].lpszField
),
696 debugstr_w(request
->custHeaders
[i
].lpszValue
));
704 requestString
= HTTP_build_req( req
, 4 );
706 LeaveCriticalSection( &request
->headers_section
);
707 return requestString
;
710 static WCHAR
* build_response_header(http_request_t
*request
, BOOL use_cr
)
712 static const WCHAR colonW
[] = { ':',' ',0 };
713 static const WCHAR crW
[] = { '\r',0 };
714 static const WCHAR lfW
[] = { '\n',0 };
715 static const WCHAR status_fmt
[] = { ' ','%','u',' ',0 };
720 EnterCriticalSection( &request
->headers_section
);
722 if (!(req
= heap_alloc( (request
->nCustHeaders
* 5 + 8) * sizeof(WCHAR
*) )))
724 LeaveCriticalSection( &request
->headers_section
);
728 if (request
->status_code
)
730 req
[n
++] = request
->version
;
731 sprintfW(buf
, status_fmt
, request
->status_code
);
733 req
[n
++] = request
->statusText
;
739 for(i
= 0; i
< request
->nCustHeaders
; i
++)
741 if(!(request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
742 && strcmpW(request
->custHeaders
[i
].lpszField
, szStatus
))
744 req
[n
++] = request
->custHeaders
[i
].lpszField
;
746 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
751 TRACE("Adding custom header %s (%s)\n",
752 debugstr_w(request
->custHeaders
[i
].lpszField
),
753 debugstr_w(request
->custHeaders
[i
].lpszValue
));
761 ret
= HTTP_build_req(req
, 0);
763 LeaveCriticalSection( &request
->headers_section
);
767 static void HTTP_ProcessCookies( http_request_t
*request
)
771 LPHTTPHEADERW setCookieHeader
;
774 if(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
)
777 path
= heap_strdupW(request
->path
);
781 tmp
= strrchrW(path
, '/');
782 if (tmp
&& tmp
[1]) tmp
[1] = 0;
784 EnterCriticalSection( &request
->headers_section
);
786 while((HeaderIndex
= HTTP_GetCustomHeaderIndex(request
, szSet_Cookie
, numCookies
++, FALSE
)) != -1)
791 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
793 if (!setCookieHeader
->lpszValue
)
796 data
= strchrW(setCookieHeader
->lpszValue
, '=');
800 name
= substr(setCookieHeader
->lpszValue
, data
- setCookieHeader
->lpszValue
);
802 set_cookie(substrz(request
->server
->name
), substrz(path
), name
, substrz(data
), INTERNET_COOKIE_HTTPONLY
);
805 LeaveCriticalSection( &request
->headers_section
);
809 static void strip_spaces(LPWSTR start
)
818 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
820 end
= start
+ strlenW(start
) - 1;
821 while (end
>= start
&& *end
== ' ')
828 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
830 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
831 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
833 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAYSIZE(szBasic
)) &&
834 ((pszAuthValue
[ARRAYSIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAYSIZE(szBasic
)]);
835 if (is_basic
&& pszRealm
)
838 LPCWSTR ptr
= &pszAuthValue
[ARRAYSIZE(szBasic
)];
842 token
= strchrW(ptr
,'=');
846 while (*realm
== ' ')
848 if(!strncmpiW(realm
, szRealm
, ARRAYSIZE(szRealm
)) &&
849 (realm
[ARRAYSIZE(szRealm
)] == ' ' || realm
[ARRAYSIZE(szRealm
)] == '='))
852 while (*token
== ' ')
856 *pszRealm
= heap_strdupW(token
);
857 strip_spaces(*pszRealm
);
864 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
866 if (!authinfo
) return;
868 if (SecIsValidHandle(&authinfo
->ctx
))
869 DeleteSecurityContext(&authinfo
->ctx
);
870 if (SecIsValidHandle(&authinfo
->cred
))
871 FreeCredentialsHandle(&authinfo
->cred
);
873 heap_free(authinfo
->auth_data
);
874 heap_free(authinfo
->scheme
);
878 static UINT
retrieve_cached_basic_authorization(const WCHAR
*host
, const WCHAR
*realm
, char **auth_data
)
880 basicAuthorizationData
*ad
;
883 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
885 EnterCriticalSection(&authcache_cs
);
886 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
888 if (!strcmpiW(host
, ad
->host
) && (!realm
|| !strcmpW(realm
, ad
->realm
)))
890 TRACE("Authorization found in cache\n");
891 *auth_data
= heap_alloc(ad
->authorizationLen
);
892 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
893 rc
= ad
->authorizationLen
;
897 LeaveCriticalSection(&authcache_cs
);
901 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
904 basicAuthorizationData
* ad
= NULL
;
906 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
908 EnterCriticalSection(&authcache_cs
);
909 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
911 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
912 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
921 TRACE("Found match in cache, replacing\n");
922 heap_free(ad
->authorization
);
923 ad
->authorization
= heap_alloc(auth_data_len
);
924 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
925 ad
->authorizationLen
= auth_data_len
;
929 ad
= heap_alloc(sizeof(basicAuthorizationData
));
930 ad
->host
= heap_strdupW(host
);
931 ad
->realm
= heap_strdupW(realm
);
932 ad
->authorization
= heap_alloc(auth_data_len
);
933 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
934 ad
->authorizationLen
= auth_data_len
;
935 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
936 TRACE("authorization cached\n");
938 LeaveCriticalSection(&authcache_cs
);
941 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
942 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
944 authorizationData
*ad
;
946 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
948 EnterCriticalSection(&authcache_cs
);
949 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
950 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
951 TRACE("Authorization found in cache\n");
953 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
954 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
955 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
956 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
957 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
958 heap_free(nt_auth_identity
->User
);
959 heap_free(nt_auth_identity
->Password
);
960 heap_free(nt_auth_identity
->Domain
);
964 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
965 nt_auth_identity
->UserLength
= ad
->user_len
;
966 nt_auth_identity
->PasswordLength
= ad
->password_len
;
967 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
968 nt_auth_identity
->DomainLength
= ad
->domain_len
;
969 LeaveCriticalSection(&authcache_cs
);
973 LeaveCriticalSection(&authcache_cs
);
978 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
979 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
981 authorizationData
*ad
;
984 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
986 EnterCriticalSection(&authcache_cs
);
987 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
988 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
995 heap_free(ad
->password
);
996 heap_free(ad
->domain
);
998 ad
= heap_alloc(sizeof(authorizationData
));
1000 LeaveCriticalSection(&authcache_cs
);
1004 ad
->host
= heap_strdupW(host
);
1005 ad
->scheme
= heap_strdupW(scheme
);
1006 list_add_head(&authorizationCache
, &ad
->entry
);
1009 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
1010 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
1011 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
1012 ad
->user_len
= nt_auth_identity
->UserLength
;
1013 ad
->password_len
= nt_auth_identity
->PasswordLength
;
1014 ad
->domain_len
= nt_auth_identity
->DomainLength
;
1016 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
1017 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
1018 heap_free(ad
->host
);
1019 heap_free(ad
->scheme
);
1020 heap_free(ad
->user
);
1021 heap_free(ad
->password
);
1022 heap_free(ad
->domain
);
1023 list_remove(&ad
->entry
);
1027 LeaveCriticalSection(&authcache_cs
);
1030 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
1031 struct HttpAuthInfo
**ppAuthInfo
,
1032 LPWSTR domain_and_username
, LPWSTR password
,
1035 SECURITY_STATUS sec_status
;
1036 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
1038 LPWSTR szRealm
= NULL
;
1040 TRACE("%s\n", debugstr_w(pszAuthValue
));
1047 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
1051 SecInvalidateHandle(&pAuthInfo
->cred
);
1052 SecInvalidateHandle(&pAuthInfo
->ctx
);
1053 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1054 pAuthInfo
->attr
= 0;
1055 pAuthInfo
->auth_data
= NULL
;
1056 pAuthInfo
->auth_data_len
= 0;
1057 pAuthInfo
->finished
= FALSE
;
1059 if (is_basic_auth_value(pszAuthValue
,NULL
))
1061 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1062 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1063 if (!pAuthInfo
->scheme
)
1065 heap_free(pAuthInfo
);
1072 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1074 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1075 if (!pAuthInfo
->scheme
)
1077 heap_free(pAuthInfo
);
1081 if (domain_and_username
)
1083 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1084 WCHAR
*domain
= domain_and_username
;
1086 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1088 pAuthData
= &nt_auth_identity
;
1093 user
= domain_and_username
;
1097 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1098 nt_auth_identity
.User
= user
;
1099 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1100 nt_auth_identity
.Domain
= domain
;
1101 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1102 nt_auth_identity
.Password
= password
;
1103 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1105 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1107 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1108 pAuthData
= &nt_auth_identity
;
1110 /* use default credentials */
1113 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1114 SECPKG_CRED_OUTBOUND
, NULL
,
1116 NULL
, &pAuthInfo
->cred
,
1119 if(pAuthData
&& !domain_and_username
) {
1120 heap_free(nt_auth_identity
.User
);
1121 heap_free(nt_auth_identity
.Domain
);
1122 heap_free(nt_auth_identity
.Password
);
1125 if (sec_status
== SEC_E_OK
)
1127 PSecPkgInfoW sec_pkg_info
;
1128 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1129 if (sec_status
== SEC_E_OK
)
1131 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1132 FreeContextBuffer(sec_pkg_info
);
1135 if (sec_status
!= SEC_E_OK
)
1137 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1138 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1139 heap_free(pAuthInfo
->scheme
);
1140 heap_free(pAuthInfo
);
1144 *ppAuthInfo
= pAuthInfo
;
1146 else if (pAuthInfo
->finished
)
1149 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1150 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1152 ERR("authentication scheme changed from %s to %s\n",
1153 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1157 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1161 char *auth_data
= NULL
;
1162 UINT auth_data_len
= 0;
1164 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1166 if (!domain_and_username
)
1168 if (host
&& szRealm
)
1169 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1170 if (auth_data_len
== 0)
1178 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1179 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1181 /* length includes a nul terminator, which will be re-used for the ':' */
1182 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1189 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1190 auth_data
[userlen
] = ':';
1191 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1192 auth_data_len
= userlen
+ 1 + passlen
;
1193 if (host
&& szRealm
)
1194 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1197 pAuthInfo
->auth_data
= auth_data
;
1198 pAuthInfo
->auth_data_len
= auth_data_len
;
1199 pAuthInfo
->finished
= TRUE
;
1205 LPCWSTR pszAuthData
;
1206 SecBufferDesc out_desc
, in_desc
;
1208 unsigned char *buffer
;
1209 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1210 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1212 in
.BufferType
= SECBUFFER_TOKEN
;
1216 in_desc
.ulVersion
= 0;
1217 in_desc
.cBuffers
= 1;
1218 in_desc
.pBuffers
= &in
;
1220 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1221 if (*pszAuthData
== ' ')
1224 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1225 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1226 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1229 buffer
= heap_alloc(pAuthInfo
->max_token
);
1231 out
.BufferType
= SECBUFFER_TOKEN
;
1232 out
.cbBuffer
= pAuthInfo
->max_token
;
1233 out
.pvBuffer
= buffer
;
1235 out_desc
.ulVersion
= 0;
1236 out_desc
.cBuffers
= 1;
1237 out_desc
.pBuffers
= &out
;
1239 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1240 first
? NULL
: &pAuthInfo
->ctx
,
1241 first
? request
->server
->name
: NULL
,
1242 context_req
, 0, SECURITY_NETWORK_DREP
,
1243 in
.pvBuffer
? &in_desc
: NULL
,
1244 0, &pAuthInfo
->ctx
, &out_desc
,
1245 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1246 if (sec_status
== SEC_E_OK
)
1248 pAuthInfo
->finished
= TRUE
;
1249 pAuthInfo
->auth_data
= out
.pvBuffer
;
1250 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1251 TRACE("sending last auth packet\n");
1253 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1255 pAuthInfo
->auth_data
= out
.pvBuffer
;
1256 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1257 TRACE("sending next auth packet\n");
1261 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1262 heap_free(out
.pvBuffer
);
1263 destroy_authinfo(pAuthInfo
);
1272 /***********************************************************************
1273 * HTTP_HttpAddRequestHeadersW (internal)
1275 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1276 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1281 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1283 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1285 if( dwHeaderLength
== ~0U )
1286 len
= strlenW(lpszHeader
);
1288 len
= dwHeaderLength
;
1289 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1290 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1296 LPWSTR
* pFieldAndValue
;
1298 lpszEnd
= lpszStart
;
1300 while (*lpszEnd
!= '\0')
1302 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1307 if (*lpszStart
== '\0')
1310 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1313 lpszEnd
++; /* Jump over newline */
1315 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1316 if (*lpszStart
== '\0')
1318 /* Skip 0-length headers */
1319 lpszStart
= lpszEnd
;
1320 res
= ERROR_SUCCESS
;
1323 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1326 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1327 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1328 HTTP_FreeTokens(pFieldAndValue
);
1331 lpszStart
= lpszEnd
;
1332 } while (res
== ERROR_SUCCESS
);
1338 /***********************************************************************
1339 * HttpAddRequestHeadersW (WININET.@)
1341 * Adds one or more HTTP header to the request handler
1344 * On Windows if dwHeaderLength includes the trailing '\0', then
1345 * HttpAddRequestHeadersW() adds it too. However this results in an
1346 * invalid HTTP header which is rejected by some servers so we probably
1347 * don't need to match Windows on that point.
1354 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1355 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1357 http_request_t
*request
;
1358 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1360 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1365 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1366 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1367 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1369 WININET_Release( &request
->hdr
);
1371 if(res
!= ERROR_SUCCESS
)
1373 return res
== ERROR_SUCCESS
;
1376 /***********************************************************************
1377 * HttpAddRequestHeadersA (WININET.@)
1379 * Adds one or more HTTP header to the request handler
1386 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1387 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1389 WCHAR
*headers
= NULL
;
1392 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1395 headers
= heap_strndupAtoW(lpszHeader
, dwHeaderLength
, &dwHeaderLength
);
1397 r
= HttpAddRequestHeadersW(hHttpRequest
, headers
, dwHeaderLength
, dwModifier
);
1403 static void free_accept_types( WCHAR
**accept_types
)
1405 WCHAR
*ptr
, **types
= accept_types
;
1408 while ((ptr
= *types
))
1413 heap_free( accept_types
);
1416 static WCHAR
**convert_accept_types( const char **accept_types
)
1419 const char **types
= accept_types
;
1421 BOOL invalid_pointer
= FALSE
;
1423 if (!types
) return NULL
;
1429 /* find out how many there are */
1430 if (*types
&& **types
)
1432 TRACE("accept type: %s\n", debugstr_a(*types
));
1438 WARN("invalid accept type pointer\n");
1439 invalid_pointer
= TRUE
;
1444 if (invalid_pointer
) return NULL
;
1445 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1447 types
= accept_types
;
1450 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1453 typesW
[count
] = NULL
;
1457 /***********************************************************************
1458 * HttpOpenRequestA (WININET.@)
1460 * Open a HTTP request handle
1463 * HINTERNET a HTTP request handle on success
1467 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1468 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1469 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1470 DWORD dwFlags
, DWORD_PTR dwContext
)
1472 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1473 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1474 HINTERNET rc
= NULL
;
1476 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1477 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1478 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1479 dwFlags
, dwContext
);
1483 szVerb
= heap_strdupAtoW(lpszVerb
);
1490 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1491 if ( !szObjectName
)
1497 szVersion
= heap_strdupAtoW(lpszVersion
);
1504 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1509 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1510 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1511 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1514 free_accept_types(szAcceptTypes
);
1515 heap_free(szReferrer
);
1516 heap_free(szVersion
);
1517 heap_free(szObjectName
);
1522 /***********************************************************************
1525 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1528 static const CHAR HTTP_Base64Enc
[] =
1529 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1533 /* first 6 bits, all from bin[0] */
1534 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1535 x
= (bin
[0] & 3) << 4;
1537 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1540 base64
[n
++] = HTTP_Base64Enc
[x
];
1545 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1546 x
= ( bin
[1] & 0x0f ) << 2;
1548 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1551 base64
[n
++] = HTTP_Base64Enc
[x
];
1555 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1557 /* last 6 bits, all from bin [2] */
1558 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1566 static const signed char HTTP_Base64Dec
[] =
1568 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1569 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1570 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1571 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1572 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1573 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1574 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1575 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1578 /***********************************************************************
1581 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1589 if (base64
[0] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1590 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1591 base64
[1] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1592 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1594 WARN("invalid base64: %s\n", debugstr_w(base64
));
1598 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1601 if ((base64
[2] == '=') && (base64
[3] == '='))
1603 if (base64
[2] > ARRAYSIZE(HTTP_Base64Dec
) ||
1604 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1606 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1610 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1613 if (base64
[3] == '=')
1615 if (base64
[3] > ARRAYSIZE(HTTP_Base64Dec
) ||
1616 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1618 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1622 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1631 static WCHAR
*encode_auth_data( const WCHAR
*scheme
, const char *data
, UINT data_len
)
1634 UINT len
, scheme_len
= strlenW( scheme
);
1636 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1637 len
= scheme_len
+ 1 + ((data_len
+ 2) * 4) / 3;
1638 if (!(ret
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1639 memcpy( ret
, scheme
, scheme_len
* sizeof(WCHAR
) );
1640 ret
[scheme_len
] = ' ';
1641 HTTP_EncodeBase64( data
, data_len
, ret
+ scheme_len
+ 1 );
1646 /***********************************************************************
1647 * HTTP_InsertAuthorization
1649 * Insert or delete the authorization field in the request header.
1651 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1653 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1654 WCHAR
*host
, *authorization
= NULL
;
1658 if (pAuthInfo
->auth_data_len
)
1660 if (!(authorization
= encode_auth_data(pAuthInfo
->scheme
, pAuthInfo
->auth_data
, pAuthInfo
->auth_data_len
)))
1663 /* clear the data as it isn't valid now that it has been sent to the
1664 * server, unless it's Basic authentication which doesn't do
1665 * connection tracking */
1666 if (strcmpiW(pAuthInfo
->scheme
, wszBasic
))
1668 heap_free(pAuthInfo
->auth_data
);
1669 pAuthInfo
->auth_data
= NULL
;
1670 pAuthInfo
->auth_data_len
= 0;
1674 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1676 HTTP_ProcessHeader(request
, header
, authorization
,
1677 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
1678 heap_free(authorization
);
1680 else if (!strcmpW(header
, szAuthorization
) && (host
= get_host_header(request
)))
1685 if ((data_len
= retrieve_cached_basic_authorization(host
, NULL
, &data
)))
1687 TRACE("Found cached basic authorization for %s\n", debugstr_w(host
));
1689 if (!(authorization
= encode_auth_data(wszBasic
, data
, data_len
)))
1696 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1698 HTTP_ProcessHeader(request
, header
, authorization
,
1699 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
1701 heap_free(authorization
);
1708 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1713 len
= strlenW(req
->server
->scheme_host_port
);
1714 size
= len
+ strlenW(req
->path
) + 1;
1715 if(*req
->path
!= '/')
1717 url
= heap_alloc(size
* sizeof(WCHAR
));
1721 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1722 if(*req
->path
!= '/')
1725 strcpyW(url
+len
, req
->path
);
1727 TRACE("url=%s\n", debugstr_w(url
));
1731 static BOOL
HTTP_DomainMatches(LPCWSTR server
, substr_t domain
)
1733 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1734 const WCHAR
*dot
, *ptr
;
1737 if(domain
.len
== sizeof(localW
)/sizeof(WCHAR
)-1 && !strncmpiW(domain
.str
, localW
, domain
.len
) && !strchrW(server
, '.' ))
1740 if(domain
.len
&& *domain
.str
!= '*')
1741 return domain
.len
== strlenW(server
) && !strncmpiW(server
, domain
.str
, domain
.len
);
1743 if(domain
.len
< 2 || domain
.str
[1] != '.')
1746 /* For a hostname to match a wildcard, the last domain must match
1747 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1748 * hostname is www.foo.a.b, it matches, but a.b does not.
1750 dot
= strchrW(server
, '.');
1754 len
= strlenW(dot
+ 1);
1755 if(len
< domain
.len
- 2)
1758 /* The server's domain is longer than the wildcard, so it
1759 * could be a subdomain. Compare the last portion of the
1762 ptr
= dot
+ 1 + len
- domain
.len
+ 2;
1763 if(!strncmpiW(ptr
, domain
.str
+2, domain
.len
-2))
1764 /* This is only a match if the preceding character is
1765 * a '.', i.e. that it is a matching domain. E.g.
1766 * if domain is '*.b.c' and server is 'www.ab.c' they
1769 return *(ptr
- 1) == '.';
1771 return len
== domain
.len
-2 && !strncmpiW(dot
+ 1, domain
.str
+ 2, len
);
1774 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1779 if (!lpwai
->proxyBypass
) return FALSE
;
1780 ptr
= lpwai
->proxyBypass
;
1784 ptr
= strchrW( ptr
, ';' );
1786 ptr
= strchrW( tmp
, ' ' );
1788 ptr
= tmp
+ strlenW(tmp
);
1789 ret
= HTTP_DomainMatches( server
, substr(tmp
, ptr
-tmp
) );
1797 /***********************************************************************
1798 * HTTP_DealWithProxy
1800 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1802 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1803 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1804 static WCHAR szNul
[] = { 0 };
1805 URL_COMPONENTSW UrlComponents
= { sizeof(UrlComponents
) };
1806 server_t
*new_server
= NULL
;
1809 proxy
= INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
);
1812 if(CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1813 proxy
, strlenW(szHttp
), szHttp
, strlenW(szHttp
))) {
1814 WCHAR
*proxy_url
= heap_alloc(strlenW(proxy
)*sizeof(WCHAR
) + sizeof(szHttp
));
1819 strcpyW(proxy_url
, szHttp
);
1820 strcatW(proxy_url
, proxy
);
1825 UrlComponents
.dwHostNameLength
= 1;
1826 if(InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) && UrlComponents
.dwHostNameLength
) {
1827 if( !request
->path
)
1828 request
->path
= szNul
;
1830 new_server
= get_server(substr(UrlComponents
.lpszHostName
, UrlComponents
.dwHostNameLength
),
1831 UrlComponents
.nPort
, UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
1837 request
->proxy
= new_server
;
1839 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1843 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1845 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1848 if(server
->addr_len
)
1849 return ERROR_SUCCESS
;
1851 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1852 INTERNET_STATUS_RESOLVING_NAME
,
1854 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1856 addr_len
= sizeof(server
->addr
);
1857 if (!GetAddress(server
->name
, server
->port
, (SOCKADDR
*)&server
->addr
, &addr_len
, server
->addr_str
))
1858 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1860 server
->addr_len
= addr_len
;
1861 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1862 INTERNET_STATUS_NAME_RESOLVED
,
1863 server
->addr_str
, strlen(server
->addr_str
)+1);
1865 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1866 return ERROR_SUCCESS
;
1869 static WCHAR
*compose_request_url(http_request_t
*req
)
1871 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1872 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1873 const WCHAR
*host
, *scheme
;
1877 host
= req
->server
->canon_host_port
;
1879 if (req
->server
->is_https
)
1884 len
= strlenW(scheme
) + strlenW(host
) + (req
->path
[0] != '/' ? 1 : 0) + strlenW(req
->path
);
1885 ptr
= buf
= heap_alloc((len
+1) * sizeof(WCHAR
));
1887 strcpyW(ptr
, scheme
);
1888 ptr
+= strlenW(ptr
);
1891 ptr
+= strlenW(ptr
);
1893 if(req
->path
[0] != '/')
1896 strcpyW(ptr
, req
->path
);
1897 ptr
+= strlenW(ptr
);
1905 /***********************************************************************
1906 * HTTPREQ_Destroy (internal)
1908 * Deallocate request handle
1911 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1913 http_request_t
*request
= (http_request_t
*) hdr
;
1918 if(request
->hCacheFile
)
1919 CloseHandle(request
->hCacheFile
);
1920 if(request
->req_file
)
1921 req_file_release(request
->req_file
);
1923 request
->headers_section
.DebugInfo
->Spare
[0] = 0;
1924 DeleteCriticalSection( &request
->headers_section
);
1925 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1926 DeleteCriticalSection( &request
->read_section
);
1927 WININET_Release(&request
->session
->hdr
);
1929 destroy_authinfo(request
->authInfo
);
1930 destroy_authinfo(request
->proxyAuthInfo
);
1933 server_release(request
->server
);
1935 server_release(request
->proxy
);
1937 heap_free(request
->path
);
1938 heap_free(request
->verb
);
1939 heap_free(request
->version
);
1940 heap_free(request
->statusText
);
1942 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1944 heap_free(request
->custHeaders
[i
].lpszField
);
1945 heap_free(request
->custHeaders
[i
].lpszValue
);
1947 destroy_data_stream(request
->data_stream
);
1948 heap_free(request
->custHeaders
);
1951 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1953 TRACE("%p %p %x\n",req
, req
->netconn
, reuse
);
1955 if(!is_valid_netconn(req
->netconn
))
1959 if(reuse
&& req
->netconn
->keep_alive
) {
1962 EnterCriticalSection(&connection_pool_cs
);
1964 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1965 req
->netconn
->keep_until
= (DWORD64
)GetTickCount() + COLLECT_TIME
;
1966 req
->netconn
= NULL
;
1968 run_collector
= !collector_running
;
1969 collector_running
= TRUE
;
1971 LeaveCriticalSection(&connection_pool_cs
);
1974 HANDLE thread
= NULL
;
1977 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
1979 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
1981 EnterCriticalSection(&connection_pool_cs
);
1982 collector_running
= FALSE
;
1983 LeaveCriticalSection(&connection_pool_cs
);
1986 FreeLibrary(module
);
1989 CloseHandle(thread
);
1994 /* Silence unused function warning */
1995 (void)collect_connections_proc
;
1998 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1999 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
2001 close_netconn(req
->netconn
);
2003 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
2004 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
2007 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
2009 WCHAR szVersion
[10];
2010 WCHAR szConnectionResponse
[20];
2011 DWORD dwBufferSize
= sizeof(szVersion
);
2012 BOOL keepalive
= FALSE
;
2014 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2015 * the connection is keep-alive by default */
2016 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2017 && !strcmpiW(szVersion
, g_szHttp1_1
))
2022 dwBufferSize
= sizeof(szConnectionResponse
);
2023 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2024 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
2026 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2032 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2034 http_request_t
*req
= (http_request_t
*)hdr
;
2036 http_release_netconn(req
, drain_content(req
, FALSE
) == ERROR_SUCCESS
);
2039 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2044 WCHAR
*buf
= buffer
;
2046 if (str
) len
= strlenW(str
);
2048 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2050 *size
= (len
+ 1) * sizeof(WCHAR
);
2051 return ERROR_INSUFFICIENT_BUFFER
;
2053 if (str
) strcpyW(buf
, str
);
2057 return ERROR_SUCCESS
;
2063 if (str
) len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
2068 return ERROR_INSUFFICIENT_BUFFER
;
2070 if (str
) WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, *size
, NULL
, NULL
);
2074 return ERROR_SUCCESS
;
2078 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2080 http_request_t
*req
= (http_request_t
*)hdr
;
2083 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2085 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2087 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2089 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2090 return ERROR_INSUFFICIENT_BUFFER
;
2091 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2092 /* FIXME: can't get a SOCKET from our connection since we don't use
2096 /* FIXME: get source port from req->netConnection */
2097 info
->SourcePort
= 0;
2098 info
->DestPort
= req
->server
->port
;
2100 if (HTTP_KeepAlive(req
))
2101 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2103 info
->Flags
|= IDSI_FLAG_PROXY
;
2104 if (is_valid_netconn(req
->netconn
) && req
->netconn
->secure
)
2105 info
->Flags
|= IDSI_FLAG_SECURE
;
2107 return ERROR_SUCCESS
;
2111 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2113 case INTERNET_OPTION_SECURITY_FLAGS
:
2117 if (*size
< sizeof(ULONG
))
2118 return ERROR_INSUFFICIENT_BUFFER
;
2120 *size
= sizeof(DWORD
);
2121 flags
= is_valid_netconn(req
->netconn
) ? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2122 *(DWORD
*)buffer
= flags
;
2124 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2125 return ERROR_SUCCESS
;
2128 case INTERNET_OPTION_HANDLE_TYPE
:
2129 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2131 if (*size
< sizeof(ULONG
))
2132 return ERROR_INSUFFICIENT_BUFFER
;
2134 *size
= sizeof(DWORD
);
2135 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2136 return ERROR_SUCCESS
;
2138 case INTERNET_OPTION_URL
: {
2142 TRACE("INTERNET_OPTION_URL\n");
2144 url
= compose_request_url(req
);
2146 return ERROR_OUTOFMEMORY
;
2148 res
= str_to_buffer(url
, buffer
, size
, unicode
);
2152 case INTERNET_OPTION_USER_AGENT
:
2153 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2154 case INTERNET_OPTION_USERNAME
:
2155 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2156 case INTERNET_OPTION_PASSWORD
:
2157 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2158 case INTERNET_OPTION_PROXY_USERNAME
:
2159 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2160 case INTERNET_OPTION_PROXY_PASSWORD
:
2161 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2163 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2164 INTERNET_CACHE_ENTRY_INFOW
*info
;
2165 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2166 DWORD nbytes
, error
;
2169 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2172 return ERROR_FILE_NOT_FOUND
;
2174 if (*size
< sizeof(*ts
))
2176 *size
= sizeof(*ts
);
2177 return ERROR_INSUFFICIENT_BUFFER
;
2181 ret
= GetUrlCacheEntryInfoW(req
->req_file
->url
, NULL
, &nbytes
);
2182 error
= GetLastError();
2183 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2185 if (!(info
= heap_alloc(nbytes
)))
2186 return ERROR_OUTOFMEMORY
;
2188 GetUrlCacheEntryInfoW(req
->req_file
->url
, info
, &nbytes
);
2190 ts
->ftExpires
= info
->ExpireTime
;
2191 ts
->ftLastModified
= info
->LastModifiedTime
;
2194 *size
= sizeof(*ts
);
2195 return ERROR_SUCCESS
;
2200 case INTERNET_OPTION_DATAFILE_NAME
: {
2203 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2205 if(!req
->req_file
) {
2207 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2211 req_size
= (lstrlenW(req
->req_file
->file_name
)+1) * sizeof(WCHAR
);
2212 if(*size
< req_size
)
2213 return ERROR_INSUFFICIENT_BUFFER
;
2216 memcpy(buffer
, req
->req_file
->file_name
, *size
);
2217 return ERROR_SUCCESS
;
2219 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
, -1, NULL
, 0, NULL
, NULL
);
2220 if (req_size
> *size
)
2221 return ERROR_INSUFFICIENT_BUFFER
;
2223 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
,
2224 -1, buffer
, *size
, NULL
, NULL
);
2225 return ERROR_SUCCESS
;
2229 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2230 PCCERT_CONTEXT context
;
2233 return ERROR_INTERNET_INVALID_OPERATION
;
2235 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2236 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2237 return ERROR_INSUFFICIENT_BUFFER
;
2240 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2242 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2245 memset(info
, 0, sizeof(*info
));
2246 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2247 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2248 len
= CertNameToStrA(context
->dwCertEncodingType
,
2249 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2250 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2251 if(info
->lpszSubjectInfo
)
2252 CertNameToStrA(context
->dwCertEncodingType
,
2253 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2254 info
->lpszSubjectInfo
, len
);
2255 len
= CertNameToStrA(context
->dwCertEncodingType
,
2256 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2257 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2258 if(info
->lpszIssuerInfo
)
2259 CertNameToStrA(context
->dwCertEncodingType
,
2260 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2261 info
->lpszIssuerInfo
, len
);
2262 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2263 CertFreeCertificateContext(context
);
2264 return ERROR_SUCCESS
;
2266 return ERROR_NOT_SUPPORTED
;
2268 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2269 if (*size
< sizeof(DWORD
))
2270 return ERROR_INSUFFICIENT_BUFFER
;
2272 *size
= sizeof(DWORD
);
2273 *(DWORD
*)buffer
= req
->connect_timeout
;
2274 return ERROR_SUCCESS
;
2275 case INTERNET_OPTION_REQUEST_FLAGS
: {
2278 if (*size
< sizeof(DWORD
))
2279 return ERROR_INSUFFICIENT_BUFFER
;
2281 /* FIXME: Add support for:
2282 * INTERNET_REQFLAG_FROM_CACHE
2283 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2287 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2288 if(!req
->status_code
)
2289 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2291 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2293 *size
= sizeof(DWORD
);
2294 *(DWORD
*)buffer
= flags
;
2295 return ERROR_SUCCESS
;
2299 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2302 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2304 http_request_t
*req
= (http_request_t
*)hdr
;
2307 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2308 TRACE("Undocumented option 99\n");
2310 if (!buffer
|| size
!= sizeof(DWORD
))
2311 return ERROR_INVALID_PARAMETER
;
2312 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2313 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2316 case INTERNET_OPTION_SECURITY_FLAGS
:
2320 if (!buffer
|| size
!= sizeof(DWORD
))
2321 return ERROR_INVALID_PARAMETER
;
2322 flags
= *(DWORD
*)buffer
;
2323 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2324 flags
&= SECURITY_SET_MASK
;
2325 req
->security_flags
|= flags
;
2326 if(is_valid_netconn(req
->netconn
))
2327 req
->netconn
->security_flags
|= flags
;
2328 return ERROR_SUCCESS
;
2330 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2331 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2332 req
->connect_timeout
= *(DWORD
*)buffer
;
2333 return ERROR_SUCCESS
;
2335 case INTERNET_OPTION_SEND_TIMEOUT
:
2336 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2337 req
->send_timeout
= *(DWORD
*)buffer
;
2338 return ERROR_SUCCESS
;
2340 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2341 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2342 req
->receive_timeout
= *(DWORD
*)buffer
;
2343 return ERROR_SUCCESS
;
2345 case INTERNET_OPTION_USERNAME
:
2346 heap_free(req
->session
->userName
);
2347 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2348 return ERROR_SUCCESS
;
2350 case INTERNET_OPTION_PASSWORD
:
2351 heap_free(req
->session
->password
);
2352 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2353 return ERROR_SUCCESS
;
2355 case INTERNET_OPTION_PROXY_USERNAME
:
2356 heap_free(req
->session
->appInfo
->proxyUsername
);
2357 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2358 return ERROR_SUCCESS
;
2360 case INTERNET_OPTION_PROXY_PASSWORD
:
2361 heap_free(req
->session
->appInfo
->proxyPassword
);
2362 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2363 return ERROR_SUCCESS
;
2367 return INET_SetOption(hdr
, option
, buffer
, size
);
2370 static void commit_cache_entry(http_request_t
*req
)
2378 CloseHandle(req
->hCacheFile
);
2379 req
->hCacheFile
= NULL
;
2381 header
= build_response_header(req
, TRUE
);
2382 header_len
= (header
? strlenW(header
) : 0);
2383 res
= CommitUrlCacheEntryW(req
->req_file
->url
, req
->req_file
->file_name
, req
->expires
,
2384 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2385 header
, header_len
, NULL
, 0);
2387 req
->req_file
->is_committed
= TRUE
;
2389 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2393 static void create_cache_entry(http_request_t
*req
)
2395 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2396 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2398 WCHAR file_name
[MAX_PATH
+1];
2402 /* FIXME: We should free previous cache file earlier */
2404 req_file_release(req
->req_file
);
2405 req
->req_file
= NULL
;
2407 if(req
->hCacheFile
) {
2408 CloseHandle(req
->hCacheFile
);
2409 req
->hCacheFile
= NULL
;
2412 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2418 EnterCriticalSection( &req
->headers_section
);
2420 header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2421 if(header_idx
!= -1) {
2424 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2427 while(*ptr
==' ' || *ptr
=='\t')
2430 end
= strchrW(ptr
, ',');
2432 end
= ptr
+ strlenW(ptr
);
2434 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2435 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2446 LeaveCriticalSection( &req
->headers_section
);
2450 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2453 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2456 url
= compose_request_url(req
);
2458 WARN("Could not get URL\n");
2462 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2464 WARN("Could not create cache entry: %08x\n", GetLastError());
2468 create_req_file(file_name
, &req
->req_file
);
2469 req
->req_file
->url
= url
;
2471 req
->hCacheFile
= CreateFileW(file_name
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2472 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2473 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2474 WARN("Could not create file: %u\n", GetLastError());
2475 req
->hCacheFile
= NULL
;
2479 if(req
->read_size
) {
2482 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2484 FIXME("WriteFile failed: %u\n", GetLastError());
2486 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2487 commit_cache_entry(req
);
2491 /* read some more data into the read buffer (the read section must be held) */
2492 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2499 /* move existing data to the start of the buffer */
2501 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2505 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2507 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2508 maxlen
- req
->read_size
, TRUE
, &len
);
2509 if(res
== ERROR_SUCCESS
)
2510 req
->read_size
+= len
;
2515 /* remove some amount of data from the read buffer (the read section must be held) */
2516 static void remove_data( http_request_t
*req
, int count
)
2518 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2519 else req
->read_pos
+= count
;
2522 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2524 int count
, bytes_read
, pos
= 0;
2527 EnterCriticalSection( &req
->read_section
);
2530 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2534 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2535 bytes_read
= count
+ 1;
2537 else count
= bytes_read
= req
->read_size
;
2539 count
= min( count
, *len
- pos
);
2540 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2542 remove_data( req
, bytes_read
);
2545 if ((res
= read_more_data( req
, -1 )))
2547 WARN( "read failed %u\n", res
);
2548 LeaveCriticalSection( &req
->read_section
);
2551 if (!req
->read_size
)
2554 TRACE( "returning empty string\n" );
2555 LeaveCriticalSection( &req
->read_section
);
2556 return ERROR_SUCCESS
;
2559 LeaveCriticalSection( &req
->read_section
);
2563 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2566 buffer
[*len
- 1] = 0;
2567 TRACE( "returning %s\n", debugstr_a(buffer
));
2568 return ERROR_SUCCESS
;
2571 /* check if we have reached the end of the data to read (the read section must be held) */
2572 static BOOL
end_of_read_data( http_request_t
*req
)
2574 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2577 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, BOOL allow_blocking
)
2581 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, allow_blocking
);
2582 if(res
!= ERROR_SUCCESS
)
2584 assert(*read
<= size
);
2586 if(req
->hCacheFile
) {
2591 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2593 FIXME("WriteFile failed: %u\n", GetLastError());
2596 if((res
== ERROR_SUCCESS
&& !*read
) || req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2597 commit_cache_entry(req
);
2603 /* fetch some more data into the read buffer (the read section must be held) */
2604 static DWORD
refill_read_buffer(http_request_t
*req
, BOOL allow_blocking
, DWORD
*read_bytes
)
2608 if(req
->read_size
== sizeof(req
->read_buf
))
2609 return ERROR_SUCCESS
;
2613 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2617 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2618 &read
, allow_blocking
);
2619 if(res
!= ERROR_SUCCESS
)
2622 req
->read_size
+= read
;
2624 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2630 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2632 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2633 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !is_valid_netconn(req
->netconn
);
2636 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2637 DWORD
*read
, BOOL allow_blocking
)
2639 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2640 DWORD res
= ERROR_SUCCESS
;
2643 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2645 if(size
&& is_valid_netconn(req
->netconn
)) {
2646 res
= NETCON_recv(req
->netconn
, buf
, size
, allow_blocking
, &ret
);
2647 if(res
== ERROR_SUCCESS
) {
2649 netconn_stream
->content_length
= netconn_stream
->content_read
;
2650 netconn_stream
->content_read
+= ret
;
2654 TRACE("res %u read %u bytes\n", res
, ret
);
2659 static DWORD
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
, BOOL allow_blocking
)
2661 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2666 if(netconn_stream
->content_length
== ~0u)
2669 while(netconn_stream
->content_read
< netconn_stream
->content_length
) {
2670 size
= min(sizeof(buf
), netconn_stream
->content_length
-netconn_stream
->content_read
);
2671 res
= NETCON_recv(req
->netconn
, buf
, size
, allow_blocking
, &len
);
2675 return WSAECONNABORTED
;
2677 netconn_stream
->content_read
+= len
;
2680 return ERROR_SUCCESS
;
2683 static void netconn_destroy(data_stream_t
*stream
)
2687 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2688 netconn_end_of_data
,
2690 netconn_drain_content
,
2694 static char next_chunked_data_char(chunked_stream_t
*stream
)
2696 assert(stream
->buf_size
);
2699 return stream
->buf
[stream
->buf_pos
++];
2702 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2704 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2705 switch(chunked_stream
->state
) {
2706 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2707 case CHUNKED_STREAM_STATE_END_OF_STREAM
:
2708 case CHUNKED_STREAM_STATE_ERROR
:
2715 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2716 DWORD
*read
, BOOL allow_blocking
)
2718 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2719 DWORD ret_read
= 0, res
= ERROR_SUCCESS
;
2720 BOOL continue_read
= TRUE
;
2725 TRACE("state %d\n", chunked_stream
->state
);
2727 /* Ensure that we have data in the buffer for states that need it. */
2728 if(!chunked_stream
->buf_size
) {
2729 BOOL blocking_read
= allow_blocking
;
2731 switch(chunked_stream
->state
) {
2732 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2733 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
:
2734 /* never allow blocking after 0 chunk size */
2735 if(!chunked_stream
->chunk_size
)
2736 blocking_read
= FALSE
;
2738 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
:
2739 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
:
2740 chunked_stream
->buf_pos
= 0;
2741 res
= NETCON_recv(req
->netconn
, chunked_stream
->buf
, sizeof(chunked_stream
->buf
), blocking_read
, &read_bytes
);
2742 if(res
== ERROR_SUCCESS
&& read_bytes
) {
2743 chunked_stream
->buf_size
+= read_bytes
;
2744 }else if(res
== WSAEWOULDBLOCK
) {
2745 if(ret_read
|| allow_blocking
)
2746 res
= ERROR_SUCCESS
;
2747 continue_read
= FALSE
;
2750 chunked_stream
->state
= CHUNKED_STREAM_STATE_ERROR
;
2758 switch(chunked_stream
->state
) {
2759 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
:
2760 ch
= next_chunked_data_char(chunked_stream
);
2762 if(ch
>= '0' && ch
<= '9') {
2763 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- '0';
2764 }else if(ch
>= 'a' && ch
<= 'f') {
2765 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- 'a' + 10;
2766 }else if (ch
>= 'A' && ch
<= 'F') {
2767 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- 'A' + 10;
2768 }else if (ch
== ';' || ch
== '\r' || ch
== '\n') {
2769 TRACE("reading %u byte chunk\n", chunked_stream
->chunk_size
);
2770 chunked_stream
->buf_size
++;
2771 chunked_stream
->buf_pos
--;
2772 if(req
->contentLength
== ~0u) req
->contentLength
= chunked_stream
->chunk_size
;
2773 else req
->contentLength
+= chunked_stream
->chunk_size
;
2774 chunked_stream
->state
= CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
;
2778 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
:
2779 ch
= next_chunked_data_char(chunked_stream
);
2781 chunked_stream
->state
= chunked_stream
->chunk_size
2782 ? CHUNKED_STREAM_STATE_READING_CHUNK
2783 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
;
2785 WARN("unexpected char '%c'\n", ch
);
2788 case CHUNKED_STREAM_STATE_READING_CHUNK
:
2789 assert(chunked_stream
->chunk_size
);
2791 continue_read
= FALSE
;
2794 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2796 if(chunked_stream
->buf_size
) {
2797 if(read_bytes
> chunked_stream
->buf_size
)
2798 read_bytes
= chunked_stream
->buf_size
;
2800 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2801 chunked_stream
->buf_pos
+= read_bytes
;
2802 chunked_stream
->buf_size
-= read_bytes
;
2804 res
= NETCON_recv(req
->netconn
, (char*)buf
+ret_read
, read_bytes
,
2805 allow_blocking
, (int*)&read_bytes
);
2806 if(res
!= ERROR_SUCCESS
) {
2807 continue_read
= FALSE
;
2812 chunked_stream
->state
= CHUNKED_STREAM_STATE_ERROR
;
2817 chunked_stream
->chunk_size
-= read_bytes
;
2819 ret_read
+= read_bytes
;
2820 if(!chunked_stream
->chunk_size
)
2821 chunked_stream
->state
= CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
;
2822 allow_blocking
= FALSE
;
2825 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
:
2826 ch
= next_chunked_data_char(chunked_stream
);
2828 chunked_stream
->state
= CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
;
2830 WARN("unexpected char '%c'\n", ch
);
2833 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2834 ch
= next_chunked_data_char(chunked_stream
);
2836 chunked_stream
->state
= CHUNKED_STREAM_STATE_END_OF_STREAM
;
2838 WARN("unexpected char '%c'\n", ch
);
2841 case CHUNKED_STREAM_STATE_END_OF_STREAM
:
2842 case CHUNKED_STREAM_STATE_ERROR
:
2843 continue_read
= FALSE
;
2846 } while(continue_read
);
2849 res
= ERROR_SUCCESS
;
2850 if(res
!= ERROR_SUCCESS
)
2853 TRACE("read %d bytes\n", ret_read
);
2855 return ERROR_SUCCESS
;
2858 static DWORD
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
, BOOL allow_blocking
)
2860 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2864 while(chunked_stream
->state
!= CHUNKED_STREAM_STATE_END_OF_STREAM
2865 && chunked_stream
->state
!= CHUNKED_STREAM_STATE_ERROR
) {
2866 res
= chunked_read(stream
, req
, buf
, sizeof(buf
), &size
, allow_blocking
);
2867 if(res
!= ERROR_SUCCESS
)
2871 if(chunked_stream
->state
!= CHUNKED_STREAM_STATE_END_OF_STREAM
)
2872 return ERROR_NO_DATA
;
2873 return ERROR_SUCCESS
;
2876 static void chunked_destroy(data_stream_t
*stream
)
2878 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2879 heap_free(chunked_stream
);
2882 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2883 chunked_end_of_data
,
2885 chunked_drain_content
,
2889 /* set the request content length based on the headers */
2890 static DWORD
set_content_length(http_request_t
*request
)
2892 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2893 static const WCHAR headW
[] = {'H','E','A','D',0};
2897 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
|| !strcmpW(request
->verb
, headW
)) {
2898 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2899 return ERROR_SUCCESS
;
2902 size
= sizeof(request
->contentLength
);
2903 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2904 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2905 request
->contentLength
= ~0u;
2906 request
->netconn_stream
.content_length
= request
->contentLength
;
2907 request
->netconn_stream
.content_read
= request
->read_size
;
2909 size
= sizeof(encoding
);
2910 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2911 !strcmpiW(encoding
, szChunked
))
2913 chunked_stream_t
*chunked_stream
;
2915 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2917 return ERROR_OUTOFMEMORY
;
2919 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2920 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2921 chunked_stream
->chunk_size
= 0;
2922 chunked_stream
->state
= CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
;
2924 if(request
->read_size
) {
2925 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2926 chunked_stream
->buf_size
= request
->read_size
;
2927 request
->read_size
= request
->read_pos
= 0;
2930 request
->data_stream
= &chunked_stream
->data_stream
;
2931 request
->contentLength
= ~0u;
2934 if(request
->hdr
.decoding
) {
2937 static const WCHAR deflateW
[] = {'d','e','f','l','a','t','e',0};
2938 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2940 EnterCriticalSection( &request
->headers_section
);
2942 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2943 if(encoding_idx
!= -1) {
2944 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2945 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2946 LeaveCriticalSection( &request
->headers_section
);
2947 return init_gzip_stream(request
, TRUE
);
2949 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, deflateW
)) {
2950 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2951 LeaveCriticalSection( &request
->headers_section
);
2952 return init_gzip_stream(request
, FALSE
);
2956 LeaveCriticalSection( &request
->headers_section
);
2959 return ERROR_SUCCESS
;
2962 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
2964 INTERNET_ASYNC_RESULT iar
;
2966 iar
.dwResult
= result
;
2967 iar
.dwError
= error
;
2969 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
2970 sizeof(INTERNET_ASYNC_RESULT
));
2973 static void HTTP_ReceiveRequestData(http_request_t
*req
)
2975 DWORD res
, read
= 0;
2979 EnterCriticalSection( &req
->read_section
);
2981 res
= refill_read_buffer(req
, FALSE
, &read
);
2982 if(res
== ERROR_SUCCESS
)
2983 read
+= req
->read_size
;
2985 LeaveCriticalSection( &req
->read_section
);
2987 if(res
!= WSAEWOULDBLOCK
&& (res
!= ERROR_SUCCESS
|| !read
)) {
2988 WARN("res %u read %u, closing connection\n", res
, read
);
2989 http_release_netconn(req
, FALSE
);
2992 if(res
!= ERROR_SUCCESS
&& res
!= WSAEWOULDBLOCK
) {
2993 send_request_complete(req
, 0, res
);
2997 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, 0);
3000 /* read data from the http connection (the read section must be held) */
3001 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
, BOOL allow_blocking
)
3003 DWORD current_read
= 0, ret_read
= 0;
3004 DWORD res
= ERROR_SUCCESS
;
3006 EnterCriticalSection( &req
->read_section
);
3008 if(req
->read_size
) {
3009 ret_read
= min(size
, req
->read_size
);
3010 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
3011 req
->read_size
-= ret_read
;
3012 req
->read_pos
+= ret_read
;
3013 allow_blocking
= FALSE
;
3016 if(ret_read
< size
) {
3017 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, allow_blocking
);
3018 if(res
== ERROR_SUCCESS
)
3019 ret_read
+= current_read
;
3020 else if(res
== WSAEWOULDBLOCK
&& ret_read
)
3021 res
= ERROR_SUCCESS
;
3024 LeaveCriticalSection( &req
->read_section
);
3027 TRACE( "retrieved %u bytes (res %u)\n", ret_read
, res
);
3029 if(res
!= WSAEWOULDBLOCK
) {
3030 if(res
!= ERROR_SUCCESS
)
3031 http_release_netconn(req
, FALSE
);
3032 else if(!ret_read
&& drain_content(req
, FALSE
) == ERROR_SUCCESS
)
3033 http_release_netconn(req
, TRUE
);
3039 static DWORD
drain_content(http_request_t
*req
, BOOL blocking
)
3043 TRACE("%p\n", req
->netconn
);
3045 if(!is_valid_netconn(req
->netconn
))
3046 return ERROR_NO_DATA
;
3048 if(!strcmpW(req
->verb
, szHEAD
))
3049 return ERROR_SUCCESS
;
3051 EnterCriticalSection( &req
->read_section
);
3052 res
= req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
, blocking
);
3053 LeaveCriticalSection( &req
->read_section
);
3065 static void async_read_file_proc(task_header_t
*hdr
)
3067 read_file_task_t
*task
= (read_file_task_t
*)hdr
;
3068 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3069 DWORD res
= ERROR_SUCCESS
, read
= task
->read_pos
, complete_arg
= 0;
3071 TRACE("req %p buf %p size %u read_pos %u ret_read %p\n", req
, task
->buf
, task
->size
, task
->read_pos
, task
->ret_read
);
3075 while (read
< task
->size
) {
3076 res
= HTTPREQ_Read(req
, (char*)task
->buf
+ read
, task
->size
- read
, &read_bytes
, TRUE
);
3077 if (res
!= ERROR_SUCCESS
|| !read_bytes
)
3082 EnterCriticalSection(&req
->read_section
);
3083 res
= refill_read_buffer(req
, TRUE
, &read
);
3084 LeaveCriticalSection(&req
->read_section
);
3087 complete_arg
= read
; /* QueryDataAvailable reports read bytes in request complete notification */
3088 if(res
!= ERROR_SUCCESS
|| !read
)
3089 http_release_netconn(req
, drain_content(req
, FALSE
) == ERROR_SUCCESS
);
3092 TRACE("res %u read %u\n", res
, read
);
3095 *task
->ret_read
= read
;
3097 /* FIXME: We should report bytes transferred before decoding content. */
3098 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
, &read
, sizeof(read
));
3100 if(res
!= ERROR_SUCCESS
)
3102 send_request_complete(req
, res
== ERROR_SUCCESS
, complete_arg
);
3105 static DWORD
async_read(http_request_t
*req
, void *buf
, DWORD size
, DWORD read_pos
, DWORD
*ret_read
)
3107 read_file_task_t
*task
;
3109 task
= alloc_async_task(&req
->hdr
, async_read_file_proc
, sizeof(*task
));
3111 return ERROR_OUTOFMEMORY
;
3115 task
->read_pos
= read_pos
;
3116 task
->ret_read
= ret_read
;
3118 INTERNET_AsyncCall(&task
->hdr
);
3119 return ERROR_IO_PENDING
;
3122 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3123 DWORD flags
, DWORD_PTR context
)
3125 http_request_t
*req
= (http_request_t
*)hdr
;
3126 DWORD res
= ERROR_SUCCESS
, read
= 0, cread
, error
= ERROR_SUCCESS
;
3127 BOOL allow_blocking
, notify_received
= FALSE
;
3129 TRACE("(%p %p %u %x)\n", req
, buf
, size
, flags
);
3131 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3132 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3134 allow_blocking
= !(req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
);
3136 if(allow_blocking
|| TryEnterCriticalSection(&req
->read_section
)) {
3138 EnterCriticalSection(&req
->read_section
);
3139 if(hdr
->dwError
== ERROR_SUCCESS
)
3140 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3141 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3142 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3144 if(req
->read_size
) {
3145 read
= min(size
, req
->read_size
);
3146 memcpy(buf
, req
->read_buf
+ req
->read_pos
, read
);
3147 req
->read_size
-= read
;
3148 req
->read_pos
+= read
;
3151 if(read
< size
&& (!read
|| !(flags
& IRF_NO_WAIT
)) && !end_of_read_data(req
)) {
3152 LeaveCriticalSection(&req
->read_section
);
3153 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3154 EnterCriticalSection( &req
->read_section
);
3155 notify_received
= TRUE
;
3157 while(read
< size
) {
3158 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
, allow_blocking
);
3160 if (res
!= ERROR_SUCCESS
|| !cread
)
3165 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3166 hdr
->dwError
= ERROR_SUCCESS
;
3168 error
= hdr
->dwError
;
3170 LeaveCriticalSection( &req
->read_section
);
3172 res
= WSAEWOULDBLOCK
;
3175 if(res
== WSAEWOULDBLOCK
) {
3176 if(!(flags
& IRF_NO_WAIT
))
3177 return async_read(req
, buf
, size
, read
, ret_read
);
3179 return async_read(req
, NULL
, 0, 0, NULL
);
3180 res
= ERROR_SUCCESS
;
3184 if (res
!= ERROR_SUCCESS
)
3188 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3189 &read
, sizeof(read
));
3193 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3196 http_request_t
*request
= (http_request_t
*)hdr
;
3198 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3201 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3202 if (res
== ERROR_SUCCESS
)
3203 request
->bytesWritten
+= *written
;
3205 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3209 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3211 http_request_t
*req
= (http_request_t
*)hdr
;
3212 DWORD res
= ERROR_SUCCESS
, avail
= 0, error
= ERROR_SUCCESS
;
3213 BOOL allow_blocking
, notify_received
= FALSE
;
3215 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3217 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3218 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3221 allow_blocking
= !(req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
);
3223 if(allow_blocking
|| TryEnterCriticalSection(&req
->read_section
)) {
3225 EnterCriticalSection(&req
->read_section
);
3226 if(hdr
->dwError
== ERROR_SUCCESS
)
3227 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3228 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3229 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3231 avail
= req
->read_size
;
3233 if(!avail
&& !end_of_read_data(req
)) {
3234 LeaveCriticalSection(&req
->read_section
);
3235 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3236 EnterCriticalSection( &req
->read_section
);
3237 notify_received
= TRUE
;
3239 res
= refill_read_buffer(req
, allow_blocking
, &avail
);
3242 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3243 hdr
->dwError
= ERROR_SUCCESS
;
3245 error
= hdr
->dwError
;
3247 LeaveCriticalSection( &req
->read_section
);
3249 res
= WSAEWOULDBLOCK
;
3252 if(res
== WSAEWOULDBLOCK
)
3253 return async_read(req
, NULL
, 0, 0, available
);
3255 if (res
!= ERROR_SUCCESS
)
3260 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3261 &avail
, sizeof(avail
));
3265 static DWORD
HTTPREQ_LockRequestFile(object_header_t
*hdr
, req_file_t
**ret
)
3267 http_request_t
*req
= (http_request_t
*)hdr
;
3269 TRACE("(%p)\n", req
);
3271 if(!req
->req_file
) {
3272 WARN("No cache file name available\n");
3273 return ERROR_FILE_NOT_FOUND
;
3276 *ret
= req_file_addref(req
->req_file
);
3277 return ERROR_SUCCESS
;
3280 static const object_vtbl_t HTTPREQVtbl
= {
3282 HTTPREQ_CloseConnection
,
3283 HTTPREQ_QueryOption
,
3287 HTTPREQ_QueryDataAvailable
,
3289 HTTPREQ_LockRequestFile
3292 /***********************************************************************
3293 * HTTP_HttpOpenRequestW (internal)
3295 * Open a HTTP request handle
3298 * HINTERNET a HTTP request handle on success
3302 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3303 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3304 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3305 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3307 appinfo_t
*hIC
= session
->appInfo
;
3308 http_request_t
*request
;
3313 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3315 return ERROR_OUTOFMEMORY
;
3317 request
->hdr
.htype
= WH_HHTTPREQ
;
3318 request
->hdr
.dwFlags
= dwFlags
;
3319 request
->hdr
.dwContext
= dwContext
;
3320 request
->hdr
.decoding
= session
->hdr
.decoding
;
3321 request
->contentLength
= ~0u;
3323 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3324 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3325 request
->connect_timeout
= session
->connect_timeout
;
3326 request
->send_timeout
= session
->send_timeout
;
3327 request
->receive_timeout
= session
->receive_timeout
;
3329 InitializeCriticalSection( &request
->headers_section
);
3330 request
->headers_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.headers_section");
3332 InitializeCriticalSection( &request
->read_section
);
3333 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3335 WININET_AddRef( &session
->hdr
);
3336 request
->session
= session
;
3337 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3339 port
= session
->hostPort
;
3340 if (port
== INTERNET_INVALID_PORT_NUMBER
)
3341 port
= (session
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ?
3342 INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
;
3344 request
->server
= get_server(substrz(session
->hostName
), port
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3345 if(!request
->server
) {
3346 WININET_Release(&request
->hdr
);
3347 return ERROR_OUTOFMEMORY
;
3350 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3351 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3352 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3353 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3355 if (lpszObjectName
&& *lpszObjectName
) {
3360 rc
= UrlCanonicalizeW(lpszObjectName
, &dummy
, &len
, URL_ESCAPE_SPACES_ONLY
);
3361 if (rc
!= E_POINTER
)
3362 len
= strlenW(lpszObjectName
)+1;
3363 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3364 rc
= UrlCanonicalizeW(lpszObjectName
, request
->path
, &len
,
3365 URL_ESCAPE_SPACES_ONLY
);
3368 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3369 strcpyW(request
->path
,lpszObjectName
);
3372 static const WCHAR slashW
[] = {'/',0};
3374 request
->path
= heap_strdupW(slashW
);
3377 if (lpszReferrer
&& *lpszReferrer
)
3378 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3380 if (lpszAcceptTypes
)
3383 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3385 if (!*lpszAcceptTypes
[i
]) continue;
3386 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3387 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3388 HTTP_ADDHDR_FLAG_REQ
|
3389 (i
== 0 ? (HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
) : 0));
3393 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3394 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3396 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3397 HTTP_DealWithProxy( hIC
, session
, request
);
3399 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3400 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3403 TRACE("<-- (%p)\n", request
);
3405 *ret
= request
->hdr
.hInternet
;
3406 return ERROR_SUCCESS
;
3409 /***********************************************************************
3410 * HttpOpenRequestW (WININET.@)
3412 * Open a HTTP request handle
3415 * HINTERNET a HTTP request handle on success
3419 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3420 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3421 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3422 DWORD dwFlags
, DWORD_PTR dwContext
)
3424 http_session_t
*session
;
3425 HINTERNET handle
= NULL
;
3428 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3429 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3430 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3431 dwFlags
, dwContext
);
3432 if(lpszAcceptTypes
!=NULL
)
3435 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3436 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3439 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3440 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3442 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3447 * My tests seem to show that the windows version does not
3448 * become asynchronous until after this point. And anyhow
3449 * if this call was asynchronous then how would you get the
3450 * necessary HINTERNET pointer returned by this function.
3453 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3454 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3455 dwFlags
, dwContext
, &handle
);
3458 WININET_Release( &session
->hdr
);
3459 TRACE("returning %p\n", handle
);
3460 if(res
!= ERROR_SUCCESS
)
3465 static const LPCWSTR header_lookup
[] = {
3466 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3467 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3468 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3469 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3470 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3471 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3472 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3473 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3474 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3475 szDate
, /* HTTP_QUERY_DATE = 9 */
3476 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3477 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3478 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3479 szURI
, /* HTTP_QUERY_URI = 13 */
3480 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3481 NULL
, /* HTTP_QUERY_COST = 15 */
3482 NULL
, /* HTTP_QUERY_LINK = 16 */
3483 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3484 NULL
, /* HTTP_QUERY_VERSION = 18 */
3485 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3486 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3487 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3488 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3489 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3490 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3491 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3492 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3493 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3494 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3495 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3496 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3497 NULL
, /* HTTP_QUERY_FROM = 31 */
3498 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3499 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3500 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3501 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3502 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3503 szServer
, /* HTTP_QUERY_SERVER = 37 */
3504 NULL
, /* HTTP_TITLE = 38 */
3505 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3506 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3507 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3508 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3509 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3510 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3511 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3512 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3513 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3514 szAge
, /* HTTP_QUERY_AGE = 48 */
3515 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3516 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3517 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3518 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3519 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3520 szETag
, /* HTTP_QUERY_ETAG = 54 */
3521 hostW
, /* HTTP_QUERY_HOST = 55 */
3522 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3523 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3524 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3525 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3526 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3527 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3528 szRange
, /* HTTP_QUERY_RANGE = 62 */
3529 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3530 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3531 szVary
, /* HTTP_QUERY_VARY = 65 */
3532 szVia
, /* HTTP_QUERY_VIA = 66 */
3533 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3534 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3535 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3536 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3539 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3541 /***********************************************************************
3542 * HTTP_HttpQueryInfoW (internal)
3544 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3545 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3547 LPHTTPHEADERW lphttpHdr
= NULL
;
3548 BOOL request_only
= !!(dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
);
3549 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3550 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3553 EnterCriticalSection( &request
->headers_section
);
3555 /* Find requested header structure */
3558 case HTTP_QUERY_CUSTOM
:
3561 LeaveCriticalSection( &request
->headers_section
);
3562 return ERROR_INVALID_PARAMETER
;
3564 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3566 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3570 DWORD res
= ERROR_INVALID_PARAMETER
;
3573 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3575 headers
= build_response_header(request
, TRUE
);
3578 LeaveCriticalSection( &request
->headers_section
);
3579 return ERROR_OUTOFMEMORY
;
3582 len
= strlenW(headers
) * sizeof(WCHAR
);
3583 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3585 len
+= sizeof(WCHAR
);
3586 res
= ERROR_INSUFFICIENT_BUFFER
;
3590 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3591 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3592 res
= ERROR_SUCCESS
;
3594 *lpdwBufferLength
= len
;
3597 LeaveCriticalSection( &request
->headers_section
);
3600 case HTTP_QUERY_RAW_HEADERS
:
3606 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3608 headers
= build_response_header(request
, FALSE
);
3612 LeaveCriticalSection( &request
->headers_section
);
3613 return ERROR_OUTOFMEMORY
;
3616 len
= strlenW(headers
) * sizeof(WCHAR
);
3617 if (len
> *lpdwBufferLength
)
3619 *lpdwBufferLength
= len
;
3621 LeaveCriticalSection( &request
->headers_section
);
3622 return ERROR_INSUFFICIENT_BUFFER
;
3629 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3631 for (i
= 0; i
< len
/ sizeof(WCHAR
); i
++)
3633 if (headers
[i
] == '\n')
3636 memcpy(lpBuffer
, headers
, len
);
3638 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3641 LeaveCriticalSection( &request
->headers_section
);
3642 return ERROR_SUCCESS
;
3644 case HTTP_QUERY_STATUS_TEXT
:
3645 if (request
->statusText
)
3647 DWORD len
= strlenW(request
->statusText
);
3648 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3650 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3651 LeaveCriticalSection( &request
->headers_section
);
3652 return ERROR_INSUFFICIENT_BUFFER
;
3656 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3657 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3659 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3660 LeaveCriticalSection( &request
->headers_section
);
3661 return ERROR_SUCCESS
;
3664 case HTTP_QUERY_VERSION
:
3665 if (request
->version
)
3667 DWORD len
= strlenW(request
->version
);
3668 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3670 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3671 LeaveCriticalSection( &request
->headers_section
);
3672 return ERROR_INSUFFICIENT_BUFFER
;
3676 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3677 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3679 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3680 LeaveCriticalSection( &request
->headers_section
);
3681 return ERROR_SUCCESS
;
3684 case HTTP_QUERY_CONTENT_ENCODING
:
3685 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3686 requested_index
,request_only
);
3688 case HTTP_QUERY_STATUS_CODE
: {
3689 DWORD res
= ERROR_SUCCESS
;
3693 LeaveCriticalSection( &request
->headers_section
);
3694 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3700 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3701 if(*lpdwBufferLength
>= sizeof(DWORD
))
3702 *(DWORD
*)lpBuffer
= request
->status_code
;
3704 res
= ERROR_INSUFFICIENT_BUFFER
;
3705 *lpdwBufferLength
= sizeof(DWORD
);
3709 static const WCHAR formatW
[] = {'%','u',0};
3711 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3713 if(size
<= *lpdwBufferLength
) {
3714 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3716 size
+= sizeof(WCHAR
);
3717 res
= ERROR_INSUFFICIENT_BUFFER
;
3720 *lpdwBufferLength
= size
;
3722 LeaveCriticalSection( &request
->headers_section
);
3726 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3728 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3729 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3730 requested_index
,request_only
);
3734 lphttpHdr
= &request
->custHeaders
[index
];
3736 /* Ensure header satisfies requested attributes */
3738 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3739 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3741 LeaveCriticalSection( &request
->headers_section
);
3742 return ERROR_HTTP_HEADER_NOT_FOUND
;
3745 /* coalesce value to requested type */
3746 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3748 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3749 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3751 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3757 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3759 tmpTM
= *gmtime(&tmpTime
);
3760 STHook
= (SYSTEMTIME
*)lpBuffer
;
3761 STHook
->wDay
= tmpTM
.tm_mday
;
3762 STHook
->wHour
= tmpTM
.tm_hour
;
3763 STHook
->wMilliseconds
= 0;
3764 STHook
->wMinute
= tmpTM
.tm_min
;
3765 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3766 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3767 STHook
->wSecond
= tmpTM
.tm_sec
;
3768 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3770 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3771 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3772 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3774 else if (lphttpHdr
->lpszValue
)
3776 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3778 if (len
> *lpdwBufferLength
)
3780 *lpdwBufferLength
= len
;
3781 LeaveCriticalSection( &request
->headers_section
);
3782 return ERROR_INSUFFICIENT_BUFFER
;
3786 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3787 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3789 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3791 if (lpdwIndex
) (*lpdwIndex
)++;
3793 LeaveCriticalSection( &request
->headers_section
);
3794 return ERROR_SUCCESS
;
3797 /***********************************************************************
3798 * HttpQueryInfoW (WININET.@)
3800 * Queries for information about an HTTP request
3807 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3808 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3810 http_request_t
*request
;
3813 if (TRACE_ON(wininet
)) {
3814 #define FE(x) { x, #x }
3815 static const wininet_flag_info query_flags
[] = {
3816 FE(HTTP_QUERY_MIME_VERSION
),
3817 FE(HTTP_QUERY_CONTENT_TYPE
),
3818 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3819 FE(HTTP_QUERY_CONTENT_ID
),
3820 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3821 FE(HTTP_QUERY_CONTENT_LENGTH
),
3822 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3823 FE(HTTP_QUERY_ALLOW
),
3824 FE(HTTP_QUERY_PUBLIC
),
3825 FE(HTTP_QUERY_DATE
),
3826 FE(HTTP_QUERY_EXPIRES
),
3827 FE(HTTP_QUERY_LAST_MODIFIED
),
3828 FE(HTTP_QUERY_MESSAGE_ID
),
3830 FE(HTTP_QUERY_DERIVED_FROM
),
3831 FE(HTTP_QUERY_COST
),
3832 FE(HTTP_QUERY_LINK
),
3833 FE(HTTP_QUERY_PRAGMA
),
3834 FE(HTTP_QUERY_VERSION
),
3835 FE(HTTP_QUERY_STATUS_CODE
),
3836 FE(HTTP_QUERY_STATUS_TEXT
),
3837 FE(HTTP_QUERY_RAW_HEADERS
),
3838 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3839 FE(HTTP_QUERY_CONNECTION
),
3840 FE(HTTP_QUERY_ACCEPT
),
3841 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3842 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3843 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3844 FE(HTTP_QUERY_AUTHORIZATION
),
3845 FE(HTTP_QUERY_CONTENT_ENCODING
),
3846 FE(HTTP_QUERY_FORWARDED
),
3847 FE(HTTP_QUERY_FROM
),
3848 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3849 FE(HTTP_QUERY_LOCATION
),
3850 FE(HTTP_QUERY_ORIG_URI
),
3851 FE(HTTP_QUERY_REFERER
),
3852 FE(HTTP_QUERY_RETRY_AFTER
),
3853 FE(HTTP_QUERY_SERVER
),
3854 FE(HTTP_QUERY_TITLE
),
3855 FE(HTTP_QUERY_USER_AGENT
),
3856 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3857 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3858 FE(HTTP_QUERY_ACCEPT_RANGES
),
3859 FE(HTTP_QUERY_SET_COOKIE
),
3860 FE(HTTP_QUERY_COOKIE
),
3861 FE(HTTP_QUERY_REQUEST_METHOD
),
3862 FE(HTTP_QUERY_REFRESH
),
3863 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3865 FE(HTTP_QUERY_CACHE_CONTROL
),
3866 FE(HTTP_QUERY_CONTENT_BASE
),
3867 FE(HTTP_QUERY_CONTENT_LOCATION
),
3868 FE(HTTP_QUERY_CONTENT_MD5
),
3869 FE(HTTP_QUERY_CONTENT_RANGE
),
3870 FE(HTTP_QUERY_ETAG
),
3871 FE(HTTP_QUERY_HOST
),
3872 FE(HTTP_QUERY_IF_MATCH
),
3873 FE(HTTP_QUERY_IF_NONE_MATCH
),
3874 FE(HTTP_QUERY_IF_RANGE
),
3875 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3876 FE(HTTP_QUERY_MAX_FORWARDS
),
3877 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3878 FE(HTTP_QUERY_RANGE
),
3879 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3880 FE(HTTP_QUERY_UPGRADE
),
3881 FE(HTTP_QUERY_VARY
),
3883 FE(HTTP_QUERY_WARNING
),
3884 FE(HTTP_QUERY_CUSTOM
)
3886 static const wininet_flag_info modifier_flags
[] = {
3887 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3888 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3889 FE(HTTP_QUERY_FLAG_NUMBER
),
3890 FE(HTTP_QUERY_FLAG_COALESCE
)
3893 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3894 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3897 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3898 TRACE(" Attribute:");
3899 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3900 if (query_flags
[i
].val
== info
) {
3901 TRACE(" %s", query_flags
[i
].name
);
3905 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3906 TRACE(" Unknown (%08x)", info
);
3909 TRACE(" Modifier:");
3910 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3911 if (modifier_flags
[i
].val
& info_mod
) {
3912 TRACE(" %s", modifier_flags
[i
].name
);
3913 info_mod
&= ~ modifier_flags
[i
].val
;
3918 TRACE(" Unknown (%08x)", info_mod
);
3923 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3924 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3926 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3930 if (lpBuffer
== NULL
)
3931 *lpdwBufferLength
= 0;
3932 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3933 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3937 WININET_Release( &request
->hdr
);
3939 TRACE("%u <--\n", res
);
3940 if(res
!= ERROR_SUCCESS
)
3942 return res
== ERROR_SUCCESS
;
3945 /***********************************************************************
3946 * HttpQueryInfoA (WININET.@)
3948 * Queries for information about an HTTP request
3955 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3956 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3962 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
3964 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3965 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3967 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3968 lpdwBufferLength
, lpdwIndex
);
3974 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
3975 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3977 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
3983 bufferW
= heap_alloc(alloclen
);
3984 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3985 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3986 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
3993 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
3997 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
3998 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
3999 *lpdwBufferLength
= len
- 1;
4001 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
4004 /* since the strings being returned from HttpQueryInfoW should be
4005 * only ASCII characters, it is reasonable to assume that all of
4006 * the Unicode characters can be reduced to a single byte */
4007 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
4009 heap_free( bufferW
);
4013 static WCHAR
*get_redirect_url(http_request_t
*request
)
4015 static WCHAR szHttp
[] = {'h','t','t','p',0};
4016 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
4017 http_session_t
*session
= request
->session
;
4018 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
4019 WCHAR
*orig_url
= NULL
, *redirect_url
= NULL
, *combined_url
= NULL
;
4020 DWORD url_length
= 0, res
;
4024 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
4025 if(res
== ERROR_INSUFFICIENT_BUFFER
) {
4026 redirect_url
= heap_alloc(url_length
);
4027 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
4029 if(res
!= ERROR_SUCCESS
) {
4030 heap_free(redirect_url
);
4034 urlComponents
.dwSchemeLength
= 1;
4035 b
= InternetCrackUrlW(redirect_url
, url_length
/ sizeof(WCHAR
), 0, &urlComponents
);
4036 if(b
&& urlComponents
.dwSchemeLength
&&
4037 urlComponents
.nScheme
!= INTERNET_SCHEME_HTTP
&& urlComponents
.nScheme
!= INTERNET_SCHEME_HTTPS
) {
4038 TRACE("redirect to non-http URL\n");
4042 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
4043 urlComponents
.dwSchemeLength
= 0;
4044 urlComponents
.lpszHostName
= request
->server
->name
;
4045 urlComponents
.nPort
= request
->server
->port
;
4046 urlComponents
.lpszUserName
= session
->userName
;
4047 urlComponents
.lpszUrlPath
= request
->path
;
4049 b
= InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
);
4050 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4051 orig_url
= heap_alloc(url_length
);
4053 /* convert from bytes to characters */
4054 url_length
= url_length
/ sizeof(WCHAR
) - 1;
4055 b
= InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
);
4060 b
= InternetCombineUrlW(orig_url
, redirect_url
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4061 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4062 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
4063 b
= InternetCombineUrlW(orig_url
, redirect_url
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4065 heap_free(combined_url
);
4066 combined_url
= NULL
;
4071 heap_free(orig_url
);
4072 heap_free(redirect_url
);
4073 return combined_url
;
4077 /***********************************************************************
4078 * HTTP_HandleRedirect (internal)
4080 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, WCHAR
*url
)
4082 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
4083 http_session_t
*session
= request
->session
;
4084 size_t url_len
= strlenW(url
);
4088 /* if it's an absolute path, keep the same session info */
4089 urlComponents
.lpszUrlPath
= url
;
4090 urlComponents
.dwUrlPathLength
= url_len
;
4094 urlComponents
.dwHostNameLength
= 1;
4095 urlComponents
.dwUserNameLength
= 1;
4096 urlComponents
.dwUrlPathLength
= 1;
4097 if(!InternetCrackUrlW(url
, url_len
, 0, &urlComponents
))
4098 return INTERNET_GetLastError();
4100 if(!urlComponents
.dwHostNameLength
)
4101 return ERROR_INTERNET_INVALID_URL
;
4104 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
4105 url
, (url_len
+ 1) * sizeof(WCHAR
));
4107 if(urlComponents
.dwHostNameLength
) {
4108 BOOL custom_port
= FALSE
;
4111 if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTP
) {
4112 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4113 TRACE("redirect from secure page to non-secure page\n");
4114 /* FIXME: warn about from secure redirect to non-secure page */
4115 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4118 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
;
4119 }else if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
) {
4120 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4121 TRACE("redirect from non-secure page to secure page\n");
4122 /* FIXME: notify about redirect to secure page */
4123 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4126 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
;
4129 heap_free(session
->hostName
);
4131 session
->hostName
= heap_strndupW(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4132 session
->hostPort
= urlComponents
.nPort
;
4134 heap_free(session
->userName
);
4135 session
->userName
= NULL
;
4136 if (urlComponents
.dwUserNameLength
)
4137 session
->userName
= heap_strndupW(urlComponents
.lpszUserName
, urlComponents
.dwUserNameLength
);
4139 reset_data_stream(request
);
4141 host
= substr(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4143 if(host
.len
!= strlenW(request
->server
->name
) || strncmpiW(request
->server
->name
, host
.str
, host
.len
)
4144 || request
->server
->port
!= urlComponents
.nPort
) {
4145 server_t
*new_server
;
4147 new_server
= get_server(host
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4148 server_release(request
->server
);
4149 request
->server
= new_server
;
4153 HTTP_ProcessHeader(request
, hostW
, request
->server
->host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4155 HTTP_ProcessHeader(request
, hostW
, request
->server
->name
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4158 heap_free(request
->path
);
4159 request
->path
= NULL
;
4160 if(urlComponents
.dwUrlPathLength
)
4167 path
= heap_strndupW(urlComponents
.lpszUrlPath
, urlComponents
.dwUrlPathLength
);
4168 rc
= UrlEscapeW(path
, &dummy
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4169 if (rc
!= E_POINTER
)
4170 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4171 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4172 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4173 URL_ESCAPE_SPACES_ONLY
);
4176 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4177 strcpyW(request
->path
, path
);
4182 /* Remove custom content-type/length headers on redirects. */
4183 remove_header(request
, szContent_Type
, TRUE
);
4184 remove_header(request
, szContent_Length
, TRUE
);
4186 return ERROR_SUCCESS
;
4189 /***********************************************************************
4190 * HTTP_build_req (internal)
4192 * concatenate all the strings in the request together
4194 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4199 for( t
= list
; *t
; t
++ )
4200 len
+= strlenW( *t
);
4203 str
= heap_alloc(len
*sizeof(WCHAR
));
4206 for( t
= list
; *t
; t
++ )
4212 static void HTTP_InsertCookies(http_request_t
*request
)
4217 res
= get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4218 if(res
!= ERROR_SUCCESS
|| !cookies
)
4221 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
),
4222 HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
4226 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4228 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4236 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4237 if (!strcmpiW(day
, days
[i
]))
4244 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4246 static const WCHAR jan
[] = { 'j','a','n',0 };
4247 static const WCHAR feb
[] = { 'f','e','b',0 };
4248 static const WCHAR mar
[] = { 'm','a','r',0 };
4249 static const WCHAR apr
[] = { 'a','p','r',0 };
4250 static const WCHAR may
[] = { 'm','a','y',0 };
4251 static const WCHAR jun
[] = { 'j','u','n',0 };
4252 static const WCHAR jul
[] = { 'j','u','l',0 };
4253 static const WCHAR aug
[] = { 'a','u','g',0 };
4254 static const WCHAR sep
[] = { 's','e','p',0 };
4255 static const WCHAR oct
[] = { 'o','c','t',0 };
4256 static const WCHAR nov
[] = { 'n','o','v',0 };
4257 static const WCHAR dec
[] = { 'd','e','c',0 };
4259 if (!strcmpiW(month
, jan
)) return 1;
4260 if (!strcmpiW(month
, feb
)) return 2;
4261 if (!strcmpiW(month
, mar
)) return 3;
4262 if (!strcmpiW(month
, apr
)) return 4;
4263 if (!strcmpiW(month
, may
)) return 5;
4264 if (!strcmpiW(month
, jun
)) return 6;
4265 if (!strcmpiW(month
, jul
)) return 7;
4266 if (!strcmpiW(month
, aug
)) return 8;
4267 if (!strcmpiW(month
, sep
)) return 9;
4268 if (!strcmpiW(month
, oct
)) return 10;
4269 if (!strcmpiW(month
, nov
)) return 11;
4270 if (!strcmpiW(month
, dec
)) return 12;
4275 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4276 * optionally preceded by whitespace.
4277 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4278 * st, and sets *str to the first character after the time format.
4280 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4286 while (isspaceW(*ptr
))
4289 num
= strtoulW(ptr
, &nextPtr
, 10);
4290 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4292 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4297 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4301 st
->wHour
= (WORD
)num
;
4302 num
= strtoulW(ptr
, &nextPtr
, 10);
4303 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4305 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4310 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4314 st
->wMinute
= (WORD
)num
;
4315 num
= strtoulW(ptr
, &nextPtr
, 10);
4316 if (!nextPtr
|| nextPtr
<= ptr
)
4318 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4323 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4328 st
->wSecond
= (WORD
)num
;
4332 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4334 static const WCHAR gmt
[]= { 'G','M','T',0 };
4335 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4337 SYSTEMTIME st
= { 0 };
4340 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4341 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4344 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4345 if (st
.wDayOfWeek
>= 7)
4347 ERR("unexpected weekday %s\n", debugstr_w(day
));
4351 while (isspaceW(*ptr
))
4354 for (monthPtr
= month
; !isspaceW(*ptr
) &&
4355 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4359 st
.wMonth
= HTTP_ParseMonth(month
);
4360 if (!st
.wMonth
|| st
.wMonth
> 12)
4362 ERR("unexpected month %s\n", debugstr_w(month
));
4366 while (isspaceW(*ptr
))
4369 num
= strtoulW(ptr
, &nextPtr
, 10);
4370 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4372 ERR("unexpected day %s\n", debugstr_w(ptr
));
4376 st
.wDay
= (WORD
)num
;
4378 while (isspaceW(*ptr
))
4381 if (!HTTP_ParseTime(&st
, &ptr
))
4384 while (isspaceW(*ptr
))
4387 num
= strtoulW(ptr
, &nextPtr
, 10);
4388 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4390 ERR("unexpected year %s\n", debugstr_w(ptr
));
4394 st
.wYear
= (WORD
)num
;
4396 while (isspaceW(*ptr
))
4399 /* asctime() doesn't report a timezone, but some web servers do, so accept
4400 * with or without GMT.
4402 if (*ptr
&& strcmpW(ptr
, gmt
))
4404 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4407 return SystemTimeToFileTime(&st
, ft
);
4410 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4412 static const WCHAR gmt
[]= { 'G','M','T',0 };
4413 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4416 SYSTEMTIME st
= { 0 };
4418 ptr
= strchrW(value
, ',');
4421 if (ptr
- value
!= 3)
4423 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4426 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4428 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4429 if (st
.wDayOfWeek
> 6)
4431 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4436 while (isspaceW(*ptr
))
4439 num
= strtoulW(ptr
, &nextPtr
, 10);
4440 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4442 WARN("unexpected day %s\n", debugstr_w(value
));
4446 st
.wDay
= (WORD
)num
;
4448 while (isspaceW(*ptr
))
4451 for (monthPtr
= month
; !isspaceW(*ptr
) &&
4452 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4456 st
.wMonth
= HTTP_ParseMonth(month
);
4457 if (!st
.wMonth
|| st
.wMonth
> 12)
4459 WARN("unexpected month %s\n", debugstr_w(month
));
4463 while (isspaceW(*ptr
))
4466 num
= strtoulW(ptr
, &nextPtr
, 10);
4467 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4469 ERR("unexpected year %s\n", debugstr_w(value
));
4473 st
.wYear
= (WORD
)num
;
4475 if (!HTTP_ParseTime(&st
, &ptr
))
4478 while (isspaceW(*ptr
))
4481 if (strcmpW(ptr
, gmt
))
4483 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4486 return SystemTimeToFileTime(&st
, ft
);
4489 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4491 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4492 { 'm','o','n','d','a','y',0 },
4493 { 't','u','e','s','d','a','y',0 },
4494 { 'w','e','d','n','e','s','d','a','y',0 },
4495 { 't','h','u','r','s','d','a','y',0 },
4496 { 'f','r','i','d','a','y',0 },
4497 { 's','a','t','u','r','d','a','y',0 }};
4499 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4500 if (!strcmpiW(day
, days
[i
]))
4507 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4509 static const WCHAR gmt
[]= { 'G','M','T',0 };
4510 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4513 SYSTEMTIME st
= { 0 };
4515 ptr
= strchrW(value
, ',');
4518 if (ptr
- value
== 3)
4520 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4522 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4523 if (st
.wDayOfWeek
> 6)
4525 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4529 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4531 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4532 day
[ptr
- value
+ 1] = 0;
4533 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4534 if (st
.wDayOfWeek
> 6)
4536 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4542 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4547 while (isspaceW(*ptr
))
4550 num
= strtoulW(ptr
, &nextPtr
, 10);
4551 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4553 ERR("unexpected day %s\n", debugstr_w(value
));
4557 st
.wDay
= (WORD
)num
;
4561 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4566 for (monthPtr
= month
; *ptr
!= '-' &&
4567 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4571 st
.wMonth
= HTTP_ParseMonth(month
);
4572 if (!st
.wMonth
|| st
.wMonth
> 12)
4574 ERR("unexpected month %s\n", debugstr_w(month
));
4580 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4585 num
= strtoulW(ptr
, &nextPtr
, 10);
4586 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4588 ERR("unexpected year %s\n", debugstr_w(value
));
4592 st
.wYear
= (WORD
)num
;
4594 if (!HTTP_ParseTime(&st
, &ptr
))
4597 while (isspaceW(*ptr
))
4600 if (strcmpW(ptr
, gmt
))
4602 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4605 return SystemTimeToFileTime(&st
, ft
);
4608 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4610 static const WCHAR zero
[] = { '0',0 };
4613 if (!strcmpW(value
, zero
))
4615 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4618 else if (strchrW(value
, ','))
4620 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4623 ret
= HTTP_ParseRfc850Date(value
, ft
);
4625 ERR("unexpected date format %s\n", debugstr_w(value
));
4630 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4632 ERR("unexpected date format %s\n", debugstr_w(value
));
4637 static void HTTP_ProcessExpires(http_request_t
*request
)
4639 BOOL expirationFound
= FALSE
;
4642 EnterCriticalSection( &request
->headers_section
);
4644 /* Look for a Cache-Control header with a max-age directive, as it takes
4645 * precedence over the Expires header.
4647 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4648 if (headerIndex
!= -1)
4650 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4653 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4655 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4660 end
= ptr
+ strlenW(ptr
);
4661 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4665 static const WCHAR max_age
[] = {
4666 'm','a','x','-','a','g','e',0 };
4668 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4673 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4674 if (nextPtr
> equal
+ 1)
4678 NtQuerySystemTime( &ft
);
4679 /* Age is in seconds, FILETIME resolution is in
4680 * 100 nanosecond intervals.
4682 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4683 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4684 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4685 expirationFound
= TRUE
;
4692 while (isspaceW(*ptr
))
4699 if (!expirationFound
)
4701 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4702 if (headerIndex
!= -1)
4704 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4707 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4709 expirationFound
= TRUE
;
4710 request
->expires
= ft
;
4714 if (!expirationFound
)
4718 /* With no known age, default to 10 minutes until expiration. */
4719 NtQuerySystemTime( &t
);
4720 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4721 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4722 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4725 LeaveCriticalSection( &request
->headers_section
);
4728 static void HTTP_ProcessLastModified(http_request_t
*request
)
4732 EnterCriticalSection( &request
->headers_section
);
4734 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4735 if (headerIndex
!= -1)
4737 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4740 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4741 request
->last_modified
= ft
;
4744 LeaveCriticalSection( &request
->headers_section
);
4747 static void http_process_keep_alive(http_request_t
*req
)
4751 EnterCriticalSection( &req
->headers_section
);
4753 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4754 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4755 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4756 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4758 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4760 LeaveCriticalSection( &req
->headers_section
);
4763 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4765 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4766 netconn_t
*netconn
= NULL
;
4769 if (request
->netconn
)
4771 if (NETCON_is_alive(request
->netconn
) && drain_content(request
, TRUE
) == ERROR_SUCCESS
)
4773 reset_data_stream(request
);
4775 return ERROR_SUCCESS
;
4778 TRACE("freeing netconn\n");
4779 free_netconn(request
->netconn
);
4780 request
->netconn
= NULL
;
4783 reset_data_stream(request
);
4785 res
= HTTP_ResolveName(request
);
4786 if(res
!= ERROR_SUCCESS
)
4789 EnterCriticalSection(&connection_pool_cs
);
4791 while(!list_empty(&request
->server
->conn_pool
)) {
4792 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4793 list_remove(&netconn
->pool_entry
);
4795 if(is_valid_netconn(netconn
) && NETCON_is_alive(netconn
))
4798 TRACE("connection %p closed during idle\n", netconn
);
4799 free_netconn(netconn
);
4803 LeaveCriticalSection(&connection_pool_cs
);
4806 TRACE("<-- reusing %p netconn\n", netconn
);
4807 request
->netconn
= netconn
;
4809 return ERROR_SUCCESS
;
4812 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4813 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4815 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4816 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4817 request
->server
->addr_str
,
4818 strlen(request
->server
->addr_str
)+1);
4820 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4821 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4822 request
->connect_timeout
, &netconn
);
4823 if(res
!= ERROR_SUCCESS
) {
4824 ERR("create_netconn failed: %u\n", res
);
4828 request
->netconn
= netconn
;
4830 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4831 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4832 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4835 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4836 return ERROR_SUCCESS
;
4839 static char *build_ascii_request( const WCHAR
*str
, void *data
, DWORD data_len
, DWORD
*out_len
)
4841 int len
= WideCharToMultiByte( CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
4844 if (!(ret
= heap_alloc( len
+ data_len
))) return NULL
;
4845 WideCharToMultiByte( CP_ACP
, 0, str
, -1, ret
, len
, NULL
, NULL
);
4846 if (data_len
) memcpy( ret
+ len
- 1, data
, data_len
);
4847 *out_len
= len
+ data_len
- 1;
4852 static void set_content_length_header( http_request_t
*request
, DWORD len
, DWORD flags
)
4854 static const WCHAR fmtW
[] =
4855 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4856 WCHAR buf
[sizeof(fmtW
)/sizeof(fmtW
[0]) + 10];
4858 sprintfW( buf
, fmtW
, len
);
4859 HTTP_HttpAddRequestHeadersW( request
, buf
, ~0u, flags
);
4862 /***********************************************************************
4863 * HTTP_HttpSendRequestW (internal)
4865 * Sends the specified request to the HTTP server
4868 * ERROR_SUCCESS on success
4869 * win32 error code on failure
4872 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4873 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4874 DWORD dwContentLength
, BOOL bEndRequest
)
4876 BOOL redirected
= FALSE
, secure_proxy_connect
= FALSE
, loop_next
;
4877 LPWSTR requestString
= NULL
;
4878 INT responseLen
, cnt
;
4881 TRACE("--> %p\n", request
);
4883 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4885 /* if the verb is NULL default to GET */
4887 request
->verb
= heap_strdupW(szGET
);
4889 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
,
4890 HTTP_ADDREQ_FLAG_ADD_IF_NEW
| HTTP_ADDHDR_FLAG_REQ
);
4892 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4894 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4895 request
->bytesToWrite
= dwContentLength
;
4897 if (request
->session
->appInfo
->agent
)
4899 WCHAR
*agent_header
;
4900 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4903 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4904 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4905 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4907 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4908 heap_free(agent_header
);
4910 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4912 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4913 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4915 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4917 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4918 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4919 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4922 /* add the headers the caller supplied */
4923 if( lpszHeaders
&& dwHeaderLength
)
4924 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4928 DWORD len
, data_len
= dwOptionalLength
;
4929 BOOL reusing_connection
;
4935 request
->contentLength
= ~0u;
4936 request
->bytesToWrite
= 0;
4939 if (TRACE_ON(wininet
))
4943 EnterCriticalSection( &request
->headers_section
);
4944 host
= HTTP_GetHeader( request
, hostW
);
4945 TRACE("Going to url %s %s\n", debugstr_w(host
->lpszValue
), debugstr_w(request
->path
));
4946 LeaveCriticalSection( &request
->headers_section
);
4949 HTTP_FixURL(request
);
4950 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4952 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
,
4953 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
4955 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4956 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4958 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4959 HTTP_InsertCookies(request
);
4961 res
= open_http_connection(request
, &reusing_connection
);
4962 if (res
!= ERROR_SUCCESS
)
4965 if (!reusing_connection
&& (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4967 if (request
->proxy
) secure_proxy_connect
= TRUE
;
4970 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4971 if (res
!= ERROR_SUCCESS
)
4973 WARN("failed to upgrade to secure connection\n");
4974 http_release_netconn(request
, FALSE
);
4979 if (secure_proxy_connect
)
4981 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
4982 const WCHAR
*target
= request
->server
->host_port
;
4984 if (HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
4985 set_content_length_header(request
, 0, HTTP_ADDREQ_FLAG_REPLACE
);
4987 requestString
= build_request_header(request
, connectW
, target
, g_szHttp1_1
, TRUE
);
4989 else if (request
->proxy
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4991 WCHAR
*url
= build_proxy_path_url(request
);
4992 requestString
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
4997 if (request
->proxy
&& HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
4998 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_REPLACE
);
5000 requestString
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
5003 TRACE("Request header -> %s\n", debugstr_w(requestString
) );
5005 /* send the request as ASCII, tack on the optional data */
5006 if (!lpOptional
|| redirected
|| secure_proxy_connect
)
5009 ascii_req
= build_ascii_request( requestString
, lpOptional
, data_len
, &len
);
5010 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
5012 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5013 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
5015 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
5016 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
5017 heap_free( ascii_req
);
5018 if(res
!= ERROR_SUCCESS
) {
5019 TRACE("send failed: %u\n", res
);
5020 if(!reusing_connection
)
5022 http_release_netconn(request
, FALSE
);
5027 request
->bytesWritten
= data_len
;
5029 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5030 INTERNET_STATUS_REQUEST_SENT
,
5031 &len
, sizeof(DWORD
));
5037 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5038 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5040 if (HTTP_GetResponseHeaders(request
, &responseLen
))
5042 http_release_netconn(request
, FALSE
);
5043 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
5046 /* FIXME: We should know that connection is closed before sending
5047 * headers. Otherwise wrong callbacks are executed */
5048 if(!responseLen
&& reusing_connection
) {
5049 TRACE("Connection closed by server, reconnecting\n");
5050 http_release_netconn(request
, FALSE
);
5055 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5056 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
5059 http_process_keep_alive(request
);
5060 HTTP_ProcessCookies(request
);
5061 HTTP_ProcessExpires(request
);
5062 HTTP_ProcessLastModified(request
);
5064 res
= set_content_length(request
);
5065 if(res
!= ERROR_SUCCESS
)
5067 if(!request
->contentLength
&& !secure_proxy_connect
)
5068 http_release_netconn(request
, TRUE
);
5070 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5074 switch(request
->status_code
) {
5075 case HTTP_STATUS_REDIRECT
:
5076 case HTTP_STATUS_MOVED
:
5077 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5078 case HTTP_STATUS_REDIRECT_METHOD
:
5079 new_url
= get_redirect_url(request
);
5083 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5084 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5086 heap_free(request
->verb
);
5087 request
->verb
= heap_strdupW(szGET
);
5089 http_release_netconn(request
, drain_content(request
, FALSE
) == ERROR_SUCCESS
);
5090 res
= HTTP_HandleRedirect(request
, new_url
);
5092 if (res
== ERROR_SUCCESS
) {
5093 heap_free(requestString
);
5099 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5101 WCHAR szAuthValue
[2048];
5103 if (request
->status_code
== HTTP_STATUS_DENIED
)
5105 WCHAR
*host
= heap_strdupW( request
->server
->canon_host_port
);
5107 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5109 if (HTTP_DoAuthorization(request
, szAuthValue
,
5111 request
->session
->userName
,
5112 request
->session
->password
, host
))
5114 heap_free(requestString
);
5115 if(!drain_content(request
, TRUE
) == ERROR_SUCCESS
) {
5116 FIXME("Could not drain content\n");
5117 http_release_netconn(request
, FALSE
);
5126 TRACE("Cleaning wrong authorization data\n");
5127 destroy_authinfo(request
->authInfo
);
5128 request
->authInfo
= NULL
;
5131 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5134 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5136 if (HTTP_DoAuthorization(request
, szAuthValue
,
5137 &request
->proxyAuthInfo
,
5138 request
->session
->appInfo
->proxyUsername
,
5139 request
->session
->appInfo
->proxyPassword
,
5142 heap_free(requestString
);
5143 if(!drain_content(request
, TRUE
) == ERROR_SUCCESS
) {
5144 FIXME("Could not drain content\n");
5145 http_release_netconn(request
, FALSE
);
5153 TRACE("Cleaning wrong proxy authorization data\n");
5154 destroy_authinfo(request
->proxyAuthInfo
);
5155 request
->proxyAuthInfo
= NULL
;
5159 if (secure_proxy_connect
&& request
->status_code
== HTTP_STATUS_OK
)
5161 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5162 if (res
!= ERROR_SUCCESS
)
5164 WARN("failed to upgrade to secure proxy connection\n");
5165 http_release_netconn( request
, FALSE
);
5168 remove_header(request
, szProxy_Authorization
, TRUE
);
5169 destroy_authinfo(request
->proxyAuthInfo
);
5170 request
->proxyAuthInfo
= NULL
;
5172 secure_proxy_connect
= FALSE
;
5177 res
= ERROR_SUCCESS
;
5182 heap_free(requestString
);
5184 /* TODO: send notification for P3P header */
5186 if(res
== ERROR_SUCCESS
)
5187 create_cache_entry(request
);
5189 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5191 if (res
== ERROR_SUCCESS
) {
5192 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5193 HTTP_ReceiveRequestData(request
);
5195 send_request_complete(request
,
5196 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5198 send_request_complete(request
, 0, res
);
5214 } send_request_task_t
;
5216 /***********************************************************************
5218 * Helper functions for the HttpSendRequest(Ex) functions
5221 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5223 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5224 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5226 TRACE("%p\n", request
);
5228 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5229 task
->optional_len
, task
->content_len
, task
->end_request
);
5231 heap_free(task
->headers
);
5235 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5238 DWORD res
= ERROR_SUCCESS
;
5240 if(!is_valid_netconn(request
->netconn
)) {
5241 WARN("Not connected\n");
5242 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5243 return ERROR_INTERNET_OPERATION_CANCELLED
;
5246 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5247 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5249 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5250 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5252 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5253 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5255 /* process cookies here. Is this right? */
5256 http_process_keep_alive(request
);
5257 HTTP_ProcessCookies(request
);
5258 HTTP_ProcessExpires(request
);
5259 HTTP_ProcessLastModified(request
);
5261 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5262 if(!request
->contentLength
)
5263 http_release_netconn(request
, TRUE
);
5266 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5268 switch(request
->status_code
) {
5269 case HTTP_STATUS_REDIRECT
:
5270 case HTTP_STATUS_MOVED
:
5271 case HTTP_STATUS_REDIRECT_METHOD
:
5272 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5275 new_url
= get_redirect_url(request
);
5279 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5280 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5282 heap_free(request
->verb
);
5283 request
->verb
= heap_strdupW(szGET
);
5285 http_release_netconn(request
, drain_content(request
, FALSE
) == ERROR_SUCCESS
);
5286 res
= HTTP_HandleRedirect(request
, new_url
);
5288 if (res
== ERROR_SUCCESS
)
5289 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5294 if(res
== ERROR_SUCCESS
)
5295 create_cache_entry(request
);
5297 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5298 HTTP_ReceiveRequestData(request
);
5300 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5305 /***********************************************************************
5306 * HttpEndRequestA (WININET.@)
5308 * Ends an HTTP request that was started by HttpSendRequestEx
5311 * TRUE if successful
5315 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5316 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5318 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5322 SetLastError(ERROR_INVALID_PARAMETER
);
5326 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5333 } end_request_task_t
;
5335 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5337 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5338 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5342 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5345 /***********************************************************************
5346 * HttpEndRequestW (WININET.@)
5348 * Ends an HTTP request that was started by HttpSendRequestEx
5351 * TRUE if successful
5355 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5356 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5358 http_request_t
*request
;
5361 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5365 SetLastError(ERROR_INVALID_PARAMETER
);
5369 request
= (http_request_t
*) get_handle_object( hRequest
);
5371 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5373 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5375 WININET_Release( &request
->hdr
);
5378 request
->hdr
.dwFlags
|= dwFlags
;
5380 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5382 end_request_task_t
*task
;
5384 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5385 task
->flags
= dwFlags
;
5386 task
->context
= dwContext
;
5388 INTERNET_AsyncCall(&task
->hdr
);
5389 res
= ERROR_IO_PENDING
;
5392 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5394 WININET_Release( &request
->hdr
);
5395 TRACE("%u <--\n", res
);
5396 if(res
!= ERROR_SUCCESS
)
5398 return res
== ERROR_SUCCESS
;
5401 /***********************************************************************
5402 * HttpSendRequestExA (WININET.@)
5404 * Sends the specified request to the HTTP server and allows chunked
5409 * Failure: FALSE, call GetLastError() for more information.
5411 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5412 LPINTERNET_BUFFERSA lpBuffersIn
,
5413 LPINTERNET_BUFFERSA lpBuffersOut
,
5414 DWORD dwFlags
, DWORD_PTR dwContext
)
5416 INTERNET_BUFFERSW BuffersInW
;
5419 LPWSTR header
= NULL
;
5421 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5422 lpBuffersOut
, dwFlags
, dwContext
);
5426 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5427 if (lpBuffersIn
->lpcszHeader
)
5429 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5430 lpBuffersIn
->dwHeadersLength
,0,0);
5431 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5432 if (!(BuffersInW
.lpcszHeader
= header
))
5434 SetLastError(ERROR_OUTOFMEMORY
);
5437 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5438 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5442 BuffersInW
.lpcszHeader
= NULL
;
5443 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5444 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5445 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5446 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5447 BuffersInW
.Next
= NULL
;
5450 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5456 /***********************************************************************
5457 * HttpSendRequestExW (WININET.@)
5459 * Sends the specified request to the HTTP server and allows chunked
5464 * Failure: FALSE, call GetLastError() for more information.
5466 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5467 LPINTERNET_BUFFERSW lpBuffersIn
,
5468 LPINTERNET_BUFFERSW lpBuffersOut
,
5469 DWORD dwFlags
, DWORD_PTR dwContext
)
5471 http_request_t
*request
;
5472 http_session_t
*session
;
5476 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5477 lpBuffersOut
, dwFlags
, dwContext
);
5479 request
= (http_request_t
*) get_handle_object( hRequest
);
5481 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5483 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5487 session
= request
->session
;
5488 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5489 hIC
= session
->appInfo
;
5490 assert(hIC
->hdr
.htype
== WH_HINIT
);
5492 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5494 send_request_task_t
*task
;
5496 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5501 if (lpBuffersIn
->lpcszHeader
)
5503 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5504 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5506 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5508 task
->headers
= heap_alloc(size
);
5509 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5511 else task
->headers
= NULL
;
5513 task
->headers_len
= size
/ sizeof(WCHAR
);
5514 task
->optional
= lpBuffersIn
->lpvBuffer
;
5515 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5516 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5520 task
->headers
= NULL
;
5521 task
->headers_len
= 0;
5522 task
->optional
= NULL
;
5523 task
->optional_len
= 0;
5524 task
->content_len
= 0;
5527 task
->end_request
= FALSE
;
5529 INTERNET_AsyncCall(&task
->hdr
);
5530 res
= ERROR_IO_PENDING
;
5535 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5536 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5537 lpBuffersIn
->dwBufferTotal
, FALSE
);
5539 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5544 WININET_Release( &request
->hdr
);
5548 return res
== ERROR_SUCCESS
;
5551 /***********************************************************************
5552 * HttpSendRequestW (WININET.@)
5554 * Sends the specified request to the HTTP server
5561 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5562 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5564 http_request_t
*request
;
5565 http_session_t
*session
= NULL
;
5566 appinfo_t
*hIC
= NULL
;
5567 DWORD res
= ERROR_SUCCESS
;
5569 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5570 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5572 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5573 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5575 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5579 session
= request
->session
;
5580 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5582 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5586 hIC
= session
->appInfo
;
5587 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5589 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5593 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5595 send_request_task_t
*task
;
5597 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5602 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5603 else size
= dwHeaderLength
* sizeof(WCHAR
);
5605 task
->headers
= heap_alloc(size
);
5606 memcpy(task
->headers
, lpszHeaders
, size
);
5609 task
->headers
= NULL
;
5610 task
->headers_len
= dwHeaderLength
;
5611 task
->optional
= lpOptional
;
5612 task
->optional_len
= dwOptionalLength
;
5613 task
->content_len
= dwOptionalLength
;
5614 task
->end_request
= TRUE
;
5616 INTERNET_AsyncCall(&task
->hdr
);
5617 res
= ERROR_IO_PENDING
;
5621 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5622 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5623 dwOptionalLength
, TRUE
);
5627 WININET_Release( &request
->hdr
);
5630 return res
== ERROR_SUCCESS
;
5633 /***********************************************************************
5634 * HttpSendRequestA (WININET.@)
5636 * Sends the specified request to the HTTP server
5643 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5644 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5647 LPWSTR szHeaders
=NULL
;
5648 DWORD nLen
=dwHeaderLength
;
5649 if(lpszHeaders
!=NULL
)
5651 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5652 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5653 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5655 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5656 heap_free(szHeaders
);
5660 /***********************************************************************
5661 * HTTPSESSION_Destroy (internal)
5663 * Deallocate session handle
5666 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5668 http_session_t
*session
= (http_session_t
*) hdr
;
5670 TRACE("%p\n", session
);
5672 WININET_Release(&session
->appInfo
->hdr
);
5674 heap_free(session
->hostName
);
5675 heap_free(session
->password
);
5676 heap_free(session
->userName
);
5679 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5681 http_session_t
*ses
= (http_session_t
*)hdr
;
5684 case INTERNET_OPTION_HANDLE_TYPE
:
5685 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5687 if (*size
< sizeof(ULONG
))
5688 return ERROR_INSUFFICIENT_BUFFER
;
5690 *size
= sizeof(DWORD
);
5691 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5692 return ERROR_SUCCESS
;
5693 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5694 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5696 if (*size
< sizeof(DWORD
))
5697 return ERROR_INSUFFICIENT_BUFFER
;
5699 *size
= sizeof(DWORD
);
5700 *(DWORD
*)buffer
= ses
->connect_timeout
;
5701 return ERROR_SUCCESS
;
5703 case INTERNET_OPTION_SEND_TIMEOUT
:
5704 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5706 if (*size
< sizeof(DWORD
))
5707 return ERROR_INSUFFICIENT_BUFFER
;
5709 *size
= sizeof(DWORD
);
5710 *(DWORD
*)buffer
= ses
->send_timeout
;
5711 return ERROR_SUCCESS
;
5713 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5714 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5716 if (*size
< sizeof(DWORD
))
5717 return ERROR_INSUFFICIENT_BUFFER
;
5719 *size
= sizeof(DWORD
);
5720 *(DWORD
*)buffer
= ses
->receive_timeout
;
5721 return ERROR_SUCCESS
;
5724 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5727 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5729 http_session_t
*ses
= (http_session_t
*)hdr
;
5732 case INTERNET_OPTION_USERNAME
:
5734 heap_free(ses
->userName
);
5735 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5736 return ERROR_SUCCESS
;
5738 case INTERNET_OPTION_PASSWORD
:
5740 heap_free(ses
->password
);
5741 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5742 return ERROR_SUCCESS
;
5744 case INTERNET_OPTION_PROXY_USERNAME
:
5746 heap_free(ses
->appInfo
->proxyUsername
);
5747 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5748 return ERROR_SUCCESS
;
5750 case INTERNET_OPTION_PROXY_PASSWORD
:
5752 heap_free(ses
->appInfo
->proxyPassword
);
5753 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5754 return ERROR_SUCCESS
;
5756 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5758 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5759 ses
->connect_timeout
= *(DWORD
*)buffer
;
5760 return ERROR_SUCCESS
;
5762 case INTERNET_OPTION_SEND_TIMEOUT
:
5764 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5765 ses
->send_timeout
= *(DWORD
*)buffer
;
5766 return ERROR_SUCCESS
;
5768 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5770 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5771 ses
->receive_timeout
= *(DWORD
*)buffer
;
5772 return ERROR_SUCCESS
;
5777 return INET_SetOption(hdr
, option
, buffer
, size
);
5780 static const object_vtbl_t HTTPSESSIONVtbl
= {
5781 HTTPSESSION_Destroy
,
5783 HTTPSESSION_QueryOption
,
5784 HTTPSESSION_SetOption
,
5792 /***********************************************************************
5793 * HTTP_Connect (internal)
5795 * Create http session handle
5798 * HINTERNET a session handle on success
5802 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5803 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5804 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5805 DWORD dwInternalFlags
, HINTERNET
*ret
)
5807 http_session_t
*session
= NULL
;
5811 if (!lpszServerName
|| !lpszServerName
[0])
5812 return ERROR_INVALID_PARAMETER
;
5814 assert( hIC
->hdr
.htype
== WH_HINIT
);
5816 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5818 return ERROR_OUTOFMEMORY
;
5821 * According to my tests. The name is not resolved until a request is sent
5824 session
->hdr
.htype
= WH_HHTTPSESSION
;
5825 session
->hdr
.dwFlags
= dwFlags
;
5826 session
->hdr
.dwContext
= dwContext
;
5827 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5828 session
->hdr
.decoding
= hIC
->hdr
.decoding
;
5830 WININET_AddRef( &hIC
->hdr
);
5831 session
->appInfo
= hIC
;
5832 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5834 session
->hostName
= heap_strdupW(lpszServerName
);
5835 if (lpszUserName
&& lpszUserName
[0])
5836 session
->userName
= heap_strdupW(lpszUserName
);
5837 if (lpszPassword
&& lpszPassword
[0])
5838 session
->password
= heap_strdupW(lpszPassword
);
5839 session
->hostPort
= serverPort
;
5840 session
->connect_timeout
= hIC
->connect_timeout
;
5841 session
->send_timeout
= 0;
5842 session
->receive_timeout
= 0;
5844 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5845 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5847 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5848 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5853 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5857 TRACE("%p --> %p\n", hIC
, session
);
5859 *ret
= session
->hdr
.hInternet
;
5860 return ERROR_SUCCESS
;
5863 /***********************************************************************
5864 * HTTP_clear_response_headers (internal)
5866 * clear out any old response headers
5868 static void HTTP_clear_response_headers( http_request_t
*request
)
5872 EnterCriticalSection( &request
->headers_section
);
5874 for( i
=0; i
<request
->nCustHeaders
; i
++)
5876 if( !request
->custHeaders
[i
].lpszField
)
5878 if( !request
->custHeaders
[i
].lpszValue
)
5880 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5882 HTTP_DeleteCustomHeader( request
, i
);
5886 LeaveCriticalSection( &request
->headers_section
);
5889 /***********************************************************************
5890 * HTTP_GetResponseHeaders (internal)
5892 * Read server response
5899 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5902 WCHAR buffer
[MAX_REPLY_LEN
];
5903 DWORD buflen
= MAX_REPLY_LEN
;
5905 char bufferA
[MAX_REPLY_LEN
];
5906 LPWSTR status_code
= NULL
, status_text
= NULL
;
5907 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5908 BOOL codeHundred
= FALSE
;
5912 if(!is_valid_netconn(request
->netconn
))
5915 /* clear old response headers (eg. from a redirect response) */
5916 HTTP_clear_response_headers( request
);
5918 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5921 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5923 buflen
= MAX_REPLY_LEN
;
5924 if ((res
= read_line(request
, bufferA
, &buflen
)))
5927 if (!buflen
) goto lend
;
5930 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5931 /* check is this a status code line? */
5932 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5934 /* split the version from the status code */
5935 status_code
= strchrW( buffer
, ' ' );
5940 /* split the status code from the status text */
5941 status_text
= strchrW( status_code
, ' ' );
5945 request
->status_code
= atoiW(status_code
);
5947 TRACE("version [%s] status code [%s] status text [%s]\n",
5948 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5950 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5952 else if (!codeHundred
)
5954 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5956 heap_free(request
->version
);
5957 heap_free(request
->statusText
);
5959 request
->status_code
= HTTP_STATUS_OK
;
5960 request
->version
= heap_strdupW(g_szHttp1_0
);
5961 request
->statusText
= heap_strdupW(szOK
);
5965 } while (codeHundred
);
5967 /* Add status code */
5968 HTTP_ProcessHeader(request
, szStatus
, status_code
,
5969 HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
5971 heap_free(request
->version
);
5972 heap_free(request
->statusText
);
5974 request
->version
= heap_strdupW(buffer
);
5975 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
5977 /* Restore the spaces */
5978 *(status_code
-1) = ' ';
5980 *(status_text
-1) = ' ';
5982 /* Parse each response line */
5985 buflen
= MAX_REPLY_LEN
;
5986 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
5988 LPWSTR
* pFieldAndValue
;
5990 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
5992 if (!bufferA
[0]) break;
5993 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5995 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
5998 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
5999 HTTP_ADDREQ_FLAG_ADD
);
6000 HTTP_FreeTokens(pFieldAndValue
);
6011 res
= ERROR_SUCCESS
;
6020 /***********************************************************************
6021 * HTTP_InterpretHttpHeader (internal)
6023 * Parse server response
6027 * Pointer to array of field, value, NULL on success.
6030 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
6032 LPWSTR
* pTokenPair
;
6036 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
6038 pszColon
= strchrW(buffer
, ':');
6039 /* must have two tokens */
6042 HTTP_FreeTokens(pTokenPair
);
6044 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
6048 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
6051 HTTP_FreeTokens(pTokenPair
);
6054 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
6055 pTokenPair
[0][pszColon
- buffer
] = '\0';
6059 len
= strlenW(pszColon
);
6060 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
6063 HTTP_FreeTokens(pTokenPair
);
6066 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
6068 strip_spaces(pTokenPair
[0]);
6069 strip_spaces(pTokenPair
[1]);
6071 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
6075 /***********************************************************************
6076 * HTTP_ProcessHeader (internal)
6078 * Stuff header into header tables according to <dwModifier>
6082 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6084 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6086 LPHTTPHEADERW lphttpHdr
;
6088 BOOL request_only
= !!(dwModifier
& HTTP_ADDHDR_FLAG_REQ
);
6089 DWORD res
= ERROR_SUCCESS
;
6091 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6093 EnterCriticalSection( &request
->headers_section
);
6095 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6098 lphttpHdr
= &request
->custHeaders
[index
];
6100 /* replace existing header if FLAG_REPLACE is given */
6101 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6103 HTTP_DeleteCustomHeader( request
, index
);
6105 if (value
&& value
[0])
6109 hdr
.lpszField
= (LPWSTR
)field
;
6110 hdr
.lpszValue
= (LPWSTR
)value
;
6111 hdr
.wFlags
= hdr
.wCount
= 0;
6113 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6114 hdr
.wFlags
|= HDR_ISREQUEST
;
6116 res
= HTTP_InsertCustomHeader( request
, &hdr
);
6122 /* do not add new header if FLAG_ADD_IF_NEW is set */
6123 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6125 res
= ERROR_HTTP_INVALID_HEADER
; /* FIXME */
6129 /* handle appending to existing header */
6130 if (dwModifier
& COALESCEFLAGS
)
6135 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6136 INT valuelen
= strlenW(value
);
6138 /* FIXME: Should it really clear HDR_ISREQUEST? */
6139 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6140 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6142 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6144 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6147 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6149 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6152 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6155 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6157 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6160 lphttpHdr
->lpszValue
= lpsztmp
;
6161 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6164 lphttpHdr
->lpszValue
[origlen
] = ch
;
6166 lphttpHdr
->lpszValue
[origlen
] = ' ';
6170 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6171 lphttpHdr
->lpszValue
[len
] = '\0';
6175 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6176 res
= ERROR_OUTOFMEMORY
;
6183 /* FIXME: What about other combinations? */
6184 if ((dwModifier
& ~HTTP_ADDHDR_FLAG_REQ
) == HTTP_ADDHDR_FLAG_REPLACE
)
6186 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
6190 /* FIXME: What if value == ""? */
6195 hdr
.lpszField
= (LPWSTR
)field
;
6196 hdr
.lpszValue
= (LPWSTR
)value
;
6197 hdr
.wFlags
= hdr
.wCount
= 0;
6199 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6200 hdr
.wFlags
|= HDR_ISREQUEST
;
6202 res
= HTTP_InsertCustomHeader( request
, &hdr
);
6206 /* FIXME: What if value == NULL? */
6208 TRACE("<-- %d\n", res
);
6209 LeaveCriticalSection( &request
->headers_section
);
6213 /***********************************************************************
6214 * HTTP_GetCustomHeaderIndex (internal)
6216 * Return index of custom header from header array
6217 * Headers section must be held
6219 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6220 int requested_index
, BOOL request_only
)
6224 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6226 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6228 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6231 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6234 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6237 if (requested_index
== 0)
6242 if (index
>= request
->nCustHeaders
)
6245 TRACE("Return: %d\n", index
);
6250 /***********************************************************************
6251 * HTTP_InsertCustomHeader (internal)
6253 * Insert header into array
6254 * Headers section must be held
6256 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6259 LPHTTPHEADERW lph
= NULL
;
6261 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6262 count
= request
->nCustHeaders
+ 1;
6264 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6266 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6269 return ERROR_OUTOFMEMORY
;
6271 request
->custHeaders
= lph
;
6272 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6273 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6274 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6275 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6276 request
->nCustHeaders
++;
6278 return ERROR_SUCCESS
;
6282 /***********************************************************************
6283 * HTTP_DeleteCustomHeader (internal)
6285 * Delete header from array
6286 * If this function is called, the index may change.
6287 * Headers section must be held
6289 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6291 if( request
->nCustHeaders
<= 0 )
6293 if( index
>= request
->nCustHeaders
)
6295 request
->nCustHeaders
--;
6297 heap_free(request
->custHeaders
[index
].lpszField
);
6298 heap_free(request
->custHeaders
[index
].lpszValue
);
6300 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6301 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6302 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6308 /***********************************************************************
6309 * IsHostInProxyBypassList (@)
6314 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6316 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);