2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
51 #define NO_SHLWAPI_STREAM
52 #define NO_SHLWAPI_REG
53 #define NO_SHLWAPI_STRFCNS
54 #define NO_SHLWAPI_GDI
61 #include "wine/debug.h"
62 #include "wine/exception.h"
63 #include "wine/unicode.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
67 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
68 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
69 static const WCHAR szOK
[] = {'O','K',0};
70 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
75 static const WCHAR szGET
[] = { 'G','E','T', 0 };
76 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
78 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
79 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
80 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
81 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
82 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
83 static const WCHAR szAge
[] = { 'A','g','e',0 };
84 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
85 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
86 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
87 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
88 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
89 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
90 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
91 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
92 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
93 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
94 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
95 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
96 static const WCHAR szContent_Transfer_Encoding
[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
97 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
98 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
99 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
100 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
101 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
102 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
103 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
104 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
106 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
107 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
108 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
109 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
110 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
111 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
112 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
113 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
114 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
115 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
116 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
117 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
118 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
119 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
120 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
121 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
122 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
123 static const WCHAR szUnless_Modified_Since
[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
124 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
125 static const WCHAR szURI
[] = { 'U','R','I',0 };
126 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
127 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
128 static const WCHAR szVia
[] = { 'V','i','a',0 };
129 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
130 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
132 static const WCHAR emptyW
[] = {0};
134 #define HTTP_REFERER szReferer
135 #define HTTP_ACCEPT szAccept
136 #define HTTP_USERAGENT szUser_Agent
138 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
139 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
140 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
141 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
142 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
143 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
144 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
146 #define COLLECT_TIME 60000
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 UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
207 static DWORD
drain_content(http_request_t
*,BOOL
);
209 static CRITICAL_SECTION connection_pool_cs
;
210 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
212 0, 0, &connection_pool_cs
,
213 { &connection_pool_debug
.ProcessLocksList
, &connection_pool_debug
.ProcessLocksList
},
214 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
216 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
218 static struct list connection_pool
= LIST_INIT(connection_pool
);
219 static BOOL collector_running
;
221 void server_addref(server_t
*server
)
223 InterlockedIncrement(&server
->ref
);
226 void server_release(server_t
*server
)
228 if(InterlockedDecrement(&server
->ref
))
231 list_remove(&server
->entry
);
233 if(server
->cert_chain
)
234 CertFreeCertificateChain(server
->cert_chain
);
235 heap_free(server
->name
);
236 heap_free(server
->scheme_host_port
);
240 static BOOL
process_host_port(server_t
*server
)
246 static const WCHAR httpW
[] = {'h','t','t','p',0};
247 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
248 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
250 name_len
= strlenW(server
->name
);
251 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
255 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
256 server
->scheme_host_port
= buf
;
258 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
262 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
263 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
267 server_t
*get_server(substr_t name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
269 server_t
*iter
, *server
= NULL
;
271 EnterCriticalSection(&connection_pool_cs
);
273 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
274 if(iter
->port
== port
&& name
.len
== strlenW(iter
->name
) && !strncmpiW(iter
->name
, name
.str
, name
.len
)
275 && iter
->is_https
== is_https
) {
277 server_addref(server
);
282 if(!server
&& do_create
) {
283 server
= heap_alloc_zero(sizeof(*server
));
285 server
->ref
= 2; /* list reference and return */
287 server
->is_https
= is_https
;
288 list_init(&server
->conn_pool
);
289 server
->name
= heap_strndupW(name
.str
, name
.len
);
290 if(server
->name
&& process_host_port(server
)) {
291 list_add_head(&connection_pool
, &server
->entry
);
299 LeaveCriticalSection(&connection_pool_cs
);
304 BOOL
collect_connections(collect_type_t collect_type
)
306 netconn_t
*netconn
, *netconn_safe
;
307 server_t
*server
, *server_safe
;
308 BOOL remaining
= FALSE
;
311 now
= GetTickCount64();
313 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
314 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
315 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
316 TRACE("freeing %p\n", netconn
);
317 list_remove(&netconn
->pool_entry
);
318 free_netconn(netconn
);
324 if(collect_type
== COLLECT_CLEANUP
) {
325 list_remove(&server
->entry
);
326 list_init(&server
->entry
);
327 server_release(server
);
334 static DWORD WINAPI
collect_connections_proc(void *arg
)
336 BOOL remaining_conns
;
339 /* FIXME: Use more sophisticated method */
342 EnterCriticalSection(&connection_pool_cs
);
344 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
346 collector_running
= FALSE
;
348 LeaveCriticalSection(&connection_pool_cs
);
349 }while(remaining_conns
);
351 FreeLibraryAndExitThread(WININET_hModule
, 0);
354 /***********************************************************************
355 * HTTP_GetHeader (internal)
357 * Headers section must be held
359 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
362 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
363 if (HeaderIndex
== -1)
366 return &req
->custHeaders
[HeaderIndex
];
369 static WCHAR
*get_host_header( http_request_t
*req
)
374 EnterCriticalSection( &req
->headers_section
);
375 if ((header
= HTTP_GetHeader( req
, hostW
))) ret
= heap_strdupW( header
->lpszValue
);
376 else ret
= heap_strdupW( req
->server
->canon_host_port
);
377 LeaveCriticalSection( &req
->headers_section
);
381 struct data_stream_vtbl_t
{
382 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
383 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,BOOL
);
384 DWORD (*drain_content
)(data_stream_t
*,http_request_t
*,BOOL
);
385 void (*destroy
)(data_stream_t
*);
389 data_stream_t data_stream
;
391 BYTE buf
[READ_BUFFER_SIZE
];
397 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
,
398 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
,
399 CHUNKED_STREAM_STATE_READING_CHUNK
,
400 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
,
401 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
,
402 CHUNKED_STREAM_STATE_END_OF_STREAM
,
403 CHUNKED_STREAM_STATE_ERROR
407 static inline void destroy_data_stream(data_stream_t
*stream
)
409 stream
->vtbl
->destroy(stream
);
412 static void reset_data_stream(http_request_t
*req
)
414 destroy_data_stream(req
->data_stream
);
415 req
->data_stream
= &req
->netconn_stream
.data_stream
;
416 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
417 req
->read_gzip
= FALSE
;
420 static void remove_header( http_request_t
*request
, const WCHAR
*str
, BOOL from_request
)
423 EnterCriticalSection( &request
->headers_section
);
424 index
= HTTP_GetCustomHeaderIndex( request
, str
, 0, from_request
);
425 if (index
!= -1) HTTP_DeleteCustomHeader( request
, index
);
426 LeaveCriticalSection( &request
->headers_section
);
432 data_stream_t stream
;
433 data_stream_t
*parent_stream
;
435 BYTE buf
[READ_BUFFER_SIZE
];
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
, BOOL allow_blocking
)
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 %x)\n", size
, allow_blocking
);
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
, allow_blocking
);
468 if(res
!= ERROR_SUCCESS
)
471 gzip_stream
->buf_size
+= current_read
;
473 WARN("unexpected end of data\n");
474 gzip_stream
->end_of_data
= TRUE
;
479 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
480 zstream
->avail_in
= gzip_stream
->buf_size
;
481 zstream
->next_out
= buf
+ret_read
;
482 zstream
->avail_out
= size
;
483 zres
= inflate(&gzip_stream
->zstream
, 0);
484 current_read
= size
- zstream
->avail_out
;
485 size
-= current_read
;
486 ret_read
+= current_read
;
487 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
488 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
489 if(zres
== Z_STREAM_END
) {
490 TRACE("end of data\n");
491 gzip_stream
->end_of_data
= TRUE
;
493 }else if(zres
!= Z_OK
) {
494 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
496 res
= ERROR_INTERNET_DECODING_FAILED
;
501 allow_blocking
= FALSE
;
504 TRACE("read %u bytes\n", ret_read
);
511 static DWORD
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
, BOOL allow_blocking
)
513 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
514 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
, allow_blocking
);
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
= {
535 static voidpf
wininet_zalloc(voidpf opaque
, uInt items
, uInt size
)
537 return heap_alloc(items
*size
);
540 static void wininet_zfree(voidpf opaque
, voidpf address
)
545 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
547 gzip_stream_t
*gzip_stream
;
550 gzip_stream
= heap_alloc_zero(sizeof(gzip_stream_t
));
552 return ERROR_OUTOFMEMORY
;
554 gzip_stream
->stream
.vtbl
= &gzip_stream_vtbl
;
555 gzip_stream
->zstream
.zalloc
= wininet_zalloc
;
556 gzip_stream
->zstream
.zfree
= wininet_zfree
;
558 zres
= inflateInit2(&gzip_stream
->zstream
, is_gzip
? 0x1f : -15);
560 ERR("inflateInit failed: %d\n", zres
);
561 heap_free(gzip_stream
);
562 return ERROR_OUTOFMEMORY
;
565 remove_header(req
, szContent_Length
, FALSE
);
568 memcpy(gzip_stream
->buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
569 gzip_stream
->buf_size
= req
->read_size
;
570 req
->read_pos
= req
->read_size
= 0;
573 req
->read_gzip
= TRUE
;
574 gzip_stream
->parent_stream
= req
->data_stream
;
575 req
->data_stream
= &gzip_stream
->stream
;
576 return ERROR_SUCCESS
;
581 static DWORD
init_gzip_stream(http_request_t
*req
, BOOL is_gzip
)
583 ERR("gzip stream not supported, missing zlib.\n");
584 return ERROR_SUCCESS
;
589 /***********************************************************************
590 * HTTP_FreeTokens (internal)
592 * Frees table of pointers.
594 static void HTTP_FreeTokens(LPWSTR
* token_array
)
597 for (i
= 0; token_array
[i
]; i
++) heap_free(token_array
[i
]);
598 heap_free(token_array
);
601 static void HTTP_FixURL(http_request_t
*request
)
603 static const WCHAR szSlash
[] = { '/',0 };
604 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/', 0 };
606 /* If we don't have a path we set it to root */
607 if (NULL
== request
->path
)
608 request
->path
= heap_strdupW(szSlash
);
609 else /* remove \r and \n*/
611 int nLen
= strlenW(request
->path
);
612 while ((nLen
>0 ) && ((request
->path
[nLen
-1] == '\r')||(request
->path
[nLen
-1] == '\n')))
615 request
->path
[nLen
]='\0';
617 /* Replace '\' with '/' */
620 if (request
->path
[nLen
] == '\\') request
->path
[nLen
]='/';
624 if(CSTR_EQUAL
!= CompareStringW( LOCALE_INVARIANT
, NORM_IGNORECASE
,
625 request
->path
, strlenW(request
->path
), szHttp
, strlenW(szHttp
) )
626 && request
->path
[0] != '/') /* not an absolute path ?? --> fix it !! */
628 WCHAR
*fixurl
= heap_alloc((strlenW(request
->path
) + 2)*sizeof(WCHAR
));
630 strcpyW(fixurl
+ 1, request
->path
);
631 heap_free( request
->path
);
632 request
->path
= fixurl
;
636 static WCHAR
* build_request_header(http_request_t
*request
, const WCHAR
*verb
,
637 const WCHAR
*path
, const WCHAR
*version
, BOOL use_cr
)
639 static const WCHAR szSpace
[] = {' ',0};
640 static const WCHAR szColon
[] = {':',' ',0};
641 static const WCHAR szCr
[] = {'\r',0};
642 static const WCHAR szLf
[] = {'\n',0};
643 LPWSTR requestString
;
648 EnterCriticalSection( &request
->headers_section
);
650 /* allocate space for an array of all the string pointers to be added */
651 len
= request
->nCustHeaders
* 5 + 10;
652 if (!(req
= heap_alloc( len
* sizeof(const WCHAR
*) )))
654 LeaveCriticalSection( &request
->headers_section
);
658 /* add the verb, path and HTTP version string */
669 /* Append custom request headers */
670 for (i
= 0; i
< request
->nCustHeaders
; i
++)
672 if (request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
674 req
[n
++] = request
->custHeaders
[i
].lpszField
;
676 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
681 TRACE("Adding custom header %s (%s)\n",
682 debugstr_w(request
->custHeaders
[i
].lpszField
),
683 debugstr_w(request
->custHeaders
[i
].lpszValue
));
691 requestString
= HTTP_build_req( req
, 4 );
693 LeaveCriticalSection( &request
->headers_section
);
694 return requestString
;
697 static WCHAR
* build_response_header(http_request_t
*request
, BOOL use_cr
)
699 static const WCHAR colonW
[] = { ':',' ',0 };
700 static const WCHAR crW
[] = { '\r',0 };
701 static const WCHAR lfW
[] = { '\n',0 };
702 static const WCHAR status_fmt
[] = { ' ','%','u',' ',0 };
707 EnterCriticalSection( &request
->headers_section
);
709 if (!(req
= heap_alloc( (request
->nCustHeaders
* 5 + 8) * sizeof(WCHAR
*) )))
711 LeaveCriticalSection( &request
->headers_section
);
715 if (request
->status_code
)
717 req
[n
++] = request
->version
;
718 sprintfW(buf
, status_fmt
, request
->status_code
);
720 req
[n
++] = request
->statusText
;
726 for(i
= 0; i
< request
->nCustHeaders
; i
++)
728 if(!(request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
729 && strcmpW(request
->custHeaders
[i
].lpszField
, szStatus
))
731 req
[n
++] = request
->custHeaders
[i
].lpszField
;
733 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
738 TRACE("Adding custom header %s (%s)\n",
739 debugstr_w(request
->custHeaders
[i
].lpszField
),
740 debugstr_w(request
->custHeaders
[i
].lpszValue
));
748 ret
= HTTP_build_req(req
, 0);
750 LeaveCriticalSection( &request
->headers_section
);
754 static void HTTP_ProcessCookies( http_request_t
*request
)
758 LPHTTPHEADERW setCookieHeader
;
760 if(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
)
763 EnterCriticalSection( &request
->headers_section
);
765 while((HeaderIndex
= HTTP_GetCustomHeaderIndex(request
, szSet_Cookie
, numCookies
++, FALSE
)) != -1)
770 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
772 if (!setCookieHeader
->lpszValue
)
775 data
= strchrW(setCookieHeader
->lpszValue
, '=');
779 name
= substr(setCookieHeader
->lpszValue
, data
- setCookieHeader
->lpszValue
);
781 set_cookie(substrz(request
->server
->name
), substrz(request
->path
), name
, substrz(data
), INTERNET_COOKIE_HTTPONLY
);
784 LeaveCriticalSection( &request
->headers_section
);
787 static void strip_spaces(LPWSTR start
)
796 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
798 end
= start
+ strlenW(start
) - 1;
799 while (end
>= start
&& *end
== ' ')
806 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
808 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
809 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
811 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAY_SIZE(szBasic
)) &&
812 ((pszAuthValue
[ARRAY_SIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAY_SIZE(szBasic
)]);
813 if (is_basic
&& pszRealm
)
816 LPCWSTR ptr
= &pszAuthValue
[ARRAY_SIZE(szBasic
)];
820 token
= strchrW(ptr
,'=');
824 while (*realm
== ' ')
826 if(!strncmpiW(realm
, szRealm
, ARRAY_SIZE(szRealm
)) &&
827 (realm
[ARRAY_SIZE(szRealm
)] == ' ' || realm
[ARRAY_SIZE(szRealm
)] == '='))
830 while (*token
== ' ')
834 *pszRealm
= heap_strdupW(token
);
835 strip_spaces(*pszRealm
);
842 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
844 if (!authinfo
) return;
846 if (SecIsValidHandle(&authinfo
->ctx
))
847 DeleteSecurityContext(&authinfo
->ctx
);
848 if (SecIsValidHandle(&authinfo
->cred
))
849 FreeCredentialsHandle(&authinfo
->cred
);
851 heap_free(authinfo
->auth_data
);
852 heap_free(authinfo
->scheme
);
856 static UINT
retrieve_cached_basic_authorization(const WCHAR
*host
, const WCHAR
*realm
, char **auth_data
)
858 basicAuthorizationData
*ad
;
861 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
863 EnterCriticalSection(&authcache_cs
);
864 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
866 if (!strcmpiW(host
, ad
->host
) && (!realm
|| !strcmpW(realm
, ad
->realm
)))
868 TRACE("Authorization found in cache\n");
869 *auth_data
= heap_alloc(ad
->authorizationLen
);
870 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
871 rc
= ad
->authorizationLen
;
875 LeaveCriticalSection(&authcache_cs
);
879 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
882 basicAuthorizationData
* ad
= NULL
;
884 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
886 EnterCriticalSection(&authcache_cs
);
887 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
889 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
890 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
899 TRACE("Found match in cache, replacing\n");
900 heap_free(ad
->authorization
);
901 ad
->authorization
= heap_alloc(auth_data_len
);
902 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
903 ad
->authorizationLen
= auth_data_len
;
907 ad
= heap_alloc(sizeof(basicAuthorizationData
));
908 ad
->host
= heap_strdupW(host
);
909 ad
->realm
= heap_strdupW(realm
);
910 ad
->authorization
= heap_alloc(auth_data_len
);
911 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
912 ad
->authorizationLen
= auth_data_len
;
913 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
914 TRACE("authorization cached\n");
916 LeaveCriticalSection(&authcache_cs
);
919 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
920 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
922 authorizationData
*ad
;
924 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
926 EnterCriticalSection(&authcache_cs
);
927 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
928 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
929 TRACE("Authorization found in cache\n");
931 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
932 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
933 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
934 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
935 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
936 heap_free(nt_auth_identity
->User
);
937 heap_free(nt_auth_identity
->Password
);
938 heap_free(nt_auth_identity
->Domain
);
942 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
943 nt_auth_identity
->UserLength
= ad
->user_len
;
944 nt_auth_identity
->PasswordLength
= ad
->password_len
;
945 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
946 nt_auth_identity
->DomainLength
= ad
->domain_len
;
947 LeaveCriticalSection(&authcache_cs
);
951 LeaveCriticalSection(&authcache_cs
);
956 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
957 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
959 authorizationData
*ad
;
962 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
964 EnterCriticalSection(&authcache_cs
);
965 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
966 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
973 heap_free(ad
->password
);
974 heap_free(ad
->domain
);
976 ad
= heap_alloc(sizeof(authorizationData
));
978 LeaveCriticalSection(&authcache_cs
);
982 ad
->host
= heap_strdupW(host
);
983 ad
->scheme
= heap_strdupW(scheme
);
984 list_add_head(&authorizationCache
, &ad
->entry
);
987 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
988 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
989 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
990 ad
->user_len
= nt_auth_identity
->UserLength
;
991 ad
->password_len
= nt_auth_identity
->PasswordLength
;
992 ad
->domain_len
= nt_auth_identity
->DomainLength
;
994 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
995 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
997 heap_free(ad
->scheme
);
999 heap_free(ad
->password
);
1000 heap_free(ad
->domain
);
1001 list_remove(&ad
->entry
);
1005 LeaveCriticalSection(&authcache_cs
);
1008 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
1009 struct HttpAuthInfo
**ppAuthInfo
,
1010 LPWSTR domain_and_username
, LPWSTR password
,
1013 SECURITY_STATUS sec_status
;
1014 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
1016 LPWSTR szRealm
= NULL
;
1018 TRACE("%s\n", debugstr_w(pszAuthValue
));
1025 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
1029 SecInvalidateHandle(&pAuthInfo
->cred
);
1030 SecInvalidateHandle(&pAuthInfo
->ctx
);
1031 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1032 pAuthInfo
->attr
= 0;
1033 pAuthInfo
->auth_data
= NULL
;
1034 pAuthInfo
->auth_data_len
= 0;
1035 pAuthInfo
->finished
= FALSE
;
1037 if (is_basic_auth_value(pszAuthValue
,NULL
))
1039 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1040 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1041 if (!pAuthInfo
->scheme
)
1043 heap_free(pAuthInfo
);
1050 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1052 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1053 if (!pAuthInfo
->scheme
)
1055 heap_free(pAuthInfo
);
1059 if (domain_and_username
)
1061 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1062 WCHAR
*domain
= domain_and_username
;
1064 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1066 pAuthData
= &nt_auth_identity
;
1071 user
= domain_and_username
;
1075 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1076 nt_auth_identity
.User
= user
;
1077 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1078 nt_auth_identity
.Domain
= domain
;
1079 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1080 nt_auth_identity
.Password
= password
;
1081 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1083 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1085 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1086 pAuthData
= &nt_auth_identity
;
1088 /* use default credentials */
1091 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1092 SECPKG_CRED_OUTBOUND
, NULL
,
1094 NULL
, &pAuthInfo
->cred
,
1097 if(pAuthData
&& !domain_and_username
) {
1098 heap_free(nt_auth_identity
.User
);
1099 heap_free(nt_auth_identity
.Domain
);
1100 heap_free(nt_auth_identity
.Password
);
1103 if (sec_status
== SEC_E_OK
)
1105 PSecPkgInfoW sec_pkg_info
;
1106 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1107 if (sec_status
== SEC_E_OK
)
1109 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1110 FreeContextBuffer(sec_pkg_info
);
1113 if (sec_status
!= SEC_E_OK
)
1115 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1116 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1117 heap_free(pAuthInfo
->scheme
);
1118 heap_free(pAuthInfo
);
1122 *ppAuthInfo
= pAuthInfo
;
1124 else if (pAuthInfo
->finished
)
1127 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1128 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1130 ERR("authentication scheme changed from %s to %s\n",
1131 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1135 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1139 char *auth_data
= NULL
;
1140 UINT auth_data_len
= 0;
1142 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1144 if (!domain_and_username
)
1146 if (host
&& szRealm
)
1147 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1148 if (auth_data_len
== 0)
1156 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1157 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1159 /* length includes a nul terminator, which will be re-used for the ':' */
1160 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1167 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1168 auth_data
[userlen
] = ':';
1169 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1170 auth_data_len
= userlen
+ 1 + passlen
;
1171 if (host
&& szRealm
)
1172 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1175 pAuthInfo
->auth_data
= auth_data
;
1176 pAuthInfo
->auth_data_len
= auth_data_len
;
1177 pAuthInfo
->finished
= TRUE
;
1183 LPCWSTR pszAuthData
;
1184 SecBufferDesc out_desc
, in_desc
;
1186 unsigned char *buffer
;
1187 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1188 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1190 in
.BufferType
= SECBUFFER_TOKEN
;
1194 in_desc
.ulVersion
= 0;
1195 in_desc
.cBuffers
= 1;
1196 in_desc
.pBuffers
= &in
;
1198 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1199 if (*pszAuthData
== ' ')
1202 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1203 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1204 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1207 buffer
= heap_alloc(pAuthInfo
->max_token
);
1209 out
.BufferType
= SECBUFFER_TOKEN
;
1210 out
.cbBuffer
= pAuthInfo
->max_token
;
1211 out
.pvBuffer
= buffer
;
1213 out_desc
.ulVersion
= 0;
1214 out_desc
.cBuffers
= 1;
1215 out_desc
.pBuffers
= &out
;
1217 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1218 first
? NULL
: &pAuthInfo
->ctx
,
1219 first
? request
->server
->name
: NULL
,
1220 context_req
, 0, SECURITY_NETWORK_DREP
,
1221 in
.pvBuffer
? &in_desc
: NULL
,
1222 0, &pAuthInfo
->ctx
, &out_desc
,
1223 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1224 if (sec_status
== SEC_E_OK
)
1226 pAuthInfo
->finished
= TRUE
;
1227 pAuthInfo
->auth_data
= out
.pvBuffer
;
1228 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1229 TRACE("sending last auth packet\n");
1231 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1233 pAuthInfo
->auth_data
= out
.pvBuffer
;
1234 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1235 TRACE("sending next auth packet\n");
1239 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1240 heap_free(out
.pvBuffer
);
1241 destroy_authinfo(pAuthInfo
);
1250 /***********************************************************************
1251 * HTTP_HttpAddRequestHeadersW (internal)
1253 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1254 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1259 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1261 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1263 if( dwHeaderLength
== ~0U )
1264 len
= strlenW(lpszHeader
);
1266 len
= dwHeaderLength
;
1267 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1268 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1274 LPWSTR
* pFieldAndValue
;
1276 lpszEnd
= lpszStart
;
1278 while (*lpszEnd
!= '\0')
1280 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1285 if (*lpszStart
== '\0')
1288 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1291 lpszEnd
++; /* Jump over newline */
1293 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1294 if (*lpszStart
== '\0')
1296 /* Skip 0-length headers */
1297 lpszStart
= lpszEnd
;
1298 res
= ERROR_SUCCESS
;
1301 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1304 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1305 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1306 HTTP_FreeTokens(pFieldAndValue
);
1309 lpszStart
= lpszEnd
;
1310 } while (res
== ERROR_SUCCESS
);
1316 /***********************************************************************
1317 * HttpAddRequestHeadersW (WININET.@)
1319 * Adds one or more HTTP header to the request handler
1322 * On Windows if dwHeaderLength includes the trailing '\0', then
1323 * HttpAddRequestHeadersW() adds it too. However this results in an
1324 * invalid HTTP header which is rejected by some servers so we probably
1325 * don't need to match Windows on that point.
1332 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1333 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1335 http_request_t
*request
;
1336 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1338 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1343 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1344 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1345 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1347 WININET_Release( &request
->hdr
);
1349 if(res
!= ERROR_SUCCESS
)
1351 return res
== ERROR_SUCCESS
;
1354 /***********************************************************************
1355 * HttpAddRequestHeadersA (WININET.@)
1357 * Adds one or more HTTP header to the request handler
1364 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1365 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1367 WCHAR
*headers
= NULL
;
1370 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1373 headers
= heap_strndupAtoW(lpszHeader
, dwHeaderLength
, &dwHeaderLength
);
1375 r
= HttpAddRequestHeadersW(hHttpRequest
, headers
, dwHeaderLength
, dwModifier
);
1381 static void free_accept_types( WCHAR
**accept_types
)
1383 WCHAR
*ptr
, **types
= accept_types
;
1386 while ((ptr
= *types
))
1391 heap_free( accept_types
);
1394 static WCHAR
**convert_accept_types( const char **accept_types
)
1397 const char **types
= accept_types
;
1399 BOOL invalid_pointer
= FALSE
;
1401 if (!types
) return NULL
;
1407 /* find out how many there are */
1408 if (*types
&& **types
)
1410 TRACE("accept type: %s\n", debugstr_a(*types
));
1416 WARN("invalid accept type pointer\n");
1417 invalid_pointer
= TRUE
;
1422 if (invalid_pointer
) return NULL
;
1423 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1425 types
= accept_types
;
1428 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1431 typesW
[count
] = NULL
;
1435 /***********************************************************************
1436 * HttpOpenRequestA (WININET.@)
1438 * Open a HTTP request handle
1441 * HINTERNET a HTTP request handle on success
1445 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1446 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1447 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1448 DWORD dwFlags
, DWORD_PTR dwContext
)
1450 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1451 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1452 HINTERNET rc
= NULL
;
1454 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1455 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1456 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1457 dwFlags
, dwContext
);
1461 szVerb
= heap_strdupAtoW(lpszVerb
);
1468 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1469 if ( !szObjectName
)
1475 szVersion
= heap_strdupAtoW(lpszVersion
);
1482 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1487 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1488 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1489 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1492 free_accept_types(szAcceptTypes
);
1493 heap_free(szReferrer
);
1494 heap_free(szVersion
);
1495 heap_free(szObjectName
);
1500 /***********************************************************************
1503 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1506 static const CHAR HTTP_Base64Enc
[] =
1507 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1511 /* first 6 bits, all from bin[0] */
1512 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1513 x
= (bin
[0] & 3) << 4;
1515 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1518 base64
[n
++] = HTTP_Base64Enc
[x
];
1523 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1524 x
= ( bin
[1] & 0x0f ) << 2;
1526 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1529 base64
[n
++] = HTTP_Base64Enc
[x
];
1533 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1535 /* last 6 bits, all from bin [2] */
1536 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1544 static const signed char HTTP_Base64Dec
[] =
1546 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1547 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1548 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1549 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1550 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1551 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1552 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1553 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1556 /***********************************************************************
1559 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1567 if (base64
[0] >= ARRAY_SIZE(HTTP_Base64Dec
) ||
1568 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1569 base64
[1] >= ARRAY_SIZE(HTTP_Base64Dec
) ||
1570 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1572 WARN("invalid base64: %s\n", debugstr_w(base64
));
1576 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1579 if ((base64
[2] == '=') && (base64
[3] == '='))
1581 if (base64
[2] > ARRAY_SIZE(HTTP_Base64Dec
) ||
1582 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1584 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1588 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1591 if (base64
[3] == '=')
1593 if (base64
[3] > ARRAY_SIZE(HTTP_Base64Dec
) ||
1594 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1596 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1600 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1609 static WCHAR
*encode_auth_data( const WCHAR
*scheme
, const char *data
, UINT data_len
)
1612 UINT len
, scheme_len
= strlenW( scheme
);
1614 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1615 len
= scheme_len
+ 1 + ((data_len
+ 2) * 4) / 3;
1616 if (!(ret
= heap_alloc( (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1617 memcpy( ret
, scheme
, scheme_len
* sizeof(WCHAR
) );
1618 ret
[scheme_len
] = ' ';
1619 HTTP_EncodeBase64( data
, data_len
, ret
+ scheme_len
+ 1 );
1624 /***********************************************************************
1625 * HTTP_InsertAuthorization
1627 * Insert or delete the authorization field in the request header.
1629 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1631 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1632 WCHAR
*host
, *authorization
= NULL
;
1636 if (pAuthInfo
->auth_data_len
)
1638 if (!(authorization
= encode_auth_data(pAuthInfo
->scheme
, pAuthInfo
->auth_data
, pAuthInfo
->auth_data_len
)))
1641 /* clear the data as it isn't valid now that it has been sent to the
1642 * server, unless it's Basic authentication which doesn't do
1643 * connection tracking */
1644 if (strcmpiW(pAuthInfo
->scheme
, wszBasic
))
1646 heap_free(pAuthInfo
->auth_data
);
1647 pAuthInfo
->auth_data
= NULL
;
1648 pAuthInfo
->auth_data_len
= 0;
1652 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1654 HTTP_ProcessHeader(request
, header
, authorization
,
1655 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
1656 heap_free(authorization
);
1658 else if (!strcmpW(header
, szAuthorization
) && (host
= get_host_header(request
)))
1663 if ((data_len
= retrieve_cached_basic_authorization(host
, NULL
, &data
)))
1665 TRACE("Found cached basic authorization for %s\n", debugstr_w(host
));
1667 if (!(authorization
= encode_auth_data(wszBasic
, data
, data_len
)))
1674 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1676 HTTP_ProcessHeader(request
, header
, authorization
,
1677 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
1679 heap_free(authorization
);
1686 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1691 len
= strlenW(req
->server
->scheme_host_port
);
1692 size
= len
+ strlenW(req
->path
) + 1;
1693 if(*req
->path
!= '/')
1695 url
= heap_alloc(size
* sizeof(WCHAR
));
1699 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1700 if(*req
->path
!= '/')
1703 strcpyW(url
+len
, req
->path
);
1705 TRACE("url=%s\n", debugstr_w(url
));
1709 static BOOL
HTTP_DomainMatches(LPCWSTR server
, substr_t domain
)
1711 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1712 const WCHAR
*dot
, *ptr
;
1715 if(domain
.len
== sizeof(localW
)/sizeof(WCHAR
)-1 && !strncmpiW(domain
.str
, localW
, domain
.len
) && !strchrW(server
, '.' ))
1718 if(domain
.len
&& *domain
.str
!= '*')
1719 return domain
.len
== strlenW(server
) && !strncmpiW(server
, domain
.str
, domain
.len
);
1721 if(domain
.len
< 2 || domain
.str
[1] != '.')
1724 /* For a hostname to match a wildcard, the last domain must match
1725 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1726 * hostname is www.foo.a.b, it matches, but a.b does not.
1728 dot
= strchrW(server
, '.');
1732 len
= strlenW(dot
+ 1);
1733 if(len
< domain
.len
- 2)
1736 /* The server's domain is longer than the wildcard, so it
1737 * could be a subdomain. Compare the last portion of the
1740 ptr
= dot
+ 1 + len
- domain
.len
+ 2;
1741 if(!strncmpiW(ptr
, domain
.str
+2, domain
.len
-2))
1742 /* This is only a match if the preceding character is
1743 * a '.', i.e. that it is a matching domain. E.g.
1744 * if domain is '*.b.c' and server is 'www.ab.c' they
1747 return *(ptr
- 1) == '.';
1749 return len
== domain
.len
-2 && !strncmpiW(dot
+ 1, domain
.str
+ 2, len
);
1752 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1757 if (!lpwai
->proxyBypass
) return FALSE
;
1758 ptr
= lpwai
->proxyBypass
;
1762 ptr
= strchrW( ptr
, ';' );
1764 ptr
= strchrW( tmp
, ' ' );
1766 ptr
= tmp
+ strlenW(tmp
);
1767 ret
= HTTP_DomainMatches( server
, substr(tmp
, ptr
-tmp
) );
1775 /***********************************************************************
1776 * HTTP_DealWithProxy
1778 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1780 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1781 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1782 static WCHAR szNul
[] = { 0 };
1783 URL_COMPONENTSW UrlComponents
= { sizeof(UrlComponents
) };
1784 server_t
*new_server
= NULL
;
1787 proxy
= INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
);
1790 if(CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1791 proxy
, strlenW(szHttp
), szHttp
, strlenW(szHttp
))) {
1792 WCHAR
*proxy_url
= heap_alloc(strlenW(proxy
)*sizeof(WCHAR
) + sizeof(szHttp
));
1797 strcpyW(proxy_url
, szHttp
);
1798 strcatW(proxy_url
, proxy
);
1803 UrlComponents
.dwHostNameLength
= 1;
1804 if(InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) && UrlComponents
.dwHostNameLength
) {
1805 if( !request
->path
)
1806 request
->path
= szNul
;
1808 new_server
= get_server(substr(UrlComponents
.lpszHostName
, UrlComponents
.dwHostNameLength
),
1809 UrlComponents
.nPort
, UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
1815 request
->proxy
= new_server
;
1817 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1821 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1823 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1826 if(server
->addr_len
)
1827 return ERROR_SUCCESS
;
1829 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1830 INTERNET_STATUS_RESOLVING_NAME
,
1832 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1834 addr_len
= sizeof(server
->addr
);
1835 if (!GetAddress(server
->name
, server
->port
, (SOCKADDR
*)&server
->addr
, &addr_len
, server
->addr_str
))
1836 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1838 server
->addr_len
= addr_len
;
1839 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1840 INTERNET_STATUS_NAME_RESOLVED
,
1841 server
->addr_str
, strlen(server
->addr_str
)+1);
1843 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1844 return ERROR_SUCCESS
;
1847 static WCHAR
*compose_request_url(http_request_t
*req
)
1849 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1850 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1851 const WCHAR
*host
, *scheme
;
1855 host
= req
->server
->canon_host_port
;
1857 if (req
->server
->is_https
)
1862 len
= strlenW(scheme
) + strlenW(host
) + (req
->path
[0] != '/' ? 1 : 0) + strlenW(req
->path
);
1863 ptr
= buf
= heap_alloc((len
+1) * sizeof(WCHAR
));
1865 strcpyW(ptr
, scheme
);
1866 ptr
+= strlenW(ptr
);
1869 ptr
+= strlenW(ptr
);
1871 if(req
->path
[0] != '/')
1874 strcpyW(ptr
, req
->path
);
1875 ptr
+= strlenW(ptr
);
1883 /***********************************************************************
1884 * HTTPREQ_Destroy (internal)
1886 * Deallocate request handle
1889 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1891 http_request_t
*request
= (http_request_t
*) hdr
;
1896 if(request
->hCacheFile
)
1897 CloseHandle(request
->hCacheFile
);
1898 if(request
->req_file
)
1899 req_file_release(request
->req_file
);
1901 request
->headers_section
.DebugInfo
->Spare
[0] = 0;
1902 DeleteCriticalSection( &request
->headers_section
);
1903 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1904 DeleteCriticalSection( &request
->read_section
);
1905 WININET_Release(&request
->session
->hdr
);
1907 destroy_authinfo(request
->authInfo
);
1908 destroy_authinfo(request
->proxyAuthInfo
);
1911 server_release(request
->server
);
1913 server_release(request
->proxy
);
1915 heap_free(request
->path
);
1916 heap_free(request
->verb
);
1917 heap_free(request
->version
);
1918 heap_free(request
->statusText
);
1920 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1922 heap_free(request
->custHeaders
[i
].lpszField
);
1923 heap_free(request
->custHeaders
[i
].lpszValue
);
1925 destroy_data_stream(request
->data_stream
);
1926 heap_free(request
->custHeaders
);
1929 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1931 TRACE("%p %p %x\n",req
, req
->netconn
, reuse
);
1933 if(!is_valid_netconn(req
->netconn
))
1936 if(reuse
&& req
->netconn
->keep_alive
) {
1939 EnterCriticalSection(&connection_pool_cs
);
1941 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1942 req
->netconn
->keep_until
= GetTickCount64() + COLLECT_TIME
;
1943 req
->netconn
= NULL
;
1945 run_collector
= !collector_running
;
1946 collector_running
= TRUE
;
1948 LeaveCriticalSection(&connection_pool_cs
);
1951 HANDLE thread
= NULL
;
1954 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
1956 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
1958 EnterCriticalSection(&connection_pool_cs
);
1959 collector_running
= FALSE
;
1960 LeaveCriticalSection(&connection_pool_cs
);
1963 FreeLibrary(module
);
1966 CloseHandle(thread
);
1971 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1972 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
1974 close_netconn(req
->netconn
);
1976 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1977 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
1980 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
1982 WCHAR szVersion
[10];
1983 WCHAR szConnectionResponse
[20];
1984 DWORD dwBufferSize
= sizeof(szVersion
);
1985 BOOL keepalive
= FALSE
;
1987 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1988 * the connection is keep-alive by default */
1989 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
1990 && !strcmpiW(szVersion
, g_szHttp1_1
))
1995 dwBufferSize
= sizeof(szConnectionResponse
);
1996 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
1997 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
1999 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2005 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2007 http_request_t
*req
= (http_request_t
*)hdr
;
2009 http_release_netconn(req
, drain_content(req
, FALSE
) == ERROR_SUCCESS
);
2012 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2017 WCHAR
*buf
= buffer
;
2019 if (str
) len
= strlenW(str
);
2021 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2023 *size
= (len
+ 1) * sizeof(WCHAR
);
2024 return ERROR_INSUFFICIENT_BUFFER
;
2026 if (str
) strcpyW(buf
, str
);
2030 return ERROR_SUCCESS
;
2036 if (str
) len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
2041 return ERROR_INSUFFICIENT_BUFFER
;
2043 if (str
) WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, *size
, NULL
, NULL
);
2047 return ERROR_SUCCESS
;
2051 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2053 http_request_t
*req
= (http_request_t
*)hdr
;
2056 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2058 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2060 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2062 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2063 return ERROR_INSUFFICIENT_BUFFER
;
2064 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2065 /* FIXME: can't get a SOCKET from our connection since we don't use
2069 /* FIXME: get source port from req->netConnection */
2070 info
->SourcePort
= 0;
2071 info
->DestPort
= req
->server
->port
;
2073 if (HTTP_KeepAlive(req
))
2074 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2076 info
->Flags
|= IDSI_FLAG_PROXY
;
2077 if (is_valid_netconn(req
->netconn
) && req
->netconn
->secure
)
2078 info
->Flags
|= IDSI_FLAG_SECURE
;
2080 return ERROR_SUCCESS
;
2084 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2086 case INTERNET_OPTION_SECURITY_FLAGS
:
2090 if (*size
< sizeof(ULONG
))
2091 return ERROR_INSUFFICIENT_BUFFER
;
2093 *size
= sizeof(DWORD
);
2094 flags
= is_valid_netconn(req
->netconn
) ? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2095 *(DWORD
*)buffer
= flags
;
2097 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2098 return ERROR_SUCCESS
;
2101 case INTERNET_OPTION_HANDLE_TYPE
:
2102 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2104 if (*size
< sizeof(ULONG
))
2105 return ERROR_INSUFFICIENT_BUFFER
;
2107 *size
= sizeof(DWORD
);
2108 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2109 return ERROR_SUCCESS
;
2111 case INTERNET_OPTION_URL
: {
2115 TRACE("INTERNET_OPTION_URL\n");
2117 url
= compose_request_url(req
);
2119 return ERROR_OUTOFMEMORY
;
2121 res
= str_to_buffer(url
, buffer
, size
, unicode
);
2125 case INTERNET_OPTION_USER_AGENT
:
2126 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2127 case INTERNET_OPTION_USERNAME
:
2128 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2129 case INTERNET_OPTION_PASSWORD
:
2130 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2131 case INTERNET_OPTION_PROXY_USERNAME
:
2132 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2133 case INTERNET_OPTION_PROXY_PASSWORD
:
2134 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2136 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2137 INTERNET_CACHE_ENTRY_INFOW
*info
;
2138 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2139 DWORD nbytes
, error
;
2142 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2145 return ERROR_FILE_NOT_FOUND
;
2147 if (*size
< sizeof(*ts
))
2149 *size
= sizeof(*ts
);
2150 return ERROR_INSUFFICIENT_BUFFER
;
2154 ret
= GetUrlCacheEntryInfoW(req
->req_file
->url
, NULL
, &nbytes
);
2155 error
= GetLastError();
2156 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2158 if (!(info
= heap_alloc(nbytes
)))
2159 return ERROR_OUTOFMEMORY
;
2161 GetUrlCacheEntryInfoW(req
->req_file
->url
, info
, &nbytes
);
2163 ts
->ftExpires
= info
->ExpireTime
;
2164 ts
->ftLastModified
= info
->LastModifiedTime
;
2167 *size
= sizeof(*ts
);
2168 return ERROR_SUCCESS
;
2173 case INTERNET_OPTION_DATAFILE_NAME
: {
2176 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2178 if(!req
->req_file
) {
2180 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2184 req_size
= (lstrlenW(req
->req_file
->file_name
)+1) * sizeof(WCHAR
);
2185 if(*size
< req_size
)
2186 return ERROR_INSUFFICIENT_BUFFER
;
2189 memcpy(buffer
, req
->req_file
->file_name
, *size
);
2190 return ERROR_SUCCESS
;
2192 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
, -1, NULL
, 0, NULL
, NULL
);
2193 if (req_size
> *size
)
2194 return ERROR_INSUFFICIENT_BUFFER
;
2196 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->req_file
->file_name
,
2197 -1, buffer
, *size
, NULL
, NULL
);
2198 return ERROR_SUCCESS
;
2202 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2203 PCCERT_CONTEXT context
;
2206 return ERROR_INTERNET_INVALID_OPERATION
;
2208 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2209 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2210 return ERROR_INSUFFICIENT_BUFFER
;
2213 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2215 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2218 memset(info
, 0, sizeof(*info
));
2219 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2220 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2221 len
= CertNameToStrA(context
->dwCertEncodingType
,
2222 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2223 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2224 if(info
->lpszSubjectInfo
)
2225 CertNameToStrA(context
->dwCertEncodingType
,
2226 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2227 info
->lpszSubjectInfo
, len
);
2228 len
= CertNameToStrA(context
->dwCertEncodingType
,
2229 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2230 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2231 if(info
->lpszIssuerInfo
)
2232 CertNameToStrA(context
->dwCertEncodingType
,
2233 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2234 info
->lpszIssuerInfo
, len
);
2235 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2236 CertFreeCertificateContext(context
);
2237 return ERROR_SUCCESS
;
2239 return ERROR_NOT_SUPPORTED
;
2241 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2242 if (*size
< sizeof(DWORD
))
2243 return ERROR_INSUFFICIENT_BUFFER
;
2245 *size
= sizeof(DWORD
);
2246 *(DWORD
*)buffer
= req
->connect_timeout
;
2247 return ERROR_SUCCESS
;
2248 case INTERNET_OPTION_REQUEST_FLAGS
: {
2251 if (*size
< sizeof(DWORD
))
2252 return ERROR_INSUFFICIENT_BUFFER
;
2254 /* FIXME: Add support for:
2255 * INTERNET_REQFLAG_FROM_CACHE
2256 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2260 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2261 if(!req
->status_code
)
2262 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2264 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2266 *size
= sizeof(DWORD
);
2267 *(DWORD
*)buffer
= flags
;
2268 return ERROR_SUCCESS
;
2272 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2275 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2277 http_request_t
*req
= (http_request_t
*)hdr
;
2280 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2281 TRACE("Undocumented option 99\n");
2283 if (!buffer
|| size
!= sizeof(DWORD
))
2284 return ERROR_INVALID_PARAMETER
;
2285 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2286 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2289 case INTERNET_OPTION_SECURITY_FLAGS
:
2293 if (!buffer
|| size
!= sizeof(DWORD
))
2294 return ERROR_INVALID_PARAMETER
;
2295 flags
= *(DWORD
*)buffer
;
2296 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2297 flags
&= SECURITY_SET_MASK
;
2298 req
->security_flags
|= flags
;
2299 if(is_valid_netconn(req
->netconn
))
2300 req
->netconn
->security_flags
|= flags
;
2301 return ERROR_SUCCESS
;
2303 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2304 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2305 req
->connect_timeout
= *(DWORD
*)buffer
;
2306 return ERROR_SUCCESS
;
2308 case INTERNET_OPTION_SEND_TIMEOUT
:
2309 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2310 req
->send_timeout
= *(DWORD
*)buffer
;
2311 return ERROR_SUCCESS
;
2313 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2314 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2315 req
->receive_timeout
= *(DWORD
*)buffer
;
2316 return ERROR_SUCCESS
;
2318 case INTERNET_OPTION_USERNAME
:
2319 heap_free(req
->session
->userName
);
2320 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2321 return ERROR_SUCCESS
;
2323 case INTERNET_OPTION_PASSWORD
:
2324 heap_free(req
->session
->password
);
2325 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2326 return ERROR_SUCCESS
;
2328 case INTERNET_OPTION_PROXY_USERNAME
:
2329 heap_free(req
->session
->appInfo
->proxyUsername
);
2330 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2331 return ERROR_SUCCESS
;
2333 case INTERNET_OPTION_PROXY_PASSWORD
:
2334 heap_free(req
->session
->appInfo
->proxyPassword
);
2335 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2336 return ERROR_SUCCESS
;
2338 case INTERNET_OPTION_HTTP_DECODING
:
2339 if(size
!= sizeof(BOOL
))
2340 return ERROR_INVALID_PARAMETER
;
2341 req
->decoding
= *(BOOL
*)buffer
;
2342 return ERROR_SUCCESS
;
2345 return INET_SetOption(hdr
, option
, buffer
, size
);
2348 static void commit_cache_entry(http_request_t
*req
)
2356 CloseHandle(req
->hCacheFile
);
2357 req
->hCacheFile
= NULL
;
2359 header
= build_response_header(req
, TRUE
);
2360 header_len
= (header
? strlenW(header
) : 0);
2361 res
= CommitUrlCacheEntryW(req
->req_file
->url
, req
->req_file
->file_name
, req
->expires
,
2362 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2363 header
, header_len
, NULL
, 0);
2365 req
->req_file
->is_committed
= TRUE
;
2367 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2371 static void create_cache_entry(http_request_t
*req
)
2373 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2374 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2376 WCHAR file_name
[MAX_PATH
+1];
2380 /* FIXME: We should free previous cache file earlier */
2382 req_file_release(req
->req_file
);
2383 req
->req_file
= NULL
;
2385 if(req
->hCacheFile
) {
2386 CloseHandle(req
->hCacheFile
);
2387 req
->hCacheFile
= NULL
;
2390 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2396 EnterCriticalSection( &req
->headers_section
);
2398 header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2399 if(header_idx
!= -1) {
2402 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2405 while(*ptr
==' ' || *ptr
=='\t')
2408 end
= strchrW(ptr
, ',');
2410 end
= ptr
+ strlenW(ptr
);
2412 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2413 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2424 LeaveCriticalSection( &req
->headers_section
);
2428 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2431 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2434 url
= compose_request_url(req
);
2436 WARN("Could not get URL\n");
2440 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2442 WARN("Could not create cache entry: %08x\n", GetLastError());
2446 create_req_file(file_name
, &req
->req_file
);
2447 req
->req_file
->url
= url
;
2449 req
->hCacheFile
= CreateFileW(file_name
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2450 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2451 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2452 WARN("Could not create file: %u\n", GetLastError());
2453 req
->hCacheFile
= NULL
;
2457 if(req
->read_size
) {
2460 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2462 FIXME("WriteFile failed: %u\n", GetLastError());
2464 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2465 commit_cache_entry(req
);
2469 /* read some more data into the read buffer (the read section must be held) */
2470 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2477 /* move existing data to the start of the buffer */
2479 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2483 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2485 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2486 maxlen
- req
->read_size
, TRUE
, &len
);
2487 if(res
== ERROR_SUCCESS
)
2488 req
->read_size
+= len
;
2493 /* remove some amount of data from the read buffer (the read section must be held) */
2494 static void remove_data( http_request_t
*req
, int count
)
2496 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2497 else req
->read_pos
+= count
;
2500 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2502 int count
, bytes_read
, pos
= 0;
2505 EnterCriticalSection( &req
->read_section
);
2508 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2512 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2513 bytes_read
= count
+ 1;
2515 else count
= bytes_read
= req
->read_size
;
2517 count
= min( count
, *len
- pos
);
2518 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2520 remove_data( req
, bytes_read
);
2523 if ((res
= read_more_data( req
, -1 )))
2525 WARN( "read failed %u\n", res
);
2526 LeaveCriticalSection( &req
->read_section
);
2529 if (!req
->read_size
)
2532 TRACE( "returning empty string\n" );
2533 LeaveCriticalSection( &req
->read_section
);
2534 return ERROR_SUCCESS
;
2537 LeaveCriticalSection( &req
->read_section
);
2541 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2544 buffer
[*len
- 1] = 0;
2545 TRACE( "returning %s\n", debugstr_a(buffer
));
2546 return ERROR_SUCCESS
;
2549 /* check if we have reached the end of the data to read (the read section must be held) */
2550 static BOOL
end_of_read_data( http_request_t
*req
)
2552 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2555 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, BOOL allow_blocking
)
2559 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, allow_blocking
);
2560 if(res
!= ERROR_SUCCESS
)
2562 assert(*read
<= size
);
2564 if(req
->hCacheFile
) {
2569 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2571 FIXME("WriteFile failed: %u\n", GetLastError());
2574 if((res
== ERROR_SUCCESS
&& !*read
) || req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2575 commit_cache_entry(req
);
2581 /* fetch some more data into the read buffer (the read section must be held) */
2582 static DWORD
refill_read_buffer(http_request_t
*req
, BOOL allow_blocking
, DWORD
*read_bytes
)
2586 if(req
->read_size
== sizeof(req
->read_buf
))
2587 return ERROR_SUCCESS
;
2591 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2595 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2596 &read
, allow_blocking
);
2597 if(res
!= ERROR_SUCCESS
)
2600 req
->read_size
+= read
;
2602 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2608 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2610 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2611 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !is_valid_netconn(req
->netconn
);
2614 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2615 DWORD
*read
, BOOL allow_blocking
)
2617 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2618 DWORD res
= ERROR_SUCCESS
;
2621 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2623 if(size
&& is_valid_netconn(req
->netconn
)) {
2624 res
= NETCON_recv(req
->netconn
, buf
, size
, allow_blocking
, &ret
);
2625 if(res
== ERROR_SUCCESS
) {
2627 netconn_stream
->content_length
= netconn_stream
->content_read
;
2628 netconn_stream
->content_read
+= ret
;
2632 TRACE("res %u read %u bytes\n", res
, ret
);
2637 static DWORD
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
, BOOL allow_blocking
)
2639 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2644 if(netconn_stream
->content_length
== ~0u)
2647 while(netconn_stream
->content_read
< netconn_stream
->content_length
) {
2648 size
= min(sizeof(buf
), netconn_stream
->content_length
-netconn_stream
->content_read
);
2649 res
= NETCON_recv(req
->netconn
, buf
, size
, allow_blocking
, &len
);
2653 return WSAECONNABORTED
;
2655 netconn_stream
->content_read
+= len
;
2658 return ERROR_SUCCESS
;
2661 static void netconn_destroy(data_stream_t
*stream
)
2665 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2666 netconn_end_of_data
,
2668 netconn_drain_content
,
2672 static char next_chunked_data_char(chunked_stream_t
*stream
)
2674 assert(stream
->buf_size
);
2677 return stream
->buf
[stream
->buf_pos
++];
2680 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2682 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2683 switch(chunked_stream
->state
) {
2684 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2685 case CHUNKED_STREAM_STATE_END_OF_STREAM
:
2686 case CHUNKED_STREAM_STATE_ERROR
:
2693 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2694 DWORD
*read
, BOOL allow_blocking
)
2696 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2697 DWORD ret_read
= 0, res
= ERROR_SUCCESS
;
2698 BOOL continue_read
= TRUE
;
2703 TRACE("state %d\n", chunked_stream
->state
);
2705 /* Ensure that we have data in the buffer for states that need it. */
2706 if(!chunked_stream
->buf_size
) {
2707 BOOL blocking_read
= allow_blocking
;
2709 switch(chunked_stream
->state
) {
2710 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2711 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
:
2712 /* never allow blocking after 0 chunk size */
2713 if(!chunked_stream
->chunk_size
)
2714 blocking_read
= FALSE
;
2716 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
:
2717 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
:
2718 chunked_stream
->buf_pos
= 0;
2719 res
= NETCON_recv(req
->netconn
, chunked_stream
->buf
, sizeof(chunked_stream
->buf
), blocking_read
, &read_bytes
);
2720 if(res
== ERROR_SUCCESS
&& read_bytes
) {
2721 chunked_stream
->buf_size
+= read_bytes
;
2722 }else if(res
== WSAEWOULDBLOCK
) {
2723 if(ret_read
|| allow_blocking
)
2724 res
= ERROR_SUCCESS
;
2725 continue_read
= FALSE
;
2728 chunked_stream
->state
= CHUNKED_STREAM_STATE_ERROR
;
2736 switch(chunked_stream
->state
) {
2737 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
:
2738 ch
= next_chunked_data_char(chunked_stream
);
2740 if(ch
>= '0' && ch
<= '9') {
2741 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- '0';
2742 }else if(ch
>= 'a' && ch
<= 'f') {
2743 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- 'a' + 10;
2744 }else if (ch
>= 'A' && ch
<= 'F') {
2745 chunked_stream
->chunk_size
= chunked_stream
->chunk_size
* 16 + ch
- 'A' + 10;
2746 }else if (ch
== ';' || ch
== '\r' || ch
== '\n') {
2747 TRACE("reading %u byte chunk\n", chunked_stream
->chunk_size
);
2748 chunked_stream
->buf_size
++;
2749 chunked_stream
->buf_pos
--;
2750 if(req
->contentLength
== ~0u) req
->contentLength
= chunked_stream
->chunk_size
;
2751 else req
->contentLength
+= chunked_stream
->chunk_size
;
2752 chunked_stream
->state
= CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
;
2756 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE
:
2757 ch
= next_chunked_data_char(chunked_stream
);
2759 chunked_stream
->state
= chunked_stream
->chunk_size
2760 ? CHUNKED_STREAM_STATE_READING_CHUNK
2761 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
;
2763 WARN("unexpected char '%c'\n", ch
);
2766 case CHUNKED_STREAM_STATE_READING_CHUNK
:
2767 assert(chunked_stream
->chunk_size
);
2769 continue_read
= FALSE
;
2772 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2774 if(chunked_stream
->buf_size
) {
2775 if(read_bytes
> chunked_stream
->buf_size
)
2776 read_bytes
= chunked_stream
->buf_size
;
2778 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2779 chunked_stream
->buf_pos
+= read_bytes
;
2780 chunked_stream
->buf_size
-= read_bytes
;
2782 res
= NETCON_recv(req
->netconn
, (char*)buf
+ret_read
, read_bytes
,
2783 allow_blocking
, (int*)&read_bytes
);
2784 if(res
!= ERROR_SUCCESS
) {
2785 continue_read
= FALSE
;
2790 chunked_stream
->state
= CHUNKED_STREAM_STATE_ERROR
;
2795 chunked_stream
->chunk_size
-= read_bytes
;
2797 ret_read
+= read_bytes
;
2798 if(!chunked_stream
->chunk_size
)
2799 chunked_stream
->state
= CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
;
2800 allow_blocking
= FALSE
;
2803 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA
:
2804 ch
= next_chunked_data_char(chunked_stream
);
2806 chunked_stream
->state
= CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
;
2808 WARN("unexpected char '%c'\n", ch
);
2811 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END
:
2812 ch
= next_chunked_data_char(chunked_stream
);
2814 chunked_stream
->state
= CHUNKED_STREAM_STATE_END_OF_STREAM
;
2816 WARN("unexpected char '%c'\n", ch
);
2819 case CHUNKED_STREAM_STATE_END_OF_STREAM
:
2820 case CHUNKED_STREAM_STATE_ERROR
:
2821 continue_read
= FALSE
;
2824 } while(continue_read
);
2827 res
= ERROR_SUCCESS
;
2828 if(res
!= ERROR_SUCCESS
)
2831 TRACE("read %d bytes\n", ret_read
);
2833 return ERROR_SUCCESS
;
2836 static DWORD
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
, BOOL allow_blocking
)
2838 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2842 while(chunked_stream
->state
!= CHUNKED_STREAM_STATE_END_OF_STREAM
2843 && chunked_stream
->state
!= CHUNKED_STREAM_STATE_ERROR
) {
2844 res
= chunked_read(stream
, req
, buf
, sizeof(buf
), &size
, allow_blocking
);
2845 if(res
!= ERROR_SUCCESS
)
2849 if(chunked_stream
->state
!= CHUNKED_STREAM_STATE_END_OF_STREAM
)
2850 return ERROR_NO_DATA
;
2851 return ERROR_SUCCESS
;
2854 static void chunked_destroy(data_stream_t
*stream
)
2856 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2857 heap_free(chunked_stream
);
2860 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2861 chunked_end_of_data
,
2863 chunked_drain_content
,
2867 /* set the request content length based on the headers */
2868 static DWORD
set_content_length(http_request_t
*request
)
2870 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2871 static const WCHAR headW
[] = {'H','E','A','D',0};
2875 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
|| !strcmpW(request
->verb
, headW
)) {
2876 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2877 return ERROR_SUCCESS
;
2880 size
= sizeof(request
->contentLength
);
2881 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2882 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2883 request
->contentLength
= ~0u;
2884 request
->netconn_stream
.content_length
= request
->contentLength
;
2885 request
->netconn_stream
.content_read
= request
->read_size
;
2887 size
= sizeof(encoding
);
2888 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2889 !strcmpiW(encoding
, szChunked
))
2891 chunked_stream_t
*chunked_stream
;
2893 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2895 return ERROR_OUTOFMEMORY
;
2897 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2898 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2899 chunked_stream
->chunk_size
= 0;
2900 chunked_stream
->state
= CHUNKED_STREAM_STATE_READING_CHUNK_SIZE
;
2902 if(request
->read_size
) {
2903 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2904 chunked_stream
->buf_size
= request
->read_size
;
2905 request
->read_size
= request
->read_pos
= 0;
2908 request
->data_stream
= &chunked_stream
->data_stream
;
2909 request
->contentLength
= ~0u;
2912 if(request
->decoding
) {
2915 static const WCHAR deflateW
[] = {'d','e','f','l','a','t','e',0};
2916 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2918 EnterCriticalSection( &request
->headers_section
);
2920 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2921 if(encoding_idx
!= -1) {
2922 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2923 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2924 LeaveCriticalSection( &request
->headers_section
);
2925 return init_gzip_stream(request
, TRUE
);
2927 if(!strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, deflateW
)) {
2928 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2929 LeaveCriticalSection( &request
->headers_section
);
2930 return init_gzip_stream(request
, FALSE
);
2934 LeaveCriticalSection( &request
->headers_section
);
2937 return ERROR_SUCCESS
;
2940 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
2942 INTERNET_ASYNC_RESULT iar
;
2944 iar
.dwResult
= result
;
2945 iar
.dwError
= error
;
2947 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
2948 sizeof(INTERNET_ASYNC_RESULT
));
2951 static void HTTP_ReceiveRequestData(http_request_t
*req
)
2953 DWORD res
, read
= 0;
2957 EnterCriticalSection( &req
->read_section
);
2959 res
= refill_read_buffer(req
, FALSE
, &read
);
2960 if(res
== ERROR_SUCCESS
)
2961 read
+= req
->read_size
;
2963 LeaveCriticalSection( &req
->read_section
);
2965 if(res
!= WSAEWOULDBLOCK
&& (res
!= ERROR_SUCCESS
|| !read
)) {
2966 WARN("res %u read %u, closing connection\n", res
, read
);
2967 http_release_netconn(req
, FALSE
);
2970 if(res
!= ERROR_SUCCESS
&& res
!= WSAEWOULDBLOCK
) {
2971 send_request_complete(req
, 0, res
);
2975 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, 0);
2978 /* read data from the http connection (the read section must be held) */
2979 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
, BOOL allow_blocking
)
2981 DWORD current_read
= 0, ret_read
= 0;
2982 DWORD res
= ERROR_SUCCESS
;
2984 EnterCriticalSection( &req
->read_section
);
2986 if(req
->read_size
) {
2987 ret_read
= min(size
, req
->read_size
);
2988 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
2989 req
->read_size
-= ret_read
;
2990 req
->read_pos
+= ret_read
;
2991 allow_blocking
= FALSE
;
2994 if(ret_read
< size
) {
2995 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, allow_blocking
);
2996 if(res
== ERROR_SUCCESS
)
2997 ret_read
+= current_read
;
2998 else if(res
== WSAEWOULDBLOCK
&& ret_read
)
2999 res
= ERROR_SUCCESS
;
3002 LeaveCriticalSection( &req
->read_section
);
3005 TRACE( "retrieved %u bytes (res %u)\n", ret_read
, res
);
3007 if(res
!= WSAEWOULDBLOCK
) {
3008 if(res
!= ERROR_SUCCESS
)
3009 http_release_netconn(req
, FALSE
);
3010 else if(!ret_read
&& drain_content(req
, FALSE
) == ERROR_SUCCESS
)
3011 http_release_netconn(req
, TRUE
);
3017 static DWORD
drain_content(http_request_t
*req
, BOOL blocking
)
3021 TRACE("%p\n", req
->netconn
);
3023 if(!is_valid_netconn(req
->netconn
))
3024 return ERROR_NO_DATA
;
3026 if(!strcmpW(req
->verb
, szHEAD
))
3027 return ERROR_SUCCESS
;
3029 EnterCriticalSection( &req
->read_section
);
3030 res
= req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
, blocking
);
3031 LeaveCriticalSection( &req
->read_section
);
3043 static void async_read_file_proc(task_header_t
*hdr
)
3045 read_file_task_t
*task
= (read_file_task_t
*)hdr
;
3046 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3047 DWORD res
= ERROR_SUCCESS
, read
= task
->read_pos
, complete_arg
= 0;
3049 TRACE("req %p buf %p size %u read_pos %u ret_read %p\n", req
, task
->buf
, task
->size
, task
->read_pos
, task
->ret_read
);
3053 while (read
< task
->size
) {
3054 res
= HTTPREQ_Read(req
, (char*)task
->buf
+ read
, task
->size
- read
, &read_bytes
, TRUE
);
3055 if (res
!= ERROR_SUCCESS
|| !read_bytes
)
3060 EnterCriticalSection(&req
->read_section
);
3061 res
= refill_read_buffer(req
, TRUE
, &read
);
3062 LeaveCriticalSection(&req
->read_section
);
3065 complete_arg
= read
; /* QueryDataAvailable reports read bytes in request complete notification */
3066 if(res
!= ERROR_SUCCESS
|| !read
)
3067 http_release_netconn(req
, drain_content(req
, FALSE
) == ERROR_SUCCESS
);
3070 TRACE("res %u read %u\n", res
, read
);
3073 *task
->ret_read
= read
;
3075 /* FIXME: We should report bytes transferred before decoding content. */
3076 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
, &read
, sizeof(read
));
3078 if(res
!= ERROR_SUCCESS
)
3080 send_request_complete(req
, res
== ERROR_SUCCESS
, complete_arg
);
3083 static DWORD
async_read(http_request_t
*req
, void *buf
, DWORD size
, DWORD read_pos
, DWORD
*ret_read
)
3085 read_file_task_t
*task
;
3087 task
= alloc_async_task(&req
->hdr
, async_read_file_proc
, sizeof(*task
));
3089 return ERROR_OUTOFMEMORY
;
3093 task
->read_pos
= read_pos
;
3094 task
->ret_read
= ret_read
;
3096 INTERNET_AsyncCall(&task
->hdr
);
3097 return ERROR_IO_PENDING
;
3100 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3101 DWORD flags
, DWORD_PTR context
)
3103 http_request_t
*req
= (http_request_t
*)hdr
;
3104 DWORD res
= ERROR_SUCCESS
, read
= 0, cread
, error
= ERROR_SUCCESS
;
3105 BOOL allow_blocking
, notify_received
= FALSE
;
3107 TRACE("(%p %p %u %x)\n", req
, buf
, size
, flags
);
3109 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3110 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3112 allow_blocking
= !(req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
);
3114 if(allow_blocking
|| TryEnterCriticalSection(&req
->read_section
)) {
3116 EnterCriticalSection(&req
->read_section
);
3117 if(hdr
->dwError
== ERROR_SUCCESS
)
3118 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3119 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3120 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3122 if(req
->read_size
) {
3123 read
= min(size
, req
->read_size
);
3124 memcpy(buf
, req
->read_buf
+ req
->read_pos
, read
);
3125 req
->read_size
-= read
;
3126 req
->read_pos
+= read
;
3129 if(read
< size
&& (!read
|| !(flags
& IRF_NO_WAIT
)) && !end_of_read_data(req
)) {
3130 LeaveCriticalSection(&req
->read_section
);
3131 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3132 EnterCriticalSection( &req
->read_section
);
3133 notify_received
= TRUE
;
3135 while(read
< size
) {
3136 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
, allow_blocking
);
3138 if (res
!= ERROR_SUCCESS
|| !cread
)
3143 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3144 hdr
->dwError
= ERROR_SUCCESS
;
3146 error
= hdr
->dwError
;
3148 LeaveCriticalSection( &req
->read_section
);
3150 res
= WSAEWOULDBLOCK
;
3153 if(res
== WSAEWOULDBLOCK
) {
3154 if(!(flags
& IRF_NO_WAIT
))
3155 return async_read(req
, buf
, size
, read
, ret_read
);
3157 return async_read(req
, NULL
, 0, 0, NULL
);
3158 res
= ERROR_SUCCESS
;
3162 if (res
!= ERROR_SUCCESS
)
3166 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3167 &read
, sizeof(read
));
3171 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3174 http_request_t
*request
= (http_request_t
*)hdr
;
3176 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3179 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3180 if (res
== ERROR_SUCCESS
)
3181 request
->bytesWritten
+= *written
;
3183 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3187 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3189 http_request_t
*req
= (http_request_t
*)hdr
;
3190 DWORD res
= ERROR_SUCCESS
, avail
= 0, error
= ERROR_SUCCESS
;
3191 BOOL allow_blocking
, notify_received
= FALSE
;
3193 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3195 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3196 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3199 allow_blocking
= !(req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
);
3201 if(allow_blocking
|| TryEnterCriticalSection(&req
->read_section
)) {
3203 EnterCriticalSection(&req
->read_section
);
3204 if(hdr
->dwError
== ERROR_SUCCESS
)
3205 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3206 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3207 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3209 avail
= req
->read_size
;
3211 if(!avail
&& !end_of_read_data(req
)) {
3212 LeaveCriticalSection(&req
->read_section
);
3213 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3214 EnterCriticalSection( &req
->read_section
);
3215 notify_received
= TRUE
;
3217 res
= refill_read_buffer(req
, allow_blocking
, &avail
);
3220 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3221 hdr
->dwError
= ERROR_SUCCESS
;
3223 error
= hdr
->dwError
;
3225 LeaveCriticalSection( &req
->read_section
);
3227 res
= WSAEWOULDBLOCK
;
3230 if(res
== WSAEWOULDBLOCK
)
3231 return async_read(req
, NULL
, 0, 0, available
);
3233 if (res
!= ERROR_SUCCESS
)
3238 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3239 &avail
, sizeof(avail
));
3243 static DWORD
HTTPREQ_LockRequestFile(object_header_t
*hdr
, req_file_t
**ret
)
3245 http_request_t
*req
= (http_request_t
*)hdr
;
3247 TRACE("(%p)\n", req
);
3249 if(!req
->req_file
) {
3250 WARN("No cache file name available\n");
3251 return ERROR_FILE_NOT_FOUND
;
3254 *ret
= req_file_addref(req
->req_file
);
3255 return ERROR_SUCCESS
;
3258 static const object_vtbl_t HTTPREQVtbl
= {
3260 HTTPREQ_CloseConnection
,
3261 HTTPREQ_QueryOption
,
3265 HTTPREQ_QueryDataAvailable
,
3267 HTTPREQ_LockRequestFile
3270 /***********************************************************************
3271 * HTTP_HttpOpenRequestW (internal)
3273 * Open a HTTP request handle
3276 * HINTERNET a HTTP request handle on success
3280 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3281 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3282 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3283 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3285 appinfo_t
*hIC
= session
->appInfo
;
3286 http_request_t
*request
;
3291 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3293 return ERROR_OUTOFMEMORY
;
3295 request
->hdr
.htype
= WH_HHTTPREQ
;
3296 request
->hdr
.dwFlags
= dwFlags
;
3297 request
->hdr
.dwContext
= dwContext
;
3298 request
->contentLength
= ~0u;
3300 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3301 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3302 request
->connect_timeout
= session
->connect_timeout
;
3303 request
->send_timeout
= session
->send_timeout
;
3304 request
->receive_timeout
= session
->receive_timeout
;
3306 InitializeCriticalSection( &request
->headers_section
);
3307 request
->headers_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.headers_section");
3309 InitializeCriticalSection( &request
->read_section
);
3310 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3312 WININET_AddRef( &session
->hdr
);
3313 request
->session
= session
;
3314 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3316 port
= session
->hostPort
;
3317 if (port
== INTERNET_INVALID_PORT_NUMBER
)
3318 port
= (session
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ?
3319 INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
;
3321 request
->server
= get_server(substrz(session
->hostName
), port
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3322 if(!request
->server
) {
3323 WININET_Release(&request
->hdr
);
3324 return ERROR_OUTOFMEMORY
;
3327 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3328 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3329 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3330 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3332 if (lpszObjectName
&& *lpszObjectName
) {
3337 rc
= UrlCanonicalizeW(lpszObjectName
, &dummy
, &len
, URL_ESCAPE_SPACES_ONLY
);
3338 if (rc
!= E_POINTER
)
3339 len
= strlenW(lpszObjectName
)+1;
3340 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3341 rc
= UrlCanonicalizeW(lpszObjectName
, request
->path
, &len
,
3342 URL_ESCAPE_SPACES_ONLY
);
3345 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3346 strcpyW(request
->path
,lpszObjectName
);
3349 static const WCHAR slashW
[] = {'/',0};
3351 request
->path
= heap_strdupW(slashW
);
3354 if (lpszReferrer
&& *lpszReferrer
)
3355 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3357 if (lpszAcceptTypes
)
3360 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3362 if (!*lpszAcceptTypes
[i
]) continue;
3363 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3364 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3365 HTTP_ADDHDR_FLAG_REQ
|
3366 (i
== 0 ? (HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
) : 0));
3370 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3371 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3373 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3374 HTTP_DealWithProxy( hIC
, session
, request
);
3376 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3377 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3380 TRACE("<-- (%p)\n", request
);
3382 *ret
= request
->hdr
.hInternet
;
3383 return ERROR_SUCCESS
;
3386 /***********************************************************************
3387 * HttpOpenRequestW (WININET.@)
3389 * Open a HTTP request handle
3392 * HINTERNET a HTTP request handle on success
3396 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3397 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3398 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3399 DWORD dwFlags
, DWORD_PTR dwContext
)
3401 http_session_t
*session
;
3402 HINTERNET handle
= NULL
;
3405 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3406 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3407 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3408 dwFlags
, dwContext
);
3409 if(lpszAcceptTypes
!=NULL
)
3412 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3413 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3416 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3417 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3419 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3424 * My tests seem to show that the windows version does not
3425 * become asynchronous until after this point. And anyhow
3426 * if this call was asynchronous then how would you get the
3427 * necessary HINTERNET pointer returned by this function.
3430 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3431 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3432 dwFlags
, dwContext
, &handle
);
3435 WININET_Release( &session
->hdr
);
3436 TRACE("returning %p\n", handle
);
3437 if(res
!= ERROR_SUCCESS
)
3442 static const LPCWSTR header_lookup
[] = {
3443 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3444 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3445 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3446 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3447 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3448 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3449 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3450 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3451 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3452 szDate
, /* HTTP_QUERY_DATE = 9 */
3453 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3454 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3455 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3456 szURI
, /* HTTP_QUERY_URI = 13 */
3457 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3458 NULL
, /* HTTP_QUERY_COST = 15 */
3459 NULL
, /* HTTP_QUERY_LINK = 16 */
3460 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3461 NULL
, /* HTTP_QUERY_VERSION = 18 */
3462 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3463 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3464 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3465 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3466 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3467 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3468 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3469 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3470 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3471 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3472 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3473 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3474 NULL
, /* HTTP_QUERY_FROM = 31 */
3475 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3476 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3477 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3478 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3479 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3480 szServer
, /* HTTP_QUERY_SERVER = 37 */
3481 NULL
, /* HTTP_TITLE = 38 */
3482 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3483 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3484 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3485 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3486 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3487 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3488 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3489 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3490 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3491 szAge
, /* HTTP_QUERY_AGE = 48 */
3492 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3493 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3494 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3495 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3496 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3497 szETag
, /* HTTP_QUERY_ETAG = 54 */
3498 hostW
, /* HTTP_QUERY_HOST = 55 */
3499 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3500 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3501 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3502 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3503 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3504 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3505 szRange
, /* HTTP_QUERY_RANGE = 62 */
3506 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3507 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3508 szVary
, /* HTTP_QUERY_VARY = 65 */
3509 szVia
, /* HTTP_QUERY_VIA = 66 */
3510 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3511 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3512 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3513 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3516 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3518 /***********************************************************************
3519 * HTTP_HttpQueryInfoW (internal)
3521 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3522 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3524 LPHTTPHEADERW lphttpHdr
= NULL
;
3525 BOOL request_only
= !!(dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
);
3526 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3527 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3530 EnterCriticalSection( &request
->headers_section
);
3532 /* Find requested header structure */
3535 case HTTP_QUERY_CUSTOM
:
3538 LeaveCriticalSection( &request
->headers_section
);
3539 return ERROR_INVALID_PARAMETER
;
3541 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3543 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3547 DWORD res
= ERROR_INVALID_PARAMETER
;
3550 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3552 headers
= build_response_header(request
, TRUE
);
3555 LeaveCriticalSection( &request
->headers_section
);
3556 return ERROR_OUTOFMEMORY
;
3559 len
= strlenW(headers
) * sizeof(WCHAR
);
3560 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3562 len
+= sizeof(WCHAR
);
3563 res
= ERROR_INSUFFICIENT_BUFFER
;
3567 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3568 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3569 res
= ERROR_SUCCESS
;
3571 *lpdwBufferLength
= len
;
3574 LeaveCriticalSection( &request
->headers_section
);
3577 case HTTP_QUERY_RAW_HEADERS
:
3583 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3585 headers
= build_response_header(request
, FALSE
);
3589 LeaveCriticalSection( &request
->headers_section
);
3590 return ERROR_OUTOFMEMORY
;
3593 len
= strlenW(headers
) * sizeof(WCHAR
);
3594 if (len
> *lpdwBufferLength
)
3596 *lpdwBufferLength
= len
;
3598 LeaveCriticalSection( &request
->headers_section
);
3599 return ERROR_INSUFFICIENT_BUFFER
;
3606 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3608 for (i
= 0; i
< len
/ sizeof(WCHAR
); i
++)
3610 if (headers
[i
] == '\n')
3613 memcpy(lpBuffer
, headers
, len
);
3615 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3618 LeaveCriticalSection( &request
->headers_section
);
3619 return ERROR_SUCCESS
;
3621 case HTTP_QUERY_STATUS_TEXT
:
3622 if (request
->statusText
)
3624 DWORD len
= strlenW(request
->statusText
);
3625 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3627 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3628 LeaveCriticalSection( &request
->headers_section
);
3629 return ERROR_INSUFFICIENT_BUFFER
;
3633 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3634 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3636 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3637 LeaveCriticalSection( &request
->headers_section
);
3638 return ERROR_SUCCESS
;
3641 case HTTP_QUERY_VERSION
:
3642 if (request
->version
)
3644 DWORD len
= strlenW(request
->version
);
3645 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3647 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3648 LeaveCriticalSection( &request
->headers_section
);
3649 return ERROR_INSUFFICIENT_BUFFER
;
3653 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3654 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3656 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3657 LeaveCriticalSection( &request
->headers_section
);
3658 return ERROR_SUCCESS
;
3661 case HTTP_QUERY_CONTENT_ENCODING
:
3662 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3663 requested_index
,request_only
);
3665 case HTTP_QUERY_STATUS_CODE
: {
3666 DWORD res
= ERROR_SUCCESS
;
3670 LeaveCriticalSection( &request
->headers_section
);
3671 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3677 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3678 if(*lpdwBufferLength
>= sizeof(DWORD
))
3679 *(DWORD
*)lpBuffer
= request
->status_code
;
3681 res
= ERROR_INSUFFICIENT_BUFFER
;
3682 *lpdwBufferLength
= sizeof(DWORD
);
3686 static const WCHAR formatW
[] = {'%','u',0};
3688 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3690 if(size
<= *lpdwBufferLength
) {
3691 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3693 size
+= sizeof(WCHAR
);
3694 res
= ERROR_INSUFFICIENT_BUFFER
;
3697 *lpdwBufferLength
= size
;
3699 LeaveCriticalSection( &request
->headers_section
);
3703 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3705 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3706 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3707 requested_index
,request_only
);
3711 lphttpHdr
= &request
->custHeaders
[index
];
3713 /* Ensure header satisfies requested attributes */
3715 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3716 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3718 LeaveCriticalSection( &request
->headers_section
);
3719 return ERROR_HTTP_HEADER_NOT_FOUND
;
3722 /* coalesce value to requested type */
3723 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3725 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3726 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3728 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3734 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3736 tmpTM
= *gmtime(&tmpTime
);
3737 STHook
= (SYSTEMTIME
*)lpBuffer
;
3738 STHook
->wDay
= tmpTM
.tm_mday
;
3739 STHook
->wHour
= tmpTM
.tm_hour
;
3740 STHook
->wMilliseconds
= 0;
3741 STHook
->wMinute
= tmpTM
.tm_min
;
3742 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3743 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3744 STHook
->wSecond
= tmpTM
.tm_sec
;
3745 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3747 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3748 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3749 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3751 else if (lphttpHdr
->lpszValue
)
3753 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3755 if (len
> *lpdwBufferLength
)
3757 *lpdwBufferLength
= len
;
3758 LeaveCriticalSection( &request
->headers_section
);
3759 return ERROR_INSUFFICIENT_BUFFER
;
3763 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3764 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3766 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3768 if (lpdwIndex
) (*lpdwIndex
)++;
3770 LeaveCriticalSection( &request
->headers_section
);
3771 return ERROR_SUCCESS
;
3774 /***********************************************************************
3775 * HttpQueryInfoW (WININET.@)
3777 * Queries for information about an HTTP request
3784 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3785 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3787 http_request_t
*request
;
3790 if (TRACE_ON(wininet
)) {
3791 #define FE(x) { x, #x }
3792 static const wininet_flag_info query_flags
[] = {
3793 FE(HTTP_QUERY_MIME_VERSION
),
3794 FE(HTTP_QUERY_CONTENT_TYPE
),
3795 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3796 FE(HTTP_QUERY_CONTENT_ID
),
3797 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3798 FE(HTTP_QUERY_CONTENT_LENGTH
),
3799 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3800 FE(HTTP_QUERY_ALLOW
),
3801 FE(HTTP_QUERY_PUBLIC
),
3802 FE(HTTP_QUERY_DATE
),
3803 FE(HTTP_QUERY_EXPIRES
),
3804 FE(HTTP_QUERY_LAST_MODIFIED
),
3805 FE(HTTP_QUERY_MESSAGE_ID
),
3807 FE(HTTP_QUERY_DERIVED_FROM
),
3808 FE(HTTP_QUERY_COST
),
3809 FE(HTTP_QUERY_LINK
),
3810 FE(HTTP_QUERY_PRAGMA
),
3811 FE(HTTP_QUERY_VERSION
),
3812 FE(HTTP_QUERY_STATUS_CODE
),
3813 FE(HTTP_QUERY_STATUS_TEXT
),
3814 FE(HTTP_QUERY_RAW_HEADERS
),
3815 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3816 FE(HTTP_QUERY_CONNECTION
),
3817 FE(HTTP_QUERY_ACCEPT
),
3818 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3819 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3820 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3821 FE(HTTP_QUERY_AUTHORIZATION
),
3822 FE(HTTP_QUERY_CONTENT_ENCODING
),
3823 FE(HTTP_QUERY_FORWARDED
),
3824 FE(HTTP_QUERY_FROM
),
3825 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3826 FE(HTTP_QUERY_LOCATION
),
3827 FE(HTTP_QUERY_ORIG_URI
),
3828 FE(HTTP_QUERY_REFERER
),
3829 FE(HTTP_QUERY_RETRY_AFTER
),
3830 FE(HTTP_QUERY_SERVER
),
3831 FE(HTTP_QUERY_TITLE
),
3832 FE(HTTP_QUERY_USER_AGENT
),
3833 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3834 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3835 FE(HTTP_QUERY_ACCEPT_RANGES
),
3836 FE(HTTP_QUERY_SET_COOKIE
),
3837 FE(HTTP_QUERY_COOKIE
),
3838 FE(HTTP_QUERY_REQUEST_METHOD
),
3839 FE(HTTP_QUERY_REFRESH
),
3840 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3842 FE(HTTP_QUERY_CACHE_CONTROL
),
3843 FE(HTTP_QUERY_CONTENT_BASE
),
3844 FE(HTTP_QUERY_CONTENT_LOCATION
),
3845 FE(HTTP_QUERY_CONTENT_MD5
),
3846 FE(HTTP_QUERY_CONTENT_RANGE
),
3847 FE(HTTP_QUERY_ETAG
),
3848 FE(HTTP_QUERY_HOST
),
3849 FE(HTTP_QUERY_IF_MATCH
),
3850 FE(HTTP_QUERY_IF_NONE_MATCH
),
3851 FE(HTTP_QUERY_IF_RANGE
),
3852 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3853 FE(HTTP_QUERY_MAX_FORWARDS
),
3854 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3855 FE(HTTP_QUERY_RANGE
),
3856 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3857 FE(HTTP_QUERY_UPGRADE
),
3858 FE(HTTP_QUERY_VARY
),
3860 FE(HTTP_QUERY_WARNING
),
3861 FE(HTTP_QUERY_CUSTOM
)
3863 static const wininet_flag_info modifier_flags
[] = {
3864 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3865 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3866 FE(HTTP_QUERY_FLAG_NUMBER
),
3867 FE(HTTP_QUERY_FLAG_COALESCE
)
3870 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3871 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3874 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3875 TRACE(" Attribute:");
3876 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3877 if (query_flags
[i
].val
== info
) {
3878 TRACE(" %s", query_flags
[i
].name
);
3882 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3883 TRACE(" Unknown (%08x)", info
);
3886 TRACE(" Modifier:");
3887 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3888 if (modifier_flags
[i
].val
& info_mod
) {
3889 TRACE(" %s", modifier_flags
[i
].name
);
3890 info_mod
&= ~ modifier_flags
[i
].val
;
3895 TRACE(" Unknown (%08x)", info_mod
);
3900 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3901 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3903 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3907 if (lpBuffer
== NULL
)
3908 *lpdwBufferLength
= 0;
3909 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3910 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3914 WININET_Release( &request
->hdr
);
3916 TRACE("%u <--\n", res
);
3917 if(res
!= ERROR_SUCCESS
)
3919 return res
== ERROR_SUCCESS
;
3922 /***********************************************************************
3923 * HttpQueryInfoA (WININET.@)
3925 * Queries for information about an HTTP request
3932 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3933 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3939 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
3941 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3942 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3944 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3945 lpdwBufferLength
, lpdwIndex
);
3951 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
3952 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3954 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
3960 bufferW
= heap_alloc(alloclen
);
3961 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3962 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3963 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
3970 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
3974 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
3975 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
3976 *lpdwBufferLength
= len
- 1;
3978 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
3981 /* since the strings being returned from HttpQueryInfoW should be
3982 * only ASCII characters, it is reasonable to assume that all of
3983 * the Unicode characters can be reduced to a single byte */
3984 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
3986 heap_free( bufferW
);
3990 static WCHAR
*get_redirect_url(http_request_t
*request
)
3992 static WCHAR szHttp
[] = {'h','t','t','p',0};
3993 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
3994 http_session_t
*session
= request
->session
;
3995 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
3996 WCHAR
*orig_url
= NULL
, *redirect_url
= NULL
, *combined_url
= NULL
;
3997 DWORD url_length
= 0, res
;
4001 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
4002 if(res
== ERROR_INSUFFICIENT_BUFFER
) {
4003 redirect_url
= heap_alloc(url_length
);
4004 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
4006 if(res
!= ERROR_SUCCESS
) {
4007 heap_free(redirect_url
);
4011 urlComponents
.dwSchemeLength
= 1;
4012 b
= InternetCrackUrlW(redirect_url
, url_length
/ sizeof(WCHAR
), 0, &urlComponents
);
4013 if(b
&& urlComponents
.dwSchemeLength
&&
4014 urlComponents
.nScheme
!= INTERNET_SCHEME_HTTP
&& urlComponents
.nScheme
!= INTERNET_SCHEME_HTTPS
) {
4015 TRACE("redirect to non-http URL\n");
4019 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
4020 urlComponents
.dwSchemeLength
= 0;
4021 urlComponents
.lpszHostName
= request
->server
->name
;
4022 urlComponents
.nPort
= request
->server
->port
;
4023 urlComponents
.lpszUserName
= session
->userName
;
4024 urlComponents
.lpszUrlPath
= request
->path
;
4026 b
= InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
);
4027 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4028 orig_url
= heap_alloc(url_length
);
4030 /* convert from bytes to characters */
4031 url_length
= url_length
/ sizeof(WCHAR
) - 1;
4032 b
= InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
);
4037 b
= InternetCombineUrlW(orig_url
, redirect_url
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4038 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4039 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
4040 b
= InternetCombineUrlW(orig_url
, redirect_url
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4042 heap_free(combined_url
);
4043 combined_url
= NULL
;
4048 heap_free(orig_url
);
4049 heap_free(redirect_url
);
4050 return combined_url
;
4054 /***********************************************************************
4055 * HTTP_HandleRedirect (internal)
4057 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, WCHAR
*url
)
4059 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
4060 http_session_t
*session
= request
->session
;
4061 size_t url_len
= strlenW(url
);
4065 /* if it's an absolute path, keep the same session info */
4066 urlComponents
.lpszUrlPath
= url
;
4067 urlComponents
.dwUrlPathLength
= url_len
;
4071 urlComponents
.dwHostNameLength
= 1;
4072 urlComponents
.dwUserNameLength
= 1;
4073 urlComponents
.dwUrlPathLength
= 1;
4074 if(!InternetCrackUrlW(url
, url_len
, 0, &urlComponents
))
4075 return INTERNET_GetLastError();
4077 if(!urlComponents
.dwHostNameLength
)
4078 return ERROR_INTERNET_INVALID_URL
;
4081 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
4082 url
, (url_len
+ 1) * sizeof(WCHAR
));
4084 if(urlComponents
.dwHostNameLength
) {
4085 BOOL custom_port
= FALSE
;
4088 if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTP
) {
4089 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4090 TRACE("redirect from secure page to non-secure page\n");
4091 /* FIXME: warn about from secure redirect to non-secure page */
4092 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4095 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
;
4096 }else if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
) {
4097 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4098 TRACE("redirect from non-secure page to secure page\n");
4099 /* FIXME: notify about redirect to secure page */
4100 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4103 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
;
4106 heap_free(session
->hostName
);
4108 session
->hostName
= heap_strndupW(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4109 session
->hostPort
= urlComponents
.nPort
;
4111 heap_free(session
->userName
);
4112 session
->userName
= NULL
;
4113 if (urlComponents
.dwUserNameLength
)
4114 session
->userName
= heap_strndupW(urlComponents
.lpszUserName
, urlComponents
.dwUserNameLength
);
4116 reset_data_stream(request
);
4118 host
= substr(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4120 if(host
.len
!= strlenW(request
->server
->name
) || strncmpiW(request
->server
->name
, host
.str
, host
.len
)
4121 || request
->server
->port
!= urlComponents
.nPort
) {
4122 server_t
*new_server
;
4124 new_server
= get_server(host
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4125 server_release(request
->server
);
4126 request
->server
= new_server
;
4130 HTTP_ProcessHeader(request
, hostW
, request
->server
->host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4132 HTTP_ProcessHeader(request
, hostW
, request
->server
->name
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4135 heap_free(request
->path
);
4136 request
->path
= NULL
;
4137 if(urlComponents
.dwUrlPathLength
)
4144 path
= heap_strndupW(urlComponents
.lpszUrlPath
, urlComponents
.dwUrlPathLength
);
4145 rc
= UrlEscapeW(path
, &dummy
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4146 if (rc
!= E_POINTER
)
4147 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4148 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4149 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4150 URL_ESCAPE_SPACES_ONLY
);
4153 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4154 strcpyW(request
->path
, path
);
4159 /* Remove custom content-type/length headers on redirects. */
4160 remove_header(request
, szContent_Type
, TRUE
);
4161 remove_header(request
, szContent_Length
, TRUE
);
4163 return ERROR_SUCCESS
;
4166 /***********************************************************************
4167 * HTTP_build_req (internal)
4169 * concatenate all the strings in the request together
4171 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4176 for( t
= list
; *t
; t
++ )
4177 len
+= strlenW( *t
);
4180 str
= heap_alloc(len
*sizeof(WCHAR
));
4183 for( t
= list
; *t
; t
++ )
4189 static void HTTP_InsertCookies(http_request_t
*request
)
4194 res
= get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4195 if(res
!= ERROR_SUCCESS
|| !cookies
)
4198 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
),
4199 HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
4203 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4205 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4213 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4214 if (!strcmpiW(day
, days
[i
]))
4221 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4223 static const WCHAR jan
[] = { 'j','a','n',0 };
4224 static const WCHAR feb
[] = { 'f','e','b',0 };
4225 static const WCHAR mar
[] = { 'm','a','r',0 };
4226 static const WCHAR apr
[] = { 'a','p','r',0 };
4227 static const WCHAR may
[] = { 'm','a','y',0 };
4228 static const WCHAR jun
[] = { 'j','u','n',0 };
4229 static const WCHAR jul
[] = { 'j','u','l',0 };
4230 static const WCHAR aug
[] = { 'a','u','g',0 };
4231 static const WCHAR sep
[] = { 's','e','p',0 };
4232 static const WCHAR oct
[] = { 'o','c','t',0 };
4233 static const WCHAR nov
[] = { 'n','o','v',0 };
4234 static const WCHAR dec
[] = { 'd','e','c',0 };
4236 if (!strcmpiW(month
, jan
)) return 1;
4237 if (!strcmpiW(month
, feb
)) return 2;
4238 if (!strcmpiW(month
, mar
)) return 3;
4239 if (!strcmpiW(month
, apr
)) return 4;
4240 if (!strcmpiW(month
, may
)) return 5;
4241 if (!strcmpiW(month
, jun
)) return 6;
4242 if (!strcmpiW(month
, jul
)) return 7;
4243 if (!strcmpiW(month
, aug
)) return 8;
4244 if (!strcmpiW(month
, sep
)) return 9;
4245 if (!strcmpiW(month
, oct
)) return 10;
4246 if (!strcmpiW(month
, nov
)) return 11;
4247 if (!strcmpiW(month
, dec
)) return 12;
4252 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4253 * optionally preceded by whitespace.
4254 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4255 * st, and sets *str to the first character after the time format.
4257 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4263 while (isspaceW(*ptr
))
4266 num
= strtoulW(ptr
, &nextPtr
, 10);
4267 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4269 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4274 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4278 st
->wHour
= (WORD
)num
;
4279 num
= strtoulW(ptr
, &nextPtr
, 10);
4280 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4282 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4287 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4291 st
->wMinute
= (WORD
)num
;
4292 num
= strtoulW(ptr
, &nextPtr
, 10);
4293 if (!nextPtr
|| nextPtr
<= ptr
)
4295 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4300 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4305 st
->wSecond
= (WORD
)num
;
4309 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4311 static const WCHAR gmt
[]= { 'G','M','T',0 };
4312 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4314 SYSTEMTIME st
= { 0 };
4317 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4318 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4321 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4322 if (st
.wDayOfWeek
>= 7)
4324 ERR("unexpected weekday %s\n", debugstr_w(day
));
4328 while (isspaceW(*ptr
))
4331 for (monthPtr
= month
; !isspaceW(*ptr
) &&
4332 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4336 st
.wMonth
= HTTP_ParseMonth(month
);
4337 if (!st
.wMonth
|| st
.wMonth
> 12)
4339 ERR("unexpected month %s\n", debugstr_w(month
));
4343 while (isspaceW(*ptr
))
4346 num
= strtoulW(ptr
, &nextPtr
, 10);
4347 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4349 ERR("unexpected day %s\n", debugstr_w(ptr
));
4353 st
.wDay
= (WORD
)num
;
4355 while (isspaceW(*ptr
))
4358 if (!HTTP_ParseTime(&st
, &ptr
))
4361 while (isspaceW(*ptr
))
4364 num
= strtoulW(ptr
, &nextPtr
, 10);
4365 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4367 ERR("unexpected year %s\n", debugstr_w(ptr
));
4371 st
.wYear
= (WORD
)num
;
4373 while (isspaceW(*ptr
))
4376 /* asctime() doesn't report a timezone, but some web servers do, so accept
4377 * with or without GMT.
4379 if (*ptr
&& strcmpW(ptr
, gmt
))
4381 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4384 return SystemTimeToFileTime(&st
, ft
);
4387 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4389 static const WCHAR gmt
[]= { 'G','M','T',0 };
4390 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4393 SYSTEMTIME st
= { 0 };
4395 ptr
= strchrW(value
, ',');
4398 if (ptr
- value
!= 3)
4400 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4403 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4405 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4406 if (st
.wDayOfWeek
> 6)
4408 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4413 while (isspaceW(*ptr
))
4416 num
= strtoulW(ptr
, &nextPtr
, 10);
4417 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4419 WARN("unexpected day %s\n", debugstr_w(value
));
4423 st
.wDay
= (WORD
)num
;
4425 while (isspaceW(*ptr
))
4428 for (monthPtr
= month
; !isspaceW(*ptr
) &&
4429 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4433 st
.wMonth
= HTTP_ParseMonth(month
);
4434 if (!st
.wMonth
|| st
.wMonth
> 12)
4436 WARN("unexpected month %s\n", debugstr_w(month
));
4440 while (isspaceW(*ptr
))
4443 num
= strtoulW(ptr
, &nextPtr
, 10);
4444 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4446 ERR("unexpected year %s\n", debugstr_w(value
));
4450 st
.wYear
= (WORD
)num
;
4452 if (!HTTP_ParseTime(&st
, &ptr
))
4455 while (isspaceW(*ptr
))
4458 if (strcmpW(ptr
, gmt
))
4460 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4463 return SystemTimeToFileTime(&st
, ft
);
4466 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4468 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4469 { 'm','o','n','d','a','y',0 },
4470 { 't','u','e','s','d','a','y',0 },
4471 { 'w','e','d','n','e','s','d','a','y',0 },
4472 { 't','h','u','r','s','d','a','y',0 },
4473 { 'f','r','i','d','a','y',0 },
4474 { 's','a','t','u','r','d','a','y',0 }};
4476 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4477 if (!strcmpiW(day
, days
[i
]))
4484 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4486 static const WCHAR gmt
[]= { 'G','M','T',0 };
4487 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4490 SYSTEMTIME st
= { 0 };
4492 ptr
= strchrW(value
, ',');
4495 if (ptr
- value
== 3)
4497 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4499 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4500 if (st
.wDayOfWeek
> 6)
4502 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4506 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4508 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4509 day
[ptr
- value
+ 1] = 0;
4510 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4511 if (st
.wDayOfWeek
> 6)
4513 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4519 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4524 while (isspaceW(*ptr
))
4527 num
= strtoulW(ptr
, &nextPtr
, 10);
4528 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4530 ERR("unexpected day %s\n", debugstr_w(value
));
4534 st
.wDay
= (WORD
)num
;
4538 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4543 for (monthPtr
= month
; *ptr
!= '-' &&
4544 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4548 st
.wMonth
= HTTP_ParseMonth(month
);
4549 if (!st
.wMonth
|| st
.wMonth
> 12)
4551 ERR("unexpected month %s\n", debugstr_w(month
));
4557 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4562 num
= strtoulW(ptr
, &nextPtr
, 10);
4563 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4565 ERR("unexpected year %s\n", debugstr_w(value
));
4569 st
.wYear
= (WORD
)num
;
4571 if (!HTTP_ParseTime(&st
, &ptr
))
4574 while (isspaceW(*ptr
))
4577 if (strcmpW(ptr
, gmt
))
4579 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4582 return SystemTimeToFileTime(&st
, ft
);
4585 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4587 static const WCHAR zero
[] = { '0',0 };
4590 if (!strcmpW(value
, zero
))
4592 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4595 else if (strchrW(value
, ','))
4597 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4600 ret
= HTTP_ParseRfc850Date(value
, ft
);
4602 ERR("unexpected date format %s\n", debugstr_w(value
));
4607 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4609 ERR("unexpected date format %s\n", debugstr_w(value
));
4614 static void HTTP_ProcessExpires(http_request_t
*request
)
4616 BOOL expirationFound
= FALSE
;
4619 EnterCriticalSection( &request
->headers_section
);
4621 /* Look for a Cache-Control header with a max-age directive, as it takes
4622 * precedence over the Expires header.
4624 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4625 if (headerIndex
!= -1)
4627 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4630 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4632 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4637 end
= ptr
+ strlenW(ptr
);
4638 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4642 static const WCHAR max_age
[] = {
4643 'm','a','x','-','a','g','e',0 };
4645 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4650 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4651 if (nextPtr
> equal
+ 1)
4655 NtQuerySystemTime( &ft
);
4656 /* Age is in seconds, FILETIME resolution is in
4657 * 100 nanosecond intervals.
4659 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4660 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4661 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4662 expirationFound
= TRUE
;
4669 while (isspaceW(*ptr
))
4676 if (!expirationFound
)
4678 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4679 if (headerIndex
!= -1)
4681 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4684 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4686 expirationFound
= TRUE
;
4687 request
->expires
= ft
;
4691 if (!expirationFound
)
4695 /* With no known age, default to 10 minutes until expiration. */
4696 NtQuerySystemTime( &t
);
4697 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4698 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4699 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4702 LeaveCriticalSection( &request
->headers_section
);
4705 static void HTTP_ProcessLastModified(http_request_t
*request
)
4709 EnterCriticalSection( &request
->headers_section
);
4711 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4712 if (headerIndex
!= -1)
4714 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4717 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4718 request
->last_modified
= ft
;
4721 LeaveCriticalSection( &request
->headers_section
);
4724 static void http_process_keep_alive(http_request_t
*req
)
4728 EnterCriticalSection( &req
->headers_section
);
4730 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4731 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4732 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4733 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4735 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4737 LeaveCriticalSection( &req
->headers_section
);
4740 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4742 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4743 netconn_t
*netconn
= NULL
;
4746 if (request
->netconn
)
4748 if (NETCON_is_alive(request
->netconn
) && drain_content(request
, TRUE
) == ERROR_SUCCESS
)
4750 reset_data_stream(request
);
4752 return ERROR_SUCCESS
;
4755 TRACE("freeing netconn\n");
4756 free_netconn(request
->netconn
);
4757 request
->netconn
= NULL
;
4760 reset_data_stream(request
);
4762 res
= HTTP_ResolveName(request
);
4763 if(res
!= ERROR_SUCCESS
)
4766 EnterCriticalSection(&connection_pool_cs
);
4768 while(!list_empty(&request
->server
->conn_pool
)) {
4769 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4770 list_remove(&netconn
->pool_entry
);
4772 if(is_valid_netconn(netconn
) && NETCON_is_alive(netconn
))
4775 TRACE("connection %p closed during idle\n", netconn
);
4776 free_netconn(netconn
);
4780 LeaveCriticalSection(&connection_pool_cs
);
4783 TRACE("<-- reusing %p netconn\n", netconn
);
4784 request
->netconn
= netconn
;
4786 return ERROR_SUCCESS
;
4789 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4790 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4792 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4793 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4794 request
->server
->addr_str
,
4795 strlen(request
->server
->addr_str
)+1);
4797 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4798 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4799 request
->connect_timeout
, &netconn
);
4800 if(res
!= ERROR_SUCCESS
) {
4801 ERR("create_netconn failed: %u\n", res
);
4805 request
->netconn
= netconn
;
4807 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4808 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4809 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4812 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4813 return ERROR_SUCCESS
;
4816 static char *build_ascii_request( const WCHAR
*str
, void *data
, DWORD data_len
, DWORD
*out_len
)
4818 int len
= WideCharToMultiByte( CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
4821 if (!(ret
= heap_alloc( len
+ data_len
))) return NULL
;
4822 WideCharToMultiByte( CP_ACP
, 0, str
, -1, ret
, len
, NULL
, NULL
);
4823 if (data_len
) memcpy( ret
+ len
- 1, data
, data_len
);
4824 *out_len
= len
+ data_len
- 1;
4829 static void set_content_length_header( http_request_t
*request
, DWORD len
, DWORD flags
)
4831 static const WCHAR fmtW
[] =
4832 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4833 WCHAR buf
[sizeof(fmtW
)/sizeof(fmtW
[0]) + 10];
4835 sprintfW( buf
, fmtW
, len
);
4836 HTTP_HttpAddRequestHeadersW( request
, buf
, ~0u, flags
);
4839 /***********************************************************************
4840 * HTTP_HttpSendRequestW (internal)
4842 * Sends the specified request to the HTTP server
4845 * ERROR_SUCCESS on success
4846 * win32 error code on failure
4849 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4850 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4851 DWORD dwContentLength
, BOOL bEndRequest
)
4853 BOOL redirected
= FALSE
, secure_proxy_connect
= FALSE
, loop_next
;
4854 WCHAR
*request_header
= NULL
;
4855 INT responseLen
, cnt
;
4858 TRACE("--> %p\n", request
);
4860 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4862 /* if the verb is NULL default to GET */
4864 request
->verb
= heap_strdupW(szGET
);
4866 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
,
4867 HTTP_ADDREQ_FLAG_ADD_IF_NEW
| HTTP_ADDHDR_FLAG_REQ
);
4869 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4871 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4872 request
->bytesToWrite
= dwContentLength
;
4874 if (request
->session
->appInfo
->agent
)
4876 WCHAR
*agent_header
;
4877 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4880 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4881 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4882 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4884 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4885 heap_free(agent_header
);
4887 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4889 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4890 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4892 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4894 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4895 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4896 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4899 /* add the headers the caller supplied */
4900 if( lpszHeaders
&& dwHeaderLength
)
4901 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4905 DWORD len
, data_len
= dwOptionalLength
;
4906 BOOL reusing_connection
;
4912 request
->contentLength
= ~0u;
4913 request
->bytesToWrite
= 0;
4916 if (TRACE_ON(wininet
))
4920 EnterCriticalSection( &request
->headers_section
);
4921 host
= HTTP_GetHeader( request
, hostW
);
4922 TRACE("Going to url %s %s\n", debugstr_w(host
->lpszValue
), debugstr_w(request
->path
));
4923 LeaveCriticalSection( &request
->headers_section
);
4926 HTTP_FixURL(request
);
4927 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4929 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
,
4930 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
4932 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4933 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4935 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4936 HTTP_InsertCookies(request
);
4938 res
= open_http_connection(request
, &reusing_connection
);
4939 if (res
!= ERROR_SUCCESS
)
4942 if (!reusing_connection
&& (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4944 if (request
->proxy
) secure_proxy_connect
= TRUE
;
4947 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4948 if (res
!= ERROR_SUCCESS
)
4950 WARN("failed to upgrade to secure connection\n");
4951 http_release_netconn(request
, FALSE
);
4956 if (secure_proxy_connect
)
4958 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
4959 const WCHAR
*target
= request
->server
->host_port
;
4961 if (HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
4962 set_content_length_header(request
, 0, HTTP_ADDREQ_FLAG_REPLACE
);
4964 request_header
= build_request_header(request
, connectW
, target
, g_szHttp1_1
, TRUE
);
4966 else if (request
->proxy
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4968 WCHAR
*url
= build_proxy_path_url(request
);
4969 request_header
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
4974 if (request
->proxy
&& HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
4975 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_REPLACE
);
4977 request_header
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
4980 TRACE("Request header -> %s\n", debugstr_w(request_header
) );
4982 /* send the request as ASCII, tack on the optional data */
4983 if (!lpOptional
|| redirected
|| secure_proxy_connect
)
4986 ascii_req
= build_ascii_request(request_header
, lpOptional
, data_len
, &len
);
4987 heap_free(request_header
);
4988 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
4990 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4991 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
4993 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
4994 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
4995 heap_free( ascii_req
);
4996 if(res
!= ERROR_SUCCESS
) {
4997 TRACE("send failed: %u\n", res
);
4998 if(!reusing_connection
)
5000 http_release_netconn(request
, FALSE
);
5005 request
->bytesWritten
= data_len
;
5007 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5008 INTERNET_STATUS_REQUEST_SENT
,
5009 &len
, sizeof(DWORD
));
5015 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5016 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5018 if (HTTP_GetResponseHeaders(request
, &responseLen
))
5020 http_release_netconn(request
, FALSE
);
5021 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
5024 /* FIXME: We should know that connection is closed before sending
5025 * headers. Otherwise wrong callbacks are executed */
5026 if(!responseLen
&& reusing_connection
) {
5027 TRACE("Connection closed by server, reconnecting\n");
5028 http_release_netconn(request
, FALSE
);
5033 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5034 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
5037 http_process_keep_alive(request
);
5038 HTTP_ProcessCookies(request
);
5039 HTTP_ProcessExpires(request
);
5040 HTTP_ProcessLastModified(request
);
5042 res
= set_content_length(request
);
5043 if(res
!= ERROR_SUCCESS
)
5045 if(!request
->contentLength
&& !secure_proxy_connect
)
5046 http_release_netconn(request
, TRUE
);
5048 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5052 switch(request
->status_code
) {
5053 case HTTP_STATUS_REDIRECT
:
5054 case HTTP_STATUS_MOVED
:
5055 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5056 case HTTP_STATUS_REDIRECT_METHOD
:
5057 new_url
= get_redirect_url(request
);
5061 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5062 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5064 heap_free(request
->verb
);
5065 request
->verb
= heap_strdupW(szGET
);
5067 http_release_netconn(request
, drain_content(request
, FALSE
) == ERROR_SUCCESS
);
5068 res
= HTTP_HandleRedirect(request
, new_url
);
5070 if (res
== ERROR_SUCCESS
)
5075 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5077 WCHAR szAuthValue
[2048];
5079 if (request
->status_code
== HTTP_STATUS_DENIED
)
5081 WCHAR
*host
= heap_strdupW( request
->server
->canon_host_port
);
5083 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5085 if (HTTP_DoAuthorization(request
, szAuthValue
,
5087 request
->session
->userName
,
5088 request
->session
->password
, host
))
5090 if (drain_content(request
, TRUE
) != ERROR_SUCCESS
)
5092 FIXME("Could not drain content\n");
5093 http_release_netconn(request
, FALSE
);
5102 TRACE("Cleaning wrong authorization data\n");
5103 destroy_authinfo(request
->authInfo
);
5104 request
->authInfo
= NULL
;
5107 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5110 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5112 if (HTTP_DoAuthorization(request
, szAuthValue
,
5113 &request
->proxyAuthInfo
,
5114 request
->session
->appInfo
->proxyUsername
,
5115 request
->session
->appInfo
->proxyPassword
,
5118 if (drain_content(request
, TRUE
) != ERROR_SUCCESS
)
5120 FIXME("Could not drain content\n");
5121 http_release_netconn(request
, FALSE
);
5129 TRACE("Cleaning wrong proxy authorization data\n");
5130 destroy_authinfo(request
->proxyAuthInfo
);
5131 request
->proxyAuthInfo
= NULL
;
5135 if (secure_proxy_connect
&& request
->status_code
== HTTP_STATUS_OK
)
5137 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5138 if (res
!= ERROR_SUCCESS
)
5140 WARN("failed to upgrade to secure proxy connection\n");
5141 http_release_netconn( request
, FALSE
);
5144 remove_header(request
, szProxy_Authorization
, TRUE
);
5145 destroy_authinfo(request
->proxyAuthInfo
);
5146 request
->proxyAuthInfo
= NULL
;
5147 request
->contentLength
= 0;
5148 request
->netconn_stream
.content_length
= 0;
5150 secure_proxy_connect
= FALSE
;
5155 res
= ERROR_SUCCESS
;
5160 /* TODO: send notification for P3P header */
5162 if(res
== ERROR_SUCCESS
)
5163 create_cache_entry(request
);
5165 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5167 if (res
== ERROR_SUCCESS
) {
5168 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5169 HTTP_ReceiveRequestData(request
);
5171 send_request_complete(request
,
5172 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5174 send_request_complete(request
, 0, res
);
5190 } send_request_task_t
;
5192 /***********************************************************************
5194 * Helper functions for the HttpSendRequest(Ex) functions
5197 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5199 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5200 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5202 TRACE("%p\n", request
);
5204 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5205 task
->optional_len
, task
->content_len
, task
->end_request
);
5207 heap_free(task
->headers
);
5211 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5214 DWORD res
= ERROR_SUCCESS
;
5216 if(!is_valid_netconn(request
->netconn
)) {
5217 WARN("Not connected\n");
5218 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5219 return ERROR_INTERNET_OPERATION_CANCELLED
;
5222 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5223 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5225 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5226 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5228 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5229 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5231 /* process cookies here. Is this right? */
5232 http_process_keep_alive(request
);
5233 HTTP_ProcessCookies(request
);
5234 HTTP_ProcessExpires(request
);
5235 HTTP_ProcessLastModified(request
);
5237 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5238 if(!request
->contentLength
)
5239 http_release_netconn(request
, TRUE
);
5242 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5244 switch(request
->status_code
) {
5245 case HTTP_STATUS_REDIRECT
:
5246 case HTTP_STATUS_MOVED
:
5247 case HTTP_STATUS_REDIRECT_METHOD
:
5248 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5251 new_url
= get_redirect_url(request
);
5255 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5256 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5258 heap_free(request
->verb
);
5259 request
->verb
= heap_strdupW(szGET
);
5261 http_release_netconn(request
, drain_content(request
, FALSE
) == ERROR_SUCCESS
);
5262 res
= HTTP_HandleRedirect(request
, new_url
);
5264 if (res
== ERROR_SUCCESS
)
5265 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5270 if(res
== ERROR_SUCCESS
)
5271 create_cache_entry(request
);
5273 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5274 HTTP_ReceiveRequestData(request
);
5276 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5281 /***********************************************************************
5282 * HttpEndRequestA (WININET.@)
5284 * Ends an HTTP request that was started by HttpSendRequestEx
5287 * TRUE if successful
5291 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5292 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5294 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5298 SetLastError(ERROR_INVALID_PARAMETER
);
5302 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5309 } end_request_task_t
;
5311 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5313 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5314 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5318 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5321 /***********************************************************************
5322 * HttpEndRequestW (WININET.@)
5324 * Ends an HTTP request that was started by HttpSendRequestEx
5327 * TRUE if successful
5331 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5332 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5334 http_request_t
*request
;
5337 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5341 SetLastError(ERROR_INVALID_PARAMETER
);
5345 request
= (http_request_t
*) get_handle_object( hRequest
);
5347 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5349 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5351 WININET_Release( &request
->hdr
);
5354 request
->hdr
.dwFlags
|= dwFlags
;
5356 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5358 end_request_task_t
*task
;
5360 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5361 task
->flags
= dwFlags
;
5362 task
->context
= dwContext
;
5364 INTERNET_AsyncCall(&task
->hdr
);
5365 res
= ERROR_IO_PENDING
;
5368 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5370 WININET_Release( &request
->hdr
);
5371 TRACE("%u <--\n", res
);
5372 if(res
!= ERROR_SUCCESS
)
5374 return res
== ERROR_SUCCESS
;
5377 /***********************************************************************
5378 * HttpSendRequestExA (WININET.@)
5380 * Sends the specified request to the HTTP server and allows chunked
5385 * Failure: FALSE, call GetLastError() for more information.
5387 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5388 LPINTERNET_BUFFERSA lpBuffersIn
,
5389 LPINTERNET_BUFFERSA lpBuffersOut
,
5390 DWORD dwFlags
, DWORD_PTR dwContext
)
5392 INTERNET_BUFFERSW BuffersInW
;
5395 LPWSTR header
= NULL
;
5397 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5398 lpBuffersOut
, dwFlags
, dwContext
);
5402 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5403 if (lpBuffersIn
->lpcszHeader
)
5405 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5406 lpBuffersIn
->dwHeadersLength
,0,0);
5407 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5408 if (!(BuffersInW
.lpcszHeader
= header
))
5410 SetLastError(ERROR_OUTOFMEMORY
);
5413 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5414 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5418 BuffersInW
.lpcszHeader
= NULL
;
5419 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5420 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5421 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5422 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5423 BuffersInW
.Next
= NULL
;
5426 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5432 /***********************************************************************
5433 * HttpSendRequestExW (WININET.@)
5435 * Sends the specified request to the HTTP server and allows chunked
5440 * Failure: FALSE, call GetLastError() for more information.
5442 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5443 LPINTERNET_BUFFERSW lpBuffersIn
,
5444 LPINTERNET_BUFFERSW lpBuffersOut
,
5445 DWORD dwFlags
, DWORD_PTR dwContext
)
5447 http_request_t
*request
;
5448 http_session_t
*session
;
5452 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5453 lpBuffersOut
, dwFlags
, dwContext
);
5455 request
= (http_request_t
*) get_handle_object( hRequest
);
5457 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5459 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5463 session
= request
->session
;
5464 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5465 hIC
= session
->appInfo
;
5466 assert(hIC
->hdr
.htype
== WH_HINIT
);
5468 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5470 send_request_task_t
*task
;
5472 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5477 if (lpBuffersIn
->lpcszHeader
)
5479 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5480 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5482 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5484 task
->headers
= heap_alloc(size
);
5485 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5487 else task
->headers
= NULL
;
5489 task
->headers_len
= size
/ sizeof(WCHAR
);
5490 task
->optional
= lpBuffersIn
->lpvBuffer
;
5491 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5492 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5496 task
->headers
= NULL
;
5497 task
->headers_len
= 0;
5498 task
->optional
= NULL
;
5499 task
->optional_len
= 0;
5500 task
->content_len
= 0;
5503 task
->end_request
= FALSE
;
5505 INTERNET_AsyncCall(&task
->hdr
);
5506 res
= ERROR_IO_PENDING
;
5511 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5512 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5513 lpBuffersIn
->dwBufferTotal
, FALSE
);
5515 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5520 WININET_Release( &request
->hdr
);
5524 return res
== ERROR_SUCCESS
;
5527 /***********************************************************************
5528 * HttpSendRequestW (WININET.@)
5530 * Sends the specified request to the HTTP server
5537 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5538 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5540 http_request_t
*request
;
5541 http_session_t
*session
= NULL
;
5542 appinfo_t
*hIC
= NULL
;
5543 DWORD res
= ERROR_SUCCESS
;
5545 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5546 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5548 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5549 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5551 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5555 session
= request
->session
;
5556 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5558 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5562 hIC
= session
->appInfo
;
5563 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5565 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5569 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5571 send_request_task_t
*task
;
5573 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5578 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5579 else size
= dwHeaderLength
* sizeof(WCHAR
);
5581 task
->headers
= heap_alloc(size
);
5582 memcpy(task
->headers
, lpszHeaders
, size
);
5585 task
->headers
= NULL
;
5586 task
->headers_len
= dwHeaderLength
;
5587 task
->optional
= lpOptional
;
5588 task
->optional_len
= dwOptionalLength
;
5589 task
->content_len
= dwOptionalLength
;
5590 task
->end_request
= TRUE
;
5592 INTERNET_AsyncCall(&task
->hdr
);
5593 res
= ERROR_IO_PENDING
;
5597 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5598 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5599 dwOptionalLength
, TRUE
);
5603 WININET_Release( &request
->hdr
);
5606 return res
== ERROR_SUCCESS
;
5609 /***********************************************************************
5610 * HttpSendRequestA (WININET.@)
5612 * Sends the specified request to the HTTP server
5619 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5620 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5623 LPWSTR szHeaders
=NULL
;
5624 DWORD nLen
=dwHeaderLength
;
5625 if(lpszHeaders
!=NULL
)
5627 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5628 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5629 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5631 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5632 heap_free(szHeaders
);
5636 /***********************************************************************
5637 * HTTPSESSION_Destroy (internal)
5639 * Deallocate session handle
5642 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5644 http_session_t
*session
= (http_session_t
*) hdr
;
5646 TRACE("%p\n", session
);
5648 WININET_Release(&session
->appInfo
->hdr
);
5650 heap_free(session
->hostName
);
5651 heap_free(session
->password
);
5652 heap_free(session
->userName
);
5655 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5657 http_session_t
*ses
= (http_session_t
*)hdr
;
5660 case INTERNET_OPTION_HANDLE_TYPE
:
5661 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5663 if (*size
< sizeof(ULONG
))
5664 return ERROR_INSUFFICIENT_BUFFER
;
5666 *size
= sizeof(DWORD
);
5667 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5668 return ERROR_SUCCESS
;
5669 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5670 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5672 if (*size
< sizeof(DWORD
))
5673 return ERROR_INSUFFICIENT_BUFFER
;
5675 *size
= sizeof(DWORD
);
5676 *(DWORD
*)buffer
= ses
->connect_timeout
;
5677 return ERROR_SUCCESS
;
5679 case INTERNET_OPTION_SEND_TIMEOUT
:
5680 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5682 if (*size
< sizeof(DWORD
))
5683 return ERROR_INSUFFICIENT_BUFFER
;
5685 *size
= sizeof(DWORD
);
5686 *(DWORD
*)buffer
= ses
->send_timeout
;
5687 return ERROR_SUCCESS
;
5689 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5690 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5692 if (*size
< sizeof(DWORD
))
5693 return ERROR_INSUFFICIENT_BUFFER
;
5695 *size
= sizeof(DWORD
);
5696 *(DWORD
*)buffer
= ses
->receive_timeout
;
5697 return ERROR_SUCCESS
;
5700 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5703 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5705 http_session_t
*ses
= (http_session_t
*)hdr
;
5708 case INTERNET_OPTION_USERNAME
:
5710 heap_free(ses
->userName
);
5711 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5712 return ERROR_SUCCESS
;
5714 case INTERNET_OPTION_PASSWORD
:
5716 heap_free(ses
->password
);
5717 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5718 return ERROR_SUCCESS
;
5720 case INTERNET_OPTION_PROXY_USERNAME
:
5722 heap_free(ses
->appInfo
->proxyUsername
);
5723 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5724 return ERROR_SUCCESS
;
5726 case INTERNET_OPTION_PROXY_PASSWORD
:
5728 heap_free(ses
->appInfo
->proxyPassword
);
5729 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5730 return ERROR_SUCCESS
;
5732 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5734 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5735 ses
->connect_timeout
= *(DWORD
*)buffer
;
5736 return ERROR_SUCCESS
;
5738 case INTERNET_OPTION_SEND_TIMEOUT
:
5740 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5741 ses
->send_timeout
= *(DWORD
*)buffer
;
5742 return ERROR_SUCCESS
;
5744 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5746 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5747 ses
->receive_timeout
= *(DWORD
*)buffer
;
5748 return ERROR_SUCCESS
;
5753 return INET_SetOption(hdr
, option
, buffer
, size
);
5756 static const object_vtbl_t HTTPSESSIONVtbl
= {
5757 HTTPSESSION_Destroy
,
5759 HTTPSESSION_QueryOption
,
5760 HTTPSESSION_SetOption
,
5768 /***********************************************************************
5769 * HTTP_Connect (internal)
5771 * Create http session handle
5774 * HINTERNET a session handle on success
5778 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5779 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5780 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5781 DWORD dwInternalFlags
, HINTERNET
*ret
)
5783 http_session_t
*session
= NULL
;
5787 if (!lpszServerName
|| !lpszServerName
[0])
5788 return ERROR_INVALID_PARAMETER
;
5790 assert( hIC
->hdr
.htype
== WH_HINIT
);
5792 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5794 return ERROR_OUTOFMEMORY
;
5797 * According to my tests. The name is not resolved until a request is sent
5800 session
->hdr
.htype
= WH_HHTTPSESSION
;
5801 session
->hdr
.dwFlags
= dwFlags
;
5802 session
->hdr
.dwContext
= dwContext
;
5803 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5805 WININET_AddRef( &hIC
->hdr
);
5806 session
->appInfo
= hIC
;
5807 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5809 session
->hostName
= heap_strdupW(lpszServerName
);
5810 if (lpszUserName
&& lpszUserName
[0])
5811 session
->userName
= heap_strdupW(lpszUserName
);
5812 session
->password
= heap_strdupW(lpszPassword
);
5813 session
->hostPort
= serverPort
;
5814 session
->connect_timeout
= hIC
->connect_timeout
;
5815 session
->send_timeout
= 0;
5816 session
->receive_timeout
= 0;
5818 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5819 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5821 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5822 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5827 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5831 TRACE("%p --> %p\n", hIC
, session
);
5833 *ret
= session
->hdr
.hInternet
;
5834 return ERROR_SUCCESS
;
5837 /***********************************************************************
5838 * HTTP_clear_response_headers (internal)
5840 * clear out any old response headers
5842 static void HTTP_clear_response_headers( http_request_t
*request
)
5846 EnterCriticalSection( &request
->headers_section
);
5848 for( i
=0; i
<request
->nCustHeaders
; i
++)
5850 if( !request
->custHeaders
[i
].lpszField
)
5852 if( !request
->custHeaders
[i
].lpszValue
)
5854 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5856 HTTP_DeleteCustomHeader( request
, i
);
5860 LeaveCriticalSection( &request
->headers_section
);
5863 /***********************************************************************
5864 * HTTP_GetResponseHeaders (internal)
5866 * Read server response
5873 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5876 WCHAR buffer
[MAX_REPLY_LEN
];
5877 DWORD buflen
= MAX_REPLY_LEN
;
5879 char bufferA
[MAX_REPLY_LEN
];
5880 LPWSTR status_code
= NULL
, status_text
= NULL
;
5881 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5882 BOOL codeHundred
= FALSE
;
5886 if(!is_valid_netconn(request
->netconn
))
5889 /* clear old response headers (eg. from a redirect response) */
5890 HTTP_clear_response_headers( request
);
5892 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5895 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5897 buflen
= MAX_REPLY_LEN
;
5898 if ((res
= read_line(request
, bufferA
, &buflen
)))
5901 if (!buflen
) goto lend
;
5904 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5905 /* check is this a status code line? */
5906 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5908 /* split the version from the status code */
5909 status_code
= strchrW( buffer
, ' ' );
5914 /* split the status code from the status text */
5915 status_text
= strchrW( status_code
, ' ' );
5919 request
->status_code
= atoiW(status_code
);
5921 TRACE("version [%s] status code [%s] status text [%s]\n",
5922 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5924 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5926 else if (!codeHundred
)
5928 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5930 heap_free(request
->version
);
5931 heap_free(request
->statusText
);
5933 request
->status_code
= HTTP_STATUS_OK
;
5934 request
->version
= heap_strdupW(g_szHttp1_0
);
5935 request
->statusText
= heap_strdupW(szOK
);
5939 } while (codeHundred
);
5941 /* Add status code */
5942 HTTP_ProcessHeader(request
, szStatus
, status_code
,
5943 HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
5945 heap_free(request
->version
);
5946 heap_free(request
->statusText
);
5948 request
->version
= heap_strdupW(buffer
);
5949 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
5951 /* Restore the spaces */
5952 *(status_code
-1) = ' ';
5954 *(status_text
-1) = ' ';
5956 /* Parse each response line */
5959 buflen
= MAX_REPLY_LEN
;
5960 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
5962 LPWSTR
* pFieldAndValue
;
5964 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
5966 if (!bufferA
[0]) break;
5967 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5969 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
5972 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
5973 HTTP_ADDREQ_FLAG_ADD
);
5974 HTTP_FreeTokens(pFieldAndValue
);
5985 res
= ERROR_SUCCESS
;
5994 /***********************************************************************
5995 * HTTP_InterpretHttpHeader (internal)
5997 * Parse server response
6001 * Pointer to array of field, value, NULL on success.
6004 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
6006 LPWSTR
* pTokenPair
;
6010 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
6012 pszColon
= strchrW(buffer
, ':');
6013 /* must have two tokens */
6016 HTTP_FreeTokens(pTokenPair
);
6018 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
6022 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
6025 HTTP_FreeTokens(pTokenPair
);
6028 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
6029 pTokenPair
[0][pszColon
- buffer
] = '\0';
6033 len
= strlenW(pszColon
);
6034 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
6037 HTTP_FreeTokens(pTokenPair
);
6040 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
6042 strip_spaces(pTokenPair
[0]);
6043 strip_spaces(pTokenPair
[1]);
6045 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
6049 /***********************************************************************
6050 * HTTP_ProcessHeader (internal)
6052 * Stuff header into header tables according to <dwModifier>
6056 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6058 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6060 LPHTTPHEADERW lphttpHdr
= NULL
;
6062 BOOL request_only
= !!(dwModifier
& HTTP_ADDHDR_FLAG_REQ
);
6063 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6065 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6067 EnterCriticalSection( &request
->headers_section
);
6069 /* REPLACE wins out over ADD */
6070 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6071 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6073 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6076 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6080 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6082 LeaveCriticalSection( &request
->headers_section
);
6083 return ERROR_HTTP_INVALID_HEADER
;
6085 lphttpHdr
= &request
->custHeaders
[index
];
6091 hdr
.lpszField
= (LPWSTR
)field
;
6092 hdr
.lpszValue
= (LPWSTR
)value
;
6093 hdr
.wFlags
= hdr
.wCount
= 0;
6095 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6096 hdr
.wFlags
|= HDR_ISREQUEST
;
6098 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6099 LeaveCriticalSection( &request
->headers_section
);
6102 /* no value to delete */
6105 LeaveCriticalSection( &request
->headers_section
);
6106 return ERROR_SUCCESS
;
6109 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6110 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6112 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6114 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6116 HTTP_DeleteCustomHeader( request
, index
);
6118 if (value
&& value
[0])
6122 hdr
.lpszField
= (LPWSTR
)field
;
6123 hdr
.lpszValue
= (LPWSTR
)value
;
6124 hdr
.wFlags
= hdr
.wCount
= 0;
6126 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6127 hdr
.wFlags
|= HDR_ISREQUEST
;
6129 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6130 LeaveCriticalSection( &request
->headers_section
);
6134 LeaveCriticalSection( &request
->headers_section
);
6135 return ERROR_SUCCESS
;
6137 else if (dwModifier
& COALESCEFLAGS
)
6142 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6143 INT valuelen
= strlenW(value
);
6145 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6148 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6150 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6153 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6156 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6158 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6161 lphttpHdr
->lpszValue
= lpsztmp
;
6162 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6165 lphttpHdr
->lpszValue
[origlen
] = ch
;
6167 lphttpHdr
->lpszValue
[origlen
] = ' ';
6171 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6172 lphttpHdr
->lpszValue
[len
] = '\0';
6173 res
= ERROR_SUCCESS
;
6177 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6178 res
= ERROR_OUTOFMEMORY
;
6181 TRACE("<-- %d\n", res
);
6182 LeaveCriticalSection( &request
->headers_section
);
6186 /***********************************************************************
6187 * HTTP_GetCustomHeaderIndex (internal)
6189 * Return index of custom header from header array
6190 * Headers section must be held
6192 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6193 int requested_index
, BOOL request_only
)
6197 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6199 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6201 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6204 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6207 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6210 if (requested_index
== 0)
6215 if (index
>= request
->nCustHeaders
)
6218 TRACE("Return: %d\n", index
);
6223 /***********************************************************************
6224 * HTTP_InsertCustomHeader (internal)
6226 * Insert header into array
6227 * Headers section must be held
6229 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6232 LPHTTPHEADERW lph
= NULL
;
6234 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6235 count
= request
->nCustHeaders
+ 1;
6237 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6239 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6242 return ERROR_OUTOFMEMORY
;
6244 request
->custHeaders
= lph
;
6245 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6246 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6247 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6248 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6249 request
->nCustHeaders
++;
6251 return ERROR_SUCCESS
;
6255 /***********************************************************************
6256 * HTTP_DeleteCustomHeader (internal)
6258 * Delete header from array
6259 * If this function is called, the index may change.
6260 * Headers section must be held
6262 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6264 if( request
->nCustHeaders
<= 0 )
6266 if( index
>= request
->nCustHeaders
)
6268 request
->nCustHeaders
--;
6270 heap_free(request
->custHeaders
[index
].lpszField
);
6271 heap_free(request
->custHeaders
[index
].lpszValue
);
6273 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6274 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6275 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6281 /***********************************************************************
6282 * IsHostInProxyBypassList (@)
6287 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6289 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);