2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
49 #define NO_SHLWAPI_STREAM
50 #define NO_SHLWAPI_REG
51 #define NO_SHLWAPI_STRFCNS
52 #define NO_SHLWAPI_GDI
59 #include "wine/debug.h"
60 #include "wine/exception.h"
61 #include "wine/unicode.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
65 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
66 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
67 static const WCHAR szOK
[] = {'O','K',0};
68 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
69 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
70 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
71 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
72 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
73 static const WCHAR szGET
[] = { 'G','E','T', 0 };
74 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
76 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
77 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
78 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
79 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
80 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
81 static const WCHAR szAge
[] = { 'A','g','e',0 };
82 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
83 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
84 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
85 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
86 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
87 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
88 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
89 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
90 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
91 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
92 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
93 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
94 static const WCHAR szContent_Transfer_Encoding
[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
95 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
96 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
97 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
98 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
99 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
100 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
101 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
102 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
103 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
104 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
106 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
107 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
108 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
109 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
110 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
111 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
112 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
113 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
114 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
115 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
116 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
117 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
118 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
119 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
120 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
121 static const WCHAR szUnless_Modified_Since
[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
122 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
123 static const WCHAR szURI
[] = { 'U','R','I',0 };
124 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
125 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
126 static const WCHAR szVia
[] = { 'V','i','a',0 };
127 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
128 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
130 static const WCHAR emptyW
[] = {0};
132 #define HTTP_REFERER szReferer
133 #define HTTP_ACCEPT szAccept
134 #define HTTP_USERAGENT szUser_Agent
136 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
137 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
138 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
139 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
140 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
141 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
142 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
144 #define COLLECT_TIME 60000
146 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
157 unsigned int auth_data_len
;
158 BOOL finished
; /* finished authenticating */
162 typedef struct _basicAuthorizationData
169 UINT authorizationLen
;
170 } basicAuthorizationData
;
172 typedef struct _authorizationData
186 static struct list basicAuthorizationCache
= LIST_INIT(basicAuthorizationCache
);
187 static struct list authorizationCache
= LIST_INIT(authorizationCache
);
189 static CRITICAL_SECTION authcache_cs
;
190 static CRITICAL_SECTION_DEBUG critsect_debug
=
193 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
194 0, 0, { (DWORD_PTR
)(__FILE__
": authcache_cs") }
196 static CRITICAL_SECTION authcache_cs
= { &critsect_debug
, -1, 0, 0, 0, 0 };
198 static DWORD
HTTP_GetResponseHeaders(http_request_t
*req
, INT
*len
);
199 static DWORD
HTTP_ProcessHeader(http_request_t
*req
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
);
200 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
);
201 static DWORD
HTTP_InsertCustomHeader(http_request_t
*req
, LPHTTPHEADERW lpHdr
);
202 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*req
, LPCWSTR lpszField
, INT index
, BOOL Request
);
203 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*req
, DWORD index
);
204 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
);
205 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*, DWORD
, LPVOID
, LPDWORD
, LPDWORD
);
206 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*req
, LPCWSTR lpszUrl
);
207 static UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
208 static BOOL
drain_content(http_request_t
*,BOOL
);
210 static CRITICAL_SECTION connection_pool_cs
;
211 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
213 0, 0, &connection_pool_cs
,
214 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
215 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
217 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
219 static struct list connection_pool
= LIST_INIT(connection_pool
);
220 static BOOL collector_running
;
222 void server_addref(server_t
*server
)
224 InterlockedIncrement(&server
->ref
);
227 void server_release(server_t
*server
)
229 if(InterlockedDecrement(&server
->ref
))
232 list_remove(&server
->entry
);
234 if(server
->cert_chain
)
235 CertFreeCertificateChain(server
->cert_chain
);
236 heap_free(server
->name
);
237 heap_free(server
->scheme_host_port
);
241 static BOOL
process_host_port(server_t
*server
)
247 static const WCHAR httpW
[] = {'h','t','t','p',0};
248 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
249 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
251 name_len
= strlenW(server
->name
);
252 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
256 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
257 server
->scheme_host_port
= buf
;
259 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
263 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
264 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
268 server_t
*get_server(const WCHAR
*name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
270 server_t
*iter
, *server
= NULL
;
272 if(port
== INTERNET_INVALID_PORT_NUMBER
)
273 port
= INTERNET_DEFAULT_HTTP_PORT
;
275 EnterCriticalSection(&connection_pool_cs
);
277 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
278 if(iter
->port
== port
&& !strcmpW(iter
->name
, name
) && iter
->is_https
== is_https
) {
280 server_addref(server
);
285 if(!server
&& do_create
) {
286 server
= heap_alloc_zero(sizeof(*server
));
288 server
->ref
= 2; /* list reference and return */
290 server
->is_https
= is_https
;
291 list_init(&server
->conn_pool
);
292 server
->name
= heap_strdupW(name
);
293 if(server
->name
&& process_host_port(server
)) {
294 list_add_head(&connection_pool
, &server
->entry
);
302 LeaveCriticalSection(&connection_pool_cs
);
307 BOOL
collect_connections(collect_type_t collect_type
)
309 netconn_t
*netconn
, *netconn_safe
;
310 server_t
*server
, *server_safe
;
311 BOOL remaining
= FALSE
;
314 now
= GetTickCount64();
316 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
317 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
318 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
319 TRACE("freeing %p\n", netconn
);
320 list_remove(&netconn
->pool_entry
);
321 free_netconn(netconn
);
327 if(collect_type
== COLLECT_CLEANUP
) {
328 list_remove(&server
->entry
);
329 list_init(&server
->entry
);
330 server_release(server
);
337 static DWORD WINAPI
collect_connections_proc(void *arg
)
339 BOOL remaining_conns
;
342 /* FIXME: Use more sophisticated method */
345 EnterCriticalSection(&connection_pool_cs
);
347 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
349 collector_running
= FALSE
;
351 LeaveCriticalSection(&connection_pool_cs
);
352 }while(remaining_conns
);
354 FreeLibraryAndExitThread(WININET_hModule
, 0);
357 /***********************************************************************
358 * HTTP_GetHeader (internal)
360 * Headers section must be held
362 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
365 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
366 if (HeaderIndex
== -1)
369 return &req
->custHeaders
[HeaderIndex
];
372 static WCHAR
*get_host_header( http_request_t
*req
)
377 EnterCriticalSection( &req
->headers_section
);
378 if ((header
= HTTP_GetHeader( req
, hostW
))) ret
= heap_strdupW( header
->lpszValue
);
379 LeaveCriticalSection( &req
->headers_section
);
383 struct data_stream_vtbl_t
{
384 DWORD (*get_avail_data
)(data_stream_t
*,http_request_t
*);
385 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
386 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,blocking_mode_t
);
387 BOOL (*drain_content
)(data_stream_t
*,http_request_t
*);
388 void (*destroy
)(data_stream_t
*);
392 data_stream_t data_stream
;
394 BYTE buf
[READ_BUFFER_SIZE
];
401 static inline void destroy_data_stream(data_stream_t
*stream
)
403 stream
->vtbl
->destroy(stream
);
406 static void reset_data_stream(http_request_t
*req
)
408 destroy_data_stream(req
->data_stream
);
409 req
->data_stream
= &req
->netconn_stream
.data_stream
;
410 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
411 req
->read_chunked
= req
->read_gzip
= FALSE
;
414 static void remove_header( http_request_t
*request
, const WCHAR
*str
, BOOL from_request
)
417 EnterCriticalSection( &request
->headers_section
);
418 index
= HTTP_GetCustomHeaderIndex( request
, str
, 0, from_request
);
419 if (index
!= -1) HTTP_DeleteCustomHeader( request
, index
);
420 LeaveCriticalSection( &request
->headers_section
);
426 data_stream_t stream
;
427 data_stream_t
*parent_stream
;
429 BYTE buf
[READ_BUFFER_SIZE
];
435 static DWORD
gzip_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
437 /* Allow reading only from read buffer */
441 static BOOL
gzip_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
443 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
444 return gzip_stream
->end_of_data
445 || (!gzip_stream
->buf_size
&& gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
));
448 static DWORD
gzip_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
449 DWORD
*read
, blocking_mode_t blocking_mode
)
451 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
452 z_stream
*zstream
= &gzip_stream
->zstream
;
453 DWORD current_read
, ret_read
= 0;
455 DWORD res
= ERROR_SUCCESS
;
457 TRACE("(%d %d)\n", size
, blocking_mode
);
459 while(size
&& !gzip_stream
->end_of_data
) {
460 if(!gzip_stream
->buf_size
) {
461 if(gzip_stream
->buf_pos
) {
462 if(gzip_stream
->buf_size
)
463 memmove(gzip_stream
->buf
, gzip_stream
->buf
+gzip_stream
->buf_pos
, gzip_stream
->buf_size
);
464 gzip_stream
->buf_pos
= 0;
466 res
= gzip_stream
->parent_stream
->vtbl
->read(gzip_stream
->parent_stream
, req
, gzip_stream
->buf
+gzip_stream
->buf_size
,
467 sizeof(gzip_stream
->buf
)-gzip_stream
->buf_size
, ¤t_read
, blocking_mode
);
468 gzip_stream
->buf_size
+= current_read
;
469 if(res
!= ERROR_SUCCESS
)
473 if(blocking_mode
!= BLOCKING_DISALLOW
) {
474 WARN("unexpected end of data\n");
475 gzip_stream
->end_of_data
= TRUE
;
481 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
482 zstream
->avail_in
= gzip_stream
->buf_size
;
483 zstream
->next_out
= buf
+ret_read
;
484 zstream
->avail_out
= size
;
485 zres
= inflate(&gzip_stream
->zstream
, 0);
486 current_read
= size
- zstream
->avail_out
;
487 size
-= current_read
;
488 ret_read
+= current_read
;
489 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
490 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
491 if(zres
== Z_STREAM_END
) {
492 TRACE("end of data\n");
493 gzip_stream
->end_of_data
= TRUE
;
495 }else if(zres
!= Z_OK
) {
496 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
498 res
= ERROR_INTERNET_DECODING_FAILED
;
502 if(ret_read
&& blocking_mode
== BLOCKING_ALLOW
)
503 blocking_mode
= BLOCKING_DISALLOW
;
506 TRACE("read %u bytes\n", ret_read
);
511 static BOOL
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
)
513 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
514 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
);
517 static void gzip_destroy(data_stream_t
*stream
)
519 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
521 destroy_data_stream(gzip_stream
->parent_stream
);
523 if(!gzip_stream
->end_of_data
)
524 inflateEnd(&gzip_stream
->zstream
);
525 heap_free(gzip_stream
);
528 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)
772 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
774 if (!setCookieHeader
->lpszValue
)
777 host
= HTTP_GetHeader(request
, hostW
);
781 data
= strchrW(setCookieHeader
->lpszValue
, '=');
785 name
= heap_strndupW(setCookieHeader
->lpszValue
, data
-setCookieHeader
->lpszValue
);
790 set_cookie(host
->lpszValue
, request
->path
, name
, data
, INTERNET_COOKIE_HTTPONLY
);
794 LeaveCriticalSection( &request
->headers_section
);
797 static void strip_spaces(LPWSTR start
)
806 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
808 end
= start
+ strlenW(start
) - 1;
809 while (end
>= start
&& *end
== ' ')
816 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
818 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
819 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
821 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAYSIZE(szBasic
)) &&
822 ((pszAuthValue
[ARRAYSIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAYSIZE(szBasic
)]);
823 if (is_basic
&& pszRealm
)
826 LPCWSTR ptr
= &pszAuthValue
[ARRAYSIZE(szBasic
)];
830 token
= strchrW(ptr
,'=');
834 while (*realm
== ' ')
836 if(!strncmpiW(realm
, szRealm
, ARRAYSIZE(szRealm
)) &&
837 (realm
[ARRAYSIZE(szRealm
)] == ' ' || realm
[ARRAYSIZE(szRealm
)] == '='))
840 while (*token
== ' ')
844 *pszRealm
= heap_strdupW(token
);
845 strip_spaces(*pszRealm
);
852 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
854 if (!authinfo
) return;
856 if (SecIsValidHandle(&authinfo
->ctx
))
857 DeleteSecurityContext(&authinfo
->ctx
);
858 if (SecIsValidHandle(&authinfo
->cred
))
859 FreeCredentialsHandle(&authinfo
->cred
);
861 heap_free(authinfo
->auth_data
);
862 heap_free(authinfo
->scheme
);
866 static UINT
retrieve_cached_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR
*auth_data
)
868 basicAuthorizationData
*ad
;
871 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
873 EnterCriticalSection(&authcache_cs
);
874 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
876 if (!strcmpiW(host
,ad
->host
) && !strcmpW(realm
,ad
->realm
))
878 TRACE("Authorization found in cache\n");
879 *auth_data
= heap_alloc(ad
->authorizationLen
);
880 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
881 rc
= ad
->authorizationLen
;
885 LeaveCriticalSection(&authcache_cs
);
889 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
892 basicAuthorizationData
* ad
= NULL
;
894 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
896 EnterCriticalSection(&authcache_cs
);
897 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
899 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
900 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
909 TRACE("Found match in cache, replacing\n");
910 heap_free(ad
->authorization
);
911 ad
->authorization
= heap_alloc(auth_data_len
);
912 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
913 ad
->authorizationLen
= auth_data_len
;
917 ad
= heap_alloc(sizeof(basicAuthorizationData
));
918 ad
->host
= heap_strdupW(host
);
919 ad
->realm
= heap_strdupW(realm
);
920 ad
->authorization
= heap_alloc(auth_data_len
);
921 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
922 ad
->authorizationLen
= auth_data_len
;
923 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
924 TRACE("authorization cached\n");
926 LeaveCriticalSection(&authcache_cs
);
929 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
930 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
932 authorizationData
*ad
;
934 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
936 EnterCriticalSection(&authcache_cs
);
937 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
938 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
939 TRACE("Authorization found in cache\n");
941 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
942 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
943 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
944 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
945 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
946 heap_free(nt_auth_identity
->User
);
947 heap_free(nt_auth_identity
->Password
);
948 heap_free(nt_auth_identity
->Domain
);
952 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
953 nt_auth_identity
->UserLength
= ad
->user_len
;
954 nt_auth_identity
->PasswordLength
= ad
->password_len
;
955 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
956 nt_auth_identity
->DomainLength
= ad
->domain_len
;
957 LeaveCriticalSection(&authcache_cs
);
961 LeaveCriticalSection(&authcache_cs
);
966 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
967 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
969 authorizationData
*ad
;
972 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
974 EnterCriticalSection(&authcache_cs
);
975 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
976 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
983 heap_free(ad
->password
);
984 heap_free(ad
->domain
);
986 ad
= heap_alloc(sizeof(authorizationData
));
988 LeaveCriticalSection(&authcache_cs
);
992 ad
->host
= heap_strdupW(host
);
993 ad
->scheme
= heap_strdupW(scheme
);
994 list_add_head(&authorizationCache
, &ad
->entry
);
997 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
998 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
999 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
1000 ad
->user_len
= nt_auth_identity
->UserLength
;
1001 ad
->password_len
= nt_auth_identity
->PasswordLength
;
1002 ad
->domain_len
= nt_auth_identity
->DomainLength
;
1004 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
1005 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
1006 heap_free(ad
->host
);
1007 heap_free(ad
->scheme
);
1008 heap_free(ad
->user
);
1009 heap_free(ad
->password
);
1010 heap_free(ad
->domain
);
1011 list_remove(&ad
->entry
);
1015 LeaveCriticalSection(&authcache_cs
);
1018 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
1019 struct HttpAuthInfo
**ppAuthInfo
,
1020 LPWSTR domain_and_username
, LPWSTR password
,
1023 SECURITY_STATUS sec_status
;
1024 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
1026 LPWSTR szRealm
= NULL
;
1028 TRACE("%s\n", debugstr_w(pszAuthValue
));
1035 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
1039 SecInvalidateHandle(&pAuthInfo
->cred
);
1040 SecInvalidateHandle(&pAuthInfo
->ctx
);
1041 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1042 pAuthInfo
->attr
= 0;
1043 pAuthInfo
->auth_data
= NULL
;
1044 pAuthInfo
->auth_data_len
= 0;
1045 pAuthInfo
->finished
= FALSE
;
1047 if (is_basic_auth_value(pszAuthValue
,NULL
))
1049 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1050 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1051 if (!pAuthInfo
->scheme
)
1053 heap_free(pAuthInfo
);
1060 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1062 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1063 if (!pAuthInfo
->scheme
)
1065 heap_free(pAuthInfo
);
1069 if (domain_and_username
)
1071 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1072 WCHAR
*domain
= domain_and_username
;
1074 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1076 pAuthData
= &nt_auth_identity
;
1081 user
= domain_and_username
;
1085 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1086 nt_auth_identity
.User
= user
;
1087 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1088 nt_auth_identity
.Domain
= domain
;
1089 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1090 nt_auth_identity
.Password
= password
;
1091 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1093 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1095 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1096 pAuthData
= &nt_auth_identity
;
1098 /* use default credentials */
1101 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1102 SECPKG_CRED_OUTBOUND
, NULL
,
1104 NULL
, &pAuthInfo
->cred
,
1107 if(pAuthData
&& !domain_and_username
) {
1108 heap_free(nt_auth_identity
.User
);
1109 heap_free(nt_auth_identity
.Domain
);
1110 heap_free(nt_auth_identity
.Password
);
1113 if (sec_status
== SEC_E_OK
)
1115 PSecPkgInfoW sec_pkg_info
;
1116 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1117 if (sec_status
== SEC_E_OK
)
1119 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1120 FreeContextBuffer(sec_pkg_info
);
1123 if (sec_status
!= SEC_E_OK
)
1125 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1126 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1127 heap_free(pAuthInfo
->scheme
);
1128 heap_free(pAuthInfo
);
1132 *ppAuthInfo
= pAuthInfo
;
1134 else if (pAuthInfo
->finished
)
1137 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1138 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1140 ERR("authentication scheme changed from %s to %s\n",
1141 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1145 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1149 char *auth_data
= NULL
;
1150 UINT auth_data_len
= 0;
1152 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1154 if (!domain_and_username
)
1156 if (host
&& szRealm
)
1157 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1158 if (auth_data_len
== 0)
1166 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1167 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1169 /* length includes a nul terminator, which will be re-used for the ':' */
1170 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1177 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1178 auth_data
[userlen
] = ':';
1179 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1180 auth_data_len
= userlen
+ 1 + passlen
;
1181 if (host
&& szRealm
)
1182 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1185 pAuthInfo
->auth_data
= auth_data
;
1186 pAuthInfo
->auth_data_len
= auth_data_len
;
1187 pAuthInfo
->finished
= TRUE
;
1193 LPCWSTR pszAuthData
;
1194 SecBufferDesc out_desc
, in_desc
;
1196 unsigned char *buffer
;
1197 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1198 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1200 in
.BufferType
= SECBUFFER_TOKEN
;
1204 in_desc
.ulVersion
= 0;
1205 in_desc
.cBuffers
= 1;
1206 in_desc
.pBuffers
= &in
;
1208 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1209 if (*pszAuthData
== ' ')
1212 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1213 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1214 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1217 buffer
= heap_alloc(pAuthInfo
->max_token
);
1219 out
.BufferType
= SECBUFFER_TOKEN
;
1220 out
.cbBuffer
= pAuthInfo
->max_token
;
1221 out
.pvBuffer
= buffer
;
1223 out_desc
.ulVersion
= 0;
1224 out_desc
.cBuffers
= 1;
1225 out_desc
.pBuffers
= &out
;
1227 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1228 first
? NULL
: &pAuthInfo
->ctx
,
1229 first
? request
->server
->name
: NULL
,
1230 context_req
, 0, SECURITY_NETWORK_DREP
,
1231 in
.pvBuffer
? &in_desc
: NULL
,
1232 0, &pAuthInfo
->ctx
, &out_desc
,
1233 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1234 if (sec_status
== SEC_E_OK
)
1236 pAuthInfo
->finished
= TRUE
;
1237 pAuthInfo
->auth_data
= out
.pvBuffer
;
1238 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1239 TRACE("sending last auth packet\n");
1241 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1243 pAuthInfo
->auth_data
= out
.pvBuffer
;
1244 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1245 TRACE("sending next auth packet\n");
1249 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1250 heap_free(out
.pvBuffer
);
1251 destroy_authinfo(pAuthInfo
);
1260 /***********************************************************************
1261 * HTTP_HttpAddRequestHeadersW (internal)
1263 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1264 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1269 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1271 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1273 if( dwHeaderLength
== ~0U )
1274 len
= strlenW(lpszHeader
);
1276 len
= dwHeaderLength
;
1277 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1278 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1284 LPWSTR
* pFieldAndValue
;
1286 lpszEnd
= lpszStart
;
1288 while (*lpszEnd
!= '\0')
1290 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1295 if (*lpszStart
== '\0')
1298 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1301 lpszEnd
++; /* Jump over newline */
1303 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1304 if (*lpszStart
== '\0')
1306 /* Skip 0-length headers */
1307 lpszStart
= lpszEnd
;
1308 res
= ERROR_SUCCESS
;
1311 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1314 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1315 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1316 HTTP_FreeTokens(pFieldAndValue
);
1319 lpszStart
= lpszEnd
;
1320 } while (res
== ERROR_SUCCESS
);
1326 /***********************************************************************
1327 * HttpAddRequestHeadersW (WININET.@)
1329 * Adds one or more HTTP header to the request handler
1332 * On Windows if dwHeaderLength includes the trailing '\0', then
1333 * HttpAddRequestHeadersW() adds it too. However this results in an
1334 * invalid HTTP header which is rejected by some servers so we probably
1335 * don't need to match Windows on that point.
1342 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1343 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1345 http_request_t
*request
;
1346 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1348 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1353 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1354 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1355 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1357 WININET_Release( &request
->hdr
);
1359 if(res
!= ERROR_SUCCESS
)
1361 return res
== ERROR_SUCCESS
;
1364 /***********************************************************************
1365 * HttpAddRequestHeadersA (WININET.@)
1367 * Adds one or more HTTP header to the request handler
1374 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1375 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1381 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1383 len
= MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, NULL
, 0 );
1384 hdr
= heap_alloc(len
*sizeof(WCHAR
));
1385 MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, hdr
, len
);
1386 if( dwHeaderLength
!= ~0U )
1387 dwHeaderLength
= len
;
1389 r
= HttpAddRequestHeadersW( hHttpRequest
, hdr
, dwHeaderLength
, dwModifier
);
1395 static void free_accept_types( WCHAR
**accept_types
)
1397 WCHAR
*ptr
, **types
= accept_types
;
1400 while ((ptr
= *types
))
1405 heap_free( accept_types
);
1408 static WCHAR
**convert_accept_types( const char **accept_types
)
1411 const char **types
= accept_types
;
1413 BOOL invalid_pointer
= FALSE
;
1415 if (!types
) return NULL
;
1421 /* find out how many there are */
1422 if (*types
&& **types
)
1424 TRACE("accept type: %s\n", debugstr_a(*types
));
1430 WARN("invalid accept type pointer\n");
1431 invalid_pointer
= TRUE
;
1436 if (invalid_pointer
) return NULL
;
1437 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1439 types
= accept_types
;
1442 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1445 typesW
[count
] = NULL
;
1449 /***********************************************************************
1450 * HttpOpenRequestA (WININET.@)
1452 * Open a HTTP request handle
1455 * HINTERNET a HTTP request handle on success
1459 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1460 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1461 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1462 DWORD dwFlags
, DWORD_PTR dwContext
)
1464 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1465 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1466 HINTERNET rc
= NULL
;
1468 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1469 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1470 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1471 dwFlags
, dwContext
);
1475 szVerb
= heap_strdupAtoW(lpszVerb
);
1482 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1483 if ( !szObjectName
)
1489 szVersion
= heap_strdupAtoW(lpszVersion
);
1496 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1501 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1502 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1503 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1506 free_accept_types(szAcceptTypes
);
1507 heap_free(szReferrer
);
1508 heap_free(szVersion
);
1509 heap_free(szObjectName
);
1514 /***********************************************************************
1517 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1520 static const CHAR HTTP_Base64Enc
[] =
1521 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1525 /* first 6 bits, all from bin[0] */
1526 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1527 x
= (bin
[0] & 3) << 4;
1529 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1532 base64
[n
++] = HTTP_Base64Enc
[x
];
1537 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1538 x
= ( bin
[1] & 0x0f ) << 2;
1540 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1543 base64
[n
++] = HTTP_Base64Enc
[x
];
1547 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1549 /* last 6 bits, all from bin [2] */
1550 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1558 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1559 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1560 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1561 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1562 static const signed char HTTP_Base64Dec
[256] =
1564 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1565 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1566 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1567 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1568 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1569 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1570 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1571 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1572 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1573 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1574 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1575 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1576 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1577 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1578 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1579 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1580 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1581 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1582 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1583 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1584 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1585 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1586 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1587 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1588 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1589 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1593 /***********************************************************************
1596 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1604 if (base64
[0] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1605 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1606 base64
[1] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1607 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1609 WARN("invalid base64: %s\n", debugstr_w(base64
));
1613 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1616 if ((base64
[2] == '=') && (base64
[3] == '='))
1618 if (base64
[2] > ARRAYSIZE(HTTP_Base64Dec
) ||
1619 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1621 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1625 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1628 if (base64
[3] == '=')
1630 if (base64
[3] > ARRAYSIZE(HTTP_Base64Dec
) ||
1631 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1633 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1637 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1646 /***********************************************************************
1647 * HTTP_InsertAuthorization
1649 * Insert or delete the authorization field in the request header.
1651 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1655 static const WCHAR wszSpace
[] = {' ',0};
1656 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1658 WCHAR
*authorization
= NULL
;
1660 if (pAuthInfo
->auth_data_len
)
1662 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1663 len
= strlenW(pAuthInfo
->scheme
)+1+((pAuthInfo
->auth_data_len
+2)*4)/3;
1664 authorization
= heap_alloc((len
+1)*sizeof(WCHAR
));
1668 strcpyW(authorization
, pAuthInfo
->scheme
);
1669 strcatW(authorization
, wszSpace
);
1670 HTTP_EncodeBase64(pAuthInfo
->auth_data
,
1671 pAuthInfo
->auth_data_len
,
1672 authorization
+strlenW(authorization
));
1674 /* clear the data as it isn't valid now that it has been sent to the
1675 * server, unless it's Basic authentication which doesn't do
1676 * connection tracking */
1677 if (strcmpiW(pAuthInfo
->scheme
, wszBasic
))
1679 heap_free(pAuthInfo
->auth_data
);
1680 pAuthInfo
->auth_data
= NULL
;
1681 pAuthInfo
->auth_data_len
= 0;
1685 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1687 HTTP_ProcessHeader(request
, header
, authorization
, HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
);
1688 heap_free(authorization
);
1693 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1698 len
= strlenW(req
->server
->scheme_host_port
);
1699 size
= len
+ strlenW(req
->path
) + 1;
1700 if(*req
->path
!= '/')
1702 url
= heap_alloc(size
* sizeof(WCHAR
));
1706 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1707 if(*req
->path
!= '/')
1710 strcpyW(url
+len
, req
->path
);
1712 TRACE("url=%s\n", debugstr_w(url
));
1716 static BOOL
HTTP_DomainMatches(LPCWSTR server
, LPCWSTR domain
)
1718 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1721 if (!strcmpiW( domain
, localW
) && !strchrW( server
, '.' ))
1723 else if (*domain
== '*')
1725 if (domain
[1] == '.')
1729 /* For a hostname to match a wildcard, the last domain must match
1730 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1731 * hostname is www.foo.a.b, it matches, but a.b does not.
1733 dot
= strchrW( server
, '.' );
1736 int len
= strlenW( dot
+ 1 );
1738 if (len
> strlenW( domain
+ 2 ))
1742 /* The server's domain is longer than the wildcard, so it
1743 * could be a subdomain. Compare the last portion of the
1746 ptr
= dot
+ len
+ 1 - strlenW( domain
+ 2 );
1747 if (!strcmpiW( ptr
, domain
+ 2 ))
1749 /* This is only a match if the preceding character is
1750 * a '.', i.e. that it is a matching domain. E.g.
1751 * if domain is '*.b.c' and server is 'www.ab.c' they
1754 ret
= *(ptr
- 1) == '.';
1758 ret
= !strcmpiW( dot
+ 1, domain
+ 2 );
1763 ret
= !strcmpiW( server
, domain
);
1767 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1772 if (!lpwai
->proxyBypass
) return FALSE
;
1773 ptr
= lpwai
->proxyBypass
;
1777 ptr
= strchrW( ptr
, ';' );
1779 ptr
= strchrW( tmp
, ' ' );
1782 if (ptr
- tmp
< INTERNET_MAX_HOST_NAME_LENGTH
)
1784 WCHAR domain
[INTERNET_MAX_HOST_NAME_LENGTH
];
1786 memcpy( domain
, tmp
, (ptr
- tmp
) * sizeof(WCHAR
) );
1787 domain
[ptr
- tmp
] = 0;
1788 ret
= HTTP_DomainMatches( server
, domain
);
1793 ret
= HTTP_DomainMatches( server
, tmp
);
1794 } while (ptr
&& !ret
);
1798 /***********************************************************************
1799 * HTTP_DealWithProxy
1801 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1803 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1804 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1805 static const WCHAR szFormat
[] = { 'h','t','t','p',':','/','/','%','s',0 };
1806 WCHAR buf
[INTERNET_MAX_HOST_NAME_LENGTH
];
1807 WCHAR protoProxy
[INTERNET_MAX_URL_LENGTH
];
1808 DWORD protoProxyLen
= INTERNET_MAX_URL_LENGTH
;
1809 WCHAR proxy
[INTERNET_MAX_URL_LENGTH
];
1810 static WCHAR szNul
[] = { 0 };
1811 URL_COMPONENTSW UrlComponents
;
1812 server_t
*new_server
;
1815 memset( &UrlComponents
, 0, sizeof UrlComponents
);
1816 UrlComponents
.dwStructSize
= sizeof UrlComponents
;
1817 UrlComponents
.lpszHostName
= buf
;
1818 UrlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
1820 if (!INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
, protoProxy
, &protoProxyLen
))
1822 if( CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1823 protoProxy
,strlenW(szHttp
),szHttp
,strlenW(szHttp
)) )
1824 sprintfW(proxy
, szFormat
, protoProxy
);
1826 strcpyW(proxy
, protoProxy
);
1827 if( !InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) )
1829 if( UrlComponents
.dwHostNameLength
== 0 )
1832 if( !request
->path
)
1833 request
->path
= szNul
;
1835 is_https
= (UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
);
1836 if (is_https
&& UrlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
1837 UrlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
1839 new_server
= get_server(UrlComponents
.lpszHostName
, UrlComponents
.nPort
, is_https
, TRUE
);
1843 request
->proxy
= new_server
;
1845 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1849 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1851 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1854 if(server
->addr_len
)
1855 return ERROR_SUCCESS
;
1857 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1858 INTERNET_STATUS_RESOLVING_NAME
,
1860 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1862 addr_len
= sizeof(server
->addr
);
1863 if (!GetAddress(server
->name
, server
->port
, (SOCKADDR
*)&server
->addr
, &addr_len
, server
->addr_str
))
1864 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1866 server
->addr_len
= addr_len
;
1867 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1868 INTERNET_STATUS_NAME_RESOLVED
,
1869 server
->addr_str
, strlen(server
->addr_str
)+1);
1871 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1872 return ERROR_SUCCESS
;
1875 static BOOL
HTTP_GetRequestURL(http_request_t
*req
, LPWSTR buf
)
1877 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1878 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1879 static const WCHAR slash
[] = { '/',0 };
1880 LPHTTPHEADERW host_header
;
1883 host_header
= HTTP_GetHeader(req
, hostW
);
1887 EnterCriticalSection( &req
->headers_section
);
1889 if (req
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)
1893 strcpyW(buf
, scheme
);
1894 strcatW(buf
, host_header
->lpszValue
);
1895 if (req
->path
[0] != '/')
1896 strcatW(buf
, slash
);
1897 strcatW(buf
, req
->path
);
1899 LeaveCriticalSection( &req
->headers_section
);
1904 /***********************************************************************
1905 * HTTPREQ_Destroy (internal)
1907 * Deallocate request handle
1910 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1912 http_request_t
*request
= (http_request_t
*) hdr
;
1917 if(request
->hCacheFile
)
1918 CloseHandle(request
->hCacheFile
);
1919 if(request
->req_file
)
1920 req_file_release(request
->req_file
);
1922 request
->headers_section
.DebugInfo
->Spare
[0] = 0;
1923 DeleteCriticalSection( &request
->headers_section
);
1924 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1925 DeleteCriticalSection( &request
->read_section
);
1926 WININET_Release(&request
->session
->hdr
);
1928 destroy_authinfo(request
->authInfo
);
1929 destroy_authinfo(request
->proxyAuthInfo
);
1932 server_release(request
->server
);
1934 server_release(request
->proxy
);
1936 heap_free(request
->path
);
1937 heap_free(request
->verb
);
1938 heap_free(request
->version
);
1939 heap_free(request
->statusText
);
1941 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1943 heap_free(request
->custHeaders
[i
].lpszField
);
1944 heap_free(request
->custHeaders
[i
].lpszValue
);
1946 destroy_data_stream(request
->data_stream
);
1947 heap_free(request
->custHeaders
);
1950 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1952 TRACE("%p %p %x\n",req
, req
->netconn
, reuse
);
1954 if(!is_valid_netconn(req
->netconn
))
1957 if(reuse
&& req
->netconn
->keep_alive
) {
1960 EnterCriticalSection(&connection_pool_cs
);
1962 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1963 req
->netconn
->keep_until
= GetTickCount64() + COLLECT_TIME
;
1964 req
->netconn
= NULL
;
1966 run_collector
= !collector_running
;
1967 collector_running
= TRUE
;
1969 LeaveCriticalSection(&connection_pool_cs
);
1972 HANDLE thread
= NULL
;
1975 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
1977 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
1979 EnterCriticalSection(&connection_pool_cs
);
1980 collector_running
= FALSE
;
1981 LeaveCriticalSection(&connection_pool_cs
);
1984 FreeLibrary(module
);
1987 CloseHandle(thread
);
1992 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1993 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
1995 close_netconn(req
->netconn
);
1997 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1998 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
2001 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
2003 WCHAR szVersion
[10];
2004 WCHAR szConnectionResponse
[20];
2005 DWORD dwBufferSize
= sizeof(szVersion
);
2006 BOOL keepalive
= FALSE
;
2008 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2009 * the connection is keep-alive by default */
2010 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2011 && !strcmpiW(szVersion
, g_szHttp1_1
))
2016 dwBufferSize
= sizeof(szConnectionResponse
);
2017 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
2018 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
2020 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2026 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2028 http_request_t
*req
= (http_request_t
*)hdr
;
2030 http_release_netconn(req
, drain_content(req
, FALSE
));
2033 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2038 WCHAR
*buf
= buffer
;
2040 if (str
) len
= strlenW(str
);
2042 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2044 *size
= (len
+ 1) * sizeof(WCHAR
);
2045 return ERROR_INSUFFICIENT_BUFFER
;
2047 if (str
) strcpyW(buf
, str
);
2051 return ERROR_SUCCESS
;
2057 if (str
) len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
2062 return ERROR_INSUFFICIENT_BUFFER
;
2064 if (str
) WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, *size
, NULL
, NULL
);
2068 return ERROR_SUCCESS
;
2072 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2074 http_request_t
*req
= (http_request_t
*)hdr
;
2077 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2079 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2081 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2083 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2084 return ERROR_INSUFFICIENT_BUFFER
;
2085 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2086 /* FIXME: can't get a SOCKET from our connection since we don't use
2090 /* FIXME: get source port from req->netConnection */
2091 info
->SourcePort
= 0;
2092 info
->DestPort
= req
->server
->port
;
2094 if (HTTP_KeepAlive(req
))
2095 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2097 info
->Flags
|= IDSI_FLAG_PROXY
;
2098 if (is_valid_netconn(req
->netconn
) && req
->netconn
->secure
)
2099 info
->Flags
|= IDSI_FLAG_SECURE
;
2101 return ERROR_SUCCESS
;
2105 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2107 case INTERNET_OPTION_SECURITY_FLAGS
:
2111 if (*size
< sizeof(ULONG
))
2112 return ERROR_INSUFFICIENT_BUFFER
;
2114 *size
= sizeof(DWORD
);
2115 flags
= is_valid_netconn(req
->netconn
) ? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2116 *(DWORD
*)buffer
= flags
;
2118 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2119 return ERROR_SUCCESS
;
2122 case INTERNET_OPTION_HANDLE_TYPE
:
2123 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2125 if (*size
< sizeof(ULONG
))
2126 return ERROR_INSUFFICIENT_BUFFER
;
2128 *size
= sizeof(DWORD
);
2129 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2130 return ERROR_SUCCESS
;
2132 case INTERNET_OPTION_URL
: {
2133 static const WCHAR httpW
[] = {'h','t','t','p',':','/','/',0};
2134 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2137 TRACE("INTERNET_OPTION_URL\n");
2139 EnterCriticalSection( &req
->headers_section
);
2140 host
= HTTP_GetHeader(req
, hostW
);
2141 strcpyW(url
, httpW
);
2142 strcatW(url
, host
->lpszValue
);
2143 strcatW(url
, req
->path
);
2144 LeaveCriticalSection( &req
->headers_section
);
2146 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url
));
2147 return str_to_buffer(url
, buffer
, size
, unicode
);
2149 case INTERNET_OPTION_USER_AGENT
:
2150 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2151 case INTERNET_OPTION_USERNAME
:
2152 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2153 case INTERNET_OPTION_PASSWORD
:
2154 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2155 case INTERNET_OPTION_PROXY_USERNAME
:
2156 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2157 case INTERNET_OPTION_PROXY_PASSWORD
:
2158 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2160 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2161 INTERNET_CACHE_ENTRY_INFOW
*info
;
2162 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2163 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2164 DWORD nbytes
, error
;
2167 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2169 if (*size
< sizeof(*ts
))
2171 *size
= sizeof(*ts
);
2172 return ERROR_INSUFFICIENT_BUFFER
;
2175 HTTP_GetRequestURL(req
, url
);
2176 ret
= GetUrlCacheEntryInfoW(url
, NULL
, &nbytes
);
2177 error
= GetLastError();
2178 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2180 if (!(info
= heap_alloc(nbytes
)))
2181 return ERROR_OUTOFMEMORY
;
2183 GetUrlCacheEntryInfoW(url
, info
, &nbytes
);
2185 ts
->ftExpires
= info
->ExpireTime
;
2186 ts
->ftLastModified
= info
->LastModifiedTime
;
2189 *size
= sizeof(*ts
);
2190 return ERROR_SUCCESS
;
2195 case INTERNET_OPTION_DATAFILE_NAME
: {
2198 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2200 if(!req
->req_file
) {
2202 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2206 req_size
= (lstrlenW(req
->req_file
->file_name
)+1) * sizeof(WCHAR
);
2207 if(*size
< req_size
)
2208 return ERROR_INSUFFICIENT_BUFFER
;
2211 memcpy(buffer
, req
->req_file
->file_name
, *size
);
2212 return ERROR_SUCCESS
;
2214 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
, -1, NULL
, 0, NULL
, NULL
);
2215 if (req_size
> *size
)
2216 return ERROR_INSUFFICIENT_BUFFER
;
2218 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
,
2219 -1, buffer
, *size
, NULL
, NULL
);
2220 return ERROR_SUCCESS
;
2224 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2225 PCCERT_CONTEXT context
;
2228 return ERROR_INTERNET_INVALID_OPERATION
;
2230 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2231 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2232 return ERROR_INSUFFICIENT_BUFFER
;
2235 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2237 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2240 memset(info
, 0, sizeof(*info
));
2241 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2242 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2243 len
= CertNameToStrA(context
->dwCertEncodingType
,
2244 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2245 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2246 if(info
->lpszSubjectInfo
)
2247 CertNameToStrA(context
->dwCertEncodingType
,
2248 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2249 info
->lpszSubjectInfo
, len
);
2250 len
= CertNameToStrA(context
->dwCertEncodingType
,
2251 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2252 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2253 if(info
->lpszIssuerInfo
)
2254 CertNameToStrA(context
->dwCertEncodingType
,
2255 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2256 info
->lpszIssuerInfo
, len
);
2257 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2258 CertFreeCertificateContext(context
);
2259 return ERROR_SUCCESS
;
2261 return ERROR_NOT_SUPPORTED
;
2263 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2264 if (*size
< sizeof(DWORD
))
2265 return ERROR_INSUFFICIENT_BUFFER
;
2267 *size
= sizeof(DWORD
);
2268 *(DWORD
*)buffer
= req
->connect_timeout
;
2269 return ERROR_SUCCESS
;
2270 case INTERNET_OPTION_REQUEST_FLAGS
: {
2273 if (*size
< sizeof(DWORD
))
2274 return ERROR_INSUFFICIENT_BUFFER
;
2276 /* FIXME: Add support for:
2277 * INTERNET_REQFLAG_FROM_CACHE
2278 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2282 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2283 if(!req
->status_code
)
2284 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2286 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2288 *size
= sizeof(DWORD
);
2289 *(DWORD
*)buffer
= flags
;
2290 return ERROR_SUCCESS
;
2294 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2297 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2299 http_request_t
*req
= (http_request_t
*)hdr
;
2302 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2303 TRACE("Undocumented option 99\n");
2305 if (!buffer
|| size
!= sizeof(DWORD
))
2306 return ERROR_INVALID_PARAMETER
;
2307 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2308 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2311 case INTERNET_OPTION_SECURITY_FLAGS
:
2315 if (!buffer
|| size
!= sizeof(DWORD
))
2316 return ERROR_INVALID_PARAMETER
;
2317 flags
= *(DWORD
*)buffer
;
2318 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2319 flags
&= SECURITY_SET_MASK
;
2320 req
->security_flags
|= flags
;
2321 if(is_valid_netconn(req
->netconn
))
2322 req
->netconn
->security_flags
|= flags
;
2323 return ERROR_SUCCESS
;
2325 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2326 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2327 req
->connect_timeout
= *(DWORD
*)buffer
;
2328 return ERROR_SUCCESS
;
2330 case INTERNET_OPTION_SEND_TIMEOUT
:
2331 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2332 req
->send_timeout
= *(DWORD
*)buffer
;
2333 return ERROR_SUCCESS
;
2335 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2336 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2337 req
->receive_timeout
= *(DWORD
*)buffer
;
2338 return ERROR_SUCCESS
;
2340 case INTERNET_OPTION_USERNAME
:
2341 heap_free(req
->session
->userName
);
2342 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2343 return ERROR_SUCCESS
;
2345 case INTERNET_OPTION_PASSWORD
:
2346 heap_free(req
->session
->password
);
2347 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2348 return ERROR_SUCCESS
;
2350 case INTERNET_OPTION_PROXY_USERNAME
:
2351 heap_free(req
->session
->appInfo
->proxyUsername
);
2352 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2353 return ERROR_SUCCESS
;
2355 case INTERNET_OPTION_PROXY_PASSWORD
:
2356 heap_free(req
->session
->appInfo
->proxyPassword
);
2357 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2358 return ERROR_SUCCESS
;
2360 case INTERNET_OPTION_HTTP_DECODING
:
2361 if(size
!= sizeof(BOOL
))
2362 return ERROR_INVALID_PARAMETER
;
2363 req
->decoding
= *(BOOL
*)buffer
;
2364 return ERROR_SUCCESS
;
2367 return INET_SetOption(hdr
, option
, buffer
, size
);
2370 static void commit_cache_entry(http_request_t
*req
)
2372 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2376 CloseHandle(req
->hCacheFile
);
2377 req
->hCacheFile
= NULL
;
2379 if(HTTP_GetRequestURL(req
, url
)) {
2384 header
= build_response_header(req
, TRUE
);
2385 header_len
= (header
? strlenW(header
) : 0);
2386 res
= CommitUrlCacheEntryW(url
, req
->req_file
->file_name
, req
->expires
,
2387 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2388 header
, header_len
, NULL
, 0);
2390 req
->req_file
->is_committed
= TRUE
;
2392 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2397 static void create_cache_entry(http_request_t
*req
)
2399 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2400 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2402 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2403 WCHAR file_name
[MAX_PATH
+1];
2406 /* FIXME: We should free previous cache file earlier */
2408 req_file_release(req
->req_file
);
2409 req
->req_file
= NULL
;
2411 if(req
->hCacheFile
) {
2412 CloseHandle(req
->hCacheFile
);
2413 req
->hCacheFile
= NULL
;
2416 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2422 EnterCriticalSection( &req
->headers_section
);
2424 header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2425 if(header_idx
!= -1) {
2428 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2431 while(*ptr
==' ' || *ptr
=='\t')
2434 end
= strchrW(ptr
, ',');
2436 end
= ptr
+ strlenW(ptr
);
2438 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2439 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2450 LeaveCriticalSection( &req
->headers_section
);
2454 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2457 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2460 b
= HTTP_GetRequestURL(req
, url
);
2462 WARN("Could not get URL\n");
2466 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2468 WARN("Could not create cache entry: %08x\n", GetLastError());
2472 create_req_file(file_name
, &req
->req_file
);
2474 req
->hCacheFile
= CreateFileW(file_name
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2475 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2476 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2477 WARN("Could not create file: %u\n", GetLastError());
2478 req
->hCacheFile
= NULL
;
2482 if(req
->read_size
) {
2485 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2487 FIXME("WriteFile failed: %u\n", GetLastError());
2489 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2490 commit_cache_entry(req
);
2494 /* read some more data into the read buffer (the read section must be held) */
2495 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2502 /* move existing data to the start of the buffer */
2504 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2508 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2510 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2511 maxlen
- req
->read_size
, BLOCKING_ALLOW
, &len
);
2512 if(res
== ERROR_SUCCESS
)
2513 req
->read_size
+= len
;
2518 /* remove some amount of data from the read buffer (the read section must be held) */
2519 static void remove_data( http_request_t
*req
, int count
)
2521 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2522 else req
->read_pos
+= count
;
2525 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2527 int count
, bytes_read
, pos
= 0;
2530 EnterCriticalSection( &req
->read_section
);
2533 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2537 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2538 bytes_read
= count
+ 1;
2540 else count
= bytes_read
= req
->read_size
;
2542 count
= min( count
, *len
- pos
);
2543 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2545 remove_data( req
, bytes_read
);
2548 if ((res
= read_more_data( req
, -1 )))
2550 WARN( "read failed %u\n", res
);
2551 LeaveCriticalSection( &req
->read_section
);
2554 if (!req
->read_size
)
2557 TRACE( "returning empty string\n" );
2558 LeaveCriticalSection( &req
->read_section
);
2559 return ERROR_SUCCESS
;
2562 LeaveCriticalSection( &req
->read_section
);
2566 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2569 buffer
[*len
- 1] = 0;
2570 TRACE( "returning %s\n", debugstr_a(buffer
));
2571 return ERROR_SUCCESS
;
2574 /* check if we have reached the end of the data to read (the read section must be held) */
2575 static BOOL
end_of_read_data( http_request_t
*req
)
2577 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2580 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, blocking_mode_t blocking_mode
)
2584 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, blocking_mode
);
2585 assert(*read
<= size
);
2587 if(req
->hCacheFile
) {
2592 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2594 FIXME("WriteFile failed: %u\n", GetLastError());
2597 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2598 commit_cache_entry(req
);
2604 /* fetch some more data into the read buffer (the read section must be held) */
2605 static DWORD
refill_read_buffer(http_request_t
*req
, blocking_mode_t blocking_mode
, DWORD
*read_bytes
)
2609 if(req
->read_size
== sizeof(req
->read_buf
))
2610 return ERROR_SUCCESS
;
2614 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2618 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2619 &read
, blocking_mode
);
2620 req
->read_size
+= read
;
2622 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2628 /* return the size of data available to be read immediately (the read section must be held) */
2629 static DWORD
get_avail_data( http_request_t
*req
)
2631 return req
->read_size
+ req
->data_stream
->vtbl
->get_avail_data(req
->data_stream
, req
);
2634 static DWORD
netconn_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2636 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2639 if(is_valid_netconn(req
->netconn
))
2640 NETCON_query_data_available(req
->netconn
, &avail
);
2641 return netconn_stream
->content_length
== ~0u
2643 : min(avail
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2646 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2648 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2649 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !is_valid_netconn(req
->netconn
);
2652 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2653 DWORD
*read
, blocking_mode_t blocking_mode
)
2655 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2656 DWORD res
= ERROR_SUCCESS
;
2659 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2661 if(size
&& is_valid_netconn(req
->netconn
)) {
2662 if((res
= NETCON_recv(req
->netconn
, buf
, size
, blocking_mode
, &len
))) {
2664 if(blocking_mode
== BLOCKING_DISALLOW
&& res
== WSAEWOULDBLOCK
)
2665 res
= ERROR_SUCCESS
;
2667 netconn_stream
->content_length
= netconn_stream
->content_read
;
2669 netconn_stream
->content_length
= netconn_stream
->content_read
;
2673 netconn_stream
->content_read
+= *read
= len
;
2674 TRACE("read %u bytes\n", len
);
2678 static BOOL
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2680 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2684 if(netconn_end_of_data(stream
, req
))
2688 if(NETCON_recv(req
->netconn
, buf
, sizeof(buf
), BLOCKING_DISALLOW
, &len
) != ERROR_SUCCESS
)
2691 netconn_stream
->content_read
+= len
;
2692 }while(netconn_stream
->content_read
< netconn_stream
->content_length
);
2697 static void netconn_destroy(data_stream_t
*stream
)
2701 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2702 netconn_get_avail_data
,
2703 netconn_end_of_data
,
2705 netconn_drain_content
,
2709 /* read some more data into the read buffer (the read section must be held) */
2710 static DWORD
read_more_chunked_data(chunked_stream_t
*stream
, http_request_t
*req
, int maxlen
)
2715 assert(!stream
->end_of_data
);
2717 if (stream
->buf_pos
)
2719 /* move existing data to the start of the buffer */
2720 if(stream
->buf_size
)
2721 memmove(stream
->buf
, stream
->buf
+ stream
->buf_pos
, stream
->buf_size
);
2722 stream
->buf_pos
= 0;
2725 if (maxlen
== -1) maxlen
= sizeof(stream
->buf
);
2727 res
= NETCON_recv( req
->netconn
, stream
->buf
+ stream
->buf_size
,
2728 maxlen
- stream
->buf_size
, BLOCKING_ALLOW
, &len
);
2729 if(res
== ERROR_SUCCESS
)
2730 stream
->buf_size
+= len
;
2735 /* remove some amount of data from the read buffer (the read section must be held) */
2736 static void remove_chunked_data(chunked_stream_t
*stream
, int count
)
2738 if (!(stream
->buf_size
-= count
)) stream
->buf_pos
= 0;
2739 else stream
->buf_pos
+= count
;
2742 /* discard data contents until we reach end of line (the read section must be held) */
2743 static DWORD
discard_chunked_eol(chunked_stream_t
*stream
, http_request_t
*req
)
2749 BYTE
*eol
= memchr(stream
->buf
+ stream
->buf_pos
, '\n', stream
->buf_size
);
2752 remove_chunked_data(stream
, (eol
+ 1) - (stream
->buf
+ stream
->buf_pos
));
2755 stream
->buf_pos
= stream
->buf_size
= 0; /* discard everything */
2756 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2757 } while (stream
->buf_size
);
2758 return ERROR_SUCCESS
;
2761 /* read the size of the next chunk (the read section must be held) */
2762 static DWORD
start_next_chunk(chunked_stream_t
*stream
, http_request_t
*req
)
2764 DWORD chunk_size
= 0, res
;
2766 assert(!stream
->chunk_size
|| stream
->chunk_size
== ~0u);
2768 if (stream
->end_of_data
) return ERROR_SUCCESS
;
2770 /* read terminator for the previous chunk */
2771 if(!stream
->chunk_size
&& (res
= discard_chunked_eol(stream
, req
)) != ERROR_SUCCESS
)
2776 while (stream
->buf_size
)
2778 char ch
= stream
->buf
[stream
->buf_pos
];
2779 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
2780 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
2781 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
2782 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
2784 TRACE( "reading %u byte chunk\n", chunk_size
);
2785 stream
->chunk_size
= chunk_size
;
2786 if (req
->contentLength
== ~0u) req
->contentLength
= chunk_size
;
2787 else req
->contentLength
+= chunk_size
;
2789 if (!chunk_size
) stream
->end_of_data
= TRUE
;
2790 return discard_chunked_eol(stream
, req
);
2792 remove_chunked_data(stream
, 1);
2794 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2795 if (!stream
->buf_size
)
2797 stream
->chunk_size
= 0;
2798 return ERROR_SUCCESS
;
2803 static DWORD
chunked_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2805 /* Allow reading only from read buffer */
2809 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2811 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2812 return chunked_stream
->end_of_data
;
2815 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2816 DWORD
*read
, blocking_mode_t blocking_mode
)
2818 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2819 DWORD read_bytes
= 0, ret_read
= 0, res
= ERROR_SUCCESS
;
2821 if(!chunked_stream
->chunk_size
|| chunked_stream
->chunk_size
== ~0u) {
2822 res
= start_next_chunk(chunked_stream
, req
);
2823 if(res
!= ERROR_SUCCESS
)
2827 while(size
&& chunked_stream
->chunk_size
&& !chunked_stream
->end_of_data
) {
2828 if(chunked_stream
->buf_size
) {
2829 read_bytes
= min(size
, min(chunked_stream
->buf_size
, chunked_stream
->chunk_size
));
2831 /* this could block */
2832 if(blocking_mode
== BLOCKING_DISALLOW
&& read_bytes
== chunked_stream
->chunk_size
)
2835 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2836 remove_chunked_data(chunked_stream
, read_bytes
);
2838 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2840 if(blocking_mode
== BLOCKING_DISALLOW
) {
2843 if(!is_valid_netconn(req
->netconn
) || !NETCON_query_data_available(req
->netconn
, &avail
) || !avail
)
2845 if(read_bytes
> avail
)
2848 /* this could block */
2849 if(read_bytes
== chunked_stream
->chunk_size
)
2853 res
= NETCON_recv(req
->netconn
, (char *)buf
+ret_read
, read_bytes
, BLOCKING_ALLOW
, (int*)&read_bytes
);
2854 if(res
!= ERROR_SUCCESS
)
2858 chunked_stream
->chunk_size
-= read_bytes
;
2860 ret_read
+= read_bytes
;
2861 if(size
&& !chunked_stream
->chunk_size
) {
2862 assert(blocking_mode
!= BLOCKING_DISALLOW
);
2863 res
= start_next_chunk(chunked_stream
, req
);
2864 if(res
!= ERROR_SUCCESS
)
2868 if(blocking_mode
== BLOCKING_ALLOW
)
2869 blocking_mode
= BLOCKING_DISALLOW
;
2872 TRACE("read %u bytes\n", ret_read
);
2877 static BOOL
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2879 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2881 remove_chunked_data(chunked_stream
, chunked_stream
->buf_size
);
2882 return chunked_stream
->end_of_data
;
2885 static void chunked_destroy(data_stream_t
*stream
)
2887 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2888 heap_free(chunked_stream
);
2891 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2892 chunked_get_avail_data
,
2893 chunked_end_of_data
,
2895 chunked_drain_content
,
2899 /* set the request content length based on the headers */
2900 static DWORD
set_content_length(http_request_t
*request
)
2902 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2903 static const WCHAR headW
[] = {'H','E','A','D',0};
2907 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
|| !strcmpW(request
->verb
, headW
)) {
2908 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2909 return ERROR_SUCCESS
;
2912 size
= sizeof(request
->contentLength
);
2913 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2914 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2915 request
->contentLength
= ~0u;
2916 request
->netconn_stream
.content_length
= request
->contentLength
;
2917 request
->netconn_stream
.content_read
= request
->read_size
;
2919 size
= sizeof(encoding
);
2920 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2921 !strcmpiW(encoding
, szChunked
))
2923 chunked_stream_t
*chunked_stream
;
2925 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2927 return ERROR_OUTOFMEMORY
;
2929 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2930 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2931 chunked_stream
->chunk_size
= ~0u;
2932 chunked_stream
->end_of_data
= FALSE
;
2934 if(request
->read_size
) {
2935 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2936 chunked_stream
->buf_size
= request
->read_size
;
2937 request
->read_size
= request
->read_pos
= 0;
2940 request
->data_stream
= &chunked_stream
->data_stream
;
2941 request
->contentLength
= ~0u;
2942 request
->read_chunked
= TRUE
;
2945 if(request
->decoding
) {
2948 static const WCHAR deflateW
[] = {'d','e','f','l','a','t','e',0};
2949 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2951 EnterCriticalSection( &request
->headers_section
);
2953 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2954 if(encoding_idx
!= -1) {
2955 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2956 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2957 LeaveCriticalSection( &request
->headers_section
);
2958 return init_gzip_stream(request
, TRUE
);
2960 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, deflateW
)) {
2961 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2962 LeaveCriticalSection( &request
->headers_section
);
2963 return init_gzip_stream(request
, FALSE
);
2967 LeaveCriticalSection( &request
->headers_section
);
2970 return ERROR_SUCCESS
;
2973 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
2975 INTERNET_ASYNC_RESULT iar
;
2977 iar
.dwResult
= result
;
2978 iar
.dwError
= error
;
2980 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
2981 sizeof(INTERNET_ASYNC_RESULT
));
2984 static void HTTP_ReceiveRequestData(http_request_t
*req
, BOOL first_notif
, DWORD
*ret_size
)
2986 DWORD res
, read
= 0, avail
= 0;
2987 blocking_mode_t mode
;
2991 EnterCriticalSection( &req
->read_section
);
2993 mode
= first_notif
&& req
->read_size
? BLOCKING_DISALLOW
: BLOCKING_ALLOW
;
2994 res
= refill_read_buffer(req
, mode
, &read
);
2995 if(res
== ERROR_SUCCESS
)
2996 avail
= get_avail_data(req
);
2998 LeaveCriticalSection( &req
->read_section
);
3000 if(res
!= ERROR_SUCCESS
|| (mode
!= BLOCKING_DISALLOW
&& !read
)) {
3001 WARN("res %u read %u, closing connection\n", res
, read
);
3002 http_release_netconn(req
, FALSE
);
3005 if(res
!= ERROR_SUCCESS
) {
3006 send_request_complete(req
, 0, res
);
3015 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, avail
);
3018 /* read data from the http connection (the read section must be held) */
3019 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
, BOOL sync
)
3021 DWORD current_read
= 0, ret_read
= 0;
3022 blocking_mode_t blocking_mode
;
3023 DWORD res
= ERROR_SUCCESS
;
3025 blocking_mode
= req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
? BLOCKING_ALLOW
: BLOCKING_WAITALL
;
3027 EnterCriticalSection( &req
->read_section
);
3029 if(req
->read_size
) {
3030 ret_read
= min(size
, req
->read_size
);
3031 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
3032 req
->read_size
-= ret_read
;
3033 req
->read_pos
+= ret_read
;
3034 if(blocking_mode
== BLOCKING_ALLOW
)
3035 blocking_mode
= BLOCKING_DISALLOW
;
3038 if(ret_read
< size
) {
3039 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, blocking_mode
);
3040 ret_read
+= current_read
;
3043 LeaveCriticalSection( &req
->read_section
);
3046 TRACE( "retrieved %u bytes (%u)\n", ret_read
, req
->contentLength
);
3048 if(size
&& !ret_read
)
3049 http_release_netconn(req
, res
== ERROR_SUCCESS
);
3054 static BOOL
drain_content(http_request_t
*req
, BOOL blocking
)
3058 if(!is_valid_netconn(req
->netconn
) || req
->contentLength
== -1)
3061 if(!strcmpW(req
->verb
, szHEAD
))
3065 return req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
);
3067 EnterCriticalSection( &req
->read_section
);
3070 DWORD bytes_read
, res
;
3073 res
= HTTPREQ_Read(req
, buf
, sizeof(buf
), &bytes_read
, TRUE
);
3074 if(res
!= ERROR_SUCCESS
) {
3084 LeaveCriticalSection( &req
->read_section
);
3088 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buffer
, DWORD size
, DWORD
*read
)
3090 http_request_t
*req
= (http_request_t
*)hdr
;
3093 EnterCriticalSection( &req
->read_section
);
3094 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3095 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3097 res
= HTTPREQ_Read(req
, buffer
, size
, read
, TRUE
);
3098 if(res
== ERROR_SUCCESS
)
3100 LeaveCriticalSection( &req
->read_section
);
3110 } read_file_ex_task_t
;
3112 static void AsyncReadFileExProc(task_header_t
*hdr
)
3114 read_file_ex_task_t
*task
= (read_file_ex_task_t
*)hdr
;
3115 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3118 TRACE("INTERNETREADFILEEXW %p\n", task
->hdr
.hdr
);
3120 res
= HTTPREQ_Read(req
, task
->buf
, task
->size
, task
->ret_read
, TRUE
);
3121 send_request_complete(req
, res
== ERROR_SUCCESS
, res
);
3124 static DWORD
HTTPREQ_ReadFileEx(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3125 DWORD flags
, DWORD_PTR context
)
3128 http_request_t
*req
= (http_request_t
*)hdr
;
3129 DWORD res
, read
, cread
, error
= ERROR_SUCCESS
;
3131 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3132 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3134 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3136 if (hdr
->dwFlags
& INTERNET_FLAG_ASYNC
)
3138 read_file_ex_task_t
*task
;
3140 if (TryEnterCriticalSection( &req
->read_section
))
3142 if (get_avail_data(req
))
3144 res
= HTTPREQ_Read(req
, buf
, size
, &read
, FALSE
);
3145 LeaveCriticalSection( &req
->read_section
);
3148 LeaveCriticalSection( &req
->read_section
);
3151 task
= alloc_async_task(&req
->hdr
, AsyncReadFileExProc
, sizeof(*task
));
3154 task
->ret_read
= ret_read
;
3156 INTERNET_AsyncCall(&task
->hdr
);
3158 return ERROR_IO_PENDING
;
3163 EnterCriticalSection( &req
->read_section
);
3164 if(hdr
->dwError
== ERROR_SUCCESS
)
3165 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3166 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3167 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3170 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
, !(flags
& IRF_NO_WAIT
));
3171 if(res
!= ERROR_SUCCESS
)
3175 if(read
== size
|| end_of_read_data(req
))
3178 LeaveCriticalSection( &req
->read_section
);
3180 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3181 &cread
, sizeof(cread
));
3182 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
3183 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3185 EnterCriticalSection( &req
->read_section
);
3188 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3189 hdr
->dwError
= ERROR_SUCCESS
;
3191 error
= hdr
->dwError
;
3193 LeaveCriticalSection( &req
->read_section
);
3197 if (res
== ERROR_SUCCESS
) {
3198 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3199 &read
, sizeof(read
));
3202 return res
==ERROR_SUCCESS
? error
: res
;
3205 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3208 http_request_t
*request
= (http_request_t
*)hdr
;
3210 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3213 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3214 if (res
== ERROR_SUCCESS
)
3215 request
->bytesWritten
+= *written
;
3217 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3224 } http_data_available_task_t
;
3226 static void AsyncQueryDataAvailableProc(task_header_t
*hdr
)
3228 http_data_available_task_t
*task
= (http_data_available_task_t
*)hdr
;
3230 HTTP_ReceiveRequestData((http_request_t
*)task
->hdr
.hdr
, FALSE
, task
->ret_size
);
3233 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3235 http_request_t
*req
= (http_request_t
*)hdr
;
3237 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3239 if (req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
3241 http_data_available_task_t
*task
;
3243 /* never wait, if we can't enter the section we queue an async request right away */
3244 if (TryEnterCriticalSection( &req
->read_section
))
3246 refill_read_buffer(req
, BLOCKING_DISALLOW
, NULL
);
3247 if ((*available
= get_avail_data( req
))) goto done
;
3248 if (end_of_read_data( req
)) goto done
;
3249 LeaveCriticalSection( &req
->read_section
);
3252 task
= alloc_async_task(&req
->hdr
, AsyncQueryDataAvailableProc
, sizeof(*task
));
3253 task
->ret_size
= available
;
3254 INTERNET_AsyncCall(&task
->hdr
);
3255 return ERROR_IO_PENDING
;
3258 EnterCriticalSection( &req
->read_section
);
3260 if (!(*available
= get_avail_data( req
)) && !end_of_read_data( req
))
3262 refill_read_buffer( req
, BLOCKING_ALLOW
, NULL
);
3263 *available
= get_avail_data( req
);
3267 LeaveCriticalSection( &req
->read_section
);
3269 TRACE( "returning %u\n", *available
);
3270 return ERROR_SUCCESS
;
3273 static DWORD
HTTPREQ_LockRequestFile(object_header_t
*hdr
, req_file_t
**ret
)
3275 http_request_t
*req
= (http_request_t
*)hdr
;
3277 TRACE("(%p)\n", req
);
3279 if(!req
->req_file
) {
3280 WARN("No cache file name available\n");
3281 return ERROR_FILE_NOT_FOUND
;
3284 *ret
= req_file_addref(req
->req_file
);
3285 return ERROR_SUCCESS
;
3288 static const object_vtbl_t HTTPREQVtbl
= {
3290 HTTPREQ_CloseConnection
,
3291 HTTPREQ_QueryOption
,
3296 HTTPREQ_QueryDataAvailable
,
3298 HTTPREQ_LockRequestFile
3301 /***********************************************************************
3302 * HTTP_HttpOpenRequestW (internal)
3304 * Open a HTTP request handle
3307 * HINTERNET a HTTP request handle on success
3311 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3312 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3313 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3314 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3316 appinfo_t
*hIC
= session
->appInfo
;
3317 http_request_t
*request
;
3322 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3324 return ERROR_OUTOFMEMORY
;
3326 request
->hdr
.htype
= WH_HHTTPREQ
;
3327 request
->hdr
.dwFlags
= dwFlags
;
3328 request
->hdr
.dwContext
= dwContext
;
3329 request
->contentLength
= ~0u;
3331 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3332 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3333 request
->connect_timeout
= session
->connect_timeout
;
3334 request
->send_timeout
= session
->send_timeout
;
3335 request
->receive_timeout
= session
->receive_timeout
;
3337 InitializeCriticalSection( &request
->headers_section
);
3338 request
->headers_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.headers_section");
3340 InitializeCriticalSection( &request
->read_section
);
3341 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3343 WININET_AddRef( &session
->hdr
);
3344 request
->session
= session
;
3345 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3347 request
->server
= get_server(session
->hostName
, session
->hostPort
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3348 if(!request
->server
) {
3349 WININET_Release(&request
->hdr
);
3350 return ERROR_OUTOFMEMORY
;
3353 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3354 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3355 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3356 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3358 if (lpszObjectName
&& *lpszObjectName
) {
3362 rc
= UrlEscapeW(lpszObjectName
, NULL
, &len
, URL_ESCAPE_SPACES_ONLY
);
3363 if (rc
!= E_POINTER
)
3364 len
= strlenW(lpszObjectName
)+1;
3365 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3366 rc
= UrlEscapeW(lpszObjectName
, request
->path
, &len
,
3367 URL_ESCAPE_SPACES_ONLY
);
3370 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3371 strcpyW(request
->path
,lpszObjectName
);
3374 static const WCHAR slashW
[] = {'/',0};
3376 request
->path
= heap_strdupW(slashW
);
3379 if (lpszReferrer
&& *lpszReferrer
)
3380 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3382 if (lpszAcceptTypes
)
3385 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3387 if (!*lpszAcceptTypes
[i
]) continue;
3388 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3389 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3390 HTTP_ADDHDR_FLAG_REQ
|
3391 (i
== 0 ? HTTP_ADDHDR_FLAG_REPLACE
: 0));
3395 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3396 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3398 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3400 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3401 HTTP_DealWithProxy( hIC
, session
, request
);
3403 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3404 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3407 TRACE("<-- (%p)\n", request
);
3409 *ret
= request
->hdr
.hInternet
;
3410 return ERROR_SUCCESS
;
3413 /***********************************************************************
3414 * HttpOpenRequestW (WININET.@)
3416 * Open a HTTP request handle
3419 * HINTERNET a HTTP request handle on success
3423 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3424 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3425 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3426 DWORD dwFlags
, DWORD_PTR dwContext
)
3428 http_session_t
*session
;
3429 HINTERNET handle
= NULL
;
3432 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3433 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3434 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3435 dwFlags
, dwContext
);
3436 if(lpszAcceptTypes
!=NULL
)
3439 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3440 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3443 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3444 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3446 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3451 * My tests seem to show that the windows version does not
3452 * become asynchronous until after this point. And anyhow
3453 * if this call was asynchronous then how would you get the
3454 * necessary HINTERNET pointer returned by this function.
3457 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3458 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3459 dwFlags
, dwContext
, &handle
);
3462 WININET_Release( &session
->hdr
);
3463 TRACE("returning %p\n", handle
);
3464 if(res
!= ERROR_SUCCESS
)
3469 static const LPCWSTR header_lookup
[] = {
3470 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3471 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3472 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3473 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3474 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3475 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3476 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3477 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3478 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3479 szDate
, /* HTTP_QUERY_DATE = 9 */
3480 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3481 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3482 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3483 szURI
, /* HTTP_QUERY_URI = 13 */
3484 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3485 NULL
, /* HTTP_QUERY_COST = 15 */
3486 NULL
, /* HTTP_QUERY_LINK = 16 */
3487 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3488 NULL
, /* HTTP_QUERY_VERSION = 18 */
3489 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3490 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3491 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3492 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3493 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3494 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3495 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3496 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3497 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3498 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3499 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3500 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3501 NULL
, /* HTTP_QUERY_FROM = 31 */
3502 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3503 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3504 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3505 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3506 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3507 szServer
, /* HTTP_QUERY_SERVER = 37 */
3508 NULL
, /* HTTP_TITLE = 38 */
3509 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3510 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3511 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3512 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3513 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3514 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3515 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3516 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3517 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3518 szAge
, /* HTTP_QUERY_AGE = 48 */
3519 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3520 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3521 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3522 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3523 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3524 szETag
, /* HTTP_QUERY_ETAG = 54 */
3525 hostW
, /* HTTP_QUERY_HOST = 55 */
3526 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3527 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3528 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3529 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3530 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3531 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3532 szRange
, /* HTTP_QUERY_RANGE = 62 */
3533 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3534 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3535 szVary
, /* HTTP_QUERY_VARY = 65 */
3536 szVia
, /* HTTP_QUERY_VIA = 66 */
3537 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3538 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3539 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3540 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3543 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3545 /***********************************************************************
3546 * HTTP_HttpQueryInfoW (internal)
3548 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3549 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3551 LPHTTPHEADERW lphttpHdr
= NULL
;
3552 BOOL request_only
= dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
;
3553 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3554 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3557 EnterCriticalSection( &request
->headers_section
);
3559 /* Find requested header structure */
3562 case HTTP_QUERY_CUSTOM
:
3565 LeaveCriticalSection( &request
->headers_section
);
3566 return ERROR_INVALID_PARAMETER
;
3568 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3570 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3574 DWORD res
= ERROR_INVALID_PARAMETER
;
3577 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3579 headers
= build_response_header(request
, TRUE
);
3582 LeaveCriticalSection( &request
->headers_section
);
3583 return ERROR_OUTOFMEMORY
;
3586 len
= strlenW(headers
) * sizeof(WCHAR
);
3587 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3589 len
+= sizeof(WCHAR
);
3590 res
= ERROR_INSUFFICIENT_BUFFER
;
3594 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3595 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3596 res
= ERROR_SUCCESS
;
3598 *lpdwBufferLength
= len
;
3601 LeaveCriticalSection( &request
->headers_section
);
3604 case HTTP_QUERY_RAW_HEADERS
:
3610 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3612 headers
= build_response_header(request
, FALSE
);
3616 LeaveCriticalSection( &request
->headers_section
);
3617 return ERROR_OUTOFMEMORY
;
3620 len
= strlenW(headers
) * sizeof(WCHAR
);
3621 if (len
> *lpdwBufferLength
)
3623 *lpdwBufferLength
= len
;
3625 LeaveCriticalSection( &request
->headers_section
);
3626 return ERROR_INSUFFICIENT_BUFFER
;
3633 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3635 for (i
= 0; i
< len
/ sizeof(WCHAR
); i
++)
3637 if (headers
[i
] == '\n')
3640 memcpy(lpBuffer
, headers
, len
);
3642 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3645 LeaveCriticalSection( &request
->headers_section
);
3646 return ERROR_SUCCESS
;
3648 case HTTP_QUERY_STATUS_TEXT
:
3649 if (request
->statusText
)
3651 DWORD len
= strlenW(request
->statusText
);
3652 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3654 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3655 LeaveCriticalSection( &request
->headers_section
);
3656 return ERROR_INSUFFICIENT_BUFFER
;
3660 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3661 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3663 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3664 LeaveCriticalSection( &request
->headers_section
);
3665 return ERROR_SUCCESS
;
3668 case HTTP_QUERY_VERSION
:
3669 if (request
->version
)
3671 DWORD len
= strlenW(request
->version
);
3672 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3674 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3675 LeaveCriticalSection( &request
->headers_section
);
3676 return ERROR_INSUFFICIENT_BUFFER
;
3680 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3681 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3683 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3684 LeaveCriticalSection( &request
->headers_section
);
3685 return ERROR_SUCCESS
;
3688 case HTTP_QUERY_CONTENT_ENCODING
:
3689 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3690 requested_index
,request_only
);
3692 case HTTP_QUERY_STATUS_CODE
: {
3693 DWORD res
= ERROR_SUCCESS
;
3697 LeaveCriticalSection( &request
->headers_section
);
3698 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3704 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3705 if(*lpdwBufferLength
>= sizeof(DWORD
))
3706 *(DWORD
*)lpBuffer
= request
->status_code
;
3708 res
= ERROR_INSUFFICIENT_BUFFER
;
3709 *lpdwBufferLength
= sizeof(DWORD
);
3713 static const WCHAR formatW
[] = {'%','u',0};
3715 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3717 if(size
<= *lpdwBufferLength
) {
3718 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3720 size
+= sizeof(WCHAR
);
3721 res
= ERROR_INSUFFICIENT_BUFFER
;
3724 *lpdwBufferLength
= size
;
3726 LeaveCriticalSection( &request
->headers_section
);
3730 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3732 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3733 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3734 requested_index
,request_only
);
3738 lphttpHdr
= &request
->custHeaders
[index
];
3740 /* Ensure header satisfies requested attributes */
3742 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3743 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3745 LeaveCriticalSection( &request
->headers_section
);
3746 return ERROR_HTTP_HEADER_NOT_FOUND
;
3749 /* coalesce value to requested type */
3750 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3752 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3753 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3755 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3761 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3763 tmpTM
= *gmtime(&tmpTime
);
3764 STHook
= (SYSTEMTIME
*)lpBuffer
;
3765 STHook
->wDay
= tmpTM
.tm_mday
;
3766 STHook
->wHour
= tmpTM
.tm_hour
;
3767 STHook
->wMilliseconds
= 0;
3768 STHook
->wMinute
= tmpTM
.tm_min
;
3769 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3770 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3771 STHook
->wSecond
= tmpTM
.tm_sec
;
3772 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3774 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3775 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3776 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3778 else if (lphttpHdr
->lpszValue
)
3780 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3782 if (len
> *lpdwBufferLength
)
3784 *lpdwBufferLength
= len
;
3785 LeaveCriticalSection( &request
->headers_section
);
3786 return ERROR_INSUFFICIENT_BUFFER
;
3790 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3791 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3793 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3795 if (lpdwIndex
) (*lpdwIndex
)++;
3797 LeaveCriticalSection( &request
->headers_section
);
3798 return ERROR_SUCCESS
;
3801 /***********************************************************************
3802 * HttpQueryInfoW (WININET.@)
3804 * Queries for information about an HTTP request
3811 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3812 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3814 http_request_t
*request
;
3817 if (TRACE_ON(wininet
)) {
3818 #define FE(x) { x, #x }
3819 static const wininet_flag_info query_flags
[] = {
3820 FE(HTTP_QUERY_MIME_VERSION
),
3821 FE(HTTP_QUERY_CONTENT_TYPE
),
3822 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3823 FE(HTTP_QUERY_CONTENT_ID
),
3824 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3825 FE(HTTP_QUERY_CONTENT_LENGTH
),
3826 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3827 FE(HTTP_QUERY_ALLOW
),
3828 FE(HTTP_QUERY_PUBLIC
),
3829 FE(HTTP_QUERY_DATE
),
3830 FE(HTTP_QUERY_EXPIRES
),
3831 FE(HTTP_QUERY_LAST_MODIFIED
),
3832 FE(HTTP_QUERY_MESSAGE_ID
),
3834 FE(HTTP_QUERY_DERIVED_FROM
),
3835 FE(HTTP_QUERY_COST
),
3836 FE(HTTP_QUERY_LINK
),
3837 FE(HTTP_QUERY_PRAGMA
),
3838 FE(HTTP_QUERY_VERSION
),
3839 FE(HTTP_QUERY_STATUS_CODE
),
3840 FE(HTTP_QUERY_STATUS_TEXT
),
3841 FE(HTTP_QUERY_RAW_HEADERS
),
3842 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3843 FE(HTTP_QUERY_CONNECTION
),
3844 FE(HTTP_QUERY_ACCEPT
),
3845 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3846 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3847 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3848 FE(HTTP_QUERY_AUTHORIZATION
),
3849 FE(HTTP_QUERY_CONTENT_ENCODING
),
3850 FE(HTTP_QUERY_FORWARDED
),
3851 FE(HTTP_QUERY_FROM
),
3852 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3853 FE(HTTP_QUERY_LOCATION
),
3854 FE(HTTP_QUERY_ORIG_URI
),
3855 FE(HTTP_QUERY_REFERER
),
3856 FE(HTTP_QUERY_RETRY_AFTER
),
3857 FE(HTTP_QUERY_SERVER
),
3858 FE(HTTP_QUERY_TITLE
),
3859 FE(HTTP_QUERY_USER_AGENT
),
3860 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3861 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3862 FE(HTTP_QUERY_ACCEPT_RANGES
),
3863 FE(HTTP_QUERY_SET_COOKIE
),
3864 FE(HTTP_QUERY_COOKIE
),
3865 FE(HTTP_QUERY_REQUEST_METHOD
),
3866 FE(HTTP_QUERY_REFRESH
),
3867 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3869 FE(HTTP_QUERY_CACHE_CONTROL
),
3870 FE(HTTP_QUERY_CONTENT_BASE
),
3871 FE(HTTP_QUERY_CONTENT_LOCATION
),
3872 FE(HTTP_QUERY_CONTENT_MD5
),
3873 FE(HTTP_QUERY_CONTENT_RANGE
),
3874 FE(HTTP_QUERY_ETAG
),
3875 FE(HTTP_QUERY_HOST
),
3876 FE(HTTP_QUERY_IF_MATCH
),
3877 FE(HTTP_QUERY_IF_NONE_MATCH
),
3878 FE(HTTP_QUERY_IF_RANGE
),
3879 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3880 FE(HTTP_QUERY_MAX_FORWARDS
),
3881 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3882 FE(HTTP_QUERY_RANGE
),
3883 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3884 FE(HTTP_QUERY_UPGRADE
),
3885 FE(HTTP_QUERY_VARY
),
3887 FE(HTTP_QUERY_WARNING
),
3888 FE(HTTP_QUERY_CUSTOM
)
3890 static const wininet_flag_info modifier_flags
[] = {
3891 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3892 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3893 FE(HTTP_QUERY_FLAG_NUMBER
),
3894 FE(HTTP_QUERY_FLAG_COALESCE
)
3897 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3898 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3901 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3902 TRACE(" Attribute:");
3903 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3904 if (query_flags
[i
].val
== info
) {
3905 TRACE(" %s", query_flags
[i
].name
);
3909 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3910 TRACE(" Unknown (%08x)", info
);
3913 TRACE(" Modifier:");
3914 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3915 if (modifier_flags
[i
].val
& info_mod
) {
3916 TRACE(" %s", modifier_flags
[i
].name
);
3917 info_mod
&= ~ modifier_flags
[i
].val
;
3922 TRACE(" Unknown (%08x)", info_mod
);
3927 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3928 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3930 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3934 if (lpBuffer
== NULL
)
3935 *lpdwBufferLength
= 0;
3936 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3937 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3941 WININET_Release( &request
->hdr
);
3943 TRACE("%u <--\n", res
);
3944 if(res
!= ERROR_SUCCESS
)
3946 return res
== ERROR_SUCCESS
;
3949 /***********************************************************************
3950 * HttpQueryInfoA (WININET.@)
3952 * Queries for information about an HTTP request
3959 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3960 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3966 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
3968 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3969 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3971 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3972 lpdwBufferLength
, lpdwIndex
);
3978 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
3979 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3981 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
3987 bufferW
= heap_alloc(alloclen
);
3988 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3989 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3990 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
3997 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
4001 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
4002 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
4003 *lpdwBufferLength
= len
- 1;
4005 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
4008 /* since the strings being returned from HttpQueryInfoW should be
4009 * only ASCII characters, it is reasonable to assume that all of
4010 * the Unicode characters can be reduced to a single byte */
4011 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
4013 heap_free( bufferW
);
4017 /***********************************************************************
4018 * HTTP_GetRedirectURL (internal)
4020 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*request
, LPCWSTR lpszUrl
)
4022 static WCHAR szHttp
[] = {'h','t','t','p',0};
4023 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
4024 http_session_t
*session
= request
->session
;
4025 URL_COMPONENTSW urlComponents
;
4026 DWORD url_length
= 0;
4028 LPWSTR combined_url
;
4030 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
4031 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
4032 urlComponents
.dwSchemeLength
= 0;
4033 urlComponents
.lpszHostName
= request
->server
->name
;
4034 urlComponents
.dwHostNameLength
= 0;
4035 urlComponents
.nPort
= request
->server
->port
;
4036 urlComponents
.lpszUserName
= session
->userName
;
4037 urlComponents
.dwUserNameLength
= 0;
4038 urlComponents
.lpszPassword
= NULL
;
4039 urlComponents
.dwPasswordLength
= 0;
4040 urlComponents
.lpszUrlPath
= request
->path
;
4041 urlComponents
.dwUrlPathLength
= 0;
4042 urlComponents
.lpszExtraInfo
= NULL
;
4043 urlComponents
.dwExtraInfoLength
= 0;
4045 if (!InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
) &&
4046 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
4049 orig_url
= heap_alloc(url_length
);
4051 /* convert from bytes to characters */
4052 url_length
= url_length
/ sizeof(WCHAR
) - 1;
4053 if (!InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
))
4055 heap_free(orig_url
);
4060 if (!InternetCombineUrlW(orig_url
, lpszUrl
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
) &&
4061 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
4063 heap_free(orig_url
);
4066 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
4068 if (!InternetCombineUrlW(orig_url
, lpszUrl
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
))
4070 heap_free(orig_url
);
4071 heap_free(combined_url
);
4074 heap_free(orig_url
);
4075 return combined_url
;
4079 /***********************************************************************
4080 * HTTP_HandleRedirect (internal)
4082 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, LPCWSTR lpszUrl
)
4084 http_session_t
*session
= request
->session
;
4085 WCHAR path
[INTERNET_MAX_PATH_LENGTH
];
4089 /* if it's an absolute path, keep the same session info */
4090 lstrcpynW(path
, lpszUrl
, INTERNET_MAX_URL_LENGTH
);
4094 URL_COMPONENTSW urlComponents
;
4095 WCHAR protocol
[INTERNET_MAX_SCHEME_LENGTH
];
4096 WCHAR hostName
[INTERNET_MAX_HOST_NAME_LENGTH
];
4097 WCHAR userName
[INTERNET_MAX_USER_NAME_LENGTH
];
4098 BOOL custom_port
= FALSE
;
4100 static const WCHAR httpW
[] = {'h','t','t','p',0};
4101 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
4107 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
4108 urlComponents
.lpszScheme
= protocol
;
4109 urlComponents
.dwSchemeLength
= INTERNET_MAX_SCHEME_LENGTH
;
4110 urlComponents
.lpszHostName
= hostName
;
4111 urlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
4112 urlComponents
.lpszUserName
= userName
;
4113 urlComponents
.dwUserNameLength
= INTERNET_MAX_USER_NAME_LENGTH
;
4114 urlComponents
.lpszPassword
= NULL
;
4115 urlComponents
.dwPasswordLength
= 0;
4116 urlComponents
.lpszUrlPath
= path
;
4117 urlComponents
.dwUrlPathLength
= INTERNET_MAX_PATH_LENGTH
;
4118 urlComponents
.lpszExtraInfo
= NULL
;
4119 urlComponents
.dwExtraInfoLength
= 0;
4120 if(!InternetCrackUrlW(lpszUrl
, strlenW(lpszUrl
), 0, &urlComponents
))
4121 return INTERNET_GetLastError();
4123 if(!strcmpiW(protocol
, httpW
)) {
4124 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4125 TRACE("redirect from secure page to non-secure page\n");
4126 /* FIXME: warn about from secure redirect to non-secure page */
4127 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4130 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4131 urlComponents
.nPort
= INTERNET_DEFAULT_HTTP_PORT
;
4132 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
)
4134 }else if(!strcmpiW(protocol
, httpsW
)) {
4135 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4136 TRACE("redirect from non-secure page to secure page\n");
4137 /* FIXME: notify about redirect to secure page */
4138 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4141 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4142 urlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
4143 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
)
4147 heap_free(session
->hostName
);
4149 session
->hostName
= heap_strdupW(hostName
);
4150 session
->hostPort
= urlComponents
.nPort
;
4152 heap_free(session
->userName
);
4153 session
->userName
= NULL
;
4155 session
->userName
= heap_strdupW(userName
);
4157 reset_data_stream(request
);
4159 if(strcmpiW(request
->server
->name
, hostName
) || request
->server
->port
!= urlComponents
.nPort
) {
4160 server_t
*new_server
;
4162 new_server
= get_server(hostName
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4163 server_release(request
->server
);
4164 request
->server
= new_server
;
4168 HTTP_ProcessHeader(request
, hostW
, request
->server
->host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4170 HTTP_ProcessHeader(request
, hostW
, request
->server
->name
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4172 heap_free(request
->path
);
4179 rc
= UrlEscapeW(path
, NULL
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4180 if (rc
!= E_POINTER
)
4181 needed
= strlenW(path
)+1;
4182 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4183 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4184 URL_ESCAPE_SPACES_ONLY
);
4187 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4188 strcpyW(request
->path
,path
);
4192 /* Remove custom content-type/length headers on redirects. */
4193 remove_header(request
, szContent_Type
, TRUE
);
4194 remove_header(request
, szContent_Length
, TRUE
);
4196 return ERROR_SUCCESS
;
4199 /***********************************************************************
4200 * HTTP_build_req (internal)
4202 * concatenate all the strings in the request together
4204 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4209 for( t
= list
; *t
; t
++ )
4210 len
+= strlenW( *t
);
4213 str
= heap_alloc(len
*sizeof(WCHAR
));
4216 for( t
= list
; *t
; t
++ )
4222 static void HTTP_InsertCookies(http_request_t
*request
)
4227 res
= get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4228 if(res
!= ERROR_SUCCESS
|| !cookies
)
4231 get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4232 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
), HTTP_ADDREQ_FLAG_REPLACE
);
4236 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4238 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4246 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4247 if (!strcmpiW(day
, days
[i
]))
4254 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4256 static const WCHAR jan
[] = { 'j','a','n',0 };
4257 static const WCHAR feb
[] = { 'f','e','b',0 };
4258 static const WCHAR mar
[] = { 'm','a','r',0 };
4259 static const WCHAR apr
[] = { 'a','p','r',0 };
4260 static const WCHAR may
[] = { 'm','a','y',0 };
4261 static const WCHAR jun
[] = { 'j','u','n',0 };
4262 static const WCHAR jul
[] = { 'j','u','l',0 };
4263 static const WCHAR aug
[] = { 'a','u','g',0 };
4264 static const WCHAR sep
[] = { 's','e','p',0 };
4265 static const WCHAR oct
[] = { 'o','c','t',0 };
4266 static const WCHAR nov
[] = { 'n','o','v',0 };
4267 static const WCHAR dec
[] = { 'd','e','c',0 };
4269 if (!strcmpiW(month
, jan
)) return 1;
4270 if (!strcmpiW(month
, feb
)) return 2;
4271 if (!strcmpiW(month
, mar
)) return 3;
4272 if (!strcmpiW(month
, apr
)) return 4;
4273 if (!strcmpiW(month
, may
)) return 5;
4274 if (!strcmpiW(month
, jun
)) return 6;
4275 if (!strcmpiW(month
, jul
)) return 7;
4276 if (!strcmpiW(month
, aug
)) return 8;
4277 if (!strcmpiW(month
, sep
)) return 9;
4278 if (!strcmpiW(month
, oct
)) return 10;
4279 if (!strcmpiW(month
, nov
)) return 11;
4280 if (!strcmpiW(month
, dec
)) return 12;
4285 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4286 * optionally preceded by whitespace.
4287 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4288 * st, and sets *str to the first character after the time format.
4290 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4296 while (isspaceW(*ptr
))
4299 num
= strtoulW(ptr
, &nextPtr
, 10);
4300 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4302 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4307 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4311 st
->wHour
= (WORD
)num
;
4312 num
= strtoulW(ptr
, &nextPtr
, 10);
4313 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4315 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4320 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4324 st
->wMinute
= (WORD
)num
;
4325 num
= strtoulW(ptr
, &nextPtr
, 10);
4326 if (!nextPtr
|| nextPtr
<= ptr
)
4328 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4333 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4338 st
->wSecond
= (WORD
)num
;
4342 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4344 static const WCHAR gmt
[]= { 'G','M','T',0 };
4345 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4347 SYSTEMTIME st
= { 0 };
4350 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4351 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4354 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4355 if (st
.wDayOfWeek
>= 7)
4357 ERR("unexpected weekday %s\n", debugstr_w(day
));
4361 while (isspaceW(*ptr
))
4364 for (monthPtr
= month
; !isspace(*ptr
) &&
4365 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4369 st
.wMonth
= HTTP_ParseMonth(month
);
4370 if (!st
.wMonth
|| st
.wMonth
> 12)
4372 ERR("unexpected month %s\n", debugstr_w(month
));
4376 while (isspaceW(*ptr
))
4379 num
= strtoulW(ptr
, &nextPtr
, 10);
4380 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4382 ERR("unexpected day %s\n", debugstr_w(ptr
));
4386 st
.wDay
= (WORD
)num
;
4388 while (isspaceW(*ptr
))
4391 if (!HTTP_ParseTime(&st
, &ptr
))
4394 while (isspaceW(*ptr
))
4397 num
= strtoulW(ptr
, &nextPtr
, 10);
4398 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4400 ERR("unexpected year %s\n", debugstr_w(ptr
));
4404 st
.wYear
= (WORD
)num
;
4406 while (isspaceW(*ptr
))
4409 /* asctime() doesn't report a timezone, but some web servers do, so accept
4410 * with or without GMT.
4412 if (*ptr
&& strcmpW(ptr
, gmt
))
4414 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4417 return SystemTimeToFileTime(&st
, ft
);
4420 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4422 static const WCHAR gmt
[]= { 'G','M','T',0 };
4423 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4426 SYSTEMTIME st
= { 0 };
4428 ptr
= strchrW(value
, ',');
4431 if (ptr
- value
!= 3)
4433 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4436 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4438 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4439 if (st
.wDayOfWeek
> 6)
4441 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4446 while (isspaceW(*ptr
))
4449 num
= strtoulW(ptr
, &nextPtr
, 10);
4450 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4452 WARN("unexpected day %s\n", debugstr_w(value
));
4456 st
.wDay
= (WORD
)num
;
4458 while (isspaceW(*ptr
))
4461 for (monthPtr
= month
; !isspace(*ptr
) &&
4462 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4466 st
.wMonth
= HTTP_ParseMonth(month
);
4467 if (!st
.wMonth
|| st
.wMonth
> 12)
4469 WARN("unexpected month %s\n", debugstr_w(month
));
4473 while (isspaceW(*ptr
))
4476 num
= strtoulW(ptr
, &nextPtr
, 10);
4477 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4479 ERR("unexpected year %s\n", debugstr_w(value
));
4483 st
.wYear
= (WORD
)num
;
4485 if (!HTTP_ParseTime(&st
, &ptr
))
4488 while (isspaceW(*ptr
))
4491 if (strcmpW(ptr
, gmt
))
4493 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4496 return SystemTimeToFileTime(&st
, ft
);
4499 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4501 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4502 { 'm','o','n','d','a','y',0 },
4503 { 't','u','e','s','d','a','y',0 },
4504 { 'w','e','d','n','e','s','d','a','y',0 },
4505 { 't','h','u','r','s','d','a','y',0 },
4506 { 'f','r','i','d','a','y',0 },
4507 { 's','a','t','u','r','d','a','y',0 }};
4509 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4510 if (!strcmpiW(day
, days
[i
]))
4517 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4519 static const WCHAR gmt
[]= { 'G','M','T',0 };
4520 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4523 SYSTEMTIME st
= { 0 };
4525 ptr
= strchrW(value
, ',');
4528 if (ptr
- value
== 3)
4530 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4532 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4533 if (st
.wDayOfWeek
> 6)
4535 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4539 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4541 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4542 day
[ptr
- value
+ 1] = 0;
4543 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4544 if (st
.wDayOfWeek
> 6)
4546 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4552 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4557 while (isspaceW(*ptr
))
4560 num
= strtoulW(ptr
, &nextPtr
, 10);
4561 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4563 ERR("unexpected day %s\n", debugstr_w(value
));
4567 st
.wDay
= (WORD
)num
;
4571 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4576 for (monthPtr
= month
; *ptr
!= '-' &&
4577 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4581 st
.wMonth
= HTTP_ParseMonth(month
);
4582 if (!st
.wMonth
|| st
.wMonth
> 12)
4584 ERR("unexpected month %s\n", debugstr_w(month
));
4590 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4595 num
= strtoulW(ptr
, &nextPtr
, 10);
4596 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4598 ERR("unexpected year %s\n", debugstr_w(value
));
4602 st
.wYear
= (WORD
)num
;
4604 if (!HTTP_ParseTime(&st
, &ptr
))
4607 while (isspaceW(*ptr
))
4610 if (strcmpW(ptr
, gmt
))
4612 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4615 return SystemTimeToFileTime(&st
, ft
);
4618 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4620 static const WCHAR zero
[] = { '0',0 };
4623 if (!strcmpW(value
, zero
))
4625 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4628 else if (strchrW(value
, ','))
4630 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4633 ret
= HTTP_ParseRfc850Date(value
, ft
);
4635 ERR("unexpected date format %s\n", debugstr_w(value
));
4640 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4642 ERR("unexpected date format %s\n", debugstr_w(value
));
4647 static void HTTP_ProcessExpires(http_request_t
*request
)
4649 BOOL expirationFound
= FALSE
;
4652 EnterCriticalSection( &request
->headers_section
);
4654 /* Look for a Cache-Control header with a max-age directive, as it takes
4655 * precedence over the Expires header.
4657 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4658 if (headerIndex
!= -1)
4660 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4663 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4665 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4670 end
= ptr
+ strlenW(ptr
);
4671 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4675 static const WCHAR max_age
[] = {
4676 'm','a','x','-','a','g','e',0 };
4678 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4683 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4684 if (nextPtr
> equal
+ 1)
4688 NtQuerySystemTime( &ft
);
4689 /* Age is in seconds, FILETIME resolution is in
4690 * 100 nanosecond intervals.
4692 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4693 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4694 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4695 expirationFound
= TRUE
;
4702 while (isspaceW(*ptr
))
4709 if (!expirationFound
)
4711 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4712 if (headerIndex
!= -1)
4714 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4717 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4719 expirationFound
= TRUE
;
4720 request
->expires
= ft
;
4724 if (!expirationFound
)
4728 /* With no known age, default to 10 minutes until expiration. */
4729 NtQuerySystemTime( &t
);
4730 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4731 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4732 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4735 LeaveCriticalSection( &request
->headers_section
);
4738 static void HTTP_ProcessLastModified(http_request_t
*request
)
4742 EnterCriticalSection( &request
->headers_section
);
4744 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4745 if (headerIndex
!= -1)
4747 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4750 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4751 request
->last_modified
= ft
;
4754 LeaveCriticalSection( &request
->headers_section
);
4757 static void http_process_keep_alive(http_request_t
*req
)
4761 EnterCriticalSection( &req
->headers_section
);
4763 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4764 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4765 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4766 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4768 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4770 LeaveCriticalSection( &req
->headers_section
);
4773 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4775 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4776 netconn_t
*netconn
= NULL
;
4779 reset_data_stream(request
);
4781 if (request
->netconn
)
4783 if (is_valid_netconn(request
->netconn
) && NETCON_is_alive(request
->netconn
))
4786 return ERROR_SUCCESS
;
4790 free_netconn(request
->netconn
);
4791 request
->netconn
= NULL
;
4795 res
= HTTP_ResolveName(request
);
4796 if(res
!= ERROR_SUCCESS
)
4799 EnterCriticalSection(&connection_pool_cs
);
4801 while(!list_empty(&request
->server
->conn_pool
)) {
4802 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4803 list_remove(&netconn
->pool_entry
);
4805 if(is_valid_netconn(netconn
) && NETCON_is_alive(netconn
))
4808 TRACE("connection %p closed during idle\n", netconn
);
4809 free_netconn(netconn
);
4813 LeaveCriticalSection(&connection_pool_cs
);
4816 TRACE("<-- reusing %p netconn\n", netconn
);
4817 request
->netconn
= netconn
;
4819 return ERROR_SUCCESS
;
4822 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4823 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4825 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4826 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4827 request
->server
->addr_str
,
4828 strlen(request
->server
->addr_str
)+1);
4830 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4831 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4832 request
->connect_timeout
, &netconn
);
4833 if(res
!= ERROR_SUCCESS
) {
4834 ERR("create_netconn failed: %u\n", res
);
4838 request
->netconn
= netconn
;
4840 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4841 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4842 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4845 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4846 return ERROR_SUCCESS
;
4849 static char *build_ascii_request( const WCHAR
*str
, void *data
, DWORD data_len
, DWORD
*out_len
)
4851 int len
= WideCharToMultiByte( CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
4854 if (!(ret
= heap_alloc( len
+ data_len
))) return NULL
;
4855 WideCharToMultiByte( CP_ACP
, 0, str
, -1, ret
, len
, NULL
, NULL
);
4856 if (data_len
) memcpy( ret
+ len
- 1, data
, data_len
);
4857 *out_len
= len
+ data_len
- 1;
4862 /***********************************************************************
4863 * HTTP_HttpSendRequestW (internal)
4865 * Sends the specified request to the HTTP server
4868 * ERROR_SUCCESS on success
4869 * win32 error code on failure
4872 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4873 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4874 DWORD dwContentLength
, BOOL bEndRequest
)
4876 static const WCHAR szContentLength
[] =
4877 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4878 BOOL redirected
= FALSE
, secure_proxy_connect
= FALSE
, loop_next
;
4879 LPWSTR requestString
= NULL
;
4880 INT responseLen
, cnt
;
4881 WCHAR contentLengthStr
[sizeof szContentLength
/2 /* includes \r\n */ + 20 /* int */ ];
4884 TRACE("--> %p\n", request
);
4886 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4888 /* if the verb is NULL default to GET */
4890 request
->verb
= heap_strdupW(szGET
);
4892 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4894 sprintfW(contentLengthStr
, szContentLength
, dwContentLength
);
4895 HTTP_HttpAddRequestHeadersW(request
, contentLengthStr
, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4896 request
->bytesToWrite
= dwContentLength
;
4898 if (request
->session
->appInfo
->agent
)
4900 WCHAR
*agent_header
;
4901 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4904 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4905 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4906 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4908 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4909 heap_free(agent_header
);
4911 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4913 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4914 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4916 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4918 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4919 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4920 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4923 /* add the headers the caller supplied */
4924 if( lpszHeaders
&& dwHeaderLength
)
4925 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4929 DWORD len
, data_len
= dwOptionalLength
;
4930 BOOL reusing_connection
;
4936 request
->contentLength
= ~0u;
4937 request
->bytesToWrite
= 0;
4940 if (TRACE_ON(wininet
))
4944 EnterCriticalSection( &request
->headers_section
);
4945 host
= HTTP_GetHeader( request
, hostW
);
4946 TRACE("Going to url %s %s\n", debugstr_w(host
->lpszValue
), debugstr_w(request
->path
));
4947 LeaveCriticalSection( &request
->headers_section
);
4950 HTTP_FixURL(request
);
4951 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4953 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
, HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
);
4955 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4956 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4958 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4959 HTTP_InsertCookies(request
);
4961 res
= open_http_connection(request
, &reusing_connection
);
4962 if (res
!= ERROR_SUCCESS
)
4965 if (!reusing_connection
&& (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4967 if (request
->proxy
) secure_proxy_connect
= TRUE
;
4970 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4971 if (res
!= ERROR_SUCCESS
)
4973 WARN("failed to upgrade to secure connection\n");
4974 http_release_netconn(request
, FALSE
);
4979 if (secure_proxy_connect
)
4981 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
4982 const WCHAR
*target
= request
->server
->host_port
;
4983 requestString
= build_request_header(request
, connectW
, target
, g_szHttp1_1
, TRUE
);
4985 else if (request
->proxy
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4987 WCHAR
*url
= build_proxy_path_url(request
);
4988 requestString
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
4992 requestString
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
4994 TRACE("Request header -> %s\n", debugstr_w(requestString
) );
4996 /* send the request as ASCII, tack on the optional data */
4997 if (!lpOptional
|| redirected
|| secure_proxy_connect
)
5000 ascii_req
= build_ascii_request( requestString
, lpOptional
, data_len
, &len
);
5001 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
5003 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5004 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
5006 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
5007 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
5008 heap_free( ascii_req
);
5009 if(res
!= ERROR_SUCCESS
) {
5010 TRACE("send failed: %u\n", res
);
5011 if(!reusing_connection
)
5013 http_release_netconn(request
, FALSE
);
5018 request
->bytesWritten
= data_len
;
5020 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5021 INTERNET_STATUS_REQUEST_SENT
,
5022 &len
, sizeof(DWORD
));
5028 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5029 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5031 if (HTTP_GetResponseHeaders(request
, &responseLen
))
5033 http_release_netconn(request
, FALSE
);
5034 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
5037 /* FIXME: We should know that connection is closed before sending
5038 * headers. Otherwise wrong callbacks are executed */
5039 if(!responseLen
&& reusing_connection
) {
5040 TRACE("Connection closed by server, reconnecting\n");
5041 http_release_netconn(request
, FALSE
);
5046 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5047 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
5050 http_process_keep_alive(request
);
5051 HTTP_ProcessCookies(request
);
5052 HTTP_ProcessExpires(request
);
5053 HTTP_ProcessLastModified(request
);
5055 res
= set_content_length(request
);
5056 if(res
!= ERROR_SUCCESS
)
5058 if(!request
->contentLength
)
5059 http_release_netconn(request
, TRUE
);
5061 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5063 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5064 dwBufferSize
=sizeof(szNewLocation
);
5065 switch(request
->status_code
) {
5066 case HTTP_STATUS_REDIRECT
:
5067 case HTTP_STATUS_MOVED
:
5068 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5069 case HTTP_STATUS_REDIRECT_METHOD
:
5070 if(HTTP_HttpQueryInfoW(request
,HTTP_QUERY_LOCATION
,szNewLocation
,&dwBufferSize
,NULL
) != ERROR_SUCCESS
)
5073 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5074 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5076 heap_free(request
->verb
);
5077 request
->verb
= heap_strdupW(szGET
);
5079 http_release_netconn(request
, drain_content(request
, FALSE
));
5080 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5082 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5083 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5084 res
= HTTP_HandleRedirect(request
, new_url
);
5085 if (res
== ERROR_SUCCESS
)
5087 heap_free(requestString
);
5090 heap_free( new_url
);
5095 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5097 WCHAR szAuthValue
[2048];
5099 if (request
->status_code
== HTTP_STATUS_DENIED
)
5101 WCHAR
*host
= get_host_header( request
);
5103 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5105 if (HTTP_DoAuthorization(request
, szAuthValue
,
5107 request
->session
->userName
,
5108 request
->session
->password
, host
))
5110 heap_free(requestString
);
5111 if(!drain_content(request
, TRUE
)) {
5112 FIXME("Could not drain content\n");
5113 http_release_netconn(request
, FALSE
);
5122 TRACE("Cleaning wrong authorization data\n");
5123 destroy_authinfo(request
->authInfo
);
5124 request
->authInfo
= NULL
;
5127 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5130 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5132 if (HTTP_DoAuthorization(request
, szAuthValue
,
5133 &request
->proxyAuthInfo
,
5134 request
->session
->appInfo
->proxyUsername
,
5135 request
->session
->appInfo
->proxyPassword
,
5138 heap_free(requestString
);
5139 if(!drain_content(request
, TRUE
)) {
5140 FIXME("Could not drain content\n");
5141 http_release_netconn(request
, FALSE
);
5149 TRACE("Cleaning wrong proxy authorization data\n");
5150 destroy_authinfo(request
->proxyAuthInfo
);
5151 request
->proxyAuthInfo
= NULL
;
5155 if (secure_proxy_connect
&& request
->status_code
== HTTP_STATUS_OK
)
5157 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5158 if (res
!= ERROR_SUCCESS
)
5160 WARN("failed to upgrade to secure proxy connection\n");
5161 http_release_netconn( request
, FALSE
);
5164 remove_header(request
, szProxy_Authorization
, TRUE
);
5165 destroy_authinfo(request
->proxyAuthInfo
);
5166 request
->proxyAuthInfo
= NULL
;
5168 secure_proxy_connect
= FALSE
;
5173 res
= ERROR_SUCCESS
;
5178 heap_free(requestString
);
5180 /* TODO: send notification for P3P header */
5182 if(res
== ERROR_SUCCESS
)
5183 create_cache_entry(request
);
5185 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5187 if (res
== ERROR_SUCCESS
) {
5188 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5189 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5191 send_request_complete(request
,
5192 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5194 send_request_complete(request
, 0, res
);
5210 } send_request_task_t
;
5212 /***********************************************************************
5214 * Helper functions for the HttpSendRequest(Ex) functions
5217 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5219 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5220 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5222 TRACE("%p\n", request
);
5224 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5225 task
->optional_len
, task
->content_len
, task
->end_request
);
5227 heap_free(task
->headers
);
5231 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5235 DWORD res
= ERROR_SUCCESS
;
5237 if(!is_valid_netconn(request
->netconn
)) {
5238 WARN("Not connected\n");
5239 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5240 return ERROR_INTERNET_OPERATION_CANCELLED
;
5243 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5244 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5246 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5247 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5249 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5250 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5252 /* process cookies here. Is this right? */
5253 http_process_keep_alive(request
);
5254 HTTP_ProcessCookies(request
);
5255 HTTP_ProcessExpires(request
);
5256 HTTP_ProcessLastModified(request
);
5258 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5259 if(!request
->contentLength
)
5260 http_release_netconn(request
, TRUE
);
5263 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5265 switch(request
->status_code
) {
5266 case HTTP_STATUS_REDIRECT
:
5267 case HTTP_STATUS_MOVED
:
5268 case HTTP_STATUS_REDIRECT_METHOD
:
5269 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5270 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5271 dwBufferSize
=sizeof(szNewLocation
);
5272 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, szNewLocation
, &dwBufferSize
, NULL
) != ERROR_SUCCESS
)
5275 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5276 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5278 heap_free(request
->verb
);
5279 request
->verb
= heap_strdupW(szGET
);
5281 http_release_netconn(request
, drain_content(request
, FALSE
));
5282 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5284 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5285 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5286 res
= HTTP_HandleRedirect(request
, new_url
);
5287 if (res
== ERROR_SUCCESS
)
5288 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5289 heap_free( new_url
);
5295 if(res
== ERROR_SUCCESS
)
5296 create_cache_entry(request
);
5298 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5299 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5301 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5306 /***********************************************************************
5307 * HttpEndRequestA (WININET.@)
5309 * Ends an HTTP request that was started by HttpSendRequestEx
5312 * TRUE if successful
5316 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5317 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5319 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5323 SetLastError(ERROR_INVALID_PARAMETER
);
5327 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5334 } end_request_task_t
;
5336 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5338 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5339 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5343 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5346 /***********************************************************************
5347 * HttpEndRequestW (WININET.@)
5349 * Ends an HTTP request that was started by HttpSendRequestEx
5352 * TRUE if successful
5356 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5357 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5359 http_request_t
*request
;
5362 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5366 SetLastError(ERROR_INVALID_PARAMETER
);
5370 request
= (http_request_t
*) get_handle_object( hRequest
);
5372 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5374 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5376 WININET_Release( &request
->hdr
);
5379 request
->hdr
.dwFlags
|= dwFlags
;
5381 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5383 end_request_task_t
*task
;
5385 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5386 task
->flags
= dwFlags
;
5387 task
->context
= dwContext
;
5389 INTERNET_AsyncCall(&task
->hdr
);
5390 res
= ERROR_IO_PENDING
;
5393 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5395 WININET_Release( &request
->hdr
);
5396 TRACE("%u <--\n", res
);
5397 if(res
!= ERROR_SUCCESS
)
5399 return res
== ERROR_SUCCESS
;
5402 /***********************************************************************
5403 * HttpSendRequestExA (WININET.@)
5405 * Sends the specified request to the HTTP server and allows chunked
5410 * Failure: FALSE, call GetLastError() for more information.
5412 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5413 LPINTERNET_BUFFERSA lpBuffersIn
,
5414 LPINTERNET_BUFFERSA lpBuffersOut
,
5415 DWORD dwFlags
, DWORD_PTR dwContext
)
5417 INTERNET_BUFFERSW BuffersInW
;
5420 LPWSTR header
= NULL
;
5422 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5423 lpBuffersOut
, dwFlags
, dwContext
);
5427 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5428 if (lpBuffersIn
->lpcszHeader
)
5430 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5431 lpBuffersIn
->dwHeadersLength
,0,0);
5432 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5433 if (!(BuffersInW
.lpcszHeader
= header
))
5435 SetLastError(ERROR_OUTOFMEMORY
);
5438 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5439 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5443 BuffersInW
.lpcszHeader
= NULL
;
5444 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5445 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5446 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5447 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5448 BuffersInW
.Next
= NULL
;
5451 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5457 /***********************************************************************
5458 * HttpSendRequestExW (WININET.@)
5460 * Sends the specified request to the HTTP server and allows chunked
5465 * Failure: FALSE, call GetLastError() for more information.
5467 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5468 LPINTERNET_BUFFERSW lpBuffersIn
,
5469 LPINTERNET_BUFFERSW lpBuffersOut
,
5470 DWORD dwFlags
, DWORD_PTR dwContext
)
5472 http_request_t
*request
;
5473 http_session_t
*session
;
5477 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5478 lpBuffersOut
, dwFlags
, dwContext
);
5480 request
= (http_request_t
*) get_handle_object( hRequest
);
5482 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5484 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5488 session
= request
->session
;
5489 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5490 hIC
= session
->appInfo
;
5491 assert(hIC
->hdr
.htype
== WH_HINIT
);
5493 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5495 send_request_task_t
*task
;
5497 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5502 if (lpBuffersIn
->lpcszHeader
)
5504 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5505 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5507 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5509 task
->headers
= heap_alloc(size
);
5510 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5512 else task
->headers
= NULL
;
5514 task
->headers_len
= size
/ sizeof(WCHAR
);
5515 task
->optional
= lpBuffersIn
->lpvBuffer
;
5516 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5517 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5521 task
->headers
= NULL
;
5522 task
->headers_len
= 0;
5523 task
->optional
= NULL
;
5524 task
->optional_len
= 0;
5525 task
->content_len
= 0;
5528 task
->end_request
= FALSE
;
5530 INTERNET_AsyncCall(&task
->hdr
);
5531 res
= ERROR_IO_PENDING
;
5536 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5537 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5538 lpBuffersIn
->dwBufferTotal
, FALSE
);
5540 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5545 WININET_Release( &request
->hdr
);
5549 return res
== ERROR_SUCCESS
;
5552 /***********************************************************************
5553 * HttpSendRequestW (WININET.@)
5555 * Sends the specified request to the HTTP server
5562 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5563 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5565 http_request_t
*request
;
5566 http_session_t
*session
= NULL
;
5567 appinfo_t
*hIC
= NULL
;
5568 DWORD res
= ERROR_SUCCESS
;
5570 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5571 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5573 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5574 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5576 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5580 session
= request
->session
;
5581 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5583 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5587 hIC
= session
->appInfo
;
5588 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5590 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5594 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5596 send_request_task_t
*task
;
5598 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5603 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5604 else size
= dwHeaderLength
* sizeof(WCHAR
);
5606 task
->headers
= heap_alloc(size
);
5607 memcpy(task
->headers
, lpszHeaders
, size
);
5610 task
->headers
= NULL
;
5611 task
->headers_len
= dwHeaderLength
;
5612 task
->optional
= lpOptional
;
5613 task
->optional_len
= dwOptionalLength
;
5614 task
->content_len
= dwOptionalLength
;
5615 task
->end_request
= TRUE
;
5617 INTERNET_AsyncCall(&task
->hdr
);
5618 res
= ERROR_IO_PENDING
;
5622 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5623 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5624 dwOptionalLength
, TRUE
);
5628 WININET_Release( &request
->hdr
);
5631 return res
== ERROR_SUCCESS
;
5634 /***********************************************************************
5635 * HttpSendRequestA (WININET.@)
5637 * Sends the specified request to the HTTP server
5644 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5645 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5648 LPWSTR szHeaders
=NULL
;
5649 DWORD nLen
=dwHeaderLength
;
5650 if(lpszHeaders
!=NULL
)
5652 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5653 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5654 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5656 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5657 heap_free(szHeaders
);
5661 /***********************************************************************
5662 * HTTPSESSION_Destroy (internal)
5664 * Deallocate session handle
5667 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5669 http_session_t
*session
= (http_session_t
*) hdr
;
5671 TRACE("%p\n", session
);
5673 WININET_Release(&session
->appInfo
->hdr
);
5675 heap_free(session
->hostName
);
5676 heap_free(session
->password
);
5677 heap_free(session
->userName
);
5680 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5682 http_session_t
*ses
= (http_session_t
*)hdr
;
5685 case INTERNET_OPTION_HANDLE_TYPE
:
5686 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5688 if (*size
< sizeof(ULONG
))
5689 return ERROR_INSUFFICIENT_BUFFER
;
5691 *size
= sizeof(DWORD
);
5692 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5693 return ERROR_SUCCESS
;
5694 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5695 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5697 if (*size
< sizeof(DWORD
))
5698 return ERROR_INSUFFICIENT_BUFFER
;
5700 *size
= sizeof(DWORD
);
5701 *(DWORD
*)buffer
= ses
->connect_timeout
;
5702 return ERROR_SUCCESS
;
5704 case INTERNET_OPTION_SEND_TIMEOUT
:
5705 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5707 if (*size
< sizeof(DWORD
))
5708 return ERROR_INSUFFICIENT_BUFFER
;
5710 *size
= sizeof(DWORD
);
5711 *(DWORD
*)buffer
= ses
->send_timeout
;
5712 return ERROR_SUCCESS
;
5714 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5715 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5717 if (*size
< sizeof(DWORD
))
5718 return ERROR_INSUFFICIENT_BUFFER
;
5720 *size
= sizeof(DWORD
);
5721 *(DWORD
*)buffer
= ses
->receive_timeout
;
5722 return ERROR_SUCCESS
;
5725 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5728 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5730 http_session_t
*ses
= (http_session_t
*)hdr
;
5733 case INTERNET_OPTION_USERNAME
:
5735 heap_free(ses
->userName
);
5736 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5737 return ERROR_SUCCESS
;
5739 case INTERNET_OPTION_PASSWORD
:
5741 heap_free(ses
->password
);
5742 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5743 return ERROR_SUCCESS
;
5745 case INTERNET_OPTION_PROXY_USERNAME
:
5747 heap_free(ses
->appInfo
->proxyUsername
);
5748 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5749 return ERROR_SUCCESS
;
5751 case INTERNET_OPTION_PROXY_PASSWORD
:
5753 heap_free(ses
->appInfo
->proxyPassword
);
5754 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5755 return ERROR_SUCCESS
;
5757 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5759 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5760 ses
->connect_timeout
= *(DWORD
*)buffer
;
5761 return ERROR_SUCCESS
;
5763 case INTERNET_OPTION_SEND_TIMEOUT
:
5765 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5766 ses
->send_timeout
= *(DWORD
*)buffer
;
5767 return ERROR_SUCCESS
;
5769 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5771 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5772 ses
->receive_timeout
= *(DWORD
*)buffer
;
5773 return ERROR_SUCCESS
;
5778 return INET_SetOption(hdr
, option
, buffer
, size
);
5781 static const object_vtbl_t HTTPSESSIONVtbl
= {
5782 HTTPSESSION_Destroy
,
5784 HTTPSESSION_QueryOption
,
5785 HTTPSESSION_SetOption
,
5794 /***********************************************************************
5795 * HTTP_Connect (internal)
5797 * Create http session handle
5800 * HINTERNET a session handle on success
5804 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5805 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5806 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5807 DWORD dwInternalFlags
, HINTERNET
*ret
)
5809 http_session_t
*session
= NULL
;
5813 if (!lpszServerName
|| !lpszServerName
[0])
5814 return ERROR_INVALID_PARAMETER
;
5816 assert( hIC
->hdr
.htype
== WH_HINIT
);
5818 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5820 return ERROR_OUTOFMEMORY
;
5823 * According to my tests. The name is not resolved until a request is sent
5826 session
->hdr
.htype
= WH_HHTTPSESSION
;
5827 session
->hdr
.dwFlags
= dwFlags
;
5828 session
->hdr
.dwContext
= dwContext
;
5829 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5831 WININET_AddRef( &hIC
->hdr
);
5832 session
->appInfo
= hIC
;
5833 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5835 session
->hostName
= heap_strdupW(lpszServerName
);
5836 if (lpszUserName
&& lpszUserName
[0])
5837 session
->userName
= heap_strdupW(lpszUserName
);
5838 if (lpszPassword
&& lpszPassword
[0])
5839 session
->password
= heap_strdupW(lpszPassword
);
5840 session
->hostPort
= serverPort
;
5841 session
->connect_timeout
= hIC
->connect_timeout
;
5842 session
->send_timeout
= INFINITE
;
5843 session
->receive_timeout
= INFINITE
;
5845 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5846 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5848 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5849 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5854 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5858 TRACE("%p --> %p\n", hIC
, session
);
5860 *ret
= session
->hdr
.hInternet
;
5861 return ERROR_SUCCESS
;
5864 /***********************************************************************
5865 * HTTP_clear_response_headers (internal)
5867 * clear out any old response headers
5869 static void HTTP_clear_response_headers( http_request_t
*request
)
5873 EnterCriticalSection( &request
->headers_section
);
5875 for( i
=0; i
<request
->nCustHeaders
; i
++)
5877 if( !request
->custHeaders
[i
].lpszField
)
5879 if( !request
->custHeaders
[i
].lpszValue
)
5881 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5883 HTTP_DeleteCustomHeader( request
, i
);
5887 LeaveCriticalSection( &request
->headers_section
);
5890 /***********************************************************************
5891 * HTTP_GetResponseHeaders (internal)
5893 * Read server response
5900 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5903 WCHAR buffer
[MAX_REPLY_LEN
];
5904 DWORD buflen
= MAX_REPLY_LEN
;
5906 char bufferA
[MAX_REPLY_LEN
];
5907 LPWSTR status_code
= NULL
, status_text
= NULL
;
5908 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5909 BOOL codeHundred
= FALSE
;
5913 if(!is_valid_netconn(request
->netconn
))
5916 /* clear old response headers (eg. from a redirect response) */
5917 HTTP_clear_response_headers( request
);
5919 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5922 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5924 buflen
= MAX_REPLY_LEN
;
5925 if ((res
= read_line(request
, bufferA
, &buflen
)))
5928 if (!buflen
) goto lend
;
5931 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5932 /* check is this a status code line? */
5933 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5935 /* split the version from the status code */
5936 status_code
= strchrW( buffer
, ' ' );
5941 /* split the status code from the status text */
5942 status_text
= strchrW( status_code
, ' ' );
5946 request
->status_code
= atoiW(status_code
);
5948 TRACE("version [%s] status code [%s] status text [%s]\n",
5949 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5951 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5953 else if (!codeHundred
)
5955 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5957 heap_free(request
->version
);
5958 heap_free(request
->statusText
);
5960 request
->status_code
= HTTP_STATUS_OK
;
5961 request
->version
= heap_strdupW(g_szHttp1_0
);
5962 request
->statusText
= heap_strdupW(szOK
);
5966 } while (codeHundred
);
5968 /* Add status code */
5969 HTTP_ProcessHeader(request
, szStatus
, status_code
,
5970 HTTP_ADDHDR_FLAG_REPLACE
);
5972 heap_free(request
->version
);
5973 heap_free(request
->statusText
);
5975 request
->version
= heap_strdupW(buffer
);
5976 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
5978 /* Restore the spaces */
5979 *(status_code
-1) = ' ';
5981 *(status_text
-1) = ' ';
5983 /* Parse each response line */
5986 buflen
= MAX_REPLY_LEN
;
5987 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
5989 LPWSTR
* pFieldAndValue
;
5991 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
5993 if (!bufferA
[0]) break;
5994 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5996 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
5999 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
6000 HTTP_ADDREQ_FLAG_ADD
);
6001 HTTP_FreeTokens(pFieldAndValue
);
6012 res
= ERROR_SUCCESS
;
6021 /***********************************************************************
6022 * HTTP_InterpretHttpHeader (internal)
6024 * Parse server response
6028 * Pointer to array of field, value, NULL on success.
6031 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
6033 LPWSTR
* pTokenPair
;
6037 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
6039 pszColon
= strchrW(buffer
, ':');
6040 /* must have two tokens */
6043 HTTP_FreeTokens(pTokenPair
);
6045 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
6049 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
6052 HTTP_FreeTokens(pTokenPair
);
6055 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
6056 pTokenPair
[0][pszColon
- buffer
] = '\0';
6060 len
= strlenW(pszColon
);
6061 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
6064 HTTP_FreeTokens(pTokenPair
);
6067 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
6069 strip_spaces(pTokenPair
[0]);
6070 strip_spaces(pTokenPair
[1]);
6072 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
6076 /***********************************************************************
6077 * HTTP_ProcessHeader (internal)
6079 * Stuff header into header tables according to <dwModifier>
6083 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6085 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6087 LPHTTPHEADERW lphttpHdr
= NULL
;
6089 BOOL request_only
= dwModifier
& HTTP_ADDHDR_FLAG_REQ
;
6090 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6092 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6094 EnterCriticalSection( &request
->headers_section
);
6096 /* REPLACE wins out over ADD */
6097 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6098 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6100 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6103 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6107 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6109 LeaveCriticalSection( &request
->headers_section
);
6110 return ERROR_HTTP_INVALID_HEADER
;
6112 lphttpHdr
= &request
->custHeaders
[index
];
6118 hdr
.lpszField
= (LPWSTR
)field
;
6119 hdr
.lpszValue
= (LPWSTR
)value
;
6120 hdr
.wFlags
= hdr
.wCount
= 0;
6122 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6123 hdr
.wFlags
|= HDR_ISREQUEST
;
6125 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6126 LeaveCriticalSection( &request
->headers_section
);
6129 /* no value to delete */
6132 LeaveCriticalSection( &request
->headers_section
);
6133 return ERROR_SUCCESS
;
6136 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6137 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6139 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6141 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6143 HTTP_DeleteCustomHeader( request
, index
);
6145 if (value
&& value
[0])
6149 hdr
.lpszField
= (LPWSTR
)field
;
6150 hdr
.lpszValue
= (LPWSTR
)value
;
6151 hdr
.wFlags
= hdr
.wCount
= 0;
6153 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6154 hdr
.wFlags
|= HDR_ISREQUEST
;
6156 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6157 LeaveCriticalSection( &request
->headers_section
);
6161 LeaveCriticalSection( &request
->headers_section
);
6162 return ERROR_SUCCESS
;
6164 else if (dwModifier
& COALESCEFLAGS
)
6169 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6170 INT valuelen
= strlenW(value
);
6172 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6175 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6177 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6180 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6183 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6185 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6188 lphttpHdr
->lpszValue
= lpsztmp
;
6189 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6192 lphttpHdr
->lpszValue
[origlen
] = ch
;
6194 lphttpHdr
->lpszValue
[origlen
] = ' ';
6198 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6199 lphttpHdr
->lpszValue
[len
] = '\0';
6200 res
= ERROR_SUCCESS
;
6204 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6205 res
= ERROR_OUTOFMEMORY
;
6208 TRACE("<-- %d\n", res
);
6209 LeaveCriticalSection( &request
->headers_section
);
6213 /***********************************************************************
6214 * HTTP_GetCustomHeaderIndex (internal)
6216 * Return index of custom header from header array
6217 * Headers section must be held
6219 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6220 int requested_index
, BOOL request_only
)
6224 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6226 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6228 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6231 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6234 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6237 if (requested_index
== 0)
6242 if (index
>= request
->nCustHeaders
)
6245 TRACE("Return: %d\n", index
);
6250 /***********************************************************************
6251 * HTTP_InsertCustomHeader (internal)
6253 * Insert header into array
6254 * Headers section must be held
6256 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6259 LPHTTPHEADERW lph
= NULL
;
6261 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6262 count
= request
->nCustHeaders
+ 1;
6264 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6266 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6269 return ERROR_OUTOFMEMORY
;
6271 request
->custHeaders
= lph
;
6272 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6273 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6274 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6275 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6276 request
->nCustHeaders
++;
6278 return ERROR_SUCCESS
;
6282 /***********************************************************************
6283 * HTTP_DeleteCustomHeader (internal)
6285 * Delete header from array
6286 * If this function is called, the index may change.
6287 * Headers section must be held
6289 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6291 if( request
->nCustHeaders
<= 0 )
6293 if( index
>= request
->nCustHeaders
)
6295 request
->nCustHeaders
--;
6297 heap_free(request
->custHeaders
[index
].lpszField
);
6298 heap_free(request
->custHeaders
[index
].lpszValue
);
6300 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6301 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6302 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6308 /***********************************************************************
6309 * IsHostInProxyBypassList (@)
6314 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6316 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);