wininet: Correctly handle the last proxy override in HTTP_ShouldBypassProxy.
[wine.git] / dlls / wininet / http.c
bloba468a84eca62545d12cc532c1e6e2c02cb2d4a1c
1 /*
2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
12 * Ulrich Czekalla
13 * David Hammerton
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
30 #include "config.h"
32 #ifdef HAVE_ZLIB
33 # include <zlib.h>
34 #endif
36 #include "winsock2.h"
37 #include "ws2ipdef.h"
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <time.h>
43 #include <assert.h>
44 #include "windef.h"
45 #include "winbase.h"
46 #include "wininet.h"
47 #include "winerror.h"
48 #include "winternl.h"
49 #define NO_SHLWAPI_STREAM
50 #define NO_SHLWAPI_REG
51 #define NO_SHLWAPI_STRFCNS
52 #define NO_SHLWAPI_GDI
53 #include "shlwapi.h"
54 #include "sspi.h"
55 #include "wincrypt.h"
56 #include "winuser.h"
58 #include "internet.h"
59 #include "wine/debug.h"
60 #include "wine/exception.h"
61 #include "wine/unicode.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
65 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
66 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
67 static const WCHAR szOK[] = {'O','K',0};
68 static const WCHAR hostW[] = { 'H','o','s','t',0 };
69 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
70 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
71 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
72 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
73 static const WCHAR szGET[] = { 'G','E','T', 0 };
74 static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
76 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
77 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
78 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
79 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
80 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
81 static const WCHAR szAge[] = { 'A','g','e',0 };
82 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
83 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
84 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
85 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
86 static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
87 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
88 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
89 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
90 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
91 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
92 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
93 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
94 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 };
95 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
96 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
97 static const WCHAR szDate[] = { 'D','a','t','e',0 };
98 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
99 static const WCHAR szETag[] = { 'E','T','a','g',0 };
100 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
101 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
102 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
103 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
104 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
106 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
107 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
108 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
109 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
110 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
111 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
112 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
113 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
114 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
115 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
116 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
117 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
118 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
119 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
120 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
121 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 };
122 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
123 static const WCHAR szURI[] = { 'U','R','I',0 };
124 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
125 static const WCHAR szVary[] = { 'V','a','r','y',0 };
126 static const WCHAR szVia[] = { 'V','i','a',0 };
127 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
128 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
130 static const WCHAR emptyW[] = {0};
132 #define HTTP_REFERER szReferer
133 #define HTTP_ACCEPT szAccept
134 #define HTTP_USERAGENT szUser_Agent
136 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
137 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
138 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
139 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
140 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
141 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
142 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
144 #define COLLECT_TIME 60000
146 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
148 struct HttpAuthInfo
150 LPWSTR scheme;
151 CredHandle cred;
152 CtxtHandle ctx;
153 TimeStamp exp;
154 ULONG attr;
155 ULONG max_token;
156 void *auth_data;
157 unsigned int auth_data_len;
158 BOOL finished; /* finished authenticating */
162 typedef struct _basicAuthorizationData
164 struct list entry;
166 LPWSTR host;
167 LPWSTR realm;
168 LPSTR authorization;
169 UINT authorizationLen;
170 } basicAuthorizationData;
172 typedef struct _authorizationData
174 struct list entry;
176 LPWSTR host;
177 LPWSTR scheme;
178 LPWSTR domain;
179 UINT domain_len;
180 LPWSTR user;
181 UINT user_len;
182 LPWSTR password;
183 UINT password_len;
184 } authorizationData;
186 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
187 static struct list authorizationCache = LIST_INIT(authorizationCache);
189 static CRITICAL_SECTION authcache_cs;
190 static CRITICAL_SECTION_DEBUG critsect_debug =
192 0, 0, &authcache_cs,
193 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
194 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
196 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
198 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
199 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
200 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
201 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
202 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
203 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
204 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
205 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
206 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
207 static BOOL drain_content(http_request_t*,BOOL);
209 static CRITICAL_SECTION connection_pool_cs;
210 static CRITICAL_SECTION_DEBUG connection_pool_debug =
212 0, 0, &connection_pool_cs,
213 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
214 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
216 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
218 static struct list connection_pool = LIST_INIT(connection_pool);
219 static BOOL collector_running;
221 void server_addref(server_t *server)
223 InterlockedIncrement(&server->ref);
226 void server_release(server_t *server)
228 if(InterlockedDecrement(&server->ref))
229 return;
231 list_remove(&server->entry);
233 if(server->cert_chain)
234 CertFreeCertificateChain(server->cert_chain);
235 heap_free(server->name);
236 heap_free(server->scheme_host_port);
237 heap_free(server);
240 static BOOL process_host_port(server_t *server)
242 BOOL default_port;
243 size_t name_len;
244 WCHAR *buf;
246 static const WCHAR httpW[] = {'h','t','t','p',0};
247 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
248 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
250 name_len = strlenW(server->name);
251 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
252 if(!buf)
253 return FALSE;
255 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
256 server->scheme_host_port = buf;
258 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
259 if(server->is_https)
260 server->host_port++;
262 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
263 server->canon_host_port = default_port ? server->name : server->host_port;
264 return TRUE;
267 server_t *get_server(substr_t name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
269 server_t *iter, *server = NULL;
271 if(port == INTERNET_INVALID_PORT_NUMBER)
272 port = INTERNET_DEFAULT_HTTP_PORT;
274 EnterCriticalSection(&connection_pool_cs);
276 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
277 if(iter->port == port && name.len == strlenW(iter->name) && !strncmpW(iter->name, name.str, name.len)
278 && iter->is_https == is_https) {
279 server = iter;
280 server_addref(server);
281 break;
285 if(!server && do_create) {
286 server = heap_alloc_zero(sizeof(*server));
287 if(server) {
288 server->ref = 2; /* list reference and return */
289 server->port = port;
290 server->is_https = is_https;
291 list_init(&server->conn_pool);
292 server->name = heap_strndupW(name.str, name.len);
293 if(server->name && process_host_port(server)) {
294 list_add_head(&connection_pool, &server->entry);
295 }else {
296 heap_free(server);
297 server = NULL;
302 LeaveCriticalSection(&connection_pool_cs);
304 return server;
307 BOOL collect_connections(collect_type_t collect_type)
309 netconn_t *netconn, *netconn_safe;
310 server_t *server, *server_safe;
311 BOOL remaining = FALSE;
312 DWORD64 now;
314 now = GetTickCount64();
316 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
317 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
318 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
319 TRACE("freeing %p\n", netconn);
320 list_remove(&netconn->pool_entry);
321 free_netconn(netconn);
322 }else {
323 remaining = TRUE;
327 if(collect_type == COLLECT_CLEANUP) {
328 list_remove(&server->entry);
329 list_init(&server->entry);
330 server_release(server);
334 return remaining;
337 static DWORD WINAPI collect_connections_proc(void *arg)
339 BOOL remaining_conns;
341 do {
342 /* FIXME: Use more sophisticated method */
343 Sleep(5000);
345 EnterCriticalSection(&connection_pool_cs);
347 remaining_conns = collect_connections(COLLECT_TIMEOUT);
348 if(!remaining_conns)
349 collector_running = FALSE;
351 LeaveCriticalSection(&connection_pool_cs);
352 }while(remaining_conns);
354 FreeLibraryAndExitThread(WININET_hModule, 0);
357 /***********************************************************************
358 * HTTP_GetHeader (internal)
360 * Headers section must be held
362 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
364 int HeaderIndex = 0;
365 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
366 if (HeaderIndex == -1)
367 return NULL;
368 else
369 return &req->custHeaders[HeaderIndex];
372 static WCHAR *get_host_header( http_request_t *req )
374 HTTPHEADERW *header;
375 WCHAR *ret = NULL;
377 EnterCriticalSection( &req->headers_section );
378 if ((header = HTTP_GetHeader( req, hostW ))) ret = heap_strdupW( header->lpszValue );
379 else ret = heap_strdupW( req->server->canon_host_port );
380 LeaveCriticalSection( &req->headers_section );
381 return ret;
384 typedef enum {
385 BLOCKING_ALLOW,
386 BLOCKING_DISALLOW,
387 BLOCKING_WAITALL
388 } blocking_mode_t;
390 struct data_stream_vtbl_t {
391 DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
392 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
393 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,blocking_mode_t);
394 BOOL (*drain_content)(data_stream_t*,http_request_t*);
395 void (*destroy)(data_stream_t*);
398 typedef struct {
399 data_stream_t data_stream;
401 BYTE buf[READ_BUFFER_SIZE];
402 DWORD buf_size;
403 DWORD buf_pos;
404 DWORD chunk_size;
405 BOOL end_of_data;
406 } chunked_stream_t;
408 static inline void destroy_data_stream(data_stream_t *stream)
410 stream->vtbl->destroy(stream);
413 static void reset_data_stream(http_request_t *req)
415 destroy_data_stream(req->data_stream);
416 req->data_stream = &req->netconn_stream.data_stream;
417 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
418 req->read_gzip = FALSE;
421 static void remove_header( http_request_t *request, const WCHAR *str, BOOL from_request )
423 int index;
424 EnterCriticalSection( &request->headers_section );
425 index = HTTP_GetCustomHeaderIndex( request, str, 0, from_request );
426 if (index != -1) HTTP_DeleteCustomHeader( request, index );
427 LeaveCriticalSection( &request->headers_section );
430 #ifdef HAVE_ZLIB
432 typedef struct {
433 data_stream_t stream;
434 data_stream_t *parent_stream;
435 z_stream zstream;
436 BYTE buf[READ_BUFFER_SIZE];
437 DWORD buf_size;
438 DWORD buf_pos;
439 BOOL end_of_data;
440 } gzip_stream_t;
442 static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
444 /* Allow reading only from read buffer */
445 return 0;
448 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
450 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
451 return gzip_stream->end_of_data
452 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
455 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
456 DWORD *read, blocking_mode_t blocking_mode)
458 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
459 z_stream *zstream = &gzip_stream->zstream;
460 DWORD current_read, ret_read = 0;
461 int zres;
462 DWORD res = ERROR_SUCCESS;
464 TRACE("(%d %d)\n", size, blocking_mode);
466 while(size && !gzip_stream->end_of_data) {
467 if(!gzip_stream->buf_size) {
468 if(gzip_stream->buf_pos) {
469 if(gzip_stream->buf_size)
470 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
471 gzip_stream->buf_pos = 0;
473 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
474 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, blocking_mode);
475 gzip_stream->buf_size += current_read;
476 if(res != ERROR_SUCCESS)
477 break;
479 if(!current_read) {
480 if(blocking_mode != BLOCKING_DISALLOW) {
481 WARN("unexpected end of data\n");
482 gzip_stream->end_of_data = TRUE;
484 break;
488 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
489 zstream->avail_in = gzip_stream->buf_size;
490 zstream->next_out = buf+ret_read;
491 zstream->avail_out = size;
492 zres = inflate(&gzip_stream->zstream, 0);
493 current_read = size - zstream->avail_out;
494 size -= current_read;
495 ret_read += current_read;
496 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
497 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
498 if(zres == Z_STREAM_END) {
499 TRACE("end of data\n");
500 gzip_stream->end_of_data = TRUE;
501 inflateEnd(zstream);
502 }else if(zres != Z_OK) {
503 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
504 if(!ret_read)
505 res = ERROR_INTERNET_DECODING_FAILED;
506 break;
509 if(ret_read && blocking_mode == BLOCKING_ALLOW)
510 blocking_mode = BLOCKING_DISALLOW;
513 TRACE("read %u bytes\n", ret_read);
514 *read = ret_read;
515 return res;
518 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
520 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
521 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
524 static void gzip_destroy(data_stream_t *stream)
526 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
528 destroy_data_stream(gzip_stream->parent_stream);
530 if(!gzip_stream->end_of_data)
531 inflateEnd(&gzip_stream->zstream);
532 heap_free(gzip_stream);
535 static const data_stream_vtbl_t gzip_stream_vtbl = {
536 gzip_get_avail_data,
537 gzip_end_of_data,
538 gzip_read,
539 gzip_drain_content,
540 gzip_destroy
543 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
545 return heap_alloc(items*size);
548 static void wininet_zfree(voidpf opaque, voidpf address)
550 heap_free(address);
553 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
555 gzip_stream_t *gzip_stream;
556 int zres;
558 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
559 if(!gzip_stream)
560 return ERROR_OUTOFMEMORY;
562 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
563 gzip_stream->zstream.zalloc = wininet_zalloc;
564 gzip_stream->zstream.zfree = wininet_zfree;
566 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
567 if(zres != Z_OK) {
568 ERR("inflateInit failed: %d\n", zres);
569 heap_free(gzip_stream);
570 return ERROR_OUTOFMEMORY;
573 remove_header(req, szContent_Length, FALSE);
575 if(req->read_size) {
576 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
577 gzip_stream->buf_size = req->read_size;
578 req->read_pos = req->read_size = 0;
581 req->read_gzip = TRUE;
582 gzip_stream->parent_stream = req->data_stream;
583 req->data_stream = &gzip_stream->stream;
584 return ERROR_SUCCESS;
587 #else
589 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
591 ERR("gzip stream not supported, missing zlib.\n");
592 return ERROR_SUCCESS;
595 #endif
597 /***********************************************************************
598 * HTTP_FreeTokens (internal)
600 * Frees table of pointers.
602 static void HTTP_FreeTokens(LPWSTR * token_array)
604 int i;
605 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
606 heap_free(token_array);
609 static void HTTP_FixURL(http_request_t *request)
611 static const WCHAR szSlash[] = { '/',0 };
612 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
614 /* If we don't have a path we set it to root */
615 if (NULL == request->path)
616 request->path = heap_strdupW(szSlash);
617 else /* remove \r and \n*/
619 int nLen = strlenW(request->path);
620 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
622 nLen--;
623 request->path[nLen]='\0';
625 /* Replace '\' with '/' */
626 while (nLen>0) {
627 nLen--;
628 if (request->path[nLen] == '\\') request->path[nLen]='/';
632 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
633 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
634 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
636 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
637 *fixurl = '/';
638 strcpyW(fixurl + 1, request->path);
639 heap_free( request->path );
640 request->path = fixurl;
644 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
645 const WCHAR *path, const WCHAR *version, BOOL use_cr)
647 static const WCHAR szSpace[] = {' ',0};
648 static const WCHAR szColon[] = {':',' ',0};
649 static const WCHAR szCr[] = {'\r',0};
650 static const WCHAR szLf[] = {'\n',0};
651 LPWSTR requestString;
652 DWORD len, n;
653 LPCWSTR *req;
654 UINT i;
656 EnterCriticalSection( &request->headers_section );
658 /* allocate space for an array of all the string pointers to be added */
659 len = request->nCustHeaders * 5 + 10;
660 if (!(req = heap_alloc( len * sizeof(const WCHAR *) )))
662 LeaveCriticalSection( &request->headers_section );
663 return NULL;
666 /* add the verb, path and HTTP version string */
667 n = 0;
668 req[n++] = verb;
669 req[n++] = szSpace;
670 req[n++] = path;
671 req[n++] = szSpace;
672 req[n++] = version;
673 if (use_cr)
674 req[n++] = szCr;
675 req[n++] = szLf;
677 /* Append custom request headers */
678 for (i = 0; i < request->nCustHeaders; i++)
680 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
682 req[n++] = request->custHeaders[i].lpszField;
683 req[n++] = szColon;
684 req[n++] = request->custHeaders[i].lpszValue;
685 if (use_cr)
686 req[n++] = szCr;
687 req[n++] = szLf;
689 TRACE("Adding custom header %s (%s)\n",
690 debugstr_w(request->custHeaders[i].lpszField),
691 debugstr_w(request->custHeaders[i].lpszValue));
694 if (use_cr)
695 req[n++] = szCr;
696 req[n++] = szLf;
697 req[n] = NULL;
699 requestString = HTTP_build_req( req, 4 );
700 heap_free( req );
701 LeaveCriticalSection( &request->headers_section );
702 return requestString;
705 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
707 static const WCHAR colonW[] = { ':',' ',0 };
708 static const WCHAR crW[] = { '\r',0 };
709 static const WCHAR lfW[] = { '\n',0 };
710 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
711 const WCHAR **req;
712 WCHAR *ret, buf[14];
713 DWORD i, n = 0;
715 EnterCriticalSection( &request->headers_section );
717 if (!(req = heap_alloc( (request->nCustHeaders * 5 + 8) * sizeof(WCHAR *) )))
719 LeaveCriticalSection( &request->headers_section );
720 return NULL;
723 if (request->status_code)
725 req[n++] = request->version;
726 sprintfW(buf, status_fmt, request->status_code);
727 req[n++] = buf;
728 req[n++] = request->statusText;
729 if (use_cr)
730 req[n++] = crW;
731 req[n++] = lfW;
734 for(i = 0; i < request->nCustHeaders; i++)
736 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
737 && strcmpW(request->custHeaders[i].lpszField, szStatus))
739 req[n++] = request->custHeaders[i].lpszField;
740 req[n++] = colonW;
741 req[n++] = request->custHeaders[i].lpszValue;
742 if(use_cr)
743 req[n++] = crW;
744 req[n++] = lfW;
746 TRACE("Adding custom header %s (%s)\n",
747 debugstr_w(request->custHeaders[i].lpszField),
748 debugstr_w(request->custHeaders[i].lpszValue));
751 if(use_cr)
752 req[n++] = crW;
753 req[n++] = lfW;
754 req[n] = NULL;
756 ret = HTTP_build_req(req, 0);
757 heap_free(req);
758 LeaveCriticalSection( &request->headers_section );
759 return ret;
762 static void HTTP_ProcessCookies( http_request_t *request )
764 int HeaderIndex;
765 int numCookies = 0;
766 LPHTTPHEADERW setCookieHeader;
768 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
769 return;
771 EnterCriticalSection( &request->headers_section );
773 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
775 const WCHAR *data;
776 substr_t name;
778 setCookieHeader = &request->custHeaders[HeaderIndex];
780 if (!setCookieHeader->lpszValue)
781 continue;
783 data = strchrW(setCookieHeader->lpszValue, '=');
784 if(!data)
785 continue;
787 name = substr(setCookieHeader->lpszValue, data - setCookieHeader->lpszValue);
788 data++;
789 set_cookie(substrz(request->server->name), substrz(request->path), name, substrz(data), INTERNET_COOKIE_HTTPONLY);
792 LeaveCriticalSection( &request->headers_section );
795 static void strip_spaces(LPWSTR start)
797 LPWSTR str = start;
798 LPWSTR end;
800 while (*str == ' ')
801 str++;
803 if (str != start)
804 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
806 end = start + strlenW(start) - 1;
807 while (end >= start && *end == ' ')
809 *end = '\0';
810 end--;
814 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
816 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
817 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
818 BOOL is_basic;
819 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
820 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
821 if (is_basic && pszRealm)
823 LPCWSTR token;
824 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
825 LPCWSTR realm;
826 ptr++;
827 *pszRealm=NULL;
828 token = strchrW(ptr,'=');
829 if (!token)
830 return TRUE;
831 realm = ptr;
832 while (*realm == ' ')
833 realm++;
834 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
835 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
837 token++;
838 while (*token == ' ')
839 token++;
840 if (*token == '\0')
841 return TRUE;
842 *pszRealm = heap_strdupW(token);
843 strip_spaces(*pszRealm);
847 return is_basic;
850 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
852 if (!authinfo) return;
854 if (SecIsValidHandle(&authinfo->ctx))
855 DeleteSecurityContext(&authinfo->ctx);
856 if (SecIsValidHandle(&authinfo->cred))
857 FreeCredentialsHandle(&authinfo->cred);
859 heap_free(authinfo->auth_data);
860 heap_free(authinfo->scheme);
861 heap_free(authinfo);
864 static UINT retrieve_cached_basic_authorization(const WCHAR *host, const WCHAR *realm, char **auth_data)
866 basicAuthorizationData *ad;
867 UINT rc = 0;
869 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
871 EnterCriticalSection(&authcache_cs);
872 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
874 if (!strcmpiW(host, ad->host) && (!realm || !strcmpW(realm, ad->realm)))
876 TRACE("Authorization found in cache\n");
877 *auth_data = heap_alloc(ad->authorizationLen);
878 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
879 rc = ad->authorizationLen;
880 break;
883 LeaveCriticalSection(&authcache_cs);
884 return rc;
887 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
889 struct list *cursor;
890 basicAuthorizationData* ad = NULL;
892 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
894 EnterCriticalSection(&authcache_cs);
895 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
897 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
898 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
900 ad = check;
901 break;
905 if (ad)
907 TRACE("Found match in cache, replacing\n");
908 heap_free(ad->authorization);
909 ad->authorization = heap_alloc(auth_data_len);
910 memcpy(ad->authorization, auth_data, auth_data_len);
911 ad->authorizationLen = auth_data_len;
913 else
915 ad = heap_alloc(sizeof(basicAuthorizationData));
916 ad->host = heap_strdupW(host);
917 ad->realm = heap_strdupW(realm);
918 ad->authorization = heap_alloc(auth_data_len);
919 memcpy(ad->authorization, auth_data, auth_data_len);
920 ad->authorizationLen = auth_data_len;
921 list_add_head(&basicAuthorizationCache,&ad->entry);
922 TRACE("authorization cached\n");
924 LeaveCriticalSection(&authcache_cs);
927 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
928 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
930 authorizationData *ad;
932 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
934 EnterCriticalSection(&authcache_cs);
935 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
936 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
937 TRACE("Authorization found in cache\n");
939 nt_auth_identity->User = heap_strdupW(ad->user);
940 nt_auth_identity->Password = heap_strdupW(ad->password);
941 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
942 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
943 (!nt_auth_identity->Domain && ad->domain_len)) {
944 heap_free(nt_auth_identity->User);
945 heap_free(nt_auth_identity->Password);
946 heap_free(nt_auth_identity->Domain);
947 break;
950 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
951 nt_auth_identity->UserLength = ad->user_len;
952 nt_auth_identity->PasswordLength = ad->password_len;
953 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
954 nt_auth_identity->DomainLength = ad->domain_len;
955 LeaveCriticalSection(&authcache_cs);
956 return TRUE;
959 LeaveCriticalSection(&authcache_cs);
961 return FALSE;
964 static void cache_authorization(LPWSTR host, LPWSTR scheme,
965 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
967 authorizationData *ad;
968 BOOL found = FALSE;
970 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
972 EnterCriticalSection(&authcache_cs);
973 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
974 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
975 found = TRUE;
976 break;
979 if(found) {
980 heap_free(ad->user);
981 heap_free(ad->password);
982 heap_free(ad->domain);
983 } else {
984 ad = heap_alloc(sizeof(authorizationData));
985 if(!ad) {
986 LeaveCriticalSection(&authcache_cs);
987 return;
990 ad->host = heap_strdupW(host);
991 ad->scheme = heap_strdupW(scheme);
992 list_add_head(&authorizationCache, &ad->entry);
995 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
996 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
997 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
998 ad->user_len = nt_auth_identity->UserLength;
999 ad->password_len = nt_auth_identity->PasswordLength;
1000 ad->domain_len = nt_auth_identity->DomainLength;
1002 if(!ad->host || !ad->scheme || !ad->user || !ad->password
1003 || (nt_auth_identity->Domain && !ad->domain)) {
1004 heap_free(ad->host);
1005 heap_free(ad->scheme);
1006 heap_free(ad->user);
1007 heap_free(ad->password);
1008 heap_free(ad->domain);
1009 list_remove(&ad->entry);
1010 heap_free(ad);
1013 LeaveCriticalSection(&authcache_cs);
1016 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1017 struct HttpAuthInfo **ppAuthInfo,
1018 LPWSTR domain_and_username, LPWSTR password,
1019 LPWSTR host )
1021 SECURITY_STATUS sec_status;
1022 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1023 BOOL first = FALSE;
1024 LPWSTR szRealm = NULL;
1026 TRACE("%s\n", debugstr_w(pszAuthValue));
1028 if (!pAuthInfo)
1030 TimeStamp exp;
1032 first = TRUE;
1033 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1034 if (!pAuthInfo)
1035 return FALSE;
1037 SecInvalidateHandle(&pAuthInfo->cred);
1038 SecInvalidateHandle(&pAuthInfo->ctx);
1039 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1040 pAuthInfo->attr = 0;
1041 pAuthInfo->auth_data = NULL;
1042 pAuthInfo->auth_data_len = 0;
1043 pAuthInfo->finished = FALSE;
1045 if (is_basic_auth_value(pszAuthValue,NULL))
1047 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1048 pAuthInfo->scheme = heap_strdupW(szBasic);
1049 if (!pAuthInfo->scheme)
1051 heap_free(pAuthInfo);
1052 return FALSE;
1055 else
1057 PVOID pAuthData;
1058 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1060 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1061 if (!pAuthInfo->scheme)
1063 heap_free(pAuthInfo);
1064 return FALSE;
1067 if (domain_and_username)
1069 WCHAR *user = strchrW(domain_and_username, '\\');
1070 WCHAR *domain = domain_and_username;
1072 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1074 pAuthData = &nt_auth_identity;
1076 if (user) user++;
1077 else
1079 user = domain_and_username;
1080 domain = NULL;
1083 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1084 nt_auth_identity.User = user;
1085 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1086 nt_auth_identity.Domain = domain;
1087 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1088 nt_auth_identity.Password = password;
1089 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1091 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1093 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1094 pAuthData = &nt_auth_identity;
1095 else
1096 /* use default credentials */
1097 pAuthData = NULL;
1099 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1100 SECPKG_CRED_OUTBOUND, NULL,
1101 pAuthData, NULL,
1102 NULL, &pAuthInfo->cred,
1103 &exp);
1105 if(pAuthData && !domain_and_username) {
1106 heap_free(nt_auth_identity.User);
1107 heap_free(nt_auth_identity.Domain);
1108 heap_free(nt_auth_identity.Password);
1111 if (sec_status == SEC_E_OK)
1113 PSecPkgInfoW sec_pkg_info;
1114 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1115 if (sec_status == SEC_E_OK)
1117 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1118 FreeContextBuffer(sec_pkg_info);
1121 if (sec_status != SEC_E_OK)
1123 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1124 debugstr_w(pAuthInfo->scheme), sec_status);
1125 heap_free(pAuthInfo->scheme);
1126 heap_free(pAuthInfo);
1127 return FALSE;
1130 *ppAuthInfo = pAuthInfo;
1132 else if (pAuthInfo->finished)
1133 return FALSE;
1135 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1136 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1138 ERR("authentication scheme changed from %s to %s\n",
1139 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1140 return FALSE;
1143 if (is_basic_auth_value(pszAuthValue,&szRealm))
1145 int userlen;
1146 int passlen;
1147 char *auth_data = NULL;
1148 UINT auth_data_len = 0;
1150 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1152 if (!domain_and_username)
1154 if (host && szRealm)
1155 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1156 if (auth_data_len == 0)
1158 heap_free(szRealm);
1159 return FALSE;
1162 else
1164 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1165 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1167 /* length includes a nul terminator, which will be re-used for the ':' */
1168 auth_data = heap_alloc(userlen + 1 + passlen);
1169 if (!auth_data)
1171 heap_free(szRealm);
1172 return FALSE;
1175 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1176 auth_data[userlen] = ':';
1177 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1178 auth_data_len = userlen + 1 + passlen;
1179 if (host && szRealm)
1180 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1183 pAuthInfo->auth_data = auth_data;
1184 pAuthInfo->auth_data_len = auth_data_len;
1185 pAuthInfo->finished = TRUE;
1186 heap_free(szRealm);
1187 return TRUE;
1189 else
1191 LPCWSTR pszAuthData;
1192 SecBufferDesc out_desc, in_desc;
1193 SecBuffer out, in;
1194 unsigned char *buffer;
1195 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1196 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1198 in.BufferType = SECBUFFER_TOKEN;
1199 in.cbBuffer = 0;
1200 in.pvBuffer = NULL;
1202 in_desc.ulVersion = 0;
1203 in_desc.cBuffers = 1;
1204 in_desc.pBuffers = &in;
1206 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1207 if (*pszAuthData == ' ')
1209 pszAuthData++;
1210 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1211 in.pvBuffer = heap_alloc(in.cbBuffer);
1212 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1215 buffer = heap_alloc(pAuthInfo->max_token);
1217 out.BufferType = SECBUFFER_TOKEN;
1218 out.cbBuffer = pAuthInfo->max_token;
1219 out.pvBuffer = buffer;
1221 out_desc.ulVersion = 0;
1222 out_desc.cBuffers = 1;
1223 out_desc.pBuffers = &out;
1225 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1226 first ? NULL : &pAuthInfo->ctx,
1227 first ? request->server->name : NULL,
1228 context_req, 0, SECURITY_NETWORK_DREP,
1229 in.pvBuffer ? &in_desc : NULL,
1230 0, &pAuthInfo->ctx, &out_desc,
1231 &pAuthInfo->attr, &pAuthInfo->exp);
1232 if (sec_status == SEC_E_OK)
1234 pAuthInfo->finished = TRUE;
1235 pAuthInfo->auth_data = out.pvBuffer;
1236 pAuthInfo->auth_data_len = out.cbBuffer;
1237 TRACE("sending last auth packet\n");
1239 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1241 pAuthInfo->auth_data = out.pvBuffer;
1242 pAuthInfo->auth_data_len = out.cbBuffer;
1243 TRACE("sending next auth packet\n");
1245 else
1247 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1248 heap_free(out.pvBuffer);
1249 destroy_authinfo(pAuthInfo);
1250 *ppAuthInfo = NULL;
1251 return FALSE;
1255 return TRUE;
1258 /***********************************************************************
1259 * HTTP_HttpAddRequestHeadersW (internal)
1261 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1262 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1264 LPWSTR lpszStart;
1265 LPWSTR lpszEnd;
1266 LPWSTR buffer;
1267 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1269 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1271 if( dwHeaderLength == ~0U )
1272 len = strlenW(lpszHeader);
1273 else
1274 len = dwHeaderLength;
1275 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1276 lstrcpynW( buffer, lpszHeader, len + 1);
1278 lpszStart = buffer;
1282 LPWSTR * pFieldAndValue;
1284 lpszEnd = lpszStart;
1286 while (*lpszEnd != '\0')
1288 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1289 break;
1290 lpszEnd++;
1293 if (*lpszStart == '\0')
1294 break;
1296 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1298 *lpszEnd = '\0';
1299 lpszEnd++; /* Jump over newline */
1301 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1302 if (*lpszStart == '\0')
1304 /* Skip 0-length headers */
1305 lpszStart = lpszEnd;
1306 res = ERROR_SUCCESS;
1307 continue;
1309 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1310 if (pFieldAndValue)
1312 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1313 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1314 HTTP_FreeTokens(pFieldAndValue);
1317 lpszStart = lpszEnd;
1318 } while (res == ERROR_SUCCESS);
1320 heap_free(buffer);
1321 return res;
1324 /***********************************************************************
1325 * HttpAddRequestHeadersW (WININET.@)
1327 * Adds one or more HTTP header to the request handler
1329 * NOTE
1330 * On Windows if dwHeaderLength includes the trailing '\0', then
1331 * HttpAddRequestHeadersW() adds it too. However this results in an
1332 * invalid HTTP header which is rejected by some servers so we probably
1333 * don't need to match Windows on that point.
1335 * RETURNS
1336 * TRUE on success
1337 * FALSE on failure
1340 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1341 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1343 http_request_t *request;
1344 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1346 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1348 if (!lpszHeader)
1349 return TRUE;
1351 request = (http_request_t*) get_handle_object( hHttpRequest );
1352 if (request && request->hdr.htype == WH_HHTTPREQ)
1353 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1354 if( request )
1355 WININET_Release( &request->hdr );
1357 if(res != ERROR_SUCCESS)
1358 SetLastError(res);
1359 return res == ERROR_SUCCESS;
1362 /***********************************************************************
1363 * HttpAddRequestHeadersA (WININET.@)
1365 * Adds one or more HTTP header to the request handler
1367 * RETURNS
1368 * TRUE on success
1369 * FALSE on failure
1372 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1373 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1375 WCHAR *headers = NULL;
1376 BOOL r;
1378 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1380 if(lpszHeader)
1381 headers = heap_strndupAtoW(lpszHeader, dwHeaderLength, &dwHeaderLength);
1383 r = HttpAddRequestHeadersW(hHttpRequest, headers, dwHeaderLength, dwModifier);
1385 heap_free(headers);
1386 return r;
1389 static void free_accept_types( WCHAR **accept_types )
1391 WCHAR *ptr, **types = accept_types;
1393 if (!types) return;
1394 while ((ptr = *types))
1396 heap_free( ptr );
1397 types++;
1399 heap_free( accept_types );
1402 static WCHAR **convert_accept_types( const char **accept_types )
1404 unsigned int count;
1405 const char **types = accept_types;
1406 WCHAR **typesW;
1407 BOOL invalid_pointer = FALSE;
1409 if (!types) return NULL;
1410 count = 0;
1411 while (*types)
1413 __TRY
1415 /* find out how many there are */
1416 if (*types && **types)
1418 TRACE("accept type: %s\n", debugstr_a(*types));
1419 count++;
1422 __EXCEPT_PAGE_FAULT
1424 WARN("invalid accept type pointer\n");
1425 invalid_pointer = TRUE;
1427 __ENDTRY;
1428 types++;
1430 if (invalid_pointer) return NULL;
1431 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1432 count = 0;
1433 types = accept_types;
1434 while (*types)
1436 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1437 types++;
1439 typesW[count] = NULL;
1440 return typesW;
1443 /***********************************************************************
1444 * HttpOpenRequestA (WININET.@)
1446 * Open a HTTP request handle
1448 * RETURNS
1449 * HINTERNET a HTTP request handle on success
1450 * NULL on failure
1453 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1454 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1455 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1456 DWORD dwFlags, DWORD_PTR dwContext)
1458 LPWSTR szVerb = NULL, szObjectName = NULL;
1459 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1460 HINTERNET rc = NULL;
1462 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1463 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1464 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1465 dwFlags, dwContext);
1467 if (lpszVerb)
1469 szVerb = heap_strdupAtoW(lpszVerb);
1470 if ( !szVerb )
1471 goto end;
1474 if (lpszObjectName)
1476 szObjectName = heap_strdupAtoW(lpszObjectName);
1477 if ( !szObjectName )
1478 goto end;
1481 if (lpszVersion)
1483 szVersion = heap_strdupAtoW(lpszVersion);
1484 if ( !szVersion )
1485 goto end;
1488 if (lpszReferrer)
1490 szReferrer = heap_strdupAtoW(lpszReferrer);
1491 if ( !szReferrer )
1492 goto end;
1495 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1496 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1497 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1499 end:
1500 free_accept_types(szAcceptTypes);
1501 heap_free(szReferrer);
1502 heap_free(szVersion);
1503 heap_free(szObjectName);
1504 heap_free(szVerb);
1505 return rc;
1508 /***********************************************************************
1509 * HTTP_EncodeBase64
1511 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1513 UINT n = 0, x;
1514 static const CHAR HTTP_Base64Enc[] =
1515 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1517 while( len > 0 )
1519 /* first 6 bits, all from bin[0] */
1520 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1521 x = (bin[0] & 3) << 4;
1523 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1524 if( len == 1 )
1526 base64[n++] = HTTP_Base64Enc[x];
1527 base64[n++] = '=';
1528 base64[n++] = '=';
1529 break;
1531 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1532 x = ( bin[1] & 0x0f ) << 2;
1534 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1535 if( len == 2 )
1537 base64[n++] = HTTP_Base64Enc[x];
1538 base64[n++] = '=';
1539 break;
1541 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1543 /* last 6 bits, all from bin [2] */
1544 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1545 bin += 3;
1546 len -= 3;
1548 base64[n] = 0;
1549 return n;
1552 static const signed char HTTP_Base64Dec[] =
1554 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1555 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1556 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1557 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1558 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1559 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1560 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1561 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1564 /***********************************************************************
1565 * HTTP_DecodeBase64
1567 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1569 unsigned int n = 0;
1571 while(*base64)
1573 signed char in[4];
1575 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1576 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1577 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1578 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1580 WARN("invalid base64: %s\n", debugstr_w(base64));
1581 return 0;
1583 if (bin)
1584 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1585 n++;
1587 if ((base64[2] == '=') && (base64[3] == '='))
1588 break;
1589 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1590 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1592 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1593 return 0;
1595 if (bin)
1596 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1597 n++;
1599 if (base64[3] == '=')
1600 break;
1601 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1602 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1604 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1605 return 0;
1607 if (bin)
1608 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1609 n++;
1611 base64 += 4;
1614 return n;
1617 static WCHAR *encode_auth_data( const WCHAR *scheme, const char *data, UINT data_len )
1619 WCHAR *ret;
1620 UINT len, scheme_len = strlenW( scheme );
1622 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1623 len = scheme_len + 1 + ((data_len + 2) * 4) / 3;
1624 if (!(ret = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return NULL;
1625 memcpy( ret, scheme, scheme_len * sizeof(WCHAR) );
1626 ret[scheme_len] = ' ';
1627 HTTP_EncodeBase64( data, data_len, ret + scheme_len + 1 );
1628 return ret;
1632 /***********************************************************************
1633 * HTTP_InsertAuthorization
1635 * Insert or delete the authorization field in the request header.
1637 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1639 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1640 WCHAR *host, *authorization = NULL;
1642 if (pAuthInfo)
1644 if (pAuthInfo->auth_data_len)
1646 if (!(authorization = encode_auth_data(pAuthInfo->scheme, pAuthInfo->auth_data, pAuthInfo->auth_data_len)))
1647 return FALSE;
1649 /* clear the data as it isn't valid now that it has been sent to the
1650 * server, unless it's Basic authentication which doesn't do
1651 * connection tracking */
1652 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1654 heap_free(pAuthInfo->auth_data);
1655 pAuthInfo->auth_data = NULL;
1656 pAuthInfo->auth_data_len = 0;
1660 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1662 HTTP_ProcessHeader(request, header, authorization,
1663 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
1664 heap_free(authorization);
1666 else if (!strcmpW(header, szAuthorization) && (host = get_host_header(request)))
1668 UINT data_len;
1669 char *data;
1671 if ((data_len = retrieve_cached_basic_authorization(host, NULL, &data)))
1673 TRACE("Found cached basic authorization for %s\n", debugstr_w(host));
1675 if (!(authorization = encode_auth_data(wszBasic, data, data_len)))
1677 heap_free(data);
1678 heap_free(host);
1679 return FALSE;
1682 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1684 HTTP_ProcessHeader(request, header, authorization,
1685 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
1686 heap_free(data);
1687 heap_free(authorization);
1689 heap_free(host);
1691 return TRUE;
1694 static WCHAR *build_proxy_path_url(http_request_t *req)
1696 DWORD size, len;
1697 WCHAR *url;
1699 len = strlenW(req->server->scheme_host_port);
1700 size = len + strlenW(req->path) + 1;
1701 if(*req->path != '/')
1702 size++;
1703 url = heap_alloc(size * sizeof(WCHAR));
1704 if(!url)
1705 return NULL;
1707 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1708 if(*req->path != '/')
1709 url[len++] = '/';
1711 strcpyW(url+len, req->path);
1713 TRACE("url=%s\n", debugstr_w(url));
1714 return url;
1717 static BOOL HTTP_DomainMatches(LPCWSTR server, substr_t domain)
1719 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1720 const WCHAR *dot, *ptr;
1721 int len;
1723 if(domain.len == sizeof(localW)/sizeof(WCHAR)-1 && !strncmpiW(domain.str, localW, domain.len) && !strchrW(server, '.' ))
1724 return TRUE;
1726 if(domain.len && *domain.str != '*')
1727 return domain.len == strlenW(server) && !strncmpiW(server, domain.str, domain.len);
1729 if(domain.len < 2 || domain.str[1] != '.')
1730 return FALSE;
1732 /* For a hostname to match a wildcard, the last domain must match
1733 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1734 * hostname is www.foo.a.b, it matches, but a.b does not.
1736 dot = strchrW(server, '.');
1737 if(!dot)
1738 return FALSE;
1740 len = strlenW(dot + 1);
1741 if(len <= domain.len - 2)
1742 return FALSE;
1744 /* The server's domain is longer than the wildcard, so it
1745 * could be a subdomain. Compare the last portion of the
1746 * server's domain.
1748 ptr = dot + 1 + len - domain.len + 2;
1749 if(!strncmpiW(ptr, domain.str+2, domain.len-2))
1750 /* This is only a match if the preceding character is
1751 * a '.', i.e. that it is a matching domain. E.g.
1752 * if domain is '*.b.c' and server is 'www.ab.c' they
1753 * do not match.
1755 return *(ptr - 1) == '.';
1757 return len == domain.len-2 && !strncmpiW(dot + 1, domain.str + 2, len);
1760 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1762 LPCWSTR ptr;
1763 BOOL ret = FALSE;
1765 if (!lpwai->proxyBypass) return FALSE;
1766 ptr = lpwai->proxyBypass;
1767 while(1) {
1768 LPCWSTR tmp = ptr;
1770 ptr = strchrW( ptr, ';' );
1771 if (!ptr)
1772 ptr = strchrW( tmp, ' ' );
1773 if (!ptr)
1774 ptr = tmp + strlenW(tmp);
1775 ret = HTTP_DomainMatches( server, substr(tmp, ptr-tmp) );
1776 if (ret || !*ptr)
1777 break;
1778 ptr++;
1780 return ret;
1783 /***********************************************************************
1784 * HTTP_DealWithProxy
1786 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1788 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1789 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1790 static WCHAR szNul[] = { 0 };
1791 URL_COMPONENTSW UrlComponents = { sizeof(UrlComponents) };
1792 server_t *new_server = NULL;
1793 WCHAR *proxy;
1795 proxy = INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp);
1796 if(!proxy)
1797 return FALSE;
1798 if(CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1799 proxy, strlenW(szHttp), szHttp, strlenW(szHttp))) {
1800 WCHAR *proxy_url = heap_alloc(strlenW(proxy)*sizeof(WCHAR) + sizeof(szHttp));
1801 if(!proxy_url) {
1802 heap_free(proxy);
1803 return FALSE;
1805 strcpyW(proxy_url, szHttp);
1806 strcatW(proxy_url, proxy);
1807 heap_free(proxy);
1808 proxy = proxy_url;
1811 UrlComponents.dwHostNameLength = 1;
1812 if(InternetCrackUrlW(proxy, 0, 0, &UrlComponents) && UrlComponents.dwHostNameLength) {
1813 if( !request->path )
1814 request->path = szNul;
1816 new_server = get_server(substr(UrlComponents.lpszHostName, UrlComponents.dwHostNameLength),
1817 UrlComponents.nPort, UrlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
1819 heap_free(proxy);
1820 if(!new_server)
1821 return FALSE;
1823 request->proxy = new_server;
1825 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1826 return TRUE;
1829 static DWORD HTTP_ResolveName(http_request_t *request)
1831 server_t *server = request->proxy ? request->proxy : request->server;
1832 int addr_len;
1834 if(server->addr_len)
1835 return ERROR_SUCCESS;
1837 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1838 INTERNET_STATUS_RESOLVING_NAME,
1839 server->name,
1840 (strlenW(server->name)+1) * sizeof(WCHAR));
1842 addr_len = sizeof(server->addr);
1843 if (!GetAddress(server->name, server->port, (SOCKADDR*)&server->addr, &addr_len, server->addr_str))
1844 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1846 server->addr_len = addr_len;
1847 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1848 INTERNET_STATUS_NAME_RESOLVED,
1849 server->addr_str, strlen(server->addr_str)+1);
1851 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1852 return ERROR_SUCCESS;
1855 static WCHAR *compose_request_url(http_request_t *req)
1857 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1858 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1859 const WCHAR *host, *scheme;
1860 WCHAR *buf, *ptr;
1861 size_t len;
1863 host = req->server->canon_host_port;
1865 if (req->server->is_https)
1866 scheme = https;
1867 else
1868 scheme = http;
1870 len = strlenW(scheme) + strlenW(host) + (req->path[0] != '/' ? 1 : 0) + strlenW(req->path);
1871 ptr = buf = heap_alloc((len+1) * sizeof(WCHAR));
1872 if(buf) {
1873 strcpyW(ptr, scheme);
1874 ptr += strlenW(ptr);
1876 strcpyW(ptr, host);
1877 ptr += strlenW(ptr);
1879 if(req->path[0] != '/')
1880 *ptr++ = '/';
1882 strcpyW(ptr, req->path);
1883 ptr += strlenW(ptr);
1884 *ptr = 0;
1887 return buf;
1891 /***********************************************************************
1892 * HTTPREQ_Destroy (internal)
1894 * Deallocate request handle
1897 static void HTTPREQ_Destroy(object_header_t *hdr)
1899 http_request_t *request = (http_request_t*) hdr;
1900 DWORD i;
1902 TRACE("\n");
1904 if(request->hCacheFile)
1905 CloseHandle(request->hCacheFile);
1906 if(request->req_file)
1907 req_file_release(request->req_file);
1909 request->headers_section.DebugInfo->Spare[0] = 0;
1910 DeleteCriticalSection( &request->headers_section );
1911 request->read_section.DebugInfo->Spare[0] = 0;
1912 DeleteCriticalSection( &request->read_section );
1913 WININET_Release(&request->session->hdr);
1915 destroy_authinfo(request->authInfo);
1916 destroy_authinfo(request->proxyAuthInfo);
1918 if(request->server)
1919 server_release(request->server);
1920 if(request->proxy)
1921 server_release(request->proxy);
1923 heap_free(request->path);
1924 heap_free(request->verb);
1925 heap_free(request->version);
1926 heap_free(request->statusText);
1928 for (i = 0; i < request->nCustHeaders; i++)
1930 heap_free(request->custHeaders[i].lpszField);
1931 heap_free(request->custHeaders[i].lpszValue);
1933 destroy_data_stream(request->data_stream);
1934 heap_free(request->custHeaders);
1937 static void http_release_netconn(http_request_t *req, BOOL reuse)
1939 TRACE("%p %p %x\n",req, req->netconn, reuse);
1941 if(!is_valid_netconn(req->netconn))
1942 return;
1944 if(reuse && req->netconn->keep_alive) {
1945 BOOL run_collector;
1947 EnterCriticalSection(&connection_pool_cs);
1949 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1950 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1951 req->netconn = NULL;
1953 run_collector = !collector_running;
1954 collector_running = TRUE;
1956 LeaveCriticalSection(&connection_pool_cs);
1958 if(run_collector) {
1959 HANDLE thread = NULL;
1960 HMODULE module;
1962 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1963 if(module)
1964 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1965 if(!thread) {
1966 EnterCriticalSection(&connection_pool_cs);
1967 collector_running = FALSE;
1968 LeaveCriticalSection(&connection_pool_cs);
1970 if(module)
1971 FreeLibrary(module);
1973 else
1974 CloseHandle(thread);
1976 return;
1979 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1980 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1982 close_netconn(req->netconn);
1984 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1985 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1988 static BOOL HTTP_KeepAlive(http_request_t *request)
1990 WCHAR szVersion[10];
1991 WCHAR szConnectionResponse[20];
1992 DWORD dwBufferSize = sizeof(szVersion);
1993 BOOL keepalive = FALSE;
1995 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1996 * the connection is keep-alive by default */
1997 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1998 && !strcmpiW(szVersion, g_szHttp1_1))
2000 keepalive = TRUE;
2003 dwBufferSize = sizeof(szConnectionResponse);
2004 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2005 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2007 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2010 return keepalive;
2013 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2015 http_request_t *req = (http_request_t*)hdr;
2017 http_release_netconn(req, drain_content(req, FALSE));
2020 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2022 int len;
2023 if (unicode)
2025 WCHAR *buf = buffer;
2027 if (str) len = strlenW(str);
2028 else len = 0;
2029 if (*size < (len + 1) * sizeof(WCHAR))
2031 *size = (len + 1) * sizeof(WCHAR);
2032 return ERROR_INSUFFICIENT_BUFFER;
2034 if (str) strcpyW(buf, str);
2035 else buf[0] = 0;
2037 *size = len;
2038 return ERROR_SUCCESS;
2040 else
2042 char *buf = buffer;
2044 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2045 else len = 1;
2046 if (*size < len)
2048 *size = len;
2049 return ERROR_INSUFFICIENT_BUFFER;
2051 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2052 else buf[0] = 0;
2054 *size = len - 1;
2055 return ERROR_SUCCESS;
2059 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2061 http_request_t *req = (http_request_t*)hdr;
2063 switch(option) {
2064 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2066 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2068 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2070 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2071 return ERROR_INSUFFICIENT_BUFFER;
2072 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2073 /* FIXME: can't get a SOCKET from our connection since we don't use
2074 * winsock
2076 info->Socket = 0;
2077 /* FIXME: get source port from req->netConnection */
2078 info->SourcePort = 0;
2079 info->DestPort = req->server->port;
2080 info->Flags = 0;
2081 if (HTTP_KeepAlive(req))
2082 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2083 if (req->proxy)
2084 info->Flags |= IDSI_FLAG_PROXY;
2085 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2086 info->Flags |= IDSI_FLAG_SECURE;
2088 return ERROR_SUCCESS;
2091 case 98:
2092 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2093 /* fall through */
2094 case INTERNET_OPTION_SECURITY_FLAGS:
2096 DWORD flags;
2098 if (*size < sizeof(ULONG))
2099 return ERROR_INSUFFICIENT_BUFFER;
2101 *size = sizeof(DWORD);
2102 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2103 *(DWORD *)buffer = flags;
2105 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2106 return ERROR_SUCCESS;
2109 case INTERNET_OPTION_HANDLE_TYPE:
2110 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2112 if (*size < sizeof(ULONG))
2113 return ERROR_INSUFFICIENT_BUFFER;
2115 *size = sizeof(DWORD);
2116 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2117 return ERROR_SUCCESS;
2119 case INTERNET_OPTION_URL: {
2120 WCHAR *url;
2121 DWORD res;
2123 TRACE("INTERNET_OPTION_URL\n");
2125 url = compose_request_url(req);
2126 if(!url)
2127 return ERROR_OUTOFMEMORY;
2129 res = str_to_buffer(url, buffer, size, unicode);
2130 heap_free(url);
2131 return res;
2133 case INTERNET_OPTION_USER_AGENT:
2134 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2135 case INTERNET_OPTION_USERNAME:
2136 return str_to_buffer(req->session->userName, buffer, size, unicode);
2137 case INTERNET_OPTION_PASSWORD:
2138 return str_to_buffer(req->session->password, buffer, size, unicode);
2139 case INTERNET_OPTION_PROXY_USERNAME:
2140 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2141 case INTERNET_OPTION_PROXY_PASSWORD:
2142 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2144 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2145 INTERNET_CACHE_ENTRY_INFOW *info;
2146 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2147 DWORD nbytes, error;
2148 BOOL ret;
2150 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2152 if(!req->req_file)
2153 return ERROR_FILE_NOT_FOUND;
2155 if (*size < sizeof(*ts))
2157 *size = sizeof(*ts);
2158 return ERROR_INSUFFICIENT_BUFFER;
2161 nbytes = 0;
2162 ret = GetUrlCacheEntryInfoW(req->req_file->url, NULL, &nbytes);
2163 error = GetLastError();
2164 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2166 if (!(info = heap_alloc(nbytes)))
2167 return ERROR_OUTOFMEMORY;
2169 GetUrlCacheEntryInfoW(req->req_file->url, info, &nbytes);
2171 ts->ftExpires = info->ExpireTime;
2172 ts->ftLastModified = info->LastModifiedTime;
2174 heap_free(info);
2175 *size = sizeof(*ts);
2176 return ERROR_SUCCESS;
2178 return error;
2181 case INTERNET_OPTION_DATAFILE_NAME: {
2182 DWORD req_size;
2184 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2186 if(!req->req_file) {
2187 *size = 0;
2188 return ERROR_INTERNET_ITEM_NOT_FOUND;
2191 if(unicode) {
2192 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2193 if(*size < req_size)
2194 return ERROR_INSUFFICIENT_BUFFER;
2196 *size = req_size;
2197 memcpy(buffer, req->req_file->file_name, *size);
2198 return ERROR_SUCCESS;
2199 }else {
2200 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2201 if (req_size > *size)
2202 return ERROR_INSUFFICIENT_BUFFER;
2204 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2205 -1, buffer, *size, NULL, NULL);
2206 return ERROR_SUCCESS;
2210 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2211 PCCERT_CONTEXT context;
2213 if(!req->netconn)
2214 return ERROR_INTERNET_INVALID_OPERATION;
2216 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2217 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2218 return ERROR_INSUFFICIENT_BUFFER;
2221 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2222 if(context) {
2223 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2224 DWORD len;
2226 memset(info, 0, sizeof(*info));
2227 info->ftExpiry = context->pCertInfo->NotAfter;
2228 info->ftStart = context->pCertInfo->NotBefore;
2229 len = CertNameToStrA(context->dwCertEncodingType,
2230 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2231 info->lpszSubjectInfo = LocalAlloc(0, len);
2232 if(info->lpszSubjectInfo)
2233 CertNameToStrA(context->dwCertEncodingType,
2234 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2235 info->lpszSubjectInfo, len);
2236 len = CertNameToStrA(context->dwCertEncodingType,
2237 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2238 info->lpszIssuerInfo = LocalAlloc(0, len);
2239 if(info->lpszIssuerInfo)
2240 CertNameToStrA(context->dwCertEncodingType,
2241 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2242 info->lpszIssuerInfo, len);
2243 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2244 CertFreeCertificateContext(context);
2245 return ERROR_SUCCESS;
2247 return ERROR_NOT_SUPPORTED;
2249 case INTERNET_OPTION_CONNECT_TIMEOUT:
2250 if (*size < sizeof(DWORD))
2251 return ERROR_INSUFFICIENT_BUFFER;
2253 *size = sizeof(DWORD);
2254 *(DWORD *)buffer = req->connect_timeout;
2255 return ERROR_SUCCESS;
2256 case INTERNET_OPTION_REQUEST_FLAGS: {
2257 DWORD flags = 0;
2259 if (*size < sizeof(DWORD))
2260 return ERROR_INSUFFICIENT_BUFFER;
2262 /* FIXME: Add support for:
2263 * INTERNET_REQFLAG_FROM_CACHE
2264 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2267 if(req->proxy)
2268 flags |= INTERNET_REQFLAG_VIA_PROXY;
2269 if(!req->status_code)
2270 flags |= INTERNET_REQFLAG_NO_HEADERS;
2272 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2274 *size = sizeof(DWORD);
2275 *(DWORD*)buffer = flags;
2276 return ERROR_SUCCESS;
2280 return INET_QueryOption(hdr, option, buffer, size, unicode);
2283 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2285 http_request_t *req = (http_request_t*)hdr;
2287 switch(option) {
2288 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2289 TRACE("Undocumented option 99\n");
2291 if (!buffer || size != sizeof(DWORD))
2292 return ERROR_INVALID_PARAMETER;
2293 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2294 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2296 /* fall through */
2297 case INTERNET_OPTION_SECURITY_FLAGS:
2299 DWORD flags;
2301 if (!buffer || size != sizeof(DWORD))
2302 return ERROR_INVALID_PARAMETER;
2303 flags = *(DWORD *)buffer;
2304 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2305 flags &= SECURITY_SET_MASK;
2306 req->security_flags |= flags;
2307 if(is_valid_netconn(req->netconn))
2308 req->netconn->security_flags |= flags;
2309 return ERROR_SUCCESS;
2311 case INTERNET_OPTION_CONNECT_TIMEOUT:
2312 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2313 req->connect_timeout = *(DWORD *)buffer;
2314 return ERROR_SUCCESS;
2316 case INTERNET_OPTION_SEND_TIMEOUT:
2317 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2318 req->send_timeout = *(DWORD *)buffer;
2319 return ERROR_SUCCESS;
2321 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2322 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2323 req->receive_timeout = *(DWORD *)buffer;
2324 return ERROR_SUCCESS;
2326 case INTERNET_OPTION_USERNAME:
2327 heap_free(req->session->userName);
2328 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2329 return ERROR_SUCCESS;
2331 case INTERNET_OPTION_PASSWORD:
2332 heap_free(req->session->password);
2333 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2334 return ERROR_SUCCESS;
2336 case INTERNET_OPTION_PROXY_USERNAME:
2337 heap_free(req->session->appInfo->proxyUsername);
2338 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2339 return ERROR_SUCCESS;
2341 case INTERNET_OPTION_PROXY_PASSWORD:
2342 heap_free(req->session->appInfo->proxyPassword);
2343 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2344 return ERROR_SUCCESS;
2346 case INTERNET_OPTION_HTTP_DECODING:
2347 if(size != sizeof(BOOL))
2348 return ERROR_INVALID_PARAMETER;
2349 req->decoding = *(BOOL*)buffer;
2350 return ERROR_SUCCESS;
2353 return INET_SetOption(hdr, option, buffer, size);
2356 static void commit_cache_entry(http_request_t *req)
2358 WCHAR *header;
2359 DWORD header_len;
2360 BOOL res;
2362 TRACE("%p\n", req);
2364 CloseHandle(req->hCacheFile);
2365 req->hCacheFile = NULL;
2367 header = build_response_header(req, TRUE);
2368 header_len = (header ? strlenW(header) : 0);
2369 res = CommitUrlCacheEntryW(req->req_file->url, req->req_file->file_name, req->expires,
2370 req->last_modified, NORMAL_CACHE_ENTRY,
2371 header, header_len, NULL, 0);
2372 if(res)
2373 req->req_file->is_committed = TRUE;
2374 else
2375 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2376 heap_free(header);
2379 static void create_cache_entry(http_request_t *req)
2381 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2382 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2384 WCHAR file_name[MAX_PATH+1];
2385 WCHAR *url;
2386 BOOL b = TRUE;
2388 /* FIXME: We should free previous cache file earlier */
2389 if(req->req_file) {
2390 req_file_release(req->req_file);
2391 req->req_file = NULL;
2393 if(req->hCacheFile) {
2394 CloseHandle(req->hCacheFile);
2395 req->hCacheFile = NULL;
2398 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2399 b = FALSE;
2401 if(b) {
2402 int header_idx;
2404 EnterCriticalSection( &req->headers_section );
2406 header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2407 if(header_idx != -1) {
2408 WCHAR *ptr;
2410 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2411 WCHAR *end;
2413 while(*ptr==' ' || *ptr=='\t')
2414 ptr++;
2416 end = strchrW(ptr, ',');
2417 if(!end)
2418 end = ptr + strlenW(ptr);
2420 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2421 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2422 b = FALSE;
2423 break;
2426 ptr = end;
2427 if(*ptr == ',')
2428 ptr++;
2432 LeaveCriticalSection( &req->headers_section );
2435 if(!b) {
2436 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2437 return;
2439 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2442 url = compose_request_url(req);
2443 if(!url) {
2444 WARN("Could not get URL\n");
2445 return;
2448 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2449 if(!b) {
2450 WARN("Could not create cache entry: %08x\n", GetLastError());
2451 return;
2454 create_req_file(file_name, &req->req_file);
2455 req->req_file->url = url;
2457 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2458 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2459 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2460 WARN("Could not create file: %u\n", GetLastError());
2461 req->hCacheFile = NULL;
2462 return;
2465 if(req->read_size) {
2466 DWORD written;
2468 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2469 if(!b)
2470 FIXME("WriteFile failed: %u\n", GetLastError());
2472 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2473 commit_cache_entry(req);
2477 /* read some more data into the read buffer (the read section must be held) */
2478 static DWORD read_more_data( http_request_t *req, int maxlen )
2480 DWORD res;
2481 int len;
2483 if (req->read_pos)
2485 /* move existing data to the start of the buffer */
2486 if(req->read_size)
2487 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2488 req->read_pos = 0;
2491 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2493 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2494 maxlen - req->read_size, TRUE, &len );
2495 if(res == ERROR_SUCCESS)
2496 req->read_size += len;
2498 return res;
2501 /* remove some amount of data from the read buffer (the read section must be held) */
2502 static void remove_data( http_request_t *req, int count )
2504 if (!(req->read_size -= count)) req->read_pos = 0;
2505 else req->read_pos += count;
2508 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2510 int count, bytes_read, pos = 0;
2511 DWORD res;
2513 EnterCriticalSection( &req->read_section );
2514 for (;;)
2516 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2518 if (eol)
2520 count = eol - (req->read_buf + req->read_pos);
2521 bytes_read = count + 1;
2523 else count = bytes_read = req->read_size;
2525 count = min( count, *len - pos );
2526 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2527 pos += count;
2528 remove_data( req, bytes_read );
2529 if (eol) break;
2531 if ((res = read_more_data( req, -1 )))
2533 WARN( "read failed %u\n", res );
2534 LeaveCriticalSection( &req->read_section );
2535 return res;
2537 if (!req->read_size)
2539 *len = 0;
2540 TRACE( "returning empty string\n" );
2541 LeaveCriticalSection( &req->read_section );
2542 return ERROR_SUCCESS;
2545 LeaveCriticalSection( &req->read_section );
2547 if (pos < *len)
2549 if (pos && buffer[pos - 1] == '\r') pos--;
2550 *len = pos + 1;
2552 buffer[*len - 1] = 0;
2553 TRACE( "returning %s\n", debugstr_a(buffer));
2554 return ERROR_SUCCESS;
2557 /* check if we have reached the end of the data to read (the read section must be held) */
2558 static BOOL end_of_read_data( http_request_t *req )
2560 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2563 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, blocking_mode_t blocking_mode)
2565 DWORD res;
2567 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, blocking_mode);
2568 assert(*read <= size);
2570 if(req->hCacheFile) {
2571 if(*read) {
2572 BOOL bres;
2573 DWORD written;
2575 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2576 if(!bres)
2577 FIXME("WriteFile failed: %u\n", GetLastError());
2580 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2581 commit_cache_entry(req);
2584 return res;
2587 /* fetch some more data into the read buffer (the read section must be held) */
2588 static DWORD refill_read_buffer(http_request_t *req, blocking_mode_t blocking_mode, DWORD *read_bytes)
2590 DWORD res, read=0;
2592 if(req->read_size == sizeof(req->read_buf))
2593 return ERROR_SUCCESS;
2595 if(req->read_pos) {
2596 if(req->read_size)
2597 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2598 req->read_pos = 0;
2601 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2602 &read, blocking_mode);
2603 req->read_size += read;
2605 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2606 if(read_bytes)
2607 *read_bytes = read;
2608 return res;
2611 /* return the size of data available to be read immediately (the read section must be held) */
2612 static DWORD get_avail_data( http_request_t *req )
2614 return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2617 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2619 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2620 DWORD avail = 0;
2622 if(is_valid_netconn(req->netconn))
2623 NETCON_query_data_available(req->netconn, &avail);
2624 return netconn_stream->content_length == ~0u
2625 ? avail
2626 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2629 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2631 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2632 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2635 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2636 DWORD *read, blocking_mode_t blocking_mode)
2638 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2639 DWORD res = ERROR_SUCCESS;
2640 int len = 0, ret = 0;
2642 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2644 if(size && is_valid_netconn(req->netconn)) {
2645 while((res = NETCON_recv(req->netconn, buf+ret, size-ret, blocking_mode != BLOCKING_DISALLOW, &len)) == ERROR_SUCCESS) {
2646 if(!len) {
2647 netconn_stream->content_length = netconn_stream->content_read;
2648 break;
2650 ret += len;
2651 netconn_stream->content_read += len;
2652 if(blocking_mode != BLOCKING_WAITALL || size == ret)
2653 break;
2656 if(ret || (blocking_mode == BLOCKING_DISALLOW && res == WSAEWOULDBLOCK))
2657 res = ERROR_SUCCESS;
2660 TRACE("read %u bytes\n", ret);
2661 *read = ret;
2662 return res;
2665 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2667 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2668 BYTE buf[1024];
2669 int len;
2671 if(netconn_end_of_data(stream, req))
2672 return TRUE;
2674 do {
2675 if(NETCON_recv(req->netconn, buf, sizeof(buf), FALSE, &len) != ERROR_SUCCESS)
2676 return FALSE;
2678 netconn_stream->content_read += len;
2679 }while(netconn_stream->content_read < netconn_stream->content_length);
2681 return TRUE;
2684 static void netconn_destroy(data_stream_t *stream)
2688 static const data_stream_vtbl_t netconn_stream_vtbl = {
2689 netconn_get_avail_data,
2690 netconn_end_of_data,
2691 netconn_read,
2692 netconn_drain_content,
2693 netconn_destroy
2696 /* read some more data into the read buffer (the read section must be held) */
2697 static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
2699 DWORD res;
2700 int len;
2702 assert(!stream->end_of_data);
2704 if (stream->buf_pos)
2706 /* move existing data to the start of the buffer */
2707 if(stream->buf_size)
2708 memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
2709 stream->buf_pos = 0;
2712 if (maxlen == -1) maxlen = sizeof(stream->buf);
2714 res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2715 maxlen - stream->buf_size, TRUE, &len );
2716 if(res == ERROR_SUCCESS)
2717 stream->buf_size += len;
2719 return res;
2722 /* remove some amount of data from the read buffer (the read section must be held) */
2723 static void remove_chunked_data(chunked_stream_t *stream, int count)
2725 if (!(stream->buf_size -= count)) stream->buf_pos = 0;
2726 else stream->buf_pos += count;
2729 /* discard data contents until we reach end of line (the read section must be held) */
2730 static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2732 DWORD res;
2736 BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2737 if (eol)
2739 remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2740 break;
2742 stream->buf_pos = stream->buf_size = 0; /* discard everything */
2743 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2744 } while (stream->buf_size);
2745 return ERROR_SUCCESS;
2748 /* read the size of the next chunk (the read section must be held) */
2749 static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2751 DWORD chunk_size = 0, res;
2753 assert(!stream->chunk_size || stream->chunk_size == ~0u);
2755 if (stream->end_of_data) return ERROR_SUCCESS;
2757 /* read terminator for the previous chunk */
2758 if(!stream->chunk_size && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2759 return res;
2761 for (;;)
2763 while (stream->buf_size)
2765 char ch = stream->buf[stream->buf_pos];
2766 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2767 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2768 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2769 else if (ch == ';' || ch == '\r' || ch == '\n')
2771 TRACE( "reading %u byte chunk\n", chunk_size );
2772 stream->chunk_size = chunk_size;
2773 if (req->contentLength == ~0u) req->contentLength = chunk_size;
2774 else req->contentLength += chunk_size;
2776 /* eat the rest of this line */
2777 if ((res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2778 return res;
2780 /* if there's chunk data, return now */
2781 if (chunk_size) return ERROR_SUCCESS;
2783 /* otherwise, eat the terminator for this chunk */
2784 if ((res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2785 return res;
2787 stream->end_of_data = TRUE;
2788 return ERROR_SUCCESS;
2790 remove_chunked_data(stream, 1);
2792 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2793 if (!stream->buf_size)
2795 stream->chunk_size = 0;
2796 return ERROR_SUCCESS;
2801 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2803 /* Allow reading only from read buffer */
2804 return 0;
2807 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2809 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2810 return chunked_stream->end_of_data;
2813 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2814 DWORD *read, blocking_mode_t blocking_mode)
2816 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2817 DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;
2819 if(!chunked_stream->chunk_size || chunked_stream->chunk_size == ~0u) {
2820 res = start_next_chunk(chunked_stream, req);
2821 if(res != ERROR_SUCCESS)
2822 return res;
2825 while(size && chunked_stream->chunk_size && !chunked_stream->end_of_data) {
2826 if(chunked_stream->buf_size) {
2827 read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2829 /* this could block */
2830 if(blocking_mode == BLOCKING_DISALLOW && read_bytes == chunked_stream->chunk_size)
2831 break;
2833 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2834 remove_chunked_data(chunked_stream, read_bytes);
2835 }else {
2836 read_bytes = min(size, chunked_stream->chunk_size);
2838 if(blocking_mode == BLOCKING_DISALLOW) {
2839 DWORD avail;
2841 if(!is_valid_netconn(req->netconn) || !NETCON_query_data_available(req->netconn, &avail) || !avail)
2842 break;
2843 if(read_bytes > avail)
2844 read_bytes = avail;
2846 /* this could block */
2847 if(read_bytes == chunked_stream->chunk_size)
2848 break;
2851 res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, TRUE, (int*)&read_bytes);
2852 if(res != ERROR_SUCCESS)
2853 break;
2856 chunked_stream->chunk_size -= read_bytes;
2857 size -= read_bytes;
2858 ret_read += read_bytes;
2859 if(size && !chunked_stream->chunk_size) {
2860 assert(blocking_mode != BLOCKING_DISALLOW);
2861 res = start_next_chunk(chunked_stream, req);
2862 if(res != ERROR_SUCCESS)
2863 break;
2866 if(blocking_mode == BLOCKING_ALLOW)
2867 blocking_mode = BLOCKING_DISALLOW;
2870 TRACE("read %u bytes\n", ret_read);
2871 *read = ret_read;
2872 return res;
2875 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2877 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2879 remove_chunked_data(chunked_stream, chunked_stream->buf_size);
2880 return chunked_stream->end_of_data;
2883 static void chunked_destroy(data_stream_t *stream)
2885 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2886 heap_free(chunked_stream);
2889 static const data_stream_vtbl_t chunked_stream_vtbl = {
2890 chunked_get_avail_data,
2891 chunked_end_of_data,
2892 chunked_read,
2893 chunked_drain_content,
2894 chunked_destroy
2897 /* set the request content length based on the headers */
2898 static DWORD set_content_length(http_request_t *request)
2900 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2901 static const WCHAR headW[] = {'H','E','A','D',0};
2902 WCHAR encoding[20];
2903 DWORD size;
2905 if(request->status_code == HTTP_STATUS_NO_CONTENT || !strcmpW(request->verb, headW)) {
2906 request->contentLength = request->netconn_stream.content_length = 0;
2907 return ERROR_SUCCESS;
2910 size = sizeof(request->contentLength);
2911 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2912 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2913 request->contentLength = ~0u;
2914 request->netconn_stream.content_length = request->contentLength;
2915 request->netconn_stream.content_read = request->read_size;
2917 size = sizeof(encoding);
2918 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2919 !strcmpiW(encoding, szChunked))
2921 chunked_stream_t *chunked_stream;
2923 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2924 if(!chunked_stream)
2925 return ERROR_OUTOFMEMORY;
2927 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2928 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2929 chunked_stream->chunk_size = ~0u;
2930 chunked_stream->end_of_data = FALSE;
2932 if(request->read_size) {
2933 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2934 chunked_stream->buf_size = request->read_size;
2935 request->read_size = request->read_pos = 0;
2938 request->data_stream = &chunked_stream->data_stream;
2939 request->contentLength = ~0u;
2942 if(request->decoding) {
2943 int encoding_idx;
2945 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2946 static const WCHAR gzipW[] = {'g','z','i','p',0};
2948 EnterCriticalSection( &request->headers_section );
2950 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2951 if(encoding_idx != -1) {
2952 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2953 HTTP_DeleteCustomHeader(request, encoding_idx);
2954 LeaveCriticalSection( &request->headers_section );
2955 return init_gzip_stream(request, TRUE);
2957 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2958 HTTP_DeleteCustomHeader(request, encoding_idx);
2959 LeaveCriticalSection( &request->headers_section );
2960 return init_gzip_stream(request, FALSE);
2964 LeaveCriticalSection( &request->headers_section );
2967 return ERROR_SUCCESS;
2970 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2972 INTERNET_ASYNC_RESULT iar;
2974 iar.dwResult = result;
2975 iar.dwError = error;
2977 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2978 sizeof(INTERNET_ASYNC_RESULT));
2981 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2983 DWORD res, read = 0, avail = 0;
2984 blocking_mode_t mode;
2986 TRACE("%p\n", req);
2988 EnterCriticalSection( &req->read_section );
2990 mode = first_notif && req->read_size ? BLOCKING_DISALLOW : BLOCKING_ALLOW;
2991 res = refill_read_buffer(req, mode, &read);
2992 if(res == ERROR_SUCCESS)
2993 avail = get_avail_data(req);
2995 LeaveCriticalSection( &req->read_section );
2997 if(res != ERROR_SUCCESS || (mode != BLOCKING_DISALLOW && !read)) {
2998 WARN("res %u read %u, closing connection\n", res, read);
2999 http_release_netconn(req, FALSE);
3002 if(res != ERROR_SUCCESS) {
3003 send_request_complete(req, 0, res);
3004 return;
3007 if(ret_size)
3008 *ret_size = avail;
3009 if(first_notif)
3010 avail = 0;
3012 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
3015 /* read data from the http connection (the read section must be held) */
3016 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read)
3018 DWORD current_read = 0, ret_read = 0;
3019 blocking_mode_t blocking_mode;
3020 DWORD res = ERROR_SUCCESS;
3022 blocking_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? BLOCKING_ALLOW : BLOCKING_WAITALL;
3024 EnterCriticalSection( &req->read_section );
3026 if(req->read_size) {
3027 ret_read = min(size, req->read_size);
3028 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3029 req->read_size -= ret_read;
3030 req->read_pos += ret_read;
3031 if(blocking_mode == BLOCKING_ALLOW)
3032 blocking_mode = BLOCKING_DISALLOW;
3035 if(ret_read < size) {
3036 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, blocking_mode);
3037 ret_read += current_read;
3040 LeaveCriticalSection( &req->read_section );
3042 *read = ret_read;
3043 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3045 if(size && !ret_read)
3046 http_release_netconn(req, res == ERROR_SUCCESS);
3048 return res;
3051 static BOOL drain_content(http_request_t *req, BOOL blocking)
3053 BOOL ret;
3055 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
3056 return FALSE;
3058 if(!strcmpW(req->verb, szHEAD))
3059 return TRUE;
3061 if(!blocking)
3062 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3064 EnterCriticalSection( &req->read_section );
3066 while(1) {
3067 DWORD bytes_read, res;
3068 BYTE buf[4096];
3070 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read);
3071 if(res != ERROR_SUCCESS) {
3072 ret = FALSE;
3073 break;
3075 if(!bytes_read) {
3076 ret = TRUE;
3077 break;
3081 LeaveCriticalSection( &req->read_section );
3082 return ret;
3085 typedef struct {
3086 task_header_t hdr;
3087 void *buf;
3088 DWORD size;
3089 DWORD *ret_read;
3090 } read_file_ex_task_t;
3092 static void AsyncReadFileExProc(task_header_t *hdr)
3094 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3095 http_request_t *req = (http_request_t*)task->hdr.hdr;
3096 DWORD res = ERROR_SUCCESS, read = 0, buffered = 0;
3098 TRACE("%p\n", req);
3100 if(task->ret_read)
3101 res = HTTPREQ_Read(req, task->buf, task->size, &read);
3102 if(res == ERROR_SUCCESS)
3103 res = refill_read_buffer(req, task->ret_read ? BLOCKING_DISALLOW : BLOCKING_ALLOW, &buffered);
3104 if (res == ERROR_SUCCESS)
3106 if(task->ret_read)
3107 *task->ret_read = read;
3108 read += buffered;
3109 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3110 &read, sizeof(read));
3113 send_request_complete(req, res == ERROR_SUCCESS, res);
3116 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3117 DWORD flags, DWORD_PTR context)
3120 http_request_t *req = (http_request_t*)hdr;
3121 DWORD res, read, cread, error = ERROR_SUCCESS;
3123 TRACE("(%p %p %u %x)\n", req, buf, size, flags);
3125 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3126 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3128 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3130 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3132 read_file_ex_task_t *task;
3134 if (TryEnterCriticalSection( &req->read_section ))
3136 if (get_avail_data(req) || end_of_read_data(req))
3138 res = HTTPREQ_Read(req, buf, size, &read);
3139 LeaveCriticalSection( &req->read_section );
3140 goto done;
3142 LeaveCriticalSection( &req->read_section );
3145 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3146 task->buf = buf;
3147 task->size = size;
3148 task->ret_read = (flags & IRF_NO_WAIT) ? NULL : ret_read;
3150 INTERNET_AsyncCall(&task->hdr);
3152 return ERROR_IO_PENDING;
3155 read = 0;
3157 EnterCriticalSection( &req->read_section );
3158 if(hdr->dwError == ERROR_SUCCESS)
3159 hdr->dwError = INTERNET_HANDLE_IN_USE;
3160 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3161 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3163 while(1) {
3164 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread);
3165 if(res != ERROR_SUCCESS)
3166 break;
3168 read += cread;
3169 if(read == size || end_of_read_data(req))
3170 break;
3172 LeaveCriticalSection( &req->read_section );
3174 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3175 &cread, sizeof(cread));
3176 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3177 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3179 EnterCriticalSection( &req->read_section );
3182 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3183 hdr->dwError = ERROR_SUCCESS;
3184 else
3185 error = hdr->dwError;
3187 LeaveCriticalSection( &req->read_section );
3189 done:
3190 *ret_read = read;
3191 if (res == ERROR_SUCCESS) {
3192 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3193 &read, sizeof(read));
3196 return res==ERROR_SUCCESS ? error : res;
3199 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3201 DWORD res;
3202 http_request_t *request = (http_request_t*)hdr;
3204 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3206 *written = 0;
3207 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3208 if (res == ERROR_SUCCESS)
3209 request->bytesWritten += *written;
3211 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3212 return res;
3215 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3217 http_request_t *req = (http_request_t*)hdr;
3218 DWORD res;
3220 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3222 read_file_ex_task_t *task;
3224 if (TryEnterCriticalSection( &req->read_section ))
3226 if (get_avail_data(req) || end_of_read_data(req))
3228 res = HTTPREQ_Read(req, buffer, size, read);
3229 LeaveCriticalSection( &req->read_section );
3230 return res;
3232 LeaveCriticalSection( &req->read_section );
3235 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3236 task->buf = buffer;
3237 task->size = size;
3238 task->ret_read = read;
3240 *read = 0;
3241 INTERNET_AsyncCall(&task->hdr);
3243 return ERROR_IO_PENDING;
3246 EnterCriticalSection( &req->read_section );
3247 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3248 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3250 res = HTTPREQ_Read(req, buffer, size, read);
3251 if(res == ERROR_SUCCESS)
3252 res = hdr->dwError;
3253 LeaveCriticalSection( &req->read_section );
3255 return res;
3258 typedef struct {
3259 task_header_t hdr;
3260 DWORD *ret_size;
3261 } http_data_available_task_t;
3263 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3265 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3267 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3270 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3272 http_request_t *req = (http_request_t*)hdr;
3274 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3276 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3278 http_data_available_task_t *task;
3280 /* never wait, if we can't enter the section we queue an async request right away */
3281 if (TryEnterCriticalSection( &req->read_section ))
3283 refill_read_buffer(req, BLOCKING_DISALLOW, NULL);
3284 if ((*available = get_avail_data( req ))) goto done;
3285 if (end_of_read_data( req )) goto done;
3286 LeaveCriticalSection( &req->read_section );
3289 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3290 task->ret_size = available;
3291 INTERNET_AsyncCall(&task->hdr);
3292 return ERROR_IO_PENDING;
3295 EnterCriticalSection( &req->read_section );
3297 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3299 refill_read_buffer( req, BLOCKING_ALLOW, NULL );
3300 *available = get_avail_data( req );
3303 done:
3304 LeaveCriticalSection( &req->read_section );
3306 TRACE( "returning %u\n", *available );
3307 return ERROR_SUCCESS;
3310 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3312 http_request_t *req = (http_request_t*)hdr;
3314 TRACE("(%p)\n", req);
3316 if(!req->req_file) {
3317 WARN("No cache file name available\n");
3318 return ERROR_FILE_NOT_FOUND;
3321 *ret = req_file_addref(req->req_file);
3322 return ERROR_SUCCESS;
3325 static const object_vtbl_t HTTPREQVtbl = {
3326 HTTPREQ_Destroy,
3327 HTTPREQ_CloseConnection,
3328 HTTPREQ_QueryOption,
3329 HTTPREQ_SetOption,
3330 HTTPREQ_ReadFile,
3331 HTTPREQ_ReadFileEx,
3332 HTTPREQ_WriteFile,
3333 HTTPREQ_QueryDataAvailable,
3334 NULL,
3335 HTTPREQ_LockRequestFile
3338 /***********************************************************************
3339 * HTTP_HttpOpenRequestW (internal)
3341 * Open a HTTP request handle
3343 * RETURNS
3344 * HINTERNET a HTTP request handle on success
3345 * NULL on failure
3348 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3349 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3350 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3351 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3353 appinfo_t *hIC = session->appInfo;
3354 http_request_t *request;
3355 DWORD len;
3357 TRACE("-->\n");
3359 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3360 if(!request)
3361 return ERROR_OUTOFMEMORY;
3363 request->hdr.htype = WH_HHTTPREQ;
3364 request->hdr.dwFlags = dwFlags;
3365 request->hdr.dwContext = dwContext;
3366 request->contentLength = ~0u;
3368 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3369 request->data_stream = &request->netconn_stream.data_stream;
3370 request->connect_timeout = session->connect_timeout;
3371 request->send_timeout = session->send_timeout;
3372 request->receive_timeout = session->receive_timeout;
3374 InitializeCriticalSection( &request->headers_section );
3375 request->headers_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.headers_section");
3377 InitializeCriticalSection( &request->read_section );
3378 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3380 WININET_AddRef( &session->hdr );
3381 request->session = session;
3382 list_add_head( &session->hdr.children, &request->hdr.entry );
3384 request->server = get_server(substrz(session->hostName), session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3385 if(!request->server) {
3386 WININET_Release(&request->hdr);
3387 return ERROR_OUTOFMEMORY;
3390 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3391 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3392 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3393 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3395 if (lpszObjectName && *lpszObjectName) {
3396 HRESULT rc;
3398 len = 0;
3399 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3400 if (rc != E_POINTER)
3401 len = strlenW(lpszObjectName)+1;
3402 request->path = heap_alloc(len*sizeof(WCHAR));
3403 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3404 URL_ESCAPE_SPACES_ONLY);
3405 if (rc != S_OK)
3407 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3408 strcpyW(request->path,lpszObjectName);
3410 }else {
3411 static const WCHAR slashW[] = {'/',0};
3413 request->path = heap_strdupW(slashW);
3416 if (lpszReferrer && *lpszReferrer)
3417 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3419 if (lpszAcceptTypes)
3421 int i;
3422 for (i = 0; lpszAcceptTypes[i]; i++)
3424 if (!*lpszAcceptTypes[i]) continue;
3425 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3426 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3427 HTTP_ADDHDR_FLAG_REQ |
3428 (i == 0 ? (HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD) : 0));
3432 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3433 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3435 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3436 HTTP_DealWithProxy( hIC, session, request );
3438 INTERNET_SendCallback(&session->hdr, dwContext,
3439 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3440 sizeof(HINTERNET));
3442 TRACE("<-- (%p)\n", request);
3444 *ret = request->hdr.hInternet;
3445 return ERROR_SUCCESS;
3448 /***********************************************************************
3449 * HttpOpenRequestW (WININET.@)
3451 * Open a HTTP request handle
3453 * RETURNS
3454 * HINTERNET a HTTP request handle on success
3455 * NULL on failure
3458 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3459 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3460 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3461 DWORD dwFlags, DWORD_PTR dwContext)
3463 http_session_t *session;
3464 HINTERNET handle = NULL;
3465 DWORD res;
3467 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3468 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3469 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3470 dwFlags, dwContext);
3471 if(lpszAcceptTypes!=NULL)
3473 int i;
3474 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3475 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3478 session = (http_session_t*) get_handle_object( hHttpSession );
3479 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3481 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3482 goto lend;
3486 * My tests seem to show that the windows version does not
3487 * become asynchronous until after this point. And anyhow
3488 * if this call was asynchronous then how would you get the
3489 * necessary HINTERNET pointer returned by this function.
3492 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3493 lpszVersion, lpszReferrer, lpszAcceptTypes,
3494 dwFlags, dwContext, &handle);
3495 lend:
3496 if( session )
3497 WININET_Release( &session->hdr );
3498 TRACE("returning %p\n", handle);
3499 if(res != ERROR_SUCCESS)
3500 SetLastError(res);
3501 return handle;
3504 static const LPCWSTR header_lookup[] = {
3505 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3506 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3507 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3508 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3509 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3510 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3511 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3512 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3513 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3514 szDate, /* HTTP_QUERY_DATE = 9 */
3515 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3516 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3517 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3518 szURI, /* HTTP_QUERY_URI = 13 */
3519 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3520 NULL, /* HTTP_QUERY_COST = 15 */
3521 NULL, /* HTTP_QUERY_LINK = 16 */
3522 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3523 NULL, /* HTTP_QUERY_VERSION = 18 */
3524 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3525 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3526 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3527 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3528 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3529 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3530 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3531 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3532 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3533 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3534 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3535 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3536 NULL, /* HTTP_QUERY_FROM = 31 */
3537 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3538 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3539 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3540 szReferer, /* HTTP_QUERY_REFERER = 35 */
3541 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3542 szServer, /* HTTP_QUERY_SERVER = 37 */
3543 NULL, /* HTTP_TITLE = 38 */
3544 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3545 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3546 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3547 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3548 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3549 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3550 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3551 NULL, /* HTTP_QUERY_REFRESH = 46 */
3552 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3553 szAge, /* HTTP_QUERY_AGE = 48 */
3554 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3555 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3556 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3557 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3558 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3559 szETag, /* HTTP_QUERY_ETAG = 54 */
3560 hostW, /* HTTP_QUERY_HOST = 55 */
3561 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3562 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3563 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3564 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3565 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3566 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3567 szRange, /* HTTP_QUERY_RANGE = 62 */
3568 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3569 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3570 szVary, /* HTTP_QUERY_VARY = 65 */
3571 szVia, /* HTTP_QUERY_VIA = 66 */
3572 szWarning, /* HTTP_QUERY_WARNING = 67 */
3573 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3574 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3575 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3578 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3580 /***********************************************************************
3581 * HTTP_HttpQueryInfoW (internal)
3583 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3584 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3586 LPHTTPHEADERW lphttpHdr = NULL;
3587 BOOL request_only = !!(dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS);
3588 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3589 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3590 INT index = -1;
3592 EnterCriticalSection( &request->headers_section );
3594 /* Find requested header structure */
3595 switch (level)
3597 case HTTP_QUERY_CUSTOM:
3598 if (!lpBuffer)
3600 LeaveCriticalSection( &request->headers_section );
3601 return ERROR_INVALID_PARAMETER;
3603 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3604 break;
3605 case HTTP_QUERY_RAW_HEADERS_CRLF:
3607 LPWSTR headers;
3608 DWORD len = 0;
3609 DWORD res = ERROR_INVALID_PARAMETER;
3611 if (request_only)
3612 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3613 else
3614 headers = build_response_header(request, TRUE);
3615 if (!headers)
3617 LeaveCriticalSection( &request->headers_section );
3618 return ERROR_OUTOFMEMORY;
3621 len = strlenW(headers) * sizeof(WCHAR);
3622 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3624 len += sizeof(WCHAR);
3625 res = ERROR_INSUFFICIENT_BUFFER;
3627 else if (lpBuffer)
3629 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3630 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3631 res = ERROR_SUCCESS;
3633 *lpdwBufferLength = len;
3635 heap_free(headers);
3636 LeaveCriticalSection( &request->headers_section );
3637 return res;
3639 case HTTP_QUERY_RAW_HEADERS:
3641 LPWSTR headers;
3642 DWORD len;
3644 if (request_only)
3645 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3646 else
3647 headers = build_response_header(request, FALSE);
3649 if (!headers)
3651 LeaveCriticalSection( &request->headers_section );
3652 return ERROR_OUTOFMEMORY;
3655 len = strlenW(headers) * sizeof(WCHAR);
3656 if (len > *lpdwBufferLength)
3658 *lpdwBufferLength = len;
3659 heap_free(headers);
3660 LeaveCriticalSection( &request->headers_section );
3661 return ERROR_INSUFFICIENT_BUFFER;
3664 if (lpBuffer)
3666 DWORD i;
3668 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3670 for (i = 0; i < len / sizeof(WCHAR); i++)
3672 if (headers[i] == '\n')
3673 headers[i] = 0;
3675 memcpy(lpBuffer, headers, len);
3677 *lpdwBufferLength = len - sizeof(WCHAR);
3679 heap_free(headers);
3680 LeaveCriticalSection( &request->headers_section );
3681 return ERROR_SUCCESS;
3683 case HTTP_QUERY_STATUS_TEXT:
3684 if (request->statusText)
3686 DWORD len = strlenW(request->statusText);
3687 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3689 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3690 LeaveCriticalSection( &request->headers_section );
3691 return ERROR_INSUFFICIENT_BUFFER;
3693 if (lpBuffer)
3695 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3696 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3698 *lpdwBufferLength = len * sizeof(WCHAR);
3699 LeaveCriticalSection( &request->headers_section );
3700 return ERROR_SUCCESS;
3702 break;
3703 case HTTP_QUERY_VERSION:
3704 if (request->version)
3706 DWORD len = strlenW(request->version);
3707 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3709 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3710 LeaveCriticalSection( &request->headers_section );
3711 return ERROR_INSUFFICIENT_BUFFER;
3713 if (lpBuffer)
3715 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3716 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3718 *lpdwBufferLength = len * sizeof(WCHAR);
3719 LeaveCriticalSection( &request->headers_section );
3720 return ERROR_SUCCESS;
3722 break;
3723 case HTTP_QUERY_CONTENT_ENCODING:
3724 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3725 requested_index,request_only);
3726 break;
3727 case HTTP_QUERY_STATUS_CODE: {
3728 DWORD res = ERROR_SUCCESS;
3730 if(request_only)
3732 LeaveCriticalSection( &request->headers_section );
3733 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3736 if(requested_index)
3737 break;
3739 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3740 if(*lpdwBufferLength >= sizeof(DWORD))
3741 *(DWORD*)lpBuffer = request->status_code;
3742 else
3743 res = ERROR_INSUFFICIENT_BUFFER;
3744 *lpdwBufferLength = sizeof(DWORD);
3745 }else {
3746 WCHAR buf[12];
3747 DWORD size;
3748 static const WCHAR formatW[] = {'%','u',0};
3750 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3752 if(size <= *lpdwBufferLength) {
3753 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3754 }else {
3755 size += sizeof(WCHAR);
3756 res = ERROR_INSUFFICIENT_BUFFER;
3759 *lpdwBufferLength = size;
3761 LeaveCriticalSection( &request->headers_section );
3762 return res;
3764 default:
3765 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3767 if (level < LAST_TABLE_HEADER && header_lookup[level])
3768 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3769 requested_index,request_only);
3772 if (index >= 0)
3773 lphttpHdr = &request->custHeaders[index];
3775 /* Ensure header satisfies requested attributes */
3776 if (!lphttpHdr ||
3777 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3778 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3780 LeaveCriticalSection( &request->headers_section );
3781 return ERROR_HTTP_HEADER_NOT_FOUND;
3784 /* coalesce value to requested type */
3785 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3787 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3788 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3790 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3792 time_t tmpTime;
3793 struct tm tmpTM;
3794 SYSTEMTIME *STHook;
3796 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3798 tmpTM = *gmtime(&tmpTime);
3799 STHook = (SYSTEMTIME *)lpBuffer;
3800 STHook->wDay = tmpTM.tm_mday;
3801 STHook->wHour = tmpTM.tm_hour;
3802 STHook->wMilliseconds = 0;
3803 STHook->wMinute = tmpTM.tm_min;
3804 STHook->wDayOfWeek = tmpTM.tm_wday;
3805 STHook->wMonth = tmpTM.tm_mon + 1;
3806 STHook->wSecond = tmpTM.tm_sec;
3807 STHook->wYear = 1900+tmpTM.tm_year;
3809 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3810 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3811 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3813 else if (lphttpHdr->lpszValue)
3815 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3817 if (len > *lpdwBufferLength)
3819 *lpdwBufferLength = len;
3820 LeaveCriticalSection( &request->headers_section );
3821 return ERROR_INSUFFICIENT_BUFFER;
3823 if (lpBuffer)
3825 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3826 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3828 *lpdwBufferLength = len - sizeof(WCHAR);
3830 if (lpdwIndex) (*lpdwIndex)++;
3832 LeaveCriticalSection( &request->headers_section );
3833 return ERROR_SUCCESS;
3836 /***********************************************************************
3837 * HttpQueryInfoW (WININET.@)
3839 * Queries for information about an HTTP request
3841 * RETURNS
3842 * TRUE on success
3843 * FALSE on failure
3846 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3847 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3849 http_request_t *request;
3850 DWORD res;
3852 if (TRACE_ON(wininet)) {
3853 #define FE(x) { x, #x }
3854 static const wininet_flag_info query_flags[] = {
3855 FE(HTTP_QUERY_MIME_VERSION),
3856 FE(HTTP_QUERY_CONTENT_TYPE),
3857 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3858 FE(HTTP_QUERY_CONTENT_ID),
3859 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3860 FE(HTTP_QUERY_CONTENT_LENGTH),
3861 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3862 FE(HTTP_QUERY_ALLOW),
3863 FE(HTTP_QUERY_PUBLIC),
3864 FE(HTTP_QUERY_DATE),
3865 FE(HTTP_QUERY_EXPIRES),
3866 FE(HTTP_QUERY_LAST_MODIFIED),
3867 FE(HTTP_QUERY_MESSAGE_ID),
3868 FE(HTTP_QUERY_URI),
3869 FE(HTTP_QUERY_DERIVED_FROM),
3870 FE(HTTP_QUERY_COST),
3871 FE(HTTP_QUERY_LINK),
3872 FE(HTTP_QUERY_PRAGMA),
3873 FE(HTTP_QUERY_VERSION),
3874 FE(HTTP_QUERY_STATUS_CODE),
3875 FE(HTTP_QUERY_STATUS_TEXT),
3876 FE(HTTP_QUERY_RAW_HEADERS),
3877 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3878 FE(HTTP_QUERY_CONNECTION),
3879 FE(HTTP_QUERY_ACCEPT),
3880 FE(HTTP_QUERY_ACCEPT_CHARSET),
3881 FE(HTTP_QUERY_ACCEPT_ENCODING),
3882 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3883 FE(HTTP_QUERY_AUTHORIZATION),
3884 FE(HTTP_QUERY_CONTENT_ENCODING),
3885 FE(HTTP_QUERY_FORWARDED),
3886 FE(HTTP_QUERY_FROM),
3887 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3888 FE(HTTP_QUERY_LOCATION),
3889 FE(HTTP_QUERY_ORIG_URI),
3890 FE(HTTP_QUERY_REFERER),
3891 FE(HTTP_QUERY_RETRY_AFTER),
3892 FE(HTTP_QUERY_SERVER),
3893 FE(HTTP_QUERY_TITLE),
3894 FE(HTTP_QUERY_USER_AGENT),
3895 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3896 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3897 FE(HTTP_QUERY_ACCEPT_RANGES),
3898 FE(HTTP_QUERY_SET_COOKIE),
3899 FE(HTTP_QUERY_COOKIE),
3900 FE(HTTP_QUERY_REQUEST_METHOD),
3901 FE(HTTP_QUERY_REFRESH),
3902 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3903 FE(HTTP_QUERY_AGE),
3904 FE(HTTP_QUERY_CACHE_CONTROL),
3905 FE(HTTP_QUERY_CONTENT_BASE),
3906 FE(HTTP_QUERY_CONTENT_LOCATION),
3907 FE(HTTP_QUERY_CONTENT_MD5),
3908 FE(HTTP_QUERY_CONTENT_RANGE),
3909 FE(HTTP_QUERY_ETAG),
3910 FE(HTTP_QUERY_HOST),
3911 FE(HTTP_QUERY_IF_MATCH),
3912 FE(HTTP_QUERY_IF_NONE_MATCH),
3913 FE(HTTP_QUERY_IF_RANGE),
3914 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3915 FE(HTTP_QUERY_MAX_FORWARDS),
3916 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3917 FE(HTTP_QUERY_RANGE),
3918 FE(HTTP_QUERY_TRANSFER_ENCODING),
3919 FE(HTTP_QUERY_UPGRADE),
3920 FE(HTTP_QUERY_VARY),
3921 FE(HTTP_QUERY_VIA),
3922 FE(HTTP_QUERY_WARNING),
3923 FE(HTTP_QUERY_CUSTOM)
3925 static const wininet_flag_info modifier_flags[] = {
3926 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3927 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3928 FE(HTTP_QUERY_FLAG_NUMBER),
3929 FE(HTTP_QUERY_FLAG_COALESCE)
3931 #undef FE
3932 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3933 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3934 DWORD i;
3936 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3937 TRACE(" Attribute:");
3938 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3939 if (query_flags[i].val == info) {
3940 TRACE(" %s", query_flags[i].name);
3941 break;
3944 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3945 TRACE(" Unknown (%08x)", info);
3948 TRACE(" Modifier:");
3949 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3950 if (modifier_flags[i].val & info_mod) {
3951 TRACE(" %s", modifier_flags[i].name);
3952 info_mod &= ~ modifier_flags[i].val;
3956 if (info_mod) {
3957 TRACE(" Unknown (%08x)", info_mod);
3959 TRACE("\n");
3962 request = (http_request_t*) get_handle_object( hHttpRequest );
3963 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3965 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3966 goto lend;
3969 if (lpBuffer == NULL)
3970 *lpdwBufferLength = 0;
3971 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3972 lpBuffer, lpdwBufferLength, lpdwIndex);
3974 lend:
3975 if( request )
3976 WININET_Release( &request->hdr );
3978 TRACE("%u <--\n", res);
3979 if(res != ERROR_SUCCESS)
3980 SetLastError(res);
3981 return res == ERROR_SUCCESS;
3984 /***********************************************************************
3985 * HttpQueryInfoA (WININET.@)
3987 * Queries for information about an HTTP request
3989 * RETURNS
3990 * TRUE on success
3991 * FALSE on failure
3994 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3995 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3997 BOOL result;
3998 DWORD len;
3999 WCHAR* bufferW;
4001 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
4003 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
4004 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
4006 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
4007 lpdwBufferLength, lpdwIndex );
4010 if (lpBuffer)
4012 DWORD alloclen;
4013 len = (*lpdwBufferLength)*sizeof(WCHAR);
4014 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
4016 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
4017 if (alloclen < len)
4018 alloclen = len;
4020 else
4021 alloclen = len;
4022 bufferW = heap_alloc(alloclen);
4023 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
4024 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
4025 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
4026 } else
4028 bufferW = NULL;
4029 len = 0;
4032 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
4033 &len, lpdwIndex );
4034 if( result )
4036 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
4037 lpBuffer, *lpdwBufferLength, NULL, NULL );
4038 *lpdwBufferLength = len - 1;
4040 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
4042 else
4043 /* since the strings being returned from HttpQueryInfoW should be
4044 * only ASCII characters, it is reasonable to assume that all of
4045 * the Unicode characters can be reduced to a single byte */
4046 *lpdwBufferLength = len / sizeof(WCHAR);
4048 heap_free( bufferW );
4049 return result;
4052 static WCHAR *get_redirect_url(http_request_t *request)
4054 static WCHAR szHttp[] = {'h','t','t','p',0};
4055 static WCHAR szHttps[] = {'h','t','t','p','s',0};
4056 http_session_t *session = request->session;
4057 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4058 WCHAR *orig_url = NULL, *redirect_url = NULL, *combined_url = NULL;
4059 DWORD url_length = 0, res;
4060 BOOL b;
4062 url_length = 0;
4063 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4064 if(res == ERROR_INSUFFICIENT_BUFFER) {
4065 redirect_url = heap_alloc(url_length);
4066 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4068 if(res != ERROR_SUCCESS) {
4069 heap_free(redirect_url);
4070 return NULL;
4073 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
4074 urlComponents.lpszHostName = request->server->name;
4075 urlComponents.nPort = request->server->port;
4076 urlComponents.lpszUserName = session->userName;
4077 urlComponents.lpszUrlPath = request->path;
4079 b = InternetCreateUrlW(&urlComponents, 0, NULL, &url_length);
4080 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4081 orig_url = heap_alloc(url_length);
4083 /* convert from bytes to characters */
4084 url_length = url_length / sizeof(WCHAR) - 1;
4085 b = InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length);
4088 if(b) {
4089 url_length = 0;
4090 b = InternetCombineUrlW(orig_url, redirect_url, NULL, &url_length, ICU_ENCODE_SPACES_ONLY);
4091 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4092 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4093 b = InternetCombineUrlW(orig_url, redirect_url, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY);
4094 if(!b) {
4095 heap_free(combined_url);
4096 combined_url = NULL;
4101 heap_free(orig_url);
4102 heap_free(redirect_url);
4103 return combined_url;
4107 /***********************************************************************
4108 * HTTP_HandleRedirect (internal)
4110 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4112 http_session_t *session = request->session;
4113 WCHAR *path;
4115 if(lpszUrl[0]=='/')
4117 /* if it's an absolute path, keep the same session info */
4118 path = heap_strdupW(lpszUrl);
4120 else
4122 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4123 BOOL custom_port = FALSE;
4124 substr_t host;
4126 urlComponents.dwHostNameLength = 1;
4127 urlComponents.dwUserNameLength = 1;
4128 urlComponents.dwUrlPathLength = 1;
4129 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4130 return INTERNET_GetLastError();
4132 if(urlComponents.nScheme == INTERNET_SCHEME_HTTP) {
4133 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4134 TRACE("redirect from secure page to non-secure page\n");
4135 /* FIXME: warn about from secure redirect to non-secure page */
4136 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4139 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT;
4140 }else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS) {
4141 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4142 TRACE("redirect from non-secure page to secure page\n");
4143 /* FIXME: notify about redirect to secure page */
4144 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4147 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT;
4150 heap_free(session->hostName);
4152 session->hostName = heap_strndupW(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4153 session->hostPort = urlComponents.nPort;
4155 heap_free(session->userName);
4156 session->userName = NULL;
4157 if (urlComponents.dwUserNameLength)
4158 session->userName = heap_strndupW(urlComponents.lpszUserName, urlComponents.dwUserNameLength);
4160 reset_data_stream(request);
4162 host = substr(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4164 if(host.len != strlenW(request->server->name) || strncmpiW(request->server->name, host.str, host.len)
4165 || request->server->port != urlComponents.nPort) {
4166 server_t *new_server;
4168 new_server = get_server(host, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4169 server_release(request->server);
4170 request->server = new_server;
4173 if (custom_port)
4174 HTTP_ProcessHeader(request, hostW, request->server->host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4175 else
4176 HTTP_ProcessHeader(request, hostW, request->server->name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4178 path = heap_strndupW(urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength);
4180 heap_free(request->path);
4181 request->path = NULL;
4182 if (*path)
4184 DWORD needed = 0;
4185 HRESULT rc;
4187 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4188 if (rc == E_POINTER)
4189 needed = strlenW(path)+1;
4190 request->path = heap_alloc(needed*sizeof(WCHAR));
4191 rc = UrlEscapeW(path, request->path, &needed,
4192 URL_ESCAPE_SPACES_ONLY);
4193 if (rc != S_OK)
4195 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4196 strcpyW(request->path, path);
4200 heap_free(path);
4202 /* Remove custom content-type/length headers on redirects. */
4203 remove_header(request, szContent_Type, TRUE);
4204 remove_header(request, szContent_Length, TRUE);
4206 return ERROR_SUCCESS;
4209 /***********************************************************************
4210 * HTTP_build_req (internal)
4212 * concatenate all the strings in the request together
4214 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4216 LPCWSTR *t;
4217 LPWSTR str;
4219 for( t = list; *t ; t++ )
4220 len += strlenW( *t );
4221 len++;
4223 str = heap_alloc(len*sizeof(WCHAR));
4224 *str = 0;
4226 for( t = list; *t ; t++ )
4227 strcatW( str, *t );
4229 return str;
4232 static void HTTP_InsertCookies(http_request_t *request)
4234 WCHAR *cookies;
4235 DWORD res;
4237 res = get_cookie_header(request->server->name, request->path, &cookies);
4238 if(res != ERROR_SUCCESS || !cookies)
4239 return;
4241 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies),
4242 HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
4243 heap_free(cookies);
4246 static WORD HTTP_ParseWkday(LPCWSTR day)
4248 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4249 { 'm','o','n',0 },
4250 { 't','u','e',0 },
4251 { 'w','e','d',0 },
4252 { 't','h','u',0 },
4253 { 'f','r','i',0 },
4254 { 's','a','t',0 }};
4255 unsigned int i;
4256 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4257 if (!strcmpiW(day, days[i]))
4258 return i;
4260 /* Invalid */
4261 return 7;
4264 static WORD HTTP_ParseMonth(LPCWSTR month)
4266 static const WCHAR jan[] = { 'j','a','n',0 };
4267 static const WCHAR feb[] = { 'f','e','b',0 };
4268 static const WCHAR mar[] = { 'm','a','r',0 };
4269 static const WCHAR apr[] = { 'a','p','r',0 };
4270 static const WCHAR may[] = { 'm','a','y',0 };
4271 static const WCHAR jun[] = { 'j','u','n',0 };
4272 static const WCHAR jul[] = { 'j','u','l',0 };
4273 static const WCHAR aug[] = { 'a','u','g',0 };
4274 static const WCHAR sep[] = { 's','e','p',0 };
4275 static const WCHAR oct[] = { 'o','c','t',0 };
4276 static const WCHAR nov[] = { 'n','o','v',0 };
4277 static const WCHAR dec[] = { 'd','e','c',0 };
4279 if (!strcmpiW(month, jan)) return 1;
4280 if (!strcmpiW(month, feb)) return 2;
4281 if (!strcmpiW(month, mar)) return 3;
4282 if (!strcmpiW(month, apr)) return 4;
4283 if (!strcmpiW(month, may)) return 5;
4284 if (!strcmpiW(month, jun)) return 6;
4285 if (!strcmpiW(month, jul)) return 7;
4286 if (!strcmpiW(month, aug)) return 8;
4287 if (!strcmpiW(month, sep)) return 9;
4288 if (!strcmpiW(month, oct)) return 10;
4289 if (!strcmpiW(month, nov)) return 11;
4290 if (!strcmpiW(month, dec)) return 12;
4291 /* Invalid */
4292 return 0;
4295 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4296 * optionally preceded by whitespace.
4297 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4298 * st, and sets *str to the first character after the time format.
4300 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4302 LPCWSTR ptr = *str;
4303 WCHAR *nextPtr;
4304 unsigned long num;
4306 while (isspaceW(*ptr))
4307 ptr++;
4309 num = strtoulW(ptr, &nextPtr, 10);
4310 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4312 ERR("unexpected time format %s\n", debugstr_w(ptr));
4313 return FALSE;
4315 if (num > 23)
4317 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4318 return FALSE;
4320 ptr = nextPtr + 1;
4321 st->wHour = (WORD)num;
4322 num = strtoulW(ptr, &nextPtr, 10);
4323 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4325 ERR("unexpected time format %s\n", debugstr_w(ptr));
4326 return FALSE;
4328 if (num > 59)
4330 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4331 return FALSE;
4333 ptr = nextPtr + 1;
4334 st->wMinute = (WORD)num;
4335 num = strtoulW(ptr, &nextPtr, 10);
4336 if (!nextPtr || nextPtr <= ptr)
4338 ERR("unexpected time format %s\n", debugstr_w(ptr));
4339 return FALSE;
4341 if (num > 59)
4343 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4344 return FALSE;
4346 ptr = nextPtr + 1;
4347 *str = ptr;
4348 st->wSecond = (WORD)num;
4349 return TRUE;
4352 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4354 static const WCHAR gmt[]= { 'G','M','T',0 };
4355 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4356 LPCWSTR ptr;
4357 SYSTEMTIME st = { 0 };
4358 unsigned long num;
4360 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4361 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4362 *dayPtr = *ptr;
4363 *dayPtr = 0;
4364 st.wDayOfWeek = HTTP_ParseWkday(day);
4365 if (st.wDayOfWeek >= 7)
4367 ERR("unexpected weekday %s\n", debugstr_w(day));
4368 return FALSE;
4371 while (isspaceW(*ptr))
4372 ptr++;
4374 for (monthPtr = month; !isspace(*ptr) &&
4375 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4376 monthPtr++, ptr++)
4377 *monthPtr = *ptr;
4378 *monthPtr = 0;
4379 st.wMonth = HTTP_ParseMonth(month);
4380 if (!st.wMonth || st.wMonth > 12)
4382 ERR("unexpected month %s\n", debugstr_w(month));
4383 return FALSE;
4386 while (isspaceW(*ptr))
4387 ptr++;
4389 num = strtoulW(ptr, &nextPtr, 10);
4390 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4392 ERR("unexpected day %s\n", debugstr_w(ptr));
4393 return FALSE;
4395 ptr = nextPtr;
4396 st.wDay = (WORD)num;
4398 while (isspaceW(*ptr))
4399 ptr++;
4401 if (!HTTP_ParseTime(&st, &ptr))
4402 return FALSE;
4404 while (isspaceW(*ptr))
4405 ptr++;
4407 num = strtoulW(ptr, &nextPtr, 10);
4408 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4410 ERR("unexpected year %s\n", debugstr_w(ptr));
4411 return FALSE;
4413 ptr = nextPtr;
4414 st.wYear = (WORD)num;
4416 while (isspaceW(*ptr))
4417 ptr++;
4419 /* asctime() doesn't report a timezone, but some web servers do, so accept
4420 * with or without GMT.
4422 if (*ptr && strcmpW(ptr, gmt))
4424 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4425 return FALSE;
4427 return SystemTimeToFileTime(&st, ft);
4430 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4432 static const WCHAR gmt[]= { 'G','M','T',0 };
4433 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4434 LPCWSTR ptr;
4435 unsigned long num;
4436 SYSTEMTIME st = { 0 };
4438 ptr = strchrW(value, ',');
4439 if (!ptr)
4440 return FALSE;
4441 if (ptr - value != 3)
4443 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4444 return FALSE;
4446 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4447 day[3] = 0;
4448 st.wDayOfWeek = HTTP_ParseWkday(day);
4449 if (st.wDayOfWeek > 6)
4451 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4452 return FALSE;
4454 ptr++;
4456 while (isspaceW(*ptr))
4457 ptr++;
4459 num = strtoulW(ptr, &nextPtr, 10);
4460 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4462 WARN("unexpected day %s\n", debugstr_w(value));
4463 return FALSE;
4465 ptr = nextPtr;
4466 st.wDay = (WORD)num;
4468 while (isspaceW(*ptr))
4469 ptr++;
4471 for (monthPtr = month; !isspace(*ptr) &&
4472 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4473 monthPtr++, ptr++)
4474 *monthPtr = *ptr;
4475 *monthPtr = 0;
4476 st.wMonth = HTTP_ParseMonth(month);
4477 if (!st.wMonth || st.wMonth > 12)
4479 WARN("unexpected month %s\n", debugstr_w(month));
4480 return FALSE;
4483 while (isspaceW(*ptr))
4484 ptr++;
4486 num = strtoulW(ptr, &nextPtr, 10);
4487 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4489 ERR("unexpected year %s\n", debugstr_w(value));
4490 return FALSE;
4492 ptr = nextPtr;
4493 st.wYear = (WORD)num;
4495 if (!HTTP_ParseTime(&st, &ptr))
4496 return FALSE;
4498 while (isspaceW(*ptr))
4499 ptr++;
4501 if (strcmpW(ptr, gmt))
4503 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4504 return FALSE;
4506 return SystemTimeToFileTime(&st, ft);
4509 static WORD HTTP_ParseWeekday(LPCWSTR day)
4511 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4512 { 'm','o','n','d','a','y',0 },
4513 { 't','u','e','s','d','a','y',0 },
4514 { 'w','e','d','n','e','s','d','a','y',0 },
4515 { 't','h','u','r','s','d','a','y',0 },
4516 { 'f','r','i','d','a','y',0 },
4517 { 's','a','t','u','r','d','a','y',0 }};
4518 unsigned int i;
4519 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4520 if (!strcmpiW(day, days[i]))
4521 return i;
4523 /* Invalid */
4524 return 7;
4527 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4529 static const WCHAR gmt[]= { 'G','M','T',0 };
4530 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4531 LPCWSTR ptr;
4532 unsigned long num;
4533 SYSTEMTIME st = { 0 };
4535 ptr = strchrW(value, ',');
4536 if (!ptr)
4537 return FALSE;
4538 if (ptr - value == 3)
4540 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4541 day[3] = 0;
4542 st.wDayOfWeek = HTTP_ParseWkday(day);
4543 if (st.wDayOfWeek > 6)
4545 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4546 return FALSE;
4549 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4551 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4552 day[ptr - value + 1] = 0;
4553 st.wDayOfWeek = HTTP_ParseWeekday(day);
4554 if (st.wDayOfWeek > 6)
4556 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4557 return FALSE;
4560 else
4562 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4563 return FALSE;
4565 ptr++;
4567 while (isspaceW(*ptr))
4568 ptr++;
4570 num = strtoulW(ptr, &nextPtr, 10);
4571 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4573 ERR("unexpected day %s\n", debugstr_w(value));
4574 return FALSE;
4576 ptr = nextPtr;
4577 st.wDay = (WORD)num;
4579 if (*ptr != '-')
4581 ERR("unexpected month format %s\n", debugstr_w(ptr));
4582 return FALSE;
4584 ptr++;
4586 for (monthPtr = month; *ptr != '-' &&
4587 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4588 monthPtr++, ptr++)
4589 *monthPtr = *ptr;
4590 *monthPtr = 0;
4591 st.wMonth = HTTP_ParseMonth(month);
4592 if (!st.wMonth || st.wMonth > 12)
4594 ERR("unexpected month %s\n", debugstr_w(month));
4595 return FALSE;
4598 if (*ptr != '-')
4600 ERR("unexpected year format %s\n", debugstr_w(ptr));
4601 return FALSE;
4603 ptr++;
4605 num = strtoulW(ptr, &nextPtr, 10);
4606 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4608 ERR("unexpected year %s\n", debugstr_w(value));
4609 return FALSE;
4611 ptr = nextPtr;
4612 st.wYear = (WORD)num;
4614 if (!HTTP_ParseTime(&st, &ptr))
4615 return FALSE;
4617 while (isspaceW(*ptr))
4618 ptr++;
4620 if (strcmpW(ptr, gmt))
4622 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4623 return FALSE;
4625 return SystemTimeToFileTime(&st, ft);
4628 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4630 static const WCHAR zero[] = { '0',0 };
4631 BOOL ret;
4633 if (!strcmpW(value, zero))
4635 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4636 ret = TRUE;
4638 else if (strchrW(value, ','))
4640 ret = HTTP_ParseRfc1123Date(value, ft);
4641 if (!ret)
4643 ret = HTTP_ParseRfc850Date(value, ft);
4644 if (!ret)
4645 ERR("unexpected date format %s\n", debugstr_w(value));
4648 else
4650 ret = HTTP_ParseDateAsAsctime(value, ft);
4651 if (!ret)
4652 ERR("unexpected date format %s\n", debugstr_w(value));
4654 return ret;
4657 static void HTTP_ProcessExpires(http_request_t *request)
4659 BOOL expirationFound = FALSE;
4660 int headerIndex;
4662 EnterCriticalSection( &request->headers_section );
4664 /* Look for a Cache-Control header with a max-age directive, as it takes
4665 * precedence over the Expires header.
4667 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4668 if (headerIndex != -1)
4670 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4671 LPWSTR ptr;
4673 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4675 LPWSTR comma = strchrW(ptr, ','), end, equal;
4677 if (comma)
4678 end = comma;
4679 else
4680 end = ptr + strlenW(ptr);
4681 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4683 if (*equal == '=')
4685 static const WCHAR max_age[] = {
4686 'm','a','x','-','a','g','e',0 };
4688 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4690 LPWSTR nextPtr;
4691 unsigned long age;
4693 age = strtoulW(equal + 1, &nextPtr, 10);
4694 if (nextPtr > equal + 1)
4696 LARGE_INTEGER ft;
4698 NtQuerySystemTime( &ft );
4699 /* Age is in seconds, FILETIME resolution is in
4700 * 100 nanosecond intervals.
4702 ft.QuadPart += age * (ULONGLONG)1000000;
4703 request->expires.dwLowDateTime = ft.u.LowPart;
4704 request->expires.dwHighDateTime = ft.u.HighPart;
4705 expirationFound = TRUE;
4709 if (comma)
4711 ptr = comma + 1;
4712 while (isspaceW(*ptr))
4713 ptr++;
4715 else
4716 ptr = NULL;
4719 if (!expirationFound)
4721 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4722 if (headerIndex != -1)
4724 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4725 FILETIME ft;
4727 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4729 expirationFound = TRUE;
4730 request->expires = ft;
4734 if (!expirationFound)
4736 LARGE_INTEGER t;
4738 /* With no known age, default to 10 minutes until expiration. */
4739 NtQuerySystemTime( &t );
4740 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4741 request->expires.dwLowDateTime = t.u.LowPart;
4742 request->expires.dwHighDateTime = t.u.HighPart;
4745 LeaveCriticalSection( &request->headers_section );
4748 static void HTTP_ProcessLastModified(http_request_t *request)
4750 int headerIndex;
4752 EnterCriticalSection( &request->headers_section );
4754 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4755 if (headerIndex != -1)
4757 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4758 FILETIME ft;
4760 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4761 request->last_modified = ft;
4764 LeaveCriticalSection( &request->headers_section );
4767 static void http_process_keep_alive(http_request_t *req)
4769 int index;
4771 EnterCriticalSection( &req->headers_section );
4773 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4774 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4775 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4776 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4777 else
4778 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4780 LeaveCriticalSection( &req->headers_section );
4783 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4785 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4786 netconn_t *netconn = NULL;
4787 DWORD res;
4789 reset_data_stream(request);
4791 if (request->netconn)
4793 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4795 *reusing = TRUE;
4796 return ERROR_SUCCESS;
4798 else
4800 free_netconn(request->netconn);
4801 request->netconn = NULL;
4805 res = HTTP_ResolveName(request);
4806 if(res != ERROR_SUCCESS)
4807 return res;
4809 EnterCriticalSection(&connection_pool_cs);
4811 while(!list_empty(&request->server->conn_pool)) {
4812 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4813 list_remove(&netconn->pool_entry);
4815 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4816 break;
4818 TRACE("connection %p closed during idle\n", netconn);
4819 free_netconn(netconn);
4820 netconn = NULL;
4823 LeaveCriticalSection(&connection_pool_cs);
4825 if(netconn) {
4826 TRACE("<-- reusing %p netconn\n", netconn);
4827 request->netconn = netconn;
4828 *reusing = TRUE;
4829 return ERROR_SUCCESS;
4832 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4833 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4835 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4836 INTERNET_STATUS_CONNECTING_TO_SERVER,
4837 request->server->addr_str,
4838 strlen(request->server->addr_str)+1);
4840 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4841 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4842 request->connect_timeout, &netconn);
4843 if(res != ERROR_SUCCESS) {
4844 ERR("create_netconn failed: %u\n", res);
4845 return res;
4848 request->netconn = netconn;
4850 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4851 INTERNET_STATUS_CONNECTED_TO_SERVER,
4852 request->server->addr_str, strlen(request->server->addr_str)+1);
4854 *reusing = FALSE;
4855 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4856 return ERROR_SUCCESS;
4859 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4861 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4862 char *ret;
4864 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4865 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4866 if (data_len) memcpy( ret + len - 1, data, data_len );
4867 *out_len = len + data_len - 1;
4868 ret[*out_len] = 0;
4869 return ret;
4872 static void set_content_length_header( http_request_t *request, DWORD len, DWORD flags )
4874 static const WCHAR fmtW[] =
4875 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4876 WCHAR buf[sizeof(fmtW)/sizeof(fmtW[0]) + 10];
4878 sprintfW( buf, fmtW, len );
4879 HTTP_HttpAddRequestHeadersW( request, buf, ~0u, flags );
4882 /***********************************************************************
4883 * HTTP_HttpSendRequestW (internal)
4885 * Sends the specified request to the HTTP server
4887 * RETURNS
4888 * ERROR_SUCCESS on success
4889 * win32 error code on failure
4892 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4893 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4894 DWORD dwContentLength, BOOL bEndRequest)
4896 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4897 LPWSTR requestString = NULL;
4898 INT responseLen, cnt;
4899 DWORD res;
4901 TRACE("--> %p\n", request);
4903 assert(request->hdr.htype == WH_HHTTPREQ);
4905 /* if the verb is NULL default to GET */
4906 if (!request->verb)
4907 request->verb = heap_strdupW(szGET);
4909 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port,
4910 HTTP_ADDREQ_FLAG_ADD_IF_NEW | HTTP_ADDHDR_FLAG_REQ);
4912 if (dwContentLength || strcmpW(request->verb, szGET))
4914 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4915 request->bytesToWrite = dwContentLength;
4917 if (request->session->appInfo->agent)
4919 WCHAR *agent_header;
4920 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4921 int len;
4923 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4924 agent_header = heap_alloc(len * sizeof(WCHAR));
4925 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4927 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4928 heap_free(agent_header);
4930 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4932 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4933 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4935 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4937 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4938 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4939 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4942 /* add the headers the caller supplied */
4943 if( lpszHeaders && dwHeaderLength )
4944 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4948 DWORD len, data_len = dwOptionalLength;
4949 BOOL reusing_connection;
4950 char *ascii_req;
4952 loop_next = FALSE;
4954 if(redirected) {
4955 request->contentLength = ~0u;
4956 request->bytesToWrite = 0;
4959 if (TRACE_ON(wininet))
4961 HTTPHEADERW *host;
4963 EnterCriticalSection( &request->headers_section );
4964 host = HTTP_GetHeader( request, hostW );
4965 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
4966 LeaveCriticalSection( &request->headers_section );
4969 HTTP_FixURL(request);
4970 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4972 HTTP_ProcessHeader(request, szConnection, szKeepAlive,
4973 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
4975 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4976 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4978 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4979 HTTP_InsertCookies(request);
4981 res = open_http_connection(request, &reusing_connection);
4982 if (res != ERROR_SUCCESS)
4983 break;
4985 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4987 if (request->proxy) secure_proxy_connect = TRUE;
4988 else
4990 res = NETCON_secure_connect(request->netconn, request->server);
4991 if (res != ERROR_SUCCESS)
4993 WARN("failed to upgrade to secure connection\n");
4994 http_release_netconn(request, FALSE);
4995 break;
4999 if (secure_proxy_connect)
5001 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
5002 const WCHAR *target = request->server->host_port;
5004 if (HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
5005 set_content_length_header(request, 0, HTTP_ADDREQ_FLAG_REPLACE);
5007 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
5009 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
5011 WCHAR *url = build_proxy_path_url(request);
5012 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
5013 heap_free(url);
5015 else
5017 if (request->proxy && HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
5018 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_REPLACE);
5020 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
5023 TRACE("Request header -> %s\n", debugstr_w(requestString) );
5025 /* send the request as ASCII, tack on the optional data */
5026 if (!lpOptional || redirected || secure_proxy_connect)
5027 data_len = 0;
5029 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
5030 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
5032 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5033 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
5035 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
5036 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
5037 heap_free( ascii_req );
5038 if(res != ERROR_SUCCESS) {
5039 TRACE("send failed: %u\n", res);
5040 if(!reusing_connection)
5041 break;
5042 http_release_netconn(request, FALSE);
5043 loop_next = TRUE;
5044 continue;
5047 request->bytesWritten = data_len;
5049 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5050 INTERNET_STATUS_REQUEST_SENT,
5051 &len, sizeof(DWORD));
5053 if (bEndRequest)
5055 DWORD dwBufferSize;
5057 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5058 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5060 if (HTTP_GetResponseHeaders(request, &responseLen))
5062 http_release_netconn(request, FALSE);
5063 res = ERROR_INTERNET_CONNECTION_ABORTED;
5064 goto lend;
5066 /* FIXME: We should know that connection is closed before sending
5067 * headers. Otherwise wrong callbacks are executed */
5068 if(!responseLen && reusing_connection) {
5069 TRACE("Connection closed by server, reconnecting\n");
5070 http_release_netconn(request, FALSE);
5071 loop_next = TRUE;
5072 continue;
5075 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5076 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5077 sizeof(DWORD));
5079 http_process_keep_alive(request);
5080 HTTP_ProcessCookies(request);
5081 HTTP_ProcessExpires(request);
5082 HTTP_ProcessLastModified(request);
5084 res = set_content_length(request);
5085 if(res != ERROR_SUCCESS)
5086 goto lend;
5087 if(!request->contentLength)
5088 http_release_netconn(request, TRUE);
5090 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5092 WCHAR *new_url;
5094 switch(request->status_code) {
5095 case HTTP_STATUS_REDIRECT:
5096 case HTTP_STATUS_MOVED:
5097 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5098 case HTTP_STATUS_REDIRECT_METHOD:
5099 new_url = get_redirect_url(request);
5100 if(!new_url)
5101 break;
5103 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5104 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5106 heap_free(request->verb);
5107 request->verb = heap_strdupW(szGET);
5109 http_release_netconn(request, drain_content(request, FALSE));
5110 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5111 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5112 res = HTTP_HandleRedirect(request, new_url);
5113 heap_free(new_url);
5114 if (res == ERROR_SUCCESS) {
5115 heap_free(requestString);
5116 loop_next = TRUE;
5118 redirected = TRUE;
5121 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5123 WCHAR szAuthValue[2048];
5124 dwBufferSize=2048;
5125 if (request->status_code == HTTP_STATUS_DENIED)
5127 WCHAR *host = heap_strdupW( request->server->canon_host_port );
5128 DWORD dwIndex = 0;
5129 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5131 if (HTTP_DoAuthorization(request, szAuthValue,
5132 &request->authInfo,
5133 request->session->userName,
5134 request->session->password, host))
5136 heap_free(requestString);
5137 if(!drain_content(request, TRUE)) {
5138 FIXME("Could not drain content\n");
5139 http_release_netconn(request, FALSE);
5141 loop_next = TRUE;
5142 break;
5145 heap_free( host );
5147 if(!loop_next) {
5148 TRACE("Cleaning wrong authorization data\n");
5149 destroy_authinfo(request->authInfo);
5150 request->authInfo = NULL;
5153 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5155 DWORD dwIndex = 0;
5156 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5158 if (HTTP_DoAuthorization(request, szAuthValue,
5159 &request->proxyAuthInfo,
5160 request->session->appInfo->proxyUsername,
5161 request->session->appInfo->proxyPassword,
5162 NULL))
5164 heap_free(requestString);
5165 if(!drain_content(request, TRUE)) {
5166 FIXME("Could not drain content\n");
5167 http_release_netconn(request, FALSE);
5169 loop_next = TRUE;
5170 break;
5174 if(!loop_next) {
5175 TRACE("Cleaning wrong proxy authorization data\n");
5176 destroy_authinfo(request->proxyAuthInfo);
5177 request->proxyAuthInfo = NULL;
5181 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5183 res = NETCON_secure_connect(request->netconn, request->server);
5184 if (res != ERROR_SUCCESS)
5186 WARN("failed to upgrade to secure proxy connection\n");
5187 http_release_netconn( request, FALSE );
5188 break;
5190 remove_header(request, szProxy_Authorization, TRUE);
5191 destroy_authinfo(request->proxyAuthInfo);
5192 request->proxyAuthInfo = NULL;
5194 secure_proxy_connect = FALSE;
5195 loop_next = TRUE;
5198 else
5199 res = ERROR_SUCCESS;
5201 while (loop_next);
5203 lend:
5204 heap_free(requestString);
5206 /* TODO: send notification for P3P header */
5208 if(res == ERROR_SUCCESS)
5209 create_cache_entry(request);
5211 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5213 if (res == ERROR_SUCCESS) {
5214 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5215 HTTP_ReceiveRequestData(request, TRUE, NULL);
5216 else
5217 send_request_complete(request,
5218 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5219 }else {
5220 send_request_complete(request, 0, res);
5224 TRACE("<--\n");
5225 return res;
5228 typedef struct {
5229 task_header_t hdr;
5230 WCHAR *headers;
5231 DWORD headers_len;
5232 void *optional;
5233 DWORD optional_len;
5234 DWORD content_len;
5235 BOOL end_request;
5236 } send_request_task_t;
5238 /***********************************************************************
5240 * Helper functions for the HttpSendRequest(Ex) functions
5243 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5245 send_request_task_t *task = (send_request_task_t*)hdr;
5246 http_request_t *request = (http_request_t*)task->hdr.hdr;
5248 TRACE("%p\n", request);
5250 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5251 task->optional_len, task->content_len, task->end_request);
5253 heap_free(task->headers);
5257 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5259 INT responseLen;
5260 DWORD res = ERROR_SUCCESS;
5262 if(!is_valid_netconn(request->netconn)) {
5263 WARN("Not connected\n");
5264 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5265 return ERROR_INTERNET_OPERATION_CANCELLED;
5268 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5269 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5271 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5272 res = ERROR_HTTP_HEADER_NOT_FOUND;
5274 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5275 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5277 /* process cookies here. Is this right? */
5278 http_process_keep_alive(request);
5279 HTTP_ProcessCookies(request);
5280 HTTP_ProcessExpires(request);
5281 HTTP_ProcessLastModified(request);
5283 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5284 if(!request->contentLength)
5285 http_release_netconn(request, TRUE);
5288 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5290 switch(request->status_code) {
5291 case HTTP_STATUS_REDIRECT:
5292 case HTTP_STATUS_MOVED:
5293 case HTTP_STATUS_REDIRECT_METHOD:
5294 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5295 WCHAR *new_url;
5297 new_url = get_redirect_url(request);
5298 if(!new_url)
5299 break;
5301 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5302 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5304 heap_free(request->verb);
5305 request->verb = heap_strdupW(szGET);
5307 http_release_netconn(request, drain_content(request, FALSE));
5308 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5309 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5310 res = HTTP_HandleRedirect(request, new_url);
5311 heap_free(new_url);
5312 if (res == ERROR_SUCCESS)
5313 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5318 if(res == ERROR_SUCCESS)
5319 create_cache_entry(request);
5321 if (res == ERROR_SUCCESS && request->contentLength)
5322 HTTP_ReceiveRequestData(request, TRUE, NULL);
5323 else
5324 send_request_complete(request, res == ERROR_SUCCESS, res);
5326 return res;
5329 /***********************************************************************
5330 * HttpEndRequestA (WININET.@)
5332 * Ends an HTTP request that was started by HttpSendRequestEx
5334 * RETURNS
5335 * TRUE if successful
5336 * FALSE on failure
5339 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5340 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5342 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5344 if (lpBuffersOut)
5346 SetLastError(ERROR_INVALID_PARAMETER);
5347 return FALSE;
5350 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5353 typedef struct {
5354 task_header_t hdr;
5355 DWORD flags;
5356 DWORD context;
5357 } end_request_task_t;
5359 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5361 end_request_task_t *task = (end_request_task_t*)hdr;
5362 http_request_t *req = (http_request_t*)task->hdr.hdr;
5364 TRACE("%p\n", req);
5366 HTTP_HttpEndRequestW(req, task->flags, task->context);
5369 /***********************************************************************
5370 * HttpEndRequestW (WININET.@)
5372 * Ends an HTTP request that was started by HttpSendRequestEx
5374 * RETURNS
5375 * TRUE if successful
5376 * FALSE on failure
5379 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5380 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5382 http_request_t *request;
5383 DWORD res;
5385 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5387 if (lpBuffersOut)
5389 SetLastError(ERROR_INVALID_PARAMETER);
5390 return FALSE;
5393 request = (http_request_t*) get_handle_object( hRequest );
5395 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5397 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5398 if (request)
5399 WININET_Release( &request->hdr );
5400 return FALSE;
5402 request->hdr.dwFlags |= dwFlags;
5404 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5406 end_request_task_t *task;
5408 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5409 task->flags = dwFlags;
5410 task->context = dwContext;
5412 INTERNET_AsyncCall(&task->hdr);
5413 res = ERROR_IO_PENDING;
5415 else
5416 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5418 WININET_Release( &request->hdr );
5419 TRACE("%u <--\n", res);
5420 if(res != ERROR_SUCCESS)
5421 SetLastError(res);
5422 return res == ERROR_SUCCESS;
5425 /***********************************************************************
5426 * HttpSendRequestExA (WININET.@)
5428 * Sends the specified request to the HTTP server and allows chunked
5429 * transfers.
5431 * RETURNS
5432 * Success: TRUE
5433 * Failure: FALSE, call GetLastError() for more information.
5435 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5436 LPINTERNET_BUFFERSA lpBuffersIn,
5437 LPINTERNET_BUFFERSA lpBuffersOut,
5438 DWORD dwFlags, DWORD_PTR dwContext)
5440 INTERNET_BUFFERSW BuffersInW;
5441 BOOL rc = FALSE;
5442 DWORD headerlen;
5443 LPWSTR header = NULL;
5445 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5446 lpBuffersOut, dwFlags, dwContext);
5448 if (lpBuffersIn)
5450 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5451 if (lpBuffersIn->lpcszHeader)
5453 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5454 lpBuffersIn->dwHeadersLength,0,0);
5455 header = heap_alloc(headerlen*sizeof(WCHAR));
5456 if (!(BuffersInW.lpcszHeader = header))
5458 SetLastError(ERROR_OUTOFMEMORY);
5459 return FALSE;
5461 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5462 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5463 header, headerlen);
5465 else
5466 BuffersInW.lpcszHeader = NULL;
5467 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5468 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5469 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5470 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5471 BuffersInW.Next = NULL;
5474 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5476 heap_free(header);
5477 return rc;
5480 /***********************************************************************
5481 * HttpSendRequestExW (WININET.@)
5483 * Sends the specified request to the HTTP server and allows chunked
5484 * transfers
5486 * RETURNS
5487 * Success: TRUE
5488 * Failure: FALSE, call GetLastError() for more information.
5490 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5491 LPINTERNET_BUFFERSW lpBuffersIn,
5492 LPINTERNET_BUFFERSW lpBuffersOut,
5493 DWORD dwFlags, DWORD_PTR dwContext)
5495 http_request_t *request;
5496 http_session_t *session;
5497 appinfo_t *hIC;
5498 DWORD res;
5500 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5501 lpBuffersOut, dwFlags, dwContext);
5503 request = (http_request_t*) get_handle_object( hRequest );
5505 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5507 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5508 goto lend;
5511 session = request->session;
5512 assert(session->hdr.htype == WH_HHTTPSESSION);
5513 hIC = session->appInfo;
5514 assert(hIC->hdr.htype == WH_HINIT);
5516 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5518 send_request_task_t *task;
5520 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5521 if (lpBuffersIn)
5523 DWORD size = 0;
5525 if (lpBuffersIn->lpcszHeader)
5527 if (lpBuffersIn->dwHeadersLength == ~0u)
5528 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5529 else
5530 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5532 task->headers = heap_alloc(size);
5533 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5535 else task->headers = NULL;
5537 task->headers_len = size / sizeof(WCHAR);
5538 task->optional = lpBuffersIn->lpvBuffer;
5539 task->optional_len = lpBuffersIn->dwBufferLength;
5540 task->content_len = lpBuffersIn->dwBufferTotal;
5542 else
5544 task->headers = NULL;
5545 task->headers_len = 0;
5546 task->optional = NULL;
5547 task->optional_len = 0;
5548 task->content_len = 0;
5551 task->end_request = FALSE;
5553 INTERNET_AsyncCall(&task->hdr);
5554 res = ERROR_IO_PENDING;
5556 else
5558 if (lpBuffersIn)
5559 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5560 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5561 lpBuffersIn->dwBufferTotal, FALSE);
5562 else
5563 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5566 lend:
5567 if ( request )
5568 WININET_Release( &request->hdr );
5570 TRACE("<---\n");
5571 SetLastError(res);
5572 return res == ERROR_SUCCESS;
5575 /***********************************************************************
5576 * HttpSendRequestW (WININET.@)
5578 * Sends the specified request to the HTTP server
5580 * RETURNS
5581 * TRUE on success
5582 * FALSE on failure
5585 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5586 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5588 http_request_t *request;
5589 http_session_t *session = NULL;
5590 appinfo_t *hIC = NULL;
5591 DWORD res = ERROR_SUCCESS;
5593 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5594 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5596 request = (http_request_t*) get_handle_object( hHttpRequest );
5597 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5599 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5600 goto lend;
5603 session = request->session;
5604 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5606 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5607 goto lend;
5610 hIC = session->appInfo;
5611 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5613 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5614 goto lend;
5617 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5619 send_request_task_t *task;
5621 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5622 if (lpszHeaders)
5624 DWORD size;
5626 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5627 else size = dwHeaderLength * sizeof(WCHAR);
5629 task->headers = heap_alloc(size);
5630 memcpy(task->headers, lpszHeaders, size);
5632 else
5633 task->headers = NULL;
5634 task->headers_len = dwHeaderLength;
5635 task->optional = lpOptional;
5636 task->optional_len = dwOptionalLength;
5637 task->content_len = dwOptionalLength;
5638 task->end_request = TRUE;
5640 INTERNET_AsyncCall(&task->hdr);
5641 res = ERROR_IO_PENDING;
5643 else
5645 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5646 dwHeaderLength, lpOptional, dwOptionalLength,
5647 dwOptionalLength, TRUE);
5649 lend:
5650 if( request )
5651 WININET_Release( &request->hdr );
5653 SetLastError(res);
5654 return res == ERROR_SUCCESS;
5657 /***********************************************************************
5658 * HttpSendRequestA (WININET.@)
5660 * Sends the specified request to the HTTP server
5662 * RETURNS
5663 * TRUE on success
5664 * FALSE on failure
5667 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5668 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5670 BOOL result;
5671 LPWSTR szHeaders=NULL;
5672 DWORD nLen=dwHeaderLength;
5673 if(lpszHeaders!=NULL)
5675 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5676 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5677 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5679 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5680 heap_free(szHeaders);
5681 return result;
5684 /***********************************************************************
5685 * HTTPSESSION_Destroy (internal)
5687 * Deallocate session handle
5690 static void HTTPSESSION_Destroy(object_header_t *hdr)
5692 http_session_t *session = (http_session_t*) hdr;
5694 TRACE("%p\n", session);
5696 WININET_Release(&session->appInfo->hdr);
5698 heap_free(session->hostName);
5699 heap_free(session->password);
5700 heap_free(session->userName);
5703 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5705 http_session_t *ses = (http_session_t *)hdr;
5707 switch(option) {
5708 case INTERNET_OPTION_HANDLE_TYPE:
5709 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5711 if (*size < sizeof(ULONG))
5712 return ERROR_INSUFFICIENT_BUFFER;
5714 *size = sizeof(DWORD);
5715 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5716 return ERROR_SUCCESS;
5717 case INTERNET_OPTION_CONNECT_TIMEOUT:
5718 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5720 if (*size < sizeof(DWORD))
5721 return ERROR_INSUFFICIENT_BUFFER;
5723 *size = sizeof(DWORD);
5724 *(DWORD *)buffer = ses->connect_timeout;
5725 return ERROR_SUCCESS;
5727 case INTERNET_OPTION_SEND_TIMEOUT:
5728 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5730 if (*size < sizeof(DWORD))
5731 return ERROR_INSUFFICIENT_BUFFER;
5733 *size = sizeof(DWORD);
5734 *(DWORD *)buffer = ses->send_timeout;
5735 return ERROR_SUCCESS;
5737 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5738 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5740 if (*size < sizeof(DWORD))
5741 return ERROR_INSUFFICIENT_BUFFER;
5743 *size = sizeof(DWORD);
5744 *(DWORD *)buffer = ses->receive_timeout;
5745 return ERROR_SUCCESS;
5748 return INET_QueryOption(hdr, option, buffer, size, unicode);
5751 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5753 http_session_t *ses = (http_session_t*)hdr;
5755 switch(option) {
5756 case INTERNET_OPTION_USERNAME:
5758 heap_free(ses->userName);
5759 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5760 return ERROR_SUCCESS;
5762 case INTERNET_OPTION_PASSWORD:
5764 heap_free(ses->password);
5765 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5766 return ERROR_SUCCESS;
5768 case INTERNET_OPTION_PROXY_USERNAME:
5770 heap_free(ses->appInfo->proxyUsername);
5771 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5772 return ERROR_SUCCESS;
5774 case INTERNET_OPTION_PROXY_PASSWORD:
5776 heap_free(ses->appInfo->proxyPassword);
5777 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5778 return ERROR_SUCCESS;
5780 case INTERNET_OPTION_CONNECT_TIMEOUT:
5782 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5783 ses->connect_timeout = *(DWORD *)buffer;
5784 return ERROR_SUCCESS;
5786 case INTERNET_OPTION_SEND_TIMEOUT:
5788 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5789 ses->send_timeout = *(DWORD *)buffer;
5790 return ERROR_SUCCESS;
5792 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5794 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5795 ses->receive_timeout = *(DWORD *)buffer;
5796 return ERROR_SUCCESS;
5798 default: break;
5801 return INET_SetOption(hdr, option, buffer, size);
5804 static const object_vtbl_t HTTPSESSIONVtbl = {
5805 HTTPSESSION_Destroy,
5806 NULL,
5807 HTTPSESSION_QueryOption,
5808 HTTPSESSION_SetOption,
5809 NULL,
5810 NULL,
5811 NULL,
5812 NULL,
5813 NULL
5817 /***********************************************************************
5818 * HTTP_Connect (internal)
5820 * Create http session handle
5822 * RETURNS
5823 * HINTERNET a session handle on success
5824 * NULL on failure
5827 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5828 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5829 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5830 DWORD dwInternalFlags, HINTERNET *ret)
5832 http_session_t *session = NULL;
5834 TRACE("-->\n");
5836 if (!lpszServerName || !lpszServerName[0])
5837 return ERROR_INVALID_PARAMETER;
5839 assert( hIC->hdr.htype == WH_HINIT );
5841 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5842 if (!session)
5843 return ERROR_OUTOFMEMORY;
5846 * According to my tests. The name is not resolved until a request is sent
5849 session->hdr.htype = WH_HHTTPSESSION;
5850 session->hdr.dwFlags = dwFlags;
5851 session->hdr.dwContext = dwContext;
5852 session->hdr.dwInternalFlags |= dwInternalFlags;
5854 WININET_AddRef( &hIC->hdr );
5855 session->appInfo = hIC;
5856 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5858 session->hostName = heap_strdupW(lpszServerName);
5859 if (lpszUserName && lpszUserName[0])
5860 session->userName = heap_strdupW(lpszUserName);
5861 if (lpszPassword && lpszPassword[0])
5862 session->password = heap_strdupW(lpszPassword);
5863 session->hostPort = serverPort;
5864 session->connect_timeout = hIC->connect_timeout;
5865 session->send_timeout = 0;
5866 session->receive_timeout = 0;
5868 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5869 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5871 INTERNET_SendCallback(&hIC->hdr, dwContext,
5872 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5873 sizeof(HINTERNET));
5877 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5878 * windows
5881 TRACE("%p --> %p\n", hIC, session);
5883 *ret = session->hdr.hInternet;
5884 return ERROR_SUCCESS;
5887 /***********************************************************************
5888 * HTTP_clear_response_headers (internal)
5890 * clear out any old response headers
5892 static void HTTP_clear_response_headers( http_request_t *request )
5894 DWORD i;
5896 EnterCriticalSection( &request->headers_section );
5898 for( i=0; i<request->nCustHeaders; i++)
5900 if( !request->custHeaders[i].lpszField )
5901 continue;
5902 if( !request->custHeaders[i].lpszValue )
5903 continue;
5904 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5905 continue;
5906 HTTP_DeleteCustomHeader( request, i );
5907 i--;
5910 LeaveCriticalSection( &request->headers_section );
5913 /***********************************************************************
5914 * HTTP_GetResponseHeaders (internal)
5916 * Read server response
5918 * RETURNS
5920 * TRUE on success
5921 * FALSE on error
5923 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5925 INT cbreaks = 0;
5926 WCHAR buffer[MAX_REPLY_LEN];
5927 DWORD buflen = MAX_REPLY_LEN;
5928 INT rc = 0;
5929 char bufferA[MAX_REPLY_LEN];
5930 LPWSTR status_code = NULL, status_text = NULL;
5931 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5932 BOOL codeHundred = FALSE;
5934 TRACE("-->\n");
5936 if(!is_valid_netconn(request->netconn))
5937 goto lend;
5939 /* clear old response headers (eg. from a redirect response) */
5940 HTTP_clear_response_headers( request );
5942 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5943 do {
5945 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5947 buflen = MAX_REPLY_LEN;
5948 if ((res = read_line(request, bufferA, &buflen)))
5949 goto lend;
5951 if (!buflen) goto lend;
5953 rc += buflen;
5954 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5955 /* check is this a status code line? */
5956 if (!strncmpW(buffer, g_szHttp1_0, 4))
5958 /* split the version from the status code */
5959 status_code = strchrW( buffer, ' ' );
5960 if( !status_code )
5961 goto lend;
5962 *status_code++=0;
5964 /* split the status code from the status text */
5965 status_text = strchrW( status_code, ' ' );
5966 if( status_text )
5967 *status_text++=0;
5969 request->status_code = atoiW(status_code);
5971 TRACE("version [%s] status code [%s] status text [%s]\n",
5972 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5974 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5976 else if (!codeHundred)
5978 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5980 heap_free(request->version);
5981 heap_free(request->statusText);
5983 request->status_code = HTTP_STATUS_OK;
5984 request->version = heap_strdupW(g_szHttp1_0);
5985 request->statusText = heap_strdupW(szOK);
5987 goto lend;
5989 } while (codeHundred);
5991 /* Add status code */
5992 HTTP_ProcessHeader(request, szStatus, status_code,
5993 HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
5995 heap_free(request->version);
5996 heap_free(request->statusText);
5998 request->version = heap_strdupW(buffer);
5999 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
6001 /* Restore the spaces */
6002 *(status_code-1) = ' ';
6003 if (status_text)
6004 *(status_text-1) = ' ';
6006 /* Parse each response line */
6009 buflen = MAX_REPLY_LEN;
6010 if (!read_line(request, bufferA, &buflen) && buflen)
6012 LPWSTR * pFieldAndValue;
6014 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
6016 if (!bufferA[0]) break;
6017 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
6019 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
6020 if (pFieldAndValue)
6022 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
6023 HTTP_ADDREQ_FLAG_ADD );
6024 HTTP_FreeTokens(pFieldAndValue);
6027 else
6029 cbreaks++;
6030 if (cbreaks >= 2)
6031 break;
6033 }while(1);
6035 res = ERROR_SUCCESS;
6037 lend:
6039 *len = rc;
6040 TRACE("<--\n");
6041 return res;
6044 /***********************************************************************
6045 * HTTP_InterpretHttpHeader (internal)
6047 * Parse server response
6049 * RETURNS
6051 * Pointer to array of field, value, NULL on success.
6052 * NULL on error.
6054 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6056 LPWSTR * pTokenPair;
6057 LPWSTR pszColon;
6058 INT len;
6060 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6062 pszColon = strchrW(buffer, ':');
6063 /* must have two tokens */
6064 if (!pszColon)
6066 HTTP_FreeTokens(pTokenPair);
6067 if (buffer[0])
6068 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6069 return NULL;
6072 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6073 if (!pTokenPair[0])
6075 HTTP_FreeTokens(pTokenPair);
6076 return NULL;
6078 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6079 pTokenPair[0][pszColon - buffer] = '\0';
6081 /* skip colon */
6082 pszColon++;
6083 len = strlenW(pszColon);
6084 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6085 if (!pTokenPair[1])
6087 HTTP_FreeTokens(pTokenPair);
6088 return NULL;
6090 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6092 strip_spaces(pTokenPair[0]);
6093 strip_spaces(pTokenPair[1]);
6095 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6096 return pTokenPair;
6099 /***********************************************************************
6100 * HTTP_ProcessHeader (internal)
6102 * Stuff header into header tables according to <dwModifier>
6106 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6108 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6110 LPHTTPHEADERW lphttpHdr = NULL;
6111 INT index;
6112 BOOL request_only = !!(dwModifier & HTTP_ADDHDR_FLAG_REQ);
6113 DWORD res = ERROR_HTTP_INVALID_HEADER;
6115 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6117 EnterCriticalSection( &request->headers_section );
6119 /* REPLACE wins out over ADD */
6120 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6121 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6123 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6124 index = -1;
6125 else
6126 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6128 if (index >= 0)
6130 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6132 LeaveCriticalSection( &request->headers_section );
6133 return ERROR_HTTP_INVALID_HEADER;
6135 lphttpHdr = &request->custHeaders[index];
6137 else if (value)
6139 HTTPHEADERW hdr;
6141 hdr.lpszField = (LPWSTR)field;
6142 hdr.lpszValue = (LPWSTR)value;
6143 hdr.wFlags = hdr.wCount = 0;
6145 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6146 hdr.wFlags |= HDR_ISREQUEST;
6148 res = HTTP_InsertCustomHeader(request, &hdr);
6149 LeaveCriticalSection( &request->headers_section );
6150 return res;
6152 /* no value to delete */
6153 else
6155 LeaveCriticalSection( &request->headers_section );
6156 return ERROR_SUCCESS;
6159 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6160 lphttpHdr->wFlags |= HDR_ISREQUEST;
6161 else
6162 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6164 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6166 HTTP_DeleteCustomHeader( request, index );
6168 if (value && value[0])
6170 HTTPHEADERW hdr;
6172 hdr.lpszField = (LPWSTR)field;
6173 hdr.lpszValue = (LPWSTR)value;
6174 hdr.wFlags = hdr.wCount = 0;
6176 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6177 hdr.wFlags |= HDR_ISREQUEST;
6179 res = HTTP_InsertCustomHeader(request, &hdr);
6180 LeaveCriticalSection( &request->headers_section );
6181 return res;
6184 LeaveCriticalSection( &request->headers_section );
6185 return ERROR_SUCCESS;
6187 else if (dwModifier & COALESCEFLAGS)
6189 LPWSTR lpsztmp;
6190 WCHAR ch = 0;
6191 INT len = 0;
6192 INT origlen = strlenW(lphttpHdr->lpszValue);
6193 INT valuelen = strlenW(value);
6195 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6197 ch = ',';
6198 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6200 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6202 ch = ';';
6203 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6206 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6208 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6209 if (lpsztmp)
6211 lphttpHdr->lpszValue = lpsztmp;
6212 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6213 if (ch > 0)
6215 lphttpHdr->lpszValue[origlen] = ch;
6216 origlen++;
6217 lphttpHdr->lpszValue[origlen] = ' ';
6218 origlen++;
6221 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6222 lphttpHdr->lpszValue[len] = '\0';
6223 res = ERROR_SUCCESS;
6225 else
6227 WARN("heap_realloc (%d bytes) failed\n",len+1);
6228 res = ERROR_OUTOFMEMORY;
6231 TRACE("<-- %d\n", res);
6232 LeaveCriticalSection( &request->headers_section );
6233 return res;
6236 /***********************************************************************
6237 * HTTP_GetCustomHeaderIndex (internal)
6239 * Return index of custom header from header array
6240 * Headers section must be held
6242 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6243 int requested_index, BOOL request_only)
6245 DWORD index;
6247 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6249 for (index = 0; index < request->nCustHeaders; index++)
6251 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6252 continue;
6254 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6255 continue;
6257 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6258 continue;
6260 if (requested_index == 0)
6261 break;
6262 requested_index --;
6265 if (index >= request->nCustHeaders)
6266 index = -1;
6268 TRACE("Return: %d\n", index);
6269 return index;
6273 /***********************************************************************
6274 * HTTP_InsertCustomHeader (internal)
6276 * Insert header into array
6277 * Headers section must be held
6279 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6281 INT count;
6282 LPHTTPHEADERW lph = NULL;
6284 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6285 count = request->nCustHeaders + 1;
6286 if (count > 1)
6287 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6288 else
6289 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6291 if (!lph)
6292 return ERROR_OUTOFMEMORY;
6294 request->custHeaders = lph;
6295 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6296 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6297 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6298 request->custHeaders[count-1].wCount= lpHdr->wCount;
6299 request->nCustHeaders++;
6301 return ERROR_SUCCESS;
6305 /***********************************************************************
6306 * HTTP_DeleteCustomHeader (internal)
6308 * Delete header from array
6309 * If this function is called, the index may change.
6310 * Headers section must be held
6312 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6314 if( request->nCustHeaders <= 0 )
6315 return FALSE;
6316 if( index >= request->nCustHeaders )
6317 return FALSE;
6318 request->nCustHeaders--;
6320 heap_free(request->custHeaders[index].lpszField);
6321 heap_free(request->custHeaders[index].lpszValue);
6323 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6324 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6325 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6327 return TRUE;
6331 /***********************************************************************
6332 * IsHostInProxyBypassList (@)
6334 * Undocumented
6337 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6339 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6340 return FALSE;