comctl32/tooltips: Reset window subclass data when removing tools.
[wine.git] / dlls / wininet / http.c
blobb1c2d944ff7a6b7e61706b61b209bb26322d82f4
1 /*
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
12 * Ulrich Czekalla
13 * David Hammerton
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
30 #include "config.h"
32 #include <stdlib.h>
34 #ifdef HAVE_ZLIB
35 # include <zlib.h>
36 #endif
38 #include "winsock2.h"
39 #include "ws2ipdef.h"
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <time.h>
44 #include <assert.h>
46 #include "windef.h"
47 #include "winbase.h"
48 #include "wininet.h"
49 #include "winerror.h"
50 #include "winternl.h"
51 #define NO_SHLWAPI_STREAM
52 #define NO_SHLWAPI_REG
53 #define NO_SHLWAPI_STRFCNS
54 #define NO_SHLWAPI_GDI
55 #include "shlwapi.h"
56 #include "sspi.h"
57 #include "wincrypt.h"
58 #include "winuser.h"
60 #include "internet.h"
61 #include "wine/debug.h"
62 #include "wine/exception.h"
63 #include "wine/unicode.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
67 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
68 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
69 static const WCHAR szOK[] = {'O','K',0};
70 static const WCHAR hostW[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
75 static const WCHAR szGET[] = { 'G','E','T', 0 };
76 static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
78 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
79 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
80 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
81 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
82 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
83 static const WCHAR szAge[] = { 'A','g','e',0 };
84 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
85 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
86 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
87 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
88 static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
89 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
90 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
91 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
92 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
93 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
94 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
95 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
96 static const WCHAR szContent_Transfer_Encoding[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
97 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
98 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
99 static const WCHAR szDate[] = { 'D','a','t','e',0 };
100 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
101 static const WCHAR szETag[] = { 'E','T','a','g',0 };
102 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
103 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
104 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
106 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
107 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
108 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
109 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
110 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
111 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
112 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
113 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
114 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
115 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
116 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
117 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
118 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
119 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
120 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
121 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
122 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
123 static const WCHAR szUnless_Modified_Since[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
124 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
125 static const WCHAR szURI[] = { 'U','R','I',0 };
126 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
127 static const WCHAR szVary[] = { 'V','a','r','y',0 };
128 static const WCHAR szVia[] = { 'V','i','a',0 };
129 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
130 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
132 static const WCHAR emptyW[] = {0};
134 #define HTTP_REFERER szReferer
135 #define HTTP_ACCEPT szAccept
136 #define HTTP_USERAGENT szUser_Agent
138 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
139 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
140 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
141 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
142 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
143 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
144 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
146 #define COLLECT_TIME 60000
148 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
150 struct HttpAuthInfo
152 LPWSTR scheme;
153 CredHandle cred;
154 CtxtHandle ctx;
155 TimeStamp exp;
156 ULONG attr;
157 ULONG max_token;
158 void *auth_data;
159 unsigned int auth_data_len;
160 BOOL finished; /* finished authenticating */
164 typedef struct _basicAuthorizationData
166 struct list entry;
168 LPWSTR host;
169 LPWSTR realm;
170 LPSTR authorization;
171 UINT authorizationLen;
172 } basicAuthorizationData;
174 typedef struct _authorizationData
176 struct list entry;
178 LPWSTR host;
179 LPWSTR scheme;
180 LPWSTR domain;
181 UINT domain_len;
182 LPWSTR user;
183 UINT user_len;
184 LPWSTR password;
185 UINT password_len;
186 } authorizationData;
188 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
189 static struct list authorizationCache = LIST_INIT(authorizationCache);
191 static CRITICAL_SECTION authcache_cs;
192 static CRITICAL_SECTION_DEBUG critsect_debug =
194 0, 0, &authcache_cs,
195 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
196 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
198 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
200 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
201 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
202 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
203 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
204 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
205 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
206 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
207 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
208 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
209 static DWORD drain_content(http_request_t*,BOOL);
211 static CRITICAL_SECTION connection_pool_cs;
212 static CRITICAL_SECTION_DEBUG connection_pool_debug =
214 0, 0, &connection_pool_cs,
215 { &connection_pool_debug.ProcessLocksList, &connection_pool_debug.ProcessLocksList },
216 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
218 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
220 static struct list connection_pool = LIST_INIT(connection_pool);
221 static BOOL collector_running;
223 void server_addref(server_t *server)
225 InterlockedIncrement(&server->ref);
228 void server_release(server_t *server)
230 if(InterlockedDecrement(&server->ref))
231 return;
233 list_remove(&server->entry);
235 if(server->cert_chain)
236 CertFreeCertificateChain(server->cert_chain);
237 heap_free(server->name);
238 heap_free(server->scheme_host_port);
239 heap_free(server);
242 static BOOL process_host_port(server_t *server)
244 BOOL default_port;
245 size_t name_len;
246 WCHAR *buf;
248 static const WCHAR httpW[] = {'h','t','t','p',0};
249 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
250 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
252 name_len = strlenW(server->name);
253 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
254 if(!buf)
255 return FALSE;
257 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
258 server->scheme_host_port = buf;
260 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
261 if(server->is_https)
262 server->host_port++;
264 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
265 server->canon_host_port = default_port ? server->name : server->host_port;
266 return TRUE;
269 server_t *get_server(substr_t name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
271 server_t *iter, *server = NULL;
273 EnterCriticalSection(&connection_pool_cs);
275 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
276 if(iter->port == port && name.len == strlenW(iter->name) && !strncmpiW(iter->name, name.str, name.len)
277 && iter->is_https == is_https) {
278 server = iter;
279 server_addref(server);
280 break;
284 if(!server && do_create) {
285 server = heap_alloc_zero(sizeof(*server));
286 if(server) {
287 server->ref = 2; /* list reference and return */
288 server->port = port;
289 server->is_https = is_https;
290 list_init(&server->conn_pool);
291 server->name = heap_strndupW(name.str, name.len);
292 if(server->name && process_host_port(server)) {
293 list_add_head(&connection_pool, &server->entry);
294 }else {
295 heap_free(server);
296 server = NULL;
301 LeaveCriticalSection(&connection_pool_cs);
303 return server;
306 BOOL collect_connections(collect_type_t collect_type)
308 netconn_t *netconn, *netconn_safe;
309 server_t *server, *server_safe;
310 BOOL remaining = FALSE;
311 DWORD64 now;
313 now = GetTickCount64();
315 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
316 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
317 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
318 TRACE("freeing %p\n", netconn);
319 list_remove(&netconn->pool_entry);
320 free_netconn(netconn);
321 }else {
322 remaining = TRUE;
326 if(collect_type == COLLECT_CLEANUP) {
327 list_remove(&server->entry);
328 list_init(&server->entry);
329 server_release(server);
333 return remaining;
336 static DWORD WINAPI collect_connections_proc(void *arg)
338 BOOL remaining_conns;
340 do {
341 /* FIXME: Use more sophisticated method */
342 Sleep(5000);
344 EnterCriticalSection(&connection_pool_cs);
346 remaining_conns = collect_connections(COLLECT_TIMEOUT);
347 if(!remaining_conns)
348 collector_running = FALSE;
350 LeaveCriticalSection(&connection_pool_cs);
351 }while(remaining_conns);
353 FreeLibraryAndExitThread(WININET_hModule, 0);
356 /***********************************************************************
357 * HTTP_GetHeader (internal)
359 * Headers section must be held
361 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
363 int HeaderIndex = 0;
364 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
365 if (HeaderIndex == -1)
366 return NULL;
367 else
368 return &req->custHeaders[HeaderIndex];
371 static WCHAR *get_host_header( http_request_t *req )
373 HTTPHEADERW *header;
374 WCHAR *ret = NULL;
376 EnterCriticalSection( &req->headers_section );
377 if ((header = HTTP_GetHeader( req, hostW ))) ret = heap_strdupW( header->lpszValue );
378 else ret = heap_strdupW( req->server->canon_host_port );
379 LeaveCriticalSection( &req->headers_section );
380 return ret;
383 struct data_stream_vtbl_t {
384 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
385 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,BOOL);
386 DWORD (*drain_content)(data_stream_t*,http_request_t*,BOOL);
387 void (*destroy)(data_stream_t*);
390 typedef struct {
391 data_stream_t data_stream;
393 BYTE buf[READ_BUFFER_SIZE];
394 DWORD buf_size;
395 DWORD buf_pos;
396 DWORD chunk_size;
398 enum {
399 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE,
400 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE,
401 CHUNKED_STREAM_STATE_READING_CHUNK,
402 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA,
403 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END,
404 CHUNKED_STREAM_STATE_END_OF_STREAM,
405 CHUNKED_STREAM_STATE_ERROR
406 } state;
407 } chunked_stream_t;
409 static inline void destroy_data_stream(data_stream_t *stream)
411 stream->vtbl->destroy(stream);
414 static void reset_data_stream(http_request_t *req)
416 destroy_data_stream(req->data_stream);
417 req->data_stream = &req->netconn_stream.data_stream;
418 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
419 req->read_gzip = FALSE;
422 static void remove_header( http_request_t *request, const WCHAR *str, BOOL from_request )
424 int index;
425 EnterCriticalSection( &request->headers_section );
426 index = HTTP_GetCustomHeaderIndex( request, str, 0, from_request );
427 if (index != -1) HTTP_DeleteCustomHeader( request, index );
428 LeaveCriticalSection( &request->headers_section );
431 #ifdef HAVE_ZLIB
433 typedef struct {
434 data_stream_t stream;
435 data_stream_t *parent_stream;
436 z_stream zstream;
437 BYTE buf[READ_BUFFER_SIZE];
438 DWORD buf_size;
439 DWORD buf_pos;
440 BOOL end_of_data;
441 } gzip_stream_t;
443 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
445 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
446 return gzip_stream->end_of_data
447 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
450 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
451 DWORD *read, BOOL allow_blocking)
453 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
454 z_stream *zstream = &gzip_stream->zstream;
455 DWORD current_read, ret_read = 0;
456 int zres;
457 DWORD res = ERROR_SUCCESS;
459 TRACE("(%d %x)\n", size, allow_blocking);
461 while(size && !gzip_stream->end_of_data) {
462 if(!gzip_stream->buf_size) {
463 if(gzip_stream->buf_pos) {
464 if(gzip_stream->buf_size)
465 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
466 gzip_stream->buf_pos = 0;
468 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
469 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, allow_blocking);
470 if(res != ERROR_SUCCESS)
471 break;
473 gzip_stream->buf_size += current_read;
474 if(!current_read) {
475 WARN("unexpected end of data\n");
476 gzip_stream->end_of_data = TRUE;
477 break;
481 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
482 zstream->avail_in = gzip_stream->buf_size;
483 zstream->next_out = buf+ret_read;
484 zstream->avail_out = size;
485 zres = inflate(&gzip_stream->zstream, 0);
486 current_read = size - zstream->avail_out;
487 size -= current_read;
488 ret_read += current_read;
489 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
490 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
491 if(zres == Z_STREAM_END) {
492 TRACE("end of data\n");
493 gzip_stream->end_of_data = TRUE;
494 inflateEnd(zstream);
495 }else if(zres != Z_OK) {
496 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
497 if(!ret_read)
498 res = ERROR_INTERNET_DECODING_FAILED;
499 break;
502 if(ret_read)
503 allow_blocking = FALSE;
506 TRACE("read %u bytes\n", ret_read);
507 if(ret_read)
508 res = ERROR_SUCCESS;
509 *read = ret_read;
510 return res;
513 static DWORD gzip_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
515 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
516 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req, allow_blocking);
519 static void gzip_destroy(data_stream_t *stream)
521 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
523 destroy_data_stream(gzip_stream->parent_stream);
525 if(!gzip_stream->end_of_data)
526 inflateEnd(&gzip_stream->zstream);
527 heap_free(gzip_stream);
530 static const data_stream_vtbl_t gzip_stream_vtbl = {
531 gzip_end_of_data,
532 gzip_read,
533 gzip_drain_content,
534 gzip_destroy
537 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
539 return heap_alloc(items*size);
542 static void wininet_zfree(voidpf opaque, voidpf address)
544 heap_free(address);
547 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
549 gzip_stream_t *gzip_stream;
550 int zres;
552 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
553 if(!gzip_stream)
554 return ERROR_OUTOFMEMORY;
556 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
557 gzip_stream->zstream.zalloc = wininet_zalloc;
558 gzip_stream->zstream.zfree = wininet_zfree;
560 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
561 if(zres != Z_OK) {
562 ERR("inflateInit failed: %d\n", zres);
563 heap_free(gzip_stream);
564 return ERROR_OUTOFMEMORY;
567 remove_header(req, szContent_Length, FALSE);
569 if(req->read_size) {
570 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
571 gzip_stream->buf_size = req->read_size;
572 req->read_pos = req->read_size = 0;
575 req->read_gzip = TRUE;
576 gzip_stream->parent_stream = req->data_stream;
577 req->data_stream = &gzip_stream->stream;
578 return ERROR_SUCCESS;
581 #else
583 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
585 ERR("gzip stream not supported, missing zlib.\n");
586 return ERROR_SUCCESS;
589 #endif
591 /***********************************************************************
592 * HTTP_FreeTokens (internal)
594 * Frees table of pointers.
596 static void HTTP_FreeTokens(LPWSTR * token_array)
598 int i;
599 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
600 heap_free(token_array);
603 static void HTTP_FixURL(http_request_t *request)
605 static const WCHAR szSlash[] = { '/',0 };
606 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
608 /* If we don't have a path we set it to root */
609 if (NULL == request->path)
610 request->path = heap_strdupW(szSlash);
611 else /* remove \r and \n*/
613 int nLen = strlenW(request->path);
614 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
616 nLen--;
617 request->path[nLen]='\0';
619 /* Replace '\' with '/' */
620 while (nLen>0) {
621 nLen--;
622 if (request->path[nLen] == '\\') request->path[nLen]='/';
626 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
627 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
628 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
630 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
631 *fixurl = '/';
632 strcpyW(fixurl + 1, request->path);
633 heap_free( request->path );
634 request->path = fixurl;
638 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
639 const WCHAR *path, const WCHAR *version, BOOL use_cr)
641 static const WCHAR szSpace[] = {' ',0};
642 static const WCHAR szColon[] = {':',' ',0};
643 static const WCHAR szCr[] = {'\r',0};
644 static const WCHAR szLf[] = {'\n',0};
645 LPWSTR requestString;
646 DWORD len, n;
647 LPCWSTR *req;
648 UINT i;
650 EnterCriticalSection( &request->headers_section );
652 /* allocate space for an array of all the string pointers to be added */
653 len = request->nCustHeaders * 5 + 10;
654 if (!(req = heap_alloc( len * sizeof(const WCHAR *) )))
656 LeaveCriticalSection( &request->headers_section );
657 return NULL;
660 /* add the verb, path and HTTP version string */
661 n = 0;
662 req[n++] = verb;
663 req[n++] = szSpace;
664 req[n++] = path;
665 req[n++] = szSpace;
666 req[n++] = version;
667 if (use_cr)
668 req[n++] = szCr;
669 req[n++] = szLf;
671 /* Append custom request headers */
672 for (i = 0; i < request->nCustHeaders; i++)
674 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
676 req[n++] = request->custHeaders[i].lpszField;
677 req[n++] = szColon;
678 req[n++] = request->custHeaders[i].lpszValue;
679 if (use_cr)
680 req[n++] = szCr;
681 req[n++] = szLf;
683 TRACE("Adding custom header %s (%s)\n",
684 debugstr_w(request->custHeaders[i].lpszField),
685 debugstr_w(request->custHeaders[i].lpszValue));
688 if (use_cr)
689 req[n++] = szCr;
690 req[n++] = szLf;
691 req[n] = NULL;
693 requestString = HTTP_build_req( req, 4 );
694 heap_free( req );
695 LeaveCriticalSection( &request->headers_section );
696 return requestString;
699 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
701 static const WCHAR colonW[] = { ':',' ',0 };
702 static const WCHAR crW[] = { '\r',0 };
703 static const WCHAR lfW[] = { '\n',0 };
704 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
705 const WCHAR **req;
706 WCHAR *ret, buf[14];
707 DWORD i, n = 0;
709 EnterCriticalSection( &request->headers_section );
711 if (!(req = heap_alloc( (request->nCustHeaders * 5 + 8) * sizeof(WCHAR *) )))
713 LeaveCriticalSection( &request->headers_section );
714 return NULL;
717 if (request->status_code)
719 req[n++] = request->version;
720 sprintfW(buf, status_fmt, request->status_code);
721 req[n++] = buf;
722 req[n++] = request->statusText;
723 if (use_cr)
724 req[n++] = crW;
725 req[n++] = lfW;
728 for(i = 0; i < request->nCustHeaders; i++)
730 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
731 && strcmpW(request->custHeaders[i].lpszField, szStatus))
733 req[n++] = request->custHeaders[i].lpszField;
734 req[n++] = colonW;
735 req[n++] = request->custHeaders[i].lpszValue;
736 if(use_cr)
737 req[n++] = crW;
738 req[n++] = lfW;
740 TRACE("Adding custom header %s (%s)\n",
741 debugstr_w(request->custHeaders[i].lpszField),
742 debugstr_w(request->custHeaders[i].lpszValue));
745 if(use_cr)
746 req[n++] = crW;
747 req[n++] = lfW;
748 req[n] = NULL;
750 ret = HTTP_build_req(req, 0);
751 heap_free(req);
752 LeaveCriticalSection( &request->headers_section );
753 return ret;
756 static void HTTP_ProcessCookies( http_request_t *request )
758 int HeaderIndex;
759 int numCookies = 0;
760 LPHTTPHEADERW setCookieHeader;
762 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
763 return;
765 EnterCriticalSection( &request->headers_section );
767 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
769 const WCHAR *data;
770 substr_t name;
772 setCookieHeader = &request->custHeaders[HeaderIndex];
774 if (!setCookieHeader->lpszValue)
775 continue;
777 data = strchrW(setCookieHeader->lpszValue, '=');
778 if(!data)
779 continue;
781 name = substr(setCookieHeader->lpszValue, data - setCookieHeader->lpszValue);
782 data++;
783 set_cookie(substrz(request->server->name), substrz(request->path), name, substrz(data), INTERNET_COOKIE_HTTPONLY);
786 LeaveCriticalSection( &request->headers_section );
789 static void strip_spaces(LPWSTR start)
791 LPWSTR str = start;
792 LPWSTR end;
794 while (*str == ' ')
795 str++;
797 if (str != start)
798 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
800 end = start + strlenW(start) - 1;
801 while (end >= start && *end == ' ')
803 *end = '\0';
804 end--;
808 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
810 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
811 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
812 BOOL is_basic;
813 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
814 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
815 if (is_basic && pszRealm)
817 LPCWSTR token;
818 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
819 LPCWSTR realm;
820 ptr++;
821 *pszRealm=NULL;
822 token = strchrW(ptr,'=');
823 if (!token)
824 return TRUE;
825 realm = ptr;
826 while (*realm == ' ')
827 realm++;
828 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
829 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
831 token++;
832 while (*token == ' ')
833 token++;
834 if (*token == '\0')
835 return TRUE;
836 *pszRealm = heap_strdupW(token);
837 strip_spaces(*pszRealm);
841 return is_basic;
844 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
846 if (!authinfo) return;
848 if (SecIsValidHandle(&authinfo->ctx))
849 DeleteSecurityContext(&authinfo->ctx);
850 if (SecIsValidHandle(&authinfo->cred))
851 FreeCredentialsHandle(&authinfo->cred);
853 heap_free(authinfo->auth_data);
854 heap_free(authinfo->scheme);
855 heap_free(authinfo);
858 static UINT retrieve_cached_basic_authorization(const WCHAR *host, const WCHAR *realm, char **auth_data)
860 basicAuthorizationData *ad;
861 UINT rc = 0;
863 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
865 EnterCriticalSection(&authcache_cs);
866 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
868 if (!strcmpiW(host, ad->host) && (!realm || !strcmpW(realm, ad->realm)))
870 TRACE("Authorization found in cache\n");
871 *auth_data = heap_alloc(ad->authorizationLen);
872 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
873 rc = ad->authorizationLen;
874 break;
877 LeaveCriticalSection(&authcache_cs);
878 return rc;
881 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
883 struct list *cursor;
884 basicAuthorizationData* ad = NULL;
886 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
888 EnterCriticalSection(&authcache_cs);
889 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
891 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
892 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
894 ad = check;
895 break;
899 if (ad)
901 TRACE("Found match in cache, replacing\n");
902 heap_free(ad->authorization);
903 ad->authorization = heap_alloc(auth_data_len);
904 memcpy(ad->authorization, auth_data, auth_data_len);
905 ad->authorizationLen = auth_data_len;
907 else
909 ad = heap_alloc(sizeof(basicAuthorizationData));
910 ad->host = heap_strdupW(host);
911 ad->realm = heap_strdupW(realm);
912 ad->authorization = heap_alloc(auth_data_len);
913 memcpy(ad->authorization, auth_data, auth_data_len);
914 ad->authorizationLen = auth_data_len;
915 list_add_head(&basicAuthorizationCache,&ad->entry);
916 TRACE("authorization cached\n");
918 LeaveCriticalSection(&authcache_cs);
921 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
922 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
924 authorizationData *ad;
926 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
928 EnterCriticalSection(&authcache_cs);
929 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
930 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
931 TRACE("Authorization found in cache\n");
933 nt_auth_identity->User = heap_strdupW(ad->user);
934 nt_auth_identity->Password = heap_strdupW(ad->password);
935 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
936 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
937 (!nt_auth_identity->Domain && ad->domain_len)) {
938 heap_free(nt_auth_identity->User);
939 heap_free(nt_auth_identity->Password);
940 heap_free(nt_auth_identity->Domain);
941 break;
944 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
945 nt_auth_identity->UserLength = ad->user_len;
946 nt_auth_identity->PasswordLength = ad->password_len;
947 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
948 nt_auth_identity->DomainLength = ad->domain_len;
949 LeaveCriticalSection(&authcache_cs);
950 return TRUE;
953 LeaveCriticalSection(&authcache_cs);
955 return FALSE;
958 static void cache_authorization(LPWSTR host, LPWSTR scheme,
959 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
961 authorizationData *ad;
962 BOOL found = FALSE;
964 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
966 EnterCriticalSection(&authcache_cs);
967 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
968 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
969 found = TRUE;
970 break;
973 if(found) {
974 heap_free(ad->user);
975 heap_free(ad->password);
976 heap_free(ad->domain);
977 } else {
978 ad = heap_alloc(sizeof(authorizationData));
979 if(!ad) {
980 LeaveCriticalSection(&authcache_cs);
981 return;
984 ad->host = heap_strdupW(host);
985 ad->scheme = heap_strdupW(scheme);
986 list_add_head(&authorizationCache, &ad->entry);
989 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
990 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
991 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
992 ad->user_len = nt_auth_identity->UserLength;
993 ad->password_len = nt_auth_identity->PasswordLength;
994 ad->domain_len = nt_auth_identity->DomainLength;
996 if(!ad->host || !ad->scheme || !ad->user || !ad->password
997 || (nt_auth_identity->Domain && !ad->domain)) {
998 heap_free(ad->host);
999 heap_free(ad->scheme);
1000 heap_free(ad->user);
1001 heap_free(ad->password);
1002 heap_free(ad->domain);
1003 list_remove(&ad->entry);
1004 heap_free(ad);
1007 LeaveCriticalSection(&authcache_cs);
1010 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1011 struct HttpAuthInfo **ppAuthInfo,
1012 LPWSTR domain_and_username, LPWSTR password,
1013 LPWSTR host )
1015 SECURITY_STATUS sec_status;
1016 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1017 BOOL first = FALSE;
1018 LPWSTR szRealm = NULL;
1020 TRACE("%s\n", debugstr_w(pszAuthValue));
1022 if (!pAuthInfo)
1024 TimeStamp exp;
1026 first = TRUE;
1027 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1028 if (!pAuthInfo)
1029 return FALSE;
1031 SecInvalidateHandle(&pAuthInfo->cred);
1032 SecInvalidateHandle(&pAuthInfo->ctx);
1033 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1034 pAuthInfo->attr = 0;
1035 pAuthInfo->auth_data = NULL;
1036 pAuthInfo->auth_data_len = 0;
1037 pAuthInfo->finished = FALSE;
1039 if (is_basic_auth_value(pszAuthValue,NULL))
1041 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1042 pAuthInfo->scheme = heap_strdupW(szBasic);
1043 if (!pAuthInfo->scheme)
1045 heap_free(pAuthInfo);
1046 return FALSE;
1049 else
1051 PVOID pAuthData;
1052 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1054 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1055 if (!pAuthInfo->scheme)
1057 heap_free(pAuthInfo);
1058 return FALSE;
1061 if (domain_and_username)
1063 WCHAR *user = strchrW(domain_and_username, '\\');
1064 WCHAR *domain = domain_and_username;
1066 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1068 pAuthData = &nt_auth_identity;
1070 if (user) user++;
1071 else
1073 user = domain_and_username;
1074 domain = NULL;
1077 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1078 nt_auth_identity.User = user;
1079 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1080 nt_auth_identity.Domain = domain;
1081 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1082 nt_auth_identity.Password = password;
1083 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1085 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1087 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1088 pAuthData = &nt_auth_identity;
1089 else
1090 /* use default credentials */
1091 pAuthData = NULL;
1093 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1094 SECPKG_CRED_OUTBOUND, NULL,
1095 pAuthData, NULL,
1096 NULL, &pAuthInfo->cred,
1097 &exp);
1099 if(pAuthData && !domain_and_username) {
1100 heap_free(nt_auth_identity.User);
1101 heap_free(nt_auth_identity.Domain);
1102 heap_free(nt_auth_identity.Password);
1105 if (sec_status == SEC_E_OK)
1107 PSecPkgInfoW sec_pkg_info;
1108 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1109 if (sec_status == SEC_E_OK)
1111 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1112 FreeContextBuffer(sec_pkg_info);
1115 if (sec_status != SEC_E_OK)
1117 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1118 debugstr_w(pAuthInfo->scheme), sec_status);
1119 heap_free(pAuthInfo->scheme);
1120 heap_free(pAuthInfo);
1121 return FALSE;
1124 *ppAuthInfo = pAuthInfo;
1126 else if (pAuthInfo->finished)
1127 return FALSE;
1129 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1130 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1132 ERR("authentication scheme changed from %s to %s\n",
1133 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1134 return FALSE;
1137 if (is_basic_auth_value(pszAuthValue,&szRealm))
1139 int userlen;
1140 int passlen;
1141 char *auth_data = NULL;
1142 UINT auth_data_len = 0;
1144 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1146 if (!domain_and_username)
1148 if (host && szRealm)
1149 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1150 if (auth_data_len == 0)
1152 heap_free(szRealm);
1153 return FALSE;
1156 else
1158 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1159 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1161 /* length includes a nul terminator, which will be re-used for the ':' */
1162 auth_data = heap_alloc(userlen + 1 + passlen);
1163 if (!auth_data)
1165 heap_free(szRealm);
1166 return FALSE;
1169 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1170 auth_data[userlen] = ':';
1171 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1172 auth_data_len = userlen + 1 + passlen;
1173 if (host && szRealm)
1174 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1177 pAuthInfo->auth_data = auth_data;
1178 pAuthInfo->auth_data_len = auth_data_len;
1179 pAuthInfo->finished = TRUE;
1180 heap_free(szRealm);
1181 return TRUE;
1183 else
1185 LPCWSTR pszAuthData;
1186 SecBufferDesc out_desc, in_desc;
1187 SecBuffer out, in;
1188 unsigned char *buffer;
1189 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1190 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1192 in.BufferType = SECBUFFER_TOKEN;
1193 in.cbBuffer = 0;
1194 in.pvBuffer = NULL;
1196 in_desc.ulVersion = 0;
1197 in_desc.cBuffers = 1;
1198 in_desc.pBuffers = &in;
1200 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1201 if (*pszAuthData == ' ')
1203 pszAuthData++;
1204 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1205 in.pvBuffer = heap_alloc(in.cbBuffer);
1206 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1209 buffer = heap_alloc(pAuthInfo->max_token);
1211 out.BufferType = SECBUFFER_TOKEN;
1212 out.cbBuffer = pAuthInfo->max_token;
1213 out.pvBuffer = buffer;
1215 out_desc.ulVersion = 0;
1216 out_desc.cBuffers = 1;
1217 out_desc.pBuffers = &out;
1219 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1220 first ? NULL : &pAuthInfo->ctx,
1221 first ? request->server->name : NULL,
1222 context_req, 0, SECURITY_NETWORK_DREP,
1223 in.pvBuffer ? &in_desc : NULL,
1224 0, &pAuthInfo->ctx, &out_desc,
1225 &pAuthInfo->attr, &pAuthInfo->exp);
1226 if (sec_status == SEC_E_OK)
1228 pAuthInfo->finished = TRUE;
1229 pAuthInfo->auth_data = out.pvBuffer;
1230 pAuthInfo->auth_data_len = out.cbBuffer;
1231 TRACE("sending last auth packet\n");
1233 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1235 pAuthInfo->auth_data = out.pvBuffer;
1236 pAuthInfo->auth_data_len = out.cbBuffer;
1237 TRACE("sending next auth packet\n");
1239 else
1241 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1242 heap_free(out.pvBuffer);
1243 destroy_authinfo(pAuthInfo);
1244 *ppAuthInfo = NULL;
1245 return FALSE;
1249 return TRUE;
1252 /***********************************************************************
1253 * HTTP_HttpAddRequestHeadersW (internal)
1255 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1256 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1258 LPWSTR lpszStart;
1259 LPWSTR lpszEnd;
1260 LPWSTR buffer;
1261 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1263 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1265 if( dwHeaderLength == ~0U )
1266 len = strlenW(lpszHeader);
1267 else
1268 len = dwHeaderLength;
1269 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1270 lstrcpynW( buffer, lpszHeader, len + 1);
1272 lpszStart = buffer;
1276 LPWSTR * pFieldAndValue;
1278 lpszEnd = lpszStart;
1280 while (*lpszEnd != '\0')
1282 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1283 break;
1284 lpszEnd++;
1287 if (*lpszStart == '\0')
1288 break;
1290 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1292 *lpszEnd = '\0';
1293 lpszEnd++; /* Jump over newline */
1295 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1296 if (*lpszStart == '\0')
1298 /* Skip 0-length headers */
1299 lpszStart = lpszEnd;
1300 res = ERROR_SUCCESS;
1301 continue;
1303 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1304 if (pFieldAndValue)
1306 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1307 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1308 HTTP_FreeTokens(pFieldAndValue);
1311 lpszStart = lpszEnd;
1312 } while (res == ERROR_SUCCESS);
1314 heap_free(buffer);
1315 return res;
1318 /***********************************************************************
1319 * HttpAddRequestHeadersW (WININET.@)
1321 * Adds one or more HTTP header to the request handler
1323 * NOTE
1324 * On Windows if dwHeaderLength includes the trailing '\0', then
1325 * HttpAddRequestHeadersW() adds it too. However this results in an
1326 * invalid HTTP header which is rejected by some servers so we probably
1327 * don't need to match Windows on that point.
1329 * RETURNS
1330 * TRUE on success
1331 * FALSE on failure
1334 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1335 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1337 http_request_t *request;
1338 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1340 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1342 if (!lpszHeader)
1343 return TRUE;
1345 request = (http_request_t*) get_handle_object( hHttpRequest );
1346 if (request && request->hdr.htype == WH_HHTTPREQ)
1347 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1348 if( request )
1349 WININET_Release( &request->hdr );
1351 if(res != ERROR_SUCCESS)
1352 SetLastError(res);
1353 return res == ERROR_SUCCESS;
1356 /***********************************************************************
1357 * HttpAddRequestHeadersA (WININET.@)
1359 * Adds one or more HTTP header to the request handler
1361 * RETURNS
1362 * TRUE on success
1363 * FALSE on failure
1366 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1367 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1369 WCHAR *headers = NULL;
1370 BOOL r;
1372 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1374 if(lpszHeader)
1375 headers = heap_strndupAtoW(lpszHeader, dwHeaderLength, &dwHeaderLength);
1377 r = HttpAddRequestHeadersW(hHttpRequest, headers, dwHeaderLength, dwModifier);
1379 heap_free(headers);
1380 return r;
1383 static void free_accept_types( WCHAR **accept_types )
1385 WCHAR *ptr, **types = accept_types;
1387 if (!types) return;
1388 while ((ptr = *types))
1390 heap_free( ptr );
1391 types++;
1393 heap_free( accept_types );
1396 static WCHAR **convert_accept_types( const char **accept_types )
1398 unsigned int count;
1399 const char **types = accept_types;
1400 WCHAR **typesW;
1401 BOOL invalid_pointer = FALSE;
1403 if (!types) return NULL;
1404 count = 0;
1405 while (*types)
1407 __TRY
1409 /* find out how many there are */
1410 if (*types && **types)
1412 TRACE("accept type: %s\n", debugstr_a(*types));
1413 count++;
1416 __EXCEPT_PAGE_FAULT
1418 WARN("invalid accept type pointer\n");
1419 invalid_pointer = TRUE;
1421 __ENDTRY;
1422 types++;
1424 if (invalid_pointer) return NULL;
1425 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1426 count = 0;
1427 types = accept_types;
1428 while (*types)
1430 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1431 types++;
1433 typesW[count] = NULL;
1434 return typesW;
1437 /***********************************************************************
1438 * HttpOpenRequestA (WININET.@)
1440 * Open a HTTP request handle
1442 * RETURNS
1443 * HINTERNET a HTTP request handle on success
1444 * NULL on failure
1447 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1448 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1449 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1450 DWORD dwFlags, DWORD_PTR dwContext)
1452 LPWSTR szVerb = NULL, szObjectName = NULL;
1453 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1454 HINTERNET rc = NULL;
1456 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1457 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1458 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1459 dwFlags, dwContext);
1461 if (lpszVerb)
1463 szVerb = heap_strdupAtoW(lpszVerb);
1464 if ( !szVerb )
1465 goto end;
1468 if (lpszObjectName)
1470 szObjectName = heap_strdupAtoW(lpszObjectName);
1471 if ( !szObjectName )
1472 goto end;
1475 if (lpszVersion)
1477 szVersion = heap_strdupAtoW(lpszVersion);
1478 if ( !szVersion )
1479 goto end;
1482 if (lpszReferrer)
1484 szReferrer = heap_strdupAtoW(lpszReferrer);
1485 if ( !szReferrer )
1486 goto end;
1489 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1490 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1491 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1493 end:
1494 free_accept_types(szAcceptTypes);
1495 heap_free(szReferrer);
1496 heap_free(szVersion);
1497 heap_free(szObjectName);
1498 heap_free(szVerb);
1499 return rc;
1502 /***********************************************************************
1503 * HTTP_EncodeBase64
1505 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1507 UINT n = 0, x;
1508 static const CHAR HTTP_Base64Enc[] =
1509 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1511 while( len > 0 )
1513 /* first 6 bits, all from bin[0] */
1514 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1515 x = (bin[0] & 3) << 4;
1517 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1518 if( len == 1 )
1520 base64[n++] = HTTP_Base64Enc[x];
1521 base64[n++] = '=';
1522 base64[n++] = '=';
1523 break;
1525 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1526 x = ( bin[1] & 0x0f ) << 2;
1528 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1529 if( len == 2 )
1531 base64[n++] = HTTP_Base64Enc[x];
1532 base64[n++] = '=';
1533 break;
1535 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1537 /* last 6 bits, all from bin [2] */
1538 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1539 bin += 3;
1540 len -= 3;
1542 base64[n] = 0;
1543 return n;
1546 static const signed char HTTP_Base64Dec[] =
1548 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1549 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1550 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1551 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1552 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1553 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1554 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1555 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1558 /***********************************************************************
1559 * HTTP_DecodeBase64
1561 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1563 unsigned int n = 0;
1565 while(*base64)
1567 signed char in[4];
1569 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1570 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1571 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1572 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1574 WARN("invalid base64: %s\n", debugstr_w(base64));
1575 return 0;
1577 if (bin)
1578 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1579 n++;
1581 if ((base64[2] == '=') && (base64[3] == '='))
1582 break;
1583 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1584 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1586 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1587 return 0;
1589 if (bin)
1590 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1591 n++;
1593 if (base64[3] == '=')
1594 break;
1595 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1596 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1598 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1599 return 0;
1601 if (bin)
1602 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1603 n++;
1605 base64 += 4;
1608 return n;
1611 static WCHAR *encode_auth_data( const WCHAR *scheme, const char *data, UINT data_len )
1613 WCHAR *ret;
1614 UINT len, scheme_len = strlenW( scheme );
1616 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1617 len = scheme_len + 1 + ((data_len + 2) * 4) / 3;
1618 if (!(ret = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return NULL;
1619 memcpy( ret, scheme, scheme_len * sizeof(WCHAR) );
1620 ret[scheme_len] = ' ';
1621 HTTP_EncodeBase64( data, data_len, ret + scheme_len + 1 );
1622 return ret;
1626 /***********************************************************************
1627 * HTTP_InsertAuthorization
1629 * Insert or delete the authorization field in the request header.
1631 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1633 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1634 WCHAR *host, *authorization = NULL;
1636 if (pAuthInfo)
1638 if (pAuthInfo->auth_data_len)
1640 if (!(authorization = encode_auth_data(pAuthInfo->scheme, pAuthInfo->auth_data, pAuthInfo->auth_data_len)))
1641 return FALSE;
1643 /* clear the data as it isn't valid now that it has been sent to the
1644 * server, unless it's Basic authentication which doesn't do
1645 * connection tracking */
1646 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1648 heap_free(pAuthInfo->auth_data);
1649 pAuthInfo->auth_data = NULL;
1650 pAuthInfo->auth_data_len = 0;
1654 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1656 HTTP_ProcessHeader(request, header, authorization,
1657 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
1658 heap_free(authorization);
1660 else if (!strcmpW(header, szAuthorization) && (host = get_host_header(request)))
1662 UINT data_len;
1663 char *data;
1665 if ((data_len = retrieve_cached_basic_authorization(host, NULL, &data)))
1667 TRACE("Found cached basic authorization for %s\n", debugstr_w(host));
1669 if (!(authorization = encode_auth_data(wszBasic, data, data_len)))
1671 heap_free(data);
1672 heap_free(host);
1673 return FALSE;
1676 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1678 HTTP_ProcessHeader(request, header, authorization,
1679 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
1680 heap_free(data);
1681 heap_free(authorization);
1683 heap_free(host);
1685 return TRUE;
1688 static WCHAR *build_proxy_path_url(http_request_t *req)
1690 DWORD size, len;
1691 WCHAR *url;
1693 len = strlenW(req->server->scheme_host_port);
1694 size = len + strlenW(req->path) + 1;
1695 if(*req->path != '/')
1696 size++;
1697 url = heap_alloc(size * sizeof(WCHAR));
1698 if(!url)
1699 return NULL;
1701 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1702 if(*req->path != '/')
1703 url[len++] = '/';
1705 strcpyW(url+len, req->path);
1707 TRACE("url=%s\n", debugstr_w(url));
1708 return url;
1711 static BOOL HTTP_DomainMatches(LPCWSTR server, substr_t domain)
1713 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1714 const WCHAR *dot, *ptr;
1715 int len;
1717 if(domain.len == sizeof(localW)/sizeof(WCHAR)-1 && !strncmpiW(domain.str, localW, domain.len) && !strchrW(server, '.' ))
1718 return TRUE;
1720 if(domain.len && *domain.str != '*')
1721 return domain.len == strlenW(server) && !strncmpiW(server, domain.str, domain.len);
1723 if(domain.len < 2 || domain.str[1] != '.')
1724 return FALSE;
1726 /* For a hostname to match a wildcard, the last domain must match
1727 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1728 * hostname is www.foo.a.b, it matches, but a.b does not.
1730 dot = strchrW(server, '.');
1731 if(!dot)
1732 return FALSE;
1734 len = strlenW(dot + 1);
1735 if(len < domain.len - 2)
1736 return FALSE;
1738 /* The server's domain is longer than the wildcard, so it
1739 * could be a subdomain. Compare the last portion of the
1740 * server's domain.
1742 ptr = dot + 1 + len - domain.len + 2;
1743 if(!strncmpiW(ptr, domain.str+2, domain.len-2))
1744 /* This is only a match if the preceding character is
1745 * a '.', i.e. that it is a matching domain. E.g.
1746 * if domain is '*.b.c' and server is 'www.ab.c' they
1747 * do not match.
1749 return *(ptr - 1) == '.';
1751 return len == domain.len-2 && !strncmpiW(dot + 1, domain.str + 2, len);
1754 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1756 LPCWSTR ptr;
1757 BOOL ret = FALSE;
1759 if (!lpwai->proxyBypass) return FALSE;
1760 ptr = lpwai->proxyBypass;
1761 while(1) {
1762 LPCWSTR tmp = ptr;
1764 ptr = strchrW( ptr, ';' );
1765 if (!ptr)
1766 ptr = strchrW( tmp, ' ' );
1767 if (!ptr)
1768 ptr = tmp + strlenW(tmp);
1769 ret = HTTP_DomainMatches( server, substr(tmp, ptr-tmp) );
1770 if (ret || !*ptr)
1771 break;
1772 ptr++;
1774 return ret;
1777 /***********************************************************************
1778 * HTTP_DealWithProxy
1780 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1782 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1783 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1784 static WCHAR szNul[] = { 0 };
1785 URL_COMPONENTSW UrlComponents = { sizeof(UrlComponents) };
1786 server_t *new_server = NULL;
1787 WCHAR *proxy;
1789 proxy = INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp);
1790 if(!proxy)
1791 return FALSE;
1792 if(CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1793 proxy, strlenW(szHttp), szHttp, strlenW(szHttp))) {
1794 WCHAR *proxy_url = heap_alloc(strlenW(proxy)*sizeof(WCHAR) + sizeof(szHttp));
1795 if(!proxy_url) {
1796 heap_free(proxy);
1797 return FALSE;
1799 strcpyW(proxy_url, szHttp);
1800 strcatW(proxy_url, proxy);
1801 heap_free(proxy);
1802 proxy = proxy_url;
1805 UrlComponents.dwHostNameLength = 1;
1806 if(InternetCrackUrlW(proxy, 0, 0, &UrlComponents) && UrlComponents.dwHostNameLength) {
1807 if( !request->path )
1808 request->path = szNul;
1810 new_server = get_server(substr(UrlComponents.lpszHostName, UrlComponents.dwHostNameLength),
1811 UrlComponents.nPort, UrlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
1813 heap_free(proxy);
1814 if(!new_server)
1815 return FALSE;
1817 request->proxy = new_server;
1819 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1820 return TRUE;
1823 static DWORD HTTP_ResolveName(http_request_t *request)
1825 server_t *server = request->proxy ? request->proxy : request->server;
1826 int addr_len;
1828 if(server->addr_len)
1829 return ERROR_SUCCESS;
1831 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1832 INTERNET_STATUS_RESOLVING_NAME,
1833 server->name,
1834 (strlenW(server->name)+1) * sizeof(WCHAR));
1836 addr_len = sizeof(server->addr);
1837 if (!GetAddress(server->name, server->port, (SOCKADDR*)&server->addr, &addr_len, server->addr_str))
1838 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1840 server->addr_len = addr_len;
1841 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1842 INTERNET_STATUS_NAME_RESOLVED,
1843 server->addr_str, strlen(server->addr_str)+1);
1845 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1846 return ERROR_SUCCESS;
1849 static WCHAR *compose_request_url(http_request_t *req)
1851 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1852 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1853 const WCHAR *host, *scheme;
1854 WCHAR *buf, *ptr;
1855 size_t len;
1857 host = req->server->canon_host_port;
1859 if (req->server->is_https)
1860 scheme = https;
1861 else
1862 scheme = http;
1864 len = strlenW(scheme) + strlenW(host) + (req->path[0] != '/' ? 1 : 0) + strlenW(req->path);
1865 ptr = buf = heap_alloc((len+1) * sizeof(WCHAR));
1866 if(buf) {
1867 strcpyW(ptr, scheme);
1868 ptr += strlenW(ptr);
1870 strcpyW(ptr, host);
1871 ptr += strlenW(ptr);
1873 if(req->path[0] != '/')
1874 *ptr++ = '/';
1876 strcpyW(ptr, req->path);
1877 ptr += strlenW(ptr);
1878 *ptr = 0;
1881 return buf;
1885 /***********************************************************************
1886 * HTTPREQ_Destroy (internal)
1888 * Deallocate request handle
1891 static void HTTPREQ_Destroy(object_header_t *hdr)
1893 http_request_t *request = (http_request_t*) hdr;
1894 DWORD i;
1896 TRACE("\n");
1898 if(request->hCacheFile)
1899 CloseHandle(request->hCacheFile);
1900 if(request->req_file)
1901 req_file_release(request->req_file);
1903 request->headers_section.DebugInfo->Spare[0] = 0;
1904 DeleteCriticalSection( &request->headers_section );
1905 request->read_section.DebugInfo->Spare[0] = 0;
1906 DeleteCriticalSection( &request->read_section );
1907 WININET_Release(&request->session->hdr);
1909 destroy_authinfo(request->authInfo);
1910 destroy_authinfo(request->proxyAuthInfo);
1912 if(request->server)
1913 server_release(request->server);
1914 if(request->proxy)
1915 server_release(request->proxy);
1917 heap_free(request->path);
1918 heap_free(request->verb);
1919 heap_free(request->version);
1920 heap_free(request->statusText);
1922 for (i = 0; i < request->nCustHeaders; i++)
1924 heap_free(request->custHeaders[i].lpszField);
1925 heap_free(request->custHeaders[i].lpszValue);
1927 destroy_data_stream(request->data_stream);
1928 heap_free(request->custHeaders);
1931 static void http_release_netconn(http_request_t *req, BOOL reuse)
1933 TRACE("%p %p %x\n",req, req->netconn, reuse);
1935 if(!is_valid_netconn(req->netconn))
1936 return;
1938 if(reuse && req->netconn->keep_alive) {
1939 BOOL run_collector;
1941 EnterCriticalSection(&connection_pool_cs);
1943 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1944 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1945 req->netconn = NULL;
1947 run_collector = !collector_running;
1948 collector_running = TRUE;
1950 LeaveCriticalSection(&connection_pool_cs);
1952 if(run_collector) {
1953 HANDLE thread = NULL;
1954 HMODULE module;
1956 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1957 if(module)
1958 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1959 if(!thread) {
1960 EnterCriticalSection(&connection_pool_cs);
1961 collector_running = FALSE;
1962 LeaveCriticalSection(&connection_pool_cs);
1964 if(module)
1965 FreeLibrary(module);
1967 else
1968 CloseHandle(thread);
1970 return;
1973 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1974 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1976 close_netconn(req->netconn);
1978 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1979 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1982 static BOOL HTTP_KeepAlive(http_request_t *request)
1984 WCHAR szVersion[10];
1985 WCHAR szConnectionResponse[20];
1986 DWORD dwBufferSize = sizeof(szVersion);
1987 BOOL keepalive = FALSE;
1989 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1990 * the connection is keep-alive by default */
1991 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1992 && !strcmpiW(szVersion, g_szHttp1_1))
1994 keepalive = TRUE;
1997 dwBufferSize = sizeof(szConnectionResponse);
1998 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
1999 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2001 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2004 return keepalive;
2007 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2009 http_request_t *req = (http_request_t*)hdr;
2011 http_release_netconn(req, drain_content(req, FALSE) == ERROR_SUCCESS);
2014 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2016 int len;
2017 if (unicode)
2019 WCHAR *buf = buffer;
2021 if (str) len = strlenW(str);
2022 else len = 0;
2023 if (*size < (len + 1) * sizeof(WCHAR))
2025 *size = (len + 1) * sizeof(WCHAR);
2026 return ERROR_INSUFFICIENT_BUFFER;
2028 if (str) strcpyW(buf, str);
2029 else buf[0] = 0;
2031 *size = len;
2032 return ERROR_SUCCESS;
2034 else
2036 char *buf = buffer;
2038 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2039 else len = 1;
2040 if (*size < len)
2042 *size = len;
2043 return ERROR_INSUFFICIENT_BUFFER;
2045 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2046 else buf[0] = 0;
2048 *size = len - 1;
2049 return ERROR_SUCCESS;
2053 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2055 http_request_t *req = (http_request_t*)hdr;
2057 switch(option) {
2058 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2060 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2062 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2064 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2065 return ERROR_INSUFFICIENT_BUFFER;
2066 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2067 /* FIXME: can't get a SOCKET from our connection since we don't use
2068 * winsock
2070 info->Socket = 0;
2071 /* FIXME: get source port from req->netConnection */
2072 info->SourcePort = 0;
2073 info->DestPort = req->server->port;
2074 info->Flags = 0;
2075 if (HTTP_KeepAlive(req))
2076 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2077 if (req->proxy)
2078 info->Flags |= IDSI_FLAG_PROXY;
2079 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2080 info->Flags |= IDSI_FLAG_SECURE;
2082 return ERROR_SUCCESS;
2085 case 98:
2086 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2087 /* fall through */
2088 case INTERNET_OPTION_SECURITY_FLAGS:
2090 DWORD flags;
2092 if (*size < sizeof(ULONG))
2093 return ERROR_INSUFFICIENT_BUFFER;
2095 *size = sizeof(DWORD);
2096 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2097 *(DWORD *)buffer = flags;
2099 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2100 return ERROR_SUCCESS;
2103 case INTERNET_OPTION_HANDLE_TYPE:
2104 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2106 if (*size < sizeof(ULONG))
2107 return ERROR_INSUFFICIENT_BUFFER;
2109 *size = sizeof(DWORD);
2110 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2111 return ERROR_SUCCESS;
2113 case INTERNET_OPTION_URL: {
2114 WCHAR *url;
2115 DWORD res;
2117 TRACE("INTERNET_OPTION_URL\n");
2119 url = compose_request_url(req);
2120 if(!url)
2121 return ERROR_OUTOFMEMORY;
2123 res = str_to_buffer(url, buffer, size, unicode);
2124 heap_free(url);
2125 return res;
2127 case INTERNET_OPTION_USER_AGENT:
2128 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2129 case INTERNET_OPTION_USERNAME:
2130 return str_to_buffer(req->session->userName, buffer, size, unicode);
2131 case INTERNET_OPTION_PASSWORD:
2132 return str_to_buffer(req->session->password, buffer, size, unicode);
2133 case INTERNET_OPTION_PROXY_USERNAME:
2134 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2135 case INTERNET_OPTION_PROXY_PASSWORD:
2136 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2138 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2139 INTERNET_CACHE_ENTRY_INFOW *info;
2140 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2141 DWORD nbytes, error;
2142 BOOL ret;
2144 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2146 if(!req->req_file)
2147 return ERROR_FILE_NOT_FOUND;
2149 if (*size < sizeof(*ts))
2151 *size = sizeof(*ts);
2152 return ERROR_INSUFFICIENT_BUFFER;
2155 nbytes = 0;
2156 ret = GetUrlCacheEntryInfoW(req->req_file->url, NULL, &nbytes);
2157 error = GetLastError();
2158 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2160 if (!(info = heap_alloc(nbytes)))
2161 return ERROR_OUTOFMEMORY;
2163 GetUrlCacheEntryInfoW(req->req_file->url, info, &nbytes);
2165 ts->ftExpires = info->ExpireTime;
2166 ts->ftLastModified = info->LastModifiedTime;
2168 heap_free(info);
2169 *size = sizeof(*ts);
2170 return ERROR_SUCCESS;
2172 return error;
2175 case INTERNET_OPTION_DATAFILE_NAME: {
2176 DWORD req_size;
2178 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2180 if(!req->req_file) {
2181 *size = 0;
2182 return ERROR_INTERNET_ITEM_NOT_FOUND;
2185 if(unicode) {
2186 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2187 if(*size < req_size)
2188 return ERROR_INSUFFICIENT_BUFFER;
2190 *size = req_size;
2191 memcpy(buffer, req->req_file->file_name, *size);
2192 return ERROR_SUCCESS;
2193 }else {
2194 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2195 if (req_size > *size)
2196 return ERROR_INSUFFICIENT_BUFFER;
2198 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2199 -1, buffer, *size, NULL, NULL);
2200 return ERROR_SUCCESS;
2204 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2205 PCCERT_CONTEXT context;
2207 if(!req->netconn)
2208 return ERROR_INTERNET_INVALID_OPERATION;
2210 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2211 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2212 return ERROR_INSUFFICIENT_BUFFER;
2215 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2216 if(context) {
2217 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2218 DWORD len;
2220 memset(info, 0, sizeof(*info));
2221 info->ftExpiry = context->pCertInfo->NotAfter;
2222 info->ftStart = context->pCertInfo->NotBefore;
2223 len = CertNameToStrA(context->dwCertEncodingType,
2224 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2225 info->lpszSubjectInfo = LocalAlloc(0, len);
2226 if(info->lpszSubjectInfo)
2227 CertNameToStrA(context->dwCertEncodingType,
2228 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2229 info->lpszSubjectInfo, len);
2230 len = CertNameToStrA(context->dwCertEncodingType,
2231 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2232 info->lpszIssuerInfo = LocalAlloc(0, len);
2233 if(info->lpszIssuerInfo)
2234 CertNameToStrA(context->dwCertEncodingType,
2235 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2236 info->lpszIssuerInfo, len);
2237 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2238 CertFreeCertificateContext(context);
2239 return ERROR_SUCCESS;
2241 return ERROR_NOT_SUPPORTED;
2243 case INTERNET_OPTION_CONNECT_TIMEOUT:
2244 if (*size < sizeof(DWORD))
2245 return ERROR_INSUFFICIENT_BUFFER;
2247 *size = sizeof(DWORD);
2248 *(DWORD *)buffer = req->connect_timeout;
2249 return ERROR_SUCCESS;
2250 case INTERNET_OPTION_REQUEST_FLAGS: {
2251 DWORD flags = 0;
2253 if (*size < sizeof(DWORD))
2254 return ERROR_INSUFFICIENT_BUFFER;
2256 /* FIXME: Add support for:
2257 * INTERNET_REQFLAG_FROM_CACHE
2258 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2261 if(req->proxy)
2262 flags |= INTERNET_REQFLAG_VIA_PROXY;
2263 if(!req->status_code)
2264 flags |= INTERNET_REQFLAG_NO_HEADERS;
2266 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2268 *size = sizeof(DWORD);
2269 *(DWORD*)buffer = flags;
2270 return ERROR_SUCCESS;
2274 return INET_QueryOption(hdr, option, buffer, size, unicode);
2277 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2279 http_request_t *req = (http_request_t*)hdr;
2281 switch(option) {
2282 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2283 TRACE("Undocumented option 99\n");
2285 if (!buffer || size != sizeof(DWORD))
2286 return ERROR_INVALID_PARAMETER;
2287 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2288 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2290 /* fall through */
2291 case INTERNET_OPTION_SECURITY_FLAGS:
2293 DWORD flags;
2295 if (!buffer || size != sizeof(DWORD))
2296 return ERROR_INVALID_PARAMETER;
2297 flags = *(DWORD *)buffer;
2298 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2299 flags &= SECURITY_SET_MASK;
2300 req->security_flags |= flags;
2301 if(is_valid_netconn(req->netconn))
2302 req->netconn->security_flags |= flags;
2303 return ERROR_SUCCESS;
2305 case INTERNET_OPTION_CONNECT_TIMEOUT:
2306 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2307 req->connect_timeout = *(DWORD *)buffer;
2308 return ERROR_SUCCESS;
2310 case INTERNET_OPTION_SEND_TIMEOUT:
2311 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2312 req->send_timeout = *(DWORD *)buffer;
2313 return ERROR_SUCCESS;
2315 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2316 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2317 req->receive_timeout = *(DWORD *)buffer;
2318 return ERROR_SUCCESS;
2320 case INTERNET_OPTION_USERNAME:
2321 heap_free(req->session->userName);
2322 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2323 return ERROR_SUCCESS;
2325 case INTERNET_OPTION_PASSWORD:
2326 heap_free(req->session->password);
2327 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2328 return ERROR_SUCCESS;
2330 case INTERNET_OPTION_PROXY_USERNAME:
2331 heap_free(req->session->appInfo->proxyUsername);
2332 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2333 return ERROR_SUCCESS;
2335 case INTERNET_OPTION_PROXY_PASSWORD:
2336 heap_free(req->session->appInfo->proxyPassword);
2337 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2338 return ERROR_SUCCESS;
2340 case INTERNET_OPTION_HTTP_DECODING:
2341 if(size != sizeof(BOOL))
2342 return ERROR_INVALID_PARAMETER;
2343 req->decoding = *(BOOL*)buffer;
2344 return ERROR_SUCCESS;
2347 return INET_SetOption(hdr, option, buffer, size);
2350 static void commit_cache_entry(http_request_t *req)
2352 WCHAR *header;
2353 DWORD header_len;
2354 BOOL res;
2356 TRACE("%p\n", req);
2358 CloseHandle(req->hCacheFile);
2359 req->hCacheFile = NULL;
2361 header = build_response_header(req, TRUE);
2362 header_len = (header ? strlenW(header) : 0);
2363 res = CommitUrlCacheEntryW(req->req_file->url, req->req_file->file_name, req->expires,
2364 req->last_modified, NORMAL_CACHE_ENTRY,
2365 header, header_len, NULL, 0);
2366 if(res)
2367 req->req_file->is_committed = TRUE;
2368 else
2369 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2370 heap_free(header);
2373 static void create_cache_entry(http_request_t *req)
2375 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2376 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2378 WCHAR file_name[MAX_PATH+1];
2379 WCHAR *url;
2380 BOOL b = TRUE;
2382 /* FIXME: We should free previous cache file earlier */
2383 if(req->req_file) {
2384 req_file_release(req->req_file);
2385 req->req_file = NULL;
2387 if(req->hCacheFile) {
2388 CloseHandle(req->hCacheFile);
2389 req->hCacheFile = NULL;
2392 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2393 b = FALSE;
2395 if(b) {
2396 int header_idx;
2398 EnterCriticalSection( &req->headers_section );
2400 header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2401 if(header_idx != -1) {
2402 WCHAR *ptr;
2404 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2405 WCHAR *end;
2407 while(*ptr==' ' || *ptr=='\t')
2408 ptr++;
2410 end = strchrW(ptr, ',');
2411 if(!end)
2412 end = ptr + strlenW(ptr);
2414 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2415 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2416 b = FALSE;
2417 break;
2420 ptr = end;
2421 if(*ptr == ',')
2422 ptr++;
2426 LeaveCriticalSection( &req->headers_section );
2429 if(!b) {
2430 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2431 return;
2433 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2436 url = compose_request_url(req);
2437 if(!url) {
2438 WARN("Could not get URL\n");
2439 return;
2442 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2443 if(!b) {
2444 WARN("Could not create cache entry: %08x\n", GetLastError());
2445 return;
2448 create_req_file(file_name, &req->req_file);
2449 req->req_file->url = url;
2451 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2452 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2453 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2454 WARN("Could not create file: %u\n", GetLastError());
2455 req->hCacheFile = NULL;
2456 return;
2459 if(req->read_size) {
2460 DWORD written;
2462 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2463 if(!b)
2464 FIXME("WriteFile failed: %u\n", GetLastError());
2466 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2467 commit_cache_entry(req);
2471 /* read some more data into the read buffer (the read section must be held) */
2472 static DWORD read_more_data( http_request_t *req, int maxlen )
2474 DWORD res;
2475 int len;
2477 if (req->read_pos)
2479 /* move existing data to the start of the buffer */
2480 if(req->read_size)
2481 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2482 req->read_pos = 0;
2485 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2487 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2488 maxlen - req->read_size, TRUE, &len );
2489 if(res == ERROR_SUCCESS)
2490 req->read_size += len;
2492 return res;
2495 /* remove some amount of data from the read buffer (the read section must be held) */
2496 static void remove_data( http_request_t *req, int count )
2498 if (!(req->read_size -= count)) req->read_pos = 0;
2499 else req->read_pos += count;
2502 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2504 int count, bytes_read, pos = 0;
2505 DWORD res;
2507 EnterCriticalSection( &req->read_section );
2508 for (;;)
2510 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2512 if (eol)
2514 count = eol - (req->read_buf + req->read_pos);
2515 bytes_read = count + 1;
2517 else count = bytes_read = req->read_size;
2519 count = min( count, *len - pos );
2520 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2521 pos += count;
2522 remove_data( req, bytes_read );
2523 if (eol) break;
2525 if ((res = read_more_data( req, -1 )))
2527 WARN( "read failed %u\n", res );
2528 LeaveCriticalSection( &req->read_section );
2529 return res;
2531 if (!req->read_size)
2533 *len = 0;
2534 TRACE( "returning empty string\n" );
2535 LeaveCriticalSection( &req->read_section );
2536 return ERROR_SUCCESS;
2539 LeaveCriticalSection( &req->read_section );
2541 if (pos < *len)
2543 if (pos && buffer[pos - 1] == '\r') pos--;
2544 *len = pos + 1;
2546 buffer[*len - 1] = 0;
2547 TRACE( "returning %s\n", debugstr_a(buffer));
2548 return ERROR_SUCCESS;
2551 /* check if we have reached the end of the data to read (the read section must be held) */
2552 static BOOL end_of_read_data( http_request_t *req )
2554 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2557 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, BOOL allow_blocking)
2559 DWORD res;
2561 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, allow_blocking);
2562 if(res != ERROR_SUCCESS)
2563 *read = 0;
2564 assert(*read <= size);
2566 if(req->hCacheFile) {
2567 if(*read) {
2568 BOOL bres;
2569 DWORD written;
2571 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2572 if(!bres)
2573 FIXME("WriteFile failed: %u\n", GetLastError());
2576 if((res == ERROR_SUCCESS && !*read) || req->data_stream->vtbl->end_of_data(req->data_stream, req))
2577 commit_cache_entry(req);
2580 return res;
2583 /* fetch some more data into the read buffer (the read section must be held) */
2584 static DWORD refill_read_buffer(http_request_t *req, BOOL allow_blocking, DWORD *read_bytes)
2586 DWORD res, read=0;
2588 if(req->read_size == sizeof(req->read_buf))
2589 return ERROR_SUCCESS;
2591 if(req->read_pos) {
2592 if(req->read_size)
2593 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2594 req->read_pos = 0;
2597 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2598 &read, allow_blocking);
2599 if(res != ERROR_SUCCESS)
2600 return res;
2602 req->read_size += read;
2604 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2605 if(read_bytes)
2606 *read_bytes = read;
2607 return res;
2610 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2612 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2613 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2616 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2617 DWORD *read, BOOL allow_blocking)
2619 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2620 DWORD res = ERROR_SUCCESS;
2621 int ret = 0;
2623 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2625 if(size && is_valid_netconn(req->netconn)) {
2626 res = NETCON_recv(req->netconn, buf, size, allow_blocking, &ret);
2627 if(res == ERROR_SUCCESS) {
2628 if(!ret)
2629 netconn_stream->content_length = netconn_stream->content_read;
2630 netconn_stream->content_read += ret;
2634 TRACE("res %u read %u bytes\n", res, ret);
2635 *read = ret;
2636 return res;
2639 static DWORD netconn_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
2641 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2642 BYTE buf[1024];
2643 int len, res;
2644 size_t size;
2646 if(netconn_stream->content_length == ~0u)
2647 return WSAEISCONN;
2649 while(netconn_stream->content_read < netconn_stream->content_length) {
2650 size = min(sizeof(buf), netconn_stream->content_length-netconn_stream->content_read);
2651 res = NETCON_recv(req->netconn, buf, size, allow_blocking, &len);
2652 if(res)
2653 return res;
2654 if(!len)
2655 return WSAECONNABORTED;
2657 netconn_stream->content_read += len;
2660 return ERROR_SUCCESS;
2663 static void netconn_destroy(data_stream_t *stream)
2667 static const data_stream_vtbl_t netconn_stream_vtbl = {
2668 netconn_end_of_data,
2669 netconn_read,
2670 netconn_drain_content,
2671 netconn_destroy
2674 static char next_chunked_data_char(chunked_stream_t *stream)
2676 assert(stream->buf_size);
2678 stream->buf_size--;
2679 return stream->buf[stream->buf_pos++];
2682 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2684 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2685 switch(chunked_stream->state) {
2686 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2687 case CHUNKED_STREAM_STATE_END_OF_STREAM:
2688 case CHUNKED_STREAM_STATE_ERROR:
2689 return TRUE;
2690 default:
2691 return FALSE;
2695 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2696 DWORD *read, BOOL allow_blocking)
2698 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2699 DWORD ret_read = 0, res = ERROR_SUCCESS;
2700 BOOL continue_read = TRUE;
2701 int read_bytes;
2702 char ch;
2704 do {
2705 TRACE("state %d\n", chunked_stream->state);
2707 /* Ensure that we have data in the buffer for states that need it. */
2708 if(!chunked_stream->buf_size) {
2709 BOOL blocking_read = allow_blocking;
2711 switch(chunked_stream->state) {
2712 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2713 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2714 /* never allow blocking after 0 chunk size */
2715 if(!chunked_stream->chunk_size)
2716 blocking_read = FALSE;
2717 /* fall through */
2718 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2719 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2720 chunked_stream->buf_pos = 0;
2721 res = NETCON_recv(req->netconn, chunked_stream->buf, sizeof(chunked_stream->buf), blocking_read, &read_bytes);
2722 if(res == ERROR_SUCCESS && read_bytes) {
2723 chunked_stream->buf_size += read_bytes;
2724 }else if(res == WSAEWOULDBLOCK) {
2725 if(ret_read || allow_blocking)
2726 res = ERROR_SUCCESS;
2727 continue_read = FALSE;
2728 continue;
2729 }else {
2730 chunked_stream->state = CHUNKED_STREAM_STATE_ERROR;
2732 break;
2733 default:
2734 break;
2738 switch(chunked_stream->state) {
2739 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2740 ch = next_chunked_data_char(chunked_stream);
2742 if(ch >= '0' && ch <= '9') {
2743 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - '0';
2744 }else if(ch >= 'a' && ch <= 'f') {
2745 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'a' + 10;
2746 }else if (ch >= 'A' && ch <= 'F') {
2747 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'A' + 10;
2748 }else if (ch == ';' || ch == '\r' || ch == '\n') {
2749 TRACE("reading %u byte chunk\n", chunked_stream->chunk_size);
2750 chunked_stream->buf_size++;
2751 chunked_stream->buf_pos--;
2752 if(req->contentLength == ~0u) req->contentLength = chunked_stream->chunk_size;
2753 else req->contentLength += chunked_stream->chunk_size;
2754 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE;
2756 break;
2758 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2759 ch = next_chunked_data_char(chunked_stream);
2760 if(ch == '\n')
2761 chunked_stream->state = chunked_stream->chunk_size
2762 ? CHUNKED_STREAM_STATE_READING_CHUNK
2763 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END;
2764 else if(ch != '\r')
2765 WARN("unexpected char '%c'\n", ch);
2766 break;
2768 case CHUNKED_STREAM_STATE_READING_CHUNK:
2769 assert(chunked_stream->chunk_size);
2770 if(!size) {
2771 continue_read = FALSE;
2772 break;
2774 read_bytes = min(size, chunked_stream->chunk_size);
2776 if(chunked_stream->buf_size) {
2777 if(read_bytes > chunked_stream->buf_size)
2778 read_bytes = chunked_stream->buf_size;
2780 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2781 chunked_stream->buf_pos += read_bytes;
2782 chunked_stream->buf_size -= read_bytes;
2783 }else {
2784 res = NETCON_recv(req->netconn, (char*)buf+ret_read, read_bytes,
2785 allow_blocking, (int*)&read_bytes);
2786 if(res != ERROR_SUCCESS) {
2787 continue_read = FALSE;
2788 break;
2791 if(!read_bytes) {
2792 chunked_stream->state = CHUNKED_STREAM_STATE_ERROR;
2793 continue;
2797 chunked_stream->chunk_size -= read_bytes;
2798 size -= read_bytes;
2799 ret_read += read_bytes;
2800 if(!chunked_stream->chunk_size)
2801 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA;
2802 allow_blocking = FALSE;
2803 break;
2805 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2806 ch = next_chunked_data_char(chunked_stream);
2807 if(ch == '\n')
2808 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2809 else if(ch != '\r')
2810 WARN("unexpected char '%c'\n", ch);
2811 break;
2813 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2814 ch = next_chunked_data_char(chunked_stream);
2815 if(ch == '\n')
2816 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2817 else if(ch != '\r')
2818 WARN("unexpected char '%c'\n", ch);
2819 break;
2821 case CHUNKED_STREAM_STATE_END_OF_STREAM:
2822 case CHUNKED_STREAM_STATE_ERROR:
2823 continue_read = FALSE;
2824 break;
2826 } while(continue_read);
2828 if(ret_read)
2829 res = ERROR_SUCCESS;
2830 if(res != ERROR_SUCCESS)
2831 return res;
2833 TRACE("read %d bytes\n", ret_read);
2834 *read = ret_read;
2835 return ERROR_SUCCESS;
2838 static DWORD chunked_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
2840 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2841 BYTE buf[1024];
2842 DWORD size, res;
2844 while(chunked_stream->state != CHUNKED_STREAM_STATE_END_OF_STREAM
2845 && chunked_stream->state != CHUNKED_STREAM_STATE_ERROR) {
2846 res = chunked_read(stream, req, buf, sizeof(buf), &size, allow_blocking);
2847 if(res != ERROR_SUCCESS)
2848 return res;
2851 if(chunked_stream->state != CHUNKED_STREAM_STATE_END_OF_STREAM)
2852 return ERROR_NO_DATA;
2853 return ERROR_SUCCESS;
2856 static void chunked_destroy(data_stream_t *stream)
2858 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2859 heap_free(chunked_stream);
2862 static const data_stream_vtbl_t chunked_stream_vtbl = {
2863 chunked_end_of_data,
2864 chunked_read,
2865 chunked_drain_content,
2866 chunked_destroy
2869 /* set the request content length based on the headers */
2870 static DWORD set_content_length(http_request_t *request)
2872 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2873 static const WCHAR headW[] = {'H','E','A','D',0};
2874 WCHAR encoding[20];
2875 DWORD size;
2877 if(request->status_code == HTTP_STATUS_NO_CONTENT || !strcmpW(request->verb, headW)) {
2878 request->contentLength = request->netconn_stream.content_length = 0;
2879 return ERROR_SUCCESS;
2882 size = sizeof(request->contentLength);
2883 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2884 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2885 request->contentLength = ~0u;
2886 request->netconn_stream.content_length = request->contentLength;
2887 request->netconn_stream.content_read = request->read_size;
2889 size = sizeof(encoding);
2890 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2891 !strcmpiW(encoding, szChunked))
2893 chunked_stream_t *chunked_stream;
2895 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2896 if(!chunked_stream)
2897 return ERROR_OUTOFMEMORY;
2899 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2900 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2901 chunked_stream->chunk_size = 0;
2902 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2904 if(request->read_size) {
2905 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2906 chunked_stream->buf_size = request->read_size;
2907 request->read_size = request->read_pos = 0;
2910 request->data_stream = &chunked_stream->data_stream;
2911 request->contentLength = ~0u;
2914 if(request->decoding) {
2915 int encoding_idx;
2917 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2918 static const WCHAR gzipW[] = {'g','z','i','p',0};
2920 EnterCriticalSection( &request->headers_section );
2922 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2923 if(encoding_idx != -1) {
2924 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2925 HTTP_DeleteCustomHeader(request, encoding_idx);
2926 LeaveCriticalSection( &request->headers_section );
2927 return init_gzip_stream(request, TRUE);
2929 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2930 HTTP_DeleteCustomHeader(request, encoding_idx);
2931 LeaveCriticalSection( &request->headers_section );
2932 return init_gzip_stream(request, FALSE);
2936 LeaveCriticalSection( &request->headers_section );
2939 return ERROR_SUCCESS;
2942 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2944 INTERNET_ASYNC_RESULT iar;
2946 iar.dwResult = result;
2947 iar.dwError = error;
2949 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2950 sizeof(INTERNET_ASYNC_RESULT));
2953 static void HTTP_ReceiveRequestData(http_request_t *req)
2955 DWORD res, read = 0;
2957 TRACE("%p\n", req);
2959 EnterCriticalSection( &req->read_section );
2961 res = refill_read_buffer(req, FALSE, &read);
2962 if(res == ERROR_SUCCESS)
2963 read += req->read_size;
2965 LeaveCriticalSection( &req->read_section );
2967 if(res != WSAEWOULDBLOCK && (res != ERROR_SUCCESS || !read)) {
2968 WARN("res %u read %u, closing connection\n", res, read);
2969 http_release_netconn(req, FALSE);
2972 if(res != ERROR_SUCCESS && res != WSAEWOULDBLOCK) {
2973 send_request_complete(req, 0, res);
2974 return;
2977 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, 0);
2980 /* read data from the http connection (the read section must be held) */
2981 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL allow_blocking)
2983 DWORD current_read = 0, ret_read = 0;
2984 DWORD res = ERROR_SUCCESS;
2986 EnterCriticalSection( &req->read_section );
2988 if(req->read_size) {
2989 ret_read = min(size, req->read_size);
2990 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
2991 req->read_size -= ret_read;
2992 req->read_pos += ret_read;
2993 allow_blocking = FALSE;
2996 if(ret_read < size) {
2997 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, allow_blocking);
2998 if(res == ERROR_SUCCESS)
2999 ret_read += current_read;
3000 else if(res == WSAEWOULDBLOCK && ret_read)
3001 res = ERROR_SUCCESS;
3004 LeaveCriticalSection( &req->read_section );
3006 *read = ret_read;
3007 TRACE( "retrieved %u bytes (res %u)\n", ret_read, res );
3009 if(res != WSAEWOULDBLOCK) {
3010 if(res != ERROR_SUCCESS)
3011 http_release_netconn(req, FALSE);
3012 else if(!ret_read && drain_content(req, FALSE) == ERROR_SUCCESS)
3013 http_release_netconn(req, TRUE);
3016 return res;
3019 static DWORD drain_content(http_request_t *req, BOOL blocking)
3021 DWORD res;
3023 TRACE("%p\n", req->netconn);
3025 if(!is_valid_netconn(req->netconn))
3026 return ERROR_NO_DATA;
3028 if(!strcmpW(req->verb, szHEAD))
3029 return ERROR_SUCCESS;
3031 EnterCriticalSection( &req->read_section );
3032 res = req->data_stream->vtbl->drain_content(req->data_stream, req, blocking);
3033 LeaveCriticalSection( &req->read_section );
3034 return res;
3037 typedef struct {
3038 task_header_t hdr;
3039 void *buf;
3040 DWORD size;
3041 DWORD read_pos;
3042 DWORD *ret_read;
3043 } read_file_task_t;
3045 static void async_read_file_proc(task_header_t *hdr)
3047 read_file_task_t *task = (read_file_task_t*)hdr;
3048 http_request_t *req = (http_request_t*)task->hdr.hdr;
3049 DWORD res = ERROR_SUCCESS, read = task->read_pos, complete_arg = 0;
3051 TRACE("req %p buf %p size %u read_pos %u ret_read %p\n", req, task->buf, task->size, task->read_pos, task->ret_read);
3053 if(task->buf) {
3054 DWORD read_bytes;
3055 while (read < task->size) {
3056 res = HTTPREQ_Read(req, (char*)task->buf + read, task->size - read, &read_bytes, TRUE);
3057 if (res != ERROR_SUCCESS || !read_bytes)
3058 break;
3059 read += read_bytes;
3061 }else {
3062 EnterCriticalSection(&req->read_section);
3063 res = refill_read_buffer(req, TRUE, &read);
3064 LeaveCriticalSection(&req->read_section);
3066 if(task->ret_read)
3067 complete_arg = read; /* QueryDataAvailable reports read bytes in request complete notification */
3068 if(res != ERROR_SUCCESS || !read)
3069 http_release_netconn(req, drain_content(req, FALSE) == ERROR_SUCCESS);
3072 TRACE("res %u read %u\n", res, read);
3074 if(task->ret_read)
3075 *task->ret_read = read;
3077 /* FIXME: We should report bytes transferred before decoding content. */
3078 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED, &read, sizeof(read));
3080 if(res != ERROR_SUCCESS)
3081 complete_arg = res;
3082 send_request_complete(req, res == ERROR_SUCCESS, complete_arg);
3085 static DWORD async_read(http_request_t *req, void *buf, DWORD size, DWORD read_pos, DWORD *ret_read)
3087 read_file_task_t *task;
3089 task = alloc_async_task(&req->hdr, async_read_file_proc, sizeof(*task));
3090 if(!task)
3091 return ERROR_OUTOFMEMORY;
3093 task->buf = buf;
3094 task->size = size;
3095 task->read_pos = read_pos;
3096 task->ret_read = ret_read;
3098 INTERNET_AsyncCall(&task->hdr);
3099 return ERROR_IO_PENDING;
3102 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3103 DWORD flags, DWORD_PTR context)
3105 http_request_t *req = (http_request_t*)hdr;
3106 DWORD res = ERROR_SUCCESS, read = 0, cread, error = ERROR_SUCCESS;
3107 BOOL allow_blocking, notify_received = FALSE;
3109 TRACE("(%p %p %u %x)\n", req, buf, size, flags);
3111 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3112 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3114 allow_blocking = !(req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC);
3116 if(allow_blocking || TryEnterCriticalSection(&req->read_section)) {
3117 if(allow_blocking)
3118 EnterCriticalSection(&req->read_section);
3119 if(hdr->dwError == ERROR_SUCCESS)
3120 hdr->dwError = INTERNET_HANDLE_IN_USE;
3121 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3122 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3124 if(req->read_size) {
3125 read = min(size, req->read_size);
3126 memcpy(buf, req->read_buf + req->read_pos, read);
3127 req->read_size -= read;
3128 req->read_pos += read;
3131 if(read < size && (!read || !(flags & IRF_NO_WAIT)) && !end_of_read_data(req)) {
3132 LeaveCriticalSection(&req->read_section);
3133 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3134 EnterCriticalSection( &req->read_section );
3135 notify_received = TRUE;
3137 while(read < size) {
3138 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, allow_blocking);
3139 read += cread;
3140 if (res != ERROR_SUCCESS || !cread)
3141 break;
3145 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3146 hdr->dwError = ERROR_SUCCESS;
3147 else
3148 error = hdr->dwError;
3150 LeaveCriticalSection( &req->read_section );
3151 }else {
3152 res = WSAEWOULDBLOCK;
3155 if(res == WSAEWOULDBLOCK) {
3156 if(!(flags & IRF_NO_WAIT))
3157 return async_read(req, buf, size, read, ret_read);
3158 if(!read)
3159 return async_read(req, NULL, 0, 0, NULL);
3160 res = ERROR_SUCCESS;
3163 *ret_read = read;
3164 if (res != ERROR_SUCCESS)
3165 return res;
3167 if(notify_received)
3168 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3169 &read, sizeof(read));
3170 return error;
3173 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3175 DWORD res;
3176 http_request_t *request = (http_request_t*)hdr;
3178 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3180 *written = 0;
3181 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3182 if (res == ERROR_SUCCESS)
3183 request->bytesWritten += *written;
3185 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3186 return res;
3189 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3191 http_request_t *req = (http_request_t*)hdr;
3192 DWORD res = ERROR_SUCCESS, avail = 0, error = ERROR_SUCCESS;
3193 BOOL allow_blocking, notify_received = FALSE;
3195 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3197 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3198 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3200 *available = 0;
3201 allow_blocking = !(req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC);
3203 if(allow_blocking || TryEnterCriticalSection(&req->read_section)) {
3204 if(allow_blocking)
3205 EnterCriticalSection(&req->read_section);
3206 if(hdr->dwError == ERROR_SUCCESS)
3207 hdr->dwError = INTERNET_HANDLE_IN_USE;
3208 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3209 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3211 avail = req->read_size;
3213 if(!avail && !end_of_read_data(req)) {
3214 LeaveCriticalSection(&req->read_section);
3215 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3216 EnterCriticalSection( &req->read_section );
3217 notify_received = TRUE;
3219 res = refill_read_buffer(req, allow_blocking, &avail);
3222 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3223 hdr->dwError = ERROR_SUCCESS;
3224 else
3225 error = hdr->dwError;
3227 LeaveCriticalSection( &req->read_section );
3228 }else {
3229 res = WSAEWOULDBLOCK;
3232 if(res == WSAEWOULDBLOCK)
3233 return async_read(req, NULL, 0, 0, available);
3235 if (res != ERROR_SUCCESS)
3236 return res;
3238 *available = avail;
3239 if(notify_received)
3240 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3241 &avail, sizeof(avail));
3242 return error;
3245 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3247 http_request_t *req = (http_request_t*)hdr;
3249 TRACE("(%p)\n", req);
3251 if(!req->req_file) {
3252 WARN("No cache file name available\n");
3253 return ERROR_FILE_NOT_FOUND;
3256 *ret = req_file_addref(req->req_file);
3257 return ERROR_SUCCESS;
3260 static const object_vtbl_t HTTPREQVtbl = {
3261 HTTPREQ_Destroy,
3262 HTTPREQ_CloseConnection,
3263 HTTPREQ_QueryOption,
3264 HTTPREQ_SetOption,
3265 HTTPREQ_ReadFile,
3266 HTTPREQ_WriteFile,
3267 HTTPREQ_QueryDataAvailable,
3268 NULL,
3269 HTTPREQ_LockRequestFile
3272 /***********************************************************************
3273 * HTTP_HttpOpenRequestW (internal)
3275 * Open a HTTP request handle
3277 * RETURNS
3278 * HINTERNET a HTTP request handle on success
3279 * NULL on failure
3282 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3283 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3284 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3285 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3287 appinfo_t *hIC = session->appInfo;
3288 http_request_t *request;
3289 DWORD port, len;
3291 TRACE("-->\n");
3293 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3294 if(!request)
3295 return ERROR_OUTOFMEMORY;
3297 request->hdr.htype = WH_HHTTPREQ;
3298 request->hdr.dwFlags = dwFlags;
3299 request->hdr.dwContext = dwContext;
3300 request->contentLength = ~0u;
3302 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3303 request->data_stream = &request->netconn_stream.data_stream;
3304 request->connect_timeout = session->connect_timeout;
3305 request->send_timeout = session->send_timeout;
3306 request->receive_timeout = session->receive_timeout;
3308 InitializeCriticalSection( &request->headers_section );
3309 request->headers_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.headers_section");
3311 InitializeCriticalSection( &request->read_section );
3312 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3314 WININET_AddRef( &session->hdr );
3315 request->session = session;
3316 list_add_head( &session->hdr.children, &request->hdr.entry );
3318 port = session->hostPort;
3319 if (port == INTERNET_INVALID_PORT_NUMBER)
3320 port = (session->hdr.dwFlags & INTERNET_FLAG_SECURE) ?
3321 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
3323 request->server = get_server(substrz(session->hostName), port, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3324 if(!request->server) {
3325 WININET_Release(&request->hdr);
3326 return ERROR_OUTOFMEMORY;
3329 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3330 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3331 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3332 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3334 if (lpszObjectName && *lpszObjectName) {
3335 HRESULT rc;
3336 WCHAR dummy;
3338 len = 1;
3339 rc = UrlCanonicalizeW(lpszObjectName, &dummy, &len, URL_ESCAPE_SPACES_ONLY);
3340 if (rc != E_POINTER)
3341 len = strlenW(lpszObjectName)+1;
3342 request->path = heap_alloc(len*sizeof(WCHAR));
3343 rc = UrlCanonicalizeW(lpszObjectName, request->path, &len,
3344 URL_ESCAPE_SPACES_ONLY);
3345 if (rc != S_OK)
3347 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3348 strcpyW(request->path,lpszObjectName);
3350 }else {
3351 static const WCHAR slashW[] = {'/',0};
3353 request->path = heap_strdupW(slashW);
3356 if (lpszReferrer && *lpszReferrer)
3357 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3359 if (lpszAcceptTypes)
3361 int i;
3362 for (i = 0; lpszAcceptTypes[i]; i++)
3364 if (!*lpszAcceptTypes[i]) continue;
3365 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3366 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3367 HTTP_ADDHDR_FLAG_REQ |
3368 (i == 0 ? (HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD) : 0));
3372 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3373 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3375 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3376 HTTP_DealWithProxy( hIC, session, request );
3378 INTERNET_SendCallback(&session->hdr, dwContext,
3379 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3380 sizeof(HINTERNET));
3382 TRACE("<-- (%p)\n", request);
3384 *ret = request->hdr.hInternet;
3385 return ERROR_SUCCESS;
3388 /***********************************************************************
3389 * HttpOpenRequestW (WININET.@)
3391 * Open a HTTP request handle
3393 * RETURNS
3394 * HINTERNET a HTTP request handle on success
3395 * NULL on failure
3398 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3399 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3400 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3401 DWORD dwFlags, DWORD_PTR dwContext)
3403 http_session_t *session;
3404 HINTERNET handle = NULL;
3405 DWORD res;
3407 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3408 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3409 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3410 dwFlags, dwContext);
3411 if(lpszAcceptTypes!=NULL)
3413 int i;
3414 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3415 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3418 session = (http_session_t*) get_handle_object( hHttpSession );
3419 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3421 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3422 goto lend;
3426 * My tests seem to show that the windows version does not
3427 * become asynchronous until after this point. And anyhow
3428 * if this call was asynchronous then how would you get the
3429 * necessary HINTERNET pointer returned by this function.
3432 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3433 lpszVersion, lpszReferrer, lpszAcceptTypes,
3434 dwFlags, dwContext, &handle);
3435 lend:
3436 if( session )
3437 WININET_Release( &session->hdr );
3438 TRACE("returning %p\n", handle);
3439 if(res != ERROR_SUCCESS)
3440 SetLastError(res);
3441 return handle;
3444 static const LPCWSTR header_lookup[] = {
3445 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3446 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3447 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3448 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3449 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3450 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3451 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3452 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3453 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3454 szDate, /* HTTP_QUERY_DATE = 9 */
3455 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3456 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3457 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3458 szURI, /* HTTP_QUERY_URI = 13 */
3459 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3460 NULL, /* HTTP_QUERY_COST = 15 */
3461 NULL, /* HTTP_QUERY_LINK = 16 */
3462 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3463 NULL, /* HTTP_QUERY_VERSION = 18 */
3464 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3465 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3466 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3467 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3468 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3469 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3470 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3471 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3472 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3473 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3474 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3475 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3476 NULL, /* HTTP_QUERY_FROM = 31 */
3477 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3478 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3479 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3480 szReferer, /* HTTP_QUERY_REFERER = 35 */
3481 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3482 szServer, /* HTTP_QUERY_SERVER = 37 */
3483 NULL, /* HTTP_TITLE = 38 */
3484 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3485 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3486 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3487 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3488 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3489 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3490 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3491 NULL, /* HTTP_QUERY_REFRESH = 46 */
3492 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3493 szAge, /* HTTP_QUERY_AGE = 48 */
3494 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3495 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3496 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3497 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3498 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3499 szETag, /* HTTP_QUERY_ETAG = 54 */
3500 hostW, /* HTTP_QUERY_HOST = 55 */
3501 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3502 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3503 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3504 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3505 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3506 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3507 szRange, /* HTTP_QUERY_RANGE = 62 */
3508 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3509 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3510 szVary, /* HTTP_QUERY_VARY = 65 */
3511 szVia, /* HTTP_QUERY_VIA = 66 */
3512 szWarning, /* HTTP_QUERY_WARNING = 67 */
3513 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3514 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3515 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3518 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3520 /***********************************************************************
3521 * HTTP_HttpQueryInfoW (internal)
3523 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3524 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3526 LPHTTPHEADERW lphttpHdr = NULL;
3527 BOOL request_only = !!(dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS);
3528 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3529 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3530 INT index = -1;
3532 EnterCriticalSection( &request->headers_section );
3534 /* Find requested header structure */
3535 switch (level)
3537 case HTTP_QUERY_CUSTOM:
3538 if (!lpBuffer)
3540 LeaveCriticalSection( &request->headers_section );
3541 return ERROR_INVALID_PARAMETER;
3543 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3544 break;
3545 case HTTP_QUERY_RAW_HEADERS_CRLF:
3547 LPWSTR headers;
3548 DWORD len = 0;
3549 DWORD res = ERROR_INVALID_PARAMETER;
3551 if (request_only)
3552 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3553 else
3554 headers = build_response_header(request, TRUE);
3555 if (!headers)
3557 LeaveCriticalSection( &request->headers_section );
3558 return ERROR_OUTOFMEMORY;
3561 len = strlenW(headers) * sizeof(WCHAR);
3562 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3564 len += sizeof(WCHAR);
3565 res = ERROR_INSUFFICIENT_BUFFER;
3567 else if (lpBuffer)
3569 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3570 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3571 res = ERROR_SUCCESS;
3573 *lpdwBufferLength = len;
3575 heap_free(headers);
3576 LeaveCriticalSection( &request->headers_section );
3577 return res;
3579 case HTTP_QUERY_RAW_HEADERS:
3581 LPWSTR headers;
3582 DWORD len;
3584 if (request_only)
3585 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3586 else
3587 headers = build_response_header(request, FALSE);
3589 if (!headers)
3591 LeaveCriticalSection( &request->headers_section );
3592 return ERROR_OUTOFMEMORY;
3595 len = strlenW(headers) * sizeof(WCHAR);
3596 if (len > *lpdwBufferLength)
3598 *lpdwBufferLength = len;
3599 heap_free(headers);
3600 LeaveCriticalSection( &request->headers_section );
3601 return ERROR_INSUFFICIENT_BUFFER;
3604 if (lpBuffer)
3606 DWORD i;
3608 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3610 for (i = 0; i < len / sizeof(WCHAR); i++)
3612 if (headers[i] == '\n')
3613 headers[i] = 0;
3615 memcpy(lpBuffer, headers, len);
3617 *lpdwBufferLength = len - sizeof(WCHAR);
3619 heap_free(headers);
3620 LeaveCriticalSection( &request->headers_section );
3621 return ERROR_SUCCESS;
3623 case HTTP_QUERY_STATUS_TEXT:
3624 if (request->statusText)
3626 DWORD len = strlenW(request->statusText);
3627 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3629 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3630 LeaveCriticalSection( &request->headers_section );
3631 return ERROR_INSUFFICIENT_BUFFER;
3633 if (lpBuffer)
3635 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3636 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3638 *lpdwBufferLength = len * sizeof(WCHAR);
3639 LeaveCriticalSection( &request->headers_section );
3640 return ERROR_SUCCESS;
3642 break;
3643 case HTTP_QUERY_VERSION:
3644 if (request->version)
3646 DWORD len = strlenW(request->version);
3647 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3649 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3650 LeaveCriticalSection( &request->headers_section );
3651 return ERROR_INSUFFICIENT_BUFFER;
3653 if (lpBuffer)
3655 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3656 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3658 *lpdwBufferLength = len * sizeof(WCHAR);
3659 LeaveCriticalSection( &request->headers_section );
3660 return ERROR_SUCCESS;
3662 break;
3663 case HTTP_QUERY_CONTENT_ENCODING:
3664 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3665 requested_index,request_only);
3666 break;
3667 case HTTP_QUERY_STATUS_CODE: {
3668 DWORD res = ERROR_SUCCESS;
3670 if(request_only)
3672 LeaveCriticalSection( &request->headers_section );
3673 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3676 if(requested_index)
3677 break;
3679 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3680 if(*lpdwBufferLength >= sizeof(DWORD))
3681 *(DWORD*)lpBuffer = request->status_code;
3682 else
3683 res = ERROR_INSUFFICIENT_BUFFER;
3684 *lpdwBufferLength = sizeof(DWORD);
3685 }else {
3686 WCHAR buf[12];
3687 DWORD size;
3688 static const WCHAR formatW[] = {'%','u',0};
3690 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3692 if(size <= *lpdwBufferLength) {
3693 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3694 }else {
3695 size += sizeof(WCHAR);
3696 res = ERROR_INSUFFICIENT_BUFFER;
3699 *lpdwBufferLength = size;
3701 LeaveCriticalSection( &request->headers_section );
3702 return res;
3704 default:
3705 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3707 if (level < LAST_TABLE_HEADER && header_lookup[level])
3708 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3709 requested_index,request_only);
3712 if (index >= 0)
3713 lphttpHdr = &request->custHeaders[index];
3715 /* Ensure header satisfies requested attributes */
3716 if (!lphttpHdr ||
3717 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3718 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3720 LeaveCriticalSection( &request->headers_section );
3721 return ERROR_HTTP_HEADER_NOT_FOUND;
3724 /* coalesce value to requested type */
3725 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3727 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3728 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3730 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3732 time_t tmpTime;
3733 struct tm tmpTM;
3734 SYSTEMTIME *STHook;
3736 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3738 tmpTM = *gmtime(&tmpTime);
3739 STHook = (SYSTEMTIME *)lpBuffer;
3740 STHook->wDay = tmpTM.tm_mday;
3741 STHook->wHour = tmpTM.tm_hour;
3742 STHook->wMilliseconds = 0;
3743 STHook->wMinute = tmpTM.tm_min;
3744 STHook->wDayOfWeek = tmpTM.tm_wday;
3745 STHook->wMonth = tmpTM.tm_mon + 1;
3746 STHook->wSecond = tmpTM.tm_sec;
3747 STHook->wYear = 1900+tmpTM.tm_year;
3749 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3750 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3751 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3753 else if (lphttpHdr->lpszValue)
3755 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3757 if (len > *lpdwBufferLength)
3759 *lpdwBufferLength = len;
3760 LeaveCriticalSection( &request->headers_section );
3761 return ERROR_INSUFFICIENT_BUFFER;
3763 if (lpBuffer)
3765 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3766 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3768 *lpdwBufferLength = len - sizeof(WCHAR);
3770 if (lpdwIndex) (*lpdwIndex)++;
3772 LeaveCriticalSection( &request->headers_section );
3773 return ERROR_SUCCESS;
3776 /***********************************************************************
3777 * HttpQueryInfoW (WININET.@)
3779 * Queries for information about an HTTP request
3781 * RETURNS
3782 * TRUE on success
3783 * FALSE on failure
3786 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3787 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3789 http_request_t *request;
3790 DWORD res;
3792 if (TRACE_ON(wininet)) {
3793 #define FE(x) { x, #x }
3794 static const wininet_flag_info query_flags[] = {
3795 FE(HTTP_QUERY_MIME_VERSION),
3796 FE(HTTP_QUERY_CONTENT_TYPE),
3797 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3798 FE(HTTP_QUERY_CONTENT_ID),
3799 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3800 FE(HTTP_QUERY_CONTENT_LENGTH),
3801 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3802 FE(HTTP_QUERY_ALLOW),
3803 FE(HTTP_QUERY_PUBLIC),
3804 FE(HTTP_QUERY_DATE),
3805 FE(HTTP_QUERY_EXPIRES),
3806 FE(HTTP_QUERY_LAST_MODIFIED),
3807 FE(HTTP_QUERY_MESSAGE_ID),
3808 FE(HTTP_QUERY_URI),
3809 FE(HTTP_QUERY_DERIVED_FROM),
3810 FE(HTTP_QUERY_COST),
3811 FE(HTTP_QUERY_LINK),
3812 FE(HTTP_QUERY_PRAGMA),
3813 FE(HTTP_QUERY_VERSION),
3814 FE(HTTP_QUERY_STATUS_CODE),
3815 FE(HTTP_QUERY_STATUS_TEXT),
3816 FE(HTTP_QUERY_RAW_HEADERS),
3817 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3818 FE(HTTP_QUERY_CONNECTION),
3819 FE(HTTP_QUERY_ACCEPT),
3820 FE(HTTP_QUERY_ACCEPT_CHARSET),
3821 FE(HTTP_QUERY_ACCEPT_ENCODING),
3822 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3823 FE(HTTP_QUERY_AUTHORIZATION),
3824 FE(HTTP_QUERY_CONTENT_ENCODING),
3825 FE(HTTP_QUERY_FORWARDED),
3826 FE(HTTP_QUERY_FROM),
3827 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3828 FE(HTTP_QUERY_LOCATION),
3829 FE(HTTP_QUERY_ORIG_URI),
3830 FE(HTTP_QUERY_REFERER),
3831 FE(HTTP_QUERY_RETRY_AFTER),
3832 FE(HTTP_QUERY_SERVER),
3833 FE(HTTP_QUERY_TITLE),
3834 FE(HTTP_QUERY_USER_AGENT),
3835 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3836 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3837 FE(HTTP_QUERY_ACCEPT_RANGES),
3838 FE(HTTP_QUERY_SET_COOKIE),
3839 FE(HTTP_QUERY_COOKIE),
3840 FE(HTTP_QUERY_REQUEST_METHOD),
3841 FE(HTTP_QUERY_REFRESH),
3842 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3843 FE(HTTP_QUERY_AGE),
3844 FE(HTTP_QUERY_CACHE_CONTROL),
3845 FE(HTTP_QUERY_CONTENT_BASE),
3846 FE(HTTP_QUERY_CONTENT_LOCATION),
3847 FE(HTTP_QUERY_CONTENT_MD5),
3848 FE(HTTP_QUERY_CONTENT_RANGE),
3849 FE(HTTP_QUERY_ETAG),
3850 FE(HTTP_QUERY_HOST),
3851 FE(HTTP_QUERY_IF_MATCH),
3852 FE(HTTP_QUERY_IF_NONE_MATCH),
3853 FE(HTTP_QUERY_IF_RANGE),
3854 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3855 FE(HTTP_QUERY_MAX_FORWARDS),
3856 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3857 FE(HTTP_QUERY_RANGE),
3858 FE(HTTP_QUERY_TRANSFER_ENCODING),
3859 FE(HTTP_QUERY_UPGRADE),
3860 FE(HTTP_QUERY_VARY),
3861 FE(HTTP_QUERY_VIA),
3862 FE(HTTP_QUERY_WARNING),
3863 FE(HTTP_QUERY_CUSTOM)
3865 static const wininet_flag_info modifier_flags[] = {
3866 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3867 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3868 FE(HTTP_QUERY_FLAG_NUMBER),
3869 FE(HTTP_QUERY_FLAG_COALESCE)
3871 #undef FE
3872 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3873 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3874 DWORD i;
3876 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3877 TRACE(" Attribute:");
3878 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3879 if (query_flags[i].val == info) {
3880 TRACE(" %s", query_flags[i].name);
3881 break;
3884 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3885 TRACE(" Unknown (%08x)", info);
3888 TRACE(" Modifier:");
3889 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3890 if (modifier_flags[i].val & info_mod) {
3891 TRACE(" %s", modifier_flags[i].name);
3892 info_mod &= ~ modifier_flags[i].val;
3896 if (info_mod) {
3897 TRACE(" Unknown (%08x)", info_mod);
3899 TRACE("\n");
3902 request = (http_request_t*) get_handle_object( hHttpRequest );
3903 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3905 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3906 goto lend;
3909 if (lpBuffer == NULL)
3910 *lpdwBufferLength = 0;
3911 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3912 lpBuffer, lpdwBufferLength, lpdwIndex);
3914 lend:
3915 if( request )
3916 WININET_Release( &request->hdr );
3918 TRACE("%u <--\n", res);
3919 if(res != ERROR_SUCCESS)
3920 SetLastError(res);
3921 return res == ERROR_SUCCESS;
3924 /***********************************************************************
3925 * HttpQueryInfoA (WININET.@)
3927 * Queries for information about an HTTP request
3929 * RETURNS
3930 * TRUE on success
3931 * FALSE on failure
3934 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3935 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3937 BOOL result;
3938 DWORD len;
3939 WCHAR* bufferW;
3941 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3943 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3944 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3946 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3947 lpdwBufferLength, lpdwIndex );
3950 if (lpBuffer)
3952 DWORD alloclen;
3953 len = (*lpdwBufferLength)*sizeof(WCHAR);
3954 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3956 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3957 if (alloclen < len)
3958 alloclen = len;
3960 else
3961 alloclen = len;
3962 bufferW = heap_alloc(alloclen);
3963 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3964 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3965 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3966 } else
3968 bufferW = NULL;
3969 len = 0;
3972 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3973 &len, lpdwIndex );
3974 if( result )
3976 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3977 lpBuffer, *lpdwBufferLength, NULL, NULL );
3978 *lpdwBufferLength = len - 1;
3980 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3982 else
3983 /* since the strings being returned from HttpQueryInfoW should be
3984 * only ASCII characters, it is reasonable to assume that all of
3985 * the Unicode characters can be reduced to a single byte */
3986 *lpdwBufferLength = len / sizeof(WCHAR);
3988 heap_free( bufferW );
3989 return result;
3992 static WCHAR *get_redirect_url(http_request_t *request)
3994 static WCHAR szHttp[] = {'h','t','t','p',0};
3995 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3996 http_session_t *session = request->session;
3997 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
3998 WCHAR *orig_url = NULL, *redirect_url = NULL, *combined_url = NULL;
3999 DWORD url_length = 0, res;
4000 BOOL b;
4002 url_length = 0;
4003 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4004 if(res == ERROR_INSUFFICIENT_BUFFER) {
4005 redirect_url = heap_alloc(url_length);
4006 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4008 if(res != ERROR_SUCCESS) {
4009 heap_free(redirect_url);
4010 return NULL;
4013 urlComponents.dwSchemeLength = 1;
4014 b = InternetCrackUrlW(redirect_url, url_length / sizeof(WCHAR), 0, &urlComponents);
4015 if(b && urlComponents.dwSchemeLength &&
4016 urlComponents.nScheme != INTERNET_SCHEME_HTTP && urlComponents.nScheme != INTERNET_SCHEME_HTTPS) {
4017 TRACE("redirect to non-http URL\n");
4018 return NULL;
4021 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
4022 urlComponents.dwSchemeLength = 0;
4023 urlComponents.lpszHostName = request->server->name;
4024 urlComponents.nPort = request->server->port;
4025 urlComponents.lpszUserName = session->userName;
4026 urlComponents.lpszUrlPath = request->path;
4028 b = InternetCreateUrlW(&urlComponents, 0, NULL, &url_length);
4029 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4030 orig_url = heap_alloc(url_length);
4032 /* convert from bytes to characters */
4033 url_length = url_length / sizeof(WCHAR) - 1;
4034 b = InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length);
4037 if(b) {
4038 url_length = 0;
4039 b = InternetCombineUrlW(orig_url, redirect_url, NULL, &url_length, ICU_ENCODE_SPACES_ONLY);
4040 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4041 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4042 b = InternetCombineUrlW(orig_url, redirect_url, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY);
4043 if(!b) {
4044 heap_free(combined_url);
4045 combined_url = NULL;
4050 heap_free(orig_url);
4051 heap_free(redirect_url);
4052 return combined_url;
4056 /***********************************************************************
4057 * HTTP_HandleRedirect (internal)
4059 static DWORD HTTP_HandleRedirect(http_request_t *request, WCHAR *url)
4061 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4062 http_session_t *session = request->session;
4063 size_t url_len = strlenW(url);
4065 if(url[0] == '/')
4067 /* if it's an absolute path, keep the same session info */
4068 urlComponents.lpszUrlPath = url;
4069 urlComponents.dwUrlPathLength = url_len;
4071 else
4073 urlComponents.dwHostNameLength = 1;
4074 urlComponents.dwUserNameLength = 1;
4075 urlComponents.dwUrlPathLength = 1;
4076 if(!InternetCrackUrlW(url, url_len, 0, &urlComponents))
4077 return INTERNET_GetLastError();
4079 if(!urlComponents.dwHostNameLength)
4080 return ERROR_INTERNET_INVALID_URL;
4083 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
4084 url, (url_len + 1) * sizeof(WCHAR));
4086 if(urlComponents.dwHostNameLength) {
4087 BOOL custom_port = FALSE;
4088 substr_t host;
4090 if(urlComponents.nScheme == INTERNET_SCHEME_HTTP) {
4091 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4092 TRACE("redirect from secure page to non-secure page\n");
4093 /* FIXME: warn about from secure redirect to non-secure page */
4094 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4097 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT;
4098 }else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS) {
4099 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4100 TRACE("redirect from non-secure page to secure page\n");
4101 /* FIXME: notify about redirect to secure page */
4102 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4105 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT;
4108 heap_free(session->hostName);
4110 session->hostName = heap_strndupW(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4111 session->hostPort = urlComponents.nPort;
4113 heap_free(session->userName);
4114 session->userName = NULL;
4115 if (urlComponents.dwUserNameLength)
4116 session->userName = heap_strndupW(urlComponents.lpszUserName, urlComponents.dwUserNameLength);
4118 reset_data_stream(request);
4120 host = substr(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4122 if(host.len != strlenW(request->server->name) || strncmpiW(request->server->name, host.str, host.len)
4123 || request->server->port != urlComponents.nPort) {
4124 server_t *new_server;
4126 new_server = get_server(host, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4127 server_release(request->server);
4128 request->server = new_server;
4131 if (custom_port)
4132 HTTP_ProcessHeader(request, hostW, request->server->host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4133 else
4134 HTTP_ProcessHeader(request, hostW, request->server->name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4137 heap_free(request->path);
4138 request->path = NULL;
4139 if(urlComponents.dwUrlPathLength)
4141 DWORD needed = 1;
4142 HRESULT rc;
4143 WCHAR dummy = 0;
4144 WCHAR *path;
4146 path = heap_strndupW(urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength);
4147 rc = UrlEscapeW(path, &dummy, &needed, URL_ESCAPE_SPACES_ONLY);
4148 if (rc != E_POINTER)
4149 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4150 request->path = heap_alloc(needed*sizeof(WCHAR));
4151 rc = UrlEscapeW(path, request->path, &needed,
4152 URL_ESCAPE_SPACES_ONLY);
4153 if (rc != S_OK)
4155 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4156 strcpyW(request->path, path);
4158 heap_free(path);
4161 /* Remove custom content-type/length headers on redirects. */
4162 remove_header(request, szContent_Type, TRUE);
4163 remove_header(request, szContent_Length, TRUE);
4165 return ERROR_SUCCESS;
4168 /***********************************************************************
4169 * HTTP_build_req (internal)
4171 * concatenate all the strings in the request together
4173 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4175 LPCWSTR *t;
4176 LPWSTR str;
4178 for( t = list; *t ; t++ )
4179 len += strlenW( *t );
4180 len++;
4182 str = heap_alloc(len*sizeof(WCHAR));
4183 *str = 0;
4185 for( t = list; *t ; t++ )
4186 strcatW( str, *t );
4188 return str;
4191 static void HTTP_InsertCookies(http_request_t *request)
4193 WCHAR *cookies;
4194 DWORD res;
4196 res = get_cookie_header(request->server->name, request->path, &cookies);
4197 if(res != ERROR_SUCCESS || !cookies)
4198 return;
4200 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies),
4201 HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
4202 heap_free(cookies);
4205 static WORD HTTP_ParseWkday(LPCWSTR day)
4207 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4208 { 'm','o','n',0 },
4209 { 't','u','e',0 },
4210 { 'w','e','d',0 },
4211 { 't','h','u',0 },
4212 { 'f','r','i',0 },
4213 { 's','a','t',0 }};
4214 unsigned int i;
4215 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4216 if (!strcmpiW(day, days[i]))
4217 return i;
4219 /* Invalid */
4220 return 7;
4223 static WORD HTTP_ParseMonth(LPCWSTR month)
4225 static const WCHAR jan[] = { 'j','a','n',0 };
4226 static const WCHAR feb[] = { 'f','e','b',0 };
4227 static const WCHAR mar[] = { 'm','a','r',0 };
4228 static const WCHAR apr[] = { 'a','p','r',0 };
4229 static const WCHAR may[] = { 'm','a','y',0 };
4230 static const WCHAR jun[] = { 'j','u','n',0 };
4231 static const WCHAR jul[] = { 'j','u','l',0 };
4232 static const WCHAR aug[] = { 'a','u','g',0 };
4233 static const WCHAR sep[] = { 's','e','p',0 };
4234 static const WCHAR oct[] = { 'o','c','t',0 };
4235 static const WCHAR nov[] = { 'n','o','v',0 };
4236 static const WCHAR dec[] = { 'd','e','c',0 };
4238 if (!strcmpiW(month, jan)) return 1;
4239 if (!strcmpiW(month, feb)) return 2;
4240 if (!strcmpiW(month, mar)) return 3;
4241 if (!strcmpiW(month, apr)) return 4;
4242 if (!strcmpiW(month, may)) return 5;
4243 if (!strcmpiW(month, jun)) return 6;
4244 if (!strcmpiW(month, jul)) return 7;
4245 if (!strcmpiW(month, aug)) return 8;
4246 if (!strcmpiW(month, sep)) return 9;
4247 if (!strcmpiW(month, oct)) return 10;
4248 if (!strcmpiW(month, nov)) return 11;
4249 if (!strcmpiW(month, dec)) return 12;
4250 /* Invalid */
4251 return 0;
4254 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4255 * optionally preceded by whitespace.
4256 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4257 * st, and sets *str to the first character after the time format.
4259 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4261 LPCWSTR ptr = *str;
4262 WCHAR *nextPtr;
4263 unsigned long num;
4265 while (isspaceW(*ptr))
4266 ptr++;
4268 num = strtoulW(ptr, &nextPtr, 10);
4269 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4271 ERR("unexpected time format %s\n", debugstr_w(ptr));
4272 return FALSE;
4274 if (num > 23)
4276 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4277 return FALSE;
4279 ptr = nextPtr + 1;
4280 st->wHour = (WORD)num;
4281 num = strtoulW(ptr, &nextPtr, 10);
4282 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4284 ERR("unexpected time format %s\n", debugstr_w(ptr));
4285 return FALSE;
4287 if (num > 59)
4289 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4290 return FALSE;
4292 ptr = nextPtr + 1;
4293 st->wMinute = (WORD)num;
4294 num = strtoulW(ptr, &nextPtr, 10);
4295 if (!nextPtr || nextPtr <= ptr)
4297 ERR("unexpected time format %s\n", debugstr_w(ptr));
4298 return FALSE;
4300 if (num > 59)
4302 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4303 return FALSE;
4305 ptr = nextPtr + 1;
4306 *str = ptr;
4307 st->wSecond = (WORD)num;
4308 return TRUE;
4311 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4313 static const WCHAR gmt[]= { 'G','M','T',0 };
4314 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4315 LPCWSTR ptr;
4316 SYSTEMTIME st = { 0 };
4317 unsigned long num;
4319 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4320 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4321 *dayPtr = *ptr;
4322 *dayPtr = 0;
4323 st.wDayOfWeek = HTTP_ParseWkday(day);
4324 if (st.wDayOfWeek >= 7)
4326 ERR("unexpected weekday %s\n", debugstr_w(day));
4327 return FALSE;
4330 while (isspaceW(*ptr))
4331 ptr++;
4333 for (monthPtr = month; !isspaceW(*ptr) &&
4334 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4335 monthPtr++, ptr++)
4336 *monthPtr = *ptr;
4337 *monthPtr = 0;
4338 st.wMonth = HTTP_ParseMonth(month);
4339 if (!st.wMonth || st.wMonth > 12)
4341 ERR("unexpected month %s\n", debugstr_w(month));
4342 return FALSE;
4345 while (isspaceW(*ptr))
4346 ptr++;
4348 num = strtoulW(ptr, &nextPtr, 10);
4349 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4351 ERR("unexpected day %s\n", debugstr_w(ptr));
4352 return FALSE;
4354 ptr = nextPtr;
4355 st.wDay = (WORD)num;
4357 while (isspaceW(*ptr))
4358 ptr++;
4360 if (!HTTP_ParseTime(&st, &ptr))
4361 return FALSE;
4363 while (isspaceW(*ptr))
4364 ptr++;
4366 num = strtoulW(ptr, &nextPtr, 10);
4367 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4369 ERR("unexpected year %s\n", debugstr_w(ptr));
4370 return FALSE;
4372 ptr = nextPtr;
4373 st.wYear = (WORD)num;
4375 while (isspaceW(*ptr))
4376 ptr++;
4378 /* asctime() doesn't report a timezone, but some web servers do, so accept
4379 * with or without GMT.
4381 if (*ptr && strcmpW(ptr, gmt))
4383 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4384 return FALSE;
4386 return SystemTimeToFileTime(&st, ft);
4389 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4391 static const WCHAR gmt[]= { 'G','M','T',0 };
4392 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4393 LPCWSTR ptr;
4394 unsigned long num;
4395 SYSTEMTIME st = { 0 };
4397 ptr = strchrW(value, ',');
4398 if (!ptr)
4399 return FALSE;
4400 if (ptr - value != 3)
4402 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4403 return FALSE;
4405 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4406 day[3] = 0;
4407 st.wDayOfWeek = HTTP_ParseWkday(day);
4408 if (st.wDayOfWeek > 6)
4410 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4411 return FALSE;
4413 ptr++;
4415 while (isspaceW(*ptr))
4416 ptr++;
4418 num = strtoulW(ptr, &nextPtr, 10);
4419 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4421 WARN("unexpected day %s\n", debugstr_w(value));
4422 return FALSE;
4424 ptr = nextPtr;
4425 st.wDay = (WORD)num;
4427 while (isspaceW(*ptr))
4428 ptr++;
4430 for (monthPtr = month; !isspaceW(*ptr) &&
4431 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4432 monthPtr++, ptr++)
4433 *monthPtr = *ptr;
4434 *monthPtr = 0;
4435 st.wMonth = HTTP_ParseMonth(month);
4436 if (!st.wMonth || st.wMonth > 12)
4438 WARN("unexpected month %s\n", debugstr_w(month));
4439 return FALSE;
4442 while (isspaceW(*ptr))
4443 ptr++;
4445 num = strtoulW(ptr, &nextPtr, 10);
4446 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4448 ERR("unexpected year %s\n", debugstr_w(value));
4449 return FALSE;
4451 ptr = nextPtr;
4452 st.wYear = (WORD)num;
4454 if (!HTTP_ParseTime(&st, &ptr))
4455 return FALSE;
4457 while (isspaceW(*ptr))
4458 ptr++;
4460 if (strcmpW(ptr, gmt))
4462 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4463 return FALSE;
4465 return SystemTimeToFileTime(&st, ft);
4468 static WORD HTTP_ParseWeekday(LPCWSTR day)
4470 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4471 { 'm','o','n','d','a','y',0 },
4472 { 't','u','e','s','d','a','y',0 },
4473 { 'w','e','d','n','e','s','d','a','y',0 },
4474 { 't','h','u','r','s','d','a','y',0 },
4475 { 'f','r','i','d','a','y',0 },
4476 { 's','a','t','u','r','d','a','y',0 }};
4477 unsigned int i;
4478 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4479 if (!strcmpiW(day, days[i]))
4480 return i;
4482 /* Invalid */
4483 return 7;
4486 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4488 static const WCHAR gmt[]= { 'G','M','T',0 };
4489 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4490 LPCWSTR ptr;
4491 unsigned long num;
4492 SYSTEMTIME st = { 0 };
4494 ptr = strchrW(value, ',');
4495 if (!ptr)
4496 return FALSE;
4497 if (ptr - value == 3)
4499 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4500 day[3] = 0;
4501 st.wDayOfWeek = HTTP_ParseWkday(day);
4502 if (st.wDayOfWeek > 6)
4504 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4505 return FALSE;
4508 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4510 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4511 day[ptr - value + 1] = 0;
4512 st.wDayOfWeek = HTTP_ParseWeekday(day);
4513 if (st.wDayOfWeek > 6)
4515 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4516 return FALSE;
4519 else
4521 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4522 return FALSE;
4524 ptr++;
4526 while (isspaceW(*ptr))
4527 ptr++;
4529 num = strtoulW(ptr, &nextPtr, 10);
4530 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4532 ERR("unexpected day %s\n", debugstr_w(value));
4533 return FALSE;
4535 ptr = nextPtr;
4536 st.wDay = (WORD)num;
4538 if (*ptr != '-')
4540 ERR("unexpected month format %s\n", debugstr_w(ptr));
4541 return FALSE;
4543 ptr++;
4545 for (monthPtr = month; *ptr != '-' &&
4546 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4547 monthPtr++, ptr++)
4548 *monthPtr = *ptr;
4549 *monthPtr = 0;
4550 st.wMonth = HTTP_ParseMonth(month);
4551 if (!st.wMonth || st.wMonth > 12)
4553 ERR("unexpected month %s\n", debugstr_w(month));
4554 return FALSE;
4557 if (*ptr != '-')
4559 ERR("unexpected year format %s\n", debugstr_w(ptr));
4560 return FALSE;
4562 ptr++;
4564 num = strtoulW(ptr, &nextPtr, 10);
4565 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4567 ERR("unexpected year %s\n", debugstr_w(value));
4568 return FALSE;
4570 ptr = nextPtr;
4571 st.wYear = (WORD)num;
4573 if (!HTTP_ParseTime(&st, &ptr))
4574 return FALSE;
4576 while (isspaceW(*ptr))
4577 ptr++;
4579 if (strcmpW(ptr, gmt))
4581 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4582 return FALSE;
4584 return SystemTimeToFileTime(&st, ft);
4587 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4589 static const WCHAR zero[] = { '0',0 };
4590 BOOL ret;
4592 if (!strcmpW(value, zero))
4594 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4595 ret = TRUE;
4597 else if (strchrW(value, ','))
4599 ret = HTTP_ParseRfc1123Date(value, ft);
4600 if (!ret)
4602 ret = HTTP_ParseRfc850Date(value, ft);
4603 if (!ret)
4604 ERR("unexpected date format %s\n", debugstr_w(value));
4607 else
4609 ret = HTTP_ParseDateAsAsctime(value, ft);
4610 if (!ret)
4611 ERR("unexpected date format %s\n", debugstr_w(value));
4613 return ret;
4616 static void HTTP_ProcessExpires(http_request_t *request)
4618 BOOL expirationFound = FALSE;
4619 int headerIndex;
4621 EnterCriticalSection( &request->headers_section );
4623 /* Look for a Cache-Control header with a max-age directive, as it takes
4624 * precedence over the Expires header.
4626 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4627 if (headerIndex != -1)
4629 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4630 LPWSTR ptr;
4632 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4634 LPWSTR comma = strchrW(ptr, ','), end, equal;
4636 if (comma)
4637 end = comma;
4638 else
4639 end = ptr + strlenW(ptr);
4640 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4642 if (*equal == '=')
4644 static const WCHAR max_age[] = {
4645 'm','a','x','-','a','g','e',0 };
4647 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4649 LPWSTR nextPtr;
4650 unsigned long age;
4652 age = strtoulW(equal + 1, &nextPtr, 10);
4653 if (nextPtr > equal + 1)
4655 LARGE_INTEGER ft;
4657 NtQuerySystemTime( &ft );
4658 /* Age is in seconds, FILETIME resolution is in
4659 * 100 nanosecond intervals.
4661 ft.QuadPart += age * (ULONGLONG)1000000;
4662 request->expires.dwLowDateTime = ft.u.LowPart;
4663 request->expires.dwHighDateTime = ft.u.HighPart;
4664 expirationFound = TRUE;
4668 if (comma)
4670 ptr = comma + 1;
4671 while (isspaceW(*ptr))
4672 ptr++;
4674 else
4675 ptr = NULL;
4678 if (!expirationFound)
4680 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4681 if (headerIndex != -1)
4683 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4684 FILETIME ft;
4686 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4688 expirationFound = TRUE;
4689 request->expires = ft;
4693 if (!expirationFound)
4695 LARGE_INTEGER t;
4697 /* With no known age, default to 10 minutes until expiration. */
4698 NtQuerySystemTime( &t );
4699 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4700 request->expires.dwLowDateTime = t.u.LowPart;
4701 request->expires.dwHighDateTime = t.u.HighPart;
4704 LeaveCriticalSection( &request->headers_section );
4707 static void HTTP_ProcessLastModified(http_request_t *request)
4709 int headerIndex;
4711 EnterCriticalSection( &request->headers_section );
4713 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4714 if (headerIndex != -1)
4716 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4717 FILETIME ft;
4719 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4720 request->last_modified = ft;
4723 LeaveCriticalSection( &request->headers_section );
4726 static void http_process_keep_alive(http_request_t *req)
4728 int index;
4730 EnterCriticalSection( &req->headers_section );
4732 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4733 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4734 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4735 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4736 else
4737 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4739 LeaveCriticalSection( &req->headers_section );
4742 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4744 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4745 netconn_t *netconn = NULL;
4746 DWORD res;
4748 if (request->netconn)
4750 if (NETCON_is_alive(request->netconn) && drain_content(request, TRUE) == ERROR_SUCCESS)
4752 reset_data_stream(request);
4753 *reusing = TRUE;
4754 return ERROR_SUCCESS;
4757 TRACE("freeing netconn\n");
4758 free_netconn(request->netconn);
4759 request->netconn = NULL;
4762 reset_data_stream(request);
4764 res = HTTP_ResolveName(request);
4765 if(res != ERROR_SUCCESS)
4766 return res;
4768 EnterCriticalSection(&connection_pool_cs);
4770 while(!list_empty(&request->server->conn_pool)) {
4771 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4772 list_remove(&netconn->pool_entry);
4774 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4775 break;
4777 TRACE("connection %p closed during idle\n", netconn);
4778 free_netconn(netconn);
4779 netconn = NULL;
4782 LeaveCriticalSection(&connection_pool_cs);
4784 if(netconn) {
4785 TRACE("<-- reusing %p netconn\n", netconn);
4786 request->netconn = netconn;
4787 *reusing = TRUE;
4788 return ERROR_SUCCESS;
4791 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4792 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4794 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4795 INTERNET_STATUS_CONNECTING_TO_SERVER,
4796 request->server->addr_str,
4797 strlen(request->server->addr_str)+1);
4799 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4800 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4801 request->connect_timeout, &netconn);
4802 if(res != ERROR_SUCCESS) {
4803 ERR("create_netconn failed: %u\n", res);
4804 return res;
4807 request->netconn = netconn;
4809 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4810 INTERNET_STATUS_CONNECTED_TO_SERVER,
4811 request->server->addr_str, strlen(request->server->addr_str)+1);
4813 *reusing = FALSE;
4814 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4815 return ERROR_SUCCESS;
4818 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4820 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4821 char *ret;
4823 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4824 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4825 if (data_len) memcpy( ret + len - 1, data, data_len );
4826 *out_len = len + data_len - 1;
4827 ret[*out_len] = 0;
4828 return ret;
4831 static void set_content_length_header( http_request_t *request, DWORD len, DWORD flags )
4833 static const WCHAR fmtW[] =
4834 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4835 WCHAR buf[sizeof(fmtW)/sizeof(fmtW[0]) + 10];
4837 sprintfW( buf, fmtW, len );
4838 HTTP_HttpAddRequestHeadersW( request, buf, ~0u, flags );
4841 /***********************************************************************
4842 * HTTP_HttpSendRequestW (internal)
4844 * Sends the specified request to the HTTP server
4846 * RETURNS
4847 * ERROR_SUCCESS on success
4848 * win32 error code on failure
4851 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4852 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4853 DWORD dwContentLength, BOOL bEndRequest)
4855 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4856 LPWSTR requestString = NULL;
4857 INT responseLen, cnt;
4858 DWORD res;
4860 TRACE("--> %p\n", request);
4862 assert(request->hdr.htype == WH_HHTTPREQ);
4864 /* if the verb is NULL default to GET */
4865 if (!request->verb)
4866 request->verb = heap_strdupW(szGET);
4868 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port,
4869 HTTP_ADDREQ_FLAG_ADD_IF_NEW | HTTP_ADDHDR_FLAG_REQ);
4871 if (dwContentLength || strcmpW(request->verb, szGET))
4873 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4874 request->bytesToWrite = dwContentLength;
4876 if (request->session->appInfo->agent)
4878 WCHAR *agent_header;
4879 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4880 int len;
4882 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4883 agent_header = heap_alloc(len * sizeof(WCHAR));
4884 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4886 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4887 heap_free(agent_header);
4889 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4891 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4892 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4894 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4896 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4897 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4898 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4901 /* add the headers the caller supplied */
4902 if( lpszHeaders && dwHeaderLength )
4903 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4907 DWORD len, data_len = dwOptionalLength;
4908 BOOL reusing_connection;
4909 char *ascii_req;
4911 loop_next = FALSE;
4913 if(redirected) {
4914 request->contentLength = ~0u;
4915 request->bytesToWrite = 0;
4918 if (TRACE_ON(wininet))
4920 HTTPHEADERW *host;
4922 EnterCriticalSection( &request->headers_section );
4923 host = HTTP_GetHeader( request, hostW );
4924 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
4925 LeaveCriticalSection( &request->headers_section );
4928 HTTP_FixURL(request);
4929 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4931 HTTP_ProcessHeader(request, szConnection, szKeepAlive,
4932 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
4934 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4935 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4937 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4938 HTTP_InsertCookies(request);
4940 res = open_http_connection(request, &reusing_connection);
4941 if (res != ERROR_SUCCESS)
4942 break;
4944 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4946 if (request->proxy) secure_proxy_connect = TRUE;
4947 else
4949 res = NETCON_secure_connect(request->netconn, request->server);
4950 if (res != ERROR_SUCCESS)
4952 WARN("failed to upgrade to secure connection\n");
4953 http_release_netconn(request, FALSE);
4954 break;
4958 if (secure_proxy_connect)
4960 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4961 const WCHAR *target = request->server->host_port;
4963 if (HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
4964 set_content_length_header(request, 0, HTTP_ADDREQ_FLAG_REPLACE);
4966 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4968 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4970 WCHAR *url = build_proxy_path_url(request);
4971 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4972 heap_free(url);
4974 else
4976 if (request->proxy && HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
4977 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_REPLACE);
4979 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4982 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4984 /* send the request as ASCII, tack on the optional data */
4985 if (!lpOptional || redirected || secure_proxy_connect)
4986 data_len = 0;
4988 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
4989 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4991 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4992 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4994 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4995 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4996 heap_free( ascii_req );
4997 if(res != ERROR_SUCCESS) {
4998 TRACE("send failed: %u\n", res);
4999 if(!reusing_connection)
5000 break;
5001 http_release_netconn(request, FALSE);
5002 loop_next = TRUE;
5003 continue;
5006 request->bytesWritten = data_len;
5008 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5009 INTERNET_STATUS_REQUEST_SENT,
5010 &len, sizeof(DWORD));
5012 if (bEndRequest)
5014 DWORD dwBufferSize;
5016 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5017 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5019 if (HTTP_GetResponseHeaders(request, &responseLen))
5021 http_release_netconn(request, FALSE);
5022 res = ERROR_INTERNET_CONNECTION_ABORTED;
5023 goto lend;
5025 /* FIXME: We should know that connection is closed before sending
5026 * headers. Otherwise wrong callbacks are executed */
5027 if(!responseLen && reusing_connection) {
5028 TRACE("Connection closed by server, reconnecting\n");
5029 http_release_netconn(request, FALSE);
5030 loop_next = TRUE;
5031 continue;
5034 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5035 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5036 sizeof(DWORD));
5038 http_process_keep_alive(request);
5039 HTTP_ProcessCookies(request);
5040 HTTP_ProcessExpires(request);
5041 HTTP_ProcessLastModified(request);
5043 res = set_content_length(request);
5044 if(res != ERROR_SUCCESS)
5045 goto lend;
5046 if(!request->contentLength)
5047 http_release_netconn(request, TRUE);
5049 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5051 WCHAR *new_url;
5053 switch(request->status_code) {
5054 case HTTP_STATUS_REDIRECT:
5055 case HTTP_STATUS_MOVED:
5056 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5057 case HTTP_STATUS_REDIRECT_METHOD:
5058 new_url = get_redirect_url(request);
5059 if(!new_url)
5060 break;
5062 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5063 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5065 heap_free(request->verb);
5066 request->verb = heap_strdupW(szGET);
5068 http_release_netconn(request, drain_content(request, FALSE) == ERROR_SUCCESS);
5069 res = HTTP_HandleRedirect(request, new_url);
5070 heap_free(new_url);
5071 if (res == ERROR_SUCCESS) {
5072 heap_free(requestString);
5073 loop_next = TRUE;
5075 redirected = TRUE;
5078 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5080 WCHAR szAuthValue[2048];
5081 dwBufferSize=2048;
5082 if (request->status_code == HTTP_STATUS_DENIED)
5084 WCHAR *host = heap_strdupW( request->server->canon_host_port );
5085 DWORD dwIndex = 0;
5086 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5088 if (HTTP_DoAuthorization(request, szAuthValue,
5089 &request->authInfo,
5090 request->session->userName,
5091 request->session->password, host))
5093 heap_free(requestString);
5094 if(!drain_content(request, TRUE) == ERROR_SUCCESS) {
5095 FIXME("Could not drain content\n");
5096 http_release_netconn(request, FALSE);
5098 loop_next = TRUE;
5099 break;
5102 heap_free( host );
5104 if(!loop_next) {
5105 TRACE("Cleaning wrong authorization data\n");
5106 destroy_authinfo(request->authInfo);
5107 request->authInfo = NULL;
5110 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5112 DWORD dwIndex = 0;
5113 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5115 if (HTTP_DoAuthorization(request, szAuthValue,
5116 &request->proxyAuthInfo,
5117 request->session->appInfo->proxyUsername,
5118 request->session->appInfo->proxyPassword,
5119 NULL))
5121 heap_free(requestString);
5122 if(!drain_content(request, TRUE) == ERROR_SUCCESS) {
5123 FIXME("Could not drain content\n");
5124 http_release_netconn(request, FALSE);
5126 loop_next = TRUE;
5127 break;
5131 if(!loop_next) {
5132 TRACE("Cleaning wrong proxy authorization data\n");
5133 destroy_authinfo(request->proxyAuthInfo);
5134 request->proxyAuthInfo = NULL;
5138 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5140 res = NETCON_secure_connect(request->netconn, request->server);
5141 if (res != ERROR_SUCCESS)
5143 WARN("failed to upgrade to secure proxy connection\n");
5144 http_release_netconn( request, FALSE );
5145 break;
5147 remove_header(request, szProxy_Authorization, TRUE);
5148 destroy_authinfo(request->proxyAuthInfo);
5149 request->proxyAuthInfo = NULL;
5151 secure_proxy_connect = FALSE;
5152 loop_next = TRUE;
5155 else
5156 res = ERROR_SUCCESS;
5158 while (loop_next);
5160 lend:
5161 heap_free(requestString);
5163 /* TODO: send notification for P3P header */
5165 if(res == ERROR_SUCCESS)
5166 create_cache_entry(request);
5168 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5170 if (res == ERROR_SUCCESS) {
5171 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5172 HTTP_ReceiveRequestData(request);
5173 else
5174 send_request_complete(request,
5175 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5176 }else {
5177 send_request_complete(request, 0, res);
5181 TRACE("<--\n");
5182 return res;
5185 typedef struct {
5186 task_header_t hdr;
5187 WCHAR *headers;
5188 DWORD headers_len;
5189 void *optional;
5190 DWORD optional_len;
5191 DWORD content_len;
5192 BOOL end_request;
5193 } send_request_task_t;
5195 /***********************************************************************
5197 * Helper functions for the HttpSendRequest(Ex) functions
5200 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5202 send_request_task_t *task = (send_request_task_t*)hdr;
5203 http_request_t *request = (http_request_t*)task->hdr.hdr;
5205 TRACE("%p\n", request);
5207 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5208 task->optional_len, task->content_len, task->end_request);
5210 heap_free(task->headers);
5214 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5216 INT responseLen;
5217 DWORD res = ERROR_SUCCESS;
5219 if(!is_valid_netconn(request->netconn)) {
5220 WARN("Not connected\n");
5221 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5222 return ERROR_INTERNET_OPERATION_CANCELLED;
5225 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5226 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5228 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5229 res = ERROR_HTTP_HEADER_NOT_FOUND;
5231 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5232 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5234 /* process cookies here. Is this right? */
5235 http_process_keep_alive(request);
5236 HTTP_ProcessCookies(request);
5237 HTTP_ProcessExpires(request);
5238 HTTP_ProcessLastModified(request);
5240 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5241 if(!request->contentLength)
5242 http_release_netconn(request, TRUE);
5245 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5247 switch(request->status_code) {
5248 case HTTP_STATUS_REDIRECT:
5249 case HTTP_STATUS_MOVED:
5250 case HTTP_STATUS_REDIRECT_METHOD:
5251 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5252 WCHAR *new_url;
5254 new_url = get_redirect_url(request);
5255 if(!new_url)
5256 break;
5258 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5259 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5261 heap_free(request->verb);
5262 request->verb = heap_strdupW(szGET);
5264 http_release_netconn(request, drain_content(request, FALSE) == ERROR_SUCCESS);
5265 res = HTTP_HandleRedirect(request, new_url);
5266 heap_free(new_url);
5267 if (res == ERROR_SUCCESS)
5268 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5273 if(res == ERROR_SUCCESS)
5274 create_cache_entry(request);
5276 if (res == ERROR_SUCCESS && request->contentLength)
5277 HTTP_ReceiveRequestData(request);
5278 else
5279 send_request_complete(request, res == ERROR_SUCCESS, res);
5281 return res;
5284 /***********************************************************************
5285 * HttpEndRequestA (WININET.@)
5287 * Ends an HTTP request that was started by HttpSendRequestEx
5289 * RETURNS
5290 * TRUE if successful
5291 * FALSE on failure
5294 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5295 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5297 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5299 if (lpBuffersOut)
5301 SetLastError(ERROR_INVALID_PARAMETER);
5302 return FALSE;
5305 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5308 typedef struct {
5309 task_header_t hdr;
5310 DWORD flags;
5311 DWORD context;
5312 } end_request_task_t;
5314 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5316 end_request_task_t *task = (end_request_task_t*)hdr;
5317 http_request_t *req = (http_request_t*)task->hdr.hdr;
5319 TRACE("%p\n", req);
5321 HTTP_HttpEndRequestW(req, task->flags, task->context);
5324 /***********************************************************************
5325 * HttpEndRequestW (WININET.@)
5327 * Ends an HTTP request that was started by HttpSendRequestEx
5329 * RETURNS
5330 * TRUE if successful
5331 * FALSE on failure
5334 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5335 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5337 http_request_t *request;
5338 DWORD res;
5340 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5342 if (lpBuffersOut)
5344 SetLastError(ERROR_INVALID_PARAMETER);
5345 return FALSE;
5348 request = (http_request_t*) get_handle_object( hRequest );
5350 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5352 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5353 if (request)
5354 WININET_Release( &request->hdr );
5355 return FALSE;
5357 request->hdr.dwFlags |= dwFlags;
5359 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5361 end_request_task_t *task;
5363 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5364 task->flags = dwFlags;
5365 task->context = dwContext;
5367 INTERNET_AsyncCall(&task->hdr);
5368 res = ERROR_IO_PENDING;
5370 else
5371 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5373 WININET_Release( &request->hdr );
5374 TRACE("%u <--\n", res);
5375 if(res != ERROR_SUCCESS)
5376 SetLastError(res);
5377 return res == ERROR_SUCCESS;
5380 /***********************************************************************
5381 * HttpSendRequestExA (WININET.@)
5383 * Sends the specified request to the HTTP server and allows chunked
5384 * transfers.
5386 * RETURNS
5387 * Success: TRUE
5388 * Failure: FALSE, call GetLastError() for more information.
5390 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5391 LPINTERNET_BUFFERSA lpBuffersIn,
5392 LPINTERNET_BUFFERSA lpBuffersOut,
5393 DWORD dwFlags, DWORD_PTR dwContext)
5395 INTERNET_BUFFERSW BuffersInW;
5396 BOOL rc = FALSE;
5397 DWORD headerlen;
5398 LPWSTR header = NULL;
5400 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5401 lpBuffersOut, dwFlags, dwContext);
5403 if (lpBuffersIn)
5405 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5406 if (lpBuffersIn->lpcszHeader)
5408 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5409 lpBuffersIn->dwHeadersLength,0,0);
5410 header = heap_alloc(headerlen*sizeof(WCHAR));
5411 if (!(BuffersInW.lpcszHeader = header))
5413 SetLastError(ERROR_OUTOFMEMORY);
5414 return FALSE;
5416 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5417 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5418 header, headerlen);
5420 else
5421 BuffersInW.lpcszHeader = NULL;
5422 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5423 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5424 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5425 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5426 BuffersInW.Next = NULL;
5429 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5431 heap_free(header);
5432 return rc;
5435 /***********************************************************************
5436 * HttpSendRequestExW (WININET.@)
5438 * Sends the specified request to the HTTP server and allows chunked
5439 * transfers
5441 * RETURNS
5442 * Success: TRUE
5443 * Failure: FALSE, call GetLastError() for more information.
5445 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5446 LPINTERNET_BUFFERSW lpBuffersIn,
5447 LPINTERNET_BUFFERSW lpBuffersOut,
5448 DWORD dwFlags, DWORD_PTR dwContext)
5450 http_request_t *request;
5451 http_session_t *session;
5452 appinfo_t *hIC;
5453 DWORD res;
5455 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5456 lpBuffersOut, dwFlags, dwContext);
5458 request = (http_request_t*) get_handle_object( hRequest );
5460 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5462 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5463 goto lend;
5466 session = request->session;
5467 assert(session->hdr.htype == WH_HHTTPSESSION);
5468 hIC = session->appInfo;
5469 assert(hIC->hdr.htype == WH_HINIT);
5471 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5473 send_request_task_t *task;
5475 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5476 if (lpBuffersIn)
5478 DWORD size = 0;
5480 if (lpBuffersIn->lpcszHeader)
5482 if (lpBuffersIn->dwHeadersLength == ~0u)
5483 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5484 else
5485 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5487 task->headers = heap_alloc(size);
5488 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5490 else task->headers = NULL;
5492 task->headers_len = size / sizeof(WCHAR);
5493 task->optional = lpBuffersIn->lpvBuffer;
5494 task->optional_len = lpBuffersIn->dwBufferLength;
5495 task->content_len = lpBuffersIn->dwBufferTotal;
5497 else
5499 task->headers = NULL;
5500 task->headers_len = 0;
5501 task->optional = NULL;
5502 task->optional_len = 0;
5503 task->content_len = 0;
5506 task->end_request = FALSE;
5508 INTERNET_AsyncCall(&task->hdr);
5509 res = ERROR_IO_PENDING;
5511 else
5513 if (lpBuffersIn)
5514 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5515 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5516 lpBuffersIn->dwBufferTotal, FALSE);
5517 else
5518 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5521 lend:
5522 if ( request )
5523 WININET_Release( &request->hdr );
5525 TRACE("<---\n");
5526 SetLastError(res);
5527 return res == ERROR_SUCCESS;
5530 /***********************************************************************
5531 * HttpSendRequestW (WININET.@)
5533 * Sends the specified request to the HTTP server
5535 * RETURNS
5536 * TRUE on success
5537 * FALSE on failure
5540 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5541 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5543 http_request_t *request;
5544 http_session_t *session = NULL;
5545 appinfo_t *hIC = NULL;
5546 DWORD res = ERROR_SUCCESS;
5548 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5549 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5551 request = (http_request_t*) get_handle_object( hHttpRequest );
5552 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5554 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5555 goto lend;
5558 session = request->session;
5559 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5561 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5562 goto lend;
5565 hIC = session->appInfo;
5566 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5568 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5569 goto lend;
5572 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5574 send_request_task_t *task;
5576 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5577 if (lpszHeaders)
5579 DWORD size;
5581 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5582 else size = dwHeaderLength * sizeof(WCHAR);
5584 task->headers = heap_alloc(size);
5585 memcpy(task->headers, lpszHeaders, size);
5587 else
5588 task->headers = NULL;
5589 task->headers_len = dwHeaderLength;
5590 task->optional = lpOptional;
5591 task->optional_len = dwOptionalLength;
5592 task->content_len = dwOptionalLength;
5593 task->end_request = TRUE;
5595 INTERNET_AsyncCall(&task->hdr);
5596 res = ERROR_IO_PENDING;
5598 else
5600 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5601 dwHeaderLength, lpOptional, dwOptionalLength,
5602 dwOptionalLength, TRUE);
5604 lend:
5605 if( request )
5606 WININET_Release( &request->hdr );
5608 SetLastError(res);
5609 return res == ERROR_SUCCESS;
5612 /***********************************************************************
5613 * HttpSendRequestA (WININET.@)
5615 * Sends the specified request to the HTTP server
5617 * RETURNS
5618 * TRUE on success
5619 * FALSE on failure
5622 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5623 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5625 BOOL result;
5626 LPWSTR szHeaders=NULL;
5627 DWORD nLen=dwHeaderLength;
5628 if(lpszHeaders!=NULL)
5630 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5631 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5632 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5634 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5635 heap_free(szHeaders);
5636 return result;
5639 /***********************************************************************
5640 * HTTPSESSION_Destroy (internal)
5642 * Deallocate session handle
5645 static void HTTPSESSION_Destroy(object_header_t *hdr)
5647 http_session_t *session = (http_session_t*) hdr;
5649 TRACE("%p\n", session);
5651 WININET_Release(&session->appInfo->hdr);
5653 heap_free(session->hostName);
5654 heap_free(session->password);
5655 heap_free(session->userName);
5658 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5660 http_session_t *ses = (http_session_t *)hdr;
5662 switch(option) {
5663 case INTERNET_OPTION_HANDLE_TYPE:
5664 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5666 if (*size < sizeof(ULONG))
5667 return ERROR_INSUFFICIENT_BUFFER;
5669 *size = sizeof(DWORD);
5670 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5671 return ERROR_SUCCESS;
5672 case INTERNET_OPTION_CONNECT_TIMEOUT:
5673 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5675 if (*size < sizeof(DWORD))
5676 return ERROR_INSUFFICIENT_BUFFER;
5678 *size = sizeof(DWORD);
5679 *(DWORD *)buffer = ses->connect_timeout;
5680 return ERROR_SUCCESS;
5682 case INTERNET_OPTION_SEND_TIMEOUT:
5683 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5685 if (*size < sizeof(DWORD))
5686 return ERROR_INSUFFICIENT_BUFFER;
5688 *size = sizeof(DWORD);
5689 *(DWORD *)buffer = ses->send_timeout;
5690 return ERROR_SUCCESS;
5692 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5693 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5695 if (*size < sizeof(DWORD))
5696 return ERROR_INSUFFICIENT_BUFFER;
5698 *size = sizeof(DWORD);
5699 *(DWORD *)buffer = ses->receive_timeout;
5700 return ERROR_SUCCESS;
5703 return INET_QueryOption(hdr, option, buffer, size, unicode);
5706 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5708 http_session_t *ses = (http_session_t*)hdr;
5710 switch(option) {
5711 case INTERNET_OPTION_USERNAME:
5713 heap_free(ses->userName);
5714 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5715 return ERROR_SUCCESS;
5717 case INTERNET_OPTION_PASSWORD:
5719 heap_free(ses->password);
5720 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5721 return ERROR_SUCCESS;
5723 case INTERNET_OPTION_PROXY_USERNAME:
5725 heap_free(ses->appInfo->proxyUsername);
5726 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5727 return ERROR_SUCCESS;
5729 case INTERNET_OPTION_PROXY_PASSWORD:
5731 heap_free(ses->appInfo->proxyPassword);
5732 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5733 return ERROR_SUCCESS;
5735 case INTERNET_OPTION_CONNECT_TIMEOUT:
5737 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5738 ses->connect_timeout = *(DWORD *)buffer;
5739 return ERROR_SUCCESS;
5741 case INTERNET_OPTION_SEND_TIMEOUT:
5743 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5744 ses->send_timeout = *(DWORD *)buffer;
5745 return ERROR_SUCCESS;
5747 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5749 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5750 ses->receive_timeout = *(DWORD *)buffer;
5751 return ERROR_SUCCESS;
5753 default: break;
5756 return INET_SetOption(hdr, option, buffer, size);
5759 static const object_vtbl_t HTTPSESSIONVtbl = {
5760 HTTPSESSION_Destroy,
5761 NULL,
5762 HTTPSESSION_QueryOption,
5763 HTTPSESSION_SetOption,
5764 NULL,
5765 NULL,
5766 NULL,
5767 NULL
5771 /***********************************************************************
5772 * HTTP_Connect (internal)
5774 * Create http session handle
5776 * RETURNS
5777 * HINTERNET a session handle on success
5778 * NULL on failure
5781 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5782 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5783 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5784 DWORD dwInternalFlags, HINTERNET *ret)
5786 http_session_t *session = NULL;
5788 TRACE("-->\n");
5790 if (!lpszServerName || !lpszServerName[0])
5791 return ERROR_INVALID_PARAMETER;
5793 assert( hIC->hdr.htype == WH_HINIT );
5795 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5796 if (!session)
5797 return ERROR_OUTOFMEMORY;
5800 * According to my tests. The name is not resolved until a request is sent
5803 session->hdr.htype = WH_HHTTPSESSION;
5804 session->hdr.dwFlags = dwFlags;
5805 session->hdr.dwContext = dwContext;
5806 session->hdr.dwInternalFlags |= dwInternalFlags;
5808 WININET_AddRef( &hIC->hdr );
5809 session->appInfo = hIC;
5810 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5812 session->hostName = heap_strdupW(lpszServerName);
5813 if (lpszUserName && lpszUserName[0])
5814 session->userName = heap_strdupW(lpszUserName);
5815 if (lpszPassword && lpszPassword[0])
5816 session->password = heap_strdupW(lpszPassword);
5817 session->hostPort = serverPort;
5818 session->connect_timeout = hIC->connect_timeout;
5819 session->send_timeout = 0;
5820 session->receive_timeout = 0;
5822 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5823 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5825 INTERNET_SendCallback(&hIC->hdr, dwContext,
5826 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5827 sizeof(HINTERNET));
5831 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5832 * windows
5835 TRACE("%p --> %p\n", hIC, session);
5837 *ret = session->hdr.hInternet;
5838 return ERROR_SUCCESS;
5841 /***********************************************************************
5842 * HTTP_clear_response_headers (internal)
5844 * clear out any old response headers
5846 static void HTTP_clear_response_headers( http_request_t *request )
5848 DWORD i;
5850 EnterCriticalSection( &request->headers_section );
5852 for( i=0; i<request->nCustHeaders; i++)
5854 if( !request->custHeaders[i].lpszField )
5855 continue;
5856 if( !request->custHeaders[i].lpszValue )
5857 continue;
5858 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5859 continue;
5860 HTTP_DeleteCustomHeader( request, i );
5861 i--;
5864 LeaveCriticalSection( &request->headers_section );
5867 /***********************************************************************
5868 * HTTP_GetResponseHeaders (internal)
5870 * Read server response
5872 * RETURNS
5874 * TRUE on success
5875 * FALSE on error
5877 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5879 INT cbreaks = 0;
5880 WCHAR buffer[MAX_REPLY_LEN];
5881 DWORD buflen = MAX_REPLY_LEN;
5882 INT rc = 0;
5883 char bufferA[MAX_REPLY_LEN];
5884 LPWSTR status_code = NULL, status_text = NULL;
5885 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5886 BOOL codeHundred = FALSE;
5888 TRACE("-->\n");
5890 if(!is_valid_netconn(request->netconn))
5891 goto lend;
5893 /* clear old response headers (eg. from a redirect response) */
5894 HTTP_clear_response_headers( request );
5896 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5897 do {
5899 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5901 buflen = MAX_REPLY_LEN;
5902 if ((res = read_line(request, bufferA, &buflen)))
5903 goto lend;
5905 if (!buflen) goto lend;
5907 rc += buflen;
5908 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5909 /* check is this a status code line? */
5910 if (!strncmpW(buffer, g_szHttp1_0, 4))
5912 /* split the version from the status code */
5913 status_code = strchrW( buffer, ' ' );
5914 if( !status_code )
5915 goto lend;
5916 *status_code++=0;
5918 /* split the status code from the status text */
5919 status_text = strchrW( status_code, ' ' );
5920 if( status_text )
5921 *status_text++=0;
5923 request->status_code = atoiW(status_code);
5925 TRACE("version [%s] status code [%s] status text [%s]\n",
5926 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5928 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5930 else if (!codeHundred)
5932 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5934 heap_free(request->version);
5935 heap_free(request->statusText);
5937 request->status_code = HTTP_STATUS_OK;
5938 request->version = heap_strdupW(g_szHttp1_0);
5939 request->statusText = heap_strdupW(szOK);
5941 goto lend;
5943 } while (codeHundred);
5945 /* Add status code */
5946 HTTP_ProcessHeader(request, szStatus, status_code,
5947 HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
5949 heap_free(request->version);
5950 heap_free(request->statusText);
5952 request->version = heap_strdupW(buffer);
5953 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5955 /* Restore the spaces */
5956 *(status_code-1) = ' ';
5957 if (status_text)
5958 *(status_text-1) = ' ';
5960 /* Parse each response line */
5963 buflen = MAX_REPLY_LEN;
5964 if (!read_line(request, bufferA, &buflen) && buflen)
5966 LPWSTR * pFieldAndValue;
5968 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5970 if (!bufferA[0]) break;
5971 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5973 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5974 if (pFieldAndValue)
5976 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5977 HTTP_ADDREQ_FLAG_ADD );
5978 HTTP_FreeTokens(pFieldAndValue);
5981 else
5983 cbreaks++;
5984 if (cbreaks >= 2)
5985 break;
5987 }while(1);
5989 res = ERROR_SUCCESS;
5991 lend:
5993 *len = rc;
5994 TRACE("<--\n");
5995 return res;
5998 /***********************************************************************
5999 * HTTP_InterpretHttpHeader (internal)
6001 * Parse server response
6003 * RETURNS
6005 * Pointer to array of field, value, NULL on success.
6006 * NULL on error.
6008 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6010 LPWSTR * pTokenPair;
6011 LPWSTR pszColon;
6012 INT len;
6014 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6016 pszColon = strchrW(buffer, ':');
6017 /* must have two tokens */
6018 if (!pszColon)
6020 HTTP_FreeTokens(pTokenPair);
6021 if (buffer[0])
6022 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6023 return NULL;
6026 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6027 if (!pTokenPair[0])
6029 HTTP_FreeTokens(pTokenPair);
6030 return NULL;
6032 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6033 pTokenPair[0][pszColon - buffer] = '\0';
6035 /* skip colon */
6036 pszColon++;
6037 len = strlenW(pszColon);
6038 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6039 if (!pTokenPair[1])
6041 HTTP_FreeTokens(pTokenPair);
6042 return NULL;
6044 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6046 strip_spaces(pTokenPair[0]);
6047 strip_spaces(pTokenPair[1]);
6049 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6050 return pTokenPair;
6053 /***********************************************************************
6054 * HTTP_ProcessHeader (internal)
6056 * Stuff header into header tables according to <dwModifier>
6060 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6062 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6064 LPHTTPHEADERW lphttpHdr = NULL;
6065 INT index;
6066 BOOL request_only = !!(dwModifier & HTTP_ADDHDR_FLAG_REQ);
6067 DWORD res = ERROR_HTTP_INVALID_HEADER;
6069 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6071 EnterCriticalSection( &request->headers_section );
6073 /* REPLACE wins out over ADD */
6074 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6075 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6077 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6078 index = -1;
6079 else
6080 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6082 if (index >= 0)
6084 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6086 LeaveCriticalSection( &request->headers_section );
6087 return ERROR_HTTP_INVALID_HEADER;
6089 lphttpHdr = &request->custHeaders[index];
6091 else if (value)
6093 HTTPHEADERW hdr;
6095 hdr.lpszField = (LPWSTR)field;
6096 hdr.lpszValue = (LPWSTR)value;
6097 hdr.wFlags = hdr.wCount = 0;
6099 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6100 hdr.wFlags |= HDR_ISREQUEST;
6102 res = HTTP_InsertCustomHeader(request, &hdr);
6103 LeaveCriticalSection( &request->headers_section );
6104 return res;
6106 /* no value to delete */
6107 else
6109 LeaveCriticalSection( &request->headers_section );
6110 return ERROR_SUCCESS;
6113 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6114 lphttpHdr->wFlags |= HDR_ISREQUEST;
6115 else
6116 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6118 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6120 HTTP_DeleteCustomHeader( request, index );
6122 if (value && value[0])
6124 HTTPHEADERW hdr;
6126 hdr.lpszField = (LPWSTR)field;
6127 hdr.lpszValue = (LPWSTR)value;
6128 hdr.wFlags = hdr.wCount = 0;
6130 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6131 hdr.wFlags |= HDR_ISREQUEST;
6133 res = HTTP_InsertCustomHeader(request, &hdr);
6134 LeaveCriticalSection( &request->headers_section );
6135 return res;
6138 LeaveCriticalSection( &request->headers_section );
6139 return ERROR_SUCCESS;
6141 else if (dwModifier & COALESCEFLAGS)
6143 LPWSTR lpsztmp;
6144 WCHAR ch = 0;
6145 INT len = 0;
6146 INT origlen = strlenW(lphttpHdr->lpszValue);
6147 INT valuelen = strlenW(value);
6149 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6151 ch = ',';
6152 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6154 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6156 ch = ';';
6157 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6160 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6162 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6163 if (lpsztmp)
6165 lphttpHdr->lpszValue = lpsztmp;
6166 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6167 if (ch > 0)
6169 lphttpHdr->lpszValue[origlen] = ch;
6170 origlen++;
6171 lphttpHdr->lpszValue[origlen] = ' ';
6172 origlen++;
6175 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6176 lphttpHdr->lpszValue[len] = '\0';
6177 res = ERROR_SUCCESS;
6179 else
6181 WARN("heap_realloc (%d bytes) failed\n",len+1);
6182 res = ERROR_OUTOFMEMORY;
6185 TRACE("<-- %d\n", res);
6186 LeaveCriticalSection( &request->headers_section );
6187 return res;
6190 /***********************************************************************
6191 * HTTP_GetCustomHeaderIndex (internal)
6193 * Return index of custom header from header array
6194 * Headers section must be held
6196 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6197 int requested_index, BOOL request_only)
6199 DWORD index;
6201 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6203 for (index = 0; index < request->nCustHeaders; index++)
6205 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6206 continue;
6208 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6209 continue;
6211 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6212 continue;
6214 if (requested_index == 0)
6215 break;
6216 requested_index --;
6219 if (index >= request->nCustHeaders)
6220 index = -1;
6222 TRACE("Return: %d\n", index);
6223 return index;
6227 /***********************************************************************
6228 * HTTP_InsertCustomHeader (internal)
6230 * Insert header into array
6231 * Headers section must be held
6233 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6235 INT count;
6236 LPHTTPHEADERW lph = NULL;
6238 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6239 count = request->nCustHeaders + 1;
6240 if (count > 1)
6241 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6242 else
6243 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6245 if (!lph)
6246 return ERROR_OUTOFMEMORY;
6248 request->custHeaders = lph;
6249 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6250 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6251 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6252 request->custHeaders[count-1].wCount= lpHdr->wCount;
6253 request->nCustHeaders++;
6255 return ERROR_SUCCESS;
6259 /***********************************************************************
6260 * HTTP_DeleteCustomHeader (internal)
6262 * Delete header from array
6263 * If this function is called, the index may change.
6264 * Headers section must be held
6266 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6268 if( request->nCustHeaders <= 0 )
6269 return FALSE;
6270 if( index >= request->nCustHeaders )
6271 return FALSE;
6272 request->nCustHeaders--;
6274 heap_free(request->custHeaders[index].lpszField);
6275 heap_free(request->custHeaders[index].lpszValue);
6277 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6278 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6279 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6281 return TRUE;
6285 /***********************************************************************
6286 * IsHostInProxyBypassList (@)
6288 * Undocumented
6291 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6293 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6294 return FALSE;