2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
51 #define NO_SHLWAPI_STREAM
52 #define NO_SHLWAPI_REG
53 #define NO_SHLWAPI_STRFCNS
54 #define NO_SHLWAPI_GDI
61 #include "wine/debug.h"
62 #include "wine/exception.h"
63 #include "wine/unicode.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
67 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
68 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
69 static const WCHAR szOK
[] = {'O','K',0};
70 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
75 static const WCHAR szGET
[] = { 'G','E','T', 0 };
76 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
78 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
79 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
80 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
81 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
82 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
83 static const WCHAR szAge
[] = { 'A','g','e',0 };
84 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
85 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
86 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
87 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
88 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
89 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
90 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
91 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
92 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
93 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
94 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
95 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
96 static const WCHAR szContent_Transfer_Encoding
[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
97 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
98 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
99 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
100 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
101 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
102 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
103 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
104 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
106 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
107 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
108 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
109 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
110 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
111 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
112 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
113 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
114 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
115 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
116 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
117 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
118 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
119 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
120 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
121 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
122 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
123 static const WCHAR szUnless_Modified_Since
[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
124 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
125 static const WCHAR szURI
[] = { 'U','R','I',0 };
126 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
127 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
128 static const WCHAR szVia
[] = { 'V','i','a',0 };
129 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
130 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
132 static const WCHAR emptyW
[] = {0};
134 #define HTTP_REFERER szReferer
135 #define HTTP_ACCEPT szAccept
136 #define HTTP_USERAGENT szUser_Agent
138 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
139 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
140 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
141 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
142 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
143 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
144 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
146 #define COLLECT_TIME 60000
148 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
159 unsigned int auth_data_len
;
160 BOOL finished
; /* finished authenticating */
164 typedef struct _basicAuthorizationData
171 UINT authorizationLen
;
172 } basicAuthorizationData
;
174 typedef struct _authorizationData
188 static struct list basicAuthorizationCache
= LIST_INIT(basicAuthorizationCache
);
189 static struct list authorizationCache
= LIST_INIT(authorizationCache
);
191 static CRITICAL_SECTION authcache_cs
;
192 static CRITICAL_SECTION_DEBUG critsect_debug
=
195 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
196 0, 0, { (DWORD_PTR
)(__FILE__
": authcache_cs") }
198 static CRITICAL_SECTION authcache_cs
= { &critsect_debug
, -1, 0, 0, 0, 0 };
200 static DWORD
HTTP_GetResponseHeaders(http_request_t
*req
, INT
*len
);
201 static DWORD
HTTP_ProcessHeader(http_request_t
*req
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
);
202 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
);
203 static DWORD
HTTP_InsertCustomHeader(http_request_t
*req
, LPHTTPHEADERW lpHdr
);
204 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*req
, LPCWSTR lpszField
, INT index
, BOOL Request
);
205 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*req
, DWORD index
);
206 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
);
207 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*, DWORD
, LPVOID
, LPDWORD
, LPDWORD
);
208 static UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
209 static BOOL
drain_content(http_request_t
*,BOOL
);
211 static CRITICAL_SECTION connection_pool_cs
;
212 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
214 0, 0, &connection_pool_cs
,
215 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
216 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
218 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
220 static struct list connection_pool
= LIST_INIT(connection_pool
);
221 static BOOL collector_running
;
223 void server_addref(server_t
*server
)
225 InterlockedIncrement(&server
->ref
);
228 void server_release(server_t
*server
)
230 if(InterlockedDecrement(&server
->ref
))
233 list_remove(&server
->entry
);
235 if(server
->cert_chain
)
236 CertFreeCertificateChain(server
->cert_chain
);
237 heap_free(server
->name
);
238 heap_free(server
->scheme_host_port
);
242 static BOOL
process_host_port(server_t
*server
)
248 static const WCHAR httpW
[] = {'h','t','t','p',0};
249 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
250 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
252 name_len
= strlenW(server
->name
);
253 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
257 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
258 server
->scheme_host_port
= buf
;
260 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
264 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
265 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
269 server_t
*get_server(substr_t name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
271 server_t
*iter
, *server
= NULL
;
273 EnterCriticalSection(&connection_pool_cs
);
275 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
276 if(iter
->port
== port
&& name
.len
== strlenW(iter
->name
) && !strncmpW(iter
->name
, name
.str
, name
.len
)
277 && iter
->is_https
== is_https
) {
279 server_addref(server
);
284 if(!server
&& do_create
) {
285 server
= heap_alloc_zero(sizeof(*server
));
287 server
->ref
= 2; /* list reference and return */
289 server
->is_https
= is_https
;
290 list_init(&server
->conn_pool
);
291 server
->name
= heap_strndupW(name
.str
, name
.len
);
292 if(server
->name
&& process_host_port(server
)) {
293 list_add_head(&connection_pool
, &server
->entry
);
301 LeaveCriticalSection(&connection_pool_cs
);
306 BOOL
collect_connections(collect_type_t collect_type
)
308 netconn_t
*netconn
, *netconn_safe
;
309 server_t
*server
, *server_safe
;
310 BOOL remaining
= FALSE
;
313 now
= GetTickCount64();
315 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
316 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
317 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
318 TRACE("freeing %p\n", netconn
);
319 list_remove(&netconn
->pool_entry
);
320 free_netconn(netconn
);
326 if(collect_type
== COLLECT_CLEANUP
) {
327 list_remove(&server
->entry
);
328 list_init(&server
->entry
);
329 server_release(server
);
336 static DWORD WINAPI
collect_connections_proc(void *arg
)
338 BOOL remaining_conns
;
341 /* FIXME: Use more sophisticated method */
344 EnterCriticalSection(&connection_pool_cs
);
346 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
348 collector_running
= FALSE
;
350 LeaveCriticalSection(&connection_pool_cs
);
351 }while(remaining_conns
);
353 FreeLibraryAndExitThread(WININET_hModule
, 0);
356 /***********************************************************************
357 * HTTP_GetHeader (internal)
359 * Headers section must be held
361 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
364 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
365 if (HeaderIndex
== -1)
368 return &req
->custHeaders
[HeaderIndex
];
371 static WCHAR
*get_host_header( http_request_t
*req
)
376 EnterCriticalSection( &req
->headers_section
);
377 if ((header
= HTTP_GetHeader( req
, hostW
))) ret
= heap_strdupW( header
->lpszValue
);
378 else ret
= heap_strdupW( req
->server
->canon_host_port
);
379 LeaveCriticalSection( &req
->headers_section
);
383 struct data_stream_vtbl_t
{
384 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
385 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,BOOL
);
386 BOOL (*drain_content
)(data_stream_t
*,http_request_t
*);
387 void (*destroy
)(data_stream_t
*);
391 data_stream_t data_stream
;
393 BYTE buf
[READ_BUFFER_SIZE
];
399 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
,
400 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
,
401 CHUNKED_STREAM_STATE_READING_CHUNK
,
402 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
,
403 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
,
404 CHUNKED_STREAM_STATE_END_OF_STREAM
408 static inline void destroy_data_stream(data_stream_t
*stream
)
410 stream
->vtbl
->destroy(stream
);
413 static void reset_data_stream(http_request_t
*req
)
415 destroy_data_stream(req
->data_stream
);
416 req
->data_stream
= &req
->netconn_stream
.data_stream
;
417 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
418 req
->read_gzip
= FALSE
;
421 static void remove_header( http_request_t
*request
, const WCHAR
*str
, BOOL from_request
)
424 EnterCriticalSection( &request
->headers_section
);
425 index
= HTTP_GetCustomHeaderIndex( request
, str
, 0, from_request
);
426 if (index
!= -1) HTTP_DeleteCustomHeader( request
, index
);
427 LeaveCriticalSection( &request
->headers_section
);
433 data_stream_t stream
;
434 data_stream_t
*parent_stream
;
436 BYTE buf
[READ_BUFFER_SIZE
];
442 static BOOL
gzip_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
444 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
445 return gzip_stream
->end_of_data
446 || (!gzip_stream
->buf_size
&& gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
));
449 static DWORD
gzip_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
450 DWORD
*read
, BOOL allow_blocking
)
452 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
453 z_stream
*zstream
= &gzip_stream
->zstream
;
454 DWORD current_read
, ret_read
= 0;
456 DWORD res
= ERROR_SUCCESS
;
458 TRACE("(%d %x)\n", size
, allow_blocking
);
460 while(size
&& !gzip_stream
->end_of_data
) {
461 if(!gzip_stream
->buf_size
) {
462 if(gzip_stream
->buf_pos
) {
463 if(gzip_stream
->buf_size
)
464 memmove(gzip_stream
->buf
, gzip_stream
->buf
+gzip_stream
->buf_pos
, gzip_stream
->buf_size
);
465 gzip_stream
->buf_pos
= 0;
467 res
= gzip_stream
->parent_stream
->vtbl
->read(gzip_stream
->parent_stream
, req
, gzip_stream
->buf
+gzip_stream
->buf_size
,
468 sizeof(gzip_stream
->buf
)-gzip_stream
->buf_size
, ¤t_read
, allow_blocking
);
469 gzip_stream
->buf_size
+= current_read
;
470 if(res
!= ERROR_SUCCESS
)
474 WARN("unexpected end of data\n");
475 gzip_stream
->end_of_data
= TRUE
;
480 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
481 zstream
->avail_in
= gzip_stream
->buf_size
;
482 zstream
->next_out
= buf
+ret_read
;
483 zstream
->avail_out
= size
;
484 zres
= inflate(&gzip_stream
->zstream
, 0);
485 current_read
= size
- zstream
->avail_out
;
486 size
-= current_read
;
487 ret_read
+= current_read
;
488 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
489 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
490 if(zres
== Z_STREAM_END
) {
491 TRACE("end of data\n");
492 gzip_stream
->end_of_data
= TRUE
;
494 }else if(zres
!= Z_OK
) {
495 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
497 res
= ERROR_INTERNET_DECODING_FAILED
;
502 allow_blocking
= FALSE
;
505 TRACE("read %u bytes\n", ret_read
);
512 static BOOL
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
)
514 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
515 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
);
518 static void gzip_destroy(data_stream_t
*stream
)
520 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
522 destroy_data_stream(gzip_stream
->parent_stream
);
524 if(!gzip_stream
->end_of_data
)
525 inflateEnd(&gzip_stream
->zstream
);
526 heap_free(gzip_stream
);
529 static const data_stream_vtbl_t gzip_stream_vtbl
= {
536 static voidpf
wininet_zalloc(voidpf opaque
, uInt items
, uInt size
)
538 return heap_alloc(items
*size
);
541 static void wininet_zfree(voidpf opaque
, voidpf address
)
546 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
548 gzip_stream_t
*gzip_stream
;
551 gzip_stream
= heap_alloc_zero(sizeof(gzip_stream_t
));
553 return ERROR_OUTOFMEMORY
;
555 gzip_stream
->stream
.vtbl
= &gzip_stream_vtbl
;
556 gzip_stream
->zstream
.zalloc
= wininet_zalloc
;
557 gzip_stream
->zstream
.zfree
= wininet_zfree
;
559 zres
= inflateInit2(&gzip_stream
->zstream
, is_gzip
? 0x1f : -15);
561 ERR("inflateInit failed: %d\n", zres
);
562 heap_free(gzip_stream
);
563 return ERROR_OUTOFMEMORY
;
566 remove_header(req
, szContent_Length
, FALSE
);
569 memcpy(gzip_stream
->buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
570 gzip_stream
->buf_size
= req
->read_size
;
571 req
->read_pos
= req
->read_size
= 0;
574 req
->read_gzip
= TRUE
;
575 gzip_stream
->parent_stream
= req
->data_stream
;
576 req
->data_stream
= &gzip_stream
->stream
;
577 return ERROR_SUCCESS
;
582 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
584 ERR("gzip stream not supported, missing zlib.\n");
585 return ERROR_SUCCESS
;
590 /***********************************************************************
591 * HTTP_FreeTokens (internal)
593 * Frees table of pointers.
595 static void HTTP_FreeTokens(LPWSTR
* token_array
)
598 for (i
= 0; token_array
[i
]; i
++) heap_free(token_array
[i
]);
599 heap_free(token_array
);
602 static void HTTP_FixURL(http_request_t
*request
)
604 static const WCHAR szSlash
[] = { '/',0 };
605 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/', 0 };
607 /* If we don't have a path we set it to root */
608 if (NULL
== request
->path
)
609 request
->path
= heap_strdupW(szSlash
);
610 else /* remove \r and \n*/
612 int nLen
= strlenW(request
->path
);
613 while ((nLen
>0 ) && ((request
->path
[nLen
-1] == '\r')||(request
->path
[nLen
-1] == '\n')))
616 request
->path
[nLen
]='\0';
618 /* Replace '\' with '/' */
621 if (request
->path
[nLen
] == '\\') request
->path
[nLen
]='/';
625 if(CSTR_EQUAL
!= CompareStringW( LOCALE_INVARIANT
, NORM_IGNORECASE
,
626 request
->path
, strlenW(request
->path
), szHttp
, strlenW(szHttp
) )
627 && request
->path
[0] != '/') /* not an absolute path ?? --> fix it !! */
629 WCHAR
*fixurl
= heap_alloc((strlenW(request
->path
) + 2)*sizeof(WCHAR
));
631 strcpyW(fixurl
+ 1, request
->path
);
632 heap_free( request
->path
);
633 request
->path
= fixurl
;
637 static WCHAR
* build_request_header(http_request_t
*request
, const WCHAR
*verb
,
638 const WCHAR
*path
, const WCHAR
*version
, BOOL use_cr
)
640 static const WCHAR szSpace
[] = {' ',0};
641 static const WCHAR szColon
[] = {':',' ',0};
642 static const WCHAR szCr
[] = {'\r',0};
643 static const WCHAR szLf
[] = {'\n',0};
644 LPWSTR requestString
;
649 EnterCriticalSection( &request
->headers_section
);
651 /* allocate space for an array of all the string pointers to be added */
652 len
= request
->nCustHeaders
* 5 + 10;
653 if (!(req
= heap_alloc( len
* sizeof(const WCHAR
*) )))
655 LeaveCriticalSection( &request
->headers_section
);
659 /* add the verb, path and HTTP version string */
670 /* Append custom request headers */
671 for (i
= 0; i
< request
->nCustHeaders
; i
++)
673 if (request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
675 req
[n
++] = request
->custHeaders
[i
].lpszField
;
677 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
682 TRACE("Adding custom header %s (%s)\n",
683 debugstr_w(request
->custHeaders
[i
].lpszField
),
684 debugstr_w(request
->custHeaders
[i
].lpszValue
));
692 requestString
= HTTP_build_req( req
, 4 );
694 LeaveCriticalSection( &request
->headers_section
);
695 return requestString
;
698 static WCHAR
* build_response_header(http_request_t
*request
, BOOL use_cr
)
700 static const WCHAR colonW
[] = { ':',' ',0 };
701 static const WCHAR crW
[] = { '\r',0 };
702 static const WCHAR lfW
[] = { '\n',0 };
703 static const WCHAR status_fmt
[] = { ' ','%','u',' ',0 };
708 EnterCriticalSection( &request
->headers_section
);
710 if (!(req
= heap_alloc( (request
->nCustHeaders
* 5 + 8) * sizeof(WCHAR
*) )))
712 LeaveCriticalSection( &request
->headers_section
);
716 if (request
->status_code
)
718 req
[n
++] = request
->version
;
719 sprintfW(buf
, status_fmt
, request
->status_code
);
721 req
[n
++] = request
->statusText
;
727 for(i
= 0; i
< request
->nCustHeaders
; i
++)
729 if(!(request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
730 && strcmpW(request
->custHeaders
[i
].lpszField
, szStatus
))
732 req
[n
++] = request
->custHeaders
[i
].lpszField
;
734 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
739 TRACE("Adding custom header %s (%s)\n",
740 debugstr_w(request
->custHeaders
[i
].lpszField
),
741 debugstr_w(request
->custHeaders
[i
].lpszValue
));
749 ret
= HTTP_build_req(req
, 0);
751 LeaveCriticalSection( &request
->headers_section
);
755 static void HTTP_ProcessCookies( http_request_t
*request
)
759 LPHTTPHEADERW setCookieHeader
;
761 if(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
)
764 EnterCriticalSection( &request
->headers_section
);
766 while((HeaderIndex
= HTTP_GetCustomHeaderIndex(request
, szSet_Cookie
, numCookies
++, FALSE
)) != -1)
771 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
773 if (!setCookieHeader
->lpszValue
)
776 data
= strchrW(setCookieHeader
->lpszValue
, '=');
780 name
= substr(setCookieHeader
->lpszValue
, data
- setCookieHeader
->lpszValue
);
782 set_cookie(substrz(request
->server
->name
), substrz(request
->path
), name
, substrz(data
), INTERNET_COOKIE_HTTPONLY
);
785 LeaveCriticalSection( &request
->headers_section
);
788 static void strip_spaces(LPWSTR start
)
797 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
799 end
= start
+ strlenW(start
) - 1;
800 while (end
>= start
&& *end
== ' ')
807 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
809 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
810 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
812 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAYSIZE(szBasic
)) &&
813 ((pszAuthValue
[ARRAYSIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAYSIZE(szBasic
)]);
814 if (is_basic
&& pszRealm
)
817 LPCWSTR ptr
= &pszAuthValue
[ARRAYSIZE(szBasic
)];
821 token
= strchrW(ptr
,'=');
825 while (*realm
== ' ')
827 if(!strncmpiW(realm
, szRealm
, ARRAYSIZE(szRealm
)) &&
828 (realm
[ARRAYSIZE(szRealm
)] == ' ' || realm
[ARRAYSIZE(szRealm
)] == '='))
831 while (*token
== ' ')
835 *pszRealm
= heap_strdupW(token
);
836 strip_spaces(*pszRealm
);
843 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
845 if (!authinfo
) return;
847 if (SecIsValidHandle(&authinfo
->ctx
))
848 DeleteSecurityContext(&authinfo
->ctx
);
849 if (SecIsValidHandle(&authinfo
->cred
))
850 FreeCredentialsHandle(&authinfo
->cred
);
852 heap_free(authinfo
->auth_data
);
853 heap_free(authinfo
->scheme
);
857 static UINT
retrieve_cached_basic_authorization(const WCHAR
*host
, const WCHAR
*realm
, char **auth_data
)
859 basicAuthorizationData
*ad
;
862 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
864 EnterCriticalSection(&authcache_cs
);
865 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
867 if (!strcmpiW(host
, ad
->host
) && (!realm
|| !strcmpW(realm
, ad
->realm
)))
869 TRACE("Authorization found in cache\n");
870 *auth_data
= heap_alloc(ad
->authorizationLen
);
871 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
872 rc
= ad
->authorizationLen
;
876 LeaveCriticalSection(&authcache_cs
);
880 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
883 basicAuthorizationData
* ad
= NULL
;
885 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
887 EnterCriticalSection(&authcache_cs
);
888 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
890 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
891 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
900 TRACE("Found match in cache, replacing\n");
901 heap_free(ad
->authorization
);
902 ad
->authorization
= heap_alloc(auth_data_len
);
903 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
904 ad
->authorizationLen
= auth_data_len
;
908 ad
= heap_alloc(sizeof(basicAuthorizationData
));
909 ad
->host
= heap_strdupW(host
);
910 ad
->realm
= heap_strdupW(realm
);
911 ad
->authorization
= heap_alloc(auth_data_len
);
912 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
913 ad
->authorizationLen
= auth_data_len
;
914 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
915 TRACE("authorization cached\n");
917 LeaveCriticalSection(&authcache_cs
);
920 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
921 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
923 authorizationData
*ad
;
925 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
927 EnterCriticalSection(&authcache_cs
);
928 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
929 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
930 TRACE("Authorization found in cache\n");
932 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
933 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
934 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
935 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
936 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
937 heap_free(nt_auth_identity
->User
);
938 heap_free(nt_auth_identity
->Password
);
939 heap_free(nt_auth_identity
->Domain
);
943 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
944 nt_auth_identity
->UserLength
= ad
->user_len
;
945 nt_auth_identity
->PasswordLength
= ad
->password_len
;
946 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
947 nt_auth_identity
->DomainLength
= ad
->domain_len
;
948 LeaveCriticalSection(&authcache_cs
);
952 LeaveCriticalSection(&authcache_cs
);
957 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
958 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
960 authorizationData
*ad
;
963 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
965 EnterCriticalSection(&authcache_cs
);
966 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
967 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
974 heap_free(ad
->password
);
975 heap_free(ad
->domain
);
977 ad
= heap_alloc(sizeof(authorizationData
));
979 LeaveCriticalSection(&authcache_cs
);
983 ad
->host
= heap_strdupW(host
);
984 ad
->scheme
= heap_strdupW(scheme
);
985 list_add_head(&authorizationCache
, &ad
->entry
);
988 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
989 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
990 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
991 ad
->user_len
= nt_auth_identity
->UserLength
;
992 ad
->password_len
= nt_auth_identity
->PasswordLength
;
993 ad
->domain_len
= nt_auth_identity
->DomainLength
;
995 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
996 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
998 heap_free(ad
->scheme
);
1000 heap_free(ad
->password
);
1001 heap_free(ad
->domain
);
1002 list_remove(&ad
->entry
);
1006 LeaveCriticalSection(&authcache_cs
);
1009 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
1010 struct HttpAuthInfo
**ppAuthInfo
,
1011 LPWSTR domain_and_username
, LPWSTR password
,
1014 SECURITY_STATUS sec_status
;
1015 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
1017 LPWSTR szRealm
= NULL
;
1019 TRACE("%s\n", debugstr_w(pszAuthValue
));
1026 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
1030 SecInvalidateHandle(&pAuthInfo
->cred
);
1031 SecInvalidateHandle(&pAuthInfo
->ctx
);
1032 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1033 pAuthInfo
->attr
= 0;
1034 pAuthInfo
->auth_data
= NULL
;
1035 pAuthInfo
->auth_data_len
= 0;
1036 pAuthInfo
->finished
= FALSE
;
1038 if (is_basic_auth_value(pszAuthValue
,NULL
))
1040 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1041 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1042 if (!pAuthInfo
->scheme
)
1044 heap_free(pAuthInfo
);
1051 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1053 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1054 if (!pAuthInfo
->scheme
)
1056 heap_free(pAuthInfo
);
1060 if (domain_and_username
)
1062 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1063 WCHAR
*domain
= domain_and_username
;
1065 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1067 pAuthData
= &nt_auth_identity
;
1072 user
= domain_and_username
;
1076 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1077 nt_auth_identity
.User
= user
;
1078 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1079 nt_auth_identity
.Domain
= domain
;
1080 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1081 nt_auth_identity
.Password
= password
;
1082 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1084 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1086 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1087 pAuthData
= &nt_auth_identity
;
1089 /* use default credentials */
1092 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1093 SECPKG_CRED_OUTBOUND
, NULL
,
1095 NULL
, &pAuthInfo
->cred
,
1098 if(pAuthData
&& !domain_and_username
) {
1099 heap_free(nt_auth_identity
.User
);
1100 heap_free(nt_auth_identity
.Domain
);
1101 heap_free(nt_auth_identity
.Password
);
1104 if (sec_status
== SEC_E_OK
)
1106 PSecPkgInfoW sec_pkg_info
;
1107 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1108 if (sec_status
== SEC_E_OK
)
1110 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1111 FreeContextBuffer(sec_pkg_info
);
1114 if (sec_status
!= SEC_E_OK
)
1116 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1117 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1118 heap_free(pAuthInfo
->scheme
);
1119 heap_free(pAuthInfo
);
1123 *ppAuthInfo
= pAuthInfo
;
1125 else if (pAuthInfo
->finished
)
1128 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1129 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1131 ERR("authentication scheme changed from %s to %s\n",
1132 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1136 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1140 char *auth_data
= NULL
;
1141 UINT auth_data_len
= 0;
1143 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1145 if (!domain_and_username
)
1147 if (host
&& szRealm
)
1148 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1149 if (auth_data_len
== 0)
1157 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1158 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1160 /* length includes a nul terminator, which will be re-used for the ':' */
1161 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1168 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1169 auth_data
[userlen
] = ':';
1170 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1171 auth_data_len
= userlen
+ 1 + passlen
;
1172 if (host
&& szRealm
)
1173 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1176 pAuthInfo
->auth_data
= auth_data
;
1177 pAuthInfo
->auth_data_len
= auth_data_len
;
1178 pAuthInfo
->finished
= TRUE
;
1184 LPCWSTR pszAuthData
;
1185 SecBufferDesc out_desc
, in_desc
;
1187 unsigned char *buffer
;
1188 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1189 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1191 in
.BufferType
= SECBUFFER_TOKEN
;
1195 in_desc
.ulVersion
= 0;
1196 in_desc
.cBuffers
= 1;
1197 in_desc
.pBuffers
= &in
;
1199 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1200 if (*pszAuthData
== ' ')
1203 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1204 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1205 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1208 buffer
= heap_alloc(pAuthInfo
->max_token
);
1210 out
.BufferType
= SECBUFFER_TOKEN
;
1211 out
.cbBuffer
= pAuthInfo
->max_token
;
1212 out
.pvBuffer
= buffer
;
1214 out_desc
.ulVersion
= 0;
1215 out_desc
.cBuffers
= 1;
1216 out_desc
.pBuffers
= &out
;
1218 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1219 first
? NULL
: &pAuthInfo
->ctx
,
1220 first
? request
->server
->name
: NULL
,
1221 context_req
, 0, SECURITY_NETWORK_DREP
,
1222 in
.pvBuffer
? &in_desc
: NULL
,
1223 0, &pAuthInfo
->ctx
, &out_desc
,
1224 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1225 if (sec_status
== SEC_E_OK
)
1227 pAuthInfo
->finished
= TRUE
;
1228 pAuthInfo
->auth_data
= out
.pvBuffer
;
1229 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1230 TRACE("sending last auth packet\n");
1232 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1234 pAuthInfo
->auth_data
= out
.pvBuffer
;
1235 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1236 TRACE("sending next auth packet\n");
1240 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1241 heap_free(out
.pvBuffer
);
1242 destroy_authinfo(pAuthInfo
);
1251 /***********************************************************************
1252 * HTTP_HttpAddRequestHeadersW (internal)
1254 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1255 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1260 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1262 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1264 if( dwHeaderLength
== ~0U )
1265 len
= strlenW(lpszHeader
);
1267 len
= dwHeaderLength
;
1268 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1269 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1275 LPWSTR
* pFieldAndValue
;
1277 lpszEnd
= lpszStart
;
1279 while (*lpszEnd
!= '\0')
1281 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1286 if (*lpszStart
== '\0')
1289 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1292 lpszEnd
++; /* Jump over newline */
1294 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1295 if (*lpszStart
== '\0')
1297 /* Skip 0-length headers */
1298 lpszStart
= lpszEnd
;
1299 res
= ERROR_SUCCESS
;
1302 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1305 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1306 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1307 HTTP_FreeTokens(pFieldAndValue
);
1310 lpszStart
= lpszEnd
;
1311 } while (res
== ERROR_SUCCESS
);
1317 /***********************************************************************
1318 * HttpAddRequestHeadersW (WININET.@)
1320 * Adds one or more HTTP header to the request handler
1323 * On Windows if dwHeaderLength includes the trailing '\0', then
1324 * HttpAddRequestHeadersW() adds it too. However this results in an
1325 * invalid HTTP header which is rejected by some servers so we probably
1326 * don't need to match Windows on that point.
1333 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1334 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1336 http_request_t
*request
;
1337 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1339 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1344 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1345 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1346 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1348 WININET_Release( &request
->hdr
);
1350 if(res
!= ERROR_SUCCESS
)
1352 return res
== ERROR_SUCCESS
;
1355 /***********************************************************************
1356 * HttpAddRequestHeadersA (WININET.@)
1358 * Adds one or more HTTP header to the request handler
1365 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1366 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1368 WCHAR
*headers
= NULL
;
1371 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1374 headers
= heap_strndupAtoW(lpszHeader
, dwHeaderLength
, &dwHeaderLength
);
1376 r
= HttpAddRequestHeadersW(hHttpRequest
, headers
, dwHeaderLength
, dwModifier
);
1382 static void free_accept_types( WCHAR
**accept_types
)
1384 WCHAR
*ptr
, **types
= accept_types
;
1387 while ((ptr
= *types
))
1392 heap_free( accept_types
);
1395 static WCHAR
**convert_accept_types( const char **accept_types
)
1398 const char **types
= accept_types
;
1400 BOOL invalid_pointer
= FALSE
;
1402 if (!types
) return NULL
;
1408 /* find out how many there are */
1409 if (*types
&& **types
)
1411 TRACE("accept type: %s\n", debugstr_a(*types
));
1417 WARN("invalid accept type pointer\n");
1418 invalid_pointer
= TRUE
;
1423 if (invalid_pointer
) return NULL
;
1424 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1426 types
= accept_types
;
1429 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1432 typesW
[count
] = NULL
;
1436 /***********************************************************************
1437 * HttpOpenRequestA (WININET.@)
1439 * Open a HTTP request handle
1442 * HINTERNET a HTTP request handle on success
1446 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1447 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1448 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1449 DWORD dwFlags
, DWORD_PTR dwContext
)
1451 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1452 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1453 HINTERNET rc
= NULL
;
1455 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1456 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1457 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1458 dwFlags
, dwContext
);
1462 szVerb
= heap_strdupAtoW(lpszVerb
);
1469 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1470 if ( !szObjectName
)
1476 szVersion
= heap_strdupAtoW(lpszVersion
);
1483 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1488 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1489 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1490 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1493 free_accept_types(szAcceptTypes
);
1494 heap_free(szReferrer
);
1495 heap_free(szVersion
);
1496 heap_free(szObjectName
);
1501 /***********************************************************************
1504 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1507 static const CHAR HTTP_Base64Enc
[] =
1508 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1512 /* first 6 bits, all from bin[0] */
1513 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1514 x
= (bin
[0] & 3) << 4;
1516 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1519 base64
[n
++] = HTTP_Base64Enc
[x
];
1524 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1525 x
= ( bin
[1] & 0x0f ) << 2;
1527 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1530 base64
[n
++] = HTTP_Base64Enc
[x
];
1534 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1536 /* last 6 bits, all from bin [2] */
1537 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1545 static const signed char HTTP_Base64Dec
[] =
1547 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1548 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1549 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1550 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1551 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1552 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1553 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1554 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1557 /***********************************************************************
1560 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1568 if (base64
[0] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1569 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1570 base64
[1] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1571 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1573 WARN("invalid base64: %s\n", debugstr_w(base64
));
1577 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1580 if ((base64
[2] == '=') && (base64
[3] == '='))
1582 if (base64
[2] > ARRAYSIZE(HTTP_Base64Dec
) ||
1583 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1585 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1589 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1592 if (base64
[3] == '=')
1594 if (base64
[3] > ARRAYSIZE(HTTP_Base64Dec
) ||
1595 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1597 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1601 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1610 static WCHAR
*encode_auth_data( const WCHAR
*scheme
, const char *data
, UINT data_len
)
1613 UINT len
, scheme_len
= strlenW( scheme
);
1615 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1616 len
= scheme_len
+ 1 + ((data_len
+ 2) * 4) / 3;
1617 if (!(ret
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1618 memcpy( ret
, scheme
, scheme_len
* sizeof(WCHAR
) );
1619 ret
[scheme_len
] = ' ';
1620 HTTP_EncodeBase64( data
, data_len
, ret
+ scheme_len
+ 1 );
1625 /***********************************************************************
1626 * HTTP_InsertAuthorization
1628 * Insert or delete the authorization field in the request header.
1630 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1632 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1633 WCHAR
*host
, *authorization
= NULL
;
1637 if (pAuthInfo
->auth_data_len
)
1639 if (!(authorization
= encode_auth_data(pAuthInfo
->scheme
, pAuthInfo
->auth_data
, pAuthInfo
->auth_data_len
)))
1642 /* clear the data as it isn't valid now that it has been sent to the
1643 * server, unless it's Basic authentication which doesn't do
1644 * connection tracking */
1645 if (strcmpiW(pAuthInfo
->scheme
, wszBasic
))
1647 heap_free(pAuthInfo
->auth_data
);
1648 pAuthInfo
->auth_data
= NULL
;
1649 pAuthInfo
->auth_data_len
= 0;
1653 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1655 HTTP_ProcessHeader(request
, header
, authorization
,
1656 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
1657 heap_free(authorization
);
1659 else if (!strcmpW(header
, szAuthorization
) && (host
= get_host_header(request
)))
1664 if ((data_len
= retrieve_cached_basic_authorization(host
, NULL
, &data
)))
1666 TRACE("Found cached basic authorization for %s\n", debugstr_w(host
));
1668 if (!(authorization
= encode_auth_data(wszBasic
, data
, data_len
)))
1675 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1677 HTTP_ProcessHeader(request
, header
, authorization
,
1678 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
1680 heap_free(authorization
);
1687 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1692 len
= strlenW(req
->server
->scheme_host_port
);
1693 size
= len
+ strlenW(req
->path
) + 1;
1694 if(*req
->path
!= '/')
1696 url
= heap_alloc(size
* sizeof(WCHAR
));
1700 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1701 if(*req
->path
!= '/')
1704 strcpyW(url
+len
, req
->path
);
1706 TRACE("url=%s\n", debugstr_w(url
));
1710 static BOOL
HTTP_DomainMatches(LPCWSTR server
, substr_t domain
)
1712 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1713 const WCHAR
*dot
, *ptr
;
1716 if(domain
.len
== sizeof(localW
)/sizeof(WCHAR
)-1 && !strncmpiW(domain
.str
, localW
, domain
.len
) && !strchrW(server
, '.' ))
1719 if(domain
.len
&& *domain
.str
!= '*')
1720 return domain
.len
== strlenW(server
) && !strncmpiW(server
, domain
.str
, domain
.len
);
1722 if(domain
.len
< 2 || domain
.str
[1] != '.')
1725 /* For a hostname to match a wildcard, the last domain must match
1726 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1727 * hostname is www.foo.a.b, it matches, but a.b does not.
1729 dot
= strchrW(server
, '.');
1733 len
= strlenW(dot
+ 1);
1734 if(len
<= domain
.len
- 2)
1737 /* The server's domain is longer than the wildcard, so it
1738 * could be a subdomain. Compare the last portion of the
1741 ptr
= dot
+ 1 + len
- domain
.len
+ 2;
1742 if(!strncmpiW(ptr
, domain
.str
+2, domain
.len
-2))
1743 /* This is only a match if the preceding character is
1744 * a '.', i.e. that it is a matching domain. E.g.
1745 * if domain is '*.b.c' and server is 'www.ab.c' they
1748 return *(ptr
- 1) == '.';
1750 return len
== domain
.len
-2 && !strncmpiW(dot
+ 1, domain
.str
+ 2, len
);
1753 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1758 if (!lpwai
->proxyBypass
) return FALSE
;
1759 ptr
= lpwai
->proxyBypass
;
1763 ptr
= strchrW( ptr
, ';' );
1765 ptr
= strchrW( tmp
, ' ' );
1767 ptr
= tmp
+ strlenW(tmp
);
1768 ret
= HTTP_DomainMatches( server
, substr(tmp
, ptr
-tmp
) );
1776 /***********************************************************************
1777 * HTTP_DealWithProxy
1779 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1781 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1782 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1783 static WCHAR szNul
[] = { 0 };
1784 URL_COMPONENTSW UrlComponents
= { sizeof(UrlComponents
) };
1785 server_t
*new_server
= NULL
;
1788 proxy
= INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
);
1791 if(CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1792 proxy
, strlenW(szHttp
), szHttp
, strlenW(szHttp
))) {
1793 WCHAR
*proxy_url
= heap_alloc(strlenW(proxy
)*sizeof(WCHAR
) + sizeof(szHttp
));
1798 strcpyW(proxy_url
, szHttp
);
1799 strcatW(proxy_url
, proxy
);
1804 UrlComponents
.dwHostNameLength
= 1;
1805 if(InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) && UrlComponents
.dwHostNameLength
) {
1806 if( !request
->path
)
1807 request
->path
= szNul
;
1809 new_server
= get_server(substr(UrlComponents
.lpszHostName
, UrlComponents
.dwHostNameLength
),
1810 UrlComponents
.nPort
, UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
1816 request
->proxy
= new_server
;
1818 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1822 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1824 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1827 if(server
->addr_len
)
1828 return ERROR_SUCCESS
;
1830 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1831 INTERNET_STATUS_RESOLVING_NAME
,
1833 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1835 addr_len
= sizeof(server
->addr
);
1836 if (!GetAddress(server
->name
, server
->port
, (SOCKADDR
*)&server
->addr
, &addr_len
, server
->addr_str
))
1837 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1839 server
->addr_len
= addr_len
;
1840 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1841 INTERNET_STATUS_NAME_RESOLVED
,
1842 server
->addr_str
, strlen(server
->addr_str
)+1);
1844 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1845 return ERROR_SUCCESS
;
1848 static WCHAR
*compose_request_url(http_request_t
*req
)
1850 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1851 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1852 const WCHAR
*host
, *scheme
;
1856 host
= req
->server
->canon_host_port
;
1858 if (req
->server
->is_https
)
1863 len
= strlenW(scheme
) + strlenW(host
) + (req
->path
[0] != '/' ? 1 : 0) + strlenW(req
->path
);
1864 ptr
= buf
= heap_alloc((len
+1) * sizeof(WCHAR
));
1866 strcpyW(ptr
, scheme
);
1867 ptr
+= strlenW(ptr
);
1870 ptr
+= strlenW(ptr
);
1872 if(req
->path
[0] != '/')
1875 strcpyW(ptr
, req
->path
);
1876 ptr
+= strlenW(ptr
);
1884 /***********************************************************************
1885 * HTTPREQ_Destroy (internal)
1887 * Deallocate request handle
1890 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1892 http_request_t
*request
= (http_request_t
*) hdr
;
1897 if(request
->hCacheFile
)
1898 CloseHandle(request
->hCacheFile
);
1899 if(request
->req_file
)
1900 req_file_release(request
->req_file
);
1902 request
->headers_section
.DebugInfo
->Spare
[0] = 0;
1903 DeleteCriticalSection( &request
->headers_section
);
1904 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1905 DeleteCriticalSection( &request
->read_section
);
1906 WININET_Release(&request
->session
->hdr
);
1908 destroy_authinfo(request
->authInfo
);
1909 destroy_authinfo(request
->proxyAuthInfo
);
1912 server_release(request
->server
);
1914 server_release(request
->proxy
);
1916 heap_free(request
->path
);
1917 heap_free(request
->verb
);
1918 heap_free(request
->version
);
1919 heap_free(request
->statusText
);
1921 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1923 heap_free(request
->custHeaders
[i
].lpszField
);
1924 heap_free(request
->custHeaders
[i
].lpszValue
);
1926 destroy_data_stream(request
->data_stream
);
1927 heap_free(request
->custHeaders
);
1930 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1932 TRACE("%p %p %x\n",req
, req
->netconn
, reuse
);
1934 if(!is_valid_netconn(req
->netconn
))
1937 if(reuse
&& req
->netconn
->keep_alive
) {
1940 EnterCriticalSection(&connection_pool_cs
);
1942 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1943 req
->netconn
->keep_until
= GetTickCount64() + COLLECT_TIME
;
1944 req
->netconn
= NULL
;
1946 run_collector
= !collector_running
;
1947 collector_running
= TRUE
;
1949 LeaveCriticalSection(&connection_pool_cs
);
1952 HANDLE thread
= NULL
;
1955 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
1957 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
1959 EnterCriticalSection(&connection_pool_cs
);
1960 collector_running
= FALSE
;
1961 LeaveCriticalSection(&connection_pool_cs
);
1964 FreeLibrary(module
);
1967 CloseHandle(thread
);
1972 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1973 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
1975 close_netconn(req
->netconn
);
1977 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1978 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
1981 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
1983 WCHAR szVersion
[10];
1984 WCHAR szConnectionResponse
[20];
1985 DWORD dwBufferSize
= sizeof(szVersion
);
1986 BOOL keepalive
= FALSE
;
1988 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1989 * the connection is keep-alive by default */
1990 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
1991 && !strcmpiW(szVersion
, g_szHttp1_1
))
1996 dwBufferSize
= sizeof(szConnectionResponse
);
1997 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
1998 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
2000 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2006 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2008 http_request_t
*req
= (http_request_t
*)hdr
;
2010 http_release_netconn(req
, drain_content(req
, FALSE
));
2013 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2018 WCHAR
*buf
= buffer
;
2020 if (str
) len
= strlenW(str
);
2022 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2024 *size
= (len
+ 1) * sizeof(WCHAR
);
2025 return ERROR_INSUFFICIENT_BUFFER
;
2027 if (str
) strcpyW(buf
, str
);
2031 return ERROR_SUCCESS
;
2037 if (str
) len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
2042 return ERROR_INSUFFICIENT_BUFFER
;
2044 if (str
) WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, *size
, NULL
, NULL
);
2048 return ERROR_SUCCESS
;
2052 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2054 http_request_t
*req
= (http_request_t
*)hdr
;
2057 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2059 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2061 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2063 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2064 return ERROR_INSUFFICIENT_BUFFER
;
2065 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2066 /* FIXME: can't get a SOCKET from our connection since we don't use
2070 /* FIXME: get source port from req->netConnection */
2071 info
->SourcePort
= 0;
2072 info
->DestPort
= req
->server
->port
;
2074 if (HTTP_KeepAlive(req
))
2075 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2077 info
->Flags
|= IDSI_FLAG_PROXY
;
2078 if (is_valid_netconn(req
->netconn
) && req
->netconn
->secure
)
2079 info
->Flags
|= IDSI_FLAG_SECURE
;
2081 return ERROR_SUCCESS
;
2085 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2087 case INTERNET_OPTION_SECURITY_FLAGS
:
2091 if (*size
< sizeof(ULONG
))
2092 return ERROR_INSUFFICIENT_BUFFER
;
2094 *size
= sizeof(DWORD
);
2095 flags
= is_valid_netconn(req
->netconn
) ? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2096 *(DWORD
*)buffer
= flags
;
2098 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2099 return ERROR_SUCCESS
;
2102 case INTERNET_OPTION_HANDLE_TYPE
:
2103 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2105 if (*size
< sizeof(ULONG
))
2106 return ERROR_INSUFFICIENT_BUFFER
;
2108 *size
= sizeof(DWORD
);
2109 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2110 return ERROR_SUCCESS
;
2112 case INTERNET_OPTION_URL
: {
2116 TRACE("INTERNET_OPTION_URL\n");
2118 url
= compose_request_url(req
);
2120 return ERROR_OUTOFMEMORY
;
2122 res
= str_to_buffer(url
, buffer
, size
, unicode
);
2126 case INTERNET_OPTION_USER_AGENT
:
2127 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2128 case INTERNET_OPTION_USERNAME
:
2129 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2130 case INTERNET_OPTION_PASSWORD
:
2131 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2132 case INTERNET_OPTION_PROXY_USERNAME
:
2133 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2134 case INTERNET_OPTION_PROXY_PASSWORD
:
2135 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2137 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2138 INTERNET_CACHE_ENTRY_INFOW
*info
;
2139 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2140 DWORD nbytes
, error
;
2143 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2146 return ERROR_FILE_NOT_FOUND
;
2148 if (*size
< sizeof(*ts
))
2150 *size
= sizeof(*ts
);
2151 return ERROR_INSUFFICIENT_BUFFER
;
2155 ret
= GetUrlCacheEntryInfoW(req
->req_file
->url
, NULL
, &nbytes
);
2156 error
= GetLastError();
2157 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2159 if (!(info
= heap_alloc(nbytes
)))
2160 return ERROR_OUTOFMEMORY
;
2162 GetUrlCacheEntryInfoW(req
->req_file
->url
, info
, &nbytes
);
2164 ts
->ftExpires
= info
->ExpireTime
;
2165 ts
->ftLastModified
= info
->LastModifiedTime
;
2168 *size
= sizeof(*ts
);
2169 return ERROR_SUCCESS
;
2174 case INTERNET_OPTION_DATAFILE_NAME
: {
2177 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2179 if(!req
->req_file
) {
2181 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2185 req_size
= (lstrlenW(req
->req_file
->file_name
)+1) * sizeof(WCHAR
);
2186 if(*size
< req_size
)
2187 return ERROR_INSUFFICIENT_BUFFER
;
2190 memcpy(buffer
, req
->req_file
->file_name
, *size
);
2191 return ERROR_SUCCESS
;
2193 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
, -1, NULL
, 0, NULL
, NULL
);
2194 if (req_size
> *size
)
2195 return ERROR_INSUFFICIENT_BUFFER
;
2197 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
,
2198 -1, buffer
, *size
, NULL
, NULL
);
2199 return ERROR_SUCCESS
;
2203 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2204 PCCERT_CONTEXT context
;
2207 return ERROR_INTERNET_INVALID_OPERATION
;
2209 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2210 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2211 return ERROR_INSUFFICIENT_BUFFER
;
2214 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2216 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2219 memset(info
, 0, sizeof(*info
));
2220 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2221 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2222 len
= CertNameToStrA(context
->dwCertEncodingType
,
2223 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2224 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2225 if(info
->lpszSubjectInfo
)
2226 CertNameToStrA(context
->dwCertEncodingType
,
2227 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2228 info
->lpszSubjectInfo
, len
);
2229 len
= CertNameToStrA(context
->dwCertEncodingType
,
2230 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2231 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2232 if(info
->lpszIssuerInfo
)
2233 CertNameToStrA(context
->dwCertEncodingType
,
2234 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2235 info
->lpszIssuerInfo
, len
);
2236 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2237 CertFreeCertificateContext(context
);
2238 return ERROR_SUCCESS
;
2240 return ERROR_NOT_SUPPORTED
;
2242 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2243 if (*size
< sizeof(DWORD
))
2244 return ERROR_INSUFFICIENT_BUFFER
;
2246 *size
= sizeof(DWORD
);
2247 *(DWORD
*)buffer
= req
->connect_timeout
;
2248 return ERROR_SUCCESS
;
2249 case INTERNET_OPTION_REQUEST_FLAGS
: {
2252 if (*size
< sizeof(DWORD
))
2253 return ERROR_INSUFFICIENT_BUFFER
;
2255 /* FIXME: Add support for:
2256 * INTERNET_REQFLAG_FROM_CACHE
2257 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2261 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2262 if(!req
->status_code
)
2263 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2265 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2267 *size
= sizeof(DWORD
);
2268 *(DWORD
*)buffer
= flags
;
2269 return ERROR_SUCCESS
;
2273 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2276 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2278 http_request_t
*req
= (http_request_t
*)hdr
;
2281 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2282 TRACE("Undocumented option 99\n");
2284 if (!buffer
|| size
!= sizeof(DWORD
))
2285 return ERROR_INVALID_PARAMETER
;
2286 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2287 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2290 case INTERNET_OPTION_SECURITY_FLAGS
:
2294 if (!buffer
|| size
!= sizeof(DWORD
))
2295 return ERROR_INVALID_PARAMETER
;
2296 flags
= *(DWORD
*)buffer
;
2297 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2298 flags
&= SECURITY_SET_MASK
;
2299 req
->security_flags
|= flags
;
2300 if(is_valid_netconn(req
->netconn
))
2301 req
->netconn
->security_flags
|= flags
;
2302 return ERROR_SUCCESS
;
2304 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2305 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2306 req
->connect_timeout
= *(DWORD
*)buffer
;
2307 return ERROR_SUCCESS
;
2309 case INTERNET_OPTION_SEND_TIMEOUT
:
2310 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2311 req
->send_timeout
= *(DWORD
*)buffer
;
2312 return ERROR_SUCCESS
;
2314 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2315 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2316 req
->receive_timeout
= *(DWORD
*)buffer
;
2317 return ERROR_SUCCESS
;
2319 case INTERNET_OPTION_USERNAME
:
2320 heap_free(req
->session
->userName
);
2321 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2322 return ERROR_SUCCESS
;
2324 case INTERNET_OPTION_PASSWORD
:
2325 heap_free(req
->session
->password
);
2326 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2327 return ERROR_SUCCESS
;
2329 case INTERNET_OPTION_PROXY_USERNAME
:
2330 heap_free(req
->session
->appInfo
->proxyUsername
);
2331 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2332 return ERROR_SUCCESS
;
2334 case INTERNET_OPTION_PROXY_PASSWORD
:
2335 heap_free(req
->session
->appInfo
->proxyPassword
);
2336 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2337 return ERROR_SUCCESS
;
2339 case INTERNET_OPTION_HTTP_DECODING
:
2340 if(size
!= sizeof(BOOL
))
2341 return ERROR_INVALID_PARAMETER
;
2342 req
->decoding
= *(BOOL
*)buffer
;
2343 return ERROR_SUCCESS
;
2346 return INET_SetOption(hdr
, option
, buffer
, size
);
2349 static void commit_cache_entry(http_request_t
*req
)
2357 CloseHandle(req
->hCacheFile
);
2358 req
->hCacheFile
= NULL
;
2360 header
= build_response_header(req
, TRUE
);
2361 header_len
= (header
? strlenW(header
) : 0);
2362 res
= CommitUrlCacheEntryW(req
->req_file
->url
, req
->req_file
->file_name
, req
->expires
,
2363 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2364 header
, header_len
, NULL
, 0);
2366 req
->req_file
->is_committed
= TRUE
;
2368 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2372 static void create_cache_entry(http_request_t
*req
)
2374 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2375 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2377 WCHAR file_name
[MAX_PATH
+1];
2381 /* FIXME: We should free previous cache file earlier */
2383 req_file_release(req
->req_file
);
2384 req
->req_file
= NULL
;
2386 if(req
->hCacheFile
) {
2387 CloseHandle(req
->hCacheFile
);
2388 req
->hCacheFile
= NULL
;
2391 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2397 EnterCriticalSection( &req
->headers_section
);
2399 header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2400 if(header_idx
!= -1) {
2403 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2406 while(*ptr
==' ' || *ptr
=='\t')
2409 end
= strchrW(ptr
, ',');
2411 end
= ptr
+ strlenW(ptr
);
2413 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2414 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2425 LeaveCriticalSection( &req
->headers_section
);
2429 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2432 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2435 url
= compose_request_url(req
);
2437 WARN("Could not get URL\n");
2441 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2443 WARN("Could not create cache entry: %08x\n", GetLastError());
2447 create_req_file(file_name
, &req
->req_file
);
2448 req
->req_file
->url
= url
;
2450 req
->hCacheFile
= CreateFileW(file_name
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2451 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2452 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2453 WARN("Could not create file: %u\n", GetLastError());
2454 req
->hCacheFile
= NULL
;
2458 if(req
->read_size
) {
2461 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2463 FIXME("WriteFile failed: %u\n", GetLastError());
2465 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2466 commit_cache_entry(req
);
2470 /* read some more data into the read buffer (the read section must be held) */
2471 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2478 /* move existing data to the start of the buffer */
2480 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2484 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2486 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2487 maxlen
- req
->read_size
, TRUE
, &len
);
2488 if(res
== ERROR_SUCCESS
)
2489 req
->read_size
+= len
;
2494 /* remove some amount of data from the read buffer (the read section must be held) */
2495 static void remove_data( http_request_t
*req
, int count
)
2497 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2498 else req
->read_pos
+= count
;
2501 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2503 int count
, bytes_read
, pos
= 0;
2506 EnterCriticalSection( &req
->read_section
);
2509 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2513 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2514 bytes_read
= count
+ 1;
2516 else count
= bytes_read
= req
->read_size
;
2518 count
= min( count
, *len
- pos
);
2519 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2521 remove_data( req
, bytes_read
);
2524 if ((res
= read_more_data( req
, -1 )))
2526 WARN( "read failed %u\n", res
);
2527 LeaveCriticalSection( &req
->read_section
);
2530 if (!req
->read_size
)
2533 TRACE( "returning empty string\n" );
2534 LeaveCriticalSection( &req
->read_section
);
2535 return ERROR_SUCCESS
;
2538 LeaveCriticalSection( &req
->read_section
);
2542 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2545 buffer
[*len
- 1] = 0;
2546 TRACE( "returning %s\n", debugstr_a(buffer
));
2547 return ERROR_SUCCESS
;
2550 /* check if we have reached the end of the data to read (the read section must be held) */
2551 static BOOL
end_of_read_data( http_request_t
*req
)
2553 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2556 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, BOOL allow_blocking
)
2560 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, allow_blocking
);
2561 if(res
!= ERROR_SUCCESS
)
2563 assert(*read
<= size
);
2565 if(req
->hCacheFile
) {
2570 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2572 FIXME("WriteFile failed: %u\n", GetLastError());
2575 if((res
== ERROR_SUCCESS
&& !*read
) || req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2576 commit_cache_entry(req
);
2582 /* fetch some more data into the read buffer (the read section must be held) */
2583 static DWORD
refill_read_buffer(http_request_t
*req
, BOOL allow_blocking
, DWORD
*read_bytes
)
2587 if(req
->read_size
== sizeof(req
->read_buf
))
2588 return ERROR_SUCCESS
;
2592 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2596 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2597 &read
, allow_blocking
);
2598 if(res
!= ERROR_SUCCESS
)
2601 req
->read_size
+= read
;
2603 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2609 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2611 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2612 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !is_valid_netconn(req
->netconn
);
2615 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2616 DWORD
*read
, BOOL allow_blocking
)
2618 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2619 DWORD res
= ERROR_SUCCESS
;
2622 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2624 if(size
&& is_valid_netconn(req
->netconn
)) {
2625 res
= NETCON_recv(req
->netconn
, buf
, size
, allow_blocking
, &ret
);
2626 if(res
== ERROR_SUCCESS
) {
2628 netconn_stream
->content_length
= netconn_stream
->content_read
;
2629 netconn_stream
->content_read
+= ret
;
2633 TRACE("res %u read %u bytes\n", res
, ret
);
2638 static BOOL
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2640 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2645 if(netconn_stream
->content_length
== ~0u)
2648 while(netconn_stream
->content_read
< netconn_stream
->content_length
) {
2649 size
= min(sizeof(buf
), netconn_stream
->content_length
-netconn_stream
->content_read
);
2650 res
= NETCON_recv(req
->netconn
, buf
, size
, FALSE
, &len
);
2654 netconn_stream
->content_read
+= len
;
2660 static void netconn_destroy(data_stream_t
*stream
)
2664 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2665 netconn_end_of_data
,
2667 netconn_drain_content
,
2671 static char next_chunked_data_char(chunked_stream_t
*stream
)
2673 assert(stream
->buf_size
);
2676 return stream
->buf
[stream
->buf_pos
++];
2679 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2681 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2682 return chunked_stream
->state
== CHUNKED_STREAM_STATE_END_OF_STREAM
;
2685 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2686 DWORD
*read
, BOOL allow_blocking
)
2688 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2689 DWORD ret_read
= 0, res
= ERROR_SUCCESS
;
2690 BOOL continue_read
= TRUE
;
2695 TRACE("state %d\n", chunked_stream
->state
);
2697 /* Ensure that we have data in the buffer for states that need it. */
2698 if(!chunked_stream
->buf_size
) {
2699 switch(chunked_stream
->state
) {
2700 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
:
2701 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
:
2702 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
:
2703 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2704 chunked_stream
->buf_pos
= 0;
2705 res
= NETCON_recv(req
->netconn
, chunked_stream
->buf
, sizeof(chunked_stream
->buf
), allow_blocking
, &read_bytes
);
2706 if(res
== ERROR_SUCCESS
&& read_bytes
) {
2707 chunked_stream
->buf_size
+= read_bytes
;
2708 }else if(res
== WSAEWOULDBLOCK
) {
2710 res
= ERROR_SUCCESS
;
2711 continue_read
= FALSE
;
2714 chunked_stream
->state
= CHUNKED_STREAM_STATE_END_OF_STREAM
;
2722 switch(chunked_stream
->state
) {
2723 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
:
2724 ch
= next_chunked_data_char(chunked_stream
);
2726 if(ch
>= '0' && ch
<= '9') {
2727 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- '0';
2728 }else if(ch
>= 'a' && ch
<= 'f') {
2729 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- 'a' + 10;
2730 }else if (ch
>= 'A' && ch
<= 'F') {
2731 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- 'A' + 10;
2732 }else if (ch
== ';' || ch
== '\r' || ch
== '\n') {
2733 TRACE("reading %u byte chunk\n", chunked_stream
->chunk_size
);
2734 chunked_stream
->buf_size
++;
2735 chunked_stream
->buf_pos
--;
2736 if(req
->contentLength
== ~0u) req
->contentLength
= chunked_stream
->chunk_size
;
2737 else req
->contentLength
+= chunked_stream
->chunk_size
;
2738 chunked_stream
->state
= CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
;
2742 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
:
2743 ch
= next_chunked_data_char(chunked_stream
);
2745 chunked_stream
->state
= chunked_stream
->chunk_size
2746 ? CHUNKED_STREAM_STATE_READING_CHUNK
2747 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
;
2749 WARN("unexpected char '%c'\n", ch
);
2752 case CHUNKED_STREAM_STATE_READING_CHUNK
:
2753 assert(chunked_stream
->chunk_size
);
2755 continue_read
= FALSE
;
2758 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2760 if(chunked_stream
->buf_size
) {
2761 if(read_bytes
> chunked_stream
->buf_size
)
2762 read_bytes
= chunked_stream
->buf_size
;
2764 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2765 chunked_stream
->buf_pos
+= read_bytes
;
2766 chunked_stream
->buf_size
-= read_bytes
;
2768 res
= NETCON_recv(req
->netconn
, (char*)buf
+ret_read
, read_bytes
,
2769 allow_blocking
, (int*)&read_bytes
);
2770 if(res
!= ERROR_SUCCESS
) {
2771 continue_read
= FALSE
;
2776 chunked_stream
->state
= CHUNKED_STREAM_STATE_END_OF_STREAM
;
2781 chunked_stream
->chunk_size
-= read_bytes
;
2783 ret_read
+= read_bytes
;
2784 if(!chunked_stream
->chunk_size
)
2785 chunked_stream
->state
= CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
;
2786 allow_blocking
= FALSE
;
2789 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
:
2790 ch
= next_chunked_data_char(chunked_stream
);
2792 chunked_stream
->state
= CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
;
2794 WARN("unexpected char '%c'\n", ch
);
2797 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2798 ch
= next_chunked_data_char(chunked_stream
);
2800 chunked_stream
->state
= CHUNKED_STREAM_STATE_END_OF_STREAM
;
2802 WARN("unexpected char '%c'\n", ch
);
2805 case CHUNKED_STREAM_STATE_END_OF_STREAM
:
2806 continue_read
= FALSE
;
2809 } while(continue_read
);
2812 res
= ERROR_SUCCESS
;
2813 if(res
!= ERROR_SUCCESS
)
2816 TRACE("read %d bytes\n", ret_read
);
2818 return ERROR_SUCCESS
;
2821 static BOOL
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2823 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2824 return chunked_stream
->state
== CHUNKED_STREAM_STATE_END_OF_STREAM
;
2827 static void chunked_destroy(data_stream_t
*stream
)
2829 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2830 heap_free(chunked_stream
);
2833 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2834 chunked_end_of_data
,
2836 chunked_drain_content
,
2840 /* set the request content length based on the headers */
2841 static DWORD
set_content_length(http_request_t
*request
)
2843 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2844 static const WCHAR headW
[] = {'H','E','A','D',0};
2848 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
|| !strcmpW(request
->verb
, headW
)) {
2849 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2850 return ERROR_SUCCESS
;
2853 size
= sizeof(request
->contentLength
);
2854 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2855 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2856 request
->contentLength
= ~0u;
2857 request
->netconn_stream
.content_length
= request
->contentLength
;
2858 request
->netconn_stream
.content_read
= request
->read_size
;
2860 size
= sizeof(encoding
);
2861 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2862 !strcmpiW(encoding
, szChunked
))
2864 chunked_stream_t
*chunked_stream
;
2866 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2868 return ERROR_OUTOFMEMORY
;
2870 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2871 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2872 chunked_stream
->chunk_size
= 0;
2873 chunked_stream
->state
= CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
;
2875 if(request
->read_size
) {
2876 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2877 chunked_stream
->buf_size
= request
->read_size
;
2878 request
->read_size
= request
->read_pos
= 0;
2881 request
->data_stream
= &chunked_stream
->data_stream
;
2882 request
->contentLength
= ~0u;
2885 if(request
->decoding
) {
2888 static const WCHAR deflateW
[] = {'d','e','f','l','a','t','e',0};
2889 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2891 EnterCriticalSection( &request
->headers_section
);
2893 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2894 if(encoding_idx
!= -1) {
2895 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2896 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2897 LeaveCriticalSection( &request
->headers_section
);
2898 return init_gzip_stream(request
, TRUE
);
2900 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, deflateW
)) {
2901 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2902 LeaveCriticalSection( &request
->headers_section
);
2903 return init_gzip_stream(request
, FALSE
);
2907 LeaveCriticalSection( &request
->headers_section
);
2910 return ERROR_SUCCESS
;
2913 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
2915 INTERNET_ASYNC_RESULT iar
;
2917 iar
.dwResult
= result
;
2918 iar
.dwError
= error
;
2920 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
2921 sizeof(INTERNET_ASYNC_RESULT
));
2924 static void HTTP_ReceiveRequestData(http_request_t
*req
)
2926 DWORD res
, read
= 0;
2930 EnterCriticalSection( &req
->read_section
);
2932 res
= refill_read_buffer(req
, FALSE
, &read
);
2933 if(res
== ERROR_SUCCESS
)
2934 read
+= req
->read_size
;
2936 LeaveCriticalSection( &req
->read_section
);
2938 if(res
!= WSAEWOULDBLOCK
&& (res
!= ERROR_SUCCESS
|| !read
)) {
2939 WARN("res %u read %u, closing connection\n", res
, read
);
2940 http_release_netconn(req
, FALSE
);
2943 if(res
!= ERROR_SUCCESS
&& res
!= WSAEWOULDBLOCK
) {
2944 send_request_complete(req
, 0, res
);
2948 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, 0);
2951 /* read data from the http connection (the read section must be held) */
2952 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
, BOOL allow_blocking
)
2954 DWORD current_read
= 0, ret_read
= 0;
2955 DWORD res
= ERROR_SUCCESS
;
2957 EnterCriticalSection( &req
->read_section
);
2959 if(req
->read_size
) {
2960 ret_read
= min(size
, req
->read_size
);
2961 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
2962 req
->read_size
-= ret_read
;
2963 req
->read_pos
+= ret_read
;
2964 allow_blocking
= FALSE
;
2967 if(ret_read
< size
) {
2968 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, allow_blocking
);
2969 if(res
== ERROR_SUCCESS
)
2970 ret_read
+= current_read
;
2971 else if(res
== WSAEWOULDBLOCK
&& ret_read
)
2972 res
= ERROR_SUCCESS
;
2975 LeaveCriticalSection( &req
->read_section
);
2978 TRACE( "retrieved %u bytes (%u)\n", ret_read
, req
->contentLength
);
2980 if(res
!= WSAEWOULDBLOCK
&& (!ret_read
|| res
!= ERROR_SUCCESS
))
2981 http_release_netconn(req
, res
== ERROR_SUCCESS
);
2986 static BOOL
drain_content(http_request_t
*req
, BOOL blocking
)
2990 if(!is_valid_netconn(req
->netconn
) || req
->contentLength
== -1)
2993 if(!strcmpW(req
->verb
, szHEAD
))
2997 return req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
);
2999 EnterCriticalSection( &req
->read_section
);
3002 DWORD bytes_read
, res
;
3005 res
= HTTPREQ_Read(req
, buf
, sizeof(buf
), &bytes_read
, TRUE
);
3006 if(res
!= ERROR_SUCCESS
) {
3016 LeaveCriticalSection( &req
->read_section
);
3028 static void async_read_file_proc(task_header_t
*hdr
)
3030 read_file_task_t
*task
= (read_file_task_t
*)hdr
;
3031 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3032 DWORD res
= ERROR_SUCCESS
, read
= task
->read_pos
, complete_arg
= 0;
3034 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
);
3038 while (read
< task
->size
) {
3039 res
= HTTPREQ_Read(req
, (char*)task
->buf
+ read
, task
->size
- read
, &read_bytes
, TRUE
);
3040 if (res
!= ERROR_SUCCESS
|| !read_bytes
)
3045 EnterCriticalSection(&req
->read_section
);
3046 res
= refill_read_buffer(req
, TRUE
, &read
);
3047 LeaveCriticalSection(&req
->read_section
);
3050 complete_arg
= read
; /* QueryDataAvailable reports read bytes in request complete notification */
3051 if(res
!= ERROR_SUCCESS
|| !read
)
3052 http_release_netconn(req
, drain_content(req
, FALSE
));
3055 TRACE("res %u read %u\n", res
, read
);
3058 *task
->ret_read
= read
;
3060 /* FIXME: We should report bytes transferred before decoding content. */
3061 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
, &read
, sizeof(read
));
3063 if(res
!= ERROR_SUCCESS
)
3065 send_request_complete(req
, res
== ERROR_SUCCESS
, complete_arg
);
3068 static DWORD
async_read(http_request_t
*req
, void *buf
, DWORD size
, DWORD read_pos
, DWORD
*ret_read
)
3070 read_file_task_t
*task
;
3072 task
= alloc_async_task(&req
->hdr
, async_read_file_proc
, sizeof(*task
));
3074 return ERROR_OUTOFMEMORY
;
3078 task
->read_pos
= read_pos
;
3079 task
->ret_read
= ret_read
;
3081 INTERNET_AsyncCall(&task
->hdr
);
3082 return ERROR_IO_PENDING
;
3085 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3086 DWORD flags
, DWORD_PTR context
)
3088 http_request_t
*req
= (http_request_t
*)hdr
;
3089 DWORD res
= ERROR_SUCCESS
, read
= 0, cread
, error
= ERROR_SUCCESS
;
3090 BOOL allow_blocking
, notify_received
= FALSE
;
3092 TRACE("(%p %p %u %x)\n", req
, buf
, size
, flags
);
3094 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3095 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3097 allow_blocking
= !(req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
);
3099 if(allow_blocking
|| TryEnterCriticalSection(&req
->read_section
)) {
3101 EnterCriticalSection(&req
->read_section
);
3102 if(hdr
->dwError
== ERROR_SUCCESS
)
3103 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3104 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3105 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3107 if(req
->read_size
) {
3108 read
= min(size
, req
->read_size
);
3109 memcpy(buf
, req
->read_buf
+ req
->read_pos
, read
);
3110 req
->read_size
-= read
;
3111 req
->read_pos
+= read
;
3114 if(read
< size
&& (!read
|| !(flags
& IRF_NO_WAIT
)) && !end_of_read_data(req
)) {
3115 LeaveCriticalSection(&req
->read_section
);
3116 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3117 EnterCriticalSection( &req
->read_section
);
3118 notify_received
= TRUE
;
3120 while(read
< size
) {
3121 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
, allow_blocking
);
3123 if (res
!= ERROR_SUCCESS
|| !cread
)
3128 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3129 hdr
->dwError
= ERROR_SUCCESS
;
3131 error
= hdr
->dwError
;
3133 LeaveCriticalSection( &req
->read_section
);
3135 res
= WSAEWOULDBLOCK
;
3138 if(res
== WSAEWOULDBLOCK
) {
3139 if(!(flags
& IRF_NO_WAIT
))
3140 return async_read(req
, buf
, size
, read
, ret_read
);
3142 return async_read(req
, NULL
, 0, 0, NULL
);
3143 res
= ERROR_SUCCESS
;
3147 if (res
!= ERROR_SUCCESS
)
3151 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3152 &read
, sizeof(read
));
3156 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3159 http_request_t
*request
= (http_request_t
*)hdr
;
3161 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3164 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3165 if (res
== ERROR_SUCCESS
)
3166 request
->bytesWritten
+= *written
;
3168 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3172 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3174 http_request_t
*req
= (http_request_t
*)hdr
;
3175 DWORD res
= ERROR_SUCCESS
, avail
= 0, error
= ERROR_SUCCESS
;
3176 BOOL allow_blocking
, notify_received
= FALSE
;
3178 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3180 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3181 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3184 allow_blocking
= !(req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
);
3186 if(allow_blocking
|| TryEnterCriticalSection(&req
->read_section
)) {
3188 EnterCriticalSection(&req
->read_section
);
3189 if(hdr
->dwError
== ERROR_SUCCESS
)
3190 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3191 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3192 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3194 avail
= req
->read_size
;
3196 if(!avail
&& !end_of_read_data(req
)) {
3197 LeaveCriticalSection(&req
->read_section
);
3198 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3199 EnterCriticalSection( &req
->read_section
);
3200 notify_received
= TRUE
;
3202 res
= refill_read_buffer(req
, allow_blocking
, &avail
);
3205 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3206 hdr
->dwError
= ERROR_SUCCESS
;
3208 error
= hdr
->dwError
;
3210 LeaveCriticalSection( &req
->read_section
);
3212 res
= WSAEWOULDBLOCK
;
3215 if(res
== WSAEWOULDBLOCK
)
3216 return async_read(req
, NULL
, 0, 0, available
);
3218 if (res
!= ERROR_SUCCESS
)
3223 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3224 &avail
, sizeof(avail
));
3228 static DWORD
HTTPREQ_LockRequestFile(object_header_t
*hdr
, req_file_t
**ret
)
3230 http_request_t
*req
= (http_request_t
*)hdr
;
3232 TRACE("(%p)\n", req
);
3234 if(!req
->req_file
) {
3235 WARN("No cache file name available\n");
3236 return ERROR_FILE_NOT_FOUND
;
3239 *ret
= req_file_addref(req
->req_file
);
3240 return ERROR_SUCCESS
;
3243 static const object_vtbl_t HTTPREQVtbl
= {
3245 HTTPREQ_CloseConnection
,
3246 HTTPREQ_QueryOption
,
3250 HTTPREQ_QueryDataAvailable
,
3252 HTTPREQ_LockRequestFile
3255 /***********************************************************************
3256 * HTTP_HttpOpenRequestW (internal)
3258 * Open a HTTP request handle
3261 * HINTERNET a HTTP request handle on success
3265 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3266 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3267 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3268 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3270 appinfo_t
*hIC
= session
->appInfo
;
3271 http_request_t
*request
;
3276 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3278 return ERROR_OUTOFMEMORY
;
3280 request
->hdr
.htype
= WH_HHTTPREQ
;
3281 request
->hdr
.dwFlags
= dwFlags
;
3282 request
->hdr
.dwContext
= dwContext
;
3283 request
->contentLength
= ~0u;
3285 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3286 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3287 request
->connect_timeout
= session
->connect_timeout
;
3288 request
->send_timeout
= session
->send_timeout
;
3289 request
->receive_timeout
= session
->receive_timeout
;
3291 InitializeCriticalSection( &request
->headers_section
);
3292 request
->headers_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.headers_section");
3294 InitializeCriticalSection( &request
->read_section
);
3295 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3297 WININET_AddRef( &session
->hdr
);
3298 request
->session
= session
;
3299 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3301 port
= session
->hostPort
;
3302 if (port
== INTERNET_INVALID_PORT_NUMBER
)
3303 port
= (session
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ?
3304 INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
;
3306 request
->server
= get_server(substrz(session
->hostName
), port
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3307 if(!request
->server
) {
3308 WININET_Release(&request
->hdr
);
3309 return ERROR_OUTOFMEMORY
;
3312 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3313 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3314 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3315 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3317 if (lpszObjectName
&& *lpszObjectName
) {
3322 rc
= UrlCanonicalizeW(lpszObjectName
, &dummy
, &len
, URL_ESCAPE_SPACES_ONLY
);
3323 if (rc
!= E_POINTER
)
3324 len
= strlenW(lpszObjectName
)+1;
3325 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3326 rc
= UrlCanonicalizeW(lpszObjectName
, request
->path
, &len
,
3327 URL_ESCAPE_SPACES_ONLY
);
3330 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3331 strcpyW(request
->path
,lpszObjectName
);
3334 static const WCHAR slashW
[] = {'/',0};
3336 request
->path
= heap_strdupW(slashW
);
3339 if (lpszReferrer
&& *lpszReferrer
)
3340 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3342 if (lpszAcceptTypes
)
3345 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3347 if (!*lpszAcceptTypes
[i
]) continue;
3348 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3349 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3350 HTTP_ADDHDR_FLAG_REQ
|
3351 (i
== 0 ? (HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
) : 0));
3355 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3356 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3358 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3359 HTTP_DealWithProxy( hIC
, session
, request
);
3361 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3362 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3365 TRACE("<-- (%p)\n", request
);
3367 *ret
= request
->hdr
.hInternet
;
3368 return ERROR_SUCCESS
;
3371 /***********************************************************************
3372 * HttpOpenRequestW (WININET.@)
3374 * Open a HTTP request handle
3377 * HINTERNET a HTTP request handle on success
3381 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3382 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3383 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3384 DWORD dwFlags
, DWORD_PTR dwContext
)
3386 http_session_t
*session
;
3387 HINTERNET handle
= NULL
;
3390 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3391 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3392 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3393 dwFlags
, dwContext
);
3394 if(lpszAcceptTypes
!=NULL
)
3397 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3398 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3401 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3402 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3404 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3409 * My tests seem to show that the windows version does not
3410 * become asynchronous until after this point. And anyhow
3411 * if this call was asynchronous then how would you get the
3412 * necessary HINTERNET pointer returned by this function.
3415 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3416 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3417 dwFlags
, dwContext
, &handle
);
3420 WININET_Release( &session
->hdr
);
3421 TRACE("returning %p\n", handle
);
3422 if(res
!= ERROR_SUCCESS
)
3427 static const LPCWSTR header_lookup
[] = {
3428 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3429 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3430 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3431 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3432 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3433 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3434 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3435 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3436 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3437 szDate
, /* HTTP_QUERY_DATE = 9 */
3438 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3439 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3440 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3441 szURI
, /* HTTP_QUERY_URI = 13 */
3442 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3443 NULL
, /* HTTP_QUERY_COST = 15 */
3444 NULL
, /* HTTP_QUERY_LINK = 16 */
3445 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3446 NULL
, /* HTTP_QUERY_VERSION = 18 */
3447 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3448 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3449 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3450 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3451 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3452 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3453 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3454 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3455 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3456 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3457 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3458 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3459 NULL
, /* HTTP_QUERY_FROM = 31 */
3460 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3461 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3462 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3463 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3464 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3465 szServer
, /* HTTP_QUERY_SERVER = 37 */
3466 NULL
, /* HTTP_TITLE = 38 */
3467 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3468 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3469 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3470 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3471 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3472 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3473 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3474 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3475 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3476 szAge
, /* HTTP_QUERY_AGE = 48 */
3477 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3478 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3479 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3480 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3481 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3482 szETag
, /* HTTP_QUERY_ETAG = 54 */
3483 hostW
, /* HTTP_QUERY_HOST = 55 */
3484 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3485 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3486 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3487 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3488 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3489 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3490 szRange
, /* HTTP_QUERY_RANGE = 62 */
3491 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3492 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3493 szVary
, /* HTTP_QUERY_VARY = 65 */
3494 szVia
, /* HTTP_QUERY_VIA = 66 */
3495 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3496 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3497 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3498 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3501 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3503 /***********************************************************************
3504 * HTTP_HttpQueryInfoW (internal)
3506 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3507 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3509 LPHTTPHEADERW lphttpHdr
= NULL
;
3510 BOOL request_only
= !!(dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
);
3511 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3512 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3515 EnterCriticalSection( &request
->headers_section
);
3517 /* Find requested header structure */
3520 case HTTP_QUERY_CUSTOM
:
3523 LeaveCriticalSection( &request
->headers_section
);
3524 return ERROR_INVALID_PARAMETER
;
3526 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3528 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3532 DWORD res
= ERROR_INVALID_PARAMETER
;
3535 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3537 headers
= build_response_header(request
, TRUE
);
3540 LeaveCriticalSection( &request
->headers_section
);
3541 return ERROR_OUTOFMEMORY
;
3544 len
= strlenW(headers
) * sizeof(WCHAR
);
3545 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3547 len
+= sizeof(WCHAR
);
3548 res
= ERROR_INSUFFICIENT_BUFFER
;
3552 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3553 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3554 res
= ERROR_SUCCESS
;
3556 *lpdwBufferLength
= len
;
3559 LeaveCriticalSection( &request
->headers_section
);
3562 case HTTP_QUERY_RAW_HEADERS
:
3568 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3570 headers
= build_response_header(request
, FALSE
);
3574 LeaveCriticalSection( &request
->headers_section
);
3575 return ERROR_OUTOFMEMORY
;
3578 len
= strlenW(headers
) * sizeof(WCHAR
);
3579 if (len
> *lpdwBufferLength
)
3581 *lpdwBufferLength
= len
;
3583 LeaveCriticalSection( &request
->headers_section
);
3584 return ERROR_INSUFFICIENT_BUFFER
;
3591 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3593 for (i
= 0; i
< len
/ sizeof(WCHAR
); i
++)
3595 if (headers
[i
] == '\n')
3598 memcpy(lpBuffer
, headers
, len
);
3600 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3603 LeaveCriticalSection( &request
->headers_section
);
3604 return ERROR_SUCCESS
;
3606 case HTTP_QUERY_STATUS_TEXT
:
3607 if (request
->statusText
)
3609 DWORD len
= strlenW(request
->statusText
);
3610 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3612 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3613 LeaveCriticalSection( &request
->headers_section
);
3614 return ERROR_INSUFFICIENT_BUFFER
;
3618 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3619 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3621 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3622 LeaveCriticalSection( &request
->headers_section
);
3623 return ERROR_SUCCESS
;
3626 case HTTP_QUERY_VERSION
:
3627 if (request
->version
)
3629 DWORD len
= strlenW(request
->version
);
3630 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3632 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3633 LeaveCriticalSection( &request
->headers_section
);
3634 return ERROR_INSUFFICIENT_BUFFER
;
3638 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3639 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3641 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3642 LeaveCriticalSection( &request
->headers_section
);
3643 return ERROR_SUCCESS
;
3646 case HTTP_QUERY_CONTENT_ENCODING
:
3647 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3648 requested_index
,request_only
);
3650 case HTTP_QUERY_STATUS_CODE
: {
3651 DWORD res
= ERROR_SUCCESS
;
3655 LeaveCriticalSection( &request
->headers_section
);
3656 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3662 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3663 if(*lpdwBufferLength
>= sizeof(DWORD
))
3664 *(DWORD
*)lpBuffer
= request
->status_code
;
3666 res
= ERROR_INSUFFICIENT_BUFFER
;
3667 *lpdwBufferLength
= sizeof(DWORD
);
3671 static const WCHAR formatW
[] = {'%','u',0};
3673 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3675 if(size
<= *lpdwBufferLength
) {
3676 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3678 size
+= sizeof(WCHAR
);
3679 res
= ERROR_INSUFFICIENT_BUFFER
;
3682 *lpdwBufferLength
= size
;
3684 LeaveCriticalSection( &request
->headers_section
);
3688 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3690 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3691 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3692 requested_index
,request_only
);
3696 lphttpHdr
= &request
->custHeaders
[index
];
3698 /* Ensure header satisfies requested attributes */
3700 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3701 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3703 LeaveCriticalSection( &request
->headers_section
);
3704 return ERROR_HTTP_HEADER_NOT_FOUND
;
3707 /* coalesce value to requested type */
3708 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3710 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3711 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3713 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3719 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3721 tmpTM
= *gmtime(&tmpTime
);
3722 STHook
= (SYSTEMTIME
*)lpBuffer
;
3723 STHook
->wDay
= tmpTM
.tm_mday
;
3724 STHook
->wHour
= tmpTM
.tm_hour
;
3725 STHook
->wMilliseconds
= 0;
3726 STHook
->wMinute
= tmpTM
.tm_min
;
3727 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3728 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3729 STHook
->wSecond
= tmpTM
.tm_sec
;
3730 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3732 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3733 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3734 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3736 else if (lphttpHdr
->lpszValue
)
3738 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3740 if (len
> *lpdwBufferLength
)
3742 *lpdwBufferLength
= len
;
3743 LeaveCriticalSection( &request
->headers_section
);
3744 return ERROR_INSUFFICIENT_BUFFER
;
3748 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3749 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3751 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3753 if (lpdwIndex
) (*lpdwIndex
)++;
3755 LeaveCriticalSection( &request
->headers_section
);
3756 return ERROR_SUCCESS
;
3759 /***********************************************************************
3760 * HttpQueryInfoW (WININET.@)
3762 * Queries for information about an HTTP request
3769 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3770 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3772 http_request_t
*request
;
3775 if (TRACE_ON(wininet
)) {
3776 #define FE(x) { x, #x }
3777 static const wininet_flag_info query_flags
[] = {
3778 FE(HTTP_QUERY_MIME_VERSION
),
3779 FE(HTTP_QUERY_CONTENT_TYPE
),
3780 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3781 FE(HTTP_QUERY_CONTENT_ID
),
3782 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3783 FE(HTTP_QUERY_CONTENT_LENGTH
),
3784 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3785 FE(HTTP_QUERY_ALLOW
),
3786 FE(HTTP_QUERY_PUBLIC
),
3787 FE(HTTP_QUERY_DATE
),
3788 FE(HTTP_QUERY_EXPIRES
),
3789 FE(HTTP_QUERY_LAST_MODIFIED
),
3790 FE(HTTP_QUERY_MESSAGE_ID
),
3792 FE(HTTP_QUERY_DERIVED_FROM
),
3793 FE(HTTP_QUERY_COST
),
3794 FE(HTTP_QUERY_LINK
),
3795 FE(HTTP_QUERY_PRAGMA
),
3796 FE(HTTP_QUERY_VERSION
),
3797 FE(HTTP_QUERY_STATUS_CODE
),
3798 FE(HTTP_QUERY_STATUS_TEXT
),
3799 FE(HTTP_QUERY_RAW_HEADERS
),
3800 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3801 FE(HTTP_QUERY_CONNECTION
),
3802 FE(HTTP_QUERY_ACCEPT
),
3803 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3804 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3805 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3806 FE(HTTP_QUERY_AUTHORIZATION
),
3807 FE(HTTP_QUERY_CONTENT_ENCODING
),
3808 FE(HTTP_QUERY_FORWARDED
),
3809 FE(HTTP_QUERY_FROM
),
3810 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3811 FE(HTTP_QUERY_LOCATION
),
3812 FE(HTTP_QUERY_ORIG_URI
),
3813 FE(HTTP_QUERY_REFERER
),
3814 FE(HTTP_QUERY_RETRY_AFTER
),
3815 FE(HTTP_QUERY_SERVER
),
3816 FE(HTTP_QUERY_TITLE
),
3817 FE(HTTP_QUERY_USER_AGENT
),
3818 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3819 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3820 FE(HTTP_QUERY_ACCEPT_RANGES
),
3821 FE(HTTP_QUERY_SET_COOKIE
),
3822 FE(HTTP_QUERY_COOKIE
),
3823 FE(HTTP_QUERY_REQUEST_METHOD
),
3824 FE(HTTP_QUERY_REFRESH
),
3825 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3827 FE(HTTP_QUERY_CACHE_CONTROL
),
3828 FE(HTTP_QUERY_CONTENT_BASE
),
3829 FE(HTTP_QUERY_CONTENT_LOCATION
),
3830 FE(HTTP_QUERY_CONTENT_MD5
),
3831 FE(HTTP_QUERY_CONTENT_RANGE
),
3832 FE(HTTP_QUERY_ETAG
),
3833 FE(HTTP_QUERY_HOST
),
3834 FE(HTTP_QUERY_IF_MATCH
),
3835 FE(HTTP_QUERY_IF_NONE_MATCH
),
3836 FE(HTTP_QUERY_IF_RANGE
),
3837 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3838 FE(HTTP_QUERY_MAX_FORWARDS
),
3839 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3840 FE(HTTP_QUERY_RANGE
),
3841 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3842 FE(HTTP_QUERY_UPGRADE
),
3843 FE(HTTP_QUERY_VARY
),
3845 FE(HTTP_QUERY_WARNING
),
3846 FE(HTTP_QUERY_CUSTOM
)
3848 static const wininet_flag_info modifier_flags
[] = {
3849 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3850 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3851 FE(HTTP_QUERY_FLAG_NUMBER
),
3852 FE(HTTP_QUERY_FLAG_COALESCE
)
3855 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3856 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3859 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3860 TRACE(" Attribute:");
3861 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3862 if (query_flags
[i
].val
== info
) {
3863 TRACE(" %s", query_flags
[i
].name
);
3867 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3868 TRACE(" Unknown (%08x)", info
);
3871 TRACE(" Modifier:");
3872 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3873 if (modifier_flags
[i
].val
& info_mod
) {
3874 TRACE(" %s", modifier_flags
[i
].name
);
3875 info_mod
&= ~ modifier_flags
[i
].val
;
3880 TRACE(" Unknown (%08x)", info_mod
);
3885 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3886 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3888 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3892 if (lpBuffer
== NULL
)
3893 *lpdwBufferLength
= 0;
3894 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3895 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3899 WININET_Release( &request
->hdr
);
3901 TRACE("%u <--\n", res
);
3902 if(res
!= ERROR_SUCCESS
)
3904 return res
== ERROR_SUCCESS
;
3907 /***********************************************************************
3908 * HttpQueryInfoA (WININET.@)
3910 * Queries for information about an HTTP request
3917 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3918 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3924 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
3926 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3927 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3929 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3930 lpdwBufferLength
, lpdwIndex
);
3936 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
3937 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3939 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
3945 bufferW
= heap_alloc(alloclen
);
3946 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3947 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3948 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
3955 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
3959 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
3960 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
3961 *lpdwBufferLength
= len
- 1;
3963 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
3966 /* since the strings being returned from HttpQueryInfoW should be
3967 * only ASCII characters, it is reasonable to assume that all of
3968 * the Unicode characters can be reduced to a single byte */
3969 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
3971 heap_free( bufferW
);
3975 static WCHAR
*get_redirect_url(http_request_t
*request
)
3977 static WCHAR szHttp
[] = {'h','t','t','p',0};
3978 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
3979 http_session_t
*session
= request
->session
;
3980 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
3981 WCHAR
*orig_url
= NULL
, *redirect_url
= NULL
, *combined_url
= NULL
;
3982 DWORD url_length
= 0, res
;
3986 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
3987 if(res
== ERROR_INSUFFICIENT_BUFFER
) {
3988 redirect_url
= heap_alloc(url_length
);
3989 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
3991 if(res
!= ERROR_SUCCESS
) {
3992 heap_free(redirect_url
);
3996 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
3997 urlComponents
.lpszHostName
= request
->server
->name
;
3998 urlComponents
.nPort
= request
->server
->port
;
3999 urlComponents
.lpszUserName
= session
->userName
;
4000 urlComponents
.lpszUrlPath
= request
->path
;
4002 b
= InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
);
4003 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4004 orig_url
= heap_alloc(url_length
);
4006 /* convert from bytes to characters */
4007 url_length
= url_length
/ sizeof(WCHAR
) - 1;
4008 b
= InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
);
4013 b
= InternetCombineUrlW(orig_url
, redirect_url
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4014 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4015 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
4016 b
= InternetCombineUrlW(orig_url
, redirect_url
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4018 heap_free(combined_url
);
4019 combined_url
= NULL
;
4024 heap_free(orig_url
);
4025 heap_free(redirect_url
);
4026 return combined_url
;
4030 /***********************************************************************
4031 * HTTP_HandleRedirect (internal)
4033 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, LPCWSTR lpszUrl
)
4035 http_session_t
*session
= request
->session
;
4040 /* if it's an absolute path, keep the same session info */
4041 path
= heap_strdupW(lpszUrl
);
4045 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
4046 BOOL custom_port
= FALSE
;
4049 urlComponents
.dwHostNameLength
= 1;
4050 urlComponents
.dwUserNameLength
= 1;
4051 urlComponents
.dwUrlPathLength
= 1;
4052 if(!InternetCrackUrlW(lpszUrl
, strlenW(lpszUrl
), 0, &urlComponents
))
4053 return INTERNET_GetLastError();
4055 if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTP
) {
4056 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4057 TRACE("redirect from secure page to non-secure page\n");
4058 /* FIXME: warn about from secure redirect to non-secure page */
4059 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4062 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
;
4063 }else if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
) {
4064 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4065 TRACE("redirect from non-secure page to secure page\n");
4066 /* FIXME: notify about redirect to secure page */
4067 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4070 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
;
4073 heap_free(session
->hostName
);
4075 session
->hostName
= heap_strndupW(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4076 session
->hostPort
= urlComponents
.nPort
;
4078 heap_free(session
->userName
);
4079 session
->userName
= NULL
;
4080 if (urlComponents
.dwUserNameLength
)
4081 session
->userName
= heap_strndupW(urlComponents
.lpszUserName
, urlComponents
.dwUserNameLength
);
4083 reset_data_stream(request
);
4085 host
= substr(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4087 if(host
.len
!= strlenW(request
->server
->name
) || strncmpiW(request
->server
->name
, host
.str
, host
.len
)
4088 || request
->server
->port
!= urlComponents
.nPort
) {
4089 server_t
*new_server
;
4091 new_server
= get_server(host
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4092 server_release(request
->server
);
4093 request
->server
= new_server
;
4097 HTTP_ProcessHeader(request
, hostW
, request
->server
->host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4099 HTTP_ProcessHeader(request
, hostW
, request
->server
->name
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4101 path
= heap_strndupW(urlComponents
.lpszUrlPath
, urlComponents
.dwUrlPathLength
);
4103 heap_free(request
->path
);
4104 request
->path
= NULL
;
4111 rc
= UrlEscapeW(path
, &dummy
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4112 if (rc
!= E_POINTER
)
4113 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4114 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4115 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4116 URL_ESCAPE_SPACES_ONLY
);
4119 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4120 strcpyW(request
->path
, path
);
4126 /* Remove custom content-type/length headers on redirects. */
4127 remove_header(request
, szContent_Type
, TRUE
);
4128 remove_header(request
, szContent_Length
, TRUE
);
4130 return ERROR_SUCCESS
;
4133 /***********************************************************************
4134 * HTTP_build_req (internal)
4136 * concatenate all the strings in the request together
4138 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4143 for( t
= list
; *t
; t
++ )
4144 len
+= strlenW( *t
);
4147 str
= heap_alloc(len
*sizeof(WCHAR
));
4150 for( t
= list
; *t
; t
++ )
4156 static void HTTP_InsertCookies(http_request_t
*request
)
4161 res
= get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4162 if(res
!= ERROR_SUCCESS
|| !cookies
)
4165 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
),
4166 HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
4170 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4172 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4180 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4181 if (!strcmpiW(day
, days
[i
]))
4188 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4190 static const WCHAR jan
[] = { 'j','a','n',0 };
4191 static const WCHAR feb
[] = { 'f','e','b',0 };
4192 static const WCHAR mar
[] = { 'm','a','r',0 };
4193 static const WCHAR apr
[] = { 'a','p','r',0 };
4194 static const WCHAR may
[] = { 'm','a','y',0 };
4195 static const WCHAR jun
[] = { 'j','u','n',0 };
4196 static const WCHAR jul
[] = { 'j','u','l',0 };
4197 static const WCHAR aug
[] = { 'a','u','g',0 };
4198 static const WCHAR sep
[] = { 's','e','p',0 };
4199 static const WCHAR oct
[] = { 'o','c','t',0 };
4200 static const WCHAR nov
[] = { 'n','o','v',0 };
4201 static const WCHAR dec
[] = { 'd','e','c',0 };
4203 if (!strcmpiW(month
, jan
)) return 1;
4204 if (!strcmpiW(month
, feb
)) return 2;
4205 if (!strcmpiW(month
, mar
)) return 3;
4206 if (!strcmpiW(month
, apr
)) return 4;
4207 if (!strcmpiW(month
, may
)) return 5;
4208 if (!strcmpiW(month
, jun
)) return 6;
4209 if (!strcmpiW(month
, jul
)) return 7;
4210 if (!strcmpiW(month
, aug
)) return 8;
4211 if (!strcmpiW(month
, sep
)) return 9;
4212 if (!strcmpiW(month
, oct
)) return 10;
4213 if (!strcmpiW(month
, nov
)) return 11;
4214 if (!strcmpiW(month
, dec
)) return 12;
4219 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4220 * optionally preceded by whitespace.
4221 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4222 * st, and sets *str to the first character after the time format.
4224 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4230 while (isspaceW(*ptr
))
4233 num
= strtoulW(ptr
, &nextPtr
, 10);
4234 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4236 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4241 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4245 st
->wHour
= (WORD
)num
;
4246 num
= strtoulW(ptr
, &nextPtr
, 10);
4247 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4249 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4254 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4258 st
->wMinute
= (WORD
)num
;
4259 num
= strtoulW(ptr
, &nextPtr
, 10);
4260 if (!nextPtr
|| nextPtr
<= ptr
)
4262 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4267 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4272 st
->wSecond
= (WORD
)num
;
4276 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4278 static const WCHAR gmt
[]= { 'G','M','T',0 };
4279 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4281 SYSTEMTIME st
= { 0 };
4284 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4285 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4288 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4289 if (st
.wDayOfWeek
>= 7)
4291 ERR("unexpected weekday %s\n", debugstr_w(day
));
4295 while (isspaceW(*ptr
))
4298 for (monthPtr
= month
; !isspace(*ptr
) &&
4299 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4303 st
.wMonth
= HTTP_ParseMonth(month
);
4304 if (!st
.wMonth
|| st
.wMonth
> 12)
4306 ERR("unexpected month %s\n", debugstr_w(month
));
4310 while (isspaceW(*ptr
))
4313 num
= strtoulW(ptr
, &nextPtr
, 10);
4314 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4316 ERR("unexpected day %s\n", debugstr_w(ptr
));
4320 st
.wDay
= (WORD
)num
;
4322 while (isspaceW(*ptr
))
4325 if (!HTTP_ParseTime(&st
, &ptr
))
4328 while (isspaceW(*ptr
))
4331 num
= strtoulW(ptr
, &nextPtr
, 10);
4332 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4334 ERR("unexpected year %s\n", debugstr_w(ptr
));
4338 st
.wYear
= (WORD
)num
;
4340 while (isspaceW(*ptr
))
4343 /* asctime() doesn't report a timezone, but some web servers do, so accept
4344 * with or without GMT.
4346 if (*ptr
&& strcmpW(ptr
, gmt
))
4348 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4351 return SystemTimeToFileTime(&st
, ft
);
4354 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4356 static const WCHAR gmt
[]= { 'G','M','T',0 };
4357 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4360 SYSTEMTIME st
= { 0 };
4362 ptr
= strchrW(value
, ',');
4365 if (ptr
- value
!= 3)
4367 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4370 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4372 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4373 if (st
.wDayOfWeek
> 6)
4375 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4380 while (isspaceW(*ptr
))
4383 num
= strtoulW(ptr
, &nextPtr
, 10);
4384 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4386 WARN("unexpected day %s\n", debugstr_w(value
));
4390 st
.wDay
= (WORD
)num
;
4392 while (isspaceW(*ptr
))
4395 for (monthPtr
= month
; !isspace(*ptr
) &&
4396 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4400 st
.wMonth
= HTTP_ParseMonth(month
);
4401 if (!st
.wMonth
|| st
.wMonth
> 12)
4403 WARN("unexpected month %s\n", debugstr_w(month
));
4407 while (isspaceW(*ptr
))
4410 num
= strtoulW(ptr
, &nextPtr
, 10);
4411 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4413 ERR("unexpected year %s\n", debugstr_w(value
));
4417 st
.wYear
= (WORD
)num
;
4419 if (!HTTP_ParseTime(&st
, &ptr
))
4422 while (isspaceW(*ptr
))
4425 if (strcmpW(ptr
, gmt
))
4427 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4430 return SystemTimeToFileTime(&st
, ft
);
4433 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4435 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4436 { 'm','o','n','d','a','y',0 },
4437 { 't','u','e','s','d','a','y',0 },
4438 { 'w','e','d','n','e','s','d','a','y',0 },
4439 { 't','h','u','r','s','d','a','y',0 },
4440 { 'f','r','i','d','a','y',0 },
4441 { 's','a','t','u','r','d','a','y',0 }};
4443 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4444 if (!strcmpiW(day
, days
[i
]))
4451 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4453 static const WCHAR gmt
[]= { 'G','M','T',0 };
4454 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4457 SYSTEMTIME st
= { 0 };
4459 ptr
= strchrW(value
, ',');
4462 if (ptr
- value
== 3)
4464 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4466 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4467 if (st
.wDayOfWeek
> 6)
4469 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4473 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4475 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4476 day
[ptr
- value
+ 1] = 0;
4477 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4478 if (st
.wDayOfWeek
> 6)
4480 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4486 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4491 while (isspaceW(*ptr
))
4494 num
= strtoulW(ptr
, &nextPtr
, 10);
4495 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4497 ERR("unexpected day %s\n", debugstr_w(value
));
4501 st
.wDay
= (WORD
)num
;
4505 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4510 for (monthPtr
= month
; *ptr
!= '-' &&
4511 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4515 st
.wMonth
= HTTP_ParseMonth(month
);
4516 if (!st
.wMonth
|| st
.wMonth
> 12)
4518 ERR("unexpected month %s\n", debugstr_w(month
));
4524 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4529 num
= strtoulW(ptr
, &nextPtr
, 10);
4530 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4532 ERR("unexpected year %s\n", debugstr_w(value
));
4536 st
.wYear
= (WORD
)num
;
4538 if (!HTTP_ParseTime(&st
, &ptr
))
4541 while (isspaceW(*ptr
))
4544 if (strcmpW(ptr
, gmt
))
4546 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4549 return SystemTimeToFileTime(&st
, ft
);
4552 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4554 static const WCHAR zero
[] = { '0',0 };
4557 if (!strcmpW(value
, zero
))
4559 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4562 else if (strchrW(value
, ','))
4564 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4567 ret
= HTTP_ParseRfc850Date(value
, ft
);
4569 ERR("unexpected date format %s\n", debugstr_w(value
));
4574 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4576 ERR("unexpected date format %s\n", debugstr_w(value
));
4581 static void HTTP_ProcessExpires(http_request_t
*request
)
4583 BOOL expirationFound
= FALSE
;
4586 EnterCriticalSection( &request
->headers_section
);
4588 /* Look for a Cache-Control header with a max-age directive, as it takes
4589 * precedence over the Expires header.
4591 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4592 if (headerIndex
!= -1)
4594 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4597 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4599 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4604 end
= ptr
+ strlenW(ptr
);
4605 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4609 static const WCHAR max_age
[] = {
4610 'm','a','x','-','a','g','e',0 };
4612 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4617 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4618 if (nextPtr
> equal
+ 1)
4622 NtQuerySystemTime( &ft
);
4623 /* Age is in seconds, FILETIME resolution is in
4624 * 100 nanosecond intervals.
4626 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4627 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4628 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4629 expirationFound
= TRUE
;
4636 while (isspaceW(*ptr
))
4643 if (!expirationFound
)
4645 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4646 if (headerIndex
!= -1)
4648 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4651 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4653 expirationFound
= TRUE
;
4654 request
->expires
= ft
;
4658 if (!expirationFound
)
4662 /* With no known age, default to 10 minutes until expiration. */
4663 NtQuerySystemTime( &t
);
4664 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4665 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4666 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4669 LeaveCriticalSection( &request
->headers_section
);
4672 static void HTTP_ProcessLastModified(http_request_t
*request
)
4676 EnterCriticalSection( &request
->headers_section
);
4678 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4679 if (headerIndex
!= -1)
4681 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4684 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4685 request
->last_modified
= ft
;
4688 LeaveCriticalSection( &request
->headers_section
);
4691 static void http_process_keep_alive(http_request_t
*req
)
4695 EnterCriticalSection( &req
->headers_section
);
4697 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4698 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4699 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4700 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4702 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4704 LeaveCriticalSection( &req
->headers_section
);
4707 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4709 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4710 netconn_t
*netconn
= NULL
;
4713 reset_data_stream(request
);
4715 if (request
->netconn
)
4717 if (is_valid_netconn(request
->netconn
) && NETCON_is_alive(request
->netconn
))
4720 return ERROR_SUCCESS
;
4724 free_netconn(request
->netconn
);
4725 request
->netconn
= NULL
;
4729 res
= HTTP_ResolveName(request
);
4730 if(res
!= ERROR_SUCCESS
)
4733 EnterCriticalSection(&connection_pool_cs
);
4735 while(!list_empty(&request
->server
->conn_pool
)) {
4736 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4737 list_remove(&netconn
->pool_entry
);
4739 if(is_valid_netconn(netconn
) && NETCON_is_alive(netconn
))
4742 TRACE("connection %p closed during idle\n", netconn
);
4743 free_netconn(netconn
);
4747 LeaveCriticalSection(&connection_pool_cs
);
4750 TRACE("<-- reusing %p netconn\n", netconn
);
4751 request
->netconn
= netconn
;
4753 return ERROR_SUCCESS
;
4756 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4757 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4759 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4760 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4761 request
->server
->addr_str
,
4762 strlen(request
->server
->addr_str
)+1);
4764 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4765 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4766 request
->connect_timeout
, &netconn
);
4767 if(res
!= ERROR_SUCCESS
) {
4768 ERR("create_netconn failed: %u\n", res
);
4772 request
->netconn
= netconn
;
4774 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4775 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4776 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4779 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4780 return ERROR_SUCCESS
;
4783 static char *build_ascii_request( const WCHAR
*str
, void *data
, DWORD data_len
, DWORD
*out_len
)
4785 int len
= WideCharToMultiByte( CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
4788 if (!(ret
= heap_alloc( len
+ data_len
))) return NULL
;
4789 WideCharToMultiByte( CP_ACP
, 0, str
, -1, ret
, len
, NULL
, NULL
);
4790 if (data_len
) memcpy( ret
+ len
- 1, data
, data_len
);
4791 *out_len
= len
+ data_len
- 1;
4796 static void set_content_length_header( http_request_t
*request
, DWORD len
, DWORD flags
)
4798 static const WCHAR fmtW
[] =
4799 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4800 WCHAR buf
[sizeof(fmtW
)/sizeof(fmtW
[0]) + 10];
4802 sprintfW( buf
, fmtW
, len
);
4803 HTTP_HttpAddRequestHeadersW( request
, buf
, ~0u, flags
);
4806 /***********************************************************************
4807 * HTTP_HttpSendRequestW (internal)
4809 * Sends the specified request to the HTTP server
4812 * ERROR_SUCCESS on success
4813 * win32 error code on failure
4816 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4817 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4818 DWORD dwContentLength
, BOOL bEndRequest
)
4820 BOOL redirected
= FALSE
, secure_proxy_connect
= FALSE
, loop_next
;
4821 LPWSTR requestString
= NULL
;
4822 INT responseLen
, cnt
;
4825 TRACE("--> %p\n", request
);
4827 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4829 /* if the verb is NULL default to GET */
4831 request
->verb
= heap_strdupW(szGET
);
4833 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
,
4834 HTTP_ADDREQ_FLAG_ADD_IF_NEW
| HTTP_ADDHDR_FLAG_REQ
);
4836 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4838 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4839 request
->bytesToWrite
= dwContentLength
;
4841 if (request
->session
->appInfo
->agent
)
4843 WCHAR
*agent_header
;
4844 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4847 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4848 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4849 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4851 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4852 heap_free(agent_header
);
4854 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4856 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4857 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4859 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4861 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4862 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4863 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4866 /* add the headers the caller supplied */
4867 if( lpszHeaders
&& dwHeaderLength
)
4868 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4872 DWORD len
, data_len
= dwOptionalLength
;
4873 BOOL reusing_connection
;
4879 request
->contentLength
= ~0u;
4880 request
->bytesToWrite
= 0;
4883 if (TRACE_ON(wininet
))
4887 EnterCriticalSection( &request
->headers_section
);
4888 host
= HTTP_GetHeader( request
, hostW
);
4889 TRACE("Going to url %s %s\n", debugstr_w(host
->lpszValue
), debugstr_w(request
->path
));
4890 LeaveCriticalSection( &request
->headers_section
);
4893 HTTP_FixURL(request
);
4894 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4896 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
,
4897 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
4899 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4900 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4902 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4903 HTTP_InsertCookies(request
);
4905 res
= open_http_connection(request
, &reusing_connection
);
4906 if (res
!= ERROR_SUCCESS
)
4909 if (!reusing_connection
&& (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4911 if (request
->proxy
) secure_proxy_connect
= TRUE
;
4914 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4915 if (res
!= ERROR_SUCCESS
)
4917 WARN("failed to upgrade to secure connection\n");
4918 http_release_netconn(request
, FALSE
);
4923 if (secure_proxy_connect
)
4925 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
4926 const WCHAR
*target
= request
->server
->host_port
;
4928 if (HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
4929 set_content_length_header(request
, 0, HTTP_ADDREQ_FLAG_REPLACE
);
4931 requestString
= build_request_header(request
, connectW
, target
, g_szHttp1_1
, TRUE
);
4933 else if (request
->proxy
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4935 WCHAR
*url
= build_proxy_path_url(request
);
4936 requestString
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
4941 if (request
->proxy
&& HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
4942 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_REPLACE
);
4944 requestString
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
4947 TRACE("Request header -> %s\n", debugstr_w(requestString
) );
4949 /* send the request as ASCII, tack on the optional data */
4950 if (!lpOptional
|| redirected
|| secure_proxy_connect
)
4953 ascii_req
= build_ascii_request( requestString
, lpOptional
, data_len
, &len
);
4954 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
4956 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4957 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
4959 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
4960 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
4961 heap_free( ascii_req
);
4962 if(res
!= ERROR_SUCCESS
) {
4963 TRACE("send failed: %u\n", res
);
4964 if(!reusing_connection
)
4966 http_release_netconn(request
, FALSE
);
4971 request
->bytesWritten
= data_len
;
4973 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4974 INTERNET_STATUS_REQUEST_SENT
,
4975 &len
, sizeof(DWORD
));
4981 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4982 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
4984 if (HTTP_GetResponseHeaders(request
, &responseLen
))
4986 http_release_netconn(request
, FALSE
);
4987 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
4990 /* FIXME: We should know that connection is closed before sending
4991 * headers. Otherwise wrong callbacks are executed */
4992 if(!responseLen
&& reusing_connection
) {
4993 TRACE("Connection closed by server, reconnecting\n");
4994 http_release_netconn(request
, FALSE
);
4999 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5000 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
5003 http_process_keep_alive(request
);
5004 HTTP_ProcessCookies(request
);
5005 HTTP_ProcessExpires(request
);
5006 HTTP_ProcessLastModified(request
);
5008 res
= set_content_length(request
);
5009 if(res
!= ERROR_SUCCESS
)
5011 if(!request
->contentLength
)
5012 http_release_netconn(request
, TRUE
);
5014 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5018 switch(request
->status_code
) {
5019 case HTTP_STATUS_REDIRECT
:
5020 case HTTP_STATUS_MOVED
:
5021 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5022 case HTTP_STATUS_REDIRECT_METHOD
:
5023 new_url
= get_redirect_url(request
);
5027 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5028 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5030 heap_free(request
->verb
);
5031 request
->verb
= heap_strdupW(szGET
);
5033 http_release_netconn(request
, drain_content(request
, FALSE
));
5034 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5035 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5036 res
= HTTP_HandleRedirect(request
, new_url
);
5038 if (res
== ERROR_SUCCESS
) {
5039 heap_free(requestString
);
5045 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5047 WCHAR szAuthValue
[2048];
5049 if (request
->status_code
== HTTP_STATUS_DENIED
)
5051 WCHAR
*host
= heap_strdupW( request
->server
->canon_host_port
);
5053 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5055 if (HTTP_DoAuthorization(request
, szAuthValue
,
5057 request
->session
->userName
,
5058 request
->session
->password
, host
))
5060 heap_free(requestString
);
5061 if(!drain_content(request
, TRUE
)) {
5062 FIXME("Could not drain content\n");
5063 http_release_netconn(request
, FALSE
);
5072 TRACE("Cleaning wrong authorization data\n");
5073 destroy_authinfo(request
->authInfo
);
5074 request
->authInfo
= NULL
;
5077 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5080 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5082 if (HTTP_DoAuthorization(request
, szAuthValue
,
5083 &request
->proxyAuthInfo
,
5084 request
->session
->appInfo
->proxyUsername
,
5085 request
->session
->appInfo
->proxyPassword
,
5088 heap_free(requestString
);
5089 if(!drain_content(request
, TRUE
)) {
5090 FIXME("Could not drain content\n");
5091 http_release_netconn(request
, FALSE
);
5099 TRACE("Cleaning wrong proxy authorization data\n");
5100 destroy_authinfo(request
->proxyAuthInfo
);
5101 request
->proxyAuthInfo
= NULL
;
5105 if (secure_proxy_connect
&& request
->status_code
== HTTP_STATUS_OK
)
5107 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5108 if (res
!= ERROR_SUCCESS
)
5110 WARN("failed to upgrade to secure proxy connection\n");
5111 http_release_netconn( request
, FALSE
);
5114 remove_header(request
, szProxy_Authorization
, TRUE
);
5115 destroy_authinfo(request
->proxyAuthInfo
);
5116 request
->proxyAuthInfo
= NULL
;
5118 secure_proxy_connect
= FALSE
;
5123 res
= ERROR_SUCCESS
;
5128 heap_free(requestString
);
5130 /* TODO: send notification for P3P header */
5132 if(res
== ERROR_SUCCESS
)
5133 create_cache_entry(request
);
5135 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5137 if (res
== ERROR_SUCCESS
) {
5138 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5139 HTTP_ReceiveRequestData(request
);
5141 send_request_complete(request
,
5142 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5144 send_request_complete(request
, 0, res
);
5160 } send_request_task_t
;
5162 /***********************************************************************
5164 * Helper functions for the HttpSendRequest(Ex) functions
5167 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5169 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5170 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5172 TRACE("%p\n", request
);
5174 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5175 task
->optional_len
, task
->content_len
, task
->end_request
);
5177 heap_free(task
->headers
);
5181 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5184 DWORD res
= ERROR_SUCCESS
;
5186 if(!is_valid_netconn(request
->netconn
)) {
5187 WARN("Not connected\n");
5188 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5189 return ERROR_INTERNET_OPERATION_CANCELLED
;
5192 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5193 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5195 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5196 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5198 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5199 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5201 /* process cookies here. Is this right? */
5202 http_process_keep_alive(request
);
5203 HTTP_ProcessCookies(request
);
5204 HTTP_ProcessExpires(request
);
5205 HTTP_ProcessLastModified(request
);
5207 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5208 if(!request
->contentLength
)
5209 http_release_netconn(request
, TRUE
);
5212 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5214 switch(request
->status_code
) {
5215 case HTTP_STATUS_REDIRECT
:
5216 case HTTP_STATUS_MOVED
:
5217 case HTTP_STATUS_REDIRECT_METHOD
:
5218 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5221 new_url
= get_redirect_url(request
);
5225 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5226 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5228 heap_free(request
->verb
);
5229 request
->verb
= heap_strdupW(szGET
);
5231 http_release_netconn(request
, drain_content(request
, FALSE
));
5232 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5233 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5234 res
= HTTP_HandleRedirect(request
, new_url
);
5236 if (res
== ERROR_SUCCESS
)
5237 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5242 if(res
== ERROR_SUCCESS
)
5243 create_cache_entry(request
);
5245 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5246 HTTP_ReceiveRequestData(request
);
5248 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5253 /***********************************************************************
5254 * HttpEndRequestA (WININET.@)
5256 * Ends an HTTP request that was started by HttpSendRequestEx
5259 * TRUE if successful
5263 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5264 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5266 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5270 SetLastError(ERROR_INVALID_PARAMETER
);
5274 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5281 } end_request_task_t
;
5283 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5285 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5286 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5290 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5293 /***********************************************************************
5294 * HttpEndRequestW (WININET.@)
5296 * Ends an HTTP request that was started by HttpSendRequestEx
5299 * TRUE if successful
5303 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5304 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5306 http_request_t
*request
;
5309 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5313 SetLastError(ERROR_INVALID_PARAMETER
);
5317 request
= (http_request_t
*) get_handle_object( hRequest
);
5319 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5321 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5323 WININET_Release( &request
->hdr
);
5326 request
->hdr
.dwFlags
|= dwFlags
;
5328 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5330 end_request_task_t
*task
;
5332 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5333 task
->flags
= dwFlags
;
5334 task
->context
= dwContext
;
5336 INTERNET_AsyncCall(&task
->hdr
);
5337 res
= ERROR_IO_PENDING
;
5340 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5342 WININET_Release( &request
->hdr
);
5343 TRACE("%u <--\n", res
);
5344 if(res
!= ERROR_SUCCESS
)
5346 return res
== ERROR_SUCCESS
;
5349 /***********************************************************************
5350 * HttpSendRequestExA (WININET.@)
5352 * Sends the specified request to the HTTP server and allows chunked
5357 * Failure: FALSE, call GetLastError() for more information.
5359 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5360 LPINTERNET_BUFFERSA lpBuffersIn
,
5361 LPINTERNET_BUFFERSA lpBuffersOut
,
5362 DWORD dwFlags
, DWORD_PTR dwContext
)
5364 INTERNET_BUFFERSW BuffersInW
;
5367 LPWSTR header
= NULL
;
5369 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5370 lpBuffersOut
, dwFlags
, dwContext
);
5374 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5375 if (lpBuffersIn
->lpcszHeader
)
5377 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5378 lpBuffersIn
->dwHeadersLength
,0,0);
5379 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5380 if (!(BuffersInW
.lpcszHeader
= header
))
5382 SetLastError(ERROR_OUTOFMEMORY
);
5385 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5386 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5390 BuffersInW
.lpcszHeader
= NULL
;
5391 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5392 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5393 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5394 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5395 BuffersInW
.Next
= NULL
;
5398 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5404 /***********************************************************************
5405 * HttpSendRequestExW (WININET.@)
5407 * Sends the specified request to the HTTP server and allows chunked
5412 * Failure: FALSE, call GetLastError() for more information.
5414 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5415 LPINTERNET_BUFFERSW lpBuffersIn
,
5416 LPINTERNET_BUFFERSW lpBuffersOut
,
5417 DWORD dwFlags
, DWORD_PTR dwContext
)
5419 http_request_t
*request
;
5420 http_session_t
*session
;
5424 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5425 lpBuffersOut
, dwFlags
, dwContext
);
5427 request
= (http_request_t
*) get_handle_object( hRequest
);
5429 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5431 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5435 session
= request
->session
;
5436 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5437 hIC
= session
->appInfo
;
5438 assert(hIC
->hdr
.htype
== WH_HINIT
);
5440 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5442 send_request_task_t
*task
;
5444 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5449 if (lpBuffersIn
->lpcszHeader
)
5451 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5452 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5454 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5456 task
->headers
= heap_alloc(size
);
5457 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5459 else task
->headers
= NULL
;
5461 task
->headers_len
= size
/ sizeof(WCHAR
);
5462 task
->optional
= lpBuffersIn
->lpvBuffer
;
5463 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5464 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5468 task
->headers
= NULL
;
5469 task
->headers_len
= 0;
5470 task
->optional
= NULL
;
5471 task
->optional_len
= 0;
5472 task
->content_len
= 0;
5475 task
->end_request
= FALSE
;
5477 INTERNET_AsyncCall(&task
->hdr
);
5478 res
= ERROR_IO_PENDING
;
5483 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5484 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5485 lpBuffersIn
->dwBufferTotal
, FALSE
);
5487 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5492 WININET_Release( &request
->hdr
);
5496 return res
== ERROR_SUCCESS
;
5499 /***********************************************************************
5500 * HttpSendRequestW (WININET.@)
5502 * Sends the specified request to the HTTP server
5509 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5510 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5512 http_request_t
*request
;
5513 http_session_t
*session
= NULL
;
5514 appinfo_t
*hIC
= NULL
;
5515 DWORD res
= ERROR_SUCCESS
;
5517 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5518 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5520 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5521 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5523 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5527 session
= request
->session
;
5528 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5530 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5534 hIC
= session
->appInfo
;
5535 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5537 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5541 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5543 send_request_task_t
*task
;
5545 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5550 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5551 else size
= dwHeaderLength
* sizeof(WCHAR
);
5553 task
->headers
= heap_alloc(size
);
5554 memcpy(task
->headers
, lpszHeaders
, size
);
5557 task
->headers
= NULL
;
5558 task
->headers_len
= dwHeaderLength
;
5559 task
->optional
= lpOptional
;
5560 task
->optional_len
= dwOptionalLength
;
5561 task
->content_len
= dwOptionalLength
;
5562 task
->end_request
= TRUE
;
5564 INTERNET_AsyncCall(&task
->hdr
);
5565 res
= ERROR_IO_PENDING
;
5569 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5570 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5571 dwOptionalLength
, TRUE
);
5575 WININET_Release( &request
->hdr
);
5578 return res
== ERROR_SUCCESS
;
5581 /***********************************************************************
5582 * HttpSendRequestA (WININET.@)
5584 * Sends the specified request to the HTTP server
5591 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5592 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5595 LPWSTR szHeaders
=NULL
;
5596 DWORD nLen
=dwHeaderLength
;
5597 if(lpszHeaders
!=NULL
)
5599 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5600 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5601 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5603 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5604 heap_free(szHeaders
);
5608 /***********************************************************************
5609 * HTTPSESSION_Destroy (internal)
5611 * Deallocate session handle
5614 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5616 http_session_t
*session
= (http_session_t
*) hdr
;
5618 TRACE("%p\n", session
);
5620 WININET_Release(&session
->appInfo
->hdr
);
5622 heap_free(session
->hostName
);
5623 heap_free(session
->password
);
5624 heap_free(session
->userName
);
5627 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5629 http_session_t
*ses
= (http_session_t
*)hdr
;
5632 case INTERNET_OPTION_HANDLE_TYPE
:
5633 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5635 if (*size
< sizeof(ULONG
))
5636 return ERROR_INSUFFICIENT_BUFFER
;
5638 *size
= sizeof(DWORD
);
5639 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5640 return ERROR_SUCCESS
;
5641 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5642 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5644 if (*size
< sizeof(DWORD
))
5645 return ERROR_INSUFFICIENT_BUFFER
;
5647 *size
= sizeof(DWORD
);
5648 *(DWORD
*)buffer
= ses
->connect_timeout
;
5649 return ERROR_SUCCESS
;
5651 case INTERNET_OPTION_SEND_TIMEOUT
:
5652 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5654 if (*size
< sizeof(DWORD
))
5655 return ERROR_INSUFFICIENT_BUFFER
;
5657 *size
= sizeof(DWORD
);
5658 *(DWORD
*)buffer
= ses
->send_timeout
;
5659 return ERROR_SUCCESS
;
5661 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5662 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5664 if (*size
< sizeof(DWORD
))
5665 return ERROR_INSUFFICIENT_BUFFER
;
5667 *size
= sizeof(DWORD
);
5668 *(DWORD
*)buffer
= ses
->receive_timeout
;
5669 return ERROR_SUCCESS
;
5672 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5675 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5677 http_session_t
*ses
= (http_session_t
*)hdr
;
5680 case INTERNET_OPTION_USERNAME
:
5682 heap_free(ses
->userName
);
5683 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5684 return ERROR_SUCCESS
;
5686 case INTERNET_OPTION_PASSWORD
:
5688 heap_free(ses
->password
);
5689 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5690 return ERROR_SUCCESS
;
5692 case INTERNET_OPTION_PROXY_USERNAME
:
5694 heap_free(ses
->appInfo
->proxyUsername
);
5695 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5696 return ERROR_SUCCESS
;
5698 case INTERNET_OPTION_PROXY_PASSWORD
:
5700 heap_free(ses
->appInfo
->proxyPassword
);
5701 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5702 return ERROR_SUCCESS
;
5704 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5706 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5707 ses
->connect_timeout
= *(DWORD
*)buffer
;
5708 return ERROR_SUCCESS
;
5710 case INTERNET_OPTION_SEND_TIMEOUT
:
5712 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5713 ses
->send_timeout
= *(DWORD
*)buffer
;
5714 return ERROR_SUCCESS
;
5716 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5718 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5719 ses
->receive_timeout
= *(DWORD
*)buffer
;
5720 return ERROR_SUCCESS
;
5725 return INET_SetOption(hdr
, option
, buffer
, size
);
5728 static const object_vtbl_t HTTPSESSIONVtbl
= {
5729 HTTPSESSION_Destroy
,
5731 HTTPSESSION_QueryOption
,
5732 HTTPSESSION_SetOption
,
5740 /***********************************************************************
5741 * HTTP_Connect (internal)
5743 * Create http session handle
5746 * HINTERNET a session handle on success
5750 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5751 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5752 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5753 DWORD dwInternalFlags
, HINTERNET
*ret
)
5755 http_session_t
*session
= NULL
;
5759 if (!lpszServerName
|| !lpszServerName
[0])
5760 return ERROR_INVALID_PARAMETER
;
5762 assert( hIC
->hdr
.htype
== WH_HINIT
);
5764 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5766 return ERROR_OUTOFMEMORY
;
5769 * According to my tests. The name is not resolved until a request is sent
5772 session
->hdr
.htype
= WH_HHTTPSESSION
;
5773 session
->hdr
.dwFlags
= dwFlags
;
5774 session
->hdr
.dwContext
= dwContext
;
5775 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5777 WININET_AddRef( &hIC
->hdr
);
5778 session
->appInfo
= hIC
;
5779 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5781 session
->hostName
= heap_strdupW(lpszServerName
);
5782 if (lpszUserName
&& lpszUserName
[0])
5783 session
->userName
= heap_strdupW(lpszUserName
);
5784 if (lpszPassword
&& lpszPassword
[0])
5785 session
->password
= heap_strdupW(lpszPassword
);
5786 session
->hostPort
= serverPort
;
5787 session
->connect_timeout
= hIC
->connect_timeout
;
5788 session
->send_timeout
= 0;
5789 session
->receive_timeout
= 0;
5791 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5792 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5794 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5795 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5800 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5804 TRACE("%p --> %p\n", hIC
, session
);
5806 *ret
= session
->hdr
.hInternet
;
5807 return ERROR_SUCCESS
;
5810 /***********************************************************************
5811 * HTTP_clear_response_headers (internal)
5813 * clear out any old response headers
5815 static void HTTP_clear_response_headers( http_request_t
*request
)
5819 EnterCriticalSection( &request
->headers_section
);
5821 for( i
=0; i
<request
->nCustHeaders
; i
++)
5823 if( !request
->custHeaders
[i
].lpszField
)
5825 if( !request
->custHeaders
[i
].lpszValue
)
5827 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5829 HTTP_DeleteCustomHeader( request
, i
);
5833 LeaveCriticalSection( &request
->headers_section
);
5836 /***********************************************************************
5837 * HTTP_GetResponseHeaders (internal)
5839 * Read server response
5846 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5849 WCHAR buffer
[MAX_REPLY_LEN
];
5850 DWORD buflen
= MAX_REPLY_LEN
;
5852 char bufferA
[MAX_REPLY_LEN
];
5853 LPWSTR status_code
= NULL
, status_text
= NULL
;
5854 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5855 BOOL codeHundred
= FALSE
;
5859 if(!is_valid_netconn(request
->netconn
))
5862 /* clear old response headers (eg. from a redirect response) */
5863 HTTP_clear_response_headers( request
);
5865 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5868 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5870 buflen
= MAX_REPLY_LEN
;
5871 if ((res
= read_line(request
, bufferA
, &buflen
)))
5874 if (!buflen
) goto lend
;
5877 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5878 /* check is this a status code line? */
5879 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5881 /* split the version from the status code */
5882 status_code
= strchrW( buffer
, ' ' );
5887 /* split the status code from the status text */
5888 status_text
= strchrW( status_code
, ' ' );
5892 request
->status_code
= atoiW(status_code
);
5894 TRACE("version [%s] status code [%s] status text [%s]\n",
5895 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5897 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5899 else if (!codeHundred
)
5901 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5903 heap_free(request
->version
);
5904 heap_free(request
->statusText
);
5906 request
->status_code
= HTTP_STATUS_OK
;
5907 request
->version
= heap_strdupW(g_szHttp1_0
);
5908 request
->statusText
= heap_strdupW(szOK
);
5912 } while (codeHundred
);
5914 /* Add status code */
5915 HTTP_ProcessHeader(request
, szStatus
, status_code
,
5916 HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
5918 heap_free(request
->version
);
5919 heap_free(request
->statusText
);
5921 request
->version
= heap_strdupW(buffer
);
5922 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
5924 /* Restore the spaces */
5925 *(status_code
-1) = ' ';
5927 *(status_text
-1) = ' ';
5929 /* Parse each response line */
5932 buflen
= MAX_REPLY_LEN
;
5933 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
5935 LPWSTR
* pFieldAndValue
;
5937 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
5939 if (!bufferA
[0]) break;
5940 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5942 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
5945 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
5946 HTTP_ADDREQ_FLAG_ADD
);
5947 HTTP_FreeTokens(pFieldAndValue
);
5958 res
= ERROR_SUCCESS
;
5967 /***********************************************************************
5968 * HTTP_InterpretHttpHeader (internal)
5970 * Parse server response
5974 * Pointer to array of field, value, NULL on success.
5977 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
5979 LPWSTR
* pTokenPair
;
5983 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
5985 pszColon
= strchrW(buffer
, ':');
5986 /* must have two tokens */
5989 HTTP_FreeTokens(pTokenPair
);
5991 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
5995 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
5998 HTTP_FreeTokens(pTokenPair
);
6001 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
6002 pTokenPair
[0][pszColon
- buffer
] = '\0';
6006 len
= strlenW(pszColon
);
6007 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
6010 HTTP_FreeTokens(pTokenPair
);
6013 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
6015 strip_spaces(pTokenPair
[0]);
6016 strip_spaces(pTokenPair
[1]);
6018 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
6022 /***********************************************************************
6023 * HTTP_ProcessHeader (internal)
6025 * Stuff header into header tables according to <dwModifier>
6029 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6031 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6033 LPHTTPHEADERW lphttpHdr
= NULL
;
6035 BOOL request_only
= !!(dwModifier
& HTTP_ADDHDR_FLAG_REQ
);
6036 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6038 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6040 EnterCriticalSection( &request
->headers_section
);
6042 /* REPLACE wins out over ADD */
6043 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6044 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6046 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6049 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6053 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6055 LeaveCriticalSection( &request
->headers_section
);
6056 return ERROR_HTTP_INVALID_HEADER
;
6058 lphttpHdr
= &request
->custHeaders
[index
];
6064 hdr
.lpszField
= (LPWSTR
)field
;
6065 hdr
.lpszValue
= (LPWSTR
)value
;
6066 hdr
.wFlags
= hdr
.wCount
= 0;
6068 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6069 hdr
.wFlags
|= HDR_ISREQUEST
;
6071 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6072 LeaveCriticalSection( &request
->headers_section
);
6075 /* no value to delete */
6078 LeaveCriticalSection( &request
->headers_section
);
6079 return ERROR_SUCCESS
;
6082 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6083 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6085 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6087 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6089 HTTP_DeleteCustomHeader( request
, index
);
6091 if (value
&& value
[0])
6095 hdr
.lpszField
= (LPWSTR
)field
;
6096 hdr
.lpszValue
= (LPWSTR
)value
;
6097 hdr
.wFlags
= hdr
.wCount
= 0;
6099 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6100 hdr
.wFlags
|= HDR_ISREQUEST
;
6102 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6103 LeaveCriticalSection( &request
->headers_section
);
6107 LeaveCriticalSection( &request
->headers_section
);
6108 return ERROR_SUCCESS
;
6110 else if (dwModifier
& COALESCEFLAGS
)
6115 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6116 INT valuelen
= strlenW(value
);
6118 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6121 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6123 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6126 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6129 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6131 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6134 lphttpHdr
->lpszValue
= lpsztmp
;
6135 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6138 lphttpHdr
->lpszValue
[origlen
] = ch
;
6140 lphttpHdr
->lpszValue
[origlen
] = ' ';
6144 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6145 lphttpHdr
->lpszValue
[len
] = '\0';
6146 res
= ERROR_SUCCESS
;
6150 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6151 res
= ERROR_OUTOFMEMORY
;
6154 TRACE("<-- %d\n", res
);
6155 LeaveCriticalSection( &request
->headers_section
);
6159 /***********************************************************************
6160 * HTTP_GetCustomHeaderIndex (internal)
6162 * Return index of custom header from header array
6163 * Headers section must be held
6165 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6166 int requested_index
, BOOL request_only
)
6170 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6172 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6174 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6177 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6180 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6183 if (requested_index
== 0)
6188 if (index
>= request
->nCustHeaders
)
6191 TRACE("Return: %d\n", index
);
6196 /***********************************************************************
6197 * HTTP_InsertCustomHeader (internal)
6199 * Insert header into array
6200 * Headers section must be held
6202 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6205 LPHTTPHEADERW lph
= NULL
;
6207 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6208 count
= request
->nCustHeaders
+ 1;
6210 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6212 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6215 return ERROR_OUTOFMEMORY
;
6217 request
->custHeaders
= lph
;
6218 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6219 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6220 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6221 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6222 request
->nCustHeaders
++;
6224 return ERROR_SUCCESS
;
6228 /***********************************************************************
6229 * HTTP_DeleteCustomHeader (internal)
6231 * Delete header from array
6232 * If this function is called, the index may change.
6233 * Headers section must be held
6235 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6237 if( request
->nCustHeaders
<= 0 )
6239 if( index
>= request
->nCustHeaders
)
6241 request
->nCustHeaders
--;
6243 heap_free(request
->custHeaders
[index
].lpszField
);
6244 heap_free(request
->custHeaders
[index
].lpszValue
);
6246 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6247 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6248 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6254 /***********************************************************************
6255 * IsHostInProxyBypassList (@)
6260 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6262 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);