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
== ARRAY_SIZE(localW
)-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
, ARRAY_SIZE(no_cacheW
)-1)
2413 || !strncmpiW(ptr
, no_storeW
, ARRAY_SIZE(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 /***********************************************************************
3517 * HTTP_HttpQueryInfoW (internal)
3519 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3520 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3522 LPHTTPHEADERW lphttpHdr
= NULL
;
3523 BOOL request_only
= !!(dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
);
3524 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3525 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3528 EnterCriticalSection( &request
->headers_section
);
3530 /* Find requested header structure */
3533 case HTTP_QUERY_CUSTOM
:
3536 LeaveCriticalSection( &request
->headers_section
);
3537 return ERROR_INVALID_PARAMETER
;
3539 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3541 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3545 DWORD res
= ERROR_INVALID_PARAMETER
;
3548 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3550 headers
= build_response_header(request
, TRUE
);
3553 LeaveCriticalSection( &request
->headers_section
);
3554 return ERROR_OUTOFMEMORY
;
3557 len
= strlenW(headers
) * sizeof(WCHAR
);
3558 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3560 len
+= sizeof(WCHAR
);
3561 res
= ERROR_INSUFFICIENT_BUFFER
;
3565 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3566 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3567 res
= ERROR_SUCCESS
;
3569 *lpdwBufferLength
= len
;
3572 LeaveCriticalSection( &request
->headers_section
);
3575 case HTTP_QUERY_RAW_HEADERS
:
3581 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3583 headers
= build_response_header(request
, FALSE
);
3587 LeaveCriticalSection( &request
->headers_section
);
3588 return ERROR_OUTOFMEMORY
;
3591 len
= strlenW(headers
) * sizeof(WCHAR
);
3592 if (len
> *lpdwBufferLength
)
3594 *lpdwBufferLength
= len
;
3596 LeaveCriticalSection( &request
->headers_section
);
3597 return ERROR_INSUFFICIENT_BUFFER
;
3604 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3606 for (i
= 0; i
< len
/ sizeof(WCHAR
); i
++)
3608 if (headers
[i
] == '\n')
3611 memcpy(lpBuffer
, headers
, len
);
3613 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3616 LeaveCriticalSection( &request
->headers_section
);
3617 return ERROR_SUCCESS
;
3619 case HTTP_QUERY_STATUS_TEXT
:
3620 if (request
->statusText
)
3622 DWORD len
= strlenW(request
->statusText
);
3623 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3625 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3626 LeaveCriticalSection( &request
->headers_section
);
3627 return ERROR_INSUFFICIENT_BUFFER
;
3631 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3632 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3634 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3635 LeaveCriticalSection( &request
->headers_section
);
3636 return ERROR_SUCCESS
;
3639 case HTTP_QUERY_VERSION
:
3640 if (request
->version
)
3642 DWORD len
= strlenW(request
->version
);
3643 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3645 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3646 LeaveCriticalSection( &request
->headers_section
);
3647 return ERROR_INSUFFICIENT_BUFFER
;
3651 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3652 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3654 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3655 LeaveCriticalSection( &request
->headers_section
);
3656 return ERROR_SUCCESS
;
3659 case HTTP_QUERY_CONTENT_ENCODING
:
3660 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3661 requested_index
,request_only
);
3663 case HTTP_QUERY_STATUS_CODE
: {
3664 DWORD res
= ERROR_SUCCESS
;
3668 LeaveCriticalSection( &request
->headers_section
);
3669 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3675 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3676 if(*lpdwBufferLength
>= sizeof(DWORD
))
3677 *(DWORD
*)lpBuffer
= request
->status_code
;
3679 res
= ERROR_INSUFFICIENT_BUFFER
;
3680 *lpdwBufferLength
= sizeof(DWORD
);
3684 static const WCHAR formatW
[] = {'%','u',0};
3686 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3688 if(size
<= *lpdwBufferLength
) {
3689 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3691 size
+= sizeof(WCHAR
);
3692 res
= ERROR_INSUFFICIENT_BUFFER
;
3695 *lpdwBufferLength
= size
;
3697 LeaveCriticalSection( &request
->headers_section
);
3701 assert (ARRAY_SIZE(header_lookup
) == (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3703 if (level
< ARRAY_SIZE(header_lookup
) && header_lookup
[level
])
3704 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3705 requested_index
,request_only
);
3709 lphttpHdr
= &request
->custHeaders
[index
];
3711 /* Ensure header satisfies requested attributes */
3713 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3714 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3716 LeaveCriticalSection( &request
->headers_section
);
3717 return ERROR_HTTP_HEADER_NOT_FOUND
;
3720 /* coalesce value to requested type */
3721 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3723 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3724 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3726 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3732 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3734 tmpTM
= *gmtime(&tmpTime
);
3735 STHook
= (SYSTEMTIME
*)lpBuffer
;
3736 STHook
->wDay
= tmpTM
.tm_mday
;
3737 STHook
->wHour
= tmpTM
.tm_hour
;
3738 STHook
->wMilliseconds
= 0;
3739 STHook
->wMinute
= tmpTM
.tm_min
;
3740 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3741 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3742 STHook
->wSecond
= tmpTM
.tm_sec
;
3743 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3745 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3746 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3747 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3749 else if (lphttpHdr
->lpszValue
)
3751 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3753 if (len
> *lpdwBufferLength
)
3755 *lpdwBufferLength
= len
;
3756 LeaveCriticalSection( &request
->headers_section
);
3757 return ERROR_INSUFFICIENT_BUFFER
;
3761 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3762 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3764 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3766 if (lpdwIndex
) (*lpdwIndex
)++;
3768 LeaveCriticalSection( &request
->headers_section
);
3769 return ERROR_SUCCESS
;
3772 /***********************************************************************
3773 * HttpQueryInfoW (WININET.@)
3775 * Queries for information about an HTTP request
3782 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3783 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3785 http_request_t
*request
;
3788 if (TRACE_ON(wininet
)) {
3789 #define FE(x) { x, #x }
3790 static const wininet_flag_info query_flags
[] = {
3791 FE(HTTP_QUERY_MIME_VERSION
),
3792 FE(HTTP_QUERY_CONTENT_TYPE
),
3793 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3794 FE(HTTP_QUERY_CONTENT_ID
),
3795 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3796 FE(HTTP_QUERY_CONTENT_LENGTH
),
3797 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3798 FE(HTTP_QUERY_ALLOW
),
3799 FE(HTTP_QUERY_PUBLIC
),
3800 FE(HTTP_QUERY_DATE
),
3801 FE(HTTP_QUERY_EXPIRES
),
3802 FE(HTTP_QUERY_LAST_MODIFIED
),
3803 FE(HTTP_QUERY_MESSAGE_ID
),
3805 FE(HTTP_QUERY_DERIVED_FROM
),
3806 FE(HTTP_QUERY_COST
),
3807 FE(HTTP_QUERY_LINK
),
3808 FE(HTTP_QUERY_PRAGMA
),
3809 FE(HTTP_QUERY_VERSION
),
3810 FE(HTTP_QUERY_STATUS_CODE
),
3811 FE(HTTP_QUERY_STATUS_TEXT
),
3812 FE(HTTP_QUERY_RAW_HEADERS
),
3813 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3814 FE(HTTP_QUERY_CONNECTION
),
3815 FE(HTTP_QUERY_ACCEPT
),
3816 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3817 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3818 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3819 FE(HTTP_QUERY_AUTHORIZATION
),
3820 FE(HTTP_QUERY_CONTENT_ENCODING
),
3821 FE(HTTP_QUERY_FORWARDED
),
3822 FE(HTTP_QUERY_FROM
),
3823 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3824 FE(HTTP_QUERY_LOCATION
),
3825 FE(HTTP_QUERY_ORIG_URI
),
3826 FE(HTTP_QUERY_REFERER
),
3827 FE(HTTP_QUERY_RETRY_AFTER
),
3828 FE(HTTP_QUERY_SERVER
),
3829 FE(HTTP_QUERY_TITLE
),
3830 FE(HTTP_QUERY_USER_AGENT
),
3831 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3832 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3833 FE(HTTP_QUERY_ACCEPT_RANGES
),
3834 FE(HTTP_QUERY_SET_COOKIE
),
3835 FE(HTTP_QUERY_COOKIE
),
3836 FE(HTTP_QUERY_REQUEST_METHOD
),
3837 FE(HTTP_QUERY_REFRESH
),
3838 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3840 FE(HTTP_QUERY_CACHE_CONTROL
),
3841 FE(HTTP_QUERY_CONTENT_BASE
),
3842 FE(HTTP_QUERY_CONTENT_LOCATION
),
3843 FE(HTTP_QUERY_CONTENT_MD5
),
3844 FE(HTTP_QUERY_CONTENT_RANGE
),
3845 FE(HTTP_QUERY_ETAG
),
3846 FE(HTTP_QUERY_HOST
),
3847 FE(HTTP_QUERY_IF_MATCH
),
3848 FE(HTTP_QUERY_IF_NONE_MATCH
),
3849 FE(HTTP_QUERY_IF_RANGE
),
3850 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3851 FE(HTTP_QUERY_MAX_FORWARDS
),
3852 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3853 FE(HTTP_QUERY_RANGE
),
3854 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3855 FE(HTTP_QUERY_UPGRADE
),
3856 FE(HTTP_QUERY_VARY
),
3858 FE(HTTP_QUERY_WARNING
),
3859 FE(HTTP_QUERY_CUSTOM
)
3861 static const wininet_flag_info modifier_flags
[] = {
3862 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3863 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3864 FE(HTTP_QUERY_FLAG_NUMBER
),
3865 FE(HTTP_QUERY_FLAG_COALESCE
)
3868 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3869 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3872 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3873 TRACE(" Attribute:");
3874 for (i
= 0; i
< ARRAY_SIZE(query_flags
); i
++) {
3875 if (query_flags
[i
].val
== info
) {
3876 TRACE(" %s", query_flags
[i
].name
);
3880 if (i
== ARRAY_SIZE(query_flags
)) {
3881 TRACE(" Unknown (%08x)", info
);
3884 TRACE(" Modifier:");
3885 for (i
= 0; i
< ARRAY_SIZE(modifier_flags
); i
++) {
3886 if (modifier_flags
[i
].val
& info_mod
) {
3887 TRACE(" %s", modifier_flags
[i
].name
);
3888 info_mod
&= ~ modifier_flags
[i
].val
;
3893 TRACE(" Unknown (%08x)", info_mod
);
3898 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3899 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3901 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3905 if (lpBuffer
== NULL
)
3906 *lpdwBufferLength
= 0;
3907 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3908 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3912 WININET_Release( &request
->hdr
);
3914 TRACE("%u <--\n", res
);
3915 if(res
!= ERROR_SUCCESS
)
3917 return res
== ERROR_SUCCESS
;
3920 /***********************************************************************
3921 * HttpQueryInfoA (WININET.@)
3923 * Queries for information about an HTTP request
3930 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3931 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3937 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
3939 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3940 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3942 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3943 lpdwBufferLength
, lpdwIndex
);
3949 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
3950 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3952 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
3958 bufferW
= heap_alloc(alloclen
);
3959 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3960 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3961 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
3968 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
3972 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
3973 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
3974 *lpdwBufferLength
= len
- 1;
3976 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
3979 /* since the strings being returned from HttpQueryInfoW should be
3980 * only ASCII characters, it is reasonable to assume that all of
3981 * the Unicode characters can be reduced to a single byte */
3982 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
3984 heap_free( bufferW
);
3988 static WCHAR
*get_redirect_url(http_request_t
*request
)
3990 static WCHAR szHttp
[] = {'h','t','t','p',0};
3991 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
3992 http_session_t
*session
= request
->session
;
3993 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
3994 WCHAR
*orig_url
= NULL
, *redirect_url
= NULL
, *combined_url
= NULL
;
3995 DWORD url_length
= 0, res
;
3999 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
4000 if(res
== ERROR_INSUFFICIENT_BUFFER
) {
4001 redirect_url
= heap_alloc(url_length
);
4002 res
= HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, redirect_url
, &url_length
, NULL
);
4004 if(res
!= ERROR_SUCCESS
) {
4005 heap_free(redirect_url
);
4009 urlComponents
.dwSchemeLength
= 1;
4010 b
= InternetCrackUrlW(redirect_url
, url_length
/ sizeof(WCHAR
), 0, &urlComponents
);
4011 if(b
&& urlComponents
.dwSchemeLength
&&
4012 urlComponents
.nScheme
!= INTERNET_SCHEME_HTTP
&& urlComponents
.nScheme
!= INTERNET_SCHEME_HTTPS
) {
4013 TRACE("redirect to non-http URL\n");
4017 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
4018 urlComponents
.dwSchemeLength
= 0;
4019 urlComponents
.lpszHostName
= request
->server
->name
;
4020 urlComponents
.nPort
= request
->server
->port
;
4021 urlComponents
.lpszUserName
= session
->userName
;
4022 urlComponents
.lpszUrlPath
= request
->path
;
4024 b
= InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
);
4025 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4026 orig_url
= heap_alloc(url_length
);
4028 /* convert from bytes to characters */
4029 url_length
= url_length
/ sizeof(WCHAR
) - 1;
4030 b
= InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
);
4035 b
= InternetCombineUrlW(orig_url
, redirect_url
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4036 if(!b
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
4037 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
4038 b
= InternetCombineUrlW(orig_url
, redirect_url
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
);
4040 heap_free(combined_url
);
4041 combined_url
= NULL
;
4046 heap_free(orig_url
);
4047 heap_free(redirect_url
);
4048 return combined_url
;
4052 /***********************************************************************
4053 * HTTP_HandleRedirect (internal)
4055 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, WCHAR
*url
)
4057 URL_COMPONENTSW urlComponents
= { sizeof(urlComponents
) };
4058 http_session_t
*session
= request
->session
;
4059 size_t url_len
= strlenW(url
);
4063 /* if it's an absolute path, keep the same session info */
4064 urlComponents
.lpszUrlPath
= url
;
4065 urlComponents
.dwUrlPathLength
= url_len
;
4069 urlComponents
.dwHostNameLength
= 1;
4070 urlComponents
.dwUserNameLength
= 1;
4071 urlComponents
.dwUrlPathLength
= 1;
4072 if(!InternetCrackUrlW(url
, url_len
, 0, &urlComponents
))
4073 return INTERNET_GetLastError();
4075 if(!urlComponents
.dwHostNameLength
)
4076 return ERROR_INTERNET_INVALID_URL
;
4079 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
4080 url
, (url_len
+ 1) * sizeof(WCHAR
));
4082 if(urlComponents
.dwHostNameLength
) {
4083 BOOL custom_port
= FALSE
;
4086 if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTP
) {
4087 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4088 TRACE("redirect from secure page to non-secure page\n");
4089 /* FIXME: warn about from secure redirect to non-secure page */
4090 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4093 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
;
4094 }else if(urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
) {
4095 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4096 TRACE("redirect from non-secure page to secure page\n");
4097 /* FIXME: notify about redirect to secure page */
4098 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4101 custom_port
= urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
;
4104 heap_free(session
->hostName
);
4106 session
->hostName
= heap_strndupW(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4107 session
->hostPort
= urlComponents
.nPort
;
4109 heap_free(session
->userName
);
4110 session
->userName
= NULL
;
4111 if (urlComponents
.dwUserNameLength
)
4112 session
->userName
= heap_strndupW(urlComponents
.lpszUserName
, urlComponents
.dwUserNameLength
);
4114 reset_data_stream(request
);
4116 host
= substr(urlComponents
.lpszHostName
, urlComponents
.dwHostNameLength
);
4118 if(host
.len
!= strlenW(request
->server
->name
) || strncmpiW(request
->server
->name
, host
.str
, host
.len
)
4119 || request
->server
->port
!= urlComponents
.nPort
) {
4120 server_t
*new_server
;
4122 new_server
= get_server(host
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4123 server_release(request
->server
);
4124 request
->server
= new_server
;
4128 HTTP_ProcessHeader(request
, hostW
, request
->server
->host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4130 HTTP_ProcessHeader(request
, hostW
, request
->server
->name
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4133 heap_free(request
->path
);
4134 request
->path
= NULL
;
4135 if(urlComponents
.dwUrlPathLength
)
4142 path
= heap_strndupW(urlComponents
.lpszUrlPath
, urlComponents
.dwUrlPathLength
);
4143 rc
= UrlEscapeW(path
, &dummy
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4144 if (rc
!= E_POINTER
)
4145 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4146 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4147 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4148 URL_ESCAPE_SPACES_ONLY
);
4151 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4152 strcpyW(request
->path
, path
);
4157 /* Remove custom content-type/length headers on redirects. */
4158 remove_header(request
, szContent_Type
, TRUE
);
4159 remove_header(request
, szContent_Length
, TRUE
);
4161 return ERROR_SUCCESS
;
4164 /***********************************************************************
4165 * HTTP_build_req (internal)
4167 * concatenate all the strings in the request together
4169 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4174 for( t
= list
; *t
; t
++ )
4175 len
+= strlenW( *t
);
4178 str
= heap_alloc(len
*sizeof(WCHAR
));
4181 for( t
= list
; *t
; t
++ )
4187 static void HTTP_InsertCookies(http_request_t
*request
)
4192 res
= get_cookie_header(request
->server
->name
, request
->path
, &cookies
);
4193 if(res
!= ERROR_SUCCESS
|| !cookies
)
4196 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
),
4197 HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDREQ_FLAG_ADD
);
4201 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4203 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4211 for (i
= 0; i
< ARRAY_SIZE(days
); i
++)
4212 if (!strcmpiW(day
, days
[i
]))
4219 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4221 static const WCHAR jan
[] = { 'j','a','n',0 };
4222 static const WCHAR feb
[] = { 'f','e','b',0 };
4223 static const WCHAR mar
[] = { 'm','a','r',0 };
4224 static const WCHAR apr
[] = { 'a','p','r',0 };
4225 static const WCHAR may
[] = { 'm','a','y',0 };
4226 static const WCHAR jun
[] = { 'j','u','n',0 };
4227 static const WCHAR jul
[] = { 'j','u','l',0 };
4228 static const WCHAR aug
[] = { 'a','u','g',0 };
4229 static const WCHAR sep
[] = { 's','e','p',0 };
4230 static const WCHAR oct
[] = { 'o','c','t',0 };
4231 static const WCHAR nov
[] = { 'n','o','v',0 };
4232 static const WCHAR dec
[] = { 'd','e','c',0 };
4234 if (!strcmpiW(month
, jan
)) return 1;
4235 if (!strcmpiW(month
, feb
)) return 2;
4236 if (!strcmpiW(month
, mar
)) return 3;
4237 if (!strcmpiW(month
, apr
)) return 4;
4238 if (!strcmpiW(month
, may
)) return 5;
4239 if (!strcmpiW(month
, jun
)) return 6;
4240 if (!strcmpiW(month
, jul
)) return 7;
4241 if (!strcmpiW(month
, aug
)) return 8;
4242 if (!strcmpiW(month
, sep
)) return 9;
4243 if (!strcmpiW(month
, oct
)) return 10;
4244 if (!strcmpiW(month
, nov
)) return 11;
4245 if (!strcmpiW(month
, dec
)) return 12;
4250 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4251 * optionally preceded by whitespace.
4252 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4253 * st, and sets *str to the first character after the time format.
4255 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4261 while (isspaceW(*ptr
))
4264 num
= strtoulW(ptr
, &nextPtr
, 10);
4265 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4267 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4272 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4276 st
->wHour
= (WORD
)num
;
4277 num
= strtoulW(ptr
, &nextPtr
, 10);
4278 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4280 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4285 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4289 st
->wMinute
= (WORD
)num
;
4290 num
= strtoulW(ptr
, &nextPtr
, 10);
4291 if (!nextPtr
|| nextPtr
<= ptr
)
4293 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4298 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4303 st
->wSecond
= (WORD
)num
;
4307 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4309 static const WCHAR gmt
[]= { 'G','M','T',0 };
4310 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4312 SYSTEMTIME st
= { 0 };
4315 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4316 dayPtr
- day
< ARRAY_SIZE(day
) - 1; ptr
++, dayPtr
++)
4319 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4320 if (st
.wDayOfWeek
>= 7)
4322 ERR("unexpected weekday %s\n", debugstr_w(day
));
4326 while (isspaceW(*ptr
))
4329 for (monthPtr
= month
; !isspaceW(*ptr
) && monthPtr
- month
< ARRAY_SIZE(month
) - 1;
4333 st
.wMonth
= HTTP_ParseMonth(month
);
4334 if (!st
.wMonth
|| st
.wMonth
> 12)
4336 ERR("unexpected month %s\n", debugstr_w(month
));
4340 while (isspaceW(*ptr
))
4343 num
= strtoulW(ptr
, &nextPtr
, 10);
4344 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4346 ERR("unexpected day %s\n", debugstr_w(ptr
));
4350 st
.wDay
= (WORD
)num
;
4352 while (isspaceW(*ptr
))
4355 if (!HTTP_ParseTime(&st
, &ptr
))
4358 while (isspaceW(*ptr
))
4361 num
= strtoulW(ptr
, &nextPtr
, 10);
4362 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4364 ERR("unexpected year %s\n", debugstr_w(ptr
));
4368 st
.wYear
= (WORD
)num
;
4370 while (isspaceW(*ptr
))
4373 /* asctime() doesn't report a timezone, but some web servers do, so accept
4374 * with or without GMT.
4376 if (*ptr
&& strcmpW(ptr
, gmt
))
4378 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4381 return SystemTimeToFileTime(&st
, ft
);
4384 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4386 static const WCHAR gmt
[]= { 'G','M','T',0 };
4387 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4390 SYSTEMTIME st
= { 0 };
4392 ptr
= strchrW(value
, ',');
4395 if (ptr
- value
!= 3)
4397 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4400 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4402 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4403 if (st
.wDayOfWeek
> 6)
4405 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4410 while (isspaceW(*ptr
))
4413 num
= strtoulW(ptr
, &nextPtr
, 10);
4414 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4416 WARN("unexpected day %s\n", debugstr_w(value
));
4420 st
.wDay
= (WORD
)num
;
4422 while (isspaceW(*ptr
))
4425 for (monthPtr
= month
; !isspaceW(*ptr
) && monthPtr
- month
< ARRAY_SIZE(month
) - 1;
4429 st
.wMonth
= HTTP_ParseMonth(month
);
4430 if (!st
.wMonth
|| st
.wMonth
> 12)
4432 WARN("unexpected month %s\n", debugstr_w(month
));
4436 while (isspaceW(*ptr
))
4439 num
= strtoulW(ptr
, &nextPtr
, 10);
4440 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4442 ERR("unexpected year %s\n", debugstr_w(value
));
4446 st
.wYear
= (WORD
)num
;
4448 if (!HTTP_ParseTime(&st
, &ptr
))
4451 while (isspaceW(*ptr
))
4454 if (strcmpW(ptr
, gmt
))
4456 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4459 return SystemTimeToFileTime(&st
, ft
);
4462 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4464 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4465 { 'm','o','n','d','a','y',0 },
4466 { 't','u','e','s','d','a','y',0 },
4467 { 'w','e','d','n','e','s','d','a','y',0 },
4468 { 't','h','u','r','s','d','a','y',0 },
4469 { 'f','r','i','d','a','y',0 },
4470 { 's','a','t','u','r','d','a','y',0 }};
4472 for (i
= 0; i
< ARRAY_SIZE(days
); i
++)
4473 if (!strcmpiW(day
, days
[i
]))
4480 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4482 static const WCHAR gmt
[]= { 'G','M','T',0 };
4483 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4486 SYSTEMTIME st
= { 0 };
4488 ptr
= strchrW(value
, ',');
4491 if (ptr
- value
== 3)
4493 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4495 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4496 if (st
.wDayOfWeek
> 6)
4498 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4502 else if (ptr
- value
< ARRAY_SIZE(day
))
4504 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4505 day
[ptr
- value
+ 1] = 0;
4506 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4507 if (st
.wDayOfWeek
> 6)
4509 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4515 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4520 while (isspaceW(*ptr
))
4523 num
= strtoulW(ptr
, &nextPtr
, 10);
4524 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4526 ERR("unexpected day %s\n", debugstr_w(value
));
4530 st
.wDay
= (WORD
)num
;
4534 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4539 for (monthPtr
= month
; *ptr
!= '-' && monthPtr
- month
< ARRAY_SIZE(month
) - 1;
4543 st
.wMonth
= HTTP_ParseMonth(month
);
4544 if (!st
.wMonth
|| st
.wMonth
> 12)
4546 ERR("unexpected month %s\n", debugstr_w(month
));
4552 ERR("unexpected year format %s\n", debugstr_w(ptr
));
4557 num
= strtoulW(ptr
, &nextPtr
, 10);
4558 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4560 ERR("unexpected year %s\n", debugstr_w(value
));
4564 st
.wYear
= (WORD
)num
;
4566 if (!HTTP_ParseTime(&st
, &ptr
))
4569 while (isspaceW(*ptr
))
4572 if (strcmpW(ptr
, gmt
))
4574 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4577 return SystemTimeToFileTime(&st
, ft
);
4580 static BOOL
HTTP_ParseDate(LPCWSTR value
, FILETIME
*ft
)
4582 static const WCHAR zero
[] = { '0',0 };
4585 if (!strcmpW(value
, zero
))
4587 ft
->dwLowDateTime
= ft
->dwHighDateTime
= 0;
4590 else if (strchrW(value
, ','))
4592 ret
= HTTP_ParseRfc1123Date(value
, ft
);
4595 ret
= HTTP_ParseRfc850Date(value
, ft
);
4597 ERR("unexpected date format %s\n", debugstr_w(value
));
4602 ret
= HTTP_ParseDateAsAsctime(value
, ft
);
4604 ERR("unexpected date format %s\n", debugstr_w(value
));
4609 static void HTTP_ProcessExpires(http_request_t
*request
)
4611 BOOL expirationFound
= FALSE
;
4614 EnterCriticalSection( &request
->headers_section
);
4616 /* Look for a Cache-Control header with a max-age directive, as it takes
4617 * precedence over the Expires header.
4619 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4620 if (headerIndex
!= -1)
4622 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4625 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4627 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4632 end
= ptr
+ strlenW(ptr
);
4633 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4637 static const WCHAR max_age
[] = {
4638 'm','a','x','-','a','g','e',0 };
4640 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4645 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4646 if (nextPtr
> equal
+ 1)
4650 NtQuerySystemTime( &ft
);
4651 /* Age is in seconds, FILETIME resolution is in
4652 * 100 nanosecond intervals.
4654 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4655 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4656 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4657 expirationFound
= TRUE
;
4664 while (isspaceW(*ptr
))
4671 if (!expirationFound
)
4673 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4674 if (headerIndex
!= -1)
4676 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4679 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4681 expirationFound
= TRUE
;
4682 request
->expires
= ft
;
4686 if (!expirationFound
)
4690 /* With no known age, default to 10 minutes until expiration. */
4691 NtQuerySystemTime( &t
);
4692 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4693 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4694 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4697 LeaveCriticalSection( &request
->headers_section
);
4700 static void HTTP_ProcessLastModified(http_request_t
*request
)
4704 EnterCriticalSection( &request
->headers_section
);
4706 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4707 if (headerIndex
!= -1)
4709 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4712 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4713 request
->last_modified
= ft
;
4716 LeaveCriticalSection( &request
->headers_section
);
4719 static void http_process_keep_alive(http_request_t
*req
)
4723 EnterCriticalSection( &req
->headers_section
);
4725 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4726 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4727 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4728 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4730 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4732 LeaveCriticalSection( &req
->headers_section
);
4735 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4737 netconn_t
*netconn
= NULL
;
4740 if (request
->netconn
)
4742 if (NETCON_is_alive(request
->netconn
) && drain_content(request
, TRUE
) == ERROR_SUCCESS
)
4744 reset_data_stream(request
);
4746 return ERROR_SUCCESS
;
4749 TRACE("freeing netconn\n");
4750 free_netconn(request
->netconn
);
4751 request
->netconn
= NULL
;
4754 reset_data_stream(request
);
4756 res
= HTTP_ResolveName(request
);
4757 if(res
!= ERROR_SUCCESS
)
4760 EnterCriticalSection(&connection_pool_cs
);
4762 while(!list_empty(&request
->server
->conn_pool
)) {
4763 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4764 list_remove(&netconn
->pool_entry
);
4766 if(is_valid_netconn(netconn
) && NETCON_is_alive(netconn
))
4769 TRACE("connection %p closed during idle\n", netconn
);
4770 free_netconn(netconn
);
4774 LeaveCriticalSection(&connection_pool_cs
);
4777 TRACE("<-- reusing %p netconn\n", netconn
);
4778 request
->netconn
= netconn
;
4780 return ERROR_SUCCESS
;
4783 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4784 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4786 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4787 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4788 request
->server
->addr_str
,
4789 strlen(request
->server
->addr_str
)+1);
4791 res
= create_netconn(request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4792 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4793 request
->connect_timeout
, &netconn
);
4794 if(res
!= ERROR_SUCCESS
) {
4795 ERR("create_netconn failed: %u\n", res
);
4799 request
->netconn
= netconn
;
4801 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4802 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4803 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4806 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4807 return ERROR_SUCCESS
;
4810 static char *build_ascii_request( const WCHAR
*str
, void *data
, DWORD data_len
, DWORD
*out_len
)
4812 int len
= WideCharToMultiByte( CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
4815 if (!(ret
= heap_alloc( len
+ data_len
))) return NULL
;
4816 WideCharToMultiByte( CP_ACP
, 0, str
, -1, ret
, len
, NULL
, NULL
);
4817 if (data_len
) memcpy( ret
+ len
- 1, data
, data_len
);
4818 *out_len
= len
+ data_len
- 1;
4823 static void set_content_length_header( http_request_t
*request
, DWORD len
, DWORD flags
)
4825 static const WCHAR fmtW
[] =
4826 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4827 WCHAR buf
[ARRAY_SIZE(fmtW
) + 10];
4829 sprintfW( buf
, fmtW
, len
);
4830 HTTP_HttpAddRequestHeadersW( request
, buf
, ~0u, flags
);
4833 /***********************************************************************
4834 * HTTP_HttpSendRequestW (internal)
4836 * Sends the specified request to the HTTP server
4839 * ERROR_SUCCESS on success
4840 * win32 error code on failure
4843 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4844 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4845 DWORD dwContentLength
, BOOL bEndRequest
)
4847 BOOL redirected
= FALSE
, secure_proxy_connect
= FALSE
, loop_next
;
4848 WCHAR
*request_header
= NULL
;
4849 INT responseLen
, cnt
;
4852 TRACE("--> %p\n", request
);
4854 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4856 /* if the verb is NULL default to GET */
4858 request
->verb
= heap_strdupW(szGET
);
4860 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
,
4861 HTTP_ADDREQ_FLAG_ADD_IF_NEW
| HTTP_ADDHDR_FLAG_REQ
);
4863 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4865 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4866 request
->bytesToWrite
= dwContentLength
;
4868 if (request
->session
->appInfo
->agent
)
4870 WCHAR
*agent_header
;
4871 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4874 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4875 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4876 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4878 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4879 heap_free(agent_header
);
4881 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4883 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4884 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4886 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4888 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4889 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4890 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4893 /* add the headers the caller supplied */
4894 if( lpszHeaders
&& dwHeaderLength
)
4895 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4899 DWORD len
, data_len
= dwOptionalLength
;
4900 BOOL reusing_connection
;
4906 request
->contentLength
= ~0u;
4907 request
->bytesToWrite
= 0;
4910 if (TRACE_ON(wininet
))
4914 EnterCriticalSection( &request
->headers_section
);
4915 host
= HTTP_GetHeader( request
, hostW
);
4916 TRACE("Going to url %s %s\n", debugstr_w(host
->lpszValue
), debugstr_w(request
->path
));
4917 LeaveCriticalSection( &request
->headers_section
);
4920 HTTP_FixURL(request
);
4921 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4923 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
,
4924 HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
4926 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4927 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4929 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4930 HTTP_InsertCookies(request
);
4932 res
= open_http_connection(request
, &reusing_connection
);
4933 if (res
!= ERROR_SUCCESS
)
4936 if (!reusing_connection
&& (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4938 if (request
->proxy
) secure_proxy_connect
= TRUE
;
4941 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4942 if (res
!= ERROR_SUCCESS
)
4944 WARN("failed to upgrade to secure connection\n");
4945 http_release_netconn(request
, FALSE
);
4950 if (secure_proxy_connect
)
4952 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
4953 const WCHAR
*target
= request
->server
->host_port
;
4955 if (HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
4956 set_content_length_header(request
, 0, HTTP_ADDREQ_FLAG_REPLACE
);
4958 request_header
= build_request_header(request
, connectW
, target
, g_szHttp1_1
, TRUE
);
4960 else if (request
->proxy
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
))
4962 WCHAR
*url
= build_proxy_path_url(request
);
4963 request_header
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
4968 if (request
->proxy
&& HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
) >= 0)
4969 set_content_length_header(request
, dwContentLength
, HTTP_ADDREQ_FLAG_REPLACE
);
4971 request_header
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
4974 TRACE("Request header -> %s\n", debugstr_w(request_header
) );
4976 /* send the request as ASCII, tack on the optional data */
4977 if (!lpOptional
|| redirected
|| secure_proxy_connect
)
4980 ascii_req
= build_ascii_request(request_header
, lpOptional
, data_len
, &len
);
4981 heap_free(request_header
);
4982 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
4984 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4985 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
4987 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
4988 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
4989 heap_free( ascii_req
);
4990 if(res
!= ERROR_SUCCESS
) {
4991 TRACE("send failed: %u\n", res
);
4992 if(!reusing_connection
)
4994 http_release_netconn(request
, FALSE
);
4999 request
->bytesWritten
= data_len
;
5001 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5002 INTERNET_STATUS_REQUEST_SENT
,
5003 &len
, sizeof(DWORD
));
5009 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5010 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5012 if (HTTP_GetResponseHeaders(request
, &responseLen
))
5014 http_release_netconn(request
, FALSE
);
5015 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
5018 /* FIXME: We should know that connection is closed before sending
5019 * headers. Otherwise wrong callbacks are executed */
5020 if(!responseLen
&& reusing_connection
) {
5021 TRACE("Connection closed by server, reconnecting\n");
5022 http_release_netconn(request
, FALSE
);
5027 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5028 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
5031 http_process_keep_alive(request
);
5032 HTTP_ProcessCookies(request
);
5033 HTTP_ProcessExpires(request
);
5034 HTTP_ProcessLastModified(request
);
5036 res
= set_content_length(request
);
5037 if(res
!= ERROR_SUCCESS
)
5039 if(!request
->contentLength
&& !secure_proxy_connect
)
5040 http_release_netconn(request
, TRUE
);
5042 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
5046 switch(request
->status_code
) {
5047 case HTTP_STATUS_REDIRECT
:
5048 case HTTP_STATUS_MOVED
:
5049 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
5050 case HTTP_STATUS_REDIRECT_METHOD
:
5051 new_url
= get_redirect_url(request
);
5055 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5056 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5058 heap_free(request
->verb
);
5059 request
->verb
= heap_strdupW(szGET
);
5061 http_release_netconn(request
, drain_content(request
, FALSE
) == ERROR_SUCCESS
);
5062 res
= HTTP_HandleRedirect(request
, new_url
);
5064 if (res
== ERROR_SUCCESS
)
5069 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5071 WCHAR szAuthValue
[2048];
5073 if (request
->status_code
== HTTP_STATUS_DENIED
)
5075 WCHAR
*host
= heap_strdupW( request
->server
->canon_host_port
);
5077 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5079 if (HTTP_DoAuthorization(request
, szAuthValue
,
5081 request
->session
->userName
,
5082 request
->session
->password
, host
))
5084 if (drain_content(request
, TRUE
) != ERROR_SUCCESS
)
5086 FIXME("Could not drain content\n");
5087 http_release_netconn(request
, FALSE
);
5096 TRACE("Cleaning wrong authorization data\n");
5097 destroy_authinfo(request
->authInfo
);
5098 request
->authInfo
= NULL
;
5101 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5104 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5106 if (HTTP_DoAuthorization(request
, szAuthValue
,
5107 &request
->proxyAuthInfo
,
5108 request
->session
->appInfo
->proxyUsername
,
5109 request
->session
->appInfo
->proxyPassword
,
5112 if (drain_content(request
, TRUE
) != ERROR_SUCCESS
)
5114 FIXME("Could not drain content\n");
5115 http_release_netconn(request
, FALSE
);
5123 TRACE("Cleaning wrong proxy authorization data\n");
5124 destroy_authinfo(request
->proxyAuthInfo
);
5125 request
->proxyAuthInfo
= NULL
;
5129 if (secure_proxy_connect
&& request
->status_code
== HTTP_STATUS_OK
)
5131 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
5132 if (res
!= ERROR_SUCCESS
)
5134 WARN("failed to upgrade to secure proxy connection\n");
5135 http_release_netconn( request
, FALSE
);
5138 remove_header(request
, szProxy_Authorization
, TRUE
);
5139 destroy_authinfo(request
->proxyAuthInfo
);
5140 request
->proxyAuthInfo
= NULL
;
5141 request
->contentLength
= 0;
5142 request
->netconn_stream
.content_length
= 0;
5144 secure_proxy_connect
= FALSE
;
5149 res
= ERROR_SUCCESS
;
5154 /* TODO: send notification for P3P header */
5156 if(res
== ERROR_SUCCESS
)
5157 create_cache_entry(request
);
5159 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5161 if (res
== ERROR_SUCCESS
) {
5162 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5163 HTTP_ReceiveRequestData(request
);
5165 send_request_complete(request
,
5166 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5168 send_request_complete(request
, 0, res
);
5184 } send_request_task_t
;
5186 /***********************************************************************
5188 * Helper functions for the HttpSendRequest(Ex) functions
5191 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5193 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5194 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5196 TRACE("%p\n", request
);
5198 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5199 task
->optional_len
, task
->content_len
, task
->end_request
);
5201 heap_free(task
->headers
);
5205 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5208 DWORD res
= ERROR_SUCCESS
;
5210 if(!is_valid_netconn(request
->netconn
)) {
5211 WARN("Not connected\n");
5212 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5213 return ERROR_INTERNET_OPERATION_CANCELLED
;
5216 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5217 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5219 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5220 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5222 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5223 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5225 /* process cookies here. Is this right? */
5226 http_process_keep_alive(request
);
5227 HTTP_ProcessCookies(request
);
5228 HTTP_ProcessExpires(request
);
5229 HTTP_ProcessLastModified(request
);
5231 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5232 if(!request
->contentLength
)
5233 http_release_netconn(request
, TRUE
);
5236 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5238 switch(request
->status_code
) {
5239 case HTTP_STATUS_REDIRECT
:
5240 case HTTP_STATUS_MOVED
:
5241 case HTTP_STATUS_REDIRECT_METHOD
:
5242 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5245 new_url
= get_redirect_url(request
);
5249 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5250 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5252 heap_free(request
->verb
);
5253 request
->verb
= heap_strdupW(szGET
);
5255 http_release_netconn(request
, drain_content(request
, FALSE
) == ERROR_SUCCESS
);
5256 res
= HTTP_HandleRedirect(request
, new_url
);
5258 if (res
== ERROR_SUCCESS
)
5259 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5264 if(res
== ERROR_SUCCESS
)
5265 create_cache_entry(request
);
5267 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5268 HTTP_ReceiveRequestData(request
);
5270 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5275 /***********************************************************************
5276 * HttpEndRequestA (WININET.@)
5278 * Ends an HTTP request that was started by HttpSendRequestEx
5281 * TRUE if successful
5285 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5286 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5288 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5292 SetLastError(ERROR_INVALID_PARAMETER
);
5296 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5303 } end_request_task_t
;
5305 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5307 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5308 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5312 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5315 /***********************************************************************
5316 * HttpEndRequestW (WININET.@)
5318 * Ends an HTTP request that was started by HttpSendRequestEx
5321 * TRUE if successful
5325 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5326 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5328 http_request_t
*request
;
5331 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5335 SetLastError(ERROR_INVALID_PARAMETER
);
5339 request
= (http_request_t
*) get_handle_object( hRequest
);
5341 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5343 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5345 WININET_Release( &request
->hdr
);
5348 request
->hdr
.dwFlags
|= dwFlags
;
5350 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5352 end_request_task_t
*task
;
5354 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5355 task
->flags
= dwFlags
;
5356 task
->context
= dwContext
;
5358 INTERNET_AsyncCall(&task
->hdr
);
5359 res
= ERROR_IO_PENDING
;
5362 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5364 WININET_Release( &request
->hdr
);
5365 TRACE("%u <--\n", res
);
5366 if(res
!= ERROR_SUCCESS
)
5368 return res
== ERROR_SUCCESS
;
5371 /***********************************************************************
5372 * HttpSendRequestExA (WININET.@)
5374 * Sends the specified request to the HTTP server and allows chunked
5379 * Failure: FALSE, call GetLastError() for more information.
5381 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5382 LPINTERNET_BUFFERSA lpBuffersIn
,
5383 LPINTERNET_BUFFERSA lpBuffersOut
,
5384 DWORD dwFlags
, DWORD_PTR dwContext
)
5386 INTERNET_BUFFERSW BuffersInW
;
5389 LPWSTR header
= NULL
;
5391 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5392 lpBuffersOut
, dwFlags
, dwContext
);
5396 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5397 if (lpBuffersIn
->lpcszHeader
)
5399 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5400 lpBuffersIn
->dwHeadersLength
,0,0);
5401 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5402 if (!(BuffersInW
.lpcszHeader
= header
))
5404 SetLastError(ERROR_OUTOFMEMORY
);
5407 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5408 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5412 BuffersInW
.lpcszHeader
= NULL
;
5413 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5414 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5415 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5416 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5417 BuffersInW
.Next
= NULL
;
5420 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5426 /***********************************************************************
5427 * HttpSendRequestExW (WININET.@)
5429 * Sends the specified request to the HTTP server and allows chunked
5434 * Failure: FALSE, call GetLastError() for more information.
5436 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5437 LPINTERNET_BUFFERSW lpBuffersIn
,
5438 LPINTERNET_BUFFERSW lpBuffersOut
,
5439 DWORD dwFlags
, DWORD_PTR dwContext
)
5441 http_request_t
*request
;
5442 http_session_t
*session
;
5446 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5447 lpBuffersOut
, dwFlags
, dwContext
);
5449 request
= (http_request_t
*) get_handle_object( hRequest
);
5451 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5453 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5457 session
= request
->session
;
5458 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5459 hIC
= session
->appInfo
;
5460 assert(hIC
->hdr
.htype
== WH_HINIT
);
5462 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5464 send_request_task_t
*task
;
5466 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5471 if (lpBuffersIn
->lpcszHeader
)
5473 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5474 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5476 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5478 task
->headers
= heap_alloc(size
);
5479 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5481 else task
->headers
= NULL
;
5483 task
->headers_len
= size
/ sizeof(WCHAR
);
5484 task
->optional
= lpBuffersIn
->lpvBuffer
;
5485 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5486 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5490 task
->headers
= NULL
;
5491 task
->headers_len
= 0;
5492 task
->optional
= NULL
;
5493 task
->optional_len
= 0;
5494 task
->content_len
= 0;
5497 task
->end_request
= FALSE
;
5499 INTERNET_AsyncCall(&task
->hdr
);
5500 res
= ERROR_IO_PENDING
;
5505 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5506 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5507 lpBuffersIn
->dwBufferTotal
, FALSE
);
5509 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5514 WININET_Release( &request
->hdr
);
5518 return res
== ERROR_SUCCESS
;
5521 /***********************************************************************
5522 * HttpSendRequestW (WININET.@)
5524 * Sends the specified request to the HTTP server
5531 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5532 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5534 http_request_t
*request
;
5535 http_session_t
*session
= NULL
;
5536 appinfo_t
*hIC
= NULL
;
5537 DWORD res
= ERROR_SUCCESS
;
5539 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5540 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5542 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5543 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5545 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5549 session
= request
->session
;
5550 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5552 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5556 hIC
= session
->appInfo
;
5557 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5559 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5563 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5565 send_request_task_t
*task
;
5567 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5572 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5573 else size
= dwHeaderLength
* sizeof(WCHAR
);
5575 task
->headers
= heap_alloc(size
);
5576 memcpy(task
->headers
, lpszHeaders
, size
);
5579 task
->headers
= NULL
;
5580 task
->headers_len
= dwHeaderLength
;
5581 task
->optional
= lpOptional
;
5582 task
->optional_len
= dwOptionalLength
;
5583 task
->content_len
= dwOptionalLength
;
5584 task
->end_request
= TRUE
;
5586 INTERNET_AsyncCall(&task
->hdr
);
5587 res
= ERROR_IO_PENDING
;
5591 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5592 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5593 dwOptionalLength
, TRUE
);
5597 WININET_Release( &request
->hdr
);
5600 return res
== ERROR_SUCCESS
;
5603 /***********************************************************************
5604 * HttpSendRequestA (WININET.@)
5606 * Sends the specified request to the HTTP server
5613 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5614 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5617 LPWSTR szHeaders
=NULL
;
5618 DWORD nLen
=dwHeaderLength
;
5619 if(lpszHeaders
!=NULL
)
5621 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5622 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5623 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5625 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5626 heap_free(szHeaders
);
5630 /***********************************************************************
5631 * HTTPSESSION_Destroy (internal)
5633 * Deallocate session handle
5636 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5638 http_session_t
*session
= (http_session_t
*) hdr
;
5640 TRACE("%p\n", session
);
5642 WININET_Release(&session
->appInfo
->hdr
);
5644 heap_free(session
->hostName
);
5645 heap_free(session
->password
);
5646 heap_free(session
->userName
);
5649 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5651 http_session_t
*ses
= (http_session_t
*)hdr
;
5654 case INTERNET_OPTION_HANDLE_TYPE
:
5655 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5657 if (*size
< sizeof(ULONG
))
5658 return ERROR_INSUFFICIENT_BUFFER
;
5660 *size
= sizeof(DWORD
);
5661 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5662 return ERROR_SUCCESS
;
5663 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5664 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5666 if (*size
< sizeof(DWORD
))
5667 return ERROR_INSUFFICIENT_BUFFER
;
5669 *size
= sizeof(DWORD
);
5670 *(DWORD
*)buffer
= ses
->connect_timeout
;
5671 return ERROR_SUCCESS
;
5673 case INTERNET_OPTION_SEND_TIMEOUT
:
5674 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5676 if (*size
< sizeof(DWORD
))
5677 return ERROR_INSUFFICIENT_BUFFER
;
5679 *size
= sizeof(DWORD
);
5680 *(DWORD
*)buffer
= ses
->send_timeout
;
5681 return ERROR_SUCCESS
;
5683 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5684 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5686 if (*size
< sizeof(DWORD
))
5687 return ERROR_INSUFFICIENT_BUFFER
;
5689 *size
= sizeof(DWORD
);
5690 *(DWORD
*)buffer
= ses
->receive_timeout
;
5691 return ERROR_SUCCESS
;
5694 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5697 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5699 http_session_t
*ses
= (http_session_t
*)hdr
;
5702 case INTERNET_OPTION_USERNAME
:
5704 heap_free(ses
->userName
);
5705 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5706 return ERROR_SUCCESS
;
5708 case INTERNET_OPTION_PASSWORD
:
5710 heap_free(ses
->password
);
5711 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5712 return ERROR_SUCCESS
;
5714 case INTERNET_OPTION_PROXY_USERNAME
:
5716 heap_free(ses
->appInfo
->proxyUsername
);
5717 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5718 return ERROR_SUCCESS
;
5720 case INTERNET_OPTION_PROXY_PASSWORD
:
5722 heap_free(ses
->appInfo
->proxyPassword
);
5723 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5724 return ERROR_SUCCESS
;
5726 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5728 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5729 ses
->connect_timeout
= *(DWORD
*)buffer
;
5730 return ERROR_SUCCESS
;
5732 case INTERNET_OPTION_SEND_TIMEOUT
:
5734 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5735 ses
->send_timeout
= *(DWORD
*)buffer
;
5736 return ERROR_SUCCESS
;
5738 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5740 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5741 ses
->receive_timeout
= *(DWORD
*)buffer
;
5742 return ERROR_SUCCESS
;
5747 return INET_SetOption(hdr
, option
, buffer
, size
);
5750 static const object_vtbl_t HTTPSESSIONVtbl
= {
5751 HTTPSESSION_Destroy
,
5753 HTTPSESSION_QueryOption
,
5754 HTTPSESSION_SetOption
,
5762 /***********************************************************************
5763 * HTTP_Connect (internal)
5765 * Create http session handle
5768 * HINTERNET a session handle on success
5772 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5773 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5774 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5775 DWORD dwInternalFlags
, HINTERNET
*ret
)
5777 http_session_t
*session
= NULL
;
5781 if (!lpszServerName
|| !lpszServerName
[0])
5782 return ERROR_INVALID_PARAMETER
;
5784 assert( hIC
->hdr
.htype
== WH_HINIT
);
5786 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5788 return ERROR_OUTOFMEMORY
;
5791 * According to my tests. The name is not resolved until a request is sent
5794 session
->hdr
.htype
= WH_HHTTPSESSION
;
5795 session
->hdr
.dwFlags
= dwFlags
;
5796 session
->hdr
.dwContext
= dwContext
;
5797 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5799 WININET_AddRef( &hIC
->hdr
);
5800 session
->appInfo
= hIC
;
5801 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5803 session
->hostName
= heap_strdupW(lpszServerName
);
5804 if (lpszUserName
&& lpszUserName
[0])
5805 session
->userName
= heap_strdupW(lpszUserName
);
5806 session
->password
= heap_strdupW(lpszPassword
);
5807 session
->hostPort
= serverPort
;
5808 session
->connect_timeout
= hIC
->connect_timeout
;
5809 session
->send_timeout
= 0;
5810 session
->receive_timeout
= 0;
5812 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5813 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5815 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5816 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5821 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5825 TRACE("%p --> %p\n", hIC
, session
);
5827 *ret
= session
->hdr
.hInternet
;
5828 return ERROR_SUCCESS
;
5831 /***********************************************************************
5832 * HTTP_clear_response_headers (internal)
5834 * clear out any old response headers
5836 static void HTTP_clear_response_headers( http_request_t
*request
)
5840 EnterCriticalSection( &request
->headers_section
);
5842 for( i
=0; i
<request
->nCustHeaders
; i
++)
5844 if( !request
->custHeaders
[i
].lpszField
)
5846 if( !request
->custHeaders
[i
].lpszValue
)
5848 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5850 HTTP_DeleteCustomHeader( request
, i
);
5854 LeaveCriticalSection( &request
->headers_section
);
5857 /***********************************************************************
5858 * HTTP_GetResponseHeaders (internal)
5860 * Read server response
5867 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5870 WCHAR buffer
[MAX_REPLY_LEN
];
5871 DWORD buflen
= MAX_REPLY_LEN
;
5873 char bufferA
[MAX_REPLY_LEN
];
5874 LPWSTR status_code
= NULL
, status_text
= NULL
;
5875 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5876 BOOL codeHundred
= FALSE
;
5880 if(!is_valid_netconn(request
->netconn
))
5883 /* clear old response headers (eg. from a redirect response) */
5884 HTTP_clear_response_headers( request
);
5886 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5889 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5891 buflen
= MAX_REPLY_LEN
;
5892 if ((res
= read_line(request
, bufferA
, &buflen
)))
5895 if (!buflen
) goto lend
;
5898 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5899 /* check is this a status code line? */
5900 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5902 /* split the version from the status code */
5903 status_code
= strchrW( buffer
, ' ' );
5908 /* split the status code from the status text */
5909 status_text
= strchrW( status_code
, ' ' );
5913 request
->status_code
= atoiW(status_code
);
5915 TRACE("version [%s] status code [%s] status text [%s]\n",
5916 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5918 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5920 else if (!codeHundred
)
5922 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5924 heap_free(request
->version
);
5925 heap_free(request
->statusText
);
5927 request
->status_code
= HTTP_STATUS_OK
;
5928 request
->version
= heap_strdupW(g_szHttp1_0
);
5929 request
->statusText
= heap_strdupW(szOK
);
5933 } while (codeHundred
);
5935 /* Add status code */
5936 HTTP_ProcessHeader(request
, szStatus
, status_code
,
5937 HTTP_ADDHDR_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_ADD
);
5939 heap_free(request
->version
);
5940 heap_free(request
->statusText
);
5942 request
->version
= heap_strdupW(buffer
);
5943 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
5945 /* Restore the spaces */
5946 *(status_code
-1) = ' ';
5948 *(status_text
-1) = ' ';
5950 /* Parse each response line */
5953 buflen
= MAX_REPLY_LEN
;
5954 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
5956 LPWSTR
* pFieldAndValue
;
5958 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
5960 if (!bufferA
[0]) break;
5961 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5963 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
5966 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
5967 HTTP_ADDREQ_FLAG_ADD
);
5968 HTTP_FreeTokens(pFieldAndValue
);
5979 res
= ERROR_SUCCESS
;
5988 /***********************************************************************
5989 * HTTP_InterpretHttpHeader (internal)
5991 * Parse server response
5995 * Pointer to array of field, value, NULL on success.
5998 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
6000 LPWSTR
* pTokenPair
;
6004 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
6006 pszColon
= strchrW(buffer
, ':');
6007 /* must have two tokens */
6010 HTTP_FreeTokens(pTokenPair
);
6012 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
6016 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
6019 HTTP_FreeTokens(pTokenPair
);
6022 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
6023 pTokenPair
[0][pszColon
- buffer
] = '\0';
6027 len
= strlenW(pszColon
);
6028 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
6031 HTTP_FreeTokens(pTokenPair
);
6034 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
6036 strip_spaces(pTokenPair
[0]);
6037 strip_spaces(pTokenPair
[1]);
6039 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
6043 /***********************************************************************
6044 * HTTP_ProcessHeader (internal)
6046 * Stuff header into header tables according to <dwModifier>
6050 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6052 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
6054 LPHTTPHEADERW lphttpHdr
= NULL
;
6056 BOOL request_only
= !!(dwModifier
& HTTP_ADDHDR_FLAG_REQ
);
6057 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6059 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6061 EnterCriticalSection( &request
->headers_section
);
6063 /* REPLACE wins out over ADD */
6064 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6065 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6067 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6070 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6074 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6076 LeaveCriticalSection( &request
->headers_section
);
6077 return ERROR_HTTP_INVALID_HEADER
;
6079 lphttpHdr
= &request
->custHeaders
[index
];
6085 hdr
.lpszField
= (LPWSTR
)field
;
6086 hdr
.lpszValue
= (LPWSTR
)value
;
6087 hdr
.wFlags
= hdr
.wCount
= 0;
6089 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6090 hdr
.wFlags
|= HDR_ISREQUEST
;
6092 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6093 LeaveCriticalSection( &request
->headers_section
);
6096 /* no value to delete */
6099 LeaveCriticalSection( &request
->headers_section
);
6100 return ERROR_SUCCESS
;
6103 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6104 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6106 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6108 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6110 HTTP_DeleteCustomHeader( request
, index
);
6112 if (value
&& value
[0])
6116 hdr
.lpszField
= (LPWSTR
)field
;
6117 hdr
.lpszValue
= (LPWSTR
)value
;
6118 hdr
.wFlags
= hdr
.wCount
= 0;
6120 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6121 hdr
.wFlags
|= HDR_ISREQUEST
;
6123 res
= HTTP_InsertCustomHeader(request
, &hdr
);
6124 LeaveCriticalSection( &request
->headers_section
);
6128 LeaveCriticalSection( &request
->headers_section
);
6129 return ERROR_SUCCESS
;
6131 else if (dwModifier
& COALESCEFLAGS
)
6136 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6137 INT valuelen
= strlenW(value
);
6139 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6142 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6144 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6147 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6150 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6152 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6155 lphttpHdr
->lpszValue
= lpsztmp
;
6156 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6159 lphttpHdr
->lpszValue
[origlen
] = ch
;
6161 lphttpHdr
->lpszValue
[origlen
] = ' ';
6165 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6166 lphttpHdr
->lpszValue
[len
] = '\0';
6167 res
= ERROR_SUCCESS
;
6171 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6172 res
= ERROR_OUTOFMEMORY
;
6175 TRACE("<-- %d\n", res
);
6176 LeaveCriticalSection( &request
->headers_section
);
6180 /***********************************************************************
6181 * HTTP_GetCustomHeaderIndex (internal)
6183 * Return index of custom header from header array
6184 * Headers section must be held
6186 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6187 int requested_index
, BOOL request_only
)
6191 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6193 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6195 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6198 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6201 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6204 if (requested_index
== 0)
6209 if (index
>= request
->nCustHeaders
)
6212 TRACE("Return: %d\n", index
);
6217 /***********************************************************************
6218 * HTTP_InsertCustomHeader (internal)
6220 * Insert header into array
6221 * Headers section must be held
6223 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6226 LPHTTPHEADERW lph
= NULL
;
6228 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6229 count
= request
->nCustHeaders
+ 1;
6231 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6233 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6236 return ERROR_OUTOFMEMORY
;
6238 request
->custHeaders
= lph
;
6239 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6240 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6241 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6242 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6243 request
->nCustHeaders
++;
6245 return ERROR_SUCCESS
;
6249 /***********************************************************************
6250 * HTTP_DeleteCustomHeader (internal)
6252 * Delete header from array
6253 * If this function is called, the index may change.
6254 * Headers section must be held
6256 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6258 if( request
->nCustHeaders
<= 0 )
6260 if( index
>= request
->nCustHeaders
)
6262 request
->nCustHeaders
--;
6264 heap_free(request
->custHeaders
[index
].lpszField
);
6265 heap_free(request
->custHeaders
[index
].lpszValue
);
6267 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6268 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6269 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6275 /***********************************************************************
6276 * IsHostInProxyBypassList (@)
6281 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6283 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);