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
38 #include <wine/exception.h>
41 #include "inet_ntop.c"
43 static const WCHAR g_szHttp1_0
[] = {'H','T','T','P','/','1','.','0',0};
44 static const WCHAR g_szHttp1_1
[] = {'H','T','T','P','/','1','.','1',0};
45 static const WCHAR szOK
[] = {'O','K',0};
46 static const WCHAR szDefaultHeader
[] = {'H','T','T','P','/','1','.','0',' ','2','0','0',' ','O','K',0};
47 static const WCHAR hostW
[] = { 'H','o','s','t',0 };
48 static const WCHAR szAuthorization
[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
49 static const WCHAR szProxy_Authorization
[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
50 static const WCHAR szStatus
[] = { 'S','t','a','t','u','s',0 };
51 static const WCHAR szKeepAlive
[] = {'K','e','e','p','-','A','l','i','v','e',0};
52 static const WCHAR szGET
[] = { 'G','E','T', 0 };
53 static const WCHAR szHEAD
[] = { 'H','E','A','D', 0 };
54 static const WCHAR szCrLf
[] = {'\r','\n', 0};
56 static const WCHAR szAccept
[] = { 'A','c','c','e','p','t',0 };
57 static const WCHAR szAccept_Charset
[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
58 static const WCHAR szAccept_Encoding
[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
59 static const WCHAR szAccept_Language
[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
60 static const WCHAR szAccept_Ranges
[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
61 static const WCHAR szAge
[] = { 'A','g','e',0 };
62 static const WCHAR szAllow
[] = { 'A','l','l','o','w',0 };
63 static const WCHAR szCache_Control
[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
64 static const WCHAR szConnection
[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
65 static const WCHAR szContent_Base
[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
66 static const WCHAR szContent_Disposition
[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
67 static const WCHAR szContent_Encoding
[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
68 static const WCHAR szContent_ID
[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
69 static const WCHAR szContent_Language
[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
70 static const WCHAR szContent_Length
[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
71 static const WCHAR szContent_Location
[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
72 static const WCHAR szContent_MD5
[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
73 static const WCHAR szContent_Range
[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
74 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 };
75 static const WCHAR szContent_Type
[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
76 static const WCHAR szCookie
[] = { 'C','o','o','k','i','e',0 };
77 static const WCHAR szDate
[] = { 'D','a','t','e',0 };
78 static const WCHAR szFrom
[] = { 'F','r','o','m',0 };
79 static const WCHAR szETag
[] = { 'E','T','a','g',0 };
80 static const WCHAR szExpect
[] = { 'E','x','p','e','c','t',0 };
81 static const WCHAR szExpires
[] = { 'E','x','p','i','r','e','s',0 };
82 static const WCHAR szIf_Match
[] = { 'I','f','-','M','a','t','c','h',0 };
83 static const WCHAR szIf_Modified_Since
[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
84 static const WCHAR szIf_None_Match
[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
85 static const WCHAR szIf_Range
[] = { 'I','f','-','R','a','n','g','e',0 };
86 static const WCHAR szIf_Unmodified_Since
[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
87 static const WCHAR szLast_Modified
[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
88 static const WCHAR szLocation
[] = { 'L','o','c','a','t','i','o','n',0 };
89 static const WCHAR szMax_Forwards
[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
90 static const WCHAR szMime_Version
[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
91 static const WCHAR szPragma
[] = { 'P','r','a','g','m','a',0 };
92 static const WCHAR szProxy_Authenticate
[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
93 static const WCHAR szProxy_Connection
[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
94 static const WCHAR szPublic
[] = { 'P','u','b','l','i','c',0 };
95 static const WCHAR szRange
[] = { 'R','a','n','g','e',0 };
96 static const WCHAR szReferer
[] = { 'R','e','f','e','r','e','r',0 };
97 static const WCHAR szRetry_After
[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
98 static const WCHAR szServer
[] = { 'S','e','r','v','e','r',0 };
99 static const WCHAR szSet_Cookie
[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
100 static const WCHAR szTransfer_Encoding
[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
101 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 };
102 static const WCHAR szUpgrade
[] = { 'U','p','g','r','a','d','e',0 };
103 static const WCHAR szURI
[] = { 'U','R','I',0 };
104 static const WCHAR szUser_Agent
[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
105 static const WCHAR szVary
[] = { 'V','a','r','y',0 };
106 static const WCHAR szVia
[] = { 'V','i','a',0 };
107 static const WCHAR szWarning
[] = { 'W','a','r','n','i','n','g',0 };
108 static const WCHAR szWWW_Authenticate
[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
110 static const WCHAR emptyW
[] = {0};
112 #define HTTP_REFERER szReferer
113 #define HTTP_ACCEPT szAccept
114 #define HTTP_USERAGENT szUser_Agent
116 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
117 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
118 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
119 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
120 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
121 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
122 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
124 #define COLLECT_TIME 60000
126 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
137 unsigned int auth_data_len
;
138 BOOL finished
; /* finished authenticating */
142 typedef struct _basicAuthorizationData
149 UINT authorizationLen
;
150 } basicAuthorizationData
;
152 typedef struct _authorizationData
166 static struct list basicAuthorizationCache
= LIST_INIT(basicAuthorizationCache
);
167 static struct list authorizationCache
= LIST_INIT(authorizationCache
);
169 static CRITICAL_SECTION authcache_cs
;
170 static CRITICAL_SECTION_DEBUG critsect_debug
=
173 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
174 0, 0, { (DWORD_PTR
)(__FILE__
": authcache_cs") }
176 static CRITICAL_SECTION authcache_cs
= { &critsect_debug
, -1, 0, 0, 0, 0 };
178 static DWORD
HTTP_GetResponseHeaders(http_request_t
*req
, INT
*len
);
179 static DWORD
HTTP_ProcessHeader(http_request_t
*req
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
);
180 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
);
181 static DWORD
HTTP_InsertCustomHeader(http_request_t
*req
, LPHTTPHEADERW lpHdr
);
182 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*req
, LPCWSTR lpszField
, INT index
, BOOL Request
);
183 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*req
, DWORD index
);
184 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
);
185 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*, DWORD
, LPVOID
, LPDWORD
, LPDWORD
);
186 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*req
, LPCWSTR lpszUrl
);
187 static UINT
HTTP_DecodeBase64(LPCWSTR base64
, LPSTR bin
);
188 static BOOL
HTTP_VerifyValidHeader(http_request_t
*req
, LPCWSTR field
);
189 static BOOL
drain_content(http_request_t
*,BOOL
);
191 static CRITICAL_SECTION connection_pool_cs
;
192 static CRITICAL_SECTION_DEBUG connection_pool_debug
=
194 0, 0, &connection_pool_cs
,
195 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
196 0, 0, { (DWORD_PTR
)(__FILE__
": connection_pool_cs") }
198 static CRITICAL_SECTION connection_pool_cs
= { &connection_pool_debug
, -1, 0, 0, 0, 0 };
200 static struct list connection_pool
= LIST_INIT(connection_pool
);
201 static BOOL collector_running
;
203 void server_addref(server_t
*server
)
205 InterlockedIncrement(&server
->ref
);
208 void server_release(server_t
*server
)
210 if(InterlockedDecrement(&server
->ref
))
214 EnterCriticalSection(&connection_pool_cs
);
216 list_remove(&server
->entry
);
218 LeaveCriticalSection(&connection_pool_cs
);
221 if(server
->cert_chain
)
222 CertFreeCertificateChain(server
->cert_chain
);
223 heap_free(server
->name
);
224 heap_free(server
->scheme_host_port
);
228 static BOOL
process_host_port(server_t
*server
)
234 static const WCHAR httpW
[] = {'h','t','t','p',0};
235 static const WCHAR httpsW
[] = {'h','t','t','p','s',0};
236 static const WCHAR formatW
[] = {'%','s',':','/','/','%','s',':','%','u',0};
238 name_len
= strlenW(server
->name
);
239 buf
= heap_alloc((name_len
+ 10 /* strlen("://:<port>") */)*sizeof(WCHAR
) + sizeof(httpsW
));
243 sprintfW(buf
, formatW
, server
->is_https
? httpsW
: httpW
, server
->name
, server
->port
);
244 server
->scheme_host_port
= buf
;
246 server
->host_port
= server
->scheme_host_port
+ 7 /* strlen("http://") */;
250 default_port
= server
->port
== (server
->is_https
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
);
251 server
->canon_host_port
= default_port
? server
->name
: server
->host_port
;
255 server_t
*get_server(const WCHAR
*name
, INTERNET_PORT port
, BOOL is_https
, BOOL do_create
)
257 server_t
*iter
, *server
= NULL
;
259 if(port
== INTERNET_INVALID_PORT_NUMBER
)
260 port
= INTERNET_DEFAULT_HTTP_PORT
;
262 EnterCriticalSection(&connection_pool_cs
);
264 LIST_FOR_EACH_ENTRY(iter
, &connection_pool
, server_t
, entry
) {
265 if(iter
->port
== port
&& !strcmpW(iter
->name
, name
) && iter
->is_https
== is_https
) {
267 server_addref(server
);
272 if(!server
&& do_create
) {
273 server
= heap_alloc_zero(sizeof(*server
));
275 server
->ref
= 2; /* list reference and return */
277 server
->is_https
= is_https
;
278 list_init(&server
->conn_pool
);
279 server
->name
= heap_strdupW(name
);
280 if(server
->name
&& process_host_port(server
)) {
281 list_add_head(&connection_pool
, &server
->entry
);
289 LeaveCriticalSection(&connection_pool_cs
);
294 BOOL
collect_connections(collect_type_t collect_type
)
296 netconn_t
*netconn
, *netconn_safe
;
297 server_t
*server
, *server_safe
;
298 BOOL remaining
= FALSE
;
301 now
= GetTickCount();
303 LIST_FOR_EACH_ENTRY_SAFE(server
, server_safe
, &connection_pool
, server_t
, entry
) {
304 LIST_FOR_EACH_ENTRY_SAFE(netconn
, netconn_safe
, &server
->conn_pool
, netconn_t
, pool_entry
) {
305 if(collect_type
> COLLECT_TIMEOUT
|| netconn
->keep_until
< now
) {
306 TRACE("freeing %p\n", netconn
);
307 list_remove(&netconn
->pool_entry
);
308 free_netconn(netconn
);
314 if(collect_type
== COLLECT_CLEANUP
) {
315 list_remove(&server
->entry
);
316 list_init(&server
->entry
);
317 server_release(server
);
324 static DWORD WINAPI
collect_connections_proc(void *arg
)
326 BOOL remaining_conns
;
329 /* FIXME: Use more sophisticated method */
332 EnterCriticalSection(&connection_pool_cs
);
334 remaining_conns
= collect_connections(COLLECT_TIMEOUT
);
336 collector_running
= FALSE
;
338 LeaveCriticalSection(&connection_pool_cs
);
339 }while(remaining_conns
);
341 FreeLibraryAndExitThread(WININET_hModule
, 0);
344 static LPHTTPHEADERW
HTTP_GetHeader(http_request_t
*req
, LPCWSTR head
)
347 HeaderIndex
= HTTP_GetCustomHeaderIndex(req
, head
, 0, TRUE
);
348 if (HeaderIndex
== -1)
351 return &req
->custHeaders
[HeaderIndex
];
360 struct data_stream_vtbl_t
{
361 DWORD (*get_avail_data
)(data_stream_t
*,http_request_t
*);
362 BOOL (*end_of_data
)(data_stream_t
*,http_request_t
*);
363 DWORD (*read
)(data_stream_t
*,http_request_t
*,BYTE
*,DWORD
,DWORD
*,read_mode_t
);
364 BOOL (*drain_content
)(data_stream_t
*,http_request_t
*);
365 void (*destroy
)(data_stream_t
*);
369 data_stream_t data_stream
;
371 BYTE buf
[READ_BUFFER_SIZE
];
377 static inline void destroy_data_stream(data_stream_t
*stream
)
379 stream
->vtbl
->destroy(stream
);
382 static void reset_data_stream(http_request_t
*req
)
384 destroy_data_stream(req
->data_stream
);
385 req
->data_stream
= &req
->netconn_stream
.data_stream
;
386 req
->read_pos
= req
->read_size
= req
->netconn_stream
.content_read
= 0;
387 req
->read_chunked
= req
->read_gzip
= FALSE
;
393 data_stream_t stream
;
394 data_stream_t
*parent_stream
;
396 BYTE buf
[READ_BUFFER_SIZE
];
402 static DWORD
gzip_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
404 /* Allow reading only from read buffer */
408 static BOOL
gzip_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
410 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
411 return gzip_stream
->end_of_data
;
414 static DWORD
gzip_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
415 DWORD
*read
, read_mode_t read_mode
)
417 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
418 z_stream
*zstream
= &gzip_stream
->zstream
;
419 DWORD current_read
, ret_read
= 0;
422 DWORD res
= ERROR_SUCCESS
;
424 while(size
&& !gzip_stream
->end_of_data
) {
425 end
= gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
);
427 if(gzip_stream
->buf_size
<= 64 && !end
) {
428 if(gzip_stream
->buf_pos
) {
429 if(gzip_stream
->buf_size
)
430 memmove(gzip_stream
->buf
, gzip_stream
->buf
+gzip_stream
->buf_pos
, gzip_stream
->buf_size
);
431 gzip_stream
->buf_pos
= 0;
433 res
= gzip_stream
->parent_stream
->vtbl
->read(gzip_stream
->parent_stream
, req
, gzip_stream
->buf
+gzip_stream
->buf_size
,
434 sizeof(gzip_stream
->buf
)-gzip_stream
->buf_size
, ¤t_read
, read_mode
);
435 gzip_stream
->buf_size
+= current_read
;
436 if(res
!= ERROR_SUCCESS
)
438 end
= gzip_stream
->parent_stream
->vtbl
->end_of_data(gzip_stream
->parent_stream
, req
);
439 if(!current_read
&& !end
) {
440 if(read_mode
!= READMODE_NOBLOCK
) {
441 WARN("unexpected end of data\n");
442 gzip_stream
->end_of_data
= TRUE
;
446 if(gzip_stream
->buf_size
<= 64 && !end
)
450 zstream
->next_in
= gzip_stream
->buf
+gzip_stream
->buf_pos
;
451 zstream
->avail_in
= gzip_stream
->buf_size
-(end
? 0 : 64);
452 zstream
->next_out
= buf
+ret_read
;
453 zstream
->avail_out
= size
;
454 zres
= inflate(&gzip_stream
->zstream
, 0);
455 current_read
= size
- zstream
->avail_out
;
456 size
-= current_read
;
457 ret_read
+= current_read
;
458 gzip_stream
->buf_size
-= zstream
->next_in
- (gzip_stream
->buf
+gzip_stream
->buf_pos
);
459 gzip_stream
->buf_pos
= zstream
->next_in
-gzip_stream
->buf
;
460 if(zres
== Z_STREAM_END
) {
461 TRACE("end of data\n");
462 gzip_stream
->end_of_data
= TRUE
;
464 }else if(zres
!= Z_OK
) {
465 WARN("inflate failed %d: %s\n", zres
, debugstr_a(zstream
->msg
));
467 res
= ERROR_INTERNET_DECODING_FAILED
;
471 if(ret_read
&& read_mode
== READMODE_ASYNC
)
472 read_mode
= READMODE_NOBLOCK
;
475 TRACE("read %u bytes\n", ret_read
);
480 static BOOL
gzip_drain_content(data_stream_t
*stream
, http_request_t
*req
)
482 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
483 return gzip_stream
->parent_stream
->vtbl
->drain_content(gzip_stream
->parent_stream
, req
);
486 static void gzip_destroy(data_stream_t
*stream
)
488 gzip_stream_t
*gzip_stream
= (gzip_stream_t
*)stream
;
490 destroy_data_stream(gzip_stream
->parent_stream
);
492 if(!gzip_stream
->end_of_data
)
493 inflateEnd(&gzip_stream
->zstream
);
494 heap_free(gzip_stream
);
497 static const data_stream_vtbl_t gzip_stream_vtbl
= {
505 static voidpf
wininet_zalloc(voidpf opaque
, uInt items
, uInt size
)
507 return heap_alloc(items
*size
);
510 static void wininet_zfree(voidpf opaque
, voidpf address
)
515 static DWORD
init_gzip_stream(http_request_t
*req
)
517 gzip_stream_t
*gzip_stream
;
520 gzip_stream
= heap_alloc_zero(sizeof(gzip_stream_t
));
522 return ERROR_OUTOFMEMORY
;
524 gzip_stream
->stream
.vtbl
= &gzip_stream_vtbl
;
525 gzip_stream
->zstream
.zalloc
= wininet_zalloc
;
526 gzip_stream
->zstream
.zfree
= wininet_zfree
;
528 zres
= inflateInit2(&gzip_stream
->zstream
, 0x1f);
530 ERR("inflateInit failed: %d\n", zres
);
531 heap_free(gzip_stream
);
532 return ERROR_OUTOFMEMORY
;
535 index
= HTTP_GetCustomHeaderIndex(req
, szContent_Length
, 0, FALSE
);
537 HTTP_DeleteCustomHeader(req
, index
);
540 memcpy(gzip_stream
->buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
541 gzip_stream
->buf_size
= req
->read_size
;
542 req
->read_pos
= req
->read_size
= 0;
545 req
->read_gzip
= TRUE
;
546 gzip_stream
->parent_stream
= req
->data_stream
;
547 req
->data_stream
= &gzip_stream
->stream
;
548 return ERROR_SUCCESS
;
553 static DWORD
init_gzip_stream(http_request_t
*req
)
555 ERR("gzip stream not supported, missing zlib.\n");
556 return ERROR_SUCCESS
;
561 /***********************************************************************
562 * HTTP_FreeTokens (internal)
564 * Frees table of pointers.
566 static void HTTP_FreeTokens(LPWSTR
* token_array
)
569 for (i
= 0; token_array
[i
]; i
++) heap_free(token_array
[i
]);
570 heap_free(token_array
);
573 static void HTTP_FixURL(http_request_t
*request
)
575 static const WCHAR szSlash
[] = { '/',0 };
576 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/', 0 };
578 /* If we don't have a path we set it to root */
579 if (NULL
== request
->path
)
580 request
->path
= heap_strdupW(szSlash
);
581 else /* remove \r and \n*/
583 int nLen
= strlenW(request
->path
);
584 while ((nLen
>0 ) && ((request
->path
[nLen
-1] == '\r')||(request
->path
[nLen
-1] == '\n')))
587 request
->path
[nLen
]='\0';
589 /* Replace '\' with '/' */
592 if (request
->path
[nLen
] == '\\') request
->path
[nLen
]='/';
596 if(CSTR_EQUAL
!= CompareStringW( LOCALE_INVARIANT
, NORM_IGNORECASE
,
597 request
->path
, strlenW(request
->path
), szHttp
, strlenW(szHttp
) )
598 && request
->path
[0] != '/') /* not an absolute path ?? --> fix it !! */
600 WCHAR
*fixurl
= heap_alloc((strlenW(request
->path
) + 2)*sizeof(WCHAR
));
602 strcpyW(fixurl
+ 1, request
->path
);
603 heap_free( request
->path
);
604 request
->path
= fixurl
;
608 static WCHAR
* build_request_header(http_request_t
*request
, const WCHAR
*verb
,
609 const WCHAR
*path
, const WCHAR
*version
, BOOL use_cr
)
611 LPWSTR requestString
;
616 static const WCHAR szSpace
[] = { ' ',0 };
617 static const WCHAR szColon
[] = { ':',' ',0 };
618 static const WCHAR szCr
[] = { '\r',0 };
619 static const WCHAR szLf
[] = { '\n',0 };
621 /* allocate space for an array of all the string pointers to be added */
622 len
= (request
->nCustHeaders
)*5 + 10;
623 req
= heap_alloc(len
*sizeof(LPCWSTR
));
625 /* add the verb, path and HTTP version string */
636 /* Append custom request headers */
637 for (i
= 0; i
< request
->nCustHeaders
; i
++)
639 if (request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
641 req
[n
++] = request
->custHeaders
[i
].lpszField
;
643 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
648 TRACE("Adding custom header %s (%s)\n",
649 debugstr_w(request
->custHeaders
[i
].lpszField
),
650 debugstr_w(request
->custHeaders
[i
].lpszValue
));
658 requestString
= HTTP_build_req( req
, 4 );
660 return requestString
;
663 static WCHAR
* build_response_header(http_request_t
*request
, BOOL use_cr
)
665 static const WCHAR colonW
[] = { ':',' ',0 };
666 static const WCHAR crW
[] = { '\r',0 };
667 static const WCHAR lfW
[] = { '\n',0 };
668 static const WCHAR status_fmt
[] = { ' ','%','u',' ',0 };
674 req
= heap_alloc((request
->nCustHeaders
*5+8)*sizeof(WCHAR
*));
678 if (request
->status_code
)
680 req
[n
++] = request
->version
;
681 sprintfW(buf
, status_fmt
, request
->status_code
);
683 req
[n
++] = request
->statusText
;
689 for(i
= 0; i
< request
->nCustHeaders
; i
++)
691 if(!(request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
692 && strcmpW(request
->custHeaders
[i
].lpszField
, szStatus
))
694 req
[n
++] = request
->custHeaders
[i
].lpszField
;
696 req
[n
++] = request
->custHeaders
[i
].lpszValue
;
701 TRACE("Adding custom header %s (%s)\n",
702 debugstr_w(request
->custHeaders
[i
].lpszField
),
703 debugstr_w(request
->custHeaders
[i
].lpszValue
));
711 ret
= HTTP_build_req(req
, 0);
716 static void HTTP_ProcessCookies( http_request_t
*request
)
720 LPHTTPHEADERW setCookieHeader
;
722 if(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
)
725 while((HeaderIndex
= HTTP_GetCustomHeaderIndex(request
, szSet_Cookie
, numCookies
++, FALSE
)) != -1)
731 setCookieHeader
= &request
->custHeaders
[HeaderIndex
];
733 if (!setCookieHeader
->lpszValue
)
736 host
= HTTP_GetHeader(request
, hostW
);
740 data
= strchrW(setCookieHeader
->lpszValue
, '=');
744 name
= heap_strndupW(setCookieHeader
->lpszValue
, data
-setCookieHeader
->lpszValue
);
749 set_cookie(host
->lpszValue
, request
->path
, name
, data
);
754 static void strip_spaces(LPWSTR start
)
759 while (*str
== ' ' && *str
!= '\0')
763 memmove(start
, str
, sizeof(WCHAR
) * (strlenW(str
) + 1));
765 end
= start
+ strlenW(start
) - 1;
766 while (end
>= start
&& *end
== ' ')
773 static inline BOOL
is_basic_auth_value( LPCWSTR pszAuthValue
, LPWSTR
*pszRealm
)
775 static const WCHAR szBasic
[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
776 static const WCHAR szRealm
[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
778 is_basic
= !strncmpiW(pszAuthValue
, szBasic
, ARRAYSIZE(szBasic
)) &&
779 ((pszAuthValue
[ARRAYSIZE(szBasic
)] == ' ') || !pszAuthValue
[ARRAYSIZE(szBasic
)]);
780 if (is_basic
&& pszRealm
)
783 LPCWSTR ptr
= &pszAuthValue
[ARRAYSIZE(szBasic
)];
787 token
= strchrW(ptr
,'=');
791 while (*realm
== ' ' && *realm
!= '\0')
793 if(!strncmpiW(realm
, szRealm
, ARRAYSIZE(szRealm
)) &&
794 (realm
[ARRAYSIZE(szRealm
)] == ' ' || realm
[ARRAYSIZE(szRealm
)] == '='))
797 while (*token
== ' ' && *token
!= '\0')
801 *pszRealm
= heap_strdupW(token
);
802 strip_spaces(*pszRealm
);
809 static void destroy_authinfo( struct HttpAuthInfo
*authinfo
)
811 if (!authinfo
) return;
813 if (SecIsValidHandle(&authinfo
->ctx
))
814 DeleteSecurityContext(&authinfo
->ctx
);
815 if (SecIsValidHandle(&authinfo
->cred
))
816 FreeCredentialsHandle(&authinfo
->cred
);
818 heap_free(authinfo
->auth_data
);
819 heap_free(authinfo
->scheme
);
823 static UINT
retrieve_cached_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR
*auth_data
)
825 basicAuthorizationData
*ad
;
828 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host
),debugstr_w(realm
));
830 EnterCriticalSection(&authcache_cs
);
831 LIST_FOR_EACH_ENTRY(ad
, &basicAuthorizationCache
, basicAuthorizationData
, entry
)
833 if (!strcmpiW(host
,ad
->host
) && !strcmpW(realm
,ad
->realm
))
835 TRACE("Authorization found in cache\n");
836 *auth_data
= heap_alloc(ad
->authorizationLen
);
837 memcpy(*auth_data
,ad
->authorization
,ad
->authorizationLen
);
838 rc
= ad
->authorizationLen
;
842 LeaveCriticalSection(&authcache_cs
);
846 static void cache_basic_authorization(LPWSTR host
, LPWSTR realm
, LPSTR auth_data
, UINT auth_data_len
)
849 basicAuthorizationData
* ad
= NULL
;
851 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host
),debugstr_w(realm
),debugstr_an(auth_data
,auth_data_len
));
853 EnterCriticalSection(&authcache_cs
);
854 LIST_FOR_EACH(cursor
, &basicAuthorizationCache
)
856 basicAuthorizationData
*check
= LIST_ENTRY(cursor
,basicAuthorizationData
,entry
);
857 if (!strcmpiW(host
,check
->host
) && !strcmpW(realm
,check
->realm
))
866 TRACE("Found match in cache, replacing\n");
867 heap_free(ad
->authorization
);
868 ad
->authorization
= heap_alloc(auth_data_len
);
869 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
870 ad
->authorizationLen
= auth_data_len
;
874 ad
= heap_alloc(sizeof(basicAuthorizationData
));
875 ad
->host
= heap_strdupW(host
);
876 ad
->realm
= heap_strdupW(realm
);
877 ad
->authorization
= heap_alloc(auth_data_len
);
878 memcpy(ad
->authorization
, auth_data
, auth_data_len
);
879 ad
->authorizationLen
= auth_data_len
;
880 list_add_head(&basicAuthorizationCache
,&ad
->entry
);
881 TRACE("authorization cached\n");
883 LeaveCriticalSection(&authcache_cs
);
886 static BOOL
retrieve_cached_authorization(LPWSTR host
, LPWSTR scheme
,
887 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
889 authorizationData
*ad
;
891 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
893 EnterCriticalSection(&authcache_cs
);
894 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
) {
895 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
896 TRACE("Authorization found in cache\n");
898 nt_auth_identity
->User
= heap_strdupW(ad
->user
);
899 nt_auth_identity
->Password
= heap_strdupW(ad
->password
);
900 nt_auth_identity
->Domain
= heap_alloc(sizeof(WCHAR
)*ad
->domain_len
);
901 if(!nt_auth_identity
->User
|| !nt_auth_identity
->Password
||
902 (!nt_auth_identity
->Domain
&& ad
->domain_len
)) {
903 heap_free(nt_auth_identity
->User
);
904 heap_free(nt_auth_identity
->Password
);
905 heap_free(nt_auth_identity
->Domain
);
909 nt_auth_identity
->Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
910 nt_auth_identity
->UserLength
= ad
->user_len
;
911 nt_auth_identity
->PasswordLength
= ad
->password_len
;
912 memcpy(nt_auth_identity
->Domain
, ad
->domain
, sizeof(WCHAR
)*ad
->domain_len
);
913 nt_auth_identity
->DomainLength
= ad
->domain_len
;
914 LeaveCriticalSection(&authcache_cs
);
918 LeaveCriticalSection(&authcache_cs
);
923 static void cache_authorization(LPWSTR host
, LPWSTR scheme
,
924 SEC_WINNT_AUTH_IDENTITY_W
*nt_auth_identity
)
926 authorizationData
*ad
;
929 TRACE("Caching authorization for %s:%s\n", debugstr_w(host
), debugstr_w(scheme
));
931 EnterCriticalSection(&authcache_cs
);
932 LIST_FOR_EACH_ENTRY(ad
, &authorizationCache
, authorizationData
, entry
)
933 if(!strcmpiW(host
, ad
->host
) && !strcmpiW(scheme
, ad
->scheme
)) {
940 heap_free(ad
->password
);
941 heap_free(ad
->domain
);
943 ad
= heap_alloc(sizeof(authorizationData
));
945 LeaveCriticalSection(&authcache_cs
);
949 ad
->host
= heap_strdupW(host
);
950 ad
->scheme
= heap_strdupW(scheme
);
951 list_add_head(&authorizationCache
, &ad
->entry
);
954 ad
->user
= heap_strndupW(nt_auth_identity
->User
, nt_auth_identity
->UserLength
);
955 ad
->password
= heap_strndupW(nt_auth_identity
->Password
, nt_auth_identity
->PasswordLength
);
956 ad
->domain
= heap_strndupW(nt_auth_identity
->Domain
, nt_auth_identity
->DomainLength
);
957 ad
->user_len
= nt_auth_identity
->UserLength
;
958 ad
->password_len
= nt_auth_identity
->PasswordLength
;
959 ad
->domain_len
= nt_auth_identity
->DomainLength
;
961 if(!ad
->host
|| !ad
->scheme
|| !ad
->user
|| !ad
->password
962 || (nt_auth_identity
->Domain
&& !ad
->domain
)) {
964 heap_free(ad
->scheme
);
966 heap_free(ad
->password
);
967 heap_free(ad
->domain
);
968 list_remove(&ad
->entry
);
972 LeaveCriticalSection(&authcache_cs
);
975 static BOOL
HTTP_DoAuthorization( http_request_t
*request
, LPCWSTR pszAuthValue
,
976 struct HttpAuthInfo
**ppAuthInfo
,
977 LPWSTR domain_and_username
, LPWSTR password
,
980 SECURITY_STATUS sec_status
;
981 struct HttpAuthInfo
*pAuthInfo
= *ppAuthInfo
;
983 LPWSTR szRealm
= NULL
;
985 TRACE("%s\n", debugstr_w(pszAuthValue
));
992 pAuthInfo
= heap_alloc(sizeof(*pAuthInfo
));
996 SecInvalidateHandle(&pAuthInfo
->cred
);
997 SecInvalidateHandle(&pAuthInfo
->ctx
);
998 memset(&pAuthInfo
->exp
, 0, sizeof(pAuthInfo
->exp
));
1000 pAuthInfo
->auth_data
= NULL
;
1001 pAuthInfo
->auth_data_len
= 0;
1002 pAuthInfo
->finished
= FALSE
;
1004 if (is_basic_auth_value(pszAuthValue
,NULL
))
1006 static const WCHAR szBasic
[] = {'B','a','s','i','c',0};
1007 pAuthInfo
->scheme
= heap_strdupW(szBasic
);
1008 if (!pAuthInfo
->scheme
)
1010 heap_free(pAuthInfo
);
1017 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity
;
1019 pAuthInfo
->scheme
= heap_strdupW(pszAuthValue
);
1020 if (!pAuthInfo
->scheme
)
1022 heap_free(pAuthInfo
);
1026 if (domain_and_username
)
1028 WCHAR
*user
= strchrW(domain_and_username
, '\\');
1029 WCHAR
*domain
= domain_and_username
;
1031 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1033 pAuthData
= &nt_auth_identity
;
1038 user
= domain_and_username
;
1042 nt_auth_identity
.Flags
= SEC_WINNT_AUTH_IDENTITY_UNICODE
;
1043 nt_auth_identity
.User
= user
;
1044 nt_auth_identity
.UserLength
= strlenW(nt_auth_identity
.User
);
1045 nt_auth_identity
.Domain
= domain
;
1046 nt_auth_identity
.DomainLength
= domain
? user
- domain
- 1 : 0;
1047 nt_auth_identity
.Password
= password
;
1048 nt_auth_identity
.PasswordLength
= strlenW(nt_auth_identity
.Password
);
1050 cache_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
);
1052 else if(retrieve_cached_authorization(host
, pAuthInfo
->scheme
, &nt_auth_identity
))
1053 pAuthData
= &nt_auth_identity
;
1055 /* use default credentials */
1058 sec_status
= AcquireCredentialsHandleW(NULL
, pAuthInfo
->scheme
,
1059 SECPKG_CRED_OUTBOUND
, NULL
,
1061 NULL
, &pAuthInfo
->cred
,
1064 if(pAuthData
&& !domain_and_username
) {
1065 heap_free(nt_auth_identity
.User
);
1066 heap_free(nt_auth_identity
.Domain
);
1067 heap_free(nt_auth_identity
.Password
);
1070 if (sec_status
== SEC_E_OK
)
1072 PSecPkgInfoW sec_pkg_info
;
1073 sec_status
= QuerySecurityPackageInfoW(pAuthInfo
->scheme
, &sec_pkg_info
);
1074 if (sec_status
== SEC_E_OK
)
1076 pAuthInfo
->max_token
= sec_pkg_info
->cbMaxToken
;
1077 FreeContextBuffer(sec_pkg_info
);
1080 if (sec_status
!= SEC_E_OK
)
1082 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1083 debugstr_w(pAuthInfo
->scheme
), sec_status
);
1084 heap_free(pAuthInfo
->scheme
);
1085 heap_free(pAuthInfo
);
1089 *ppAuthInfo
= pAuthInfo
;
1091 else if (pAuthInfo
->finished
)
1094 if ((strlenW(pszAuthValue
) < strlenW(pAuthInfo
->scheme
)) ||
1095 strncmpiW(pszAuthValue
, pAuthInfo
->scheme
, strlenW(pAuthInfo
->scheme
)))
1097 ERR("authentication scheme changed from %s to %s\n",
1098 debugstr_w(pAuthInfo
->scheme
), debugstr_w(pszAuthValue
));
1102 if (is_basic_auth_value(pszAuthValue
,&szRealm
))
1106 char *auth_data
= NULL
;
1107 UINT auth_data_len
= 0;
1109 TRACE("basic authentication realm %s\n",debugstr_w(szRealm
));
1111 if (!domain_and_username
)
1113 if (host
&& szRealm
)
1114 auth_data_len
= retrieve_cached_basic_authorization(host
, szRealm
,&auth_data
);
1115 if (auth_data_len
== 0)
1123 userlen
= WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, lstrlenW(domain_and_username
), NULL
, 0, NULL
, NULL
);
1124 passlen
= WideCharToMultiByte(CP_UTF8
, 0, password
, lstrlenW(password
), NULL
, 0, NULL
, NULL
);
1126 /* length includes a nul terminator, which will be re-used for the ':' */
1127 auth_data
= heap_alloc(userlen
+ 1 + passlen
);
1134 WideCharToMultiByte(CP_UTF8
, 0, domain_and_username
, -1, auth_data
, userlen
, NULL
, NULL
);
1135 auth_data
[userlen
] = ':';
1136 WideCharToMultiByte(CP_UTF8
, 0, password
, -1, &auth_data
[userlen
+1], passlen
, NULL
, NULL
);
1137 auth_data_len
= userlen
+ 1 + passlen
;
1138 if (host
&& szRealm
)
1139 cache_basic_authorization(host
, szRealm
, auth_data
, auth_data_len
);
1142 pAuthInfo
->auth_data
= auth_data
;
1143 pAuthInfo
->auth_data_len
= auth_data_len
;
1144 pAuthInfo
->finished
= TRUE
;
1150 LPCWSTR pszAuthData
;
1151 SecBufferDesc out_desc
, in_desc
;
1153 unsigned char *buffer
;
1154 ULONG context_req
= ISC_REQ_CONNECTION
| ISC_REQ_USE_DCE_STYLE
|
1155 ISC_REQ_MUTUAL_AUTH
| ISC_REQ_DELEGATE
;
1157 in
.BufferType
= SECBUFFER_TOKEN
;
1161 in_desc
.ulVersion
= 0;
1162 in_desc
.cBuffers
= 1;
1163 in_desc
.pBuffers
= &in
;
1165 pszAuthData
= pszAuthValue
+ strlenW(pAuthInfo
->scheme
);
1166 if (*pszAuthData
== ' ')
1169 in
.cbBuffer
= HTTP_DecodeBase64(pszAuthData
, NULL
);
1170 in
.pvBuffer
= heap_alloc(in
.cbBuffer
);
1171 HTTP_DecodeBase64(pszAuthData
, in
.pvBuffer
);
1174 buffer
= heap_alloc(pAuthInfo
->max_token
);
1176 out
.BufferType
= SECBUFFER_TOKEN
;
1177 out
.cbBuffer
= pAuthInfo
->max_token
;
1178 out
.pvBuffer
= buffer
;
1180 out_desc
.ulVersion
= 0;
1181 out_desc
.cBuffers
= 1;
1182 out_desc
.pBuffers
= &out
;
1184 sec_status
= InitializeSecurityContextW(first
? &pAuthInfo
->cred
: NULL
,
1185 first
? NULL
: &pAuthInfo
->ctx
,
1186 first
? request
->server
->name
: NULL
,
1187 context_req
, 0, SECURITY_NETWORK_DREP
,
1188 in
.pvBuffer
? &in_desc
: NULL
,
1189 0, &pAuthInfo
->ctx
, &out_desc
,
1190 &pAuthInfo
->attr
, &pAuthInfo
->exp
);
1191 if (sec_status
== SEC_E_OK
)
1193 pAuthInfo
->finished
= TRUE
;
1194 pAuthInfo
->auth_data
= out
.pvBuffer
;
1195 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1196 TRACE("sending last auth packet\n");
1198 else if (sec_status
== SEC_I_CONTINUE_NEEDED
)
1200 pAuthInfo
->auth_data
= out
.pvBuffer
;
1201 pAuthInfo
->auth_data_len
= out
.cbBuffer
;
1202 TRACE("sending next auth packet\n");
1206 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status
);
1207 heap_free(out
.pvBuffer
);
1208 destroy_authinfo(pAuthInfo
);
1217 /***********************************************************************
1218 * HTTP_HttpAddRequestHeadersW (internal)
1220 static DWORD
HTTP_HttpAddRequestHeadersW(http_request_t
*request
,
1221 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1226 DWORD len
, res
= ERROR_HTTP_INVALID_HEADER
;
1228 TRACE("copying header: %s\n", debugstr_wn(lpszHeader
, dwHeaderLength
));
1230 if( dwHeaderLength
== ~0U )
1231 len
= strlenW(lpszHeader
);
1233 len
= dwHeaderLength
;
1234 buffer
= heap_alloc(sizeof(WCHAR
)*(len
+1));
1235 lstrcpynW( buffer
, lpszHeader
, len
+ 1);
1241 LPWSTR
* pFieldAndValue
;
1243 lpszEnd
= lpszStart
;
1245 while (*lpszEnd
!= '\0')
1247 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1252 if (*lpszStart
== '\0')
1255 if (*lpszEnd
== '\r' || *lpszEnd
== '\n')
1258 lpszEnd
++; /* Jump over newline */
1260 TRACE("interpreting header %s\n", debugstr_w(lpszStart
));
1261 if (*lpszStart
== '\0')
1263 /* Skip 0-length headers */
1264 lpszStart
= lpszEnd
;
1265 res
= ERROR_SUCCESS
;
1268 pFieldAndValue
= HTTP_InterpretHttpHeader(lpszStart
);
1271 res
= HTTP_VerifyValidHeader(request
, pFieldAndValue
[0]);
1272 if (res
== ERROR_SUCCESS
)
1273 res
= HTTP_ProcessHeader(request
, pFieldAndValue
[0],
1274 pFieldAndValue
[1], dwModifier
| HTTP_ADDHDR_FLAG_REQ
);
1275 HTTP_FreeTokens(pFieldAndValue
);
1278 lpszStart
= lpszEnd
;
1279 } while (res
== ERROR_SUCCESS
);
1285 /***********************************************************************
1286 * HttpAddRequestHeadersW (WININET.@)
1288 * Adds one or more HTTP header to the request handler
1291 * On Windows if dwHeaderLength includes the trailing '\0', then
1292 * HttpAddRequestHeadersW() adds it too. However this results in an
1293 * invalid HTTP header which is rejected by some servers so we probably
1294 * don't need to match Windows on that point.
1301 BOOL WINAPI
HttpAddRequestHeadersW(HINTERNET hHttpRequest
,
1302 LPCWSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1304 http_request_t
*request
;
1305 DWORD res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
1307 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_wn(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1312 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
1313 if (request
&& request
->hdr
.htype
== WH_HHTTPREQ
)
1314 res
= HTTP_HttpAddRequestHeadersW( request
, lpszHeader
, dwHeaderLength
, dwModifier
);
1316 WININET_Release( &request
->hdr
);
1318 if(res
!= ERROR_SUCCESS
)
1320 return res
== ERROR_SUCCESS
;
1323 /***********************************************************************
1324 * HttpAddRequestHeadersA (WININET.@)
1326 * Adds one or more HTTP header to the request handler
1333 BOOL WINAPI
HttpAddRequestHeadersA(HINTERNET hHttpRequest
,
1334 LPCSTR lpszHeader
, DWORD dwHeaderLength
, DWORD dwModifier
)
1340 TRACE("%p, %s, %i, %i\n", hHttpRequest
, debugstr_an(lpszHeader
, dwHeaderLength
), dwHeaderLength
, dwModifier
);
1342 len
= MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, NULL
, 0 );
1343 hdr
= heap_alloc(len
*sizeof(WCHAR
));
1344 MultiByteToWideChar( CP_ACP
, 0, lpszHeader
, dwHeaderLength
, hdr
, len
);
1345 if( dwHeaderLength
!= ~0U )
1346 dwHeaderLength
= len
;
1348 r
= HttpAddRequestHeadersW( hHttpRequest
, hdr
, dwHeaderLength
, dwModifier
);
1354 static void free_accept_types( WCHAR
**accept_types
)
1356 WCHAR
*ptr
, **types
= accept_types
;
1359 while ((ptr
= *types
))
1364 heap_free( accept_types
);
1367 static WCHAR
**convert_accept_types( const char **accept_types
)
1370 const char **types
= accept_types
;
1372 BOOL invalid_pointer
= FALSE
;
1374 if (!types
) return NULL
;
1380 /* find out how many there are */
1381 if (*types
&& **types
)
1383 TRACE("accept type: %s\n", debugstr_a(*types
));
1389 WARN("invalid accept type pointer\n");
1390 invalid_pointer
= TRUE
;
1395 if (invalid_pointer
) return NULL
;
1396 if (!(typesW
= heap_alloc( sizeof(WCHAR
*) * (count
+ 1) ))) return NULL
;
1398 types
= accept_types
;
1401 if (*types
&& **types
) typesW
[count
++] = heap_strdupAtoW( *types
);
1404 typesW
[count
] = NULL
;
1408 /***********************************************************************
1409 * HttpOpenRequestA (WININET.@)
1411 * Open a HTTP request handle
1414 * HINTERNET a HTTP request handle on success
1418 HINTERNET WINAPI
HttpOpenRequestA(HINTERNET hHttpSession
,
1419 LPCSTR lpszVerb
, LPCSTR lpszObjectName
, LPCSTR lpszVersion
,
1420 LPCSTR lpszReferrer
, LPCSTR
*lpszAcceptTypes
,
1421 DWORD dwFlags
, DWORD_PTR dwContext
)
1423 LPWSTR szVerb
= NULL
, szObjectName
= NULL
;
1424 LPWSTR szVersion
= NULL
, szReferrer
= NULL
, *szAcceptTypes
= NULL
;
1425 HINTERNET rc
= FALSE
;
1427 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
1428 debugstr_a(lpszVerb
), debugstr_a(lpszObjectName
),
1429 debugstr_a(lpszVersion
), debugstr_a(lpszReferrer
), lpszAcceptTypes
,
1430 dwFlags
, dwContext
);
1434 szVerb
= heap_strdupAtoW(lpszVerb
);
1441 szObjectName
= heap_strdupAtoW(lpszObjectName
);
1442 if ( !szObjectName
)
1448 szVersion
= heap_strdupAtoW(lpszVersion
);
1455 szReferrer
= heap_strdupAtoW(lpszReferrer
);
1460 szAcceptTypes
= convert_accept_types( lpszAcceptTypes
);
1461 rc
= HttpOpenRequestW(hHttpSession
, szVerb
, szObjectName
, szVersion
, szReferrer
,
1462 (const WCHAR
**)szAcceptTypes
, dwFlags
, dwContext
);
1465 free_accept_types(szAcceptTypes
);
1466 heap_free(szReferrer
);
1467 heap_free(szVersion
);
1468 heap_free(szObjectName
);
1473 /***********************************************************************
1476 static UINT
HTTP_EncodeBase64( LPCSTR bin
, unsigned int len
, LPWSTR base64
)
1479 static const CHAR HTTP_Base64Enc
[] =
1480 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1484 /* first 6 bits, all from bin[0] */
1485 base64
[n
++] = HTTP_Base64Enc
[(bin
[0] & 0xfc) >> 2];
1486 x
= (bin
[0] & 3) << 4;
1488 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1491 base64
[n
++] = HTTP_Base64Enc
[x
];
1496 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[1]&0xf0) >> 4 ) ];
1497 x
= ( bin
[1] & 0x0f ) << 2;
1499 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1502 base64
[n
++] = HTTP_Base64Enc
[x
];
1506 base64
[n
++] = HTTP_Base64Enc
[ x
| ( (bin
[2]&0xc0 ) >> 6 ) ];
1508 /* last 6 bits, all from bin [2] */
1509 base64
[n
++] = HTTP_Base64Enc
[ bin
[2] & 0x3f ];
1517 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1518 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1519 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1520 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1521 static const signed char HTTP_Base64Dec
[256] =
1523 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1524 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1525 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1526 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1527 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1528 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1529 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1530 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1531 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1532 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1533 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1534 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1535 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1536 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1537 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1538 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1539 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1540 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1541 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1542 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1543 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1544 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1545 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1546 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1547 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1548 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1552 /***********************************************************************
1555 static UINT
HTTP_DecodeBase64( LPCWSTR base64
, LPSTR bin
)
1563 if (base64
[0] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1564 ((in
[0] = HTTP_Base64Dec
[base64
[0]]) == -1) ||
1565 base64
[1] >= ARRAYSIZE(HTTP_Base64Dec
) ||
1566 ((in
[1] = HTTP_Base64Dec
[base64
[1]]) == -1))
1568 WARN("invalid base64: %s\n", debugstr_w(base64
));
1572 bin
[n
] = (unsigned char) (in
[0] << 2 | in
[1] >> 4);
1575 if ((base64
[2] == '=') && (base64
[3] == '='))
1577 if (base64
[2] > ARRAYSIZE(HTTP_Base64Dec
) ||
1578 ((in
[2] = HTTP_Base64Dec
[base64
[2]]) == -1))
1580 WARN("invalid base64: %s\n", debugstr_w(&base64
[2]));
1584 bin
[n
] = (unsigned char) (in
[1] << 4 | in
[2] >> 2);
1587 if (base64
[3] == '=')
1589 if (base64
[3] > ARRAYSIZE(HTTP_Base64Dec
) ||
1590 ((in
[3] = HTTP_Base64Dec
[base64
[3]]) == -1))
1592 WARN("invalid base64: %s\n", debugstr_w(&base64
[3]));
1596 bin
[n
] = (unsigned char) (((in
[2] << 6) & 0xc0) | in
[3]);
1605 /***********************************************************************
1606 * HTTP_InsertAuthorization
1608 * Insert or delete the authorization field in the request header.
1610 static BOOL
HTTP_InsertAuthorization( http_request_t
*request
, struct HttpAuthInfo
*pAuthInfo
, LPCWSTR header
)
1614 static const WCHAR wszSpace
[] = {' ',0};
1615 static const WCHAR wszBasic
[] = {'B','a','s','i','c',0};
1617 WCHAR
*authorization
= NULL
;
1619 if (pAuthInfo
->auth_data_len
)
1621 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1622 len
= strlenW(pAuthInfo
->scheme
)+1+((pAuthInfo
->auth_data_len
+2)*4)/3;
1623 authorization
= heap_alloc((len
+1)*sizeof(WCHAR
));
1627 strcpyW(authorization
, pAuthInfo
->scheme
);
1628 strcatW(authorization
, wszSpace
);
1629 HTTP_EncodeBase64(pAuthInfo
->auth_data
,
1630 pAuthInfo
->auth_data_len
,
1631 authorization
+strlenW(authorization
));
1633 /* clear the data as it isn't valid now that it has been sent to the
1634 * server, unless it's Basic authentication which doesn't do
1635 * connection tracking */
1636 if (strcmpiW(pAuthInfo
->scheme
, wszBasic
))
1638 heap_free(pAuthInfo
->auth_data
);
1639 pAuthInfo
->auth_data
= NULL
;
1640 pAuthInfo
->auth_data_len
= 0;
1644 TRACE("Inserting authorization: %s\n", debugstr_w(authorization
));
1646 HTTP_ProcessHeader(request
, header
, authorization
, HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
);
1647 heap_free(authorization
);
1652 static WCHAR
*build_proxy_path_url(http_request_t
*req
)
1657 len
= strlenW(req
->server
->scheme_host_port
);
1658 size
= len
+ strlenW(req
->path
) + 1;
1659 if(*req
->path
!= '/')
1661 url
= heap_alloc(size
* sizeof(WCHAR
));
1665 memcpy(url
, req
->server
->scheme_host_port
, len
*sizeof(WCHAR
));
1666 if(*req
->path
!= '/')
1669 strcpyW(url
+len
, req
->path
);
1671 TRACE("url=%s\n", debugstr_w(url
));
1675 static BOOL
HTTP_DomainMatches(LPCWSTR server
, LPCWSTR domain
)
1677 static const WCHAR localW
[] = { '<','l','o','c','a','l','>',0 };
1680 if (!strcmpiW( domain
, localW
) && !strchrW( server
, '.' ))
1682 else if (*domain
== '*')
1684 if (domain
[1] == '.')
1688 /* For a hostname to match a wildcard, the last domain must match
1689 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1690 * hostname is www.foo.a.b, it matches, but a.b does not.
1692 dot
= strchrW( server
, '.' );
1695 int len
= strlenW( dot
+ 1 );
1697 if (len
> strlenW( domain
+ 2 ))
1701 /* The server's domain is longer than the wildcard, so it
1702 * could be a subdomain. Compare the last portion of the
1705 ptr
= dot
+ len
+ 1 - strlenW( domain
+ 2 );
1706 if (!strcmpiW( ptr
, domain
+ 2 ))
1708 /* This is only a match if the preceding character is
1709 * a '.', i.e. that it is a matching domain. E.g.
1710 * if domain is '*.b.c' and server is 'www.ab.c' they
1713 ret
= *(ptr
- 1) == '.';
1717 ret
= !strcmpiW( dot
+ 1, domain
+ 2 );
1722 ret
= !strcmpiW( server
, domain
);
1726 static BOOL
HTTP_ShouldBypassProxy(appinfo_t
*lpwai
, LPCWSTR server
)
1731 if (!lpwai
->proxyBypass
) return FALSE
;
1732 ptr
= lpwai
->proxyBypass
;
1736 ptr
= strchrW( ptr
, ';' );
1738 ptr
= strchrW( tmp
, ' ' );
1741 if (ptr
- tmp
< INTERNET_MAX_HOST_NAME_LENGTH
)
1743 WCHAR domain
[INTERNET_MAX_HOST_NAME_LENGTH
];
1745 memcpy( domain
, tmp
, (ptr
- tmp
) * sizeof(WCHAR
) );
1746 domain
[ptr
- tmp
] = 0;
1747 ret
= HTTP_DomainMatches( server
, domain
);
1752 ret
= HTTP_DomainMatches( server
, tmp
);
1753 } while (ptr
&& !ret
);
1757 /***********************************************************************
1758 * HTTP_DealWithProxy
1760 static BOOL
HTTP_DealWithProxy(appinfo_t
*hIC
, http_session_t
*session
, http_request_t
*request
)
1762 static const WCHAR protoHttp
[] = { 'h','t','t','p',0 };
1763 static const WCHAR szHttp
[] = { 'h','t','t','p',':','/','/',0 };
1764 static const WCHAR szFormat
[] = { 'h','t','t','p',':','/','/','%','s',0 };
1765 WCHAR buf
[INTERNET_MAX_HOST_NAME_LENGTH
];
1766 WCHAR protoProxy
[INTERNET_MAX_URL_LENGTH
];
1767 DWORD protoProxyLen
= INTERNET_MAX_URL_LENGTH
;
1768 WCHAR proxy
[INTERNET_MAX_URL_LENGTH
];
1769 static WCHAR szNul
[] = { 0 };
1770 URL_COMPONENTSW UrlComponents
;
1771 server_t
*new_server
;
1774 memset( &UrlComponents
, 0, sizeof UrlComponents
);
1775 UrlComponents
.dwStructSize
= sizeof UrlComponents
;
1776 UrlComponents
.lpszHostName
= buf
;
1777 UrlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
1779 if (!INTERNET_FindProxyForProtocol(hIC
->proxy
, protoHttp
, protoProxy
, &protoProxyLen
))
1781 if( CSTR_EQUAL
!= CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1782 protoProxy
,strlenW(szHttp
),szHttp
,strlenW(szHttp
)) )
1783 sprintfW(proxy
, szFormat
, protoProxy
);
1785 strcpyW(proxy
, protoProxy
);
1786 if( !InternetCrackUrlW(proxy
, 0, 0, &UrlComponents
) )
1788 if( UrlComponents
.dwHostNameLength
== 0 )
1791 if( !request
->path
)
1792 request
->path
= szNul
;
1794 is_https
= (UrlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
);
1795 if (is_https
&& UrlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
1796 UrlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
1798 new_server
= get_server(UrlComponents
.lpszHostName
, UrlComponents
.nPort
, is_https
, TRUE
);
1802 request
->proxy
= new_server
;
1804 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server
->name
), new_server
->port
);
1808 static DWORD
HTTP_ResolveName(http_request_t
*request
)
1810 server_t
*server
= request
->proxy
? request
->proxy
: request
->server
;
1814 if(server
->addr_len
)
1815 return ERROR_SUCCESS
;
1817 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1818 INTERNET_STATUS_RESOLVING_NAME
,
1820 (strlenW(server
->name
)+1) * sizeof(WCHAR
));
1822 addr_len
= sizeof(server
->addr
);
1823 if (!GetAddress(server
->name
, server
->port
, (struct sockaddr
*)&server
->addr
, &addr_len
))
1824 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1826 switch(server
->addr
.ss_family
) {
1828 addr
= &((struct sockaddr_in
*)&server
->addr
)->sin_addr
;
1831 addr
= &((struct sockaddr_in6
*)&server
->addr
)->sin6_addr
;
1834 WARN("unsupported family %d\n", server
->addr
.ss_family
);
1835 return ERROR_INTERNET_NAME_NOT_RESOLVED
;
1838 server
->addr_len
= addr_len
;
1839 inet_ntop(server
->addr
.ss_family
, addr
, server
->addr_str
, sizeof(server
->addr_str
));
1840 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
1841 INTERNET_STATUS_NAME_RESOLVED
,
1842 server
->addr_str
, strlen(server
->addr_str
)+1);
1844 TRACE("resolved %s to %s\n", debugstr_w(server
->name
), server
->addr_str
);
1845 return ERROR_SUCCESS
;
1848 static BOOL
HTTP_GetRequestURL(http_request_t
*req
, LPWSTR buf
)
1850 static const WCHAR http
[] = { 'h','t','t','p',':','/','/',0 };
1851 static const WCHAR https
[] = { 'h','t','t','p','s',':','/','/',0 };
1852 static const WCHAR slash
[] = { '/',0 };
1853 LPHTTPHEADERW host_header
;
1856 host_header
= HTTP_GetHeader(req
, hostW
);
1860 if (req
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)
1864 strcpyW(buf
, scheme
);
1865 strcatW(buf
, host_header
->lpszValue
);
1866 if (req
->path
[0] != '/')
1867 strcatW(buf
, slash
);
1868 strcatW(buf
, req
->path
);
1873 /***********************************************************************
1874 * HTTPREQ_Destroy (internal)
1876 * Deallocate request handle
1879 static void HTTPREQ_Destroy(object_header_t
*hdr
)
1881 http_request_t
*request
= (http_request_t
*) hdr
;
1886 if(request
->hCacheFile
) {
1887 CloseHandle(request
->hCacheFile
);
1888 DeleteFileW(request
->cacheFile
);
1890 heap_free(request
->cacheFile
);
1892 request
->read_section
.DebugInfo
->Spare
[0] = 0;
1893 DeleteCriticalSection( &request
->read_section
);
1894 WININET_Release(&request
->session
->hdr
);
1896 destroy_authinfo(request
->authInfo
);
1897 destroy_authinfo(request
->proxyAuthInfo
);
1900 server_release(request
->server
);
1902 server_release(request
->proxy
);
1904 heap_free(request
->path
);
1905 heap_free(request
->verb
);
1906 heap_free(request
->version
);
1907 heap_free(request
->statusText
);
1909 for (i
= 0; i
< request
->nCustHeaders
; i
++)
1911 heap_free(request
->custHeaders
[i
].lpszField
);
1912 heap_free(request
->custHeaders
[i
].lpszValue
);
1914 destroy_data_stream(request
->data_stream
);
1915 heap_free(request
->custHeaders
);
1918 static void http_release_netconn(http_request_t
*req
, BOOL reuse
)
1920 TRACE("%p %p\n",req
, req
->netconn
);
1926 if(reuse
&& req
->netconn
->keep_alive
) {
1929 EnterCriticalSection(&connection_pool_cs
);
1931 list_add_head(&req
->netconn
->server
->conn_pool
, &req
->netconn
->pool_entry
);
1932 req
->netconn
->keep_until
= (DWORD64
)GetTickCount() + COLLECT_TIME
;
1933 req
->netconn
= NULL
;
1935 run_collector
= !collector_running
;
1936 collector_running
= TRUE
;
1938 LeaveCriticalSection(&connection_pool_cs
);
1941 HANDLE thread
= NULL
;
1944 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
, (const WCHAR
*)WININET_hModule
, &module
);
1946 thread
= CreateThread(NULL
, 0, collect_connections_proc
, NULL
, 0, NULL
);
1948 EnterCriticalSection(&connection_pool_cs
);
1949 collector_running
= FALSE
;
1950 LeaveCriticalSection(&connection_pool_cs
);
1953 FreeLibrary(module
);
1956 CloseHandle(thread
);
1961 // silence unused function warning
1962 (void)collect_connections_proc
;
1965 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1966 INTERNET_STATUS_CLOSING_CONNECTION
, 0, 0);
1968 free_netconn(req
->netconn
);
1969 req
->netconn
= NULL
;
1971 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
1972 INTERNET_STATUS_CONNECTION_CLOSED
, 0, 0);
1975 static BOOL
HTTP_KeepAlive(http_request_t
*request
)
1977 WCHAR szVersion
[10];
1978 WCHAR szConnectionResponse
[20];
1979 DWORD dwBufferSize
= sizeof(szVersion
);
1980 BOOL keepalive
= FALSE
;
1982 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1983 * the connection is keep-alive by default */
1984 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_VERSION
, szVersion
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
1985 && !strcmpiW(szVersion
, g_szHttp1_1
))
1990 dwBufferSize
= sizeof(szConnectionResponse
);
1991 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_PROXY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
1992 || HTTP_HttpQueryInfoW(request
, HTTP_QUERY_CONNECTION
, szConnectionResponse
, &dwBufferSize
, NULL
) == ERROR_SUCCESS
)
1994 keepalive
= !strcmpiW(szConnectionResponse
, szKeepAlive
);
2000 static void HTTPREQ_CloseConnection(object_header_t
*hdr
)
2002 http_request_t
*req
= (http_request_t
*)hdr
;
2004 http_release_netconn(req
, drain_content(req
, FALSE
));
2007 static DWORD
str_to_buffer(const WCHAR
*str
, void *buffer
, DWORD
*size
, BOOL unicode
)
2012 WCHAR
*buf
= buffer
;
2014 if (str
) len
= strlenW(str
);
2016 if (*size
< (len
+ 1) * sizeof(WCHAR
))
2018 *size
= (len
+ 1) * sizeof(WCHAR
);
2019 return ERROR_INSUFFICIENT_BUFFER
;
2021 if (str
) strcpyW(buf
, str
);
2025 return ERROR_SUCCESS
;
2031 if (str
) len
= WideCharToMultiByte(CP_ACP
, 0, str
, -1, NULL
, 0, NULL
, NULL
);
2036 return ERROR_INSUFFICIENT_BUFFER
;
2038 if (str
) WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, *size
, NULL
, NULL
);
2042 return ERROR_SUCCESS
;
2046 static DWORD
HTTPREQ_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
2048 http_request_t
*req
= (http_request_t
*)hdr
;
2051 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO
:
2053 INTERNET_DIAGNOSTIC_SOCKET_INFO
*info
= buffer
;
2055 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2057 if (*size
< sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
))
2058 return ERROR_INSUFFICIENT_BUFFER
;
2059 *size
= sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO
);
2060 /* FIXME: can't get a SOCKET from our connection since we don't use
2064 /* FIXME: get source port from req->netConnection */
2065 info
->SourcePort
= 0;
2066 info
->DestPort
= req
->server
->port
;
2068 if (HTTP_KeepAlive(req
))
2069 info
->Flags
|= IDSI_FLAG_KEEP_ALIVE
;
2071 info
->Flags
|= IDSI_FLAG_PROXY
;
2072 if (req
->netconn
&& req
->netconn
->secure
)
2073 info
->Flags
|= IDSI_FLAG_SECURE
;
2075 return ERROR_SUCCESS
;
2079 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2081 case INTERNET_OPTION_SECURITY_FLAGS
:
2085 if (*size
< sizeof(ULONG
))
2086 return ERROR_INSUFFICIENT_BUFFER
;
2088 *size
= sizeof(DWORD
);
2089 flags
= req
->netconn
? req
->netconn
->security_flags
: req
->security_flags
| req
->server
->security_flags
;
2090 *(DWORD
*)buffer
= flags
;
2092 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags
);
2093 return ERROR_SUCCESS
;
2096 case INTERNET_OPTION_HANDLE_TYPE
:
2097 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2099 if (*size
< sizeof(ULONG
))
2100 return ERROR_INSUFFICIENT_BUFFER
;
2102 *size
= sizeof(DWORD
);
2103 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_HTTP_REQUEST
;
2104 return ERROR_SUCCESS
;
2106 case INTERNET_OPTION_URL
: {
2107 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2110 static const WCHAR httpW
[] = {'h','t','t','p',':','/','/',0};
2112 TRACE("INTERNET_OPTION_URL\n");
2114 host
= HTTP_GetHeader(req
, hostW
);
2115 strcpyW(url
, httpW
);
2116 strcatW(url
, host
->lpszValue
);
2117 strcatW(url
, req
->path
);
2119 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url
));
2120 return str_to_buffer(url
, buffer
, size
, unicode
);
2122 case INTERNET_OPTION_USER_AGENT
:
2123 return str_to_buffer(req
->session
->appInfo
->agent
, buffer
, size
, unicode
);
2124 case INTERNET_OPTION_USERNAME
:
2125 return str_to_buffer(req
->session
->userName
, buffer
, size
, unicode
);
2126 case INTERNET_OPTION_PASSWORD
:
2127 return str_to_buffer(req
->session
->password
, buffer
, size
, unicode
);
2128 case INTERNET_OPTION_PROXY_USERNAME
:
2129 return str_to_buffer(req
->session
->appInfo
->proxyUsername
, buffer
, size
, unicode
);
2130 case INTERNET_OPTION_PROXY_PASSWORD
:
2131 return str_to_buffer(req
->session
->appInfo
->proxyPassword
, buffer
, size
, unicode
);
2133 case INTERNET_OPTION_CACHE_TIMESTAMPS
: {
2134 INTERNET_CACHE_ENTRY_INFOW
*info
;
2135 INTERNET_CACHE_TIMESTAMPS
*ts
= buffer
;
2136 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2137 DWORD nbytes
, error
;
2140 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2142 if (*size
< sizeof(*ts
))
2144 *size
= sizeof(*ts
);
2145 return ERROR_INSUFFICIENT_BUFFER
;
2148 HTTP_GetRequestURL(req
, url
);
2149 ret
= GetUrlCacheEntryInfoW(url
, NULL
, &nbytes
);
2150 error
= GetLastError();
2151 if (!ret
&& error
== ERROR_INSUFFICIENT_BUFFER
)
2153 if (!(info
= heap_alloc(nbytes
)))
2154 return ERROR_OUTOFMEMORY
;
2156 GetUrlCacheEntryInfoW(url
, info
, &nbytes
);
2158 ts
->ftExpires
= info
->ExpireTime
;
2159 ts
->ftLastModified
= info
->LastModifiedTime
;
2162 *size
= sizeof(*ts
);
2163 return ERROR_SUCCESS
;
2168 case INTERNET_OPTION_DATAFILE_NAME
: {
2171 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2173 if(!req
->cacheFile
) {
2175 return ERROR_INTERNET_ITEM_NOT_FOUND
;
2179 req_size
= (lstrlenW(req
->cacheFile
)+1) * sizeof(WCHAR
);
2180 if(*size
< req_size
)
2181 return ERROR_INSUFFICIENT_BUFFER
;
2184 memcpy(buffer
, req
->cacheFile
, *size
);
2185 return ERROR_SUCCESS
;
2187 req_size
= WideCharToMultiByte(CP_ACP
, 0, req
->cacheFile
, -1, NULL
, 0, NULL
, NULL
);
2188 if (req_size
> *size
)
2189 return ERROR_INSUFFICIENT_BUFFER
;
2191 *size
= WideCharToMultiByte(CP_ACP
, 0, req
->cacheFile
,
2192 -1, buffer
, *size
, NULL
, NULL
);
2193 return ERROR_SUCCESS
;
2197 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
: {
2198 PCCERT_CONTEXT context
;
2201 return ERROR_INTERNET_INVALID_OPERATION
;
2203 if(*size
< sizeof(INTERNET_CERTIFICATE_INFOA
)) {
2204 *size
= sizeof(INTERNET_CERTIFICATE_INFOA
);
2205 return ERROR_INSUFFICIENT_BUFFER
;
2208 context
= (PCCERT_CONTEXT
)NETCON_GetCert(req
->netconn
);
2210 INTERNET_CERTIFICATE_INFOA
*info
= (INTERNET_CERTIFICATE_INFOA
*)buffer
;
2213 memset(info
, 0, sizeof(*info
));
2214 info
->ftExpiry
= context
->pCertInfo
->NotAfter
;
2215 info
->ftStart
= context
->pCertInfo
->NotBefore
;
2216 len
= CertNameToStrA(context
->dwCertEncodingType
,
2217 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2218 info
->lpszSubjectInfo
= LocalAlloc(0, len
);
2219 if(info
->lpszSubjectInfo
)
2220 CertNameToStrA(context
->dwCertEncodingType
,
2221 &context
->pCertInfo
->Subject
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2222 info
->lpszSubjectInfo
, len
);
2223 len
= CertNameToStrA(context
->dwCertEncodingType
,
2224 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
, NULL
, 0);
2225 info
->lpszIssuerInfo
= LocalAlloc(0, len
);
2226 if(info
->lpszIssuerInfo
)
2227 CertNameToStrA(context
->dwCertEncodingType
,
2228 &context
->pCertInfo
->Issuer
, CERT_SIMPLE_NAME_STR
|CERT_NAME_STR_CRLF_FLAG
,
2229 info
->lpszIssuerInfo
, len
);
2230 info
->dwKeySize
= NETCON_GetCipherStrength(req
->netconn
);
2231 CertFreeCertificateContext(context
);
2232 return ERROR_SUCCESS
;
2234 return ERROR_NOT_SUPPORTED
;
2236 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2237 if (*size
< sizeof(DWORD
))
2238 return ERROR_INSUFFICIENT_BUFFER
;
2240 *size
= sizeof(DWORD
);
2241 *(DWORD
*)buffer
= req
->connect_timeout
;
2242 return ERROR_SUCCESS
;
2243 case INTERNET_OPTION_REQUEST_FLAGS
: {
2246 if (*size
< sizeof(DWORD
))
2247 return ERROR_INSUFFICIENT_BUFFER
;
2249 /* FIXME: Add support for:
2250 * INTERNET_REQFLAG_FROM_CACHE
2251 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2255 flags
|= INTERNET_REQFLAG_VIA_PROXY
;
2256 if(!req
->status_code
)
2257 flags
|= INTERNET_REQFLAG_NO_HEADERS
;
2259 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags
);
2261 *size
= sizeof(DWORD
);
2262 *(DWORD
*)buffer
= flags
;
2263 return ERROR_SUCCESS
;
2267 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
2270 static DWORD
HTTPREQ_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
2272 http_request_t
*req
= (http_request_t
*)hdr
;
2275 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2276 TRACE("Undocumented option 99\n");
2278 if (!buffer
|| size
!= sizeof(DWORD
))
2279 return ERROR_INVALID_PARAMETER
;
2280 if(*(DWORD
*)buffer
& ~SECURITY_SET_MASK
)
2281 return ERROR_INTERNET_OPTION_NOT_SETTABLE
;
2284 case INTERNET_OPTION_SECURITY_FLAGS
:
2288 if (!buffer
|| size
!= sizeof(DWORD
))
2289 return ERROR_INVALID_PARAMETER
;
2290 flags
= *(DWORD
*)buffer
;
2291 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags
);
2292 flags
&= SECURITY_SET_MASK
;
2293 req
->security_flags
|= flags
;
2295 req
->netconn
->security_flags
|= flags
;
2296 return ERROR_SUCCESS
;
2298 case INTERNET_OPTION_CONNECT_TIMEOUT
:
2299 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2300 req
->connect_timeout
= *(DWORD
*)buffer
;
2301 return ERROR_SUCCESS
;
2303 case INTERNET_OPTION_SEND_TIMEOUT
:
2304 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2305 req
->send_timeout
= *(DWORD
*)buffer
;
2306 return ERROR_SUCCESS
;
2308 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
2309 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
2310 req
->receive_timeout
= *(DWORD
*)buffer
;
2311 return ERROR_SUCCESS
;
2313 case INTERNET_OPTION_USERNAME
:
2314 heap_free(req
->session
->userName
);
2315 if (!(req
->session
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2316 return ERROR_SUCCESS
;
2318 case INTERNET_OPTION_PASSWORD
:
2319 heap_free(req
->session
->password
);
2320 if (!(req
->session
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2321 return ERROR_SUCCESS
;
2323 case INTERNET_OPTION_PROXY_USERNAME
:
2324 heap_free(req
->session
->appInfo
->proxyUsername
);
2325 if (!(req
->session
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2326 return ERROR_SUCCESS
;
2328 case INTERNET_OPTION_PROXY_PASSWORD
:
2329 heap_free(req
->session
->appInfo
->proxyPassword
);
2330 if (!(req
->session
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
2331 return ERROR_SUCCESS
;
2333 case INTERNET_OPTION_HTTP_DECODING
:
2334 if(size
!= sizeof(BOOL
))
2335 return ERROR_INVALID_PARAMETER
;
2336 req
->decoding
= *(BOOL
*)buffer
;
2337 return ERROR_SUCCESS
;
2340 return INET_SetOption(hdr
, option
, buffer
, size
);
2343 static void commit_cache_entry(http_request_t
*req
)
2345 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2349 CloseHandle(req
->hCacheFile
);
2350 req
->hCacheFile
= NULL
;
2352 if(HTTP_GetRequestURL(req
, url
)) {
2356 header
= build_response_header(req
, TRUE
);
2357 header_len
= (header
? strlenW(header
) : 0);
2358 CommitUrlCacheEntryW(url
, req
->cacheFile
, req
->expires
,
2359 req
->last_modified
, NORMAL_CACHE_ENTRY
,
2360 header
, header_len
, NULL
, 0);
2365 static void create_cache_entry(http_request_t
*req
)
2367 static const WCHAR no_cacheW
[] = {'n','o','-','c','a','c','h','e',0};
2368 static const WCHAR no_storeW
[] = {'n','o','-','s','t','o','r','e',0};
2370 WCHAR url
[INTERNET_MAX_URL_LENGTH
];
2371 WCHAR file_name
[MAX_PATH
+1];
2374 /* FIXME: We should free previous cache file earlier */
2375 heap_free(req
->cacheFile
);
2376 CloseHandle(req
->hCacheFile
);
2377 req
->hCacheFile
= NULL
;
2379 if(req
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
)
2383 int header_idx
= HTTP_GetCustomHeaderIndex(req
, szCache_Control
, 0, FALSE
);
2384 if(header_idx
!= -1) {
2387 for(ptr
=req
->custHeaders
[header_idx
].lpszValue
; *ptr
; ) {
2390 while(*ptr
==' ' || *ptr
=='\t')
2393 end
= strchrW(ptr
, ',');
2395 end
= ptr
+ strlenW(ptr
);
2397 if(!strncmpiW(ptr
, no_cacheW
, sizeof(no_cacheW
)/sizeof(*no_cacheW
)-1)
2398 || !strncmpiW(ptr
, no_storeW
, sizeof(no_storeW
)/sizeof(*no_storeW
)-1)) {
2411 if(!(req
->hdr
.dwFlags
& INTERNET_FLAG_NEED_FILE
))
2414 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2417 b
= HTTP_GetRequestURL(req
, url
);
2419 WARN("Could not get URL\n");
2423 b
= CreateUrlCacheEntryW(url
, req
->contentLength
== ~0u ? 0 : req
->contentLength
, NULL
, file_name
, 0);
2425 WARN("Could not create cache entry: %08x\n", GetLastError());
2429 req
->cacheFile
= heap_strdupW(file_name
);
2430 req
->hCacheFile
= CreateFileW(req
->cacheFile
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
2431 NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2432 if(req
->hCacheFile
== INVALID_HANDLE_VALUE
) {
2433 WARN("Could not create file: %u\n", GetLastError());
2434 req
->hCacheFile
= NULL
;
2438 if(req
->read_size
) {
2441 b
= WriteFile(req
->hCacheFile
, req
->read_buf
+req
->read_pos
, req
->read_size
, &written
, NULL
);
2443 FIXME("WriteFile failed: %u\n", GetLastError());
2445 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2446 commit_cache_entry(req
);
2450 /* read some more data into the read buffer (the read section must be held) */
2451 static DWORD
read_more_data( http_request_t
*req
, int maxlen
)
2458 /* move existing data to the start of the buffer */
2460 memmove( req
->read_buf
, req
->read_buf
+ req
->read_pos
, req
->read_size
);
2464 if (maxlen
== -1) maxlen
= sizeof(req
->read_buf
);
2466 res
= NETCON_recv( req
->netconn
, req
->read_buf
+ req
->read_size
,
2467 maxlen
- req
->read_size
, 0, &len
);
2468 if(res
== ERROR_SUCCESS
)
2469 req
->read_size
+= len
;
2474 /* remove some amount of data from the read buffer (the read section must be held) */
2475 static void remove_data( http_request_t
*req
, int count
)
2477 if (!(req
->read_size
-= count
)) req
->read_pos
= 0;
2478 else req
->read_pos
+= count
;
2481 static DWORD
read_line( http_request_t
*req
, LPSTR buffer
, DWORD
*len
)
2483 int count
, bytes_read
, pos
= 0;
2486 EnterCriticalSection( &req
->read_section
);
2489 BYTE
*eol
= memchr( req
->read_buf
+ req
->read_pos
, '\n', req
->read_size
);
2493 count
= eol
- (req
->read_buf
+ req
->read_pos
);
2494 bytes_read
= count
+ 1;
2496 else count
= bytes_read
= req
->read_size
;
2498 count
= min( count
, *len
- pos
);
2499 memcpy( buffer
+ pos
, req
->read_buf
+ req
->read_pos
, count
);
2501 remove_data( req
, bytes_read
);
2504 if ((res
= read_more_data( req
, -1 )))
2506 WARN( "read failed %u\n", res
);
2507 LeaveCriticalSection( &req
->read_section
);
2510 if (!req
->read_size
)
2513 TRACE( "returning empty string\n" );
2514 LeaveCriticalSection( &req
->read_section
);
2515 return ERROR_SUCCESS
;
2518 LeaveCriticalSection( &req
->read_section
);
2522 if (pos
&& buffer
[pos
- 1] == '\r') pos
--;
2525 buffer
[*len
- 1] = 0;
2526 TRACE( "returning %s\n", debugstr_a(buffer
));
2527 return ERROR_SUCCESS
;
2530 /* check if we have reached the end of the data to read (the read section must be held) */
2531 static BOOL
end_of_read_data( http_request_t
*req
)
2533 return !req
->read_size
&& req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
);
2536 static DWORD
read_http_stream(http_request_t
*req
, BYTE
*buf
, DWORD size
, DWORD
*read
, read_mode_t read_mode
)
2540 res
= req
->data_stream
->vtbl
->read(req
->data_stream
, req
, buf
, size
, read
, read_mode
);
2541 assert(*read
<= size
);
2543 if(req
->hCacheFile
) {
2548 bres
= WriteFile(req
->hCacheFile
, buf
, *read
, &written
, NULL
);
2550 FIXME("WriteFile failed: %u\n", GetLastError());
2553 if(req
->data_stream
->vtbl
->end_of_data(req
->data_stream
, req
))
2554 commit_cache_entry(req
);
2560 /* fetch some more data into the read buffer (the read section must be held) */
2561 static DWORD
refill_read_buffer(http_request_t
*req
, read_mode_t read_mode
, DWORD
*read_bytes
)
2565 if(req
->read_size
== sizeof(req
->read_buf
))
2566 return ERROR_SUCCESS
;
2570 memmove(req
->read_buf
, req
->read_buf
+req
->read_pos
, req
->read_size
);
2574 res
= read_http_stream(req
, req
->read_buf
+req
->read_size
, sizeof(req
->read_buf
) - req
->read_size
,
2576 req
->read_size
+= read
;
2578 TRACE("read %u bytes, read_size %u\n", read
, req
->read_size
);
2584 /* return the size of data available to be read immediately (the read section must be held) */
2585 static DWORD
get_avail_data( http_request_t
*req
)
2587 return req
->read_size
+ req
->data_stream
->vtbl
->get_avail_data(req
->data_stream
, req
);
2590 static DWORD
netconn_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2592 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2596 NETCON_query_data_available(req
->netconn
, &avail
);
2597 return netconn_stream
->content_length
== ~0u
2599 : min(avail
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2602 static BOOL
netconn_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2604 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2605 return netconn_stream
->content_read
== netconn_stream
->content_length
|| !req
->netconn
;
2608 static DWORD
netconn_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2609 DWORD
*read
, read_mode_t read_mode
)
2611 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2612 DWORD res
= ERROR_SUCCESS
;
2615 size
= min(size
, netconn_stream
->content_length
-netconn_stream
->content_read
);
2617 if(read_mode
== READMODE_NOBLOCK
) {
2618 DWORD avail
= netconn_get_avail_data(stream
, req
);
2623 if(size
&& req
->netconn
) {
2624 if((res
= NETCON_recv(req
->netconn
, buf
, size
, read_mode
== READMODE_SYNC
? MSG_WAITALL
: 0, &len
)))
2627 netconn_stream
->content_length
= netconn_stream
->content_read
;
2630 netconn_stream
->content_read
+= *read
= len
;
2631 TRACE("read %u bytes\n", len
);
2635 static BOOL
netconn_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2637 netconn_stream_t
*netconn_stream
= (netconn_stream_t
*)stream
;
2642 if(netconn_end_of_data(stream
, req
))
2646 avail
= netconn_get_avail_data(stream
, req
);
2650 if(NETCON_recv(req
->netconn
, buf
, min(avail
, sizeof(buf
)), 0, &len
) != ERROR_SUCCESS
)
2653 netconn_stream
->content_read
+= len
;
2654 }while(netconn_stream
->content_read
< netconn_stream
->content_length
);
2659 static void netconn_destroy(data_stream_t
*stream
)
2663 static const data_stream_vtbl_t netconn_stream_vtbl
= {
2664 netconn_get_avail_data
,
2665 netconn_end_of_data
,
2667 netconn_drain_content
,
2671 /* read some more data into the read buffer (the read section must be held) */
2672 static DWORD
read_more_chunked_data(chunked_stream_t
*stream
, http_request_t
*req
, int maxlen
)
2677 if (stream
->buf_pos
)
2679 /* move existing data to the start of the buffer */
2680 if(stream
->buf_size
)
2681 memmove(stream
->buf
, stream
->buf
+ stream
->buf_pos
, stream
->buf_size
);
2682 stream
->buf_pos
= 0;
2685 if (maxlen
== -1) maxlen
= sizeof(stream
->buf
);
2687 res
= NETCON_recv( req
->netconn
, stream
->buf
+ stream
->buf_size
,
2688 maxlen
- stream
->buf_size
, 0, &len
);
2689 if(res
== ERROR_SUCCESS
)
2690 stream
->buf_size
+= len
;
2695 /* remove some amount of data from the read buffer (the read section must be held) */
2696 static void remove_chunked_data(chunked_stream_t
*stream
, int count
)
2698 if (!(stream
->buf_size
-= count
)) stream
->buf_pos
= 0;
2699 else stream
->buf_pos
+= count
;
2702 /* discard data contents until we reach end of line (the read section must be held) */
2703 static DWORD
discard_chunked_eol(chunked_stream_t
*stream
, http_request_t
*req
)
2709 BYTE
*eol
= memchr(stream
->buf
+ stream
->buf_pos
, '\n', stream
->buf_size
);
2712 remove_chunked_data(stream
, (eol
+ 1) - (stream
->buf
+ stream
->buf_pos
));
2715 stream
->buf_pos
= stream
->buf_size
= 0; /* discard everything */
2716 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2717 } while (stream
->buf_size
);
2718 return ERROR_SUCCESS
;
2721 /* read the size of the next chunk (the read section must be held) */
2722 static DWORD
start_next_chunk(chunked_stream_t
*stream
, http_request_t
*req
)
2725 DWORD chunk_size
= 0, res
;
2727 if(stream
->chunk_size
!= ~0u && (res
= discard_chunked_eol(stream
, req
)) != ERROR_SUCCESS
)
2732 while (stream
->buf_size
)
2734 char ch
= stream
->buf
[stream
->buf_pos
];
2735 if (ch
>= '0' && ch
<= '9') chunk_size
= chunk_size
* 16 + ch
- '0';
2736 else if (ch
>= 'a' && ch
<= 'f') chunk_size
= chunk_size
* 16 + ch
- 'a' + 10;
2737 else if (ch
>= 'A' && ch
<= 'F') chunk_size
= chunk_size
* 16 + ch
- 'A' + 10;
2738 else if (ch
== ';' || ch
== '\r' || ch
== '\n')
2740 TRACE( "reading %u byte chunk\n", chunk_size
);
2741 stream
->chunk_size
= chunk_size
;
2742 req
->contentLength
+= chunk_size
;
2743 return discard_chunked_eol(stream
, req
);
2745 remove_chunked_data(stream
, 1);
2747 if ((res
= read_more_chunked_data(stream
, req
, -1)) != ERROR_SUCCESS
) return res
;
2748 if (!stream
->buf_size
)
2750 stream
->chunk_size
= 0;
2751 return ERROR_SUCCESS
;
2756 static DWORD
chunked_get_avail_data(data_stream_t
*stream
, http_request_t
*req
)
2758 /* Allow reading only from read buffer */
2762 static BOOL
chunked_end_of_data(data_stream_t
*stream
, http_request_t
*req
)
2764 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2765 return !chunked_stream
->chunk_size
;
2768 static DWORD
chunked_read(data_stream_t
*stream
, http_request_t
*req
, BYTE
*buf
, DWORD size
,
2769 DWORD
*read
, read_mode_t read_mode
)
2771 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2772 DWORD read_bytes
= 0, ret_read
= 0, res
= ERROR_SUCCESS
;
2774 if(chunked_stream
->chunk_size
== ~0u) {
2775 res
= start_next_chunk(chunked_stream
, req
);
2776 if(res
!= ERROR_SUCCESS
)
2780 while(size
&& chunked_stream
->chunk_size
) {
2781 if(chunked_stream
->buf_size
) {
2782 read_bytes
= min(size
, min(chunked_stream
->buf_size
, chunked_stream
->chunk_size
));
2784 /* this could block */
2785 if(read_mode
== READMODE_NOBLOCK
&& read_bytes
== chunked_stream
->chunk_size
)
2788 memcpy(buf
+ret_read
, chunked_stream
->buf
+chunked_stream
->buf_pos
, read_bytes
);
2789 remove_chunked_data(chunked_stream
, read_bytes
);
2791 read_bytes
= min(size
, chunked_stream
->chunk_size
);
2793 if(read_mode
== READMODE_NOBLOCK
) {
2796 if(!req
->netconn
|| !NETCON_query_data_available(req
->netconn
, &avail
) || !avail
)
2798 if(read_bytes
> avail
)
2801 /* this could block */
2802 if(read_bytes
== chunked_stream
->chunk_size
)
2806 res
= NETCON_recv(req
->netconn
, (char *)buf
+ret_read
, read_bytes
, 0, (int*)&read_bytes
);
2807 if(res
!= ERROR_SUCCESS
)
2811 chunked_stream
->chunk_size
-= read_bytes
;
2813 ret_read
+= read_bytes
;
2814 if(!chunked_stream
->chunk_size
) {
2815 assert(read_mode
!= READMODE_NOBLOCK
);
2816 res
= start_next_chunk(chunked_stream
, req
);
2817 if(res
!= ERROR_SUCCESS
)
2821 if(read_mode
== READMODE_ASYNC
)
2822 read_mode
= READMODE_NOBLOCK
;
2825 TRACE("read %u bytes\n", ret_read
);
2830 static BOOL
chunked_drain_content(data_stream_t
*stream
, http_request_t
*req
)
2832 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2834 /* FIXME: we can do better */
2835 return !chunked_stream
->chunk_size
;
2838 static void chunked_destroy(data_stream_t
*stream
)
2840 chunked_stream_t
*chunked_stream
= (chunked_stream_t
*)stream
;
2841 heap_free(chunked_stream
);
2844 static const data_stream_vtbl_t chunked_stream_vtbl
= {
2845 chunked_get_avail_data
,
2846 chunked_end_of_data
,
2848 chunked_drain_content
,
2852 /* set the request content length based on the headers */
2853 static DWORD
set_content_length(http_request_t
*request
)
2855 static const WCHAR szChunked
[] = {'c','h','u','n','k','e','d',0};
2859 if(request
->status_code
== HTTP_STATUS_NO_CONTENT
) {
2860 request
->contentLength
= request
->netconn_stream
.content_length
= 0;
2861 return ERROR_SUCCESS
;
2864 size
= sizeof(request
->contentLength
);
2865 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
,
2866 &request
->contentLength
, &size
, NULL
) != ERROR_SUCCESS
)
2867 request
->contentLength
= ~0u;
2868 request
->netconn_stream
.content_length
= request
->contentLength
;
2869 request
->netconn_stream
.content_read
= request
->read_size
;
2871 size
= sizeof(encoding
);
2872 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_TRANSFER_ENCODING
, encoding
, &size
, NULL
) == ERROR_SUCCESS
&&
2873 !strcmpiW(encoding
, szChunked
))
2875 chunked_stream_t
*chunked_stream
;
2877 chunked_stream
= heap_alloc(sizeof(*chunked_stream
));
2879 return ERROR_OUTOFMEMORY
;
2881 chunked_stream
->data_stream
.vtbl
= &chunked_stream_vtbl
;
2882 chunked_stream
->buf_size
= chunked_stream
->buf_pos
= 0;
2883 chunked_stream
->chunk_size
= ~0u;
2885 if(request
->read_size
) {
2886 memcpy(chunked_stream
->buf
, request
->read_buf
+request
->read_pos
, request
->read_size
);
2887 chunked_stream
->buf_size
= request
->read_size
;
2888 request
->read_size
= request
->read_pos
= 0;
2891 request
->data_stream
= &chunked_stream
->data_stream
;
2892 request
->contentLength
= ~0u;
2893 request
->read_chunked
= TRUE
;
2896 if(request
->decoding
) {
2899 static const WCHAR gzipW
[] = {'g','z','i','p',0};
2901 encoding_idx
= HTTP_GetCustomHeaderIndex(request
, szContent_Encoding
, 0, FALSE
);
2902 if(encoding_idx
!= -1 && !strcmpiW(request
->custHeaders
[encoding_idx
].lpszValue
, gzipW
)) {
2903 HTTP_DeleteCustomHeader(request
, encoding_idx
);
2904 return init_gzip_stream(request
);
2908 return ERROR_SUCCESS
;
2911 static void send_request_complete(http_request_t
*req
, DWORD_PTR result
, DWORD error
)
2913 INTERNET_ASYNC_RESULT iar
;
2915 iar
.dwResult
= result
;
2916 iar
.dwError
= error
;
2918 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_COMPLETE
, &iar
,
2919 sizeof(INTERNET_ASYNC_RESULT
));
2922 static void HTTP_ReceiveRequestData(http_request_t
*req
, BOOL first_notif
, DWORD
*ret_size
)
2924 DWORD res
, read
= 0, avail
= 0;
2929 EnterCriticalSection( &req
->read_section
);
2931 mode
= first_notif
&& req
->read_size
? READMODE_NOBLOCK
: READMODE_ASYNC
;
2932 res
= refill_read_buffer(req
, mode
, &read
);
2933 if(res
== ERROR_SUCCESS
)
2934 avail
= get_avail_data(req
);
2936 LeaveCriticalSection( &req
->read_section
);
2938 if(res
!= ERROR_SUCCESS
|| (mode
!= READMODE_NOBLOCK
&& !read
)) {
2939 WARN("res %u read %u, closing connection\n", res
, read
);
2940 http_release_netconn(req
, FALSE
);
2943 if(res
!= ERROR_SUCCESS
) {
2944 send_request_complete(req
, 0, res
);
2953 send_request_complete(req
, req
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)req
->hdr
.hInternet
: 1, avail
);
2956 /* read data from the http connection (the read section must be held) */
2957 static DWORD
HTTPREQ_Read(http_request_t
*req
, void *buffer
, DWORD size
, DWORD
*read
, BOOL sync
)
2959 DWORD current_read
= 0, ret_read
= 0;
2960 read_mode_t read_mode
;
2961 DWORD res
= ERROR_SUCCESS
;
2963 read_mode
= req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
? READMODE_ASYNC
: READMODE_SYNC
;
2965 EnterCriticalSection( &req
->read_section
);
2967 if(req
->read_size
) {
2968 ret_read
= min(size
, req
->read_size
);
2969 memcpy(buffer
, req
->read_buf
+req
->read_pos
, ret_read
);
2970 req
->read_size
-= ret_read
;
2971 req
->read_pos
+= ret_read
;
2972 if(read_mode
== READMODE_ASYNC
)
2973 read_mode
= READMODE_NOBLOCK
;
2976 if(ret_read
< size
) {
2977 res
= read_http_stream(req
, (BYTE
*)buffer
+ret_read
, size
-ret_read
, ¤t_read
, read_mode
);
2978 ret_read
+= current_read
;
2981 LeaveCriticalSection( &req
->read_section
);
2984 TRACE( "retrieved %u bytes (%u)\n", ret_read
, req
->contentLength
);
2986 if(size
&& !ret_read
)
2987 http_release_netconn(req
, res
== ERROR_SUCCESS
);
2992 static BOOL
drain_content(http_request_t
*req
, BOOL blocking
)
2996 if(!req
->netconn
|| req
->contentLength
== -1)
2999 if(!strcmpW(req
->verb
, szHEAD
))
3003 return req
->data_stream
->vtbl
->drain_content(req
->data_stream
, req
);
3005 EnterCriticalSection( &req
->read_section
);
3008 DWORD bytes_read
, res
;
3011 res
= HTTPREQ_Read(req
, buf
, sizeof(buf
), &bytes_read
, TRUE
);
3012 if(res
!= ERROR_SUCCESS
) {
3022 LeaveCriticalSection( &req
->read_section
);
3026 static DWORD
HTTPREQ_ReadFile(object_header_t
*hdr
, void *buffer
, DWORD size
, DWORD
*read
)
3028 http_request_t
*req
= (http_request_t
*)hdr
;
3031 EnterCriticalSection( &req
->read_section
);
3032 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3033 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3035 res
= HTTPREQ_Read(req
, buffer
, size
, read
, TRUE
);
3036 if(res
== ERROR_SUCCESS
)
3038 LeaveCriticalSection( &req
->read_section
);
3048 } read_file_ex_task_t
;
3050 static void AsyncReadFileExProc(task_header_t
*hdr
)
3052 read_file_ex_task_t
*task
= (read_file_ex_task_t
*)hdr
;
3053 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
3056 TRACE("INTERNETREADFILEEXW %p\n", task
->hdr
.hdr
);
3058 res
= HTTPREQ_Read(req
, task
->buf
, task
->size
, task
->ret_read
, TRUE
);
3059 send_request_complete(req
, res
== ERROR_SUCCESS
, res
);
3062 static DWORD
HTTPREQ_ReadFileEx(object_header_t
*hdr
, void *buf
, DWORD size
, DWORD
*ret_read
,
3063 DWORD flags
, DWORD_PTR context
)
3066 http_request_t
*req
= (http_request_t
*)hdr
;
3067 DWORD res
, read
, cread
, error
= ERROR_SUCCESS
;
3069 if (flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
))
3070 FIXME("these dwFlags aren't implemented: 0x%x\n", flags
& ~(IRF_ASYNC
|IRF_NO_WAIT
));
3072 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3074 if (hdr
->dwFlags
& INTERNET_FLAG_ASYNC
)
3076 read_file_ex_task_t
*task
;
3078 if (TryEnterCriticalSection( &req
->read_section
))
3080 if (get_avail_data(req
))
3082 res
= HTTPREQ_Read(req
, buf
, size
, &read
, FALSE
);
3083 LeaveCriticalSection( &req
->read_section
);
3086 LeaveCriticalSection( &req
->read_section
);
3089 task
= alloc_async_task(&req
->hdr
, AsyncReadFileExProc
, sizeof(*task
));
3092 task
->ret_read
= ret_read
;
3094 INTERNET_AsyncCall(&task
->hdr
);
3096 return ERROR_IO_PENDING
;
3101 EnterCriticalSection( &req
->read_section
);
3102 if(hdr
->dwError
== ERROR_SUCCESS
)
3103 hdr
->dwError
= INTERNET_HANDLE_IN_USE
;
3104 else if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3105 hdr
->dwError
= ERROR_INTERNET_INTERNAL_ERROR
;
3108 res
= HTTPREQ_Read(req
, (char*)buf
+read
, size
-read
, &cread
, !(flags
& IRF_NO_WAIT
));
3109 if(res
!= ERROR_SUCCESS
)
3113 if(read
== size
|| end_of_read_data(req
))
3116 LeaveCriticalSection( &req
->read_section
);
3118 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3119 &cread
, sizeof(cread
));
3120 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
,
3121 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
3123 EnterCriticalSection( &req
->read_section
);
3126 if(hdr
->dwError
== INTERNET_HANDLE_IN_USE
)
3127 hdr
->dwError
= ERROR_SUCCESS
;
3129 error
= hdr
->dwError
;
3131 LeaveCriticalSection( &req
->read_section
);
3135 if (res
== ERROR_SUCCESS
) {
3136 INTERNET_SendCallback(&req
->hdr
, req
->hdr
.dwContext
, INTERNET_STATUS_RESPONSE_RECEIVED
,
3137 &read
, sizeof(read
));
3140 return res
==ERROR_SUCCESS
? error
: res
;
3143 static DWORD
HTTPREQ_WriteFile(object_header_t
*hdr
, const void *buffer
, DWORD size
, DWORD
*written
)
3146 http_request_t
*request
= (http_request_t
*)hdr
;
3148 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
3151 res
= NETCON_send(request
->netconn
, buffer
, size
, 0, (LPINT
)written
);
3152 if (res
== ERROR_SUCCESS
)
3153 request
->bytesWritten
+= *written
;
3155 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REQUEST_SENT
, written
, sizeof(DWORD
));
3162 } http_data_available_task_t
;
3164 static void AsyncQueryDataAvailableProc(task_header_t
*hdr
)
3166 http_data_available_task_t
*task
= (http_data_available_task_t
*)hdr
;
3168 HTTP_ReceiveRequestData((http_request_t
*)task
->hdr
.hdr
, FALSE
, task
->ret_size
);
3171 static DWORD
HTTPREQ_QueryDataAvailable(object_header_t
*hdr
, DWORD
*available
, DWORD flags
, DWORD_PTR ctx
)
3173 http_request_t
*req
= (http_request_t
*)hdr
;
3175 TRACE("(%p %p %x %lx)\n", req
, available
, flags
, ctx
);
3177 if (req
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
3179 http_data_available_task_t
*task
;
3181 /* never wait, if we can't enter the section we queue an async request right away */
3182 if (TryEnterCriticalSection( &req
->read_section
))
3184 refill_read_buffer(req
, READMODE_NOBLOCK
, NULL
);
3185 if ((*available
= get_avail_data( req
))) goto done
;
3186 if (end_of_read_data( req
)) goto done
;
3187 LeaveCriticalSection( &req
->read_section
);
3190 task
= alloc_async_task(&req
->hdr
, AsyncQueryDataAvailableProc
, sizeof(*task
));
3191 task
->ret_size
= available
;
3192 INTERNET_AsyncCall(&task
->hdr
);
3193 return ERROR_IO_PENDING
;
3196 EnterCriticalSection( &req
->read_section
);
3198 if (!(*available
= get_avail_data( req
)) && !end_of_read_data( req
))
3200 refill_read_buffer( req
, READMODE_ASYNC
, NULL
);
3201 *available
= get_avail_data( req
);
3205 LeaveCriticalSection( &req
->read_section
);
3207 TRACE( "returning %u\n", *available
);
3208 return ERROR_SUCCESS
;
3211 static const object_vtbl_t HTTPREQVtbl
= {
3213 HTTPREQ_CloseConnection
,
3214 HTTPREQ_QueryOption
,
3219 HTTPREQ_QueryDataAvailable
,
3223 /***********************************************************************
3224 * HTTP_HttpOpenRequestW (internal)
3226 * Open a HTTP request handle
3229 * HINTERNET a HTTP request handle on success
3233 static DWORD
HTTP_HttpOpenRequestW(http_session_t
*session
,
3234 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3235 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3236 DWORD dwFlags
, DWORD_PTR dwContext
, HINTERNET
*ret
)
3238 appinfo_t
*hIC
= session
->appInfo
;
3239 http_request_t
*request
;
3240 DWORD len
, res
= ERROR_SUCCESS
;
3244 request
= alloc_object(&session
->hdr
, &HTTPREQVtbl
, sizeof(http_request_t
));
3246 return ERROR_OUTOFMEMORY
;
3248 request
->hdr
.htype
= WH_HHTTPREQ
;
3249 request
->hdr
.dwFlags
= dwFlags
;
3250 request
->hdr
.dwContext
= dwContext
;
3251 request
->contentLength
= ~0u;
3253 request
->netconn_stream
.data_stream
.vtbl
= &netconn_stream_vtbl
;
3254 request
->data_stream
= &request
->netconn_stream
.data_stream
;
3255 request
->connect_timeout
= session
->connect_timeout
;
3256 request
->send_timeout
= session
->send_timeout
;
3257 request
->receive_timeout
= session
->receive_timeout
;
3259 InitializeCriticalSection( &request
->read_section
);
3260 request
->read_section
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": http_request_t.read_section");
3262 WININET_AddRef( &session
->hdr
);
3263 request
->session
= session
;
3264 list_add_head( &session
->hdr
.children
, &request
->hdr
.entry
);
3266 request
->server
= get_server(session
->hostName
, session
->hostPort
, (dwFlags
& INTERNET_FLAG_SECURE
) != 0, TRUE
);
3267 if(!request
->server
) {
3268 WININET_Release(&request
->hdr
);
3269 return ERROR_OUTOFMEMORY
;
3272 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_CN_INVALID
)
3273 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
3274 if (dwFlags
& INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
)
3275 request
->security_flags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
3277 if (lpszObjectName
&& *lpszObjectName
) {
3281 rc
= UrlEscapeW(lpszObjectName
, NULL
, &len
, URL_ESCAPE_SPACES_ONLY
);
3282 if (rc
!= E_POINTER
)
3283 len
= strlenW(lpszObjectName
)+1;
3284 request
->path
= heap_alloc(len
*sizeof(WCHAR
));
3285 rc
= UrlEscapeW(lpszObjectName
, request
->path
, &len
,
3286 URL_ESCAPE_SPACES_ONLY
);
3289 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName
),rc
);
3290 strcpyW(request
->path
,lpszObjectName
);
3293 static const WCHAR slashW
[] = {'/',0};
3295 request
->path
= heap_strdupW(slashW
);
3298 if (lpszReferrer
&& *lpszReferrer
)
3299 HTTP_ProcessHeader(request
, HTTP_REFERER
, lpszReferrer
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3301 if (lpszAcceptTypes
)
3304 for (i
= 0; lpszAcceptTypes
[i
]; i
++)
3306 if (!*lpszAcceptTypes
[i
]) continue;
3307 HTTP_ProcessHeader(request
, HTTP_ACCEPT
, lpszAcceptTypes
[i
],
3308 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
|
3309 HTTP_ADDHDR_FLAG_REQ
|
3310 (i
== 0 ? HTTP_ADDHDR_FLAG_REPLACE
: 0));
3314 request
->verb
= heap_strdupW(lpszVerb
&& *lpszVerb
? lpszVerb
: szGET
);
3315 request
->version
= heap_strdupW(lpszVersion
&& *lpszVersion
? lpszVersion
: g_szHttp1_1
);
3317 HTTP_ProcessHeader(request
, hostW
, request
->server
->canon_host_port
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REQ
);
3319 if (session
->hostPort
== INTERNET_INVALID_PORT_NUMBER
)
3320 session
->hostPort
= INTERNET_DEFAULT_HTTP_PORT
;
3322 if (hIC
->proxy
&& hIC
->proxy
[0] && !HTTP_ShouldBypassProxy(hIC
, session
->hostName
))
3323 HTTP_DealWithProxy( hIC
, session
, request
);
3325 INTERNET_SendCallback(&session
->hdr
, dwContext
,
3326 INTERNET_STATUS_HANDLE_CREATED
, &request
->hdr
.hInternet
,
3329 TRACE("<-- %u (%p)\n", res
, request
);
3331 if(res
!= ERROR_SUCCESS
) {
3332 WININET_Release( &request
->hdr
);
3337 *ret
= request
->hdr
.hInternet
;
3338 return ERROR_SUCCESS
;
3341 /***********************************************************************
3342 * HttpOpenRequestW (WININET.@)
3344 * Open a HTTP request handle
3347 * HINTERNET a HTTP request handle on success
3351 HINTERNET WINAPI
HttpOpenRequestW(HINTERNET hHttpSession
,
3352 LPCWSTR lpszVerb
, LPCWSTR lpszObjectName
, LPCWSTR lpszVersion
,
3353 LPCWSTR lpszReferrer
, LPCWSTR
*lpszAcceptTypes
,
3354 DWORD dwFlags
, DWORD_PTR dwContext
)
3356 http_session_t
*session
;
3357 HINTERNET handle
= NULL
;
3360 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession
,
3361 debugstr_w(lpszVerb
), debugstr_w(lpszObjectName
),
3362 debugstr_w(lpszVersion
), debugstr_w(lpszReferrer
), lpszAcceptTypes
,
3363 dwFlags
, dwContext
);
3364 if(lpszAcceptTypes
!=NULL
)
3367 for(i
=0;lpszAcceptTypes
[i
]!=NULL
;i
++)
3368 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes
[i
]));
3371 session
= (http_session_t
*) get_handle_object( hHttpSession
);
3372 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
3374 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3379 * My tests seem to show that the windows version does not
3380 * become asynchronous until after this point. And anyhow
3381 * if this call was asynchronous then how would you get the
3382 * necessary HINTERNET pointer returned by this function.
3385 res
= HTTP_HttpOpenRequestW(session
, lpszVerb
, lpszObjectName
,
3386 lpszVersion
, lpszReferrer
, lpszAcceptTypes
,
3387 dwFlags
, dwContext
, &handle
);
3390 WININET_Release( &session
->hdr
);
3391 TRACE("returning %p\n", handle
);
3392 if(res
!= ERROR_SUCCESS
)
3397 static const LPCWSTR header_lookup
[] = {
3398 szMime_Version
, /* HTTP_QUERY_MIME_VERSION = 0 */
3399 szContent_Type
, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3400 szContent_Transfer_Encoding
,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3401 szContent_ID
, /* HTTP_QUERY_CONTENT_ID = 3 */
3402 NULL
, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3403 szContent_Length
, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3404 szContent_Language
, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3405 szAllow
, /* HTTP_QUERY_ALLOW = 7 */
3406 szPublic
, /* HTTP_QUERY_PUBLIC = 8 */
3407 szDate
, /* HTTP_QUERY_DATE = 9 */
3408 szExpires
, /* HTTP_QUERY_EXPIRES = 10 */
3409 szLast_Modified
, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3410 NULL
, /* HTTP_QUERY_MESSAGE_ID = 12 */
3411 szURI
, /* HTTP_QUERY_URI = 13 */
3412 szFrom
, /* HTTP_QUERY_DERIVED_FROM = 14 */
3413 NULL
, /* HTTP_QUERY_COST = 15 */
3414 NULL
, /* HTTP_QUERY_LINK = 16 */
3415 szPragma
, /* HTTP_QUERY_PRAGMA = 17 */
3416 NULL
, /* HTTP_QUERY_VERSION = 18 */
3417 szStatus
, /* HTTP_QUERY_STATUS_CODE = 19 */
3418 NULL
, /* HTTP_QUERY_STATUS_TEXT = 20 */
3419 NULL
, /* HTTP_QUERY_RAW_HEADERS = 21 */
3420 NULL
, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3421 szConnection
, /* HTTP_QUERY_CONNECTION = 23 */
3422 szAccept
, /* HTTP_QUERY_ACCEPT = 24 */
3423 szAccept_Charset
, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3424 szAccept_Encoding
, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3425 szAccept_Language
, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3426 szAuthorization
, /* HTTP_QUERY_AUTHORIZATION = 28 */
3427 szContent_Encoding
, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3428 NULL
, /* HTTP_QUERY_FORWARDED = 30 */
3429 NULL
, /* HTTP_QUERY_FROM = 31 */
3430 szIf_Modified_Since
, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3431 szLocation
, /* HTTP_QUERY_LOCATION = 33 */
3432 NULL
, /* HTTP_QUERY_ORIG_URI = 34 */
3433 szReferer
, /* HTTP_QUERY_REFERER = 35 */
3434 szRetry_After
, /* HTTP_QUERY_RETRY_AFTER = 36 */
3435 szServer
, /* HTTP_QUERY_SERVER = 37 */
3436 NULL
, /* HTTP_TITLE = 38 */
3437 szUser_Agent
, /* HTTP_QUERY_USER_AGENT = 39 */
3438 szWWW_Authenticate
, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3439 szProxy_Authenticate
, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3440 szAccept_Ranges
, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3441 szSet_Cookie
, /* HTTP_QUERY_SET_COOKIE = 43 */
3442 szCookie
, /* HTTP_QUERY_COOKIE = 44 */
3443 NULL
, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3444 NULL
, /* HTTP_QUERY_REFRESH = 46 */
3445 szContent_Disposition
, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3446 szAge
, /* HTTP_QUERY_AGE = 48 */
3447 szCache_Control
, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3448 szContent_Base
, /* HTTP_QUERY_CONTENT_BASE = 50 */
3449 szContent_Location
, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3450 szContent_MD5
, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3451 szContent_Range
, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3452 szETag
, /* HTTP_QUERY_ETAG = 54 */
3453 hostW
, /* HTTP_QUERY_HOST = 55 */
3454 szIf_Match
, /* HTTP_QUERY_IF_MATCH = 56 */
3455 szIf_None_Match
, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3456 szIf_Range
, /* HTTP_QUERY_IF_RANGE = 58 */
3457 szIf_Unmodified_Since
, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3458 szMax_Forwards
, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3459 szProxy_Authorization
, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3460 szRange
, /* HTTP_QUERY_RANGE = 62 */
3461 szTransfer_Encoding
, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3462 szUpgrade
, /* HTTP_QUERY_UPGRADE = 64 */
3463 szVary
, /* HTTP_QUERY_VARY = 65 */
3464 szVia
, /* HTTP_QUERY_VIA = 66 */
3465 szWarning
, /* HTTP_QUERY_WARNING = 67 */
3466 szExpect
, /* HTTP_QUERY_EXPECT = 68 */
3467 szProxy_Connection
, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3468 szUnless_Modified_Since
, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3471 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3473 /***********************************************************************
3474 * HTTP_HttpQueryInfoW (internal)
3476 static DWORD
HTTP_HttpQueryInfoW(http_request_t
*request
, DWORD dwInfoLevel
,
3477 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3479 LPHTTPHEADERW lphttpHdr
= NULL
;
3480 BOOL request_only
= dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
;
3481 INT requested_index
= lpdwIndex
? *lpdwIndex
: 0;
3482 DWORD level
= (dwInfoLevel
& ~HTTP_QUERY_MODIFIER_FLAGS_MASK
);
3485 /* Find requested header structure */
3488 case HTTP_QUERY_CUSTOM
:
3489 if (!lpBuffer
) return ERROR_INVALID_PARAMETER
;
3490 index
= HTTP_GetCustomHeaderIndex(request
, lpBuffer
, requested_index
, request_only
);
3492 case HTTP_QUERY_RAW_HEADERS_CRLF
:
3496 DWORD res
= ERROR_INVALID_PARAMETER
;
3499 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
3501 headers
= build_response_header(request
, TRUE
);
3503 return ERROR_OUTOFMEMORY
;
3505 len
= strlenW(headers
) * sizeof(WCHAR
);
3506 if (len
+ sizeof(WCHAR
) > *lpdwBufferLength
)
3508 len
+= sizeof(WCHAR
);
3509 res
= ERROR_INSUFFICIENT_BUFFER
;
3513 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3514 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
/ sizeof(WCHAR
)));
3515 res
= ERROR_SUCCESS
;
3517 *lpdwBufferLength
= len
;
3522 case HTTP_QUERY_RAW_HEADERS
:
3528 headers
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, FALSE
);
3530 headers
= build_response_header(request
, FALSE
);
3532 return ERROR_OUTOFMEMORY
;
3534 len
= strlenW(headers
) * sizeof(WCHAR
);
3535 if (len
> *lpdwBufferLength
)
3537 *lpdwBufferLength
= len
;
3539 return ERROR_INSUFFICIENT_BUFFER
;
3546 TRACE("returning data: %s\n", debugstr_wn(headers
, len
/ sizeof(WCHAR
)));
3548 for (i
=0; i
<len
; i
++)
3550 if (headers
[i
] == '\n')
3553 memcpy(lpBuffer
, headers
, len
+ sizeof(WCHAR
));
3555 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3558 return ERROR_SUCCESS
;
3560 case HTTP_QUERY_STATUS_TEXT
:
3561 if (request
->statusText
)
3563 DWORD len
= strlenW(request
->statusText
);
3564 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3566 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3567 return ERROR_INSUFFICIENT_BUFFER
;
3571 memcpy(lpBuffer
, request
->statusText
, (len
+ 1) * sizeof(WCHAR
));
3572 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3574 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3575 return ERROR_SUCCESS
;
3578 case HTTP_QUERY_VERSION
:
3579 if (request
->version
)
3581 DWORD len
= strlenW(request
->version
);
3582 if (len
+ 1 > *lpdwBufferLength
/sizeof(WCHAR
))
3584 *lpdwBufferLength
= (len
+ 1) * sizeof(WCHAR
);
3585 return ERROR_INSUFFICIENT_BUFFER
;
3589 memcpy(lpBuffer
, request
->version
, (len
+ 1) * sizeof(WCHAR
));
3590 TRACE("returning data: %s\n", debugstr_wn(lpBuffer
, len
));
3592 *lpdwBufferLength
= len
* sizeof(WCHAR
);
3593 return ERROR_SUCCESS
;
3596 case HTTP_QUERY_CONTENT_ENCODING
:
3597 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[request
->read_gzip
? HTTP_QUERY_CONTENT_TYPE
: level
],
3598 requested_index
,request_only
);
3600 case HTTP_QUERY_STATUS_CODE
: {
3601 DWORD res
= ERROR_SUCCESS
;
3604 return ERROR_HTTP_INVALID_QUERY_REQUEST
;
3609 if(dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) {
3610 if(*lpdwBufferLength
>= sizeof(DWORD
))
3611 *(DWORD
*)lpBuffer
= request
->status_code
;
3613 res
= ERROR_INSUFFICIENT_BUFFER
;
3614 *lpdwBufferLength
= sizeof(DWORD
);
3618 static const WCHAR formatW
[] = {'%','u',0};
3620 size
= sprintfW(buf
, formatW
, request
->status_code
) * sizeof(WCHAR
);
3622 if(size
<= *lpdwBufferLength
) {
3623 memcpy(lpBuffer
, buf
, size
+sizeof(WCHAR
));
3625 size
+= sizeof(WCHAR
);
3626 res
= ERROR_INSUFFICIENT_BUFFER
;
3629 *lpdwBufferLength
= size
;
3634 assert (LAST_TABLE_HEADER
== (HTTP_QUERY_UNLESS_MODIFIED_SINCE
+ 1));
3636 if (level
< LAST_TABLE_HEADER
&& header_lookup
[level
])
3637 index
= HTTP_GetCustomHeaderIndex(request
, header_lookup
[level
],
3638 requested_index
,request_only
);
3642 lphttpHdr
= &request
->custHeaders
[index
];
3644 /* Ensure header satisfies requested attributes */
3646 ((dwInfoLevel
& HTTP_QUERY_FLAG_REQUEST_HEADERS
) &&
3647 (~lphttpHdr
->wFlags
& HDR_ISREQUEST
)))
3649 return ERROR_HTTP_HEADER_NOT_FOUND
;
3652 if (lpdwIndex
) (*lpdwIndex
)++;
3654 /* coalesce value to requested type */
3655 if (dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
&& lpBuffer
)
3657 *(int *)lpBuffer
= atoiW(lphttpHdr
->lpszValue
);
3658 TRACE(" returning number: %d\n", *(int *)lpBuffer
);
3660 else if (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
&& lpBuffer
)
3666 tmpTime
= ConvertTimeString(lphttpHdr
->lpszValue
);
3668 tmpTM
= *gmtime(&tmpTime
);
3669 STHook
= (SYSTEMTIME
*)lpBuffer
;
3670 STHook
->wDay
= tmpTM
.tm_mday
;
3671 STHook
->wHour
= tmpTM
.tm_hour
;
3672 STHook
->wMilliseconds
= 0;
3673 STHook
->wMinute
= tmpTM
.tm_min
;
3674 STHook
->wDayOfWeek
= tmpTM
.tm_wday
;
3675 STHook
->wMonth
= tmpTM
.tm_mon
+ 1;
3676 STHook
->wSecond
= tmpTM
.tm_sec
;
3677 STHook
->wYear
= 1900+tmpTM
.tm_year
;
3679 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3680 STHook
->wYear
, STHook
->wMonth
, STHook
->wDay
, STHook
->wDayOfWeek
,
3681 STHook
->wHour
, STHook
->wMinute
, STHook
->wSecond
, STHook
->wMilliseconds
);
3683 else if (lphttpHdr
->lpszValue
)
3685 DWORD len
= (strlenW(lphttpHdr
->lpszValue
) + 1) * sizeof(WCHAR
);
3687 if (len
> *lpdwBufferLength
)
3689 *lpdwBufferLength
= len
;
3690 return ERROR_INSUFFICIENT_BUFFER
;
3694 memcpy(lpBuffer
, lphttpHdr
->lpszValue
, len
);
3695 TRACE("! returning string: %s\n", debugstr_w(lpBuffer
));
3697 *lpdwBufferLength
= len
- sizeof(WCHAR
);
3699 return ERROR_SUCCESS
;
3702 /***********************************************************************
3703 * HttpQueryInfoW (WININET.@)
3705 * Queries for information about an HTTP request
3712 BOOL WINAPI
HttpQueryInfoW(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3713 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3715 http_request_t
*request
;
3718 if (TRACE_ON(wininet
)) {
3719 #define FE(x) { x, #x }
3720 static const wininet_flag_info query_flags
[] = {
3721 FE(HTTP_QUERY_MIME_VERSION
),
3722 FE(HTTP_QUERY_CONTENT_TYPE
),
3723 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING
),
3724 FE(HTTP_QUERY_CONTENT_ID
),
3725 FE(HTTP_QUERY_CONTENT_DESCRIPTION
),
3726 FE(HTTP_QUERY_CONTENT_LENGTH
),
3727 FE(HTTP_QUERY_CONTENT_LANGUAGE
),
3728 FE(HTTP_QUERY_ALLOW
),
3729 FE(HTTP_QUERY_PUBLIC
),
3730 FE(HTTP_QUERY_DATE
),
3731 FE(HTTP_QUERY_EXPIRES
),
3732 FE(HTTP_QUERY_LAST_MODIFIED
),
3733 FE(HTTP_QUERY_MESSAGE_ID
),
3735 FE(HTTP_QUERY_DERIVED_FROM
),
3736 FE(HTTP_QUERY_COST
),
3737 FE(HTTP_QUERY_LINK
),
3738 FE(HTTP_QUERY_PRAGMA
),
3739 FE(HTTP_QUERY_VERSION
),
3740 FE(HTTP_QUERY_STATUS_CODE
),
3741 FE(HTTP_QUERY_STATUS_TEXT
),
3742 FE(HTTP_QUERY_RAW_HEADERS
),
3743 FE(HTTP_QUERY_RAW_HEADERS_CRLF
),
3744 FE(HTTP_QUERY_CONNECTION
),
3745 FE(HTTP_QUERY_ACCEPT
),
3746 FE(HTTP_QUERY_ACCEPT_CHARSET
),
3747 FE(HTTP_QUERY_ACCEPT_ENCODING
),
3748 FE(HTTP_QUERY_ACCEPT_LANGUAGE
),
3749 FE(HTTP_QUERY_AUTHORIZATION
),
3750 FE(HTTP_QUERY_CONTENT_ENCODING
),
3751 FE(HTTP_QUERY_FORWARDED
),
3752 FE(HTTP_QUERY_FROM
),
3753 FE(HTTP_QUERY_IF_MODIFIED_SINCE
),
3754 FE(HTTP_QUERY_LOCATION
),
3755 FE(HTTP_QUERY_ORIG_URI
),
3756 FE(HTTP_QUERY_REFERER
),
3757 FE(HTTP_QUERY_RETRY_AFTER
),
3758 FE(HTTP_QUERY_SERVER
),
3759 FE(HTTP_QUERY_TITLE
),
3760 FE(HTTP_QUERY_USER_AGENT
),
3761 FE(HTTP_QUERY_WWW_AUTHENTICATE
),
3762 FE(HTTP_QUERY_PROXY_AUTHENTICATE
),
3763 FE(HTTP_QUERY_ACCEPT_RANGES
),
3764 FE(HTTP_QUERY_SET_COOKIE
),
3765 FE(HTTP_QUERY_COOKIE
),
3766 FE(HTTP_QUERY_REQUEST_METHOD
),
3767 FE(HTTP_QUERY_REFRESH
),
3768 FE(HTTP_QUERY_CONTENT_DISPOSITION
),
3770 FE(HTTP_QUERY_CACHE_CONTROL
),
3771 FE(HTTP_QUERY_CONTENT_BASE
),
3772 FE(HTTP_QUERY_CONTENT_LOCATION
),
3773 FE(HTTP_QUERY_CONTENT_MD5
),
3774 FE(HTTP_QUERY_CONTENT_RANGE
),
3775 FE(HTTP_QUERY_ETAG
),
3776 FE(HTTP_QUERY_HOST
),
3777 FE(HTTP_QUERY_IF_MATCH
),
3778 FE(HTTP_QUERY_IF_NONE_MATCH
),
3779 FE(HTTP_QUERY_IF_RANGE
),
3780 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE
),
3781 FE(HTTP_QUERY_MAX_FORWARDS
),
3782 FE(HTTP_QUERY_PROXY_AUTHORIZATION
),
3783 FE(HTTP_QUERY_RANGE
),
3784 FE(HTTP_QUERY_TRANSFER_ENCODING
),
3785 FE(HTTP_QUERY_UPGRADE
),
3786 FE(HTTP_QUERY_VARY
),
3788 FE(HTTP_QUERY_WARNING
),
3789 FE(HTTP_QUERY_CUSTOM
)
3791 static const wininet_flag_info modifier_flags
[] = {
3792 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS
),
3793 FE(HTTP_QUERY_FLAG_SYSTEMTIME
),
3794 FE(HTTP_QUERY_FLAG_NUMBER
),
3795 FE(HTTP_QUERY_FLAG_COALESCE
)
3798 DWORD info_mod
= dwInfoLevel
& HTTP_QUERY_MODIFIER_FLAGS_MASK
;
3799 DWORD info
= dwInfoLevel
& HTTP_QUERY_HEADER_MASK
;
3802 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest
, dwInfoLevel
, info
);
3803 TRACE(" Attribute:");
3804 for (i
= 0; i
< (sizeof(query_flags
) / sizeof(query_flags
[0])); i
++) {
3805 if (query_flags
[i
].val
== info
) {
3806 TRACE(" %s", query_flags
[i
].name
);
3810 if (i
== (sizeof(query_flags
) / sizeof(query_flags
[0]))) {
3811 TRACE(" Unknown (%08x)", info
);
3814 TRACE(" Modifier:");
3815 for (i
= 0; i
< (sizeof(modifier_flags
) / sizeof(modifier_flags
[0])); i
++) {
3816 if (modifier_flags
[i
].val
& info_mod
) {
3817 TRACE(" %s", modifier_flags
[i
].name
);
3818 info_mod
&= ~ modifier_flags
[i
].val
;
3823 TRACE(" Unknown (%08x)", info_mod
);
3828 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
3829 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
3831 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
3835 if (lpBuffer
== NULL
)
3836 *lpdwBufferLength
= 0;
3837 res
= HTTP_HttpQueryInfoW( request
, dwInfoLevel
,
3838 lpBuffer
, lpdwBufferLength
, lpdwIndex
);
3842 WININET_Release( &request
->hdr
);
3844 TRACE("%u <--\n", res
);
3845 if(res
!= ERROR_SUCCESS
)
3847 return res
== ERROR_SUCCESS
;
3850 /***********************************************************************
3851 * HttpQueryInfoA (WININET.@)
3853 * Queries for information about an HTTP request
3860 BOOL WINAPI
HttpQueryInfoA(HINTERNET hHttpRequest
, DWORD dwInfoLevel
,
3861 LPVOID lpBuffer
, LPDWORD lpdwBufferLength
, LPDWORD lpdwIndex
)
3867 TRACE("%p %x\n", hHttpRequest
, dwInfoLevel
);
3869 if((dwInfoLevel
& HTTP_QUERY_FLAG_NUMBER
) ||
3870 (dwInfoLevel
& HTTP_QUERY_FLAG_SYSTEMTIME
))
3872 return HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, lpBuffer
,
3873 lpdwBufferLength
, lpdwIndex
);
3879 len
= (*lpdwBufferLength
)*sizeof(WCHAR
);
3880 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3882 alloclen
= MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, NULL
, 0 ) * sizeof(WCHAR
);
3888 bufferW
= heap_alloc(alloclen
);
3889 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3890 if ((dwInfoLevel
& HTTP_QUERY_HEADER_MASK
) == HTTP_QUERY_CUSTOM
)
3891 MultiByteToWideChar( CP_ACP
, 0, lpBuffer
, -1, bufferW
, alloclen
/ sizeof(WCHAR
) );
3898 result
= HttpQueryInfoW( hHttpRequest
, dwInfoLevel
, bufferW
,
3902 len
= WideCharToMultiByte( CP_ACP
,0, bufferW
, len
/ sizeof(WCHAR
) + 1,
3903 lpBuffer
, *lpdwBufferLength
, NULL
, NULL
);
3904 *lpdwBufferLength
= len
- 1;
3906 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer
));
3909 /* since the strings being returned from HttpQueryInfoW should be
3910 * only ASCII characters, it is reasonable to assume that all of
3911 * the Unicode characters can be reduced to a single byte */
3912 *lpdwBufferLength
= len
/ sizeof(WCHAR
);
3914 heap_free( bufferW
);
3918 /***********************************************************************
3919 * HTTP_GetRedirectURL (internal)
3921 static LPWSTR
HTTP_GetRedirectURL(http_request_t
*request
, LPCWSTR lpszUrl
)
3923 static WCHAR szHttp
[] = {'h','t','t','p',0};
3924 static WCHAR szHttps
[] = {'h','t','t','p','s',0};
3925 http_session_t
*session
= request
->session
;
3926 URL_COMPONENTSW urlComponents
;
3927 DWORD url_length
= 0;
3929 LPWSTR combined_url
;
3931 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
3932 urlComponents
.lpszScheme
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) ? szHttps
: szHttp
;
3933 urlComponents
.dwSchemeLength
= 0;
3934 urlComponents
.lpszHostName
= session
->hostName
;
3935 urlComponents
.dwHostNameLength
= 0;
3936 urlComponents
.nPort
= session
->hostPort
;
3937 urlComponents
.lpszUserName
= session
->userName
;
3938 urlComponents
.dwUserNameLength
= 0;
3939 urlComponents
.lpszPassword
= NULL
;
3940 urlComponents
.dwPasswordLength
= 0;
3941 urlComponents
.lpszUrlPath
= request
->path
;
3942 urlComponents
.dwUrlPathLength
= 0;
3943 urlComponents
.lpszExtraInfo
= NULL
;
3944 urlComponents
.dwExtraInfoLength
= 0;
3946 if (!InternetCreateUrlW(&urlComponents
, 0, NULL
, &url_length
) &&
3947 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
3950 orig_url
= heap_alloc(url_length
);
3952 /* convert from bytes to characters */
3953 url_length
= url_length
/ sizeof(WCHAR
) - 1;
3954 if (!InternetCreateUrlW(&urlComponents
, 0, orig_url
, &url_length
))
3956 heap_free(orig_url
);
3961 if (!InternetCombineUrlW(orig_url
, lpszUrl
, NULL
, &url_length
, ICU_ENCODE_SPACES_ONLY
) &&
3962 (GetLastError() != ERROR_INSUFFICIENT_BUFFER
))
3964 heap_free(orig_url
);
3967 combined_url
= heap_alloc(url_length
* sizeof(WCHAR
));
3969 if (!InternetCombineUrlW(orig_url
, lpszUrl
, combined_url
, &url_length
, ICU_ENCODE_SPACES_ONLY
))
3971 heap_free(orig_url
);
3972 heap_free(combined_url
);
3975 heap_free(orig_url
);
3976 return combined_url
;
3980 /***********************************************************************
3981 * HTTP_HandleRedirect (internal)
3983 static DWORD
HTTP_HandleRedirect(http_request_t
*request
, LPCWSTR lpszUrl
)
3985 http_session_t
*session
= request
->session
;
3986 WCHAR path
[INTERNET_MAX_PATH_LENGTH
];
3991 /* if it's an absolute path, keep the same session info */
3992 lstrcpynW(path
, lpszUrl
, INTERNET_MAX_URL_LENGTH
);
3996 URL_COMPONENTSW urlComponents
;
3997 WCHAR protocol
[INTERNET_MAX_SCHEME_LENGTH
];
3998 WCHAR hostName
[INTERNET_MAX_HOST_NAME_LENGTH
];
3999 WCHAR userName
[INTERNET_MAX_USER_NAME_LENGTH
];
4000 BOOL custom_port
= FALSE
;
4002 static WCHAR httpW
[] = {'h','t','t','p',0};
4003 static WCHAR httpsW
[] = {'h','t','t','p','s',0};
4009 urlComponents
.dwStructSize
= sizeof(URL_COMPONENTSW
);
4010 urlComponents
.lpszScheme
= protocol
;
4011 urlComponents
.dwSchemeLength
= INTERNET_MAX_SCHEME_LENGTH
;
4012 urlComponents
.lpszHostName
= hostName
;
4013 urlComponents
.dwHostNameLength
= INTERNET_MAX_HOST_NAME_LENGTH
;
4014 urlComponents
.lpszUserName
= userName
;
4015 urlComponents
.dwUserNameLength
= INTERNET_MAX_USER_NAME_LENGTH
;
4016 urlComponents
.lpszPassword
= NULL
;
4017 urlComponents
.dwPasswordLength
= 0;
4018 urlComponents
.lpszUrlPath
= path
;
4019 urlComponents
.dwUrlPathLength
= INTERNET_MAX_PATH_LENGTH
;
4020 urlComponents
.lpszExtraInfo
= NULL
;
4021 urlComponents
.dwExtraInfoLength
= 0;
4022 if(!InternetCrackUrlW(lpszUrl
, strlenW(lpszUrl
), 0, &urlComponents
))
4023 return INTERNET_GetLastError();
4025 if(!strcmpiW(protocol
, httpW
)) {
4026 if(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) {
4027 TRACE("redirect from secure page to non-secure page\n");
4028 /* FIXME: warn about from secure redirect to non-secure page */
4029 request
->hdr
.dwFlags
&= ~INTERNET_FLAG_SECURE
;
4032 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4033 urlComponents
.nPort
= INTERNET_DEFAULT_HTTP_PORT
;
4034 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTP_PORT
)
4036 }else if(!strcmpiW(protocol
, httpsW
)) {
4037 if(!(request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
)) {
4038 TRACE("redirect from non-secure page to secure page\n");
4039 /* FIXME: notify about redirect to secure page */
4040 request
->hdr
.dwFlags
|= INTERNET_FLAG_SECURE
;
4043 if(urlComponents
.nPort
== INTERNET_INVALID_PORT_NUMBER
)
4044 urlComponents
.nPort
= INTERNET_DEFAULT_HTTPS_PORT
;
4045 else if(urlComponents
.nPort
!= INTERNET_DEFAULT_HTTPS_PORT
)
4049 heap_free(session
->hostName
);
4053 static const WCHAR fmt
[] = {'%','s',':','%','u',0};
4054 len
= lstrlenW(hostName
);
4055 len
+= 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4056 session
->hostName
= heap_alloc(len
*sizeof(WCHAR
));
4057 sprintfW(session
->hostName
, fmt
, hostName
, urlComponents
.nPort
);
4060 session
->hostName
= heap_strdupW(hostName
);
4062 HTTP_ProcessHeader(request
, hostW
, session
->hostName
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDREQ_FLAG_REPLACE
| HTTP_ADDHDR_FLAG_REQ
);
4064 heap_free(session
->userName
);
4065 session
->userName
= NULL
;
4067 session
->userName
= heap_strdupW(userName
);
4069 reset_data_stream(request
);
4071 if(strcmpiW(request
->server
->name
, hostName
) || request
->server
->port
!= urlComponents
.nPort
) {
4072 server_t
*new_server
;
4074 new_server
= get_server(hostName
, urlComponents
.nPort
, urlComponents
.nScheme
== INTERNET_SCHEME_HTTPS
, TRUE
);
4075 server_release(request
->server
);
4076 request
->server
= new_server
;
4079 heap_free(request
->path
);
4086 rc
= UrlEscapeW(path
, NULL
, &needed
, URL_ESCAPE_SPACES_ONLY
);
4087 if (rc
!= E_POINTER
)
4088 needed
= strlenW(path
)+1;
4089 request
->path
= heap_alloc(needed
*sizeof(WCHAR
));
4090 rc
= UrlEscapeW(path
, request
->path
, &needed
,
4091 URL_ESCAPE_SPACES_ONLY
);
4094 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path
),rc
);
4095 strcpyW(request
->path
,path
);
4099 /* Remove custom content-type/length headers on redirects. */
4100 index
= HTTP_GetCustomHeaderIndex(request
, szContent_Type
, 0, TRUE
);
4102 HTTP_DeleteCustomHeader(request
, index
);
4103 index
= HTTP_GetCustomHeaderIndex(request
, szContent_Length
, 0, TRUE
);
4105 HTTP_DeleteCustomHeader(request
, index
);
4107 return ERROR_SUCCESS
;
4110 /***********************************************************************
4111 * HTTP_build_req (internal)
4113 * concatenate all the strings in the request together
4115 static LPWSTR
HTTP_build_req( LPCWSTR
*list
, int len
)
4120 for( t
= list
; *t
; t
++ )
4121 len
+= strlenW( *t
);
4124 str
= heap_alloc(len
*sizeof(WCHAR
));
4127 for( t
= list
; *t
; t
++ )
4133 static DWORD
HTTP_SecureProxyConnect(http_request_t
*request
)
4135 server_t
*server
= request
->server
;
4136 LPWSTR requestString
;
4143 static const WCHAR connectW
[] = {'C','O','N','N','E','C','T',0};
4147 requestString
= build_request_header( request
, connectW
, server
->host_port
, g_szHttp1_1
, TRUE
);
4149 len
= WideCharToMultiByte( CP_ACP
, 0, requestString
, -1,
4150 NULL
, 0, NULL
, NULL
);
4151 len
--; /* the nul terminator isn't needed */
4152 ascii_req
= heap_alloc(len
);
4153 WideCharToMultiByte( CP_ACP
, 0, requestString
, -1, ascii_req
, len
, NULL
, NULL
);
4154 heap_free( requestString
);
4156 TRACE("full request -> %s\n", debugstr_an( ascii_req
, len
) );
4158 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
4159 res
= NETCON_send( request
->netconn
, ascii_req
, len
, 0, &cnt
);
4160 heap_free( ascii_req
);
4161 if (res
!= ERROR_SUCCESS
)
4164 if (HTTP_GetResponseHeaders( request
, &responseLen
) || !responseLen
)
4165 return ERROR_HTTP_INVALID_HEADER
;
4167 return ERROR_SUCCESS
;
4170 static void HTTP_InsertCookies(http_request_t
*request
)
4172 DWORD cookie_size
, size
, cnt
= 0;
4176 static const WCHAR cookieW
[] = {'C','o','o','k','i','e',':',' ',0};
4178 host
= HTTP_GetHeader(request
, hostW
);
4182 if(get_cookie(host
->lpszValue
, request
->path
, NULL
, &cookie_size
) != ERROR_SUCCESS
)
4185 size
= sizeof(cookieW
) + cookie_size
* sizeof(WCHAR
) + sizeof(szCrLf
);
4186 if(!(cookies
= heap_alloc(size
)))
4189 cnt
+= sprintfW(cookies
, cookieW
);
4190 get_cookie(host
->lpszValue
, request
->path
, cookies
+cnt
, &cookie_size
);
4191 strcatW(cookies
, szCrLf
);
4193 HTTP_HttpAddRequestHeadersW(request
, cookies
, strlenW(cookies
), HTTP_ADDREQ_FLAG_REPLACE
);
4198 static WORD
HTTP_ParseWkday(LPCWSTR day
)
4200 static const WCHAR days
[7][4] = {{ 's','u','n',0 },
4208 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4209 if (!strcmpiW(day
, days
[i
]))
4216 static WORD
HTTP_ParseMonth(LPCWSTR month
)
4218 static const WCHAR jan
[] = { 'j','a','n',0 };
4219 static const WCHAR feb
[] = { 'f','e','b',0 };
4220 static const WCHAR mar
[] = { 'm','a','r',0 };
4221 static const WCHAR apr
[] = { 'a','p','r',0 };
4222 static const WCHAR may
[] = { 'm','a','y',0 };
4223 static const WCHAR jun
[] = { 'j','u','n',0 };
4224 static const WCHAR jul
[] = { 'j','u','l',0 };
4225 static const WCHAR aug
[] = { 'a','u','g',0 };
4226 static const WCHAR sep
[] = { 's','e','p',0 };
4227 static const WCHAR oct
[] = { 'o','c','t',0 };
4228 static const WCHAR nov
[] = { 'n','o','v',0 };
4229 static const WCHAR dec
[] = { 'd','e','c',0 };
4231 if (!strcmpiW(month
, jan
)) return 1;
4232 if (!strcmpiW(month
, feb
)) return 2;
4233 if (!strcmpiW(month
, mar
)) return 3;
4234 if (!strcmpiW(month
, apr
)) return 4;
4235 if (!strcmpiW(month
, may
)) return 5;
4236 if (!strcmpiW(month
, jun
)) return 6;
4237 if (!strcmpiW(month
, jul
)) return 7;
4238 if (!strcmpiW(month
, aug
)) return 8;
4239 if (!strcmpiW(month
, sep
)) return 9;
4240 if (!strcmpiW(month
, oct
)) return 10;
4241 if (!strcmpiW(month
, nov
)) return 11;
4242 if (!strcmpiW(month
, dec
)) return 12;
4247 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4248 * optionally preceded by whitespace.
4249 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4250 * st, and sets *str to the first character after the time format.
4252 static BOOL
HTTP_ParseTime(SYSTEMTIME
*st
, LPCWSTR
*str
)
4258 while (isspaceW(*ptr
))
4261 num
= strtoulW(ptr
, &nextPtr
, 10);
4262 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4264 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4269 ERR("unexpected hour in time format %s\n", debugstr_w(ptr
));
4273 st
->wHour
= (WORD
)num
;
4274 num
= strtoulW(ptr
, &nextPtr
, 10);
4275 if (!nextPtr
|| nextPtr
<= ptr
|| *nextPtr
!= ':')
4277 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4282 ERR("unexpected minute in time format %s\n", debugstr_w(ptr
));
4286 st
->wMinute
= (WORD
)num
;
4287 num
= strtoulW(ptr
, &nextPtr
, 10);
4288 if (!nextPtr
|| nextPtr
<= ptr
)
4290 ERR("unexpected time format %s\n", debugstr_w(ptr
));
4295 ERR("unexpected second in time format %s\n", debugstr_w(ptr
));
4300 st
->wSecond
= (WORD
)num
;
4304 static BOOL
HTTP_ParseDateAsAsctime(LPCWSTR value
, FILETIME
*ft
)
4306 static const WCHAR gmt
[]= { 'G','M','T',0 };
4307 WCHAR day
[4], *dayPtr
, month
[4], *monthPtr
, *nextPtr
;
4309 SYSTEMTIME st
= { 0 };
4312 for (ptr
= value
, dayPtr
= day
; *ptr
&& !isspaceW(*ptr
) &&
4313 dayPtr
- day
< sizeof(day
) / sizeof(day
[0]) - 1; ptr
++, dayPtr
++)
4316 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4317 if (st
.wDayOfWeek
>= 7)
4319 ERR("unexpected weekday %s\n", debugstr_w(day
));
4323 while (isspaceW(*ptr
))
4326 for (monthPtr
= month
; !isspace(*ptr
) &&
4327 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4331 st
.wMonth
= HTTP_ParseMonth(month
);
4332 if (!st
.wMonth
|| st
.wMonth
> 12)
4334 ERR("unexpected month %s\n", debugstr_w(month
));
4338 while (isspaceW(*ptr
))
4341 num
= strtoulW(ptr
, &nextPtr
, 10);
4342 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4344 ERR("unexpected day %s\n", debugstr_w(ptr
));
4348 st
.wDay
= (WORD
)num
;
4350 while (isspaceW(*ptr
))
4353 if (!HTTP_ParseTime(&st
, &ptr
))
4356 while (isspaceW(*ptr
))
4359 num
= strtoulW(ptr
, &nextPtr
, 10);
4360 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4362 ERR("unexpected year %s\n", debugstr_w(ptr
));
4366 st
.wYear
= (WORD
)num
;
4368 while (isspaceW(*ptr
))
4371 /* asctime() doesn't report a timezone, but some web servers do, so accept
4372 * with or without GMT.
4374 if (*ptr
&& strcmpW(ptr
, gmt
))
4376 ERR("unexpected timezone %s\n", debugstr_w(ptr
));
4379 return SystemTimeToFileTime(&st
, ft
);
4382 static BOOL
HTTP_ParseRfc1123Date(LPCWSTR value
, FILETIME
*ft
)
4384 static const WCHAR gmt
[]= { 'G','M','T',0 };
4385 WCHAR
*nextPtr
, day
[4], month
[4], *monthPtr
;
4388 SYSTEMTIME st
= { 0 };
4390 ptr
= strchrW(value
, ',');
4393 if (ptr
- value
!= 3)
4395 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4398 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4400 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4401 if (st
.wDayOfWeek
> 6)
4403 WARN("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4408 while (isspaceW(*ptr
))
4411 num
= strtoulW(ptr
, &nextPtr
, 10);
4412 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4414 WARN("unexpected day %s\n", debugstr_w(value
));
4418 st
.wDay
= (WORD
)num
;
4420 while (isspaceW(*ptr
))
4423 for (monthPtr
= month
; !isspace(*ptr
) &&
4424 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 1;
4428 st
.wMonth
= HTTP_ParseMonth(month
);
4429 if (!st
.wMonth
|| st
.wMonth
> 12)
4431 WARN("unexpected month %s\n", debugstr_w(month
));
4435 while (isspaceW(*ptr
))
4438 num
= strtoulW(ptr
, &nextPtr
, 10);
4439 if (!nextPtr
|| nextPtr
<= ptr
|| num
< 1601 || num
> 30827)
4441 ERR("unexpected year %s\n", debugstr_w(value
));
4445 st
.wYear
= (WORD
)num
;
4447 if (!HTTP_ParseTime(&st
, &ptr
))
4450 while (isspaceW(*ptr
))
4453 if (strcmpW(ptr
, gmt
))
4455 ERR("unexpected time zone %s\n", debugstr_w(ptr
));
4458 return SystemTimeToFileTime(&st
, ft
);
4461 static WORD
HTTP_ParseWeekday(LPCWSTR day
)
4463 static const WCHAR days
[7][10] = {{ 's','u','n','d','a','y',0 },
4464 { 'm','o','n','d','a','y',0 },
4465 { 't','u','e','s','d','a','y',0 },
4466 { 'w','e','d','n','e','s','d','a','y',0 },
4467 { 't','h','u','r','s','d','a','y',0 },
4468 { 'f','r','i','d','a','y',0 },
4469 { 's','a','t','u','r','d','a','y',0 }};
4471 for (i
= 0; i
< sizeof(days
)/sizeof(*days
); i
++)
4472 if (!strcmpiW(day
, days
[i
]))
4479 static BOOL
HTTP_ParseRfc850Date(LPCWSTR value
, FILETIME
*ft
)
4481 static const WCHAR gmt
[]= { 'G','M','T',0 };
4482 WCHAR
*nextPtr
, day
[10], month
[4], *monthPtr
;
4485 SYSTEMTIME st
= { 0 };
4487 ptr
= strchrW(value
, ',');
4490 if (ptr
- value
== 3)
4492 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4494 st
.wDayOfWeek
= HTTP_ParseWkday(day
);
4495 if (st
.wDayOfWeek
> 6)
4497 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4501 else if (ptr
- value
< sizeof(day
) / sizeof(day
[0]))
4503 memcpy(day
, value
, (ptr
- value
) * sizeof(WCHAR
));
4504 day
[ptr
- value
+ 1] = 0;
4505 st
.wDayOfWeek
= HTTP_ParseWeekday(day
);
4506 if (st
.wDayOfWeek
> 6)
4508 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4514 ERR("unexpected weekday %s\n", debugstr_wn(value
, ptr
- value
));
4519 while (isspaceW(*ptr
))
4522 num
= strtoulW(ptr
, &nextPtr
, 10);
4523 if (!nextPtr
|| nextPtr
<= ptr
|| !num
|| num
> 31)
4525 ERR("unexpected day %s\n", debugstr_w(value
));
4529 st
.wDay
= (WORD
)num
;
4533 ERR("unexpected month format %s\n", debugstr_w(ptr
));
4538 for (monthPtr
= month
; *ptr
!= '-' &&
4539 monthPtr
- month
< sizeof(month
) / sizeof(month
[0]) - 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 /* Look for a Cache-Control header with a max-age directive, as it takes
4615 * precedence over the Expires header.
4617 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szCache_Control
, 0, FALSE
);
4618 if (headerIndex
!= -1)
4620 LPHTTPHEADERW ccHeader
= &request
->custHeaders
[headerIndex
];
4623 for (ptr
= ccHeader
->lpszValue
; ptr
&& *ptr
; )
4625 LPWSTR comma
= strchrW(ptr
, ','), end
, equal
;
4630 end
= ptr
+ strlenW(ptr
);
4631 for (equal
= end
- 1; equal
> ptr
&& *equal
!= '='; equal
--)
4635 static const WCHAR max_age
[] = {
4636 'm','a','x','-','a','g','e',0 };
4638 if (!strncmpiW(ptr
, max_age
, equal
- ptr
- 1))
4643 age
= strtoulW(equal
+ 1, &nextPtr
, 10);
4644 if (nextPtr
> equal
+ 1)
4648 NtQuerySystemTime( &ft
);
4649 /* Age is in seconds, FILETIME resolution is in
4650 * 100 nanosecond intervals.
4652 ft
.QuadPart
+= age
* (ULONGLONG
)1000000;
4653 request
->expires
.dwLowDateTime
= ft
.u
.LowPart
;
4654 request
->expires
.dwHighDateTime
= ft
.u
.HighPart
;
4655 expirationFound
= TRUE
;
4662 while (isspaceW(*ptr
))
4669 if (!expirationFound
)
4671 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szExpires
, 0, FALSE
);
4672 if (headerIndex
!= -1)
4674 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4677 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4679 expirationFound
= TRUE
;
4680 request
->expires
= ft
;
4684 if (!expirationFound
)
4688 /* With no known age, default to 10 minutes until expiration. */
4689 NtQuerySystemTime( &t
);
4690 t
.QuadPart
+= 10 * 60 * (ULONGLONG
)10000000;
4691 request
->expires
.dwLowDateTime
= t
.u
.LowPart
;
4692 request
->expires
.dwHighDateTime
= t
.u
.HighPart
;
4696 static void HTTP_ProcessLastModified(http_request_t
*request
)
4700 headerIndex
= HTTP_GetCustomHeaderIndex(request
, szLast_Modified
, 0, FALSE
);
4701 if (headerIndex
!= -1)
4703 LPHTTPHEADERW expiresHeader
= &request
->custHeaders
[headerIndex
];
4706 if (HTTP_ParseDate(expiresHeader
->lpszValue
, &ft
))
4707 request
->last_modified
= ft
;
4711 static void http_process_keep_alive(http_request_t
*req
)
4715 if ((index
= HTTP_GetCustomHeaderIndex(req
, szConnection
, 0, FALSE
)) != -1)
4716 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4717 else if ((index
= HTTP_GetCustomHeaderIndex(req
, szProxy_Connection
, 0, FALSE
)) != -1)
4718 req
->netconn
->keep_alive
= !strcmpiW(req
->custHeaders
[index
].lpszValue
, szKeepAlive
);
4720 req
->netconn
->keep_alive
= !strcmpiW(req
->version
, g_szHttp1_1
);
4723 static DWORD
open_http_connection(http_request_t
*request
, BOOL
*reusing
)
4725 const BOOL is_https
= (request
->hdr
.dwFlags
& INTERNET_FLAG_SECURE
) != 0;
4726 netconn_t
*netconn
= NULL
;
4729 assert(!request
->netconn
);
4730 reset_data_stream(request
);
4732 res
= HTTP_ResolveName(request
);
4733 if(res
!= ERROR_SUCCESS
)
4736 EnterCriticalSection(&connection_pool_cs
);
4738 while(!list_empty(&request
->server
->conn_pool
)) {
4739 netconn
= LIST_ENTRY(list_head(&request
->server
->conn_pool
), netconn_t
, pool_entry
);
4740 list_remove(&netconn
->pool_entry
);
4742 if(NETCON_is_alive(netconn
))
4745 TRACE("connection %p closed during idle\n", netconn
);
4746 free_netconn(netconn
);
4750 LeaveCriticalSection(&connection_pool_cs
);
4753 TRACE("<-- reusing %p netconn\n", netconn
);
4754 request
->netconn
= netconn
;
4756 return ERROR_SUCCESS
;
4759 TRACE("connecting to %s, proxy %s\n", debugstr_w(request
->server
->name
),
4760 request
->proxy
? debugstr_w(request
->proxy
->name
) : "(null)");
4762 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4763 INTERNET_STATUS_CONNECTING_TO_SERVER
,
4764 request
->server
->addr_str
,
4765 strlen(request
->server
->addr_str
)+1);
4767 res
= create_netconn(is_https
, request
->proxy
? request
->proxy
: request
->server
, request
->security_flags
,
4768 (request
->hdr
.ErrorMask
& INTERNET_ERROR_MASK_COMBINED_SEC_CERT
) != 0,
4769 request
->connect_timeout
, &netconn
);
4770 if(res
!= ERROR_SUCCESS
) {
4771 ERR("create_netconn failed: %u\n", res
);
4775 request
->netconn
= netconn
;
4777 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4778 INTERNET_STATUS_CONNECTED_TO_SERVER
,
4779 request
->server
->addr_str
, strlen(request
->server
->addr_str
)+1);
4782 /* Note: we differ from Microsoft's WinINet here. they seem to have
4783 * a bug that causes no status callbacks to be sent when starting
4784 * a tunnel to a proxy server using the CONNECT verb. i believe our
4785 * behaviour to be more correct and to not cause any incompatibilities
4786 * because using a secure connection through a proxy server is a rare
4787 * case that would be hard for anyone to depend on */
4789 res
= HTTP_SecureProxyConnect(request
);
4790 if(res
== ERROR_SUCCESS
)
4791 res
= NETCON_secure_connect(request
->netconn
, request
->server
);
4794 if(res
!= ERROR_SUCCESS
) {
4795 http_release_netconn(request
, FALSE
);
4800 TRACE("Created connection to %s: %p\n", debugstr_w(request
->server
->name
), netconn
);
4801 return ERROR_SUCCESS
;
4804 /***********************************************************************
4805 * HTTP_HttpSendRequestW (internal)
4807 * Sends the specified request to the HTTP server
4810 * ERROR_SUCCESS on success
4811 * win32 error code on failure
4814 static DWORD
HTTP_HttpSendRequestW(http_request_t
*request
, LPCWSTR lpszHeaders
,
4815 DWORD dwHeaderLength
, LPVOID lpOptional
, DWORD dwOptionalLength
,
4816 DWORD dwContentLength
, BOOL bEndRequest
)
4819 BOOL redirected
= FALSE
;
4820 LPWSTR requestString
= NULL
;
4823 static const WCHAR szContentLength
[] =
4824 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4825 WCHAR contentLengthStr
[sizeof szContentLength
/2 /* includes \r\n */ + 20 /* int */ ];
4828 TRACE("--> %p\n", request
);
4830 assert(request
->hdr
.htype
== WH_HHTTPREQ
);
4832 /* if the verb is NULL default to GET */
4834 request
->verb
= heap_strdupW(szGET
);
4836 if (dwContentLength
|| strcmpW(request
->verb
, szGET
))
4838 sprintfW(contentLengthStr
, szContentLength
, dwContentLength
);
4839 HTTP_HttpAddRequestHeadersW(request
, contentLengthStr
, -1L, HTTP_ADDREQ_FLAG_REPLACE
);
4840 request
->bytesToWrite
= dwContentLength
;
4842 if (request
->session
->appInfo
->agent
)
4844 WCHAR
*agent_header
;
4845 static const WCHAR user_agent
[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4848 len
= strlenW(request
->session
->appInfo
->agent
) + strlenW(user_agent
);
4849 agent_header
= heap_alloc(len
* sizeof(WCHAR
));
4850 sprintfW(agent_header
, user_agent
, request
->session
->appInfo
->agent
);
4852 HTTP_HttpAddRequestHeadersW(request
, agent_header
, strlenW(agent_header
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4853 heap_free(agent_header
);
4855 if (request
->hdr
.dwFlags
& INTERNET_FLAG_PRAGMA_NOCACHE
)
4857 static const WCHAR pragma_nocache
[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4858 HTTP_HttpAddRequestHeadersW(request
, pragma_nocache
, strlenW(pragma_nocache
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4860 if ((request
->hdr
.dwFlags
& INTERNET_FLAG_NO_CACHE_WRITE
) && strcmpW(request
->verb
, szGET
))
4862 static const WCHAR cache_control
[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4863 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4864 HTTP_HttpAddRequestHeadersW(request
, cache_control
, strlenW(cache_control
), HTTP_ADDREQ_FLAG_ADD_IF_NEW
);
4867 /* add the headers the caller supplied */
4868 if( lpszHeaders
&& dwHeaderLength
)
4869 HTTP_HttpAddRequestHeadersW(request
, lpszHeaders
, dwHeaderLength
, HTTP_ADDREQ_FLAG_ADD
| HTTP_ADDHDR_FLAG_REPLACE
);
4874 BOOL reusing_connection
;
4878 reusing_connection
= request
->netconn
!= NULL
;
4881 request
->contentLength
= ~0u;
4882 request
->bytesToWrite
= 0;
4885 if (TRACE_ON(wininet
))
4887 LPHTTPHEADERW Host
= HTTP_GetHeader(request
, hostW
);
4888 TRACE("Going to url %s %s\n", debugstr_w(Host
->lpszValue
), debugstr_w(request
->path
));
4891 HTTP_FixURL(request
);
4892 if (request
->hdr
.dwFlags
& INTERNET_FLAG_KEEP_CONNECTION
)
4894 HTTP_ProcessHeader(request
, szConnection
, szKeepAlive
, HTTP_ADDHDR_FLAG_REQ
| HTTP_ADDHDR_FLAG_REPLACE
);
4896 HTTP_InsertAuthorization(request
, request
->authInfo
, szAuthorization
);
4897 HTTP_InsertAuthorization(request
, request
->proxyAuthInfo
, szProxy_Authorization
);
4899 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_COOKIES
))
4900 HTTP_InsertCookies(request
);
4904 WCHAR
*url
= build_proxy_path_url(request
);
4905 requestString
= build_request_header(request
, request
->verb
, url
, request
->version
, TRUE
);
4909 requestString
= build_request_header(request
, request
->verb
, request
->path
, request
->version
, TRUE
);
4912 TRACE("Request header -> %s\n", debugstr_w(requestString
) );
4914 if (!reusing_connection
&& (res
= open_http_connection(request
, &reusing_connection
)) != ERROR_SUCCESS
)
4917 /* send the request as ASCII, tack on the optional data */
4918 if (!lpOptional
|| redirected
)
4919 dwOptionalLength
= 0;
4920 len
= WideCharToMultiByte( CP_ACP
, 0, requestString
, -1,
4921 NULL
, 0, NULL
, NULL
);
4922 ascii_req
= heap_alloc(len
+ dwOptionalLength
);
4923 WideCharToMultiByte( CP_ACP
, 0, requestString
, -1,
4924 ascii_req
, len
, NULL
, NULL
);
4926 memcpy( &ascii_req
[len
-1], lpOptional
, dwOptionalLength
);
4927 len
= (len
+ dwOptionalLength
- 1);
4929 TRACE("full request -> %s\n", debugstr_a(ascii_req
) );
4931 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4932 INTERNET_STATUS_SENDING_REQUEST
, NULL
, 0);
4934 NETCON_set_timeout( request
->netconn
, TRUE
, request
->send_timeout
);
4935 res
= NETCON_send(request
->netconn
, ascii_req
, len
, 0, &cnt
);
4936 heap_free( ascii_req
);
4937 if(res
!= ERROR_SUCCESS
) {
4938 TRACE("send failed: %u\n", res
);
4939 if(!reusing_connection
)
4941 http_release_netconn(request
, FALSE
);
4946 request
->bytesWritten
= dwOptionalLength
;
4948 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4949 INTERNET_STATUS_REQUEST_SENT
,
4950 &len
, sizeof(DWORD
));
4956 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4957 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
4959 if (HTTP_GetResponseHeaders(request
, &responseLen
))
4961 http_release_netconn(request
, FALSE
);
4962 res
= ERROR_INTERNET_CONNECTION_ABORTED
;
4965 /* FIXME: We should know that connection is closed before sending
4966 * headers. Otherwise wrong callbacks are executed */
4967 if(!responseLen
&& reusing_connection
) {
4968 TRACE("Connection closed by server, reconnecting\n");
4969 http_release_netconn(request
, FALSE
);
4974 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
4975 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
,
4978 http_process_keep_alive(request
);
4979 HTTP_ProcessCookies(request
);
4980 HTTP_ProcessExpires(request
);
4981 HTTP_ProcessLastModified(request
);
4983 res
= set_content_length(request
);
4984 if(res
!= ERROR_SUCCESS
)
4986 if(!request
->contentLength
)
4987 http_release_netconn(request
, TRUE
);
4989 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
) && responseLen
)
4991 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
4992 dwBufferSize
=sizeof(szNewLocation
);
4993 switch(request
->status_code
) {
4994 case HTTP_STATUS_REDIRECT
:
4995 case HTTP_STATUS_MOVED
:
4996 case HTTP_STATUS_REDIRECT_KEEP_VERB
:
4997 case HTTP_STATUS_REDIRECT_METHOD
:
4998 if(HTTP_HttpQueryInfoW(request
,HTTP_QUERY_LOCATION
,szNewLocation
,&dwBufferSize
,NULL
) != ERROR_SUCCESS
)
5001 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5002 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5004 heap_free(request
->verb
);
5005 request
->verb
= heap_strdupW(szGET
);
5007 http_release_netconn(request
, drain_content(request
, FALSE
));
5008 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5010 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5011 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5012 res
= HTTP_HandleRedirect(request
, new_url
);
5013 if (res
== ERROR_SUCCESS
)
5015 heap_free(requestString
);
5018 heap_free( new_url
);
5023 if (!(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTH
) && res
== ERROR_SUCCESS
)
5025 WCHAR szAuthValue
[2048];
5027 if (request
->status_code
== HTTP_STATUS_DENIED
)
5029 LPHTTPHEADERW Host
= HTTP_GetHeader(request
, hostW
);
5031 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_WWW_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5033 if (HTTP_DoAuthorization(request
, szAuthValue
,
5035 request
->session
->userName
,
5036 request
->session
->password
,
5039 heap_free(requestString
);
5040 if(!drain_content(request
, TRUE
)) {
5041 FIXME("Could not drain content\n");
5042 http_release_netconn(request
, FALSE
);
5050 TRACE("Cleaning wrong authorization data\n");
5051 destroy_authinfo(request
->authInfo
);
5052 request
->authInfo
= NULL
;
5055 if (request
->status_code
== HTTP_STATUS_PROXY_AUTH_REQ
)
5058 while (HTTP_HttpQueryInfoW(request
,HTTP_QUERY_PROXY_AUTHENTICATE
,szAuthValue
,&dwBufferSize
,&dwIndex
) == ERROR_SUCCESS
)
5060 if (HTTP_DoAuthorization(request
, szAuthValue
,
5061 &request
->proxyAuthInfo
,
5062 request
->session
->appInfo
->proxyUsername
,
5063 request
->session
->appInfo
->proxyPassword
,
5066 heap_free(requestString
);
5067 if(!drain_content(request
, TRUE
)) {
5068 FIXME("Could not drain content\n");
5069 http_release_netconn(request
, FALSE
);
5077 TRACE("Cleaning wrong proxy authorization data\n");
5078 destroy_authinfo(request
->proxyAuthInfo
);
5079 request
->proxyAuthInfo
= NULL
;
5085 res
= ERROR_SUCCESS
;
5090 heap_free(requestString
);
5092 /* TODO: send notification for P3P header */
5094 if(res
== ERROR_SUCCESS
)
5095 create_cache_entry(request
);
5097 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5099 if (res
== ERROR_SUCCESS
) {
5100 if(bEndRequest
&& request
->contentLength
&& request
->bytesWritten
== request
->bytesToWrite
)
5101 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5103 send_request_complete(request
,
5104 request
->session
->hdr
.dwInternalFlags
& INET_OPENURL
? (DWORD_PTR
)request
->hdr
.hInternet
: 1, 0);
5106 send_request_complete(request
, 0, res
);
5122 } send_request_task_t
;
5124 /***********************************************************************
5126 * Helper functions for the HttpSendRequest(Ex) functions
5129 static void AsyncHttpSendRequestProc(task_header_t
*hdr
)
5131 send_request_task_t
*task
= (send_request_task_t
*)hdr
;
5132 http_request_t
*request
= (http_request_t
*)task
->hdr
.hdr
;
5134 TRACE("%p\n", request
);
5136 HTTP_HttpSendRequestW(request
, task
->headers
, task
->headers_len
, task
->optional
,
5137 task
->optional_len
, task
->content_len
, task
->end_request
);
5139 heap_free(task
->headers
);
5143 static DWORD
HTTP_HttpEndRequestW(http_request_t
*request
, DWORD dwFlags
, DWORD_PTR dwContext
)
5147 DWORD res
= ERROR_SUCCESS
;
5149 if(!request
->netconn
) {
5150 WARN("Not connected\n");
5151 send_request_complete(request
, 0, ERROR_INTERNET_OPERATION_CANCELLED
);
5152 return ERROR_INTERNET_OPERATION_CANCELLED
;
5155 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5156 INTERNET_STATUS_RECEIVING_RESPONSE
, NULL
, 0);
5158 if (HTTP_GetResponseHeaders(request
, &responseLen
) || !responseLen
)
5159 res
= ERROR_HTTP_HEADER_NOT_FOUND
;
5161 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
,
5162 INTERNET_STATUS_RESPONSE_RECEIVED
, &responseLen
, sizeof(DWORD
));
5164 /* process cookies here. Is this right? */
5165 http_process_keep_alive(request
);
5166 HTTP_ProcessCookies(request
);
5167 HTTP_ProcessExpires(request
);
5168 HTTP_ProcessLastModified(request
);
5170 if ((res
= set_content_length(request
)) == ERROR_SUCCESS
) {
5171 if(!request
->contentLength
)
5172 http_release_netconn(request
, TRUE
);
5175 if (res
== ERROR_SUCCESS
&& !(request
->hdr
.dwFlags
& INTERNET_FLAG_NO_AUTO_REDIRECT
))
5177 switch(request
->status_code
) {
5178 case HTTP_STATUS_REDIRECT
:
5179 case HTTP_STATUS_MOVED
:
5180 case HTTP_STATUS_REDIRECT_METHOD
:
5181 case HTTP_STATUS_REDIRECT_KEEP_VERB
: {
5182 WCHAR
*new_url
, szNewLocation
[INTERNET_MAX_URL_LENGTH
];
5183 dwBufferSize
=sizeof(szNewLocation
);
5184 if (HTTP_HttpQueryInfoW(request
, HTTP_QUERY_LOCATION
, szNewLocation
, &dwBufferSize
, NULL
) != ERROR_SUCCESS
)
5187 if (strcmpW(request
->verb
, szGET
) && strcmpW(request
->verb
, szHEAD
) &&
5188 request
->status_code
!= HTTP_STATUS_REDIRECT_KEEP_VERB
)
5190 heap_free(request
->verb
);
5191 request
->verb
= heap_strdupW(szGET
);
5193 http_release_netconn(request
, drain_content(request
, FALSE
));
5194 if ((new_url
= HTTP_GetRedirectURL( request
, szNewLocation
)))
5196 INTERNET_SendCallback(&request
->hdr
, request
->hdr
.dwContext
, INTERNET_STATUS_REDIRECT
,
5197 new_url
, (strlenW(new_url
) + 1) * sizeof(WCHAR
));
5198 res
= HTTP_HandleRedirect(request
, new_url
);
5199 if (res
== ERROR_SUCCESS
)
5200 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, TRUE
);
5201 heap_free( new_url
);
5207 if(res
== ERROR_SUCCESS
)
5208 create_cache_entry(request
);
5210 if (res
== ERROR_SUCCESS
&& request
->contentLength
)
5211 HTTP_ReceiveRequestData(request
, TRUE
, NULL
);
5213 send_request_complete(request
, res
== ERROR_SUCCESS
, res
);
5218 /***********************************************************************
5219 * HttpEndRequestA (WININET.@)
5221 * Ends an HTTP request that was started by HttpSendRequestEx
5224 * TRUE if successful
5228 BOOL WINAPI
HttpEndRequestA(HINTERNET hRequest
,
5229 LPINTERNET_BUFFERSA lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5231 TRACE("(%p, %p, %08x, %08lx)\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5235 SetLastError(ERROR_INVALID_PARAMETER
);
5239 return HttpEndRequestW(hRequest
, NULL
, dwFlags
, dwContext
);
5246 } end_request_task_t
;
5248 static void AsyncHttpEndRequestProc(task_header_t
*hdr
)
5250 end_request_task_t
*task
= (end_request_task_t
*)hdr
;
5251 http_request_t
*req
= (http_request_t
*)task
->hdr
.hdr
;
5255 HTTP_HttpEndRequestW(req
, task
->flags
, task
->context
);
5258 /***********************************************************************
5259 * HttpEndRequestW (WININET.@)
5261 * Ends an HTTP request that was started by HttpSendRequestEx
5264 * TRUE if successful
5268 BOOL WINAPI
HttpEndRequestW(HINTERNET hRequest
,
5269 LPINTERNET_BUFFERSW lpBuffersOut
, DWORD dwFlags
, DWORD_PTR dwContext
)
5271 http_request_t
*request
;
5274 TRACE("%p %p %x %lx -->\n", hRequest
, lpBuffersOut
, dwFlags
, dwContext
);
5278 SetLastError(ERROR_INVALID_PARAMETER
);
5282 request
= (http_request_t
*) get_handle_object( hRequest
);
5284 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5286 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE
);
5288 WININET_Release( &request
->hdr
);
5291 request
->hdr
.dwFlags
|= dwFlags
;
5293 if (request
->session
->appInfo
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5295 end_request_task_t
*task
;
5297 task
= alloc_async_task(&request
->hdr
, AsyncHttpEndRequestProc
, sizeof(*task
));
5298 task
->flags
= dwFlags
;
5299 task
->context
= dwContext
;
5301 INTERNET_AsyncCall(&task
->hdr
);
5302 res
= ERROR_IO_PENDING
;
5305 res
= HTTP_HttpEndRequestW(request
, dwFlags
, dwContext
);
5307 WININET_Release( &request
->hdr
);
5308 TRACE("%u <--\n", res
);
5309 if(res
!= ERROR_SUCCESS
)
5311 return res
== ERROR_SUCCESS
;
5314 /***********************************************************************
5315 * HttpSendRequestExA (WININET.@)
5317 * Sends the specified request to the HTTP server and allows chunked
5322 * Failure: FALSE, call GetLastError() for more information.
5324 BOOL WINAPI
HttpSendRequestExA(HINTERNET hRequest
,
5325 LPINTERNET_BUFFERSA lpBuffersIn
,
5326 LPINTERNET_BUFFERSA lpBuffersOut
,
5327 DWORD dwFlags
, DWORD_PTR dwContext
)
5329 INTERNET_BUFFERSW BuffersInW
;
5332 LPWSTR header
= NULL
;
5334 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5335 lpBuffersOut
, dwFlags
, dwContext
);
5339 BuffersInW
.dwStructSize
= sizeof(LPINTERNET_BUFFERSW
);
5340 if (lpBuffersIn
->lpcszHeader
)
5342 headerlen
= MultiByteToWideChar(CP_ACP
,0,lpBuffersIn
->lpcszHeader
,
5343 lpBuffersIn
->dwHeadersLength
,0,0);
5344 header
= heap_alloc(headerlen
*sizeof(WCHAR
));
5345 if (!(BuffersInW
.lpcszHeader
= header
))
5347 SetLastError(ERROR_OUTOFMEMORY
);
5350 BuffersInW
.dwHeadersLength
= MultiByteToWideChar(CP_ACP
, 0,
5351 lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5355 BuffersInW
.lpcszHeader
= NULL
;
5356 BuffersInW
.dwHeadersTotal
= lpBuffersIn
->dwHeadersTotal
;
5357 BuffersInW
.lpvBuffer
= lpBuffersIn
->lpvBuffer
;
5358 BuffersInW
.dwBufferLength
= lpBuffersIn
->dwBufferLength
;
5359 BuffersInW
.dwBufferTotal
= lpBuffersIn
->dwBufferTotal
;
5360 BuffersInW
.Next
= NULL
;
5363 rc
= HttpSendRequestExW(hRequest
, lpBuffersIn
? &BuffersInW
: NULL
, NULL
, dwFlags
, dwContext
);
5369 /***********************************************************************
5370 * HttpSendRequestExW (WININET.@)
5372 * Sends the specified request to the HTTP server and allows chunked
5377 * Failure: FALSE, call GetLastError() for more information.
5379 BOOL WINAPI
HttpSendRequestExW(HINTERNET hRequest
,
5380 LPINTERNET_BUFFERSW lpBuffersIn
,
5381 LPINTERNET_BUFFERSW lpBuffersOut
,
5382 DWORD dwFlags
, DWORD_PTR dwContext
)
5384 http_request_t
*request
;
5385 http_session_t
*session
;
5389 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest
, lpBuffersIn
,
5390 lpBuffersOut
, dwFlags
, dwContext
);
5392 request
= (http_request_t
*) get_handle_object( hRequest
);
5394 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5396 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5400 session
= request
->session
;
5401 assert(session
->hdr
.htype
== WH_HHTTPSESSION
);
5402 hIC
= session
->appInfo
;
5403 assert(hIC
->hdr
.htype
== WH_HINIT
);
5405 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5407 send_request_task_t
*task
;
5409 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5414 if (lpBuffersIn
->lpcszHeader
)
5416 if (lpBuffersIn
->dwHeadersLength
== ~0u)
5417 size
= (strlenW( lpBuffersIn
->lpcszHeader
) + 1) * sizeof(WCHAR
);
5419 size
= lpBuffersIn
->dwHeadersLength
* sizeof(WCHAR
);
5421 task
->headers
= heap_alloc(size
);
5422 memcpy(task
->headers
, lpBuffersIn
->lpcszHeader
, size
);
5424 else task
->headers
= NULL
;
5426 task
->headers_len
= size
/ sizeof(WCHAR
);
5427 task
->optional
= lpBuffersIn
->lpvBuffer
;
5428 task
->optional_len
= lpBuffersIn
->dwBufferLength
;
5429 task
->content_len
= lpBuffersIn
->dwBufferTotal
;
5433 task
->headers
= NULL
;
5434 task
->headers_len
= 0;
5435 task
->optional
= NULL
;
5436 task
->optional_len
= 0;
5437 task
->content_len
= 0;
5440 task
->end_request
= FALSE
;
5442 INTERNET_AsyncCall(&task
->hdr
);
5443 res
= ERROR_IO_PENDING
;
5448 res
= HTTP_HttpSendRequestW(request
, lpBuffersIn
->lpcszHeader
, lpBuffersIn
->dwHeadersLength
,
5449 lpBuffersIn
->lpvBuffer
, lpBuffersIn
->dwBufferLength
,
5450 lpBuffersIn
->dwBufferTotal
, FALSE
);
5452 res
= HTTP_HttpSendRequestW(request
, NULL
, 0, NULL
, 0, 0, FALSE
);
5457 WININET_Release( &request
->hdr
);
5461 return res
== ERROR_SUCCESS
;
5464 /***********************************************************************
5465 * HttpSendRequestW (WININET.@)
5467 * Sends the specified request to the HTTP server
5474 BOOL WINAPI
HttpSendRequestW(HINTERNET hHttpRequest
, LPCWSTR lpszHeaders
,
5475 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5477 http_request_t
*request
;
5478 http_session_t
*session
= NULL
;
5479 appinfo_t
*hIC
= NULL
;
5480 DWORD res
= ERROR_SUCCESS
;
5482 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest
,
5483 debugstr_wn(lpszHeaders
, dwHeaderLength
), dwHeaderLength
, lpOptional
, dwOptionalLength
);
5485 request
= (http_request_t
*) get_handle_object( hHttpRequest
);
5486 if (NULL
== request
|| request
->hdr
.htype
!= WH_HHTTPREQ
)
5488 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5492 session
= request
->session
;
5493 if (NULL
== session
|| session
->hdr
.htype
!= WH_HHTTPSESSION
)
5495 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5499 hIC
= session
->appInfo
;
5500 if (NULL
== hIC
|| hIC
->hdr
.htype
!= WH_HINIT
)
5502 res
= ERROR_INTERNET_INCORRECT_HANDLE_TYPE
;
5506 if (hIC
->hdr
.dwFlags
& INTERNET_FLAG_ASYNC
)
5508 send_request_task_t
*task
;
5510 task
= alloc_async_task(&request
->hdr
, AsyncHttpSendRequestProc
, sizeof(*task
));
5515 if (dwHeaderLength
== ~0u) size
= (strlenW(lpszHeaders
) + 1) * sizeof(WCHAR
);
5516 else size
= dwHeaderLength
* sizeof(WCHAR
);
5518 task
->headers
= heap_alloc(size
);
5519 memcpy(task
->headers
, lpszHeaders
, size
);
5522 task
->headers
= NULL
;
5523 task
->headers_len
= dwHeaderLength
;
5524 task
->optional
= lpOptional
;
5525 task
->optional_len
= dwOptionalLength
;
5526 task
->content_len
= dwOptionalLength
;
5527 task
->end_request
= TRUE
;
5529 INTERNET_AsyncCall(&task
->hdr
);
5530 res
= ERROR_IO_PENDING
;
5534 res
= HTTP_HttpSendRequestW(request
, lpszHeaders
,
5535 dwHeaderLength
, lpOptional
, dwOptionalLength
,
5536 dwOptionalLength
, TRUE
);
5540 WININET_Release( &request
->hdr
);
5543 return res
== ERROR_SUCCESS
;
5546 /***********************************************************************
5547 * HttpSendRequestA (WININET.@)
5549 * Sends the specified request to the HTTP server
5556 BOOL WINAPI
HttpSendRequestA(HINTERNET hHttpRequest
, LPCSTR lpszHeaders
,
5557 DWORD dwHeaderLength
, LPVOID lpOptional
,DWORD dwOptionalLength
)
5560 LPWSTR szHeaders
=NULL
;
5561 DWORD nLen
=dwHeaderLength
;
5562 if(lpszHeaders
!=NULL
)
5564 nLen
=MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,NULL
,0);
5565 szHeaders
= heap_alloc(nLen
*sizeof(WCHAR
));
5566 MultiByteToWideChar(CP_ACP
,0,lpszHeaders
,dwHeaderLength
,szHeaders
,nLen
);
5568 result
= HttpSendRequestW(hHttpRequest
, szHeaders
, nLen
, lpOptional
, dwOptionalLength
);
5569 heap_free(szHeaders
);
5573 /***********************************************************************
5574 * HTTPSESSION_Destroy (internal)
5576 * Deallocate session handle
5579 static void HTTPSESSION_Destroy(object_header_t
*hdr
)
5581 http_session_t
*session
= (http_session_t
*) hdr
;
5583 TRACE("%p\n", session
);
5585 WININET_Release(&session
->appInfo
->hdr
);
5587 heap_free(session
->hostName
);
5588 heap_free(session
->password
);
5589 heap_free(session
->userName
);
5592 static DWORD
HTTPSESSION_QueryOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD
*size
, BOOL unicode
)
5594 http_session_t
*ses
= (http_session_t
*)hdr
;
5597 case INTERNET_OPTION_HANDLE_TYPE
:
5598 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5600 if (*size
< sizeof(ULONG
))
5601 return ERROR_INSUFFICIENT_BUFFER
;
5603 *size
= sizeof(DWORD
);
5604 *(DWORD
*)buffer
= INTERNET_HANDLE_TYPE_CONNECT_HTTP
;
5605 return ERROR_SUCCESS
;
5606 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5607 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5609 if (*size
< sizeof(DWORD
))
5610 return ERROR_INSUFFICIENT_BUFFER
;
5612 *size
= sizeof(DWORD
);
5613 *(DWORD
*)buffer
= ses
->connect_timeout
;
5614 return ERROR_SUCCESS
;
5616 case INTERNET_OPTION_SEND_TIMEOUT
:
5617 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5619 if (*size
< sizeof(DWORD
))
5620 return ERROR_INSUFFICIENT_BUFFER
;
5622 *size
= sizeof(DWORD
);
5623 *(DWORD
*)buffer
= ses
->send_timeout
;
5624 return ERROR_SUCCESS
;
5626 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5627 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5629 if (*size
< sizeof(DWORD
))
5630 return ERROR_INSUFFICIENT_BUFFER
;
5632 *size
= sizeof(DWORD
);
5633 *(DWORD
*)buffer
= ses
->receive_timeout
;
5634 return ERROR_SUCCESS
;
5637 return INET_QueryOption(hdr
, option
, buffer
, size
, unicode
);
5640 static DWORD
HTTPSESSION_SetOption(object_header_t
*hdr
, DWORD option
, void *buffer
, DWORD size
)
5642 http_session_t
*ses
= (http_session_t
*)hdr
;
5645 case INTERNET_OPTION_USERNAME
:
5647 heap_free(ses
->userName
);
5648 if (!(ses
->userName
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5649 return ERROR_SUCCESS
;
5651 case INTERNET_OPTION_PASSWORD
:
5653 heap_free(ses
->password
);
5654 if (!(ses
->password
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5655 return ERROR_SUCCESS
;
5657 case INTERNET_OPTION_PROXY_USERNAME
:
5659 heap_free(ses
->appInfo
->proxyUsername
);
5660 if (!(ses
->appInfo
->proxyUsername
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5661 return ERROR_SUCCESS
;
5663 case INTERNET_OPTION_PROXY_PASSWORD
:
5665 heap_free(ses
->appInfo
->proxyPassword
);
5666 if (!(ses
->appInfo
->proxyPassword
= heap_strdupW(buffer
))) return ERROR_OUTOFMEMORY
;
5667 return ERROR_SUCCESS
;
5669 case INTERNET_OPTION_CONNECT_TIMEOUT
:
5671 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5672 ses
->connect_timeout
= *(DWORD
*)buffer
;
5673 return ERROR_SUCCESS
;
5675 case INTERNET_OPTION_SEND_TIMEOUT
:
5677 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5678 ses
->send_timeout
= *(DWORD
*)buffer
;
5679 return ERROR_SUCCESS
;
5681 case INTERNET_OPTION_RECEIVE_TIMEOUT
:
5683 if (!buffer
|| size
!= sizeof(DWORD
)) return ERROR_INVALID_PARAMETER
;
5684 ses
->receive_timeout
= *(DWORD
*)buffer
;
5685 return ERROR_SUCCESS
;
5690 return INET_SetOption(hdr
, option
, buffer
, size
);
5693 static const object_vtbl_t HTTPSESSIONVtbl
= {
5694 HTTPSESSION_Destroy
,
5696 HTTPSESSION_QueryOption
,
5697 HTTPSESSION_SetOption
,
5706 /***********************************************************************
5707 * HTTP_Connect (internal)
5709 * Create http session handle
5712 * HINTERNET a session handle on success
5716 DWORD
HTTP_Connect(appinfo_t
*hIC
, LPCWSTR lpszServerName
,
5717 INTERNET_PORT serverPort
, LPCWSTR lpszUserName
,
5718 LPCWSTR lpszPassword
, DWORD dwFlags
, DWORD_PTR dwContext
,
5719 DWORD dwInternalFlags
, HINTERNET
*ret
)
5721 http_session_t
*session
= NULL
;
5725 if (!lpszServerName
|| !lpszServerName
[0])
5726 return ERROR_INVALID_PARAMETER
;
5728 assert( hIC
->hdr
.htype
== WH_HINIT
);
5730 session
= alloc_object(&hIC
->hdr
, &HTTPSESSIONVtbl
, sizeof(http_session_t
));
5732 return ERROR_OUTOFMEMORY
;
5735 * According to my tests. The name is not resolved until a request is sent
5738 session
->hdr
.htype
= WH_HHTTPSESSION
;
5739 session
->hdr
.dwFlags
= dwFlags
;
5740 session
->hdr
.dwContext
= dwContext
;
5741 session
->hdr
.dwInternalFlags
|= dwInternalFlags
;
5743 WININET_AddRef( &hIC
->hdr
);
5744 session
->appInfo
= hIC
;
5745 list_add_head( &hIC
->hdr
.children
, &session
->hdr
.entry
);
5747 session
->hostName
= heap_strdupW(lpszServerName
);
5748 if (lpszUserName
&& lpszUserName
[0])
5749 session
->userName
= heap_strdupW(lpszUserName
);
5750 if (lpszPassword
&& lpszPassword
[0])
5751 session
->password
= heap_strdupW(lpszPassword
);
5752 session
->hostPort
= serverPort
;
5753 session
->connect_timeout
= hIC
->connect_timeout
;
5754 session
->send_timeout
= INFINITE
;
5755 session
->receive_timeout
= INFINITE
;
5757 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5758 if (!(session
->hdr
.dwInternalFlags
& INET_OPENURL
))
5760 INTERNET_SendCallback(&hIC
->hdr
, dwContext
,
5761 INTERNET_STATUS_HANDLE_CREATED
, &session
->hdr
.hInternet
,
5766 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5770 TRACE("%p --> %p\n", hIC
, session
);
5772 *ret
= session
->hdr
.hInternet
;
5773 return ERROR_SUCCESS
;
5776 /***********************************************************************
5777 * HTTP_clear_response_headers (internal)
5779 * clear out any old response headers
5781 static void HTTP_clear_response_headers( http_request_t
*request
)
5785 for( i
=0; i
<request
->nCustHeaders
; i
++)
5787 if( !request
->custHeaders
[i
].lpszField
)
5789 if( !request
->custHeaders
[i
].lpszValue
)
5791 if ( request
->custHeaders
[i
].wFlags
& HDR_ISREQUEST
)
5793 HTTP_DeleteCustomHeader( request
, i
);
5798 /***********************************************************************
5799 * HTTP_GetResponseHeaders (internal)
5801 * Read server response
5808 static DWORD
HTTP_GetResponseHeaders(http_request_t
*request
, INT
*len
)
5811 WCHAR buffer
[MAX_REPLY_LEN
];
5812 DWORD buflen
= MAX_REPLY_LEN
;
5814 char bufferA
[MAX_REPLY_LEN
];
5815 LPWSTR status_code
= NULL
, status_text
= NULL
;
5816 DWORD res
= ERROR_HTTP_INVALID_SERVER_RESPONSE
;
5817 BOOL codeHundred
= FALSE
;
5821 if(!request
->netconn
)
5824 /* clear old response headers (eg. from a redirect response) */
5825 HTTP_clear_response_headers( request
);
5827 NETCON_set_timeout( request
->netconn
, FALSE
, request
->receive_timeout
);
5830 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5832 buflen
= MAX_REPLY_LEN
;
5833 if ((res
= read_line(request
, bufferA
, &buflen
)))
5836 if (!buflen
) goto lend
;
5839 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5840 /* check is this a status code line? */
5841 if (!strncmpW(buffer
, g_szHttp1_0
, 4))
5843 /* split the version from the status code */
5844 status_code
= strchrW( buffer
, ' ' );
5849 /* split the status code from the status text */
5850 status_text
= strchrW( status_code
, ' ' );
5854 request
->status_code
= atoiW(status_code
);
5856 TRACE("version [%s] status code [%s] status text [%s]\n",
5857 debugstr_w(buffer
), debugstr_w(status_code
), debugstr_w(status_text
) );
5859 codeHundred
= request
->status_code
== HTTP_STATUS_CONTINUE
;
5861 else if (!codeHundred
)
5863 WARN("No status line at head of response (%s)\n", debugstr_w(buffer
));
5865 heap_free(request
->version
);
5866 heap_free(request
->statusText
);
5868 request
->status_code
= HTTP_STATUS_OK
;
5869 request
->version
= heap_strdupW(g_szHttp1_0
);
5870 request
->statusText
= heap_strdupW(szOK
);
5874 } while (codeHundred
);
5876 /* Add status code */
5877 HTTP_ProcessHeader(request
, szStatus
, status_code
,
5878 HTTP_ADDHDR_FLAG_REPLACE
);
5880 heap_free(request
->version
);
5881 heap_free(request
->statusText
);
5883 request
->version
= heap_strdupW(buffer
);
5884 request
->statusText
= heap_strdupW(status_text
? status_text
: emptyW
);
5886 /* Restore the spaces */
5887 *(status_code
-1) = ' ';
5889 *(status_text
-1) = ' ';
5891 /* Parse each response line */
5894 buflen
= MAX_REPLY_LEN
;
5895 if (!read_line(request
, bufferA
, &buflen
) && buflen
)
5897 LPWSTR
* pFieldAndValue
;
5899 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA
));
5901 if (!bufferA
[0]) break;
5902 MultiByteToWideChar( CP_ACP
, 0, bufferA
, buflen
, buffer
, MAX_REPLY_LEN
);
5904 pFieldAndValue
= HTTP_InterpretHttpHeader(buffer
);
5907 HTTP_ProcessHeader(request
, pFieldAndValue
[0], pFieldAndValue
[1],
5908 HTTP_ADDREQ_FLAG_ADD
);
5909 HTTP_FreeTokens(pFieldAndValue
);
5920 res
= ERROR_SUCCESS
;
5929 /***********************************************************************
5930 * HTTP_InterpretHttpHeader (internal)
5932 * Parse server response
5936 * Pointer to array of field, value, NULL on success.
5939 static LPWSTR
* HTTP_InterpretHttpHeader(LPCWSTR buffer
)
5941 LPWSTR
* pTokenPair
;
5945 pTokenPair
= heap_alloc_zero(sizeof(*pTokenPair
)*3);
5947 pszColon
= strchrW(buffer
, ':');
5948 /* must have two tokens */
5951 HTTP_FreeTokens(pTokenPair
);
5953 TRACE("No ':' in line: %s\n", debugstr_w(buffer
));
5957 pTokenPair
[0] = heap_alloc((pszColon
- buffer
+ 1) * sizeof(WCHAR
));
5960 HTTP_FreeTokens(pTokenPair
);
5963 memcpy(pTokenPair
[0], buffer
, (pszColon
- buffer
) * sizeof(WCHAR
));
5964 pTokenPair
[0][pszColon
- buffer
] = '\0';
5968 len
= strlenW(pszColon
);
5969 pTokenPair
[1] = heap_alloc((len
+ 1) * sizeof(WCHAR
));
5972 HTTP_FreeTokens(pTokenPair
);
5975 memcpy(pTokenPair
[1], pszColon
, (len
+ 1) * sizeof(WCHAR
));
5977 strip_spaces(pTokenPair
[0]);
5978 strip_spaces(pTokenPair
[1]);
5980 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair
[0]), debugstr_w(pTokenPair
[1]));
5984 /***********************************************************************
5985 * HTTP_ProcessHeader (internal)
5987 * Stuff header into header tables according to <dwModifier>
5991 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
5993 static DWORD
HTTP_ProcessHeader(http_request_t
*request
, LPCWSTR field
, LPCWSTR value
, DWORD dwModifier
)
5995 LPHTTPHEADERW lphttpHdr
= NULL
;
5997 BOOL request_only
= dwModifier
& HTTP_ADDHDR_FLAG_REQ
;
5998 DWORD res
= ERROR_HTTP_INVALID_HEADER
;
6000 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field
), debugstr_w(value
), dwModifier
);
6002 /* REPLACE wins out over ADD */
6003 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6004 dwModifier
&= ~HTTP_ADDHDR_FLAG_ADD
;
6006 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD
)
6009 index
= HTTP_GetCustomHeaderIndex(request
, field
, 0, request_only
);
6013 if (dwModifier
& HTTP_ADDHDR_FLAG_ADD_IF_NEW
)
6014 return ERROR_HTTP_INVALID_HEADER
;
6015 lphttpHdr
= &request
->custHeaders
[index
];
6021 hdr
.lpszField
= (LPWSTR
)field
;
6022 hdr
.lpszValue
= (LPWSTR
)value
;
6023 hdr
.wFlags
= hdr
.wCount
= 0;
6025 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6026 hdr
.wFlags
|= HDR_ISREQUEST
;
6028 return HTTP_InsertCustomHeader(request
, &hdr
);
6030 /* no value to delete */
6031 else return ERROR_SUCCESS
;
6033 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6034 lphttpHdr
->wFlags
|= HDR_ISREQUEST
;
6036 lphttpHdr
->wFlags
&= ~HDR_ISREQUEST
;
6038 if (dwModifier
& HTTP_ADDHDR_FLAG_REPLACE
)
6040 HTTP_DeleteCustomHeader( request
, index
);
6042 if (value
&& value
[0])
6046 hdr
.lpszField
= (LPWSTR
)field
;
6047 hdr
.lpszValue
= (LPWSTR
)value
;
6048 hdr
.wFlags
= hdr
.wCount
= 0;
6050 if (dwModifier
& HTTP_ADDHDR_FLAG_REQ
)
6051 hdr
.wFlags
|= HDR_ISREQUEST
;
6053 return HTTP_InsertCustomHeader(request
, &hdr
);
6056 return ERROR_SUCCESS
;
6058 else if (dwModifier
& COALESCEFLAGS
)
6063 INT origlen
= strlenW(lphttpHdr
->lpszValue
);
6064 INT valuelen
= strlenW(value
);
6066 if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA
)
6069 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6071 else if (dwModifier
& HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON
)
6074 lphttpHdr
->wFlags
|= HDR_COMMADELIMITED
;
6077 len
= origlen
+ valuelen
+ ((ch
> 0) ? 2 : 0);
6079 lpsztmp
= heap_realloc(lphttpHdr
->lpszValue
, (len
+1)*sizeof(WCHAR
));
6082 lphttpHdr
->lpszValue
= lpsztmp
;
6083 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6086 lphttpHdr
->lpszValue
[origlen
] = ch
;
6088 lphttpHdr
->lpszValue
[origlen
] = ' ';
6092 memcpy(&lphttpHdr
->lpszValue
[origlen
], value
, valuelen
*sizeof(WCHAR
));
6093 lphttpHdr
->lpszValue
[len
] = '\0';
6094 res
= ERROR_SUCCESS
;
6098 WARN("heap_realloc (%d bytes) failed\n",len
+1);
6099 res
= ERROR_OUTOFMEMORY
;
6102 TRACE("<-- %d\n", res
);
6106 /***********************************************************************
6107 * HTTP_GetCustomHeaderIndex (internal)
6109 * Return index of custom header from header array
6112 static INT
HTTP_GetCustomHeaderIndex(http_request_t
*request
, LPCWSTR lpszField
,
6113 int requested_index
, BOOL request_only
)
6117 TRACE("%s, %d, %d\n", debugstr_w(lpszField
), requested_index
, request_only
);
6119 for (index
= 0; index
< request
->nCustHeaders
; index
++)
6121 if (strcmpiW(request
->custHeaders
[index
].lpszField
, lpszField
))
6124 if (request_only
&& !(request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6127 if (!request_only
&& (request
->custHeaders
[index
].wFlags
& HDR_ISREQUEST
))
6130 if (requested_index
== 0)
6135 if (index
>= request
->nCustHeaders
)
6138 TRACE("Return: %d\n", index
);
6143 /***********************************************************************
6144 * HTTP_InsertCustomHeader (internal)
6146 * Insert header into array
6149 static DWORD
HTTP_InsertCustomHeader(http_request_t
*request
, LPHTTPHEADERW lpHdr
)
6152 LPHTTPHEADERW lph
= NULL
;
6154 TRACE("--> %s: %s\n", debugstr_w(lpHdr
->lpszField
), debugstr_w(lpHdr
->lpszValue
));
6155 count
= request
->nCustHeaders
+ 1;
6157 lph
= heap_realloc_zero(request
->custHeaders
, sizeof(HTTPHEADERW
) * count
);
6159 lph
= heap_alloc_zero(sizeof(HTTPHEADERW
) * count
);
6162 return ERROR_OUTOFMEMORY
;
6164 request
->custHeaders
= lph
;
6165 request
->custHeaders
[count
-1].lpszField
= heap_strdupW(lpHdr
->lpszField
);
6166 request
->custHeaders
[count
-1].lpszValue
= heap_strdupW(lpHdr
->lpszValue
);
6167 request
->custHeaders
[count
-1].wFlags
= lpHdr
->wFlags
;
6168 request
->custHeaders
[count
-1].wCount
= lpHdr
->wCount
;
6169 request
->nCustHeaders
++;
6171 return ERROR_SUCCESS
;
6175 /***********************************************************************
6176 * HTTP_DeleteCustomHeader (internal)
6178 * Delete header from array
6179 * If this function is called, the indexs may change.
6181 static BOOL
HTTP_DeleteCustomHeader(http_request_t
*request
, DWORD index
)
6183 if( request
->nCustHeaders
<= 0 )
6185 if( index
>= request
->nCustHeaders
)
6187 request
->nCustHeaders
--;
6189 heap_free(request
->custHeaders
[index
].lpszField
);
6190 heap_free(request
->custHeaders
[index
].lpszValue
);
6192 memmove( &request
->custHeaders
[index
], &request
->custHeaders
[index
+1],
6193 (request
->nCustHeaders
- index
)* sizeof(HTTPHEADERW
) );
6194 memset( &request
->custHeaders
[request
->nCustHeaders
], 0, sizeof(HTTPHEADERW
) );
6200 /***********************************************************************
6201 * HTTP_VerifyValidHeader (internal)
6203 * Verify the given header is not invalid for the given http request
6206 static BOOL
HTTP_VerifyValidHeader(http_request_t
*request
, LPCWSTR field
)
6208 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6209 if (!strcmpW(request
->version
, g_szHttp1_0
) && !strcmpiW(field
, szAccept_Encoding
))
6210 return ERROR_HTTP_INVALID_HEADER
;
6212 return ERROR_SUCCESS
;
6215 /***********************************************************************
6216 * IsHostInProxyBypassList (@)
6221 BOOL WINAPI
IsHostInProxyBypassList(DWORD flags
, LPCSTR szHost
, DWORD length
)
6223 FIXME("STUB: flags=%d host=%s length=%d\n",flags
,szHost
,length
);