wininet: Remove custom port handling in HTTP_HandleRedirect.
[wine/multimedia.git] / dlls / wininet / http.c
bloba98ed53786a3f8b482436ffd9386e6b79937a9b8
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"
31 #include "wine/port.h"
33 #if defined(__MINGW32__) || defined (_MSC_VER)
34 #include <ws2tcpip.h>
35 #endif
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
40 #endif
41 #ifdef HAVE_ARPA_INET_H
42 # include <arpa/inet.h>
43 #endif
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #include <time.h>
51 #include <assert.h>
52 #ifdef HAVE_ZLIB
53 # include <zlib.h>
54 #endif
56 #include "windef.h"
57 #include "winbase.h"
58 #include "wininet.h"
59 #include "winerror.h"
60 #include "winternl.h"
61 #define NO_SHLWAPI_STREAM
62 #define NO_SHLWAPI_REG
63 #define NO_SHLWAPI_STRFCNS
64 #define NO_SHLWAPI_GDI
65 #include "shlwapi.h"
66 #include "sspi.h"
67 #include "wincrypt.h"
68 #include "winuser.h"
70 #include "internet.h"
71 #include "wine/debug.h"
72 #include "wine/exception.h"
73 #include "wine/unicode.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
77 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
78 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
79 static const WCHAR szOK[] = {'O','K',0};
80 static const WCHAR szDefaultHeader[] = {'H','T','T','P','/','1','.','0',' ','2','0','0',' ','O','K',0};
81 static const WCHAR hostW[] = { 'H','o','s','t',0 };
82 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
83 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
84 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
85 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
86 static const WCHAR szGET[] = { 'G','E','T', 0 };
87 static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
88 static const WCHAR szCrLf[] = {'\r','\n', 0};
90 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
91 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
92 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
93 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
94 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
95 static const WCHAR szAge[] = { 'A','g','e',0 };
96 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
97 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
98 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
99 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
100 static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
101 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
102 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
103 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
104 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
105 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
106 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
107 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
108 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 };
109 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
110 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
111 static const WCHAR szDate[] = { 'D','a','t','e',0 };
112 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
113 static const WCHAR szETag[] = { 'E','T','a','g',0 };
114 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
115 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
116 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
117 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
118 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
119 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
120 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
121 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
122 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
123 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
124 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
125 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
126 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
127 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
128 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
129 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
130 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
131 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
132 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
133 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
134 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
135 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 };
136 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
137 static const WCHAR szURI[] = { 'U','R','I',0 };
138 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
139 static const WCHAR szVary[] = { 'V','a','r','y',0 };
140 static const WCHAR szVia[] = { 'V','i','a',0 };
141 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
142 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
144 static const WCHAR emptyW[] = {0};
146 #define HTTP_REFERER szReferer
147 #define HTTP_ACCEPT szAccept
148 #define HTTP_USERAGENT szUser_Agent
150 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
151 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
152 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
153 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
154 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
155 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
156 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
158 #define COLLECT_TIME 60000
160 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
162 struct HttpAuthInfo
164 LPWSTR scheme;
165 CredHandle cred;
166 CtxtHandle ctx;
167 TimeStamp exp;
168 ULONG attr;
169 ULONG max_token;
170 void *auth_data;
171 unsigned int auth_data_len;
172 BOOL finished; /* finished authenticating */
176 typedef struct _basicAuthorizationData
178 struct list entry;
180 LPWSTR host;
181 LPWSTR realm;
182 LPSTR authorization;
183 UINT authorizationLen;
184 } basicAuthorizationData;
186 typedef struct _authorizationData
188 struct list entry;
190 LPWSTR host;
191 LPWSTR scheme;
192 LPWSTR domain;
193 UINT domain_len;
194 LPWSTR user;
195 UINT user_len;
196 LPWSTR password;
197 UINT password_len;
198 } authorizationData;
200 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
201 static struct list authorizationCache = LIST_INIT(authorizationCache);
203 static CRITICAL_SECTION authcache_cs;
204 static CRITICAL_SECTION_DEBUG critsect_debug =
206 0, 0, &authcache_cs,
207 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
208 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
210 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
212 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
213 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
214 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
215 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
216 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
217 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
218 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
219 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
220 static LPWSTR HTTP_GetRedirectURL(http_request_t *req, LPCWSTR lpszUrl);
221 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
222 static BOOL HTTP_VerifyValidHeader(http_request_t *req, LPCWSTR field);
223 static BOOL drain_content(http_request_t*,BOOL);
225 static CRITICAL_SECTION connection_pool_cs;
226 static CRITICAL_SECTION_DEBUG connection_pool_debug =
228 0, 0, &connection_pool_cs,
229 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
230 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
232 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
234 static struct list connection_pool = LIST_INIT(connection_pool);
235 static BOOL collector_running;
237 void server_addref(server_t *server)
239 InterlockedIncrement(&server->ref);
242 void server_release(server_t *server)
244 if(InterlockedDecrement(&server->ref))
245 return;
247 list_remove(&server->entry);
249 if(server->cert_chain)
250 CertFreeCertificateChain(server->cert_chain);
251 heap_free(server->name);
252 heap_free(server->scheme_host_port);
253 heap_free(server);
256 static BOOL process_host_port(server_t *server)
258 BOOL default_port;
259 size_t name_len;
260 WCHAR *buf;
262 static const WCHAR httpW[] = {'h','t','t','p',0};
263 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
264 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
266 name_len = strlenW(server->name);
267 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
268 if(!buf)
269 return FALSE;
271 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
272 server->scheme_host_port = buf;
274 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
275 if(server->is_https)
276 server->host_port++;
278 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
279 server->canon_host_port = default_port ? server->name : server->host_port;
280 return TRUE;
283 server_t *get_server(const WCHAR *name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
285 server_t *iter, *server = NULL;
287 if(port == INTERNET_INVALID_PORT_NUMBER)
288 port = INTERNET_DEFAULT_HTTP_PORT;
290 EnterCriticalSection(&connection_pool_cs);
292 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
293 if(iter->port == port && !strcmpW(iter->name, name) && iter->is_https == is_https) {
294 server = iter;
295 server_addref(server);
296 break;
300 if(!server && do_create) {
301 server = heap_alloc_zero(sizeof(*server));
302 if(server) {
303 server->ref = 2; /* list reference and return */
304 server->port = port;
305 server->is_https = is_https;
306 list_init(&server->conn_pool);
307 server->name = heap_strdupW(name);
308 if(server->name && process_host_port(server)) {
309 list_add_head(&connection_pool, &server->entry);
310 }else {
311 heap_free(server);
312 server = NULL;
317 LeaveCriticalSection(&connection_pool_cs);
319 return server;
322 BOOL collect_connections(collect_type_t collect_type)
324 netconn_t *netconn, *netconn_safe;
325 server_t *server, *server_safe;
326 BOOL remaining = FALSE;
327 DWORD64 now;
329 now = GetTickCount64();
331 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
332 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
333 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
334 TRACE("freeing %p\n", netconn);
335 list_remove(&netconn->pool_entry);
336 free_netconn(netconn);
337 }else {
338 remaining = TRUE;
342 if(collect_type == COLLECT_CLEANUP) {
343 list_remove(&server->entry);
344 list_init(&server->entry);
345 server_release(server);
349 return remaining;
352 static DWORD WINAPI collect_connections_proc(void *arg)
354 BOOL remaining_conns;
356 do {
357 /* FIXME: Use more sophisticated method */
358 Sleep(5000);
360 EnterCriticalSection(&connection_pool_cs);
362 remaining_conns = collect_connections(COLLECT_TIMEOUT);
363 if(!remaining_conns)
364 collector_running = FALSE;
366 LeaveCriticalSection(&connection_pool_cs);
367 }while(remaining_conns);
369 FreeLibraryAndExitThread(WININET_hModule, 0);
372 /***********************************************************************
373 * HTTP_GetHeader (internal)
375 * Headers section must be held
377 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
379 int HeaderIndex = 0;
380 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
381 if (HeaderIndex == -1)
382 return NULL;
383 else
384 return &req->custHeaders[HeaderIndex];
387 static WCHAR *get_host_header( http_request_t *req )
389 HTTPHEADERW *header;
390 WCHAR *ret = NULL;
392 EnterCriticalSection( &req->headers_section );
393 if ((header = HTTP_GetHeader( req, hostW ))) ret = heap_strdupW( header->lpszValue );
394 LeaveCriticalSection( &req->headers_section );
395 return ret;
398 struct data_stream_vtbl_t {
399 DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
400 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
401 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,blocking_mode_t);
402 BOOL (*drain_content)(data_stream_t*,http_request_t*);
403 void (*destroy)(data_stream_t*);
406 typedef struct {
407 data_stream_t data_stream;
409 BYTE buf[READ_BUFFER_SIZE];
410 DWORD buf_size;
411 DWORD buf_pos;
412 DWORD chunk_size;
413 BOOL end_of_data;
414 } chunked_stream_t;
416 static inline void destroy_data_stream(data_stream_t *stream)
418 stream->vtbl->destroy(stream);
421 static void reset_data_stream(http_request_t *req)
423 destroy_data_stream(req->data_stream);
424 req->data_stream = &req->netconn_stream.data_stream;
425 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
426 req->read_chunked = req->read_gzip = FALSE;
429 #ifdef HAVE_ZLIB
431 typedef struct {
432 data_stream_t stream;
433 data_stream_t *parent_stream;
434 z_stream zstream;
435 BYTE buf[READ_BUFFER_SIZE];
436 DWORD buf_size;
437 DWORD buf_pos;
438 BOOL end_of_data;
439 } gzip_stream_t;
441 static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
443 /* Allow reading only from read buffer */
444 return 0;
447 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
449 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
450 return gzip_stream->end_of_data
451 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
454 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
455 DWORD *read, blocking_mode_t blocking_mode)
457 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
458 z_stream *zstream = &gzip_stream->zstream;
459 DWORD current_read, ret_read = 0;
460 int zres;
461 DWORD res = ERROR_SUCCESS;
463 TRACE("(%d %d)\n", size, blocking_mode);
465 while(size && !gzip_stream->end_of_data) {
466 if(!gzip_stream->buf_size) {
467 if(gzip_stream->buf_pos) {
468 if(gzip_stream->buf_size)
469 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
470 gzip_stream->buf_pos = 0;
472 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
473 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, blocking_mode);
474 gzip_stream->buf_size += current_read;
475 if(res != ERROR_SUCCESS)
476 break;
478 if(!current_read) {
479 if(blocking_mode != BLOCKING_DISALLOW) {
480 WARN("unexpected end of data\n");
481 gzip_stream->end_of_data = TRUE;
483 break;
487 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
488 zstream->avail_in = gzip_stream->buf_size;
489 zstream->next_out = buf+ret_read;
490 zstream->avail_out = size;
491 zres = inflate(&gzip_stream->zstream, 0);
492 current_read = size - zstream->avail_out;
493 size -= current_read;
494 ret_read += current_read;
495 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
496 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
497 if(zres == Z_STREAM_END) {
498 TRACE("end of data\n");
499 gzip_stream->end_of_data = TRUE;
500 inflateEnd(zstream);
501 }else if(zres != Z_OK) {
502 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
503 if(!ret_read)
504 res = ERROR_INTERNET_DECODING_FAILED;
505 break;
508 if(ret_read && blocking_mode == BLOCKING_ALLOW)
509 blocking_mode = BLOCKING_DISALLOW;
512 TRACE("read %u bytes\n", ret_read);
513 *read = ret_read;
514 return res;
517 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
519 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
520 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
523 static void gzip_destroy(data_stream_t *stream)
525 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
527 destroy_data_stream(gzip_stream->parent_stream);
529 if(!gzip_stream->end_of_data)
530 inflateEnd(&gzip_stream->zstream);
531 heap_free(gzip_stream);
534 static const data_stream_vtbl_t gzip_stream_vtbl = {
535 gzip_get_avail_data,
536 gzip_end_of_data,
537 gzip_read,
538 gzip_drain_content,
539 gzip_destroy
542 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
544 return heap_alloc(items*size);
547 static void wininet_zfree(voidpf opaque, voidpf address)
549 heap_free(address);
552 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
554 gzip_stream_t *gzip_stream;
555 int index, zres;
557 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
558 if(!gzip_stream)
559 return ERROR_OUTOFMEMORY;
561 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
562 gzip_stream->zstream.zalloc = wininet_zalloc;
563 gzip_stream->zstream.zfree = wininet_zfree;
565 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
566 if(zres != Z_OK) {
567 ERR("inflateInit failed: %d\n", zres);
568 heap_free(gzip_stream);
569 return ERROR_OUTOFMEMORY;
572 EnterCriticalSection( &req->headers_section );
573 index = HTTP_GetCustomHeaderIndex(req, szContent_Length, 0, FALSE);
574 if(index != -1)
575 HTTP_DeleteCustomHeader(req, index);
576 LeaveCriticalSection( &req->headers_section );
578 if(req->read_size) {
579 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
580 gzip_stream->buf_size = req->read_size;
581 req->read_pos = req->read_size = 0;
584 req->read_gzip = TRUE;
585 gzip_stream->parent_stream = req->data_stream;
586 req->data_stream = &gzip_stream->stream;
587 return ERROR_SUCCESS;
590 #else
592 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
594 ERR("gzip stream not supported, missing zlib.\n");
595 return ERROR_SUCCESS;
598 #endif
600 /***********************************************************************
601 * HTTP_FreeTokens (internal)
603 * Frees table of pointers.
605 static void HTTP_FreeTokens(LPWSTR * token_array)
607 int i;
608 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
609 heap_free(token_array);
612 static void HTTP_FixURL(http_request_t *request)
614 static const WCHAR szSlash[] = { '/',0 };
615 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
617 /* If we don't have a path we set it to root */
618 if (NULL == request->path)
619 request->path = heap_strdupW(szSlash);
620 else /* remove \r and \n*/
622 int nLen = strlenW(request->path);
623 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
625 nLen--;
626 request->path[nLen]='\0';
628 /* Replace '\' with '/' */
629 while (nLen>0) {
630 nLen--;
631 if (request->path[nLen] == '\\') request->path[nLen]='/';
635 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
636 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
637 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
639 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
640 *fixurl = '/';
641 strcpyW(fixurl + 1, request->path);
642 heap_free( request->path );
643 request->path = fixurl;
647 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
648 const WCHAR *path, const WCHAR *version, BOOL use_cr)
650 static const WCHAR szSpace[] = {' ',0};
651 static const WCHAR szColon[] = {':',' ',0};
652 static const WCHAR szCr[] = {'\r',0};
653 static const WCHAR szLf[] = {'\n',0};
654 LPWSTR requestString;
655 DWORD len, n;
656 LPCWSTR *req;
657 UINT i;
659 EnterCriticalSection( &request->headers_section );
661 /* allocate space for an array of all the string pointers to be added */
662 len = request->nCustHeaders * 5 + 10;
663 if (!(req = heap_alloc( len * sizeof(const WCHAR *) )))
665 LeaveCriticalSection( &request->headers_section );
666 return NULL;
669 /* add the verb, path and HTTP version string */
670 n = 0;
671 req[n++] = verb;
672 req[n++] = szSpace;
673 req[n++] = path;
674 req[n++] = szSpace;
675 req[n++] = version;
676 if (use_cr)
677 req[n++] = szCr;
678 req[n++] = szLf;
680 /* Append custom request headers */
681 for (i = 0; i < request->nCustHeaders; i++)
683 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
685 req[n++] = request->custHeaders[i].lpszField;
686 req[n++] = szColon;
687 req[n++] = request->custHeaders[i].lpszValue;
688 if (use_cr)
689 req[n++] = szCr;
690 req[n++] = szLf;
692 TRACE("Adding custom header %s (%s)\n",
693 debugstr_w(request->custHeaders[i].lpszField),
694 debugstr_w(request->custHeaders[i].lpszValue));
697 if (use_cr)
698 req[n++] = szCr;
699 req[n++] = szLf;
700 req[n] = NULL;
702 requestString = HTTP_build_req( req, 4 );
703 heap_free( req );
704 LeaveCriticalSection( &request->headers_section );
705 return requestString;
708 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
710 static const WCHAR colonW[] = { ':',' ',0 };
711 static const WCHAR crW[] = { '\r',0 };
712 static const WCHAR lfW[] = { '\n',0 };
713 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
714 const WCHAR **req;
715 WCHAR *ret, buf[14];
716 DWORD i, n = 0;
718 EnterCriticalSection( &request->headers_section );
720 if (!(req = heap_alloc( (request->nCustHeaders * 5 + 8) * sizeof(WCHAR *) )))
722 LeaveCriticalSection( &request->headers_section );
723 return NULL;
726 if (request->status_code)
728 req[n++] = request->version;
729 sprintfW(buf, status_fmt, request->status_code);
730 req[n++] = buf;
731 req[n++] = request->statusText;
732 if (use_cr)
733 req[n++] = crW;
734 req[n++] = lfW;
737 for(i = 0; i < request->nCustHeaders; i++)
739 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
740 && strcmpW(request->custHeaders[i].lpszField, szStatus))
742 req[n++] = request->custHeaders[i].lpszField;
743 req[n++] = colonW;
744 req[n++] = request->custHeaders[i].lpszValue;
745 if(use_cr)
746 req[n++] = crW;
747 req[n++] = lfW;
749 TRACE("Adding custom header %s (%s)\n",
750 debugstr_w(request->custHeaders[i].lpszField),
751 debugstr_w(request->custHeaders[i].lpszValue));
754 if(use_cr)
755 req[n++] = crW;
756 req[n++] = lfW;
757 req[n] = NULL;
759 ret = HTTP_build_req(req, 0);
760 heap_free(req);
761 LeaveCriticalSection( &request->headers_section );
762 return ret;
765 static void HTTP_ProcessCookies( http_request_t *request )
767 int HeaderIndex;
768 int numCookies = 0;
769 LPHTTPHEADERW setCookieHeader;
771 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
772 return;
774 EnterCriticalSection( &request->headers_section );
776 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
778 HTTPHEADERW *host;
779 const WCHAR *data;
780 WCHAR *name;
782 setCookieHeader = &request->custHeaders[HeaderIndex];
784 if (!setCookieHeader->lpszValue)
785 continue;
787 host = HTTP_GetHeader(request, hostW);
788 if(!host)
789 continue;
791 data = strchrW(setCookieHeader->lpszValue, '=');
792 if(!data)
793 continue;
795 name = heap_strndupW(setCookieHeader->lpszValue, data-setCookieHeader->lpszValue);
796 if(!name)
797 continue;
799 data++;
800 set_cookie(host->lpszValue, request->path, name, data, INTERNET_COOKIE_HTTPONLY);
801 heap_free(name);
804 LeaveCriticalSection( &request->headers_section );
807 static void strip_spaces(LPWSTR start)
809 LPWSTR str = start;
810 LPWSTR end;
812 while (*str == ' ' && *str != '\0')
813 str++;
815 if (str != start)
816 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
818 end = start + strlenW(start) - 1;
819 while (end >= start && *end == ' ')
821 *end = '\0';
822 end--;
826 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
828 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
829 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
830 BOOL is_basic;
831 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
832 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
833 if (is_basic && pszRealm)
835 LPCWSTR token;
836 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
837 LPCWSTR realm;
838 ptr++;
839 *pszRealm=NULL;
840 token = strchrW(ptr,'=');
841 if (!token)
842 return TRUE;
843 realm = ptr;
844 while (*realm == ' ' && *realm != '\0')
845 realm++;
846 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
847 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
849 token++;
850 while (*token == ' ' && *token != '\0')
851 token++;
852 if (*token == '\0')
853 return TRUE;
854 *pszRealm = heap_strdupW(token);
855 strip_spaces(*pszRealm);
859 return is_basic;
862 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
864 if (!authinfo) return;
866 if (SecIsValidHandle(&authinfo->ctx))
867 DeleteSecurityContext(&authinfo->ctx);
868 if (SecIsValidHandle(&authinfo->cred))
869 FreeCredentialsHandle(&authinfo->cred);
871 heap_free(authinfo->auth_data);
872 heap_free(authinfo->scheme);
873 heap_free(authinfo);
876 static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
878 basicAuthorizationData *ad;
879 UINT rc = 0;
881 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
883 EnterCriticalSection(&authcache_cs);
884 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
886 if (!strcmpiW(host,ad->host) && !strcmpW(realm,ad->realm))
888 TRACE("Authorization found in cache\n");
889 *auth_data = heap_alloc(ad->authorizationLen);
890 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
891 rc = ad->authorizationLen;
892 break;
895 LeaveCriticalSection(&authcache_cs);
896 return rc;
899 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
901 struct list *cursor;
902 basicAuthorizationData* ad = NULL;
904 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
906 EnterCriticalSection(&authcache_cs);
907 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
909 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
910 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
912 ad = check;
913 break;
917 if (ad)
919 TRACE("Found match in cache, replacing\n");
920 heap_free(ad->authorization);
921 ad->authorization = heap_alloc(auth_data_len);
922 memcpy(ad->authorization, auth_data, auth_data_len);
923 ad->authorizationLen = auth_data_len;
925 else
927 ad = heap_alloc(sizeof(basicAuthorizationData));
928 ad->host = heap_strdupW(host);
929 ad->realm = heap_strdupW(realm);
930 ad->authorization = heap_alloc(auth_data_len);
931 memcpy(ad->authorization, auth_data, auth_data_len);
932 ad->authorizationLen = auth_data_len;
933 list_add_head(&basicAuthorizationCache,&ad->entry);
934 TRACE("authorization cached\n");
936 LeaveCriticalSection(&authcache_cs);
939 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
940 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
942 authorizationData *ad;
944 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
946 EnterCriticalSection(&authcache_cs);
947 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
948 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
949 TRACE("Authorization found in cache\n");
951 nt_auth_identity->User = heap_strdupW(ad->user);
952 nt_auth_identity->Password = heap_strdupW(ad->password);
953 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
954 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
955 (!nt_auth_identity->Domain && ad->domain_len)) {
956 heap_free(nt_auth_identity->User);
957 heap_free(nt_auth_identity->Password);
958 heap_free(nt_auth_identity->Domain);
959 break;
962 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
963 nt_auth_identity->UserLength = ad->user_len;
964 nt_auth_identity->PasswordLength = ad->password_len;
965 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
966 nt_auth_identity->DomainLength = ad->domain_len;
967 LeaveCriticalSection(&authcache_cs);
968 return TRUE;
971 LeaveCriticalSection(&authcache_cs);
973 return FALSE;
976 static void cache_authorization(LPWSTR host, LPWSTR scheme,
977 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
979 authorizationData *ad;
980 BOOL found = FALSE;
982 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
984 EnterCriticalSection(&authcache_cs);
985 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
986 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
987 found = TRUE;
988 break;
991 if(found) {
992 heap_free(ad->user);
993 heap_free(ad->password);
994 heap_free(ad->domain);
995 } else {
996 ad = heap_alloc(sizeof(authorizationData));
997 if(!ad) {
998 LeaveCriticalSection(&authcache_cs);
999 return;
1002 ad->host = heap_strdupW(host);
1003 ad->scheme = heap_strdupW(scheme);
1004 list_add_head(&authorizationCache, &ad->entry);
1007 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
1008 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
1009 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
1010 ad->user_len = nt_auth_identity->UserLength;
1011 ad->password_len = nt_auth_identity->PasswordLength;
1012 ad->domain_len = nt_auth_identity->DomainLength;
1014 if(!ad->host || !ad->scheme || !ad->user || !ad->password
1015 || (nt_auth_identity->Domain && !ad->domain)) {
1016 heap_free(ad->host);
1017 heap_free(ad->scheme);
1018 heap_free(ad->user);
1019 heap_free(ad->password);
1020 heap_free(ad->domain);
1021 list_remove(&ad->entry);
1022 heap_free(ad);
1025 LeaveCriticalSection(&authcache_cs);
1028 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1029 struct HttpAuthInfo **ppAuthInfo,
1030 LPWSTR domain_and_username, LPWSTR password,
1031 LPWSTR host )
1033 SECURITY_STATUS sec_status;
1034 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1035 BOOL first = FALSE;
1036 LPWSTR szRealm = NULL;
1038 TRACE("%s\n", debugstr_w(pszAuthValue));
1040 if (!pAuthInfo)
1042 TimeStamp exp;
1044 first = TRUE;
1045 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1046 if (!pAuthInfo)
1047 return FALSE;
1049 SecInvalidateHandle(&pAuthInfo->cred);
1050 SecInvalidateHandle(&pAuthInfo->ctx);
1051 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1052 pAuthInfo->attr = 0;
1053 pAuthInfo->auth_data = NULL;
1054 pAuthInfo->auth_data_len = 0;
1055 pAuthInfo->finished = FALSE;
1057 if (is_basic_auth_value(pszAuthValue,NULL))
1059 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1060 pAuthInfo->scheme = heap_strdupW(szBasic);
1061 if (!pAuthInfo->scheme)
1063 heap_free(pAuthInfo);
1064 return FALSE;
1067 else
1069 PVOID pAuthData;
1070 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1072 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1073 if (!pAuthInfo->scheme)
1075 heap_free(pAuthInfo);
1076 return FALSE;
1079 if (domain_and_username)
1081 WCHAR *user = strchrW(domain_and_username, '\\');
1082 WCHAR *domain = domain_and_username;
1084 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1086 pAuthData = &nt_auth_identity;
1088 if (user) user++;
1089 else
1091 user = domain_and_username;
1092 domain = NULL;
1095 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1096 nt_auth_identity.User = user;
1097 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1098 nt_auth_identity.Domain = domain;
1099 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1100 nt_auth_identity.Password = password;
1101 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1103 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1105 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1106 pAuthData = &nt_auth_identity;
1107 else
1108 /* use default credentials */
1109 pAuthData = NULL;
1111 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1112 SECPKG_CRED_OUTBOUND, NULL,
1113 pAuthData, NULL,
1114 NULL, &pAuthInfo->cred,
1115 &exp);
1117 if(pAuthData && !domain_and_username) {
1118 heap_free(nt_auth_identity.User);
1119 heap_free(nt_auth_identity.Domain);
1120 heap_free(nt_auth_identity.Password);
1123 if (sec_status == SEC_E_OK)
1125 PSecPkgInfoW sec_pkg_info;
1126 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1127 if (sec_status == SEC_E_OK)
1129 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1130 FreeContextBuffer(sec_pkg_info);
1133 if (sec_status != SEC_E_OK)
1135 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1136 debugstr_w(pAuthInfo->scheme), sec_status);
1137 heap_free(pAuthInfo->scheme);
1138 heap_free(pAuthInfo);
1139 return FALSE;
1142 *ppAuthInfo = pAuthInfo;
1144 else if (pAuthInfo->finished)
1145 return FALSE;
1147 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1148 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1150 ERR("authentication scheme changed from %s to %s\n",
1151 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1152 return FALSE;
1155 if (is_basic_auth_value(pszAuthValue,&szRealm))
1157 int userlen;
1158 int passlen;
1159 char *auth_data = NULL;
1160 UINT auth_data_len = 0;
1162 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1164 if (!domain_and_username)
1166 if (host && szRealm)
1167 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1168 if (auth_data_len == 0)
1170 heap_free(szRealm);
1171 return FALSE;
1174 else
1176 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1177 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1179 /* length includes a nul terminator, which will be re-used for the ':' */
1180 auth_data = heap_alloc(userlen + 1 + passlen);
1181 if (!auth_data)
1183 heap_free(szRealm);
1184 return FALSE;
1187 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1188 auth_data[userlen] = ':';
1189 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1190 auth_data_len = userlen + 1 + passlen;
1191 if (host && szRealm)
1192 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1195 pAuthInfo->auth_data = auth_data;
1196 pAuthInfo->auth_data_len = auth_data_len;
1197 pAuthInfo->finished = TRUE;
1198 heap_free(szRealm);
1199 return TRUE;
1201 else
1203 LPCWSTR pszAuthData;
1204 SecBufferDesc out_desc, in_desc;
1205 SecBuffer out, in;
1206 unsigned char *buffer;
1207 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1208 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1210 in.BufferType = SECBUFFER_TOKEN;
1211 in.cbBuffer = 0;
1212 in.pvBuffer = NULL;
1214 in_desc.ulVersion = 0;
1215 in_desc.cBuffers = 1;
1216 in_desc.pBuffers = &in;
1218 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1219 if (*pszAuthData == ' ')
1221 pszAuthData++;
1222 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1223 in.pvBuffer = heap_alloc(in.cbBuffer);
1224 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1227 buffer = heap_alloc(pAuthInfo->max_token);
1229 out.BufferType = SECBUFFER_TOKEN;
1230 out.cbBuffer = pAuthInfo->max_token;
1231 out.pvBuffer = buffer;
1233 out_desc.ulVersion = 0;
1234 out_desc.cBuffers = 1;
1235 out_desc.pBuffers = &out;
1237 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1238 first ? NULL : &pAuthInfo->ctx,
1239 first ? request->server->name : NULL,
1240 context_req, 0, SECURITY_NETWORK_DREP,
1241 in.pvBuffer ? &in_desc : NULL,
1242 0, &pAuthInfo->ctx, &out_desc,
1243 &pAuthInfo->attr, &pAuthInfo->exp);
1244 if (sec_status == SEC_E_OK)
1246 pAuthInfo->finished = TRUE;
1247 pAuthInfo->auth_data = out.pvBuffer;
1248 pAuthInfo->auth_data_len = out.cbBuffer;
1249 TRACE("sending last auth packet\n");
1251 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1253 pAuthInfo->auth_data = out.pvBuffer;
1254 pAuthInfo->auth_data_len = out.cbBuffer;
1255 TRACE("sending next auth packet\n");
1257 else
1259 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1260 heap_free(out.pvBuffer);
1261 destroy_authinfo(pAuthInfo);
1262 *ppAuthInfo = NULL;
1263 return FALSE;
1267 return TRUE;
1270 /***********************************************************************
1271 * HTTP_HttpAddRequestHeadersW (internal)
1273 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1274 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1276 LPWSTR lpszStart;
1277 LPWSTR lpszEnd;
1278 LPWSTR buffer;
1279 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1281 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1283 if( dwHeaderLength == ~0U )
1284 len = strlenW(lpszHeader);
1285 else
1286 len = dwHeaderLength;
1287 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1288 lstrcpynW( buffer, lpszHeader, len + 1);
1290 lpszStart = buffer;
1294 LPWSTR * pFieldAndValue;
1296 lpszEnd = lpszStart;
1298 while (*lpszEnd != '\0')
1300 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1301 break;
1302 lpszEnd++;
1305 if (*lpszStart == '\0')
1306 break;
1308 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1310 *lpszEnd = '\0';
1311 lpszEnd++; /* Jump over newline */
1313 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1314 if (*lpszStart == '\0')
1316 /* Skip 0-length headers */
1317 lpszStart = lpszEnd;
1318 res = ERROR_SUCCESS;
1319 continue;
1321 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1322 if (pFieldAndValue)
1324 res = HTTP_VerifyValidHeader(request, pFieldAndValue[0]);
1325 if (res == ERROR_SUCCESS)
1326 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1327 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1328 HTTP_FreeTokens(pFieldAndValue);
1331 lpszStart = lpszEnd;
1332 } while (res == ERROR_SUCCESS);
1334 heap_free(buffer);
1335 return res;
1338 /***********************************************************************
1339 * HttpAddRequestHeadersW (WININET.@)
1341 * Adds one or more HTTP header to the request handler
1343 * NOTE
1344 * On Windows if dwHeaderLength includes the trailing '\0', then
1345 * HttpAddRequestHeadersW() adds it too. However this results in an
1346 * invalid HTTP header which is rejected by some servers so we probably
1347 * don't need to match Windows on that point.
1349 * RETURNS
1350 * TRUE on success
1351 * FALSE on failure
1354 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1355 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1357 http_request_t *request;
1358 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1360 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1362 if (!lpszHeader)
1363 return TRUE;
1365 request = (http_request_t*) get_handle_object( hHttpRequest );
1366 if (request && request->hdr.htype == WH_HHTTPREQ)
1367 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1368 if( request )
1369 WININET_Release( &request->hdr );
1371 if(res != ERROR_SUCCESS)
1372 SetLastError(res);
1373 return res == ERROR_SUCCESS;
1376 /***********************************************************************
1377 * HttpAddRequestHeadersA (WININET.@)
1379 * Adds one or more HTTP header to the request handler
1381 * RETURNS
1382 * TRUE on success
1383 * FALSE on failure
1386 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1387 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1389 DWORD len;
1390 LPWSTR hdr;
1391 BOOL r;
1393 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1395 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
1396 hdr = heap_alloc(len*sizeof(WCHAR));
1397 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
1398 if( dwHeaderLength != ~0U )
1399 dwHeaderLength = len;
1401 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
1403 heap_free( hdr );
1404 return r;
1407 static void free_accept_types( WCHAR **accept_types )
1409 WCHAR *ptr, **types = accept_types;
1411 if (!types) return;
1412 while ((ptr = *types))
1414 heap_free( ptr );
1415 types++;
1417 heap_free( accept_types );
1420 static WCHAR **convert_accept_types( const char **accept_types )
1422 unsigned int count;
1423 const char **types = accept_types;
1424 WCHAR **typesW;
1425 BOOL invalid_pointer = FALSE;
1427 if (!types) return NULL;
1428 count = 0;
1429 while (*types)
1431 __TRY
1433 /* find out how many there are */
1434 if (*types && **types)
1436 TRACE("accept type: %s\n", debugstr_a(*types));
1437 count++;
1440 __EXCEPT_PAGE_FAULT
1442 WARN("invalid accept type pointer\n");
1443 invalid_pointer = TRUE;
1445 __ENDTRY;
1446 types++;
1448 if (invalid_pointer) return NULL;
1449 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1450 count = 0;
1451 types = accept_types;
1452 while (*types)
1454 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1455 types++;
1457 typesW[count] = NULL;
1458 return typesW;
1461 /***********************************************************************
1462 * HttpOpenRequestA (WININET.@)
1464 * Open a HTTP request handle
1466 * RETURNS
1467 * HINTERNET a HTTP request handle on success
1468 * NULL on failure
1471 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1472 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1473 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1474 DWORD dwFlags, DWORD_PTR dwContext)
1476 LPWSTR szVerb = NULL, szObjectName = NULL;
1477 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1478 HINTERNET rc = NULL;
1480 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1481 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1482 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1483 dwFlags, dwContext);
1485 if (lpszVerb)
1487 szVerb = heap_strdupAtoW(lpszVerb);
1488 if ( !szVerb )
1489 goto end;
1492 if (lpszObjectName)
1494 szObjectName = heap_strdupAtoW(lpszObjectName);
1495 if ( !szObjectName )
1496 goto end;
1499 if (lpszVersion)
1501 szVersion = heap_strdupAtoW(lpszVersion);
1502 if ( !szVersion )
1503 goto end;
1506 if (lpszReferrer)
1508 szReferrer = heap_strdupAtoW(lpszReferrer);
1509 if ( !szReferrer )
1510 goto end;
1513 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1514 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1515 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1517 end:
1518 free_accept_types(szAcceptTypes);
1519 heap_free(szReferrer);
1520 heap_free(szVersion);
1521 heap_free(szObjectName);
1522 heap_free(szVerb);
1523 return rc;
1526 /***********************************************************************
1527 * HTTP_EncodeBase64
1529 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1531 UINT n = 0, x;
1532 static const CHAR HTTP_Base64Enc[] =
1533 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1535 while( len > 0 )
1537 /* first 6 bits, all from bin[0] */
1538 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1539 x = (bin[0] & 3) << 4;
1541 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1542 if( len == 1 )
1544 base64[n++] = HTTP_Base64Enc[x];
1545 base64[n++] = '=';
1546 base64[n++] = '=';
1547 break;
1549 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1550 x = ( bin[1] & 0x0f ) << 2;
1552 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1553 if( len == 2 )
1555 base64[n++] = HTTP_Base64Enc[x];
1556 base64[n++] = '=';
1557 break;
1559 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1561 /* last 6 bits, all from bin [2] */
1562 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1563 bin += 3;
1564 len -= 3;
1566 base64[n] = 0;
1567 return n;
1570 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1571 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1572 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1573 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1574 static const signed char HTTP_Base64Dec[256] =
1576 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1577 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1578 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1579 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1580 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1581 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1582 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1583 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1584 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1585 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1586 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1587 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1588 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1589 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1590 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1591 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1592 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1593 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1594 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1595 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1596 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1597 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1598 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1599 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1600 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1601 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1603 #undef CH
1605 /***********************************************************************
1606 * HTTP_DecodeBase64
1608 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1610 unsigned int n = 0;
1612 while(*base64)
1614 signed char in[4];
1616 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1617 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1618 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1619 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1621 WARN("invalid base64: %s\n", debugstr_w(base64));
1622 return 0;
1624 if (bin)
1625 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1626 n++;
1628 if ((base64[2] == '=') && (base64[3] == '='))
1629 break;
1630 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1631 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1633 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1634 return 0;
1636 if (bin)
1637 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1638 n++;
1640 if (base64[3] == '=')
1641 break;
1642 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1643 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1645 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1646 return 0;
1648 if (bin)
1649 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1650 n++;
1652 base64 += 4;
1655 return n;
1658 /***********************************************************************
1659 * HTTP_InsertAuthorization
1661 * Insert or delete the authorization field in the request header.
1663 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1665 if (pAuthInfo)
1667 static const WCHAR wszSpace[] = {' ',0};
1668 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1669 unsigned int len;
1670 WCHAR *authorization = NULL;
1672 if (pAuthInfo->auth_data_len)
1674 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1675 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1676 authorization = heap_alloc((len+1)*sizeof(WCHAR));
1677 if (!authorization)
1678 return FALSE;
1680 strcpyW(authorization, pAuthInfo->scheme);
1681 strcatW(authorization, wszSpace);
1682 HTTP_EncodeBase64(pAuthInfo->auth_data,
1683 pAuthInfo->auth_data_len,
1684 authorization+strlenW(authorization));
1686 /* clear the data as it isn't valid now that it has been sent to the
1687 * server, unless it's Basic authentication which doesn't do
1688 * connection tracking */
1689 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1691 heap_free(pAuthInfo->auth_data);
1692 pAuthInfo->auth_data = NULL;
1693 pAuthInfo->auth_data_len = 0;
1697 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1699 HTTP_ProcessHeader(request, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1700 heap_free(authorization);
1702 return TRUE;
1705 static WCHAR *build_proxy_path_url(http_request_t *req)
1707 DWORD size, len;
1708 WCHAR *url;
1710 len = strlenW(req->server->scheme_host_port);
1711 size = len + strlenW(req->path) + 1;
1712 if(*req->path != '/')
1713 size++;
1714 url = heap_alloc(size * sizeof(WCHAR));
1715 if(!url)
1716 return NULL;
1718 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1719 if(*req->path != '/')
1720 url[len++] = '/';
1722 strcpyW(url+len, req->path);
1724 TRACE("url=%s\n", debugstr_w(url));
1725 return url;
1728 static BOOL HTTP_DomainMatches(LPCWSTR server, LPCWSTR domain)
1730 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1731 BOOL ret = FALSE;
1733 if (!strcmpiW( domain, localW ) && !strchrW( server, '.' ))
1734 ret = TRUE;
1735 else if (*domain == '*')
1737 if (domain[1] == '.')
1739 LPCWSTR dot;
1741 /* For a hostname to match a wildcard, the last domain must match
1742 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1743 * hostname is www.foo.a.b, it matches, but a.b does not.
1745 dot = strchrW( server, '.' );
1746 if (dot)
1748 int len = strlenW( dot + 1 );
1750 if (len > strlenW( domain + 2 ))
1752 LPCWSTR ptr;
1754 /* The server's domain is longer than the wildcard, so it
1755 * could be a subdomain. Compare the last portion of the
1756 * server's domain.
1758 ptr = dot + len + 1 - strlenW( domain + 2 );
1759 if (!strcmpiW( ptr, domain + 2 ))
1761 /* This is only a match if the preceding character is
1762 * a '.', i.e. that it is a matching domain. E.g.
1763 * if domain is '*.b.c' and server is 'www.ab.c' they
1764 * do not match.
1766 ret = *(ptr - 1) == '.';
1769 else
1770 ret = !strcmpiW( dot + 1, domain + 2 );
1774 else
1775 ret = !strcmpiW( server, domain );
1776 return ret;
1779 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1781 LPCWSTR ptr;
1782 BOOL ret = FALSE;
1784 if (!lpwai->proxyBypass) return FALSE;
1785 ptr = lpwai->proxyBypass;
1786 do {
1787 LPCWSTR tmp = ptr;
1789 ptr = strchrW( ptr, ';' );
1790 if (!ptr)
1791 ptr = strchrW( tmp, ' ' );
1792 if (ptr)
1794 if (ptr - tmp < INTERNET_MAX_HOST_NAME_LENGTH)
1796 WCHAR domain[INTERNET_MAX_HOST_NAME_LENGTH];
1798 memcpy( domain, tmp, (ptr - tmp) * sizeof(WCHAR) );
1799 domain[ptr - tmp] = 0;
1800 ret = HTTP_DomainMatches( server, domain );
1802 ptr += 1;
1804 else if (*tmp)
1805 ret = HTTP_DomainMatches( server, tmp );
1806 } while (ptr && !ret);
1807 return ret;
1810 /***********************************************************************
1811 * HTTP_DealWithProxy
1813 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1815 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1816 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1817 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1818 WCHAR buf[INTERNET_MAX_HOST_NAME_LENGTH];
1819 WCHAR protoProxy[INTERNET_MAX_URL_LENGTH];
1820 DWORD protoProxyLen = INTERNET_MAX_URL_LENGTH;
1821 WCHAR proxy[INTERNET_MAX_URL_LENGTH];
1822 static WCHAR szNul[] = { 0 };
1823 URL_COMPONENTSW UrlComponents;
1824 server_t *new_server;
1825 BOOL is_https;
1827 memset( &UrlComponents, 0, sizeof UrlComponents );
1828 UrlComponents.dwStructSize = sizeof UrlComponents;
1829 UrlComponents.lpszHostName = buf;
1830 UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
1832 if (!INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp, protoProxy, &protoProxyLen))
1833 return FALSE;
1834 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1835 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1836 sprintfW(proxy, szFormat, protoProxy);
1837 else
1838 strcpyW(proxy, protoProxy);
1839 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1840 return FALSE;
1841 if( UrlComponents.dwHostNameLength == 0 )
1842 return FALSE;
1844 if( !request->path )
1845 request->path = szNul;
1847 is_https = (UrlComponents.nScheme == INTERNET_SCHEME_HTTPS);
1848 if (is_https && UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1849 UrlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1851 new_server = get_server(UrlComponents.lpszHostName, UrlComponents.nPort, is_https, TRUE);
1852 if(!new_server)
1853 return FALSE;
1855 request->proxy = new_server;
1857 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1858 return TRUE;
1861 static DWORD HTTP_ResolveName(http_request_t *request)
1863 server_t *server = request->proxy ? request->proxy : request->server;
1864 socklen_t addr_len;
1865 void *addr;
1867 if(server->addr_len)
1868 return ERROR_SUCCESS;
1870 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1871 INTERNET_STATUS_RESOLVING_NAME,
1872 server->name,
1873 (strlenW(server->name)+1) * sizeof(WCHAR));
1875 addr_len = sizeof(server->addr);
1876 if (!GetAddress(server->name, server->port, (struct sockaddr *)&server->addr, &addr_len))
1877 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1879 switch(server->addr.ss_family) {
1880 case AF_INET:
1881 addr = &((struct sockaddr_in *)&server->addr)->sin_addr;
1882 break;
1883 case AF_INET6:
1884 addr = &((struct sockaddr_in6 *)&server->addr)->sin6_addr;
1885 break;
1886 default:
1887 WARN("unsupported family %d\n", server->addr.ss_family);
1888 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1891 server->addr_len = addr_len;
1892 inet_ntop(server->addr.ss_family, addr, server->addr_str, sizeof(server->addr_str));
1893 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1894 INTERNET_STATUS_NAME_RESOLVED,
1895 server->addr_str, strlen(server->addr_str)+1);
1897 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1898 return ERROR_SUCCESS;
1901 static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
1903 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1904 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1905 static const WCHAR slash[] = { '/',0 };
1906 LPHTTPHEADERW host_header;
1907 LPCWSTR scheme;
1909 host_header = HTTP_GetHeader(req, hostW);
1910 if(!host_header)
1911 return FALSE;
1913 EnterCriticalSection( &req->headers_section );
1915 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1916 scheme = https;
1917 else
1918 scheme = http;
1919 strcpyW(buf, scheme);
1920 strcatW(buf, host_header->lpszValue);
1921 if (req->path[0] != '/')
1922 strcatW(buf, slash);
1923 strcatW(buf, req->path);
1925 LeaveCriticalSection( &req->headers_section );
1926 return TRUE;
1930 /***********************************************************************
1931 * HTTPREQ_Destroy (internal)
1933 * Deallocate request handle
1936 static void HTTPREQ_Destroy(object_header_t *hdr)
1938 http_request_t *request = (http_request_t*) hdr;
1939 DWORD i;
1941 TRACE("\n");
1943 if(request->hCacheFile)
1944 CloseHandle(request->hCacheFile);
1945 if(request->req_file)
1946 req_file_release(request->req_file);
1948 request->headers_section.DebugInfo->Spare[0] = 0;
1949 DeleteCriticalSection( &request->headers_section );
1950 request->read_section.DebugInfo->Spare[0] = 0;
1951 DeleteCriticalSection( &request->read_section );
1952 WININET_Release(&request->session->hdr);
1954 destroy_authinfo(request->authInfo);
1955 destroy_authinfo(request->proxyAuthInfo);
1957 if(request->server)
1958 server_release(request->server);
1959 if(request->proxy)
1960 server_release(request->proxy);
1962 heap_free(request->path);
1963 heap_free(request->verb);
1964 heap_free(request->version);
1965 heap_free(request->statusText);
1967 for (i = 0; i < request->nCustHeaders; i++)
1969 heap_free(request->custHeaders[i].lpszField);
1970 heap_free(request->custHeaders[i].lpszValue);
1972 destroy_data_stream(request->data_stream);
1973 heap_free(request->custHeaders);
1976 static void http_release_netconn(http_request_t *req, BOOL reuse)
1978 TRACE("%p %p %x\n",req, req->netconn, reuse);
1980 if(!is_valid_netconn(req->netconn))
1981 return;
1983 if(reuse && req->netconn->keep_alive) {
1984 BOOL run_collector;
1986 EnterCriticalSection(&connection_pool_cs);
1988 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1989 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1990 req->netconn = NULL;
1992 run_collector = !collector_running;
1993 collector_running = TRUE;
1995 LeaveCriticalSection(&connection_pool_cs);
1997 if(run_collector) {
1998 HANDLE thread = NULL;
1999 HMODULE module;
2001 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
2002 if(module)
2003 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
2004 if(!thread) {
2005 EnterCriticalSection(&connection_pool_cs);
2006 collector_running = FALSE;
2007 LeaveCriticalSection(&connection_pool_cs);
2009 if(module)
2010 FreeLibrary(module);
2012 else
2013 CloseHandle(thread);
2015 return;
2018 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
2019 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
2021 close_netconn(req->netconn);
2023 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
2024 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
2027 static BOOL HTTP_KeepAlive(http_request_t *request)
2029 WCHAR szVersion[10];
2030 WCHAR szConnectionResponse[20];
2031 DWORD dwBufferSize = sizeof(szVersion);
2032 BOOL keepalive = FALSE;
2034 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2035 * the connection is keep-alive by default */
2036 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
2037 && !strcmpiW(szVersion, g_szHttp1_1))
2039 keepalive = TRUE;
2042 dwBufferSize = sizeof(szConnectionResponse);
2043 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2044 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2046 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2049 return keepalive;
2052 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2054 http_request_t *req = (http_request_t*)hdr;
2056 http_release_netconn(req, drain_content(req, FALSE));
2059 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2061 int len;
2062 if (unicode)
2064 WCHAR *buf = buffer;
2066 if (str) len = strlenW(str);
2067 else len = 0;
2068 if (*size < (len + 1) * sizeof(WCHAR))
2070 *size = (len + 1) * sizeof(WCHAR);
2071 return ERROR_INSUFFICIENT_BUFFER;
2073 if (str) strcpyW(buf, str);
2074 else buf[0] = 0;
2076 *size = len;
2077 return ERROR_SUCCESS;
2079 else
2081 char *buf = buffer;
2083 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2084 else len = 1;
2085 if (*size < len)
2087 *size = len;
2088 return ERROR_INSUFFICIENT_BUFFER;
2090 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2091 else buf[0] = 0;
2093 *size = len - 1;
2094 return ERROR_SUCCESS;
2098 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2100 http_request_t *req = (http_request_t*)hdr;
2102 switch(option) {
2103 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2105 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2107 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2109 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2110 return ERROR_INSUFFICIENT_BUFFER;
2111 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2112 /* FIXME: can't get a SOCKET from our connection since we don't use
2113 * winsock
2115 info->Socket = 0;
2116 /* FIXME: get source port from req->netConnection */
2117 info->SourcePort = 0;
2118 info->DestPort = req->server->port;
2119 info->Flags = 0;
2120 if (HTTP_KeepAlive(req))
2121 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2122 if (req->proxy)
2123 info->Flags |= IDSI_FLAG_PROXY;
2124 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2125 info->Flags |= IDSI_FLAG_SECURE;
2127 return ERROR_SUCCESS;
2130 case 98:
2131 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2132 /* fall through */
2133 case INTERNET_OPTION_SECURITY_FLAGS:
2135 DWORD flags;
2137 if (*size < sizeof(ULONG))
2138 return ERROR_INSUFFICIENT_BUFFER;
2140 *size = sizeof(DWORD);
2141 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2142 *(DWORD *)buffer = flags;
2144 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2145 return ERROR_SUCCESS;
2148 case INTERNET_OPTION_HANDLE_TYPE:
2149 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2151 if (*size < sizeof(ULONG))
2152 return ERROR_INSUFFICIENT_BUFFER;
2154 *size = sizeof(DWORD);
2155 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2156 return ERROR_SUCCESS;
2158 case INTERNET_OPTION_URL: {
2159 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
2160 WCHAR url[INTERNET_MAX_URL_LENGTH];
2161 HTTPHEADERW *host;
2163 TRACE("INTERNET_OPTION_URL\n");
2165 EnterCriticalSection( &req->headers_section );
2166 host = HTTP_GetHeader(req, hostW);
2167 strcpyW(url, httpW);
2168 strcatW(url, host->lpszValue);
2169 strcatW(url, req->path);
2170 LeaveCriticalSection( &req->headers_section );
2172 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
2173 return str_to_buffer(url, buffer, size, unicode);
2175 case INTERNET_OPTION_USER_AGENT:
2176 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2177 case INTERNET_OPTION_USERNAME:
2178 return str_to_buffer(req->session->userName, buffer, size, unicode);
2179 case INTERNET_OPTION_PASSWORD:
2180 return str_to_buffer(req->session->password, buffer, size, unicode);
2181 case INTERNET_OPTION_PROXY_USERNAME:
2182 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2183 case INTERNET_OPTION_PROXY_PASSWORD:
2184 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2186 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2187 INTERNET_CACHE_ENTRY_INFOW *info;
2188 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2189 WCHAR url[INTERNET_MAX_URL_LENGTH];
2190 DWORD nbytes, error;
2191 BOOL ret;
2193 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2195 if (*size < sizeof(*ts))
2197 *size = sizeof(*ts);
2198 return ERROR_INSUFFICIENT_BUFFER;
2200 nbytes = 0;
2201 HTTP_GetRequestURL(req, url);
2202 ret = GetUrlCacheEntryInfoW(url, NULL, &nbytes);
2203 error = GetLastError();
2204 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2206 if (!(info = heap_alloc(nbytes)))
2207 return ERROR_OUTOFMEMORY;
2209 GetUrlCacheEntryInfoW(url, info, &nbytes);
2211 ts->ftExpires = info->ExpireTime;
2212 ts->ftLastModified = info->LastModifiedTime;
2214 heap_free(info);
2215 *size = sizeof(*ts);
2216 return ERROR_SUCCESS;
2218 return error;
2221 case INTERNET_OPTION_DATAFILE_NAME: {
2222 DWORD req_size;
2224 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2226 if(!req->req_file) {
2227 *size = 0;
2228 return ERROR_INTERNET_ITEM_NOT_FOUND;
2231 if(unicode) {
2232 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2233 if(*size < req_size)
2234 return ERROR_INSUFFICIENT_BUFFER;
2236 *size = req_size;
2237 memcpy(buffer, req->req_file->file_name, *size);
2238 return ERROR_SUCCESS;
2239 }else {
2240 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2241 if (req_size > *size)
2242 return ERROR_INSUFFICIENT_BUFFER;
2244 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2245 -1, buffer, *size, NULL, NULL);
2246 return ERROR_SUCCESS;
2250 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2251 PCCERT_CONTEXT context;
2253 if(!req->netconn)
2254 return ERROR_INTERNET_INVALID_OPERATION;
2256 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2257 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2258 return ERROR_INSUFFICIENT_BUFFER;
2261 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2262 if(context) {
2263 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2264 DWORD len;
2266 memset(info, 0, sizeof(*info));
2267 info->ftExpiry = context->pCertInfo->NotAfter;
2268 info->ftStart = context->pCertInfo->NotBefore;
2269 len = CertNameToStrA(context->dwCertEncodingType,
2270 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2271 info->lpszSubjectInfo = LocalAlloc(0, len);
2272 if(info->lpszSubjectInfo)
2273 CertNameToStrA(context->dwCertEncodingType,
2274 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2275 info->lpszSubjectInfo, len);
2276 len = CertNameToStrA(context->dwCertEncodingType,
2277 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2278 info->lpszIssuerInfo = LocalAlloc(0, len);
2279 if(info->lpszIssuerInfo)
2280 CertNameToStrA(context->dwCertEncodingType,
2281 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2282 info->lpszIssuerInfo, len);
2283 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2284 CertFreeCertificateContext(context);
2285 return ERROR_SUCCESS;
2287 return ERROR_NOT_SUPPORTED;
2289 case INTERNET_OPTION_CONNECT_TIMEOUT:
2290 if (*size < sizeof(DWORD))
2291 return ERROR_INSUFFICIENT_BUFFER;
2293 *size = sizeof(DWORD);
2294 *(DWORD *)buffer = req->connect_timeout;
2295 return ERROR_SUCCESS;
2296 case INTERNET_OPTION_REQUEST_FLAGS: {
2297 DWORD flags = 0;
2299 if (*size < sizeof(DWORD))
2300 return ERROR_INSUFFICIENT_BUFFER;
2302 /* FIXME: Add support for:
2303 * INTERNET_REQFLAG_FROM_CACHE
2304 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2307 if(req->proxy)
2308 flags |= INTERNET_REQFLAG_VIA_PROXY;
2309 if(!req->status_code)
2310 flags |= INTERNET_REQFLAG_NO_HEADERS;
2312 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2314 *size = sizeof(DWORD);
2315 *(DWORD*)buffer = flags;
2316 return ERROR_SUCCESS;
2320 return INET_QueryOption(hdr, option, buffer, size, unicode);
2323 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2325 http_request_t *req = (http_request_t*)hdr;
2327 switch(option) {
2328 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2329 TRACE("Undocumented option 99\n");
2331 if (!buffer || size != sizeof(DWORD))
2332 return ERROR_INVALID_PARAMETER;
2333 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2334 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2336 /* fall through */
2337 case INTERNET_OPTION_SECURITY_FLAGS:
2339 DWORD flags;
2341 if (!buffer || size != sizeof(DWORD))
2342 return ERROR_INVALID_PARAMETER;
2343 flags = *(DWORD *)buffer;
2344 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2345 flags &= SECURITY_SET_MASK;
2346 req->security_flags |= flags;
2347 if(is_valid_netconn(req->netconn))
2348 req->netconn->security_flags |= flags;
2349 return ERROR_SUCCESS;
2351 case INTERNET_OPTION_CONNECT_TIMEOUT:
2352 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2353 req->connect_timeout = *(DWORD *)buffer;
2354 return ERROR_SUCCESS;
2356 case INTERNET_OPTION_SEND_TIMEOUT:
2357 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2358 req->send_timeout = *(DWORD *)buffer;
2359 return ERROR_SUCCESS;
2361 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2362 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2363 req->receive_timeout = *(DWORD *)buffer;
2364 return ERROR_SUCCESS;
2366 case INTERNET_OPTION_USERNAME:
2367 heap_free(req->session->userName);
2368 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2369 return ERROR_SUCCESS;
2371 case INTERNET_OPTION_PASSWORD:
2372 heap_free(req->session->password);
2373 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2374 return ERROR_SUCCESS;
2376 case INTERNET_OPTION_PROXY_USERNAME:
2377 heap_free(req->session->appInfo->proxyUsername);
2378 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2379 return ERROR_SUCCESS;
2381 case INTERNET_OPTION_PROXY_PASSWORD:
2382 heap_free(req->session->appInfo->proxyPassword);
2383 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2384 return ERROR_SUCCESS;
2386 case INTERNET_OPTION_HTTP_DECODING:
2387 if(size != sizeof(BOOL))
2388 return ERROR_INVALID_PARAMETER;
2389 req->decoding = *(BOOL*)buffer;
2390 return ERROR_SUCCESS;
2393 return INET_SetOption(hdr, option, buffer, size);
2396 static void commit_cache_entry(http_request_t *req)
2398 WCHAR url[INTERNET_MAX_URL_LENGTH];
2400 TRACE("%p\n", req);
2402 CloseHandle(req->hCacheFile);
2403 req->hCacheFile = NULL;
2405 if(HTTP_GetRequestURL(req, url)) {
2406 WCHAR *header;
2407 DWORD header_len;
2408 BOOL res;
2410 header = build_response_header(req, TRUE);
2411 header_len = (header ? strlenW(header) : 0);
2412 res = CommitUrlCacheEntryW(url, req->req_file->file_name, req->expires,
2413 req->last_modified, NORMAL_CACHE_ENTRY,
2414 header, header_len, NULL, 0);
2415 if(res)
2416 req->req_file->is_committed = TRUE;
2417 else
2418 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2419 heap_free(header);
2423 static void create_cache_entry(http_request_t *req)
2425 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2426 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2428 WCHAR url[INTERNET_MAX_URL_LENGTH];
2429 WCHAR file_name[MAX_PATH+1];
2430 BOOL b = TRUE;
2432 /* FIXME: We should free previous cache file earlier */
2433 if(req->req_file) {
2434 req_file_release(req->req_file);
2435 req->req_file = NULL;
2437 if(req->hCacheFile) {
2438 CloseHandle(req->hCacheFile);
2439 req->hCacheFile = NULL;
2442 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2443 b = FALSE;
2445 if(b) {
2446 int header_idx;
2448 EnterCriticalSection( &req->headers_section );
2450 header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2451 if(header_idx != -1) {
2452 WCHAR *ptr;
2454 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2455 WCHAR *end;
2457 while(*ptr==' ' || *ptr=='\t')
2458 ptr++;
2460 end = strchrW(ptr, ',');
2461 if(!end)
2462 end = ptr + strlenW(ptr);
2464 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2465 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2466 b = FALSE;
2467 break;
2470 ptr = end;
2471 if(*ptr == ',')
2472 ptr++;
2476 LeaveCriticalSection( &req->headers_section );
2479 if(!b) {
2480 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2481 return;
2483 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2486 b = HTTP_GetRequestURL(req, url);
2487 if(!b) {
2488 WARN("Could not get URL\n");
2489 return;
2492 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2493 if(!b) {
2494 WARN("Could not create cache entry: %08x\n", GetLastError());
2495 return;
2498 create_req_file(file_name, &req->req_file);
2500 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2501 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2502 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2503 WARN("Could not create file: %u\n", GetLastError());
2504 req->hCacheFile = NULL;
2505 return;
2508 if(req->read_size) {
2509 DWORD written;
2511 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2512 if(!b)
2513 FIXME("WriteFile failed: %u\n", GetLastError());
2515 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2516 commit_cache_entry(req);
2520 /* read some more data into the read buffer (the read section must be held) */
2521 static DWORD read_more_data( http_request_t *req, int maxlen )
2523 DWORD res;
2524 int len;
2526 if (req->read_pos)
2528 /* move existing data to the start of the buffer */
2529 if(req->read_size)
2530 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2531 req->read_pos = 0;
2534 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2536 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2537 maxlen - req->read_size, BLOCKING_ALLOW, &len );
2538 if(res == ERROR_SUCCESS)
2539 req->read_size += len;
2541 return res;
2544 /* remove some amount of data from the read buffer (the read section must be held) */
2545 static void remove_data( http_request_t *req, int count )
2547 if (!(req->read_size -= count)) req->read_pos = 0;
2548 else req->read_pos += count;
2551 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2553 int count, bytes_read, pos = 0;
2554 DWORD res;
2556 EnterCriticalSection( &req->read_section );
2557 for (;;)
2559 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2561 if (eol)
2563 count = eol - (req->read_buf + req->read_pos);
2564 bytes_read = count + 1;
2566 else count = bytes_read = req->read_size;
2568 count = min( count, *len - pos );
2569 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2570 pos += count;
2571 remove_data( req, bytes_read );
2572 if (eol) break;
2574 if ((res = read_more_data( req, -1 )))
2576 WARN( "read failed %u\n", res );
2577 LeaveCriticalSection( &req->read_section );
2578 return res;
2580 if (!req->read_size)
2582 *len = 0;
2583 TRACE( "returning empty string\n" );
2584 LeaveCriticalSection( &req->read_section );
2585 return ERROR_SUCCESS;
2588 LeaveCriticalSection( &req->read_section );
2590 if (pos < *len)
2592 if (pos && buffer[pos - 1] == '\r') pos--;
2593 *len = pos + 1;
2595 buffer[*len - 1] = 0;
2596 TRACE( "returning %s\n", debugstr_a(buffer));
2597 return ERROR_SUCCESS;
2600 /* check if we have reached the end of the data to read (the read section must be held) */
2601 static BOOL end_of_read_data( http_request_t *req )
2603 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2606 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, blocking_mode_t blocking_mode)
2608 DWORD res;
2610 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, blocking_mode);
2611 assert(*read <= size);
2613 if(req->hCacheFile) {
2614 if(*read) {
2615 BOOL bres;
2616 DWORD written;
2618 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2619 if(!bres)
2620 FIXME("WriteFile failed: %u\n", GetLastError());
2623 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2624 commit_cache_entry(req);
2627 return res;
2630 /* fetch some more data into the read buffer (the read section must be held) */
2631 static DWORD refill_read_buffer(http_request_t *req, blocking_mode_t blocking_mode, DWORD *read_bytes)
2633 DWORD res, read=0;
2635 if(req->read_size == sizeof(req->read_buf))
2636 return ERROR_SUCCESS;
2638 if(req->read_pos) {
2639 if(req->read_size)
2640 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2641 req->read_pos = 0;
2644 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2645 &read, blocking_mode);
2646 req->read_size += read;
2648 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2649 if(read_bytes)
2650 *read_bytes = read;
2651 return res;
2654 /* return the size of data available to be read immediately (the read section must be held) */
2655 static DWORD get_avail_data( http_request_t *req )
2657 return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2660 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2662 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2663 DWORD avail = 0;
2665 if(is_valid_netconn(req->netconn))
2666 NETCON_query_data_available(req->netconn, &avail);
2667 return netconn_stream->content_length == ~0u
2668 ? avail
2669 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2672 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2674 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2675 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2678 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2679 DWORD *read, blocking_mode_t blocking_mode)
2681 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2682 DWORD res = ERROR_SUCCESS;
2683 int len = 0;
2685 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2687 if(size && is_valid_netconn(req->netconn)) {
2688 if((res = NETCON_recv(req->netconn, buf, size, blocking_mode, &len))) {
2689 len = 0;
2690 if(blocking_mode == BLOCKING_DISALLOW && res == WSAEWOULDBLOCK)
2691 res = ERROR_SUCCESS;
2692 else
2693 netconn_stream->content_length = netconn_stream->content_read;
2694 }else if(!len) {
2695 netconn_stream->content_length = netconn_stream->content_read;
2699 netconn_stream->content_read += *read = len;
2700 TRACE("read %u bytes\n", len);
2701 return res;
2704 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2706 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2707 BYTE buf[1024];
2708 int len;
2710 if(netconn_end_of_data(stream, req))
2711 return TRUE;
2713 do {
2714 if(NETCON_recv(req->netconn, buf, sizeof(buf), BLOCKING_DISALLOW, &len) != ERROR_SUCCESS)
2715 return FALSE;
2717 netconn_stream->content_read += len;
2718 }while(netconn_stream->content_read < netconn_stream->content_length);
2720 return TRUE;
2723 static void netconn_destroy(data_stream_t *stream)
2727 static const data_stream_vtbl_t netconn_stream_vtbl = {
2728 netconn_get_avail_data,
2729 netconn_end_of_data,
2730 netconn_read,
2731 netconn_drain_content,
2732 netconn_destroy
2735 /* read some more data into the read buffer (the read section must be held) */
2736 static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
2738 DWORD res;
2739 int len;
2741 assert(!stream->end_of_data);
2743 if (stream->buf_pos)
2745 /* move existing data to the start of the buffer */
2746 if(stream->buf_size)
2747 memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
2748 stream->buf_pos = 0;
2751 if (maxlen == -1) maxlen = sizeof(stream->buf);
2753 res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2754 maxlen - stream->buf_size, BLOCKING_ALLOW, &len );
2755 if(res == ERROR_SUCCESS)
2756 stream->buf_size += len;
2758 return res;
2761 /* remove some amount of data from the read buffer (the read section must be held) */
2762 static void remove_chunked_data(chunked_stream_t *stream, int count)
2764 if (!(stream->buf_size -= count)) stream->buf_pos = 0;
2765 else stream->buf_pos += count;
2768 /* discard data contents until we reach end of line (the read section must be held) */
2769 static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2771 DWORD res;
2775 BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2776 if (eol)
2778 remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2779 break;
2781 stream->buf_pos = stream->buf_size = 0; /* discard everything */
2782 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2783 } while (stream->buf_size);
2784 return ERROR_SUCCESS;
2787 /* read the size of the next chunk (the read section must be held) */
2788 static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2790 DWORD chunk_size = 0, res;
2792 assert(!stream->chunk_size || stream->chunk_size == ~0u);
2794 if (stream->end_of_data) return ERROR_SUCCESS;
2796 /* read terminator for the previous chunk */
2797 if(!stream->chunk_size && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2798 return res;
2800 for (;;)
2802 while (stream->buf_size)
2804 char ch = stream->buf[stream->buf_pos];
2805 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2806 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2807 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2808 else if (ch == ';' || ch == '\r' || ch == '\n')
2810 TRACE( "reading %u byte chunk\n", chunk_size );
2811 stream->chunk_size = chunk_size;
2812 if (req->contentLength == ~0u) req->contentLength = chunk_size;
2813 else req->contentLength += chunk_size;
2815 if (!chunk_size) stream->end_of_data = TRUE;
2816 return discard_chunked_eol(stream, req);
2818 remove_chunked_data(stream, 1);
2820 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2821 if (!stream->buf_size)
2823 stream->chunk_size = 0;
2824 return ERROR_SUCCESS;
2829 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2831 /* Allow reading only from read buffer */
2832 return 0;
2835 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2837 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2838 return chunked_stream->end_of_data;
2841 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2842 DWORD *read, blocking_mode_t blocking_mode)
2844 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2845 DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;
2847 if(!chunked_stream->chunk_size || chunked_stream->chunk_size == ~0u) {
2848 res = start_next_chunk(chunked_stream, req);
2849 if(res != ERROR_SUCCESS)
2850 return res;
2853 while(size && chunked_stream->chunk_size && !chunked_stream->end_of_data) {
2854 if(chunked_stream->buf_size) {
2855 read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2857 /* this could block */
2858 if(blocking_mode == BLOCKING_DISALLOW && read_bytes == chunked_stream->chunk_size)
2859 break;
2861 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2862 remove_chunked_data(chunked_stream, read_bytes);
2863 }else {
2864 read_bytes = min(size, chunked_stream->chunk_size);
2866 if(blocking_mode == BLOCKING_DISALLOW) {
2867 DWORD avail;
2869 if(!is_valid_netconn(req->netconn) || !NETCON_query_data_available(req->netconn, &avail) || !avail)
2870 break;
2871 if(read_bytes > avail)
2872 read_bytes = avail;
2874 /* this could block */
2875 if(read_bytes == chunked_stream->chunk_size)
2876 break;
2879 res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, BLOCKING_ALLOW, (int*)&read_bytes);
2880 if(res != ERROR_SUCCESS)
2881 break;
2884 chunked_stream->chunk_size -= read_bytes;
2885 size -= read_bytes;
2886 ret_read += read_bytes;
2887 if(size && !chunked_stream->chunk_size) {
2888 assert(blocking_mode != BLOCKING_DISALLOW);
2889 res = start_next_chunk(chunked_stream, req);
2890 if(res != ERROR_SUCCESS)
2891 break;
2894 if(blocking_mode == BLOCKING_ALLOW)
2895 blocking_mode = BLOCKING_DISALLOW;
2898 TRACE("read %u bytes\n", ret_read);
2899 *read = ret_read;
2900 return res;
2903 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2905 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2907 remove_chunked_data(chunked_stream, chunked_stream->buf_size);
2908 return chunked_stream->end_of_data;
2911 static void chunked_destroy(data_stream_t *stream)
2913 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2914 heap_free(chunked_stream);
2917 static const data_stream_vtbl_t chunked_stream_vtbl = {
2918 chunked_get_avail_data,
2919 chunked_end_of_data,
2920 chunked_read,
2921 chunked_drain_content,
2922 chunked_destroy
2925 /* set the request content length based on the headers */
2926 static DWORD set_content_length(http_request_t *request)
2928 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2929 static const WCHAR headW[] = {'H','E','A','D',0};
2930 WCHAR encoding[20];
2931 DWORD size;
2933 if(request->status_code == HTTP_STATUS_NO_CONTENT || !strcmpW(request->verb, headW)) {
2934 request->contentLength = request->netconn_stream.content_length = 0;
2935 return ERROR_SUCCESS;
2938 size = sizeof(request->contentLength);
2939 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2940 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2941 request->contentLength = ~0u;
2942 request->netconn_stream.content_length = request->contentLength;
2943 request->netconn_stream.content_read = request->read_size;
2945 size = sizeof(encoding);
2946 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2947 !strcmpiW(encoding, szChunked))
2949 chunked_stream_t *chunked_stream;
2951 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2952 if(!chunked_stream)
2953 return ERROR_OUTOFMEMORY;
2955 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2956 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2957 chunked_stream->chunk_size = ~0u;
2958 chunked_stream->end_of_data = FALSE;
2960 if(request->read_size) {
2961 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2962 chunked_stream->buf_size = request->read_size;
2963 request->read_size = request->read_pos = 0;
2966 request->data_stream = &chunked_stream->data_stream;
2967 request->contentLength = ~0u;
2968 request->read_chunked = TRUE;
2971 if(request->decoding) {
2972 int encoding_idx;
2974 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2975 static const WCHAR gzipW[] = {'g','z','i','p',0};
2977 EnterCriticalSection( &request->headers_section );
2979 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2980 if(encoding_idx != -1) {
2981 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2982 HTTP_DeleteCustomHeader(request, encoding_idx);
2983 LeaveCriticalSection( &request->headers_section );
2984 return init_gzip_stream(request, TRUE);
2986 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2987 HTTP_DeleteCustomHeader(request, encoding_idx);
2988 LeaveCriticalSection( &request->headers_section );
2989 return init_gzip_stream(request, FALSE);
2993 LeaveCriticalSection( &request->headers_section );
2996 return ERROR_SUCCESS;
2999 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
3001 INTERNET_ASYNC_RESULT iar;
3003 iar.dwResult = result;
3004 iar.dwError = error;
3006 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3007 sizeof(INTERNET_ASYNC_RESULT));
3010 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
3012 DWORD res, read = 0, avail = 0;
3013 blocking_mode_t mode;
3015 TRACE("%p\n", req);
3017 EnterCriticalSection( &req->read_section );
3019 mode = first_notif && req->read_size ? BLOCKING_DISALLOW : BLOCKING_ALLOW;
3020 res = refill_read_buffer(req, mode, &read);
3021 if(res == ERROR_SUCCESS)
3022 avail = get_avail_data(req);
3024 LeaveCriticalSection( &req->read_section );
3026 if(res != ERROR_SUCCESS || (mode != BLOCKING_DISALLOW && !read)) {
3027 WARN("res %u read %u, closing connection\n", res, read);
3028 http_release_netconn(req, FALSE);
3031 if(res != ERROR_SUCCESS) {
3032 send_request_complete(req, 0, res);
3033 return;
3036 if(ret_size)
3037 *ret_size = avail;
3038 if(first_notif)
3039 avail = 0;
3041 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
3044 /* read data from the http connection (the read section must be held) */
3045 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
3047 DWORD current_read = 0, ret_read = 0;
3048 blocking_mode_t blocking_mode;
3049 DWORD res = ERROR_SUCCESS;
3051 blocking_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? BLOCKING_ALLOW : BLOCKING_WAITALL;
3053 EnterCriticalSection( &req->read_section );
3055 if(req->read_size) {
3056 ret_read = min(size, req->read_size);
3057 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3058 req->read_size -= ret_read;
3059 req->read_pos += ret_read;
3060 if(blocking_mode == BLOCKING_ALLOW)
3061 blocking_mode = BLOCKING_DISALLOW;
3064 if(ret_read < size) {
3065 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, blocking_mode);
3066 ret_read += current_read;
3069 LeaveCriticalSection( &req->read_section );
3071 *read = ret_read;
3072 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3074 if(size && !ret_read)
3075 http_release_netconn(req, res == ERROR_SUCCESS);
3077 return res;
3080 static BOOL drain_content(http_request_t *req, BOOL blocking)
3082 BOOL ret;
3084 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
3085 return FALSE;
3087 if(!strcmpW(req->verb, szHEAD))
3088 return TRUE;
3090 if(!blocking)
3091 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3093 EnterCriticalSection( &req->read_section );
3095 while(1) {
3096 DWORD bytes_read, res;
3097 BYTE buf[4096];
3099 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3100 if(res != ERROR_SUCCESS) {
3101 ret = FALSE;
3102 break;
3104 if(!bytes_read) {
3105 ret = TRUE;
3106 break;
3110 LeaveCriticalSection( &req->read_section );
3111 return ret;
3114 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3116 http_request_t *req = (http_request_t*)hdr;
3117 DWORD res;
3119 EnterCriticalSection( &req->read_section );
3120 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3121 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3123 res = HTTPREQ_Read(req, buffer, size, read, TRUE);
3124 if(res == ERROR_SUCCESS)
3125 res = hdr->dwError;
3126 LeaveCriticalSection( &req->read_section );
3128 return res;
3131 typedef struct {
3132 task_header_t hdr;
3133 void *buf;
3134 DWORD size;
3135 DWORD *ret_read;
3136 } read_file_ex_task_t;
3138 static void AsyncReadFileExProc(task_header_t *hdr)
3140 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3141 http_request_t *req = (http_request_t*)task->hdr.hdr;
3142 DWORD res;
3144 TRACE("INTERNETREADFILEEXW %p\n", task->hdr.hdr);
3146 res = HTTPREQ_Read(req, task->buf, task->size, task->ret_read, TRUE);
3147 send_request_complete(req, res == ERROR_SUCCESS, res);
3150 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3151 DWORD flags, DWORD_PTR context)
3154 http_request_t *req = (http_request_t*)hdr;
3155 DWORD res, read, cread, error = ERROR_SUCCESS;
3157 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3158 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3160 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3162 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
3164 read_file_ex_task_t *task;
3166 if (TryEnterCriticalSection( &req->read_section ))
3168 if (get_avail_data(req))
3170 res = HTTPREQ_Read(req, buf, size, &read, FALSE);
3171 LeaveCriticalSection( &req->read_section );
3172 goto done;
3174 LeaveCriticalSection( &req->read_section );
3177 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3178 task->buf = buf;
3179 task->size = size;
3180 task->ret_read = ret_read;
3182 INTERNET_AsyncCall(&task->hdr);
3184 return ERROR_IO_PENDING;
3187 read = 0;
3189 EnterCriticalSection( &req->read_section );
3190 if(hdr->dwError == ERROR_SUCCESS)
3191 hdr->dwError = INTERNET_HANDLE_IN_USE;
3192 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3193 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3195 while(1) {
3196 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, !(flags & IRF_NO_WAIT));
3197 if(res != ERROR_SUCCESS)
3198 break;
3200 read += cread;
3201 if(read == size || end_of_read_data(req))
3202 break;
3204 LeaveCriticalSection( &req->read_section );
3206 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3207 &cread, sizeof(cread));
3208 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3209 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3211 EnterCriticalSection( &req->read_section );
3214 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3215 hdr->dwError = ERROR_SUCCESS;
3216 else
3217 error = hdr->dwError;
3219 LeaveCriticalSection( &req->read_section );
3221 done:
3222 *ret_read = read;
3223 if (res == ERROR_SUCCESS) {
3224 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3225 &read, sizeof(read));
3228 return res==ERROR_SUCCESS ? error : res;
3231 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3233 DWORD res;
3234 http_request_t *request = (http_request_t*)hdr;
3236 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3238 *written = 0;
3239 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3240 if (res == ERROR_SUCCESS)
3241 request->bytesWritten += *written;
3243 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3244 return res;
3247 typedef struct {
3248 task_header_t hdr;
3249 DWORD *ret_size;
3250 } http_data_available_task_t;
3252 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3254 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3256 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3259 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3261 http_request_t *req = (http_request_t*)hdr;
3263 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3265 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3267 http_data_available_task_t *task;
3269 /* never wait, if we can't enter the section we queue an async request right away */
3270 if (TryEnterCriticalSection( &req->read_section ))
3272 refill_read_buffer(req, BLOCKING_DISALLOW, NULL);
3273 if ((*available = get_avail_data( req ))) goto done;
3274 if (end_of_read_data( req )) goto done;
3275 LeaveCriticalSection( &req->read_section );
3278 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3279 task->ret_size = available;
3280 INTERNET_AsyncCall(&task->hdr);
3281 return ERROR_IO_PENDING;
3284 EnterCriticalSection( &req->read_section );
3286 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3288 refill_read_buffer( req, BLOCKING_ALLOW, NULL );
3289 *available = get_avail_data( req );
3292 done:
3293 LeaveCriticalSection( &req->read_section );
3295 TRACE( "returning %u\n", *available );
3296 return ERROR_SUCCESS;
3299 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3301 http_request_t *req = (http_request_t*)hdr;
3303 TRACE("(%p)\n", req);
3305 if(!req->req_file) {
3306 WARN("No cache file name available\n");
3307 return ERROR_FILE_NOT_FOUND;
3310 *ret = req_file_addref(req->req_file);
3311 return ERROR_SUCCESS;
3314 static const object_vtbl_t HTTPREQVtbl = {
3315 HTTPREQ_Destroy,
3316 HTTPREQ_CloseConnection,
3317 HTTPREQ_QueryOption,
3318 HTTPREQ_SetOption,
3319 HTTPREQ_ReadFile,
3320 HTTPREQ_ReadFileEx,
3321 HTTPREQ_WriteFile,
3322 HTTPREQ_QueryDataAvailable,
3323 NULL,
3324 HTTPREQ_LockRequestFile
3327 /***********************************************************************
3328 * HTTP_HttpOpenRequestW (internal)
3330 * Open a HTTP request handle
3332 * RETURNS
3333 * HINTERNET a HTTP request handle on success
3334 * NULL on failure
3337 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3338 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3339 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3340 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3342 appinfo_t *hIC = session->appInfo;
3343 http_request_t *request;
3344 DWORD len;
3346 TRACE("-->\n");
3348 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3349 if(!request)
3350 return ERROR_OUTOFMEMORY;
3352 request->hdr.htype = WH_HHTTPREQ;
3353 request->hdr.dwFlags = dwFlags;
3354 request->hdr.dwContext = dwContext;
3355 request->contentLength = ~0u;
3357 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3358 request->data_stream = &request->netconn_stream.data_stream;
3359 request->connect_timeout = session->connect_timeout;
3360 request->send_timeout = session->send_timeout;
3361 request->receive_timeout = session->receive_timeout;
3363 InitializeCriticalSection( &request->headers_section );
3364 request->headers_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.headers_section");
3366 InitializeCriticalSection( &request->read_section );
3367 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3369 WININET_AddRef( &session->hdr );
3370 request->session = session;
3371 list_add_head( &session->hdr.children, &request->hdr.entry );
3373 request->server = get_server(session->hostName, session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3374 if(!request->server) {
3375 WININET_Release(&request->hdr);
3376 return ERROR_OUTOFMEMORY;
3379 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3380 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3381 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3382 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3384 if (lpszObjectName && *lpszObjectName) {
3385 HRESULT rc;
3387 len = 0;
3388 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3389 if (rc != E_POINTER)
3390 len = strlenW(lpszObjectName)+1;
3391 request->path = heap_alloc(len*sizeof(WCHAR));
3392 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3393 URL_ESCAPE_SPACES_ONLY);
3394 if (rc != S_OK)
3396 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3397 strcpyW(request->path,lpszObjectName);
3399 }else {
3400 static const WCHAR slashW[] = {'/',0};
3402 request->path = heap_strdupW(slashW);
3405 if (lpszReferrer && *lpszReferrer)
3406 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3408 if (lpszAcceptTypes)
3410 int i;
3411 for (i = 0; lpszAcceptTypes[i]; i++)
3413 if (!*lpszAcceptTypes[i]) continue;
3414 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3415 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3416 HTTP_ADDHDR_FLAG_REQ |
3417 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
3421 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3422 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3424 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3426 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3427 HTTP_DealWithProxy( hIC, session, request );
3429 INTERNET_SendCallback(&session->hdr, dwContext,
3430 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3431 sizeof(HINTERNET));
3433 TRACE("<-- (%p)\n", request);
3435 *ret = request->hdr.hInternet;
3436 return ERROR_SUCCESS;
3439 /***********************************************************************
3440 * HttpOpenRequestW (WININET.@)
3442 * Open a HTTP request handle
3444 * RETURNS
3445 * HINTERNET a HTTP request handle on success
3446 * NULL on failure
3449 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3450 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3451 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3452 DWORD dwFlags, DWORD_PTR dwContext)
3454 http_session_t *session;
3455 HINTERNET handle = NULL;
3456 DWORD res;
3458 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3459 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3460 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3461 dwFlags, dwContext);
3462 if(lpszAcceptTypes!=NULL)
3464 int i;
3465 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3466 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3469 session = (http_session_t*) get_handle_object( hHttpSession );
3470 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3472 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3473 goto lend;
3477 * My tests seem to show that the windows version does not
3478 * become asynchronous until after this point. And anyhow
3479 * if this call was asynchronous then how would you get the
3480 * necessary HINTERNET pointer returned by this function.
3483 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3484 lpszVersion, lpszReferrer, lpszAcceptTypes,
3485 dwFlags, dwContext, &handle);
3486 lend:
3487 if( session )
3488 WININET_Release( &session->hdr );
3489 TRACE("returning %p\n", handle);
3490 if(res != ERROR_SUCCESS)
3491 SetLastError(res);
3492 return handle;
3495 static const LPCWSTR header_lookup[] = {
3496 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3497 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3498 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3499 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3500 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3501 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3502 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3503 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3504 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3505 szDate, /* HTTP_QUERY_DATE = 9 */
3506 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3507 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3508 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3509 szURI, /* HTTP_QUERY_URI = 13 */
3510 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3511 NULL, /* HTTP_QUERY_COST = 15 */
3512 NULL, /* HTTP_QUERY_LINK = 16 */
3513 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3514 NULL, /* HTTP_QUERY_VERSION = 18 */
3515 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3516 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3517 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3518 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3519 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3520 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3521 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3522 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3523 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3524 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3525 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3526 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3527 NULL, /* HTTP_QUERY_FROM = 31 */
3528 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3529 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3530 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3531 szReferer, /* HTTP_QUERY_REFERER = 35 */
3532 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3533 szServer, /* HTTP_QUERY_SERVER = 37 */
3534 NULL, /* HTTP_TITLE = 38 */
3535 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3536 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3537 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3538 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3539 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3540 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3541 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3542 NULL, /* HTTP_QUERY_REFRESH = 46 */
3543 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3544 szAge, /* HTTP_QUERY_AGE = 48 */
3545 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3546 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3547 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3548 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3549 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3550 szETag, /* HTTP_QUERY_ETAG = 54 */
3551 hostW, /* HTTP_QUERY_HOST = 55 */
3552 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3553 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3554 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3555 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3556 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3557 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3558 szRange, /* HTTP_QUERY_RANGE = 62 */
3559 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3560 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3561 szVary, /* HTTP_QUERY_VARY = 65 */
3562 szVia, /* HTTP_QUERY_VIA = 66 */
3563 szWarning, /* HTTP_QUERY_WARNING = 67 */
3564 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3565 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3566 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3569 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3571 /***********************************************************************
3572 * HTTP_HttpQueryInfoW (internal)
3574 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3575 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3577 LPHTTPHEADERW lphttpHdr = NULL;
3578 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3579 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3580 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3581 INT index = -1;
3583 EnterCriticalSection( &request->headers_section );
3585 /* Find requested header structure */
3586 switch (level)
3588 case HTTP_QUERY_CUSTOM:
3589 if (!lpBuffer)
3591 LeaveCriticalSection( &request->headers_section );
3592 return ERROR_INVALID_PARAMETER;
3594 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3595 break;
3596 case HTTP_QUERY_RAW_HEADERS_CRLF:
3598 LPWSTR headers;
3599 DWORD len = 0;
3600 DWORD res = ERROR_INVALID_PARAMETER;
3602 if (request_only)
3603 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3604 else
3605 headers = build_response_header(request, TRUE);
3606 if (!headers)
3608 LeaveCriticalSection( &request->headers_section );
3609 return ERROR_OUTOFMEMORY;
3612 len = strlenW(headers) * sizeof(WCHAR);
3613 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3615 len += sizeof(WCHAR);
3616 res = ERROR_INSUFFICIENT_BUFFER;
3618 else if (lpBuffer)
3620 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3621 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3622 res = ERROR_SUCCESS;
3624 *lpdwBufferLength = len;
3626 heap_free(headers);
3627 LeaveCriticalSection( &request->headers_section );
3628 return res;
3630 case HTTP_QUERY_RAW_HEADERS:
3632 LPWSTR headers;
3633 DWORD len;
3635 if (request_only)
3636 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3637 else
3638 headers = build_response_header(request, FALSE);
3640 if (!headers)
3642 LeaveCriticalSection( &request->headers_section );
3643 return ERROR_OUTOFMEMORY;
3646 len = strlenW(headers) * sizeof(WCHAR);
3647 if (len > *lpdwBufferLength)
3649 *lpdwBufferLength = len;
3650 heap_free(headers);
3651 LeaveCriticalSection( &request->headers_section );
3652 return ERROR_INSUFFICIENT_BUFFER;
3655 if (lpBuffer)
3657 DWORD i;
3659 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3661 for (i = 0; i < len / sizeof(WCHAR); i++)
3663 if (headers[i] == '\n')
3664 headers[i] = 0;
3666 memcpy(lpBuffer, headers, len);
3668 *lpdwBufferLength = len - sizeof(WCHAR);
3670 heap_free(headers);
3671 LeaveCriticalSection( &request->headers_section );
3672 return ERROR_SUCCESS;
3674 case HTTP_QUERY_STATUS_TEXT:
3675 if (request->statusText)
3677 DWORD len = strlenW(request->statusText);
3678 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3680 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3681 LeaveCriticalSection( &request->headers_section );
3682 return ERROR_INSUFFICIENT_BUFFER;
3684 if (lpBuffer)
3686 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3687 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3689 *lpdwBufferLength = len * sizeof(WCHAR);
3690 LeaveCriticalSection( &request->headers_section );
3691 return ERROR_SUCCESS;
3693 break;
3694 case HTTP_QUERY_VERSION:
3695 if (request->version)
3697 DWORD len = strlenW(request->version);
3698 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3700 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3701 LeaveCriticalSection( &request->headers_section );
3702 return ERROR_INSUFFICIENT_BUFFER;
3704 if (lpBuffer)
3706 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3707 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3709 *lpdwBufferLength = len * sizeof(WCHAR);
3710 LeaveCriticalSection( &request->headers_section );
3711 return ERROR_SUCCESS;
3713 break;
3714 case HTTP_QUERY_CONTENT_ENCODING:
3715 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3716 requested_index,request_only);
3717 break;
3718 case HTTP_QUERY_STATUS_CODE: {
3719 DWORD res = ERROR_SUCCESS;
3721 if(request_only)
3723 LeaveCriticalSection( &request->headers_section );
3724 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3727 if(requested_index)
3728 break;
3730 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3731 if(*lpdwBufferLength >= sizeof(DWORD))
3732 *(DWORD*)lpBuffer = request->status_code;
3733 else
3734 res = ERROR_INSUFFICIENT_BUFFER;
3735 *lpdwBufferLength = sizeof(DWORD);
3736 }else {
3737 WCHAR buf[12];
3738 DWORD size;
3739 static const WCHAR formatW[] = {'%','u',0};
3741 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3743 if(size <= *lpdwBufferLength) {
3744 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3745 }else {
3746 size += sizeof(WCHAR);
3747 res = ERROR_INSUFFICIENT_BUFFER;
3750 *lpdwBufferLength = size;
3752 LeaveCriticalSection( &request->headers_section );
3753 return res;
3755 default:
3756 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3758 if (level < LAST_TABLE_HEADER && header_lookup[level])
3759 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3760 requested_index,request_only);
3763 if (index >= 0)
3764 lphttpHdr = &request->custHeaders[index];
3766 /* Ensure header satisfies requested attributes */
3767 if (!lphttpHdr ||
3768 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3769 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3771 LeaveCriticalSection( &request->headers_section );
3772 return ERROR_HTTP_HEADER_NOT_FOUND;
3775 /* coalesce value to requested type */
3776 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3778 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3779 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3781 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3783 time_t tmpTime;
3784 struct tm tmpTM;
3785 SYSTEMTIME *STHook;
3787 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3789 tmpTM = *gmtime(&tmpTime);
3790 STHook = (SYSTEMTIME *)lpBuffer;
3791 STHook->wDay = tmpTM.tm_mday;
3792 STHook->wHour = tmpTM.tm_hour;
3793 STHook->wMilliseconds = 0;
3794 STHook->wMinute = tmpTM.tm_min;
3795 STHook->wDayOfWeek = tmpTM.tm_wday;
3796 STHook->wMonth = tmpTM.tm_mon + 1;
3797 STHook->wSecond = tmpTM.tm_sec;
3798 STHook->wYear = 1900+tmpTM.tm_year;
3800 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3801 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3802 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3804 else if (lphttpHdr->lpszValue)
3806 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3808 if (len > *lpdwBufferLength)
3810 *lpdwBufferLength = len;
3811 LeaveCriticalSection( &request->headers_section );
3812 return ERROR_INSUFFICIENT_BUFFER;
3814 if (lpBuffer)
3816 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3817 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3819 *lpdwBufferLength = len - sizeof(WCHAR);
3821 if (lpdwIndex) (*lpdwIndex)++;
3823 LeaveCriticalSection( &request->headers_section );
3824 return ERROR_SUCCESS;
3827 /***********************************************************************
3828 * HttpQueryInfoW (WININET.@)
3830 * Queries for information about an HTTP request
3832 * RETURNS
3833 * TRUE on success
3834 * FALSE on failure
3837 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3838 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3840 http_request_t *request;
3841 DWORD res;
3843 if (TRACE_ON(wininet)) {
3844 #define FE(x) { x, #x }
3845 static const wininet_flag_info query_flags[] = {
3846 FE(HTTP_QUERY_MIME_VERSION),
3847 FE(HTTP_QUERY_CONTENT_TYPE),
3848 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3849 FE(HTTP_QUERY_CONTENT_ID),
3850 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3851 FE(HTTP_QUERY_CONTENT_LENGTH),
3852 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3853 FE(HTTP_QUERY_ALLOW),
3854 FE(HTTP_QUERY_PUBLIC),
3855 FE(HTTP_QUERY_DATE),
3856 FE(HTTP_QUERY_EXPIRES),
3857 FE(HTTP_QUERY_LAST_MODIFIED),
3858 FE(HTTP_QUERY_MESSAGE_ID),
3859 FE(HTTP_QUERY_URI),
3860 FE(HTTP_QUERY_DERIVED_FROM),
3861 FE(HTTP_QUERY_COST),
3862 FE(HTTP_QUERY_LINK),
3863 FE(HTTP_QUERY_PRAGMA),
3864 FE(HTTP_QUERY_VERSION),
3865 FE(HTTP_QUERY_STATUS_CODE),
3866 FE(HTTP_QUERY_STATUS_TEXT),
3867 FE(HTTP_QUERY_RAW_HEADERS),
3868 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3869 FE(HTTP_QUERY_CONNECTION),
3870 FE(HTTP_QUERY_ACCEPT),
3871 FE(HTTP_QUERY_ACCEPT_CHARSET),
3872 FE(HTTP_QUERY_ACCEPT_ENCODING),
3873 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3874 FE(HTTP_QUERY_AUTHORIZATION),
3875 FE(HTTP_QUERY_CONTENT_ENCODING),
3876 FE(HTTP_QUERY_FORWARDED),
3877 FE(HTTP_QUERY_FROM),
3878 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3879 FE(HTTP_QUERY_LOCATION),
3880 FE(HTTP_QUERY_ORIG_URI),
3881 FE(HTTP_QUERY_REFERER),
3882 FE(HTTP_QUERY_RETRY_AFTER),
3883 FE(HTTP_QUERY_SERVER),
3884 FE(HTTP_QUERY_TITLE),
3885 FE(HTTP_QUERY_USER_AGENT),
3886 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3887 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3888 FE(HTTP_QUERY_ACCEPT_RANGES),
3889 FE(HTTP_QUERY_SET_COOKIE),
3890 FE(HTTP_QUERY_COOKIE),
3891 FE(HTTP_QUERY_REQUEST_METHOD),
3892 FE(HTTP_QUERY_REFRESH),
3893 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3894 FE(HTTP_QUERY_AGE),
3895 FE(HTTP_QUERY_CACHE_CONTROL),
3896 FE(HTTP_QUERY_CONTENT_BASE),
3897 FE(HTTP_QUERY_CONTENT_LOCATION),
3898 FE(HTTP_QUERY_CONTENT_MD5),
3899 FE(HTTP_QUERY_CONTENT_RANGE),
3900 FE(HTTP_QUERY_ETAG),
3901 FE(HTTP_QUERY_HOST),
3902 FE(HTTP_QUERY_IF_MATCH),
3903 FE(HTTP_QUERY_IF_NONE_MATCH),
3904 FE(HTTP_QUERY_IF_RANGE),
3905 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3906 FE(HTTP_QUERY_MAX_FORWARDS),
3907 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3908 FE(HTTP_QUERY_RANGE),
3909 FE(HTTP_QUERY_TRANSFER_ENCODING),
3910 FE(HTTP_QUERY_UPGRADE),
3911 FE(HTTP_QUERY_VARY),
3912 FE(HTTP_QUERY_VIA),
3913 FE(HTTP_QUERY_WARNING),
3914 FE(HTTP_QUERY_CUSTOM)
3916 static const wininet_flag_info modifier_flags[] = {
3917 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3918 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3919 FE(HTTP_QUERY_FLAG_NUMBER),
3920 FE(HTTP_QUERY_FLAG_COALESCE)
3922 #undef FE
3923 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3924 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3925 DWORD i;
3927 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3928 TRACE(" Attribute:");
3929 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3930 if (query_flags[i].val == info) {
3931 TRACE(" %s", query_flags[i].name);
3932 break;
3935 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3936 TRACE(" Unknown (%08x)", info);
3939 TRACE(" Modifier:");
3940 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3941 if (modifier_flags[i].val & info_mod) {
3942 TRACE(" %s", modifier_flags[i].name);
3943 info_mod &= ~ modifier_flags[i].val;
3947 if (info_mod) {
3948 TRACE(" Unknown (%08x)", info_mod);
3950 TRACE("\n");
3953 request = (http_request_t*) get_handle_object( hHttpRequest );
3954 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3956 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3957 goto lend;
3960 if (lpBuffer == NULL)
3961 *lpdwBufferLength = 0;
3962 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3963 lpBuffer, lpdwBufferLength, lpdwIndex);
3965 lend:
3966 if( request )
3967 WININET_Release( &request->hdr );
3969 TRACE("%u <--\n", res);
3970 if(res != ERROR_SUCCESS)
3971 SetLastError(res);
3972 return res == ERROR_SUCCESS;
3975 /***********************************************************************
3976 * HttpQueryInfoA (WININET.@)
3978 * Queries for information about an HTTP request
3980 * RETURNS
3981 * TRUE on success
3982 * FALSE on failure
3985 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3986 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3988 BOOL result;
3989 DWORD len;
3990 WCHAR* bufferW;
3992 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3994 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3995 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3997 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3998 lpdwBufferLength, lpdwIndex );
4001 if (lpBuffer)
4003 DWORD alloclen;
4004 len = (*lpdwBufferLength)*sizeof(WCHAR);
4005 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
4007 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
4008 if (alloclen < len)
4009 alloclen = len;
4011 else
4012 alloclen = len;
4013 bufferW = heap_alloc(alloclen);
4014 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
4015 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
4016 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
4017 } else
4019 bufferW = NULL;
4020 len = 0;
4023 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
4024 &len, lpdwIndex );
4025 if( result )
4027 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
4028 lpBuffer, *lpdwBufferLength, NULL, NULL );
4029 *lpdwBufferLength = len - 1;
4031 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
4033 else
4034 /* since the strings being returned from HttpQueryInfoW should be
4035 * only ASCII characters, it is reasonable to assume that all of
4036 * the Unicode characters can be reduced to a single byte */
4037 *lpdwBufferLength = len / sizeof(WCHAR);
4039 heap_free( bufferW );
4040 return result;
4043 /***********************************************************************
4044 * HTTP_GetRedirectURL (internal)
4046 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
4048 static WCHAR szHttp[] = {'h','t','t','p',0};
4049 static WCHAR szHttps[] = {'h','t','t','p','s',0};
4050 http_session_t *session = request->session;
4051 URL_COMPONENTSW urlComponents;
4052 DWORD url_length = 0;
4053 LPWSTR orig_url;
4054 LPWSTR combined_url;
4056 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4057 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
4058 urlComponents.dwSchemeLength = 0;
4059 urlComponents.lpszHostName = request->server->name;
4060 urlComponents.dwHostNameLength = 0;
4061 urlComponents.nPort = request->server->port;
4062 urlComponents.lpszUserName = session->userName;
4063 urlComponents.dwUserNameLength = 0;
4064 urlComponents.lpszPassword = NULL;
4065 urlComponents.dwPasswordLength = 0;
4066 urlComponents.lpszUrlPath = request->path;
4067 urlComponents.dwUrlPathLength = 0;
4068 urlComponents.lpszExtraInfo = NULL;
4069 urlComponents.dwExtraInfoLength = 0;
4071 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
4072 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4073 return NULL;
4075 orig_url = heap_alloc(url_length);
4077 /* convert from bytes to characters */
4078 url_length = url_length / sizeof(WCHAR) - 1;
4079 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
4081 heap_free(orig_url);
4082 return NULL;
4085 url_length = 0;
4086 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
4087 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4089 heap_free(orig_url);
4090 return NULL;
4092 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4094 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
4096 heap_free(orig_url);
4097 heap_free(combined_url);
4098 return NULL;
4100 heap_free(orig_url);
4101 return combined_url;
4105 /***********************************************************************
4106 * HTTP_HandleRedirect (internal)
4108 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4110 http_session_t *session = request->session;
4111 WCHAR path[INTERNET_MAX_PATH_LENGTH];
4112 int index;
4114 if(lpszUrl[0]=='/')
4116 /* if it's an absolute path, keep the same session info */
4117 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4119 else
4121 URL_COMPONENTSW urlComponents;
4122 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4123 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4124 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4125 BOOL custom_port = FALSE;
4127 static const WCHAR httpW[] = {'h','t','t','p',0};
4128 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
4130 userName[0] = 0;
4131 hostName[0] = 0;
4132 protocol[0] = 0;
4134 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4135 urlComponents.lpszScheme = protocol;
4136 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4137 urlComponents.lpszHostName = hostName;
4138 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4139 urlComponents.lpszUserName = userName;
4140 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4141 urlComponents.lpszPassword = NULL;
4142 urlComponents.dwPasswordLength = 0;
4143 urlComponents.lpszUrlPath = path;
4144 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4145 urlComponents.lpszExtraInfo = NULL;
4146 urlComponents.dwExtraInfoLength = 0;
4147 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4148 return INTERNET_GetLastError();
4150 if(!strcmpiW(protocol, httpW)) {
4151 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4152 TRACE("redirect from secure page to non-secure page\n");
4153 /* FIXME: warn about from secure redirect to non-secure page */
4154 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4157 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4158 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4159 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4160 custom_port = TRUE;
4161 }else if(!strcmpiW(protocol, httpsW)) {
4162 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4163 TRACE("redirect from non-secure page to secure page\n");
4164 /* FIXME: notify about redirect to secure page */
4165 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4168 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4169 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4170 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4171 custom_port = TRUE;
4174 heap_free(session->hostName);
4176 session->hostName = heap_strdupW(hostName);
4177 session->hostPort = urlComponents.nPort;
4179 heap_free(session->userName);
4180 session->userName = NULL;
4181 if (userName[0])
4182 session->userName = heap_strdupW(userName);
4184 reset_data_stream(request);
4186 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4187 server_t *new_server;
4189 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4190 server_release(request->server);
4191 request->server = new_server;
4194 if (custom_port)
4195 HTTP_ProcessHeader(request, hostW, request->server->host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4196 else
4197 HTTP_ProcessHeader(request, hostW, request->server->name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4199 heap_free(request->path);
4200 request->path=NULL;
4201 if (*path)
4203 DWORD needed = 0;
4204 HRESULT rc;
4206 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4207 if (rc != E_POINTER)
4208 needed = strlenW(path)+1;
4209 request->path = heap_alloc(needed*sizeof(WCHAR));
4210 rc = UrlEscapeW(path, request->path, &needed,
4211 URL_ESCAPE_SPACES_ONLY);
4212 if (rc != S_OK)
4214 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4215 strcpyW(request->path,path);
4219 EnterCriticalSection( &request->headers_section );
4221 /* Remove custom content-type/length headers on redirects. */
4222 index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
4223 if (index != -1) HTTP_DeleteCustomHeader(request, index);
4224 index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
4225 if (index != -1) HTTP_DeleteCustomHeader(request, index);
4227 LeaveCriticalSection( &request->headers_section );
4229 return ERROR_SUCCESS;
4232 /***********************************************************************
4233 * HTTP_build_req (internal)
4235 * concatenate all the strings in the request together
4237 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4239 LPCWSTR *t;
4240 LPWSTR str;
4242 for( t = list; *t ; t++ )
4243 len += strlenW( *t );
4244 len++;
4246 str = heap_alloc(len*sizeof(WCHAR));
4247 *str = 0;
4249 for( t = list; *t ; t++ )
4250 strcatW( str, *t );
4252 return str;
4255 static void HTTP_InsertCookies(http_request_t *request)
4257 WCHAR *cookies;
4258 DWORD res;
4260 res = get_cookie_header(request->server->name, request->path, &cookies);
4261 if(res != ERROR_SUCCESS || !cookies)
4262 return;
4264 get_cookie_header(request->server->name, request->path, &cookies);
4265 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4266 heap_free(cookies);
4269 static WORD HTTP_ParseWkday(LPCWSTR day)
4271 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4272 { 'm','o','n',0 },
4273 { 't','u','e',0 },
4274 { 'w','e','d',0 },
4275 { 't','h','u',0 },
4276 { 'f','r','i',0 },
4277 { 's','a','t',0 }};
4278 unsigned int i;
4279 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4280 if (!strcmpiW(day, days[i]))
4281 return i;
4283 /* Invalid */
4284 return 7;
4287 static WORD HTTP_ParseMonth(LPCWSTR month)
4289 static const WCHAR jan[] = { 'j','a','n',0 };
4290 static const WCHAR feb[] = { 'f','e','b',0 };
4291 static const WCHAR mar[] = { 'm','a','r',0 };
4292 static const WCHAR apr[] = { 'a','p','r',0 };
4293 static const WCHAR may[] = { 'm','a','y',0 };
4294 static const WCHAR jun[] = { 'j','u','n',0 };
4295 static const WCHAR jul[] = { 'j','u','l',0 };
4296 static const WCHAR aug[] = { 'a','u','g',0 };
4297 static const WCHAR sep[] = { 's','e','p',0 };
4298 static const WCHAR oct[] = { 'o','c','t',0 };
4299 static const WCHAR nov[] = { 'n','o','v',0 };
4300 static const WCHAR dec[] = { 'd','e','c',0 };
4302 if (!strcmpiW(month, jan)) return 1;
4303 if (!strcmpiW(month, feb)) return 2;
4304 if (!strcmpiW(month, mar)) return 3;
4305 if (!strcmpiW(month, apr)) return 4;
4306 if (!strcmpiW(month, may)) return 5;
4307 if (!strcmpiW(month, jun)) return 6;
4308 if (!strcmpiW(month, jul)) return 7;
4309 if (!strcmpiW(month, aug)) return 8;
4310 if (!strcmpiW(month, sep)) return 9;
4311 if (!strcmpiW(month, oct)) return 10;
4312 if (!strcmpiW(month, nov)) return 11;
4313 if (!strcmpiW(month, dec)) return 12;
4314 /* Invalid */
4315 return 0;
4318 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4319 * optionally preceded by whitespace.
4320 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4321 * st, and sets *str to the first character after the time format.
4323 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4325 LPCWSTR ptr = *str;
4326 WCHAR *nextPtr;
4327 unsigned long num;
4329 while (isspaceW(*ptr))
4330 ptr++;
4332 num = strtoulW(ptr, &nextPtr, 10);
4333 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4335 ERR("unexpected time format %s\n", debugstr_w(ptr));
4336 return FALSE;
4338 if (num > 23)
4340 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4341 return FALSE;
4343 ptr = nextPtr + 1;
4344 st->wHour = (WORD)num;
4345 num = strtoulW(ptr, &nextPtr, 10);
4346 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4348 ERR("unexpected time format %s\n", debugstr_w(ptr));
4349 return FALSE;
4351 if (num > 59)
4353 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4354 return FALSE;
4356 ptr = nextPtr + 1;
4357 st->wMinute = (WORD)num;
4358 num = strtoulW(ptr, &nextPtr, 10);
4359 if (!nextPtr || nextPtr <= ptr)
4361 ERR("unexpected time format %s\n", debugstr_w(ptr));
4362 return FALSE;
4364 if (num > 59)
4366 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4367 return FALSE;
4369 ptr = nextPtr + 1;
4370 *str = ptr;
4371 st->wSecond = (WORD)num;
4372 return TRUE;
4375 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4377 static const WCHAR gmt[]= { 'G','M','T',0 };
4378 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4379 LPCWSTR ptr;
4380 SYSTEMTIME st = { 0 };
4381 unsigned long num;
4383 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4384 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4385 *dayPtr = *ptr;
4386 *dayPtr = 0;
4387 st.wDayOfWeek = HTTP_ParseWkday(day);
4388 if (st.wDayOfWeek >= 7)
4390 ERR("unexpected weekday %s\n", debugstr_w(day));
4391 return FALSE;
4394 while (isspaceW(*ptr))
4395 ptr++;
4397 for (monthPtr = month; !isspace(*ptr) &&
4398 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4399 monthPtr++, ptr++)
4400 *monthPtr = *ptr;
4401 *monthPtr = 0;
4402 st.wMonth = HTTP_ParseMonth(month);
4403 if (!st.wMonth || st.wMonth > 12)
4405 ERR("unexpected month %s\n", debugstr_w(month));
4406 return FALSE;
4409 while (isspaceW(*ptr))
4410 ptr++;
4412 num = strtoulW(ptr, &nextPtr, 10);
4413 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4415 ERR("unexpected day %s\n", debugstr_w(ptr));
4416 return FALSE;
4418 ptr = nextPtr;
4419 st.wDay = (WORD)num;
4421 while (isspaceW(*ptr))
4422 ptr++;
4424 if (!HTTP_ParseTime(&st, &ptr))
4425 return FALSE;
4427 while (isspaceW(*ptr))
4428 ptr++;
4430 num = strtoulW(ptr, &nextPtr, 10);
4431 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4433 ERR("unexpected year %s\n", debugstr_w(ptr));
4434 return FALSE;
4436 ptr = nextPtr;
4437 st.wYear = (WORD)num;
4439 while (isspaceW(*ptr))
4440 ptr++;
4442 /* asctime() doesn't report a timezone, but some web servers do, so accept
4443 * with or without GMT.
4445 if (*ptr && strcmpW(ptr, gmt))
4447 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4448 return FALSE;
4450 return SystemTimeToFileTime(&st, ft);
4453 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4455 static const WCHAR gmt[]= { 'G','M','T',0 };
4456 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4457 LPCWSTR ptr;
4458 unsigned long num;
4459 SYSTEMTIME st = { 0 };
4461 ptr = strchrW(value, ',');
4462 if (!ptr)
4463 return FALSE;
4464 if (ptr - value != 3)
4466 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4467 return FALSE;
4469 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4470 day[3] = 0;
4471 st.wDayOfWeek = HTTP_ParseWkday(day);
4472 if (st.wDayOfWeek > 6)
4474 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4475 return FALSE;
4477 ptr++;
4479 while (isspaceW(*ptr))
4480 ptr++;
4482 num = strtoulW(ptr, &nextPtr, 10);
4483 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4485 WARN("unexpected day %s\n", debugstr_w(value));
4486 return FALSE;
4488 ptr = nextPtr;
4489 st.wDay = (WORD)num;
4491 while (isspaceW(*ptr))
4492 ptr++;
4494 for (monthPtr = month; !isspace(*ptr) &&
4495 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4496 monthPtr++, ptr++)
4497 *monthPtr = *ptr;
4498 *monthPtr = 0;
4499 st.wMonth = HTTP_ParseMonth(month);
4500 if (!st.wMonth || st.wMonth > 12)
4502 WARN("unexpected month %s\n", debugstr_w(month));
4503 return FALSE;
4506 while (isspaceW(*ptr))
4507 ptr++;
4509 num = strtoulW(ptr, &nextPtr, 10);
4510 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4512 ERR("unexpected year %s\n", debugstr_w(value));
4513 return FALSE;
4515 ptr = nextPtr;
4516 st.wYear = (WORD)num;
4518 if (!HTTP_ParseTime(&st, &ptr))
4519 return FALSE;
4521 while (isspaceW(*ptr))
4522 ptr++;
4524 if (strcmpW(ptr, gmt))
4526 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4527 return FALSE;
4529 return SystemTimeToFileTime(&st, ft);
4532 static WORD HTTP_ParseWeekday(LPCWSTR day)
4534 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4535 { 'm','o','n','d','a','y',0 },
4536 { 't','u','e','s','d','a','y',0 },
4537 { 'w','e','d','n','e','s','d','a','y',0 },
4538 { 't','h','u','r','s','d','a','y',0 },
4539 { 'f','r','i','d','a','y',0 },
4540 { 's','a','t','u','r','d','a','y',0 }};
4541 unsigned int i;
4542 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4543 if (!strcmpiW(day, days[i]))
4544 return i;
4546 /* Invalid */
4547 return 7;
4550 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4552 static const WCHAR gmt[]= { 'G','M','T',0 };
4553 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4554 LPCWSTR ptr;
4555 unsigned long num;
4556 SYSTEMTIME st = { 0 };
4558 ptr = strchrW(value, ',');
4559 if (!ptr)
4560 return FALSE;
4561 if (ptr - value == 3)
4563 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4564 day[3] = 0;
4565 st.wDayOfWeek = HTTP_ParseWkday(day);
4566 if (st.wDayOfWeek > 6)
4568 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4569 return FALSE;
4572 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4574 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4575 day[ptr - value + 1] = 0;
4576 st.wDayOfWeek = HTTP_ParseWeekday(day);
4577 if (st.wDayOfWeek > 6)
4579 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4580 return FALSE;
4583 else
4585 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4586 return FALSE;
4588 ptr++;
4590 while (isspaceW(*ptr))
4591 ptr++;
4593 num = strtoulW(ptr, &nextPtr, 10);
4594 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4596 ERR("unexpected day %s\n", debugstr_w(value));
4597 return FALSE;
4599 ptr = nextPtr;
4600 st.wDay = (WORD)num;
4602 if (*ptr != '-')
4604 ERR("unexpected month format %s\n", debugstr_w(ptr));
4605 return FALSE;
4607 ptr++;
4609 for (monthPtr = month; *ptr != '-' &&
4610 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4611 monthPtr++, ptr++)
4612 *monthPtr = *ptr;
4613 *monthPtr = 0;
4614 st.wMonth = HTTP_ParseMonth(month);
4615 if (!st.wMonth || st.wMonth > 12)
4617 ERR("unexpected month %s\n", debugstr_w(month));
4618 return FALSE;
4621 if (*ptr != '-')
4623 ERR("unexpected year format %s\n", debugstr_w(ptr));
4624 return FALSE;
4626 ptr++;
4628 num = strtoulW(ptr, &nextPtr, 10);
4629 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4631 ERR("unexpected year %s\n", debugstr_w(value));
4632 return FALSE;
4634 ptr = nextPtr;
4635 st.wYear = (WORD)num;
4637 if (!HTTP_ParseTime(&st, &ptr))
4638 return FALSE;
4640 while (isspaceW(*ptr))
4641 ptr++;
4643 if (strcmpW(ptr, gmt))
4645 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4646 return FALSE;
4648 return SystemTimeToFileTime(&st, ft);
4651 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4653 static const WCHAR zero[] = { '0',0 };
4654 BOOL ret;
4656 if (!strcmpW(value, zero))
4658 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4659 ret = TRUE;
4661 else if (strchrW(value, ','))
4663 ret = HTTP_ParseRfc1123Date(value, ft);
4664 if (!ret)
4666 ret = HTTP_ParseRfc850Date(value, ft);
4667 if (!ret)
4668 ERR("unexpected date format %s\n", debugstr_w(value));
4671 else
4673 ret = HTTP_ParseDateAsAsctime(value, ft);
4674 if (!ret)
4675 ERR("unexpected date format %s\n", debugstr_w(value));
4677 return ret;
4680 static void HTTP_ProcessExpires(http_request_t *request)
4682 BOOL expirationFound = FALSE;
4683 int headerIndex;
4685 EnterCriticalSection( &request->headers_section );
4687 /* Look for a Cache-Control header with a max-age directive, as it takes
4688 * precedence over the Expires header.
4690 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4691 if (headerIndex != -1)
4693 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4694 LPWSTR ptr;
4696 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4698 LPWSTR comma = strchrW(ptr, ','), end, equal;
4700 if (comma)
4701 end = comma;
4702 else
4703 end = ptr + strlenW(ptr);
4704 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4706 if (*equal == '=')
4708 static const WCHAR max_age[] = {
4709 'm','a','x','-','a','g','e',0 };
4711 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4713 LPWSTR nextPtr;
4714 unsigned long age;
4716 age = strtoulW(equal + 1, &nextPtr, 10);
4717 if (nextPtr > equal + 1)
4719 LARGE_INTEGER ft;
4721 NtQuerySystemTime( &ft );
4722 /* Age is in seconds, FILETIME resolution is in
4723 * 100 nanosecond intervals.
4725 ft.QuadPart += age * (ULONGLONG)1000000;
4726 request->expires.dwLowDateTime = ft.u.LowPart;
4727 request->expires.dwHighDateTime = ft.u.HighPart;
4728 expirationFound = TRUE;
4732 if (comma)
4734 ptr = comma + 1;
4735 while (isspaceW(*ptr))
4736 ptr++;
4738 else
4739 ptr = NULL;
4742 if (!expirationFound)
4744 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4745 if (headerIndex != -1)
4747 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4748 FILETIME ft;
4750 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4752 expirationFound = TRUE;
4753 request->expires = ft;
4757 if (!expirationFound)
4759 LARGE_INTEGER t;
4761 /* With no known age, default to 10 minutes until expiration. */
4762 NtQuerySystemTime( &t );
4763 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4764 request->expires.dwLowDateTime = t.u.LowPart;
4765 request->expires.dwHighDateTime = t.u.HighPart;
4768 LeaveCriticalSection( &request->headers_section );
4771 static void HTTP_ProcessLastModified(http_request_t *request)
4773 int headerIndex;
4775 EnterCriticalSection( &request->headers_section );
4777 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4778 if (headerIndex != -1)
4780 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4781 FILETIME ft;
4783 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4784 request->last_modified = ft;
4787 LeaveCriticalSection( &request->headers_section );
4790 static void http_process_keep_alive(http_request_t *req)
4792 int index;
4794 EnterCriticalSection( &req->headers_section );
4796 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4797 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4798 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4799 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4800 else
4801 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4803 LeaveCriticalSection( &req->headers_section );
4806 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4808 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4809 netconn_t *netconn = NULL;
4810 DWORD res;
4812 reset_data_stream(request);
4814 if (request->netconn)
4816 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4818 *reusing = TRUE;
4819 return ERROR_SUCCESS;
4821 else
4823 free_netconn(request->netconn);
4824 request->netconn = NULL;
4828 res = HTTP_ResolveName(request);
4829 if(res != ERROR_SUCCESS)
4830 return res;
4832 EnterCriticalSection(&connection_pool_cs);
4834 while(!list_empty(&request->server->conn_pool)) {
4835 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4836 list_remove(&netconn->pool_entry);
4838 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4839 break;
4841 TRACE("connection %p closed during idle\n", netconn);
4842 free_netconn(netconn);
4843 netconn = NULL;
4846 LeaveCriticalSection(&connection_pool_cs);
4848 if(netconn) {
4849 TRACE("<-- reusing %p netconn\n", netconn);
4850 request->netconn = netconn;
4851 *reusing = TRUE;
4852 return ERROR_SUCCESS;
4855 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4856 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4858 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4859 INTERNET_STATUS_CONNECTING_TO_SERVER,
4860 request->server->addr_str,
4861 strlen(request->server->addr_str)+1);
4863 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4864 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4865 request->connect_timeout, &netconn);
4866 if(res != ERROR_SUCCESS) {
4867 ERR("create_netconn failed: %u\n", res);
4868 return res;
4871 request->netconn = netconn;
4873 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4874 INTERNET_STATUS_CONNECTED_TO_SERVER,
4875 request->server->addr_str, strlen(request->server->addr_str)+1);
4877 *reusing = FALSE;
4878 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4879 return ERROR_SUCCESS;
4882 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4884 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4885 char *ret;
4887 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4888 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4889 if (data_len) memcpy( ret + len - 1, data, data_len );
4890 *out_len = len + data_len - 1;
4891 ret[*out_len] = 0;
4892 return ret;
4895 /***********************************************************************
4896 * HTTP_HttpSendRequestW (internal)
4898 * Sends the specified request to the HTTP server
4900 * RETURNS
4901 * ERROR_SUCCESS on success
4902 * win32 error code on failure
4905 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4906 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4907 DWORD dwContentLength, BOOL bEndRequest)
4909 static const WCHAR szContentLength[] =
4910 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4911 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4912 LPWSTR requestString = NULL;
4913 INT responseLen, cnt;
4914 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4915 DWORD res;
4917 TRACE("--> %p\n", request);
4919 assert(request->hdr.htype == WH_HHTTPREQ);
4921 /* if the verb is NULL default to GET */
4922 if (!request->verb)
4923 request->verb = heap_strdupW(szGET);
4925 if (dwContentLength || strcmpW(request->verb, szGET))
4927 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4928 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4929 request->bytesToWrite = dwContentLength;
4931 if (request->session->appInfo->agent)
4933 WCHAR *agent_header;
4934 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4935 int len;
4937 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4938 agent_header = heap_alloc(len * sizeof(WCHAR));
4939 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4941 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4942 heap_free(agent_header);
4944 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4946 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4947 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4949 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4951 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4952 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4953 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4956 /* add the headers the caller supplied */
4957 if( lpszHeaders && dwHeaderLength )
4958 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4962 DWORD len, data_len = dwOptionalLength;
4963 BOOL reusing_connection;
4964 char *ascii_req;
4966 loop_next = FALSE;
4968 if(redirected) {
4969 request->contentLength = ~0u;
4970 request->bytesToWrite = 0;
4973 if (TRACE_ON(wininet))
4975 HTTPHEADERW *host;
4977 EnterCriticalSection( &request->headers_section );
4978 host = HTTP_GetHeader( request, hostW );
4979 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
4980 LeaveCriticalSection( &request->headers_section );
4983 HTTP_FixURL(request);
4984 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4986 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4988 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4989 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4991 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4992 HTTP_InsertCookies(request);
4994 res = open_http_connection(request, &reusing_connection);
4995 if (res != ERROR_SUCCESS)
4996 break;
4998 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
5000 if (request->proxy) secure_proxy_connect = TRUE;
5001 else
5003 res = NETCON_secure_connect(request->netconn, request->server);
5004 if (res != ERROR_SUCCESS)
5006 WARN("failed to upgrade to secure connection\n");
5007 http_release_netconn(request, FALSE);
5008 break;
5012 if (secure_proxy_connect)
5014 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
5015 const WCHAR *target = request->server->host_port;
5016 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
5018 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
5020 WCHAR *url = build_proxy_path_url(request);
5021 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
5022 heap_free(url);
5024 else
5025 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
5027 TRACE("Request header -> %s\n", debugstr_w(requestString) );
5029 /* send the request as ASCII, tack on the optional data */
5030 if (!lpOptional || redirected || secure_proxy_connect)
5031 data_len = 0;
5033 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
5034 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
5036 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5037 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
5039 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
5040 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
5041 heap_free( ascii_req );
5042 if(res != ERROR_SUCCESS) {
5043 TRACE("send failed: %u\n", res);
5044 if(!reusing_connection)
5045 break;
5046 http_release_netconn(request, FALSE);
5047 loop_next = TRUE;
5048 continue;
5051 request->bytesWritten = data_len;
5053 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5054 INTERNET_STATUS_REQUEST_SENT,
5055 &len, sizeof(DWORD));
5057 if (bEndRequest)
5059 DWORD dwBufferSize;
5061 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5062 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5064 if (HTTP_GetResponseHeaders(request, &responseLen))
5066 http_release_netconn(request, FALSE);
5067 res = ERROR_INTERNET_CONNECTION_ABORTED;
5068 goto lend;
5070 /* FIXME: We should know that connection is closed before sending
5071 * headers. Otherwise wrong callbacks are executed */
5072 if(!responseLen && reusing_connection) {
5073 TRACE("Connection closed by server, reconnecting\n");
5074 http_release_netconn(request, FALSE);
5075 loop_next = TRUE;
5076 continue;
5079 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5080 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5081 sizeof(DWORD));
5083 http_process_keep_alive(request);
5084 HTTP_ProcessCookies(request);
5085 HTTP_ProcessExpires(request);
5086 HTTP_ProcessLastModified(request);
5088 res = set_content_length(request);
5089 if(res != ERROR_SUCCESS)
5090 goto lend;
5091 if(!request->contentLength)
5092 http_release_netconn(request, TRUE);
5094 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5096 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5097 dwBufferSize=sizeof(szNewLocation);
5098 switch(request->status_code) {
5099 case HTTP_STATUS_REDIRECT:
5100 case HTTP_STATUS_MOVED:
5101 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5102 case HTTP_STATUS_REDIRECT_METHOD:
5103 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5104 break;
5106 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5107 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5109 heap_free(request->verb);
5110 request->verb = heap_strdupW(szGET);
5112 http_release_netconn(request, drain_content(request, FALSE));
5113 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5115 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5116 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5117 res = HTTP_HandleRedirect(request, new_url);
5118 if (res == ERROR_SUCCESS)
5120 heap_free(requestString);
5121 loop_next = TRUE;
5123 heap_free( new_url );
5125 redirected = TRUE;
5128 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5130 WCHAR szAuthValue[2048];
5131 dwBufferSize=2048;
5132 if (request->status_code == HTTP_STATUS_DENIED)
5134 WCHAR *host = get_host_header( request );
5135 DWORD dwIndex = 0;
5136 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5138 if (HTTP_DoAuthorization(request, szAuthValue,
5139 &request->authInfo,
5140 request->session->userName,
5141 request->session->password, host))
5143 heap_free(requestString);
5144 if(!drain_content(request, TRUE)) {
5145 FIXME("Could not drain content\n");
5146 http_release_netconn(request, FALSE);
5148 loop_next = TRUE;
5149 break;
5152 heap_free( host );
5154 if(!loop_next) {
5155 TRACE("Cleaning wrong authorization data\n");
5156 destroy_authinfo(request->authInfo);
5157 request->authInfo = NULL;
5160 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5162 DWORD dwIndex = 0;
5163 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5165 if (HTTP_DoAuthorization(request, szAuthValue,
5166 &request->proxyAuthInfo,
5167 request->session->appInfo->proxyUsername,
5168 request->session->appInfo->proxyPassword,
5169 NULL))
5171 heap_free(requestString);
5172 if(!drain_content(request, TRUE)) {
5173 FIXME("Could not drain content\n");
5174 http_release_netconn(request, FALSE);
5176 loop_next = TRUE;
5177 break;
5181 if(!loop_next) {
5182 TRACE("Cleaning wrong proxy authorization data\n");
5183 destroy_authinfo(request->proxyAuthInfo);
5184 request->proxyAuthInfo = NULL;
5188 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5190 int index;
5192 res = NETCON_secure_connect(request->netconn, request->server);
5193 if (res != ERROR_SUCCESS)
5195 WARN("failed to upgrade to secure proxy connection\n");
5196 http_release_netconn( request, FALSE );
5197 break;
5199 EnterCriticalSection( &request->headers_section );
5200 index = HTTP_GetCustomHeaderIndex(request, szProxy_Authorization, 0, TRUE);
5201 if (index != -1) HTTP_DeleteCustomHeader(request, index);
5202 LeaveCriticalSection( &request->headers_section );
5204 destroy_authinfo(request->proxyAuthInfo);
5205 request->proxyAuthInfo = NULL;
5207 secure_proxy_connect = FALSE;
5208 loop_next = TRUE;
5211 else
5212 res = ERROR_SUCCESS;
5214 while (loop_next);
5216 lend:
5217 heap_free(requestString);
5219 /* TODO: send notification for P3P header */
5221 if(res == ERROR_SUCCESS)
5222 create_cache_entry(request);
5224 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5226 if (res == ERROR_SUCCESS) {
5227 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5228 HTTP_ReceiveRequestData(request, TRUE, NULL);
5229 else
5230 send_request_complete(request,
5231 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5232 }else {
5233 send_request_complete(request, 0, res);
5237 TRACE("<--\n");
5238 return res;
5241 typedef struct {
5242 task_header_t hdr;
5243 WCHAR *headers;
5244 DWORD headers_len;
5245 void *optional;
5246 DWORD optional_len;
5247 DWORD content_len;
5248 BOOL end_request;
5249 } send_request_task_t;
5251 /***********************************************************************
5253 * Helper functions for the HttpSendRequest(Ex) functions
5256 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5258 send_request_task_t *task = (send_request_task_t*)hdr;
5259 http_request_t *request = (http_request_t*)task->hdr.hdr;
5261 TRACE("%p\n", request);
5263 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5264 task->optional_len, task->content_len, task->end_request);
5266 heap_free(task->headers);
5270 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5272 DWORD dwBufferSize;
5273 INT responseLen;
5274 DWORD res = ERROR_SUCCESS;
5276 if(!is_valid_netconn(request->netconn)) {
5277 WARN("Not connected\n");
5278 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5279 return ERROR_INTERNET_OPERATION_CANCELLED;
5282 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5283 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5285 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5286 res = ERROR_HTTP_HEADER_NOT_FOUND;
5288 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5289 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5291 /* process cookies here. Is this right? */
5292 http_process_keep_alive(request);
5293 HTTP_ProcessCookies(request);
5294 HTTP_ProcessExpires(request);
5295 HTTP_ProcessLastModified(request);
5297 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5298 if(!request->contentLength)
5299 http_release_netconn(request, TRUE);
5302 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5304 switch(request->status_code) {
5305 case HTTP_STATUS_REDIRECT:
5306 case HTTP_STATUS_MOVED:
5307 case HTTP_STATUS_REDIRECT_METHOD:
5308 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5309 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5310 dwBufferSize=sizeof(szNewLocation);
5311 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5312 break;
5314 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5315 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5317 heap_free(request->verb);
5318 request->verb = heap_strdupW(szGET);
5320 http_release_netconn(request, drain_content(request, FALSE));
5321 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5323 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5324 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5325 res = HTTP_HandleRedirect(request, new_url);
5326 if (res == ERROR_SUCCESS)
5327 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5328 heap_free( new_url );
5334 if(res == ERROR_SUCCESS)
5335 create_cache_entry(request);
5337 if (res == ERROR_SUCCESS && request->contentLength)
5338 HTTP_ReceiveRequestData(request, TRUE, NULL);
5339 else
5340 send_request_complete(request, res == ERROR_SUCCESS, res);
5342 return res;
5345 /***********************************************************************
5346 * HttpEndRequestA (WININET.@)
5348 * Ends an HTTP request that was started by HttpSendRequestEx
5350 * RETURNS
5351 * TRUE if successful
5352 * FALSE on failure
5355 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5356 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5358 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5360 if (lpBuffersOut)
5362 SetLastError(ERROR_INVALID_PARAMETER);
5363 return FALSE;
5366 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5369 typedef struct {
5370 task_header_t hdr;
5371 DWORD flags;
5372 DWORD context;
5373 } end_request_task_t;
5375 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5377 end_request_task_t *task = (end_request_task_t*)hdr;
5378 http_request_t *req = (http_request_t*)task->hdr.hdr;
5380 TRACE("%p\n", req);
5382 HTTP_HttpEndRequestW(req, task->flags, task->context);
5385 /***********************************************************************
5386 * HttpEndRequestW (WININET.@)
5388 * Ends an HTTP request that was started by HttpSendRequestEx
5390 * RETURNS
5391 * TRUE if successful
5392 * FALSE on failure
5395 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5396 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5398 http_request_t *request;
5399 DWORD res;
5401 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5403 if (lpBuffersOut)
5405 SetLastError(ERROR_INVALID_PARAMETER);
5406 return FALSE;
5409 request = (http_request_t*) get_handle_object( hRequest );
5411 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5413 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5414 if (request)
5415 WININET_Release( &request->hdr );
5416 return FALSE;
5418 request->hdr.dwFlags |= dwFlags;
5420 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5422 end_request_task_t *task;
5424 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5425 task->flags = dwFlags;
5426 task->context = dwContext;
5428 INTERNET_AsyncCall(&task->hdr);
5429 res = ERROR_IO_PENDING;
5431 else
5432 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5434 WININET_Release( &request->hdr );
5435 TRACE("%u <--\n", res);
5436 if(res != ERROR_SUCCESS)
5437 SetLastError(res);
5438 return res == ERROR_SUCCESS;
5441 /***********************************************************************
5442 * HttpSendRequestExA (WININET.@)
5444 * Sends the specified request to the HTTP server and allows chunked
5445 * transfers.
5447 * RETURNS
5448 * Success: TRUE
5449 * Failure: FALSE, call GetLastError() for more information.
5451 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5452 LPINTERNET_BUFFERSA lpBuffersIn,
5453 LPINTERNET_BUFFERSA lpBuffersOut,
5454 DWORD dwFlags, DWORD_PTR dwContext)
5456 INTERNET_BUFFERSW BuffersInW;
5457 BOOL rc = FALSE;
5458 DWORD headerlen;
5459 LPWSTR header = NULL;
5461 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5462 lpBuffersOut, dwFlags, dwContext);
5464 if (lpBuffersIn)
5466 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5467 if (lpBuffersIn->lpcszHeader)
5469 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5470 lpBuffersIn->dwHeadersLength,0,0);
5471 header = heap_alloc(headerlen*sizeof(WCHAR));
5472 if (!(BuffersInW.lpcszHeader = header))
5474 SetLastError(ERROR_OUTOFMEMORY);
5475 return FALSE;
5477 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5478 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5479 header, headerlen);
5481 else
5482 BuffersInW.lpcszHeader = NULL;
5483 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5484 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5485 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5486 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5487 BuffersInW.Next = NULL;
5490 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5492 heap_free(header);
5493 return rc;
5496 /***********************************************************************
5497 * HttpSendRequestExW (WININET.@)
5499 * Sends the specified request to the HTTP server and allows chunked
5500 * transfers
5502 * RETURNS
5503 * Success: TRUE
5504 * Failure: FALSE, call GetLastError() for more information.
5506 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5507 LPINTERNET_BUFFERSW lpBuffersIn,
5508 LPINTERNET_BUFFERSW lpBuffersOut,
5509 DWORD dwFlags, DWORD_PTR dwContext)
5511 http_request_t *request;
5512 http_session_t *session;
5513 appinfo_t *hIC;
5514 DWORD res;
5516 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5517 lpBuffersOut, dwFlags, dwContext);
5519 request = (http_request_t*) get_handle_object( hRequest );
5521 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5523 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5524 goto lend;
5527 session = request->session;
5528 assert(session->hdr.htype == WH_HHTTPSESSION);
5529 hIC = session->appInfo;
5530 assert(hIC->hdr.htype == WH_HINIT);
5532 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5534 send_request_task_t *task;
5536 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5537 if (lpBuffersIn)
5539 DWORD size = 0;
5541 if (lpBuffersIn->lpcszHeader)
5543 if (lpBuffersIn->dwHeadersLength == ~0u)
5544 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5545 else
5546 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5548 task->headers = heap_alloc(size);
5549 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5551 else task->headers = NULL;
5553 task->headers_len = size / sizeof(WCHAR);
5554 task->optional = lpBuffersIn->lpvBuffer;
5555 task->optional_len = lpBuffersIn->dwBufferLength;
5556 task->content_len = lpBuffersIn->dwBufferTotal;
5558 else
5560 task->headers = NULL;
5561 task->headers_len = 0;
5562 task->optional = NULL;
5563 task->optional_len = 0;
5564 task->content_len = 0;
5567 task->end_request = FALSE;
5569 INTERNET_AsyncCall(&task->hdr);
5570 res = ERROR_IO_PENDING;
5572 else
5574 if (lpBuffersIn)
5575 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5576 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5577 lpBuffersIn->dwBufferTotal, FALSE);
5578 else
5579 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5582 lend:
5583 if ( request )
5584 WININET_Release( &request->hdr );
5586 TRACE("<---\n");
5587 SetLastError(res);
5588 return res == ERROR_SUCCESS;
5591 /***********************************************************************
5592 * HttpSendRequestW (WININET.@)
5594 * Sends the specified request to the HTTP server
5596 * RETURNS
5597 * TRUE on success
5598 * FALSE on failure
5601 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5602 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5604 http_request_t *request;
5605 http_session_t *session = NULL;
5606 appinfo_t *hIC = NULL;
5607 DWORD res = ERROR_SUCCESS;
5609 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5610 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5612 request = (http_request_t*) get_handle_object( hHttpRequest );
5613 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5615 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5616 goto lend;
5619 session = request->session;
5620 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5622 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5623 goto lend;
5626 hIC = session->appInfo;
5627 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5629 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5630 goto lend;
5633 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5635 send_request_task_t *task;
5637 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5638 if (lpszHeaders)
5640 DWORD size;
5642 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5643 else size = dwHeaderLength * sizeof(WCHAR);
5645 task->headers = heap_alloc(size);
5646 memcpy(task->headers, lpszHeaders, size);
5648 else
5649 task->headers = NULL;
5650 task->headers_len = dwHeaderLength;
5651 task->optional = lpOptional;
5652 task->optional_len = dwOptionalLength;
5653 task->content_len = dwOptionalLength;
5654 task->end_request = TRUE;
5656 INTERNET_AsyncCall(&task->hdr);
5657 res = ERROR_IO_PENDING;
5659 else
5661 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5662 dwHeaderLength, lpOptional, dwOptionalLength,
5663 dwOptionalLength, TRUE);
5665 lend:
5666 if( request )
5667 WININET_Release( &request->hdr );
5669 SetLastError(res);
5670 return res == ERROR_SUCCESS;
5673 /***********************************************************************
5674 * HttpSendRequestA (WININET.@)
5676 * Sends the specified request to the HTTP server
5678 * RETURNS
5679 * TRUE on success
5680 * FALSE on failure
5683 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5684 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5686 BOOL result;
5687 LPWSTR szHeaders=NULL;
5688 DWORD nLen=dwHeaderLength;
5689 if(lpszHeaders!=NULL)
5691 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5692 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5693 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5695 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5696 heap_free(szHeaders);
5697 return result;
5700 /***********************************************************************
5701 * HTTPSESSION_Destroy (internal)
5703 * Deallocate session handle
5706 static void HTTPSESSION_Destroy(object_header_t *hdr)
5708 http_session_t *session = (http_session_t*) hdr;
5710 TRACE("%p\n", session);
5712 WININET_Release(&session->appInfo->hdr);
5714 heap_free(session->hostName);
5715 heap_free(session->password);
5716 heap_free(session->userName);
5719 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5721 http_session_t *ses = (http_session_t *)hdr;
5723 switch(option) {
5724 case INTERNET_OPTION_HANDLE_TYPE:
5725 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5727 if (*size < sizeof(ULONG))
5728 return ERROR_INSUFFICIENT_BUFFER;
5730 *size = sizeof(DWORD);
5731 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5732 return ERROR_SUCCESS;
5733 case INTERNET_OPTION_CONNECT_TIMEOUT:
5734 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5736 if (*size < sizeof(DWORD))
5737 return ERROR_INSUFFICIENT_BUFFER;
5739 *size = sizeof(DWORD);
5740 *(DWORD *)buffer = ses->connect_timeout;
5741 return ERROR_SUCCESS;
5743 case INTERNET_OPTION_SEND_TIMEOUT:
5744 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5746 if (*size < sizeof(DWORD))
5747 return ERROR_INSUFFICIENT_BUFFER;
5749 *size = sizeof(DWORD);
5750 *(DWORD *)buffer = ses->send_timeout;
5751 return ERROR_SUCCESS;
5753 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5754 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5756 if (*size < sizeof(DWORD))
5757 return ERROR_INSUFFICIENT_BUFFER;
5759 *size = sizeof(DWORD);
5760 *(DWORD *)buffer = ses->receive_timeout;
5761 return ERROR_SUCCESS;
5764 return INET_QueryOption(hdr, option, buffer, size, unicode);
5767 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5769 http_session_t *ses = (http_session_t*)hdr;
5771 switch(option) {
5772 case INTERNET_OPTION_USERNAME:
5774 heap_free(ses->userName);
5775 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5776 return ERROR_SUCCESS;
5778 case INTERNET_OPTION_PASSWORD:
5780 heap_free(ses->password);
5781 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5782 return ERROR_SUCCESS;
5784 case INTERNET_OPTION_PROXY_USERNAME:
5786 heap_free(ses->appInfo->proxyUsername);
5787 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5788 return ERROR_SUCCESS;
5790 case INTERNET_OPTION_PROXY_PASSWORD:
5792 heap_free(ses->appInfo->proxyPassword);
5793 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5794 return ERROR_SUCCESS;
5796 case INTERNET_OPTION_CONNECT_TIMEOUT:
5798 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5799 ses->connect_timeout = *(DWORD *)buffer;
5800 return ERROR_SUCCESS;
5802 case INTERNET_OPTION_SEND_TIMEOUT:
5804 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5805 ses->send_timeout = *(DWORD *)buffer;
5806 return ERROR_SUCCESS;
5808 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5810 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5811 ses->receive_timeout = *(DWORD *)buffer;
5812 return ERROR_SUCCESS;
5814 default: break;
5817 return INET_SetOption(hdr, option, buffer, size);
5820 static const object_vtbl_t HTTPSESSIONVtbl = {
5821 HTTPSESSION_Destroy,
5822 NULL,
5823 HTTPSESSION_QueryOption,
5824 HTTPSESSION_SetOption,
5825 NULL,
5826 NULL,
5827 NULL,
5828 NULL,
5829 NULL
5833 /***********************************************************************
5834 * HTTP_Connect (internal)
5836 * Create http session handle
5838 * RETURNS
5839 * HINTERNET a session handle on success
5840 * NULL on failure
5843 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5844 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5845 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5846 DWORD dwInternalFlags, HINTERNET *ret)
5848 http_session_t *session = NULL;
5850 TRACE("-->\n");
5852 if (!lpszServerName || !lpszServerName[0])
5853 return ERROR_INVALID_PARAMETER;
5855 assert( hIC->hdr.htype == WH_HINIT );
5857 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5858 if (!session)
5859 return ERROR_OUTOFMEMORY;
5862 * According to my tests. The name is not resolved until a request is sent
5865 session->hdr.htype = WH_HHTTPSESSION;
5866 session->hdr.dwFlags = dwFlags;
5867 session->hdr.dwContext = dwContext;
5868 session->hdr.dwInternalFlags |= dwInternalFlags;
5870 WININET_AddRef( &hIC->hdr );
5871 session->appInfo = hIC;
5872 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5874 session->hostName = heap_strdupW(lpszServerName);
5875 if (lpszUserName && lpszUserName[0])
5876 session->userName = heap_strdupW(lpszUserName);
5877 if (lpszPassword && lpszPassword[0])
5878 session->password = heap_strdupW(lpszPassword);
5879 session->hostPort = serverPort;
5880 session->connect_timeout = hIC->connect_timeout;
5881 session->send_timeout = INFINITE;
5882 session->receive_timeout = INFINITE;
5884 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5885 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5887 INTERNET_SendCallback(&hIC->hdr, dwContext,
5888 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5889 sizeof(HINTERNET));
5893 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5894 * windows
5897 TRACE("%p --> %p\n", hIC, session);
5899 *ret = session->hdr.hInternet;
5900 return ERROR_SUCCESS;
5903 /***********************************************************************
5904 * HTTP_clear_response_headers (internal)
5906 * clear out any old response headers
5908 static void HTTP_clear_response_headers( http_request_t *request )
5910 DWORD i;
5912 EnterCriticalSection( &request->headers_section );
5914 for( i=0; i<request->nCustHeaders; i++)
5916 if( !request->custHeaders[i].lpszField )
5917 continue;
5918 if( !request->custHeaders[i].lpszValue )
5919 continue;
5920 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5921 continue;
5922 HTTP_DeleteCustomHeader( request, i );
5923 i--;
5926 LeaveCriticalSection( &request->headers_section );
5929 /***********************************************************************
5930 * HTTP_GetResponseHeaders (internal)
5932 * Read server response
5934 * RETURNS
5936 * TRUE on success
5937 * FALSE on error
5939 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5941 INT cbreaks = 0;
5942 WCHAR buffer[MAX_REPLY_LEN];
5943 DWORD buflen = MAX_REPLY_LEN;
5944 INT rc = 0;
5945 char bufferA[MAX_REPLY_LEN];
5946 LPWSTR status_code = NULL, status_text = NULL;
5947 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5948 BOOL codeHundred = FALSE;
5950 TRACE("-->\n");
5952 if(!is_valid_netconn(request->netconn))
5953 goto lend;
5955 /* clear old response headers (eg. from a redirect response) */
5956 HTTP_clear_response_headers( request );
5958 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5959 do {
5961 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5963 buflen = MAX_REPLY_LEN;
5964 if ((res = read_line(request, bufferA, &buflen)))
5965 goto lend;
5967 if (!buflen) goto lend;
5969 rc += buflen;
5970 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5971 /* check is this a status code line? */
5972 if (!strncmpW(buffer, g_szHttp1_0, 4))
5974 /* split the version from the status code */
5975 status_code = strchrW( buffer, ' ' );
5976 if( !status_code )
5977 goto lend;
5978 *status_code++=0;
5980 /* split the status code from the status text */
5981 status_text = strchrW( status_code, ' ' );
5982 if( status_text )
5983 *status_text++=0;
5985 request->status_code = atoiW(status_code);
5987 TRACE("version [%s] status code [%s] status text [%s]\n",
5988 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5990 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5992 else if (!codeHundred)
5994 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5996 heap_free(request->version);
5997 heap_free(request->statusText);
5999 request->status_code = HTTP_STATUS_OK;
6000 request->version = heap_strdupW(g_szHttp1_0);
6001 request->statusText = heap_strdupW(szOK);
6003 goto lend;
6005 } while (codeHundred);
6007 /* Add status code */
6008 HTTP_ProcessHeader(request, szStatus, status_code,
6009 HTTP_ADDHDR_FLAG_REPLACE);
6011 heap_free(request->version);
6012 heap_free(request->statusText);
6014 request->version = heap_strdupW(buffer);
6015 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
6017 /* Restore the spaces */
6018 *(status_code-1) = ' ';
6019 if (status_text)
6020 *(status_text-1) = ' ';
6022 /* Parse each response line */
6025 buflen = MAX_REPLY_LEN;
6026 if (!read_line(request, bufferA, &buflen) && buflen)
6028 LPWSTR * pFieldAndValue;
6030 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
6032 if (!bufferA[0]) break;
6033 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
6035 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
6036 if (pFieldAndValue)
6038 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
6039 HTTP_ADDREQ_FLAG_ADD );
6040 HTTP_FreeTokens(pFieldAndValue);
6043 else
6045 cbreaks++;
6046 if (cbreaks >= 2)
6047 break;
6049 }while(1);
6051 res = ERROR_SUCCESS;
6053 lend:
6055 *len = rc;
6056 TRACE("<--\n");
6057 return res;
6060 /***********************************************************************
6061 * HTTP_InterpretHttpHeader (internal)
6063 * Parse server response
6065 * RETURNS
6067 * Pointer to array of field, value, NULL on success.
6068 * NULL on error.
6070 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6072 LPWSTR * pTokenPair;
6073 LPWSTR pszColon;
6074 INT len;
6076 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6078 pszColon = strchrW(buffer, ':');
6079 /* must have two tokens */
6080 if (!pszColon)
6082 HTTP_FreeTokens(pTokenPair);
6083 if (buffer[0])
6084 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6085 return NULL;
6088 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6089 if (!pTokenPair[0])
6091 HTTP_FreeTokens(pTokenPair);
6092 return NULL;
6094 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6095 pTokenPair[0][pszColon - buffer] = '\0';
6097 /* skip colon */
6098 pszColon++;
6099 len = strlenW(pszColon);
6100 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6101 if (!pTokenPair[1])
6103 HTTP_FreeTokens(pTokenPair);
6104 return NULL;
6106 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6108 strip_spaces(pTokenPair[0]);
6109 strip_spaces(pTokenPair[1]);
6111 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6112 return pTokenPair;
6115 /***********************************************************************
6116 * HTTP_ProcessHeader (internal)
6118 * Stuff header into header tables according to <dwModifier>
6122 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6124 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6126 LPHTTPHEADERW lphttpHdr = NULL;
6127 INT index;
6128 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6129 DWORD res = ERROR_HTTP_INVALID_HEADER;
6131 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6133 EnterCriticalSection( &request->headers_section );
6135 /* REPLACE wins out over ADD */
6136 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6137 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6139 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6140 index = -1;
6141 else
6142 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6144 if (index >= 0)
6146 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6148 LeaveCriticalSection( &request->headers_section );
6149 return ERROR_HTTP_INVALID_HEADER;
6151 lphttpHdr = &request->custHeaders[index];
6153 else if (value)
6155 HTTPHEADERW hdr;
6157 hdr.lpszField = (LPWSTR)field;
6158 hdr.lpszValue = (LPWSTR)value;
6159 hdr.wFlags = hdr.wCount = 0;
6161 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6162 hdr.wFlags |= HDR_ISREQUEST;
6164 res = HTTP_InsertCustomHeader(request, &hdr);
6165 LeaveCriticalSection( &request->headers_section );
6166 return res;
6168 /* no value to delete */
6169 else
6171 LeaveCriticalSection( &request->headers_section );
6172 return ERROR_SUCCESS;
6175 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6176 lphttpHdr->wFlags |= HDR_ISREQUEST;
6177 else
6178 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6180 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6182 HTTP_DeleteCustomHeader( request, index );
6184 if (value && value[0])
6186 HTTPHEADERW hdr;
6188 hdr.lpszField = (LPWSTR)field;
6189 hdr.lpszValue = (LPWSTR)value;
6190 hdr.wFlags = hdr.wCount = 0;
6192 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6193 hdr.wFlags |= HDR_ISREQUEST;
6195 res = HTTP_InsertCustomHeader(request, &hdr);
6196 LeaveCriticalSection( &request->headers_section );
6197 return res;
6200 LeaveCriticalSection( &request->headers_section );
6201 return ERROR_SUCCESS;
6203 else if (dwModifier & COALESCEFLAGS)
6205 LPWSTR lpsztmp;
6206 WCHAR ch = 0;
6207 INT len = 0;
6208 INT origlen = strlenW(lphttpHdr->lpszValue);
6209 INT valuelen = strlenW(value);
6211 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6213 ch = ',';
6214 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6216 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6218 ch = ';';
6219 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6222 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6224 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6225 if (lpsztmp)
6227 lphttpHdr->lpszValue = lpsztmp;
6228 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6229 if (ch > 0)
6231 lphttpHdr->lpszValue[origlen] = ch;
6232 origlen++;
6233 lphttpHdr->lpszValue[origlen] = ' ';
6234 origlen++;
6237 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6238 lphttpHdr->lpszValue[len] = '\0';
6239 res = ERROR_SUCCESS;
6241 else
6243 WARN("heap_realloc (%d bytes) failed\n",len+1);
6244 res = ERROR_OUTOFMEMORY;
6247 TRACE("<-- %d\n", res);
6248 LeaveCriticalSection( &request->headers_section );
6249 return res;
6252 /***********************************************************************
6253 * HTTP_GetCustomHeaderIndex (internal)
6255 * Return index of custom header from header array
6256 * Headers section must be held
6258 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6259 int requested_index, BOOL request_only)
6261 DWORD index;
6263 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6265 for (index = 0; index < request->nCustHeaders; index++)
6267 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6268 continue;
6270 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6271 continue;
6273 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6274 continue;
6276 if (requested_index == 0)
6277 break;
6278 requested_index --;
6281 if (index >= request->nCustHeaders)
6282 index = -1;
6284 TRACE("Return: %d\n", index);
6285 return index;
6289 /***********************************************************************
6290 * HTTP_InsertCustomHeader (internal)
6292 * Insert header into array
6293 * Headers section must be held
6295 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6297 INT count;
6298 LPHTTPHEADERW lph = NULL;
6300 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6301 count = request->nCustHeaders + 1;
6302 if (count > 1)
6303 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6304 else
6305 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6307 if (!lph)
6308 return ERROR_OUTOFMEMORY;
6310 request->custHeaders = lph;
6311 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6312 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6313 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6314 request->custHeaders[count-1].wCount= lpHdr->wCount;
6315 request->nCustHeaders++;
6317 return ERROR_SUCCESS;
6321 /***********************************************************************
6322 * HTTP_DeleteCustomHeader (internal)
6324 * Delete header from array
6325 * If this function is called, the index may change.
6326 * Headers section must be held
6328 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6330 if( request->nCustHeaders <= 0 )
6331 return FALSE;
6332 if( index >= request->nCustHeaders )
6333 return FALSE;
6334 request->nCustHeaders--;
6336 heap_free(request->custHeaders[index].lpszField);
6337 heap_free(request->custHeaders[index].lpszValue);
6339 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6340 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6341 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6343 return TRUE;
6347 /***********************************************************************
6348 * HTTP_VerifyValidHeader (internal)
6350 * Verify the given header is not invalid for the given http request
6353 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6355 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6356 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6357 return ERROR_HTTP_INVALID_HEADER;
6359 return ERROR_SUCCESS;
6362 /***********************************************************************
6363 * IsHostInProxyBypassList (@)
6365 * Undocumented
6368 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6370 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6371 return FALSE;