wininet: Added support for INTERNET_COOKIE_HTTPONLY flag to InternetGetCookieEx.
[wine/multimedia.git] / dlls / wininet / http.c
blobffd31e69010c25febe57cab67188b7eb23d4800e
1 /*
2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
12 * Ulrich Czekalla
13 * David Hammerton
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
30 #include "config.h"
31 #include "wine/port.h"
33 #if defined(__MINGW32__) || defined (_MSC_VER)
34 #include <ws2tcpip.h>
35 #endif
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
40 #endif
41 #ifdef HAVE_ARPA_INET_H
42 # include <arpa/inet.h>
43 #endif
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #include <time.h>
51 #include <assert.h>
52 #ifdef HAVE_ZLIB
53 # include <zlib.h>
54 #endif
56 #include "windef.h"
57 #include "winbase.h"
58 #include "wininet.h"
59 #include "winerror.h"
60 #include "winternl.h"
61 #define NO_SHLWAPI_STREAM
62 #define NO_SHLWAPI_REG
63 #define NO_SHLWAPI_STRFCNS
64 #define NO_SHLWAPI_GDI
65 #include "shlwapi.h"
66 #include "sspi.h"
67 #include "wincrypt.h"
68 #include "winuser.h"
70 #include "internet.h"
71 #include "wine/debug.h"
72 #include "wine/exception.h"
73 #include "wine/unicode.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
77 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
78 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
79 static const WCHAR szOK[] = {'O','K',0};
80 static const WCHAR szDefaultHeader[] = {'H','T','T','P','/','1','.','0',' ','2','0','0',' ','O','K',0};
81 static const WCHAR hostW[] = { 'H','o','s','t',0 };
82 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
83 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
84 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
85 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
86 static const WCHAR szGET[] = { 'G','E','T', 0 };
87 static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
88 static const WCHAR szCrLf[] = {'\r','\n', 0};
90 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
91 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
92 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
93 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
94 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
95 static const WCHAR szAge[] = { 'A','g','e',0 };
96 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
97 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
98 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
99 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
100 static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
101 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
102 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
103 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
104 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
105 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
106 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
107 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
108 static const WCHAR szContent_Transfer_Encoding[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
109 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
110 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
111 static const WCHAR szDate[] = { 'D','a','t','e',0 };
112 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
113 static const WCHAR szETag[] = { 'E','T','a','g',0 };
114 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
115 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
116 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
117 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
118 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
119 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
120 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
121 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
122 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
123 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
124 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
125 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
126 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
127 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
128 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
129 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
130 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
131 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
132 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
133 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
134 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
135 static const WCHAR szUnless_Modified_Since[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
136 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
137 static const WCHAR szURI[] = { 'U','R','I',0 };
138 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
139 static const WCHAR szVary[] = { 'V','a','r','y',0 };
140 static const WCHAR szVia[] = { 'V','i','a',0 };
141 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
142 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
144 static const WCHAR emptyW[] = {0};
146 #define HTTP_REFERER szReferer
147 #define HTTP_ACCEPT szAccept
148 #define HTTP_USERAGENT szUser_Agent
150 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
151 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
152 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
153 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
154 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
155 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
156 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
158 #define COLLECT_TIME 60000
160 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
162 struct HttpAuthInfo
164 LPWSTR scheme;
165 CredHandle cred;
166 CtxtHandle ctx;
167 TimeStamp exp;
168 ULONG attr;
169 ULONG max_token;
170 void *auth_data;
171 unsigned int auth_data_len;
172 BOOL finished; /* finished authenticating */
176 typedef struct _basicAuthorizationData
178 struct list entry;
180 LPWSTR host;
181 LPWSTR realm;
182 LPSTR authorization;
183 UINT authorizationLen;
184 } basicAuthorizationData;
186 typedef struct _authorizationData
188 struct list entry;
190 LPWSTR host;
191 LPWSTR scheme;
192 LPWSTR domain;
193 UINT domain_len;
194 LPWSTR user;
195 UINT user_len;
196 LPWSTR password;
197 UINT password_len;
198 } authorizationData;
200 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
201 static struct list authorizationCache = LIST_INIT(authorizationCache);
203 static CRITICAL_SECTION authcache_cs;
204 static CRITICAL_SECTION_DEBUG critsect_debug =
206 0, 0, &authcache_cs,
207 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
208 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
210 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
212 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
213 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
214 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
215 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
216 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
217 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
218 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
219 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
220 static LPWSTR HTTP_GetRedirectURL(http_request_t *req, LPCWSTR lpszUrl);
221 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
222 static BOOL HTTP_VerifyValidHeader(http_request_t *req, LPCWSTR field);
223 static BOOL drain_content(http_request_t*,BOOL);
225 static CRITICAL_SECTION connection_pool_cs;
226 static CRITICAL_SECTION_DEBUG connection_pool_debug =
228 0, 0, &connection_pool_cs,
229 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
230 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
232 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
234 static struct list connection_pool = LIST_INIT(connection_pool);
235 static BOOL collector_running;
237 void server_addref(server_t *server)
239 InterlockedIncrement(&server->ref);
242 void server_release(server_t *server)
244 if(InterlockedDecrement(&server->ref))
245 return;
247 list_remove(&server->entry);
249 if(server->cert_chain)
250 CertFreeCertificateChain(server->cert_chain);
251 heap_free(server->name);
252 heap_free(server->scheme_host_port);
253 heap_free(server);
256 static BOOL process_host_port(server_t *server)
258 BOOL default_port;
259 size_t name_len;
260 WCHAR *buf;
262 static const WCHAR httpW[] = {'h','t','t','p',0};
263 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
264 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
266 name_len = strlenW(server->name);
267 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
268 if(!buf)
269 return FALSE;
271 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
272 server->scheme_host_port = buf;
274 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
275 if(server->is_https)
276 server->host_port++;
278 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
279 server->canon_host_port = default_port ? server->name : server->host_port;
280 return TRUE;
283 server_t *get_server(const WCHAR *name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
285 server_t *iter, *server = NULL;
287 if(port == INTERNET_INVALID_PORT_NUMBER)
288 port = INTERNET_DEFAULT_HTTP_PORT;
290 EnterCriticalSection(&connection_pool_cs);
292 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
293 if(iter->port == port && !strcmpW(iter->name, name) && iter->is_https == is_https) {
294 server = iter;
295 server_addref(server);
296 break;
300 if(!server && do_create) {
301 server = heap_alloc_zero(sizeof(*server));
302 if(server) {
303 server->ref = 2; /* list reference and return */
304 server->port = port;
305 server->is_https = is_https;
306 list_init(&server->conn_pool);
307 server->name = heap_strdupW(name);
308 if(server->name && process_host_port(server)) {
309 list_add_head(&connection_pool, &server->entry);
310 }else {
311 heap_free(server);
312 server = NULL;
317 LeaveCriticalSection(&connection_pool_cs);
319 return server;
322 BOOL collect_connections(collect_type_t collect_type)
324 netconn_t *netconn, *netconn_safe;
325 server_t *server, *server_safe;
326 BOOL remaining = FALSE;
327 DWORD64 now;
329 now = GetTickCount64();
331 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
332 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
333 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
334 TRACE("freeing %p\n", netconn);
335 list_remove(&netconn->pool_entry);
336 free_netconn(netconn);
337 }else {
338 remaining = TRUE;
342 if(collect_type == COLLECT_CLEANUP) {
343 list_remove(&server->entry);
344 list_init(&server->entry);
345 server_release(server);
349 return remaining;
352 static DWORD WINAPI collect_connections_proc(void *arg)
354 BOOL remaining_conns;
356 do {
357 /* FIXME: Use more sophisticated method */
358 Sleep(5000);
360 EnterCriticalSection(&connection_pool_cs);
362 remaining_conns = collect_connections(COLLECT_TIMEOUT);
363 if(!remaining_conns)
364 collector_running = FALSE;
366 LeaveCriticalSection(&connection_pool_cs);
367 }while(remaining_conns);
369 FreeLibraryAndExitThread(WININET_hModule, 0);
372 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
374 int HeaderIndex = 0;
375 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
376 if (HeaderIndex == -1)
377 return NULL;
378 else
379 return &req->custHeaders[HeaderIndex];
382 struct data_stream_vtbl_t {
383 DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
384 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
385 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,blocking_mode_t);
386 BOOL (*drain_content)(data_stream_t*,http_request_t*);
387 void (*destroy)(data_stream_t*);
390 typedef struct {
391 data_stream_t data_stream;
393 BYTE buf[READ_BUFFER_SIZE];
394 DWORD buf_size;
395 DWORD buf_pos;
396 DWORD chunk_size;
397 BOOL end_of_data;
398 } chunked_stream_t;
400 static inline void destroy_data_stream(data_stream_t *stream)
402 stream->vtbl->destroy(stream);
405 static void reset_data_stream(http_request_t *req)
407 destroy_data_stream(req->data_stream);
408 req->data_stream = &req->netconn_stream.data_stream;
409 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
410 req->read_chunked = req->read_gzip = FALSE;
413 #ifdef HAVE_ZLIB
415 typedef struct {
416 data_stream_t stream;
417 data_stream_t *parent_stream;
418 z_stream zstream;
419 BYTE buf[READ_BUFFER_SIZE];
420 DWORD buf_size;
421 DWORD buf_pos;
422 BOOL end_of_data;
423 } gzip_stream_t;
425 static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
427 /* Allow reading only from read buffer */
428 return 0;
431 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
433 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
434 return gzip_stream->end_of_data
435 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
438 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
439 DWORD *read, blocking_mode_t blocking_mode)
441 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
442 z_stream *zstream = &gzip_stream->zstream;
443 DWORD current_read, ret_read = 0;
444 int zres;
445 DWORD res = ERROR_SUCCESS;
447 TRACE("(%d %d)\n", size, blocking_mode);
449 while(size && !gzip_stream->end_of_data) {
450 if(!gzip_stream->buf_size) {
451 if(gzip_stream->buf_pos) {
452 if(gzip_stream->buf_size)
453 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
454 gzip_stream->buf_pos = 0;
456 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
457 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, blocking_mode);
458 gzip_stream->buf_size += current_read;
459 if(res != ERROR_SUCCESS)
460 break;
462 if(!current_read) {
463 if(blocking_mode != BLOCKING_DISALLOW) {
464 WARN("unexpected end of data\n");
465 gzip_stream->end_of_data = TRUE;
467 break;
471 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
472 zstream->avail_in = gzip_stream->buf_size;
473 zstream->next_out = buf+ret_read;
474 zstream->avail_out = size;
475 zres = inflate(&gzip_stream->zstream, 0);
476 current_read = size - zstream->avail_out;
477 size -= current_read;
478 ret_read += current_read;
479 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
480 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
481 if(zres == Z_STREAM_END) {
482 TRACE("end of data\n");
483 gzip_stream->end_of_data = TRUE;
484 inflateEnd(zstream);
485 }else if(zres != Z_OK) {
486 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
487 if(!ret_read)
488 res = ERROR_INTERNET_DECODING_FAILED;
489 break;
492 if(ret_read && blocking_mode == BLOCKING_ALLOW)
493 blocking_mode = BLOCKING_DISALLOW;
496 TRACE("read %u bytes\n", ret_read);
497 *read = ret_read;
498 return res;
501 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
503 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
504 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
507 static void gzip_destroy(data_stream_t *stream)
509 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
511 destroy_data_stream(gzip_stream->parent_stream);
513 if(!gzip_stream->end_of_data)
514 inflateEnd(&gzip_stream->zstream);
515 heap_free(gzip_stream);
518 static const data_stream_vtbl_t gzip_stream_vtbl = {
519 gzip_get_avail_data,
520 gzip_end_of_data,
521 gzip_read,
522 gzip_drain_content,
523 gzip_destroy
526 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
528 return heap_alloc(items*size);
531 static void wininet_zfree(voidpf opaque, voidpf address)
533 heap_free(address);
536 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
538 gzip_stream_t *gzip_stream;
539 int index, zres;
541 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
542 if(!gzip_stream)
543 return ERROR_OUTOFMEMORY;
545 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
546 gzip_stream->zstream.zalloc = wininet_zalloc;
547 gzip_stream->zstream.zfree = wininet_zfree;
549 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
550 if(zres != Z_OK) {
551 ERR("inflateInit failed: %d\n", zres);
552 heap_free(gzip_stream);
553 return ERROR_OUTOFMEMORY;
556 index = HTTP_GetCustomHeaderIndex(req, szContent_Length, 0, FALSE);
557 if(index != -1)
558 HTTP_DeleteCustomHeader(req, index);
560 if(req->read_size) {
561 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
562 gzip_stream->buf_size = req->read_size;
563 req->read_pos = req->read_size = 0;
566 req->read_gzip = TRUE;
567 gzip_stream->parent_stream = req->data_stream;
568 req->data_stream = &gzip_stream->stream;
569 return ERROR_SUCCESS;
572 #else
574 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
576 ERR("gzip stream not supported, missing zlib.\n");
577 return ERROR_SUCCESS;
580 #endif
582 /***********************************************************************
583 * HTTP_FreeTokens (internal)
585 * Frees table of pointers.
587 static void HTTP_FreeTokens(LPWSTR * token_array)
589 int i;
590 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
591 heap_free(token_array);
594 static void HTTP_FixURL(http_request_t *request)
596 static const WCHAR szSlash[] = { '/',0 };
597 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
599 /* If we don't have a path we set it to root */
600 if (NULL == request->path)
601 request->path = heap_strdupW(szSlash);
602 else /* remove \r and \n*/
604 int nLen = strlenW(request->path);
605 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
607 nLen--;
608 request->path[nLen]='\0';
610 /* Replace '\' with '/' */
611 while (nLen>0) {
612 nLen--;
613 if (request->path[nLen] == '\\') request->path[nLen]='/';
617 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
618 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
619 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
621 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
622 *fixurl = '/';
623 strcpyW(fixurl + 1, request->path);
624 heap_free( request->path );
625 request->path = fixurl;
629 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
630 const WCHAR *path, const WCHAR *version, BOOL use_cr)
632 LPWSTR requestString;
633 DWORD len, n;
634 LPCWSTR *req;
635 UINT i;
637 static const WCHAR szSpace[] = { ' ',0 };
638 static const WCHAR szColon[] = { ':',' ',0 };
639 static const WCHAR szCr[] = { '\r',0 };
640 static const WCHAR szLf[] = { '\n',0 };
642 /* allocate space for an array of all the string pointers to be added */
643 len = (request->nCustHeaders)*5 + 10;
644 req = heap_alloc(len*sizeof(LPCWSTR));
646 /* add the verb, path and HTTP version string */
647 n = 0;
648 req[n++] = verb;
649 req[n++] = szSpace;
650 req[n++] = path;
651 req[n++] = szSpace;
652 req[n++] = version;
653 if (use_cr)
654 req[n++] = szCr;
655 req[n++] = szLf;
657 /* Append custom request headers */
658 for (i = 0; i < request->nCustHeaders; i++)
660 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
662 req[n++] = request->custHeaders[i].lpszField;
663 req[n++] = szColon;
664 req[n++] = request->custHeaders[i].lpszValue;
665 if (use_cr)
666 req[n++] = szCr;
667 req[n++] = szLf;
669 TRACE("Adding custom header %s (%s)\n",
670 debugstr_w(request->custHeaders[i].lpszField),
671 debugstr_w(request->custHeaders[i].lpszValue));
674 if (use_cr)
675 req[n++] = szCr;
676 req[n++] = szLf;
677 req[n] = NULL;
679 requestString = HTTP_build_req( req, 4 );
680 heap_free( req );
681 return requestString;
684 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
686 static const WCHAR colonW[] = { ':',' ',0 };
687 static const WCHAR crW[] = { '\r',0 };
688 static const WCHAR lfW[] = { '\n',0 };
689 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
691 const WCHAR **req;
692 WCHAR *ret, buf[14];
693 DWORD i, n = 0;
695 req = heap_alloc((request->nCustHeaders*5+8)*sizeof(WCHAR*));
696 if(!req)
697 return NULL;
699 if (request->status_code)
701 req[n++] = request->version;
702 sprintfW(buf, status_fmt, request->status_code);
703 req[n++] = buf;
704 req[n++] = request->statusText;
705 if (use_cr)
706 req[n++] = crW;
707 req[n++] = lfW;
710 for(i = 0; i < request->nCustHeaders; i++)
712 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
713 && strcmpW(request->custHeaders[i].lpszField, szStatus))
715 req[n++] = request->custHeaders[i].lpszField;
716 req[n++] = colonW;
717 req[n++] = request->custHeaders[i].lpszValue;
718 if(use_cr)
719 req[n++] = crW;
720 req[n++] = lfW;
722 TRACE("Adding custom header %s (%s)\n",
723 debugstr_w(request->custHeaders[i].lpszField),
724 debugstr_w(request->custHeaders[i].lpszValue));
727 if(use_cr)
728 req[n++] = crW;
729 req[n++] = lfW;
730 req[n] = NULL;
732 ret = HTTP_build_req(req, 0);
733 heap_free(req);
734 return ret;
737 static void HTTP_ProcessCookies( http_request_t *request )
739 int HeaderIndex;
740 int numCookies = 0;
741 LPHTTPHEADERW setCookieHeader;
743 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
744 return;
746 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
748 HTTPHEADERW *host;
749 const WCHAR *data;
750 WCHAR *name;
752 setCookieHeader = &request->custHeaders[HeaderIndex];
754 if (!setCookieHeader->lpszValue)
755 continue;
757 host = HTTP_GetHeader(request, hostW);
758 if(!host)
759 continue;
761 data = strchrW(setCookieHeader->lpszValue, '=');
762 if(!data)
763 continue;
765 name = heap_strndupW(setCookieHeader->lpszValue, data-setCookieHeader->lpszValue);
766 if(!name)
767 continue;
769 data++;
770 set_cookie(host->lpszValue, request->path, name, data, INTERNET_COOKIE_HTTPONLY);
771 heap_free(name);
775 static void strip_spaces(LPWSTR start)
777 LPWSTR str = start;
778 LPWSTR end;
780 while (*str == ' ' && *str != '\0')
781 str++;
783 if (str != start)
784 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
786 end = start + strlenW(start) - 1;
787 while (end >= start && *end == ' ')
789 *end = '\0';
790 end--;
794 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
796 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
797 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
798 BOOL is_basic;
799 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
800 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
801 if (is_basic && pszRealm)
803 LPCWSTR token;
804 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
805 LPCWSTR realm;
806 ptr++;
807 *pszRealm=NULL;
808 token = strchrW(ptr,'=');
809 if (!token)
810 return TRUE;
811 realm = ptr;
812 while (*realm == ' ' && *realm != '\0')
813 realm++;
814 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
815 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
817 token++;
818 while (*token == ' ' && *token != '\0')
819 token++;
820 if (*token == '\0')
821 return TRUE;
822 *pszRealm = heap_strdupW(token);
823 strip_spaces(*pszRealm);
827 return is_basic;
830 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
832 if (!authinfo) return;
834 if (SecIsValidHandle(&authinfo->ctx))
835 DeleteSecurityContext(&authinfo->ctx);
836 if (SecIsValidHandle(&authinfo->cred))
837 FreeCredentialsHandle(&authinfo->cred);
839 heap_free(authinfo->auth_data);
840 heap_free(authinfo->scheme);
841 heap_free(authinfo);
844 static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
846 basicAuthorizationData *ad;
847 UINT rc = 0;
849 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
851 EnterCriticalSection(&authcache_cs);
852 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
854 if (!strcmpiW(host,ad->host) && !strcmpW(realm,ad->realm))
856 TRACE("Authorization found in cache\n");
857 *auth_data = heap_alloc(ad->authorizationLen);
858 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
859 rc = ad->authorizationLen;
860 break;
863 LeaveCriticalSection(&authcache_cs);
864 return rc;
867 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
869 struct list *cursor;
870 basicAuthorizationData* ad = NULL;
872 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
874 EnterCriticalSection(&authcache_cs);
875 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
877 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
878 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
880 ad = check;
881 break;
885 if (ad)
887 TRACE("Found match in cache, replacing\n");
888 heap_free(ad->authorization);
889 ad->authorization = heap_alloc(auth_data_len);
890 memcpy(ad->authorization, auth_data, auth_data_len);
891 ad->authorizationLen = auth_data_len;
893 else
895 ad = heap_alloc(sizeof(basicAuthorizationData));
896 ad->host = heap_strdupW(host);
897 ad->realm = heap_strdupW(realm);
898 ad->authorization = heap_alloc(auth_data_len);
899 memcpy(ad->authorization, auth_data, auth_data_len);
900 ad->authorizationLen = auth_data_len;
901 list_add_head(&basicAuthorizationCache,&ad->entry);
902 TRACE("authorization cached\n");
904 LeaveCriticalSection(&authcache_cs);
907 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
908 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
910 authorizationData *ad;
912 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
914 EnterCriticalSection(&authcache_cs);
915 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
916 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
917 TRACE("Authorization found in cache\n");
919 nt_auth_identity->User = heap_strdupW(ad->user);
920 nt_auth_identity->Password = heap_strdupW(ad->password);
921 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
922 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
923 (!nt_auth_identity->Domain && ad->domain_len)) {
924 heap_free(nt_auth_identity->User);
925 heap_free(nt_auth_identity->Password);
926 heap_free(nt_auth_identity->Domain);
927 break;
930 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
931 nt_auth_identity->UserLength = ad->user_len;
932 nt_auth_identity->PasswordLength = ad->password_len;
933 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
934 nt_auth_identity->DomainLength = ad->domain_len;
935 LeaveCriticalSection(&authcache_cs);
936 return TRUE;
939 LeaveCriticalSection(&authcache_cs);
941 return FALSE;
944 static void cache_authorization(LPWSTR host, LPWSTR scheme,
945 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
947 authorizationData *ad;
948 BOOL found = FALSE;
950 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
952 EnterCriticalSection(&authcache_cs);
953 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
954 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
955 found = TRUE;
956 break;
959 if(found) {
960 heap_free(ad->user);
961 heap_free(ad->password);
962 heap_free(ad->domain);
963 } else {
964 ad = heap_alloc(sizeof(authorizationData));
965 if(!ad) {
966 LeaveCriticalSection(&authcache_cs);
967 return;
970 ad->host = heap_strdupW(host);
971 ad->scheme = heap_strdupW(scheme);
972 list_add_head(&authorizationCache, &ad->entry);
975 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
976 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
977 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
978 ad->user_len = nt_auth_identity->UserLength;
979 ad->password_len = nt_auth_identity->PasswordLength;
980 ad->domain_len = nt_auth_identity->DomainLength;
982 if(!ad->host || !ad->scheme || !ad->user || !ad->password
983 || (nt_auth_identity->Domain && !ad->domain)) {
984 heap_free(ad->host);
985 heap_free(ad->scheme);
986 heap_free(ad->user);
987 heap_free(ad->password);
988 heap_free(ad->domain);
989 list_remove(&ad->entry);
990 heap_free(ad);
993 LeaveCriticalSection(&authcache_cs);
996 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
997 struct HttpAuthInfo **ppAuthInfo,
998 LPWSTR domain_and_username, LPWSTR password,
999 LPWSTR host )
1001 SECURITY_STATUS sec_status;
1002 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1003 BOOL first = FALSE;
1004 LPWSTR szRealm = NULL;
1006 TRACE("%s\n", debugstr_w(pszAuthValue));
1008 if (!pAuthInfo)
1010 TimeStamp exp;
1012 first = TRUE;
1013 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1014 if (!pAuthInfo)
1015 return FALSE;
1017 SecInvalidateHandle(&pAuthInfo->cred);
1018 SecInvalidateHandle(&pAuthInfo->ctx);
1019 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1020 pAuthInfo->attr = 0;
1021 pAuthInfo->auth_data = NULL;
1022 pAuthInfo->auth_data_len = 0;
1023 pAuthInfo->finished = FALSE;
1025 if (is_basic_auth_value(pszAuthValue,NULL))
1027 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1028 pAuthInfo->scheme = heap_strdupW(szBasic);
1029 if (!pAuthInfo->scheme)
1031 heap_free(pAuthInfo);
1032 return FALSE;
1035 else
1037 PVOID pAuthData;
1038 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1040 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1041 if (!pAuthInfo->scheme)
1043 heap_free(pAuthInfo);
1044 return FALSE;
1047 if (domain_and_username)
1049 WCHAR *user = strchrW(domain_and_username, '\\');
1050 WCHAR *domain = domain_and_username;
1052 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1054 pAuthData = &nt_auth_identity;
1056 if (user) user++;
1057 else
1059 user = domain_and_username;
1060 domain = NULL;
1063 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1064 nt_auth_identity.User = user;
1065 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1066 nt_auth_identity.Domain = domain;
1067 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1068 nt_auth_identity.Password = password;
1069 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1071 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1073 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1074 pAuthData = &nt_auth_identity;
1075 else
1076 /* use default credentials */
1077 pAuthData = NULL;
1079 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1080 SECPKG_CRED_OUTBOUND, NULL,
1081 pAuthData, NULL,
1082 NULL, &pAuthInfo->cred,
1083 &exp);
1085 if(pAuthData && !domain_and_username) {
1086 heap_free(nt_auth_identity.User);
1087 heap_free(nt_auth_identity.Domain);
1088 heap_free(nt_auth_identity.Password);
1091 if (sec_status == SEC_E_OK)
1093 PSecPkgInfoW sec_pkg_info;
1094 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1095 if (sec_status == SEC_E_OK)
1097 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1098 FreeContextBuffer(sec_pkg_info);
1101 if (sec_status != SEC_E_OK)
1103 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1104 debugstr_w(pAuthInfo->scheme), sec_status);
1105 heap_free(pAuthInfo->scheme);
1106 heap_free(pAuthInfo);
1107 return FALSE;
1110 *ppAuthInfo = pAuthInfo;
1112 else if (pAuthInfo->finished)
1113 return FALSE;
1115 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1116 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1118 ERR("authentication scheme changed from %s to %s\n",
1119 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1120 return FALSE;
1123 if (is_basic_auth_value(pszAuthValue,&szRealm))
1125 int userlen;
1126 int passlen;
1127 char *auth_data = NULL;
1128 UINT auth_data_len = 0;
1130 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1132 if (!domain_and_username)
1134 if (host && szRealm)
1135 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1136 if (auth_data_len == 0)
1138 heap_free(szRealm);
1139 return FALSE;
1142 else
1144 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1145 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1147 /* length includes a nul terminator, which will be re-used for the ':' */
1148 auth_data = heap_alloc(userlen + 1 + passlen);
1149 if (!auth_data)
1151 heap_free(szRealm);
1152 return FALSE;
1155 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1156 auth_data[userlen] = ':';
1157 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1158 auth_data_len = userlen + 1 + passlen;
1159 if (host && szRealm)
1160 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1163 pAuthInfo->auth_data = auth_data;
1164 pAuthInfo->auth_data_len = auth_data_len;
1165 pAuthInfo->finished = TRUE;
1166 heap_free(szRealm);
1167 return TRUE;
1169 else
1171 LPCWSTR pszAuthData;
1172 SecBufferDesc out_desc, in_desc;
1173 SecBuffer out, in;
1174 unsigned char *buffer;
1175 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1176 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1178 in.BufferType = SECBUFFER_TOKEN;
1179 in.cbBuffer = 0;
1180 in.pvBuffer = NULL;
1182 in_desc.ulVersion = 0;
1183 in_desc.cBuffers = 1;
1184 in_desc.pBuffers = &in;
1186 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1187 if (*pszAuthData == ' ')
1189 pszAuthData++;
1190 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1191 in.pvBuffer = heap_alloc(in.cbBuffer);
1192 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1195 buffer = heap_alloc(pAuthInfo->max_token);
1197 out.BufferType = SECBUFFER_TOKEN;
1198 out.cbBuffer = pAuthInfo->max_token;
1199 out.pvBuffer = buffer;
1201 out_desc.ulVersion = 0;
1202 out_desc.cBuffers = 1;
1203 out_desc.pBuffers = &out;
1205 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1206 first ? NULL : &pAuthInfo->ctx,
1207 first ? request->server->name : NULL,
1208 context_req, 0, SECURITY_NETWORK_DREP,
1209 in.pvBuffer ? &in_desc : NULL,
1210 0, &pAuthInfo->ctx, &out_desc,
1211 &pAuthInfo->attr, &pAuthInfo->exp);
1212 if (sec_status == SEC_E_OK)
1214 pAuthInfo->finished = TRUE;
1215 pAuthInfo->auth_data = out.pvBuffer;
1216 pAuthInfo->auth_data_len = out.cbBuffer;
1217 TRACE("sending last auth packet\n");
1219 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1221 pAuthInfo->auth_data = out.pvBuffer;
1222 pAuthInfo->auth_data_len = out.cbBuffer;
1223 TRACE("sending next auth packet\n");
1225 else
1227 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1228 heap_free(out.pvBuffer);
1229 destroy_authinfo(pAuthInfo);
1230 *ppAuthInfo = NULL;
1231 return FALSE;
1235 return TRUE;
1238 /***********************************************************************
1239 * HTTP_HttpAddRequestHeadersW (internal)
1241 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1242 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1244 LPWSTR lpszStart;
1245 LPWSTR lpszEnd;
1246 LPWSTR buffer;
1247 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1249 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1251 if( dwHeaderLength == ~0U )
1252 len = strlenW(lpszHeader);
1253 else
1254 len = dwHeaderLength;
1255 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1256 lstrcpynW( buffer, lpszHeader, len + 1);
1258 lpszStart = buffer;
1262 LPWSTR * pFieldAndValue;
1264 lpszEnd = lpszStart;
1266 while (*lpszEnd != '\0')
1268 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1269 break;
1270 lpszEnd++;
1273 if (*lpszStart == '\0')
1274 break;
1276 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1278 *lpszEnd = '\0';
1279 lpszEnd++; /* Jump over newline */
1281 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1282 if (*lpszStart == '\0')
1284 /* Skip 0-length headers */
1285 lpszStart = lpszEnd;
1286 res = ERROR_SUCCESS;
1287 continue;
1289 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1290 if (pFieldAndValue)
1292 res = HTTP_VerifyValidHeader(request, pFieldAndValue[0]);
1293 if (res == ERROR_SUCCESS)
1294 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1295 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1296 HTTP_FreeTokens(pFieldAndValue);
1299 lpszStart = lpszEnd;
1300 } while (res == ERROR_SUCCESS);
1302 heap_free(buffer);
1303 return res;
1306 /***********************************************************************
1307 * HttpAddRequestHeadersW (WININET.@)
1309 * Adds one or more HTTP header to the request handler
1311 * NOTE
1312 * On Windows if dwHeaderLength includes the trailing '\0', then
1313 * HttpAddRequestHeadersW() adds it too. However this results in an
1314 * invalid HTTP header which is rejected by some servers so we probably
1315 * don't need to match Windows on that point.
1317 * RETURNS
1318 * TRUE on success
1319 * FALSE on failure
1322 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1323 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1325 http_request_t *request;
1326 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1328 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1330 if (!lpszHeader)
1331 return TRUE;
1333 request = (http_request_t*) get_handle_object( hHttpRequest );
1334 if (request && request->hdr.htype == WH_HHTTPREQ)
1335 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1336 if( request )
1337 WININET_Release( &request->hdr );
1339 if(res != ERROR_SUCCESS)
1340 SetLastError(res);
1341 return res == ERROR_SUCCESS;
1344 /***********************************************************************
1345 * HttpAddRequestHeadersA (WININET.@)
1347 * Adds one or more HTTP header to the request handler
1349 * RETURNS
1350 * TRUE on success
1351 * FALSE on failure
1354 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1355 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1357 DWORD len;
1358 LPWSTR hdr;
1359 BOOL r;
1361 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1363 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
1364 hdr = heap_alloc(len*sizeof(WCHAR));
1365 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
1366 if( dwHeaderLength != ~0U )
1367 dwHeaderLength = len;
1369 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
1371 heap_free( hdr );
1372 return r;
1375 static void free_accept_types( WCHAR **accept_types )
1377 WCHAR *ptr, **types = accept_types;
1379 if (!types) return;
1380 while ((ptr = *types))
1382 heap_free( ptr );
1383 types++;
1385 heap_free( accept_types );
1388 static WCHAR **convert_accept_types( const char **accept_types )
1390 unsigned int count;
1391 const char **types = accept_types;
1392 WCHAR **typesW;
1393 BOOL invalid_pointer = FALSE;
1395 if (!types) return NULL;
1396 count = 0;
1397 while (*types)
1399 __TRY
1401 /* find out how many there are */
1402 if (*types && **types)
1404 TRACE("accept type: %s\n", debugstr_a(*types));
1405 count++;
1408 __EXCEPT_PAGE_FAULT
1410 WARN("invalid accept type pointer\n");
1411 invalid_pointer = TRUE;
1413 __ENDTRY;
1414 types++;
1416 if (invalid_pointer) return NULL;
1417 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1418 count = 0;
1419 types = accept_types;
1420 while (*types)
1422 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1423 types++;
1425 typesW[count] = NULL;
1426 return typesW;
1429 /***********************************************************************
1430 * HttpOpenRequestA (WININET.@)
1432 * Open a HTTP request handle
1434 * RETURNS
1435 * HINTERNET a HTTP request handle on success
1436 * NULL on failure
1439 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1440 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1441 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1442 DWORD dwFlags, DWORD_PTR dwContext)
1444 LPWSTR szVerb = NULL, szObjectName = NULL;
1445 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1446 HINTERNET rc = NULL;
1448 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1449 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1450 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1451 dwFlags, dwContext);
1453 if (lpszVerb)
1455 szVerb = heap_strdupAtoW(lpszVerb);
1456 if ( !szVerb )
1457 goto end;
1460 if (lpszObjectName)
1462 szObjectName = heap_strdupAtoW(lpszObjectName);
1463 if ( !szObjectName )
1464 goto end;
1467 if (lpszVersion)
1469 szVersion = heap_strdupAtoW(lpszVersion);
1470 if ( !szVersion )
1471 goto end;
1474 if (lpszReferrer)
1476 szReferrer = heap_strdupAtoW(lpszReferrer);
1477 if ( !szReferrer )
1478 goto end;
1481 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1482 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1483 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1485 end:
1486 free_accept_types(szAcceptTypes);
1487 heap_free(szReferrer);
1488 heap_free(szVersion);
1489 heap_free(szObjectName);
1490 heap_free(szVerb);
1491 return rc;
1494 /***********************************************************************
1495 * HTTP_EncodeBase64
1497 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1499 UINT n = 0, x;
1500 static const CHAR HTTP_Base64Enc[] =
1501 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1503 while( len > 0 )
1505 /* first 6 bits, all from bin[0] */
1506 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1507 x = (bin[0] & 3) << 4;
1509 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1510 if( len == 1 )
1512 base64[n++] = HTTP_Base64Enc[x];
1513 base64[n++] = '=';
1514 base64[n++] = '=';
1515 break;
1517 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1518 x = ( bin[1] & 0x0f ) << 2;
1520 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1521 if( len == 2 )
1523 base64[n++] = HTTP_Base64Enc[x];
1524 base64[n++] = '=';
1525 break;
1527 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1529 /* last 6 bits, all from bin [2] */
1530 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1531 bin += 3;
1532 len -= 3;
1534 base64[n] = 0;
1535 return n;
1538 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1539 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1540 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1541 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1542 static const signed char HTTP_Base64Dec[256] =
1544 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1545 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1546 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1547 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1548 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1549 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1550 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1551 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1552 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1553 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1554 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1555 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1556 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1557 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1558 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1559 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1560 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1561 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1562 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1563 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1564 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1565 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1566 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1567 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1568 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1569 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1571 #undef CH
1573 /***********************************************************************
1574 * HTTP_DecodeBase64
1576 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1578 unsigned int n = 0;
1580 while(*base64)
1582 signed char in[4];
1584 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1585 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1586 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1587 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1589 WARN("invalid base64: %s\n", debugstr_w(base64));
1590 return 0;
1592 if (bin)
1593 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1594 n++;
1596 if ((base64[2] == '=') && (base64[3] == '='))
1597 break;
1598 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1599 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1601 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1602 return 0;
1604 if (bin)
1605 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1606 n++;
1608 if (base64[3] == '=')
1609 break;
1610 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1611 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1613 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1614 return 0;
1616 if (bin)
1617 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1618 n++;
1620 base64 += 4;
1623 return n;
1626 /***********************************************************************
1627 * HTTP_InsertAuthorization
1629 * Insert or delete the authorization field in the request header.
1631 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1633 if (pAuthInfo)
1635 static const WCHAR wszSpace[] = {' ',0};
1636 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1637 unsigned int len;
1638 WCHAR *authorization = NULL;
1640 if (pAuthInfo->auth_data_len)
1642 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1643 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1644 authorization = heap_alloc((len+1)*sizeof(WCHAR));
1645 if (!authorization)
1646 return FALSE;
1648 strcpyW(authorization, pAuthInfo->scheme);
1649 strcatW(authorization, wszSpace);
1650 HTTP_EncodeBase64(pAuthInfo->auth_data,
1651 pAuthInfo->auth_data_len,
1652 authorization+strlenW(authorization));
1654 /* clear the data as it isn't valid now that it has been sent to the
1655 * server, unless it's Basic authentication which doesn't do
1656 * connection tracking */
1657 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1659 heap_free(pAuthInfo->auth_data);
1660 pAuthInfo->auth_data = NULL;
1661 pAuthInfo->auth_data_len = 0;
1665 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1667 HTTP_ProcessHeader(request, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1668 heap_free(authorization);
1670 return TRUE;
1673 static WCHAR *build_proxy_path_url(http_request_t *req)
1675 DWORD size, len;
1676 WCHAR *url;
1678 len = strlenW(req->server->scheme_host_port);
1679 size = len + strlenW(req->path) + 1;
1680 if(*req->path != '/')
1681 size++;
1682 url = heap_alloc(size * sizeof(WCHAR));
1683 if(!url)
1684 return NULL;
1686 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1687 if(*req->path != '/')
1688 url[len++] = '/';
1690 strcpyW(url+len, req->path);
1692 TRACE("url=%s\n", debugstr_w(url));
1693 return url;
1696 static BOOL HTTP_DomainMatches(LPCWSTR server, LPCWSTR domain)
1698 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1699 BOOL ret = FALSE;
1701 if (!strcmpiW( domain, localW ) && !strchrW( server, '.' ))
1702 ret = TRUE;
1703 else if (*domain == '*')
1705 if (domain[1] == '.')
1707 LPCWSTR dot;
1709 /* For a hostname to match a wildcard, the last domain must match
1710 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1711 * hostname is www.foo.a.b, it matches, but a.b does not.
1713 dot = strchrW( server, '.' );
1714 if (dot)
1716 int len = strlenW( dot + 1 );
1718 if (len > strlenW( domain + 2 ))
1720 LPCWSTR ptr;
1722 /* The server's domain is longer than the wildcard, so it
1723 * could be a subdomain. Compare the last portion of the
1724 * server's domain.
1726 ptr = dot + len + 1 - strlenW( domain + 2 );
1727 if (!strcmpiW( ptr, domain + 2 ))
1729 /* This is only a match if the preceding character is
1730 * a '.', i.e. that it is a matching domain. E.g.
1731 * if domain is '*.b.c' and server is 'www.ab.c' they
1732 * do not match.
1734 ret = *(ptr - 1) == '.';
1737 else
1738 ret = !strcmpiW( dot + 1, domain + 2 );
1742 else
1743 ret = !strcmpiW( server, domain );
1744 return ret;
1747 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1749 LPCWSTR ptr;
1750 BOOL ret = FALSE;
1752 if (!lpwai->proxyBypass) return FALSE;
1753 ptr = lpwai->proxyBypass;
1754 do {
1755 LPCWSTR tmp = ptr;
1757 ptr = strchrW( ptr, ';' );
1758 if (!ptr)
1759 ptr = strchrW( tmp, ' ' );
1760 if (ptr)
1762 if (ptr - tmp < INTERNET_MAX_HOST_NAME_LENGTH)
1764 WCHAR domain[INTERNET_MAX_HOST_NAME_LENGTH];
1766 memcpy( domain, tmp, (ptr - tmp) * sizeof(WCHAR) );
1767 domain[ptr - tmp] = 0;
1768 ret = HTTP_DomainMatches( server, domain );
1770 ptr += 1;
1772 else if (*tmp)
1773 ret = HTTP_DomainMatches( server, tmp );
1774 } while (ptr && !ret);
1775 return ret;
1778 /***********************************************************************
1779 * HTTP_DealWithProxy
1781 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1783 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1784 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1785 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1786 WCHAR buf[INTERNET_MAX_HOST_NAME_LENGTH];
1787 WCHAR protoProxy[INTERNET_MAX_URL_LENGTH];
1788 DWORD protoProxyLen = INTERNET_MAX_URL_LENGTH;
1789 WCHAR proxy[INTERNET_MAX_URL_LENGTH];
1790 static WCHAR szNul[] = { 0 };
1791 URL_COMPONENTSW UrlComponents;
1792 server_t *new_server;
1793 BOOL is_https;
1795 memset( &UrlComponents, 0, sizeof UrlComponents );
1796 UrlComponents.dwStructSize = sizeof UrlComponents;
1797 UrlComponents.lpszHostName = buf;
1798 UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
1800 if (!INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp, protoProxy, &protoProxyLen))
1801 return FALSE;
1802 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1803 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1804 sprintfW(proxy, szFormat, protoProxy);
1805 else
1806 strcpyW(proxy, protoProxy);
1807 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1808 return FALSE;
1809 if( UrlComponents.dwHostNameLength == 0 )
1810 return FALSE;
1812 if( !request->path )
1813 request->path = szNul;
1815 is_https = (UrlComponents.nScheme == INTERNET_SCHEME_HTTPS);
1816 if (is_https && UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1817 UrlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1819 new_server = get_server(UrlComponents.lpszHostName, UrlComponents.nPort, is_https, TRUE);
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 socklen_t addr_len;
1833 void *addr;
1835 if(server->addr_len)
1836 return ERROR_SUCCESS;
1838 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1839 INTERNET_STATUS_RESOLVING_NAME,
1840 server->name,
1841 (strlenW(server->name)+1) * sizeof(WCHAR));
1843 addr_len = sizeof(server->addr);
1844 if (!GetAddress(server->name, server->port, (struct sockaddr *)&server->addr, &addr_len))
1845 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1847 switch(server->addr.ss_family) {
1848 case AF_INET:
1849 addr = &((struct sockaddr_in *)&server->addr)->sin_addr;
1850 break;
1851 case AF_INET6:
1852 addr = &((struct sockaddr_in6 *)&server->addr)->sin6_addr;
1853 break;
1854 default:
1855 WARN("unsupported family %d\n", server->addr.ss_family);
1856 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1859 server->addr_len = addr_len;
1860 inet_ntop(server->addr.ss_family, addr, server->addr_str, sizeof(server->addr_str));
1861 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1862 INTERNET_STATUS_NAME_RESOLVED,
1863 server->addr_str, strlen(server->addr_str)+1);
1865 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1866 return ERROR_SUCCESS;
1869 static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
1871 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1872 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1873 static const WCHAR slash[] = { '/',0 };
1874 LPHTTPHEADERW host_header;
1875 LPCWSTR scheme;
1877 host_header = HTTP_GetHeader(req, hostW);
1878 if(!host_header)
1879 return FALSE;
1881 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1882 scheme = https;
1883 else
1884 scheme = http;
1885 strcpyW(buf, scheme);
1886 strcatW(buf, host_header->lpszValue);
1887 if (req->path[0] != '/')
1888 strcatW(buf, slash);
1889 strcatW(buf, req->path);
1890 return TRUE;
1894 /***********************************************************************
1895 * HTTPREQ_Destroy (internal)
1897 * Deallocate request handle
1900 static void HTTPREQ_Destroy(object_header_t *hdr)
1902 http_request_t *request = (http_request_t*) hdr;
1903 DWORD i;
1905 TRACE("\n");
1907 if(request->hCacheFile)
1908 CloseHandle(request->hCacheFile);
1909 if(request->req_file)
1910 req_file_release(request->req_file);
1912 request->read_section.DebugInfo->Spare[0] = 0;
1913 DeleteCriticalSection( &request->read_section );
1914 WININET_Release(&request->session->hdr);
1916 destroy_authinfo(request->authInfo);
1917 destroy_authinfo(request->proxyAuthInfo);
1919 if(request->server)
1920 server_release(request->server);
1921 if(request->proxy)
1922 server_release(request->proxy);
1924 heap_free(request->path);
1925 heap_free(request->verb);
1926 heap_free(request->version);
1927 heap_free(request->statusText);
1929 for (i = 0; i < request->nCustHeaders; i++)
1931 heap_free(request->custHeaders[i].lpszField);
1932 heap_free(request->custHeaders[i].lpszValue);
1934 destroy_data_stream(request->data_stream);
1935 heap_free(request->custHeaders);
1938 static void http_release_netconn(http_request_t *req, BOOL reuse)
1940 TRACE("%p %p %x\n",req, req->netconn, reuse);
1942 if(!is_valid_netconn(req->netconn))
1943 return;
1945 if(reuse && req->netconn->keep_alive) {
1946 BOOL run_collector;
1948 EnterCriticalSection(&connection_pool_cs);
1950 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1951 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1952 req->netconn = NULL;
1954 run_collector = !collector_running;
1955 collector_running = TRUE;
1957 LeaveCriticalSection(&connection_pool_cs);
1959 if(run_collector) {
1960 HANDLE thread = NULL;
1961 HMODULE module;
1963 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1964 if(module)
1965 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1966 if(!thread) {
1967 EnterCriticalSection(&connection_pool_cs);
1968 collector_running = FALSE;
1969 LeaveCriticalSection(&connection_pool_cs);
1971 if(module)
1972 FreeLibrary(module);
1974 else
1975 CloseHandle(thread);
1977 return;
1980 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1981 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1983 close_netconn(req->netconn);
1985 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1986 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1989 static BOOL HTTP_KeepAlive(http_request_t *request)
1991 WCHAR szVersion[10];
1992 WCHAR szConnectionResponse[20];
1993 DWORD dwBufferSize = sizeof(szVersion);
1994 BOOL keepalive = FALSE;
1996 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1997 * the connection is keep-alive by default */
1998 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1999 && !strcmpiW(szVersion, g_szHttp1_1))
2001 keepalive = TRUE;
2004 dwBufferSize = sizeof(szConnectionResponse);
2005 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2006 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2008 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2011 return keepalive;
2014 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2016 http_request_t *req = (http_request_t*)hdr;
2018 http_release_netconn(req, drain_content(req, FALSE));
2021 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2023 int len;
2024 if (unicode)
2026 WCHAR *buf = buffer;
2028 if (str) len = strlenW(str);
2029 else len = 0;
2030 if (*size < (len + 1) * sizeof(WCHAR))
2032 *size = (len + 1) * sizeof(WCHAR);
2033 return ERROR_INSUFFICIENT_BUFFER;
2035 if (str) strcpyW(buf, str);
2036 else buf[0] = 0;
2038 *size = len;
2039 return ERROR_SUCCESS;
2041 else
2043 char *buf = buffer;
2045 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2046 else len = 1;
2047 if (*size < len)
2049 *size = len;
2050 return ERROR_INSUFFICIENT_BUFFER;
2052 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2053 else buf[0] = 0;
2055 *size = len - 1;
2056 return ERROR_SUCCESS;
2060 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2062 http_request_t *req = (http_request_t*)hdr;
2064 switch(option) {
2065 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2067 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2069 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2071 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2072 return ERROR_INSUFFICIENT_BUFFER;
2073 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2074 /* FIXME: can't get a SOCKET from our connection since we don't use
2075 * winsock
2077 info->Socket = 0;
2078 /* FIXME: get source port from req->netConnection */
2079 info->SourcePort = 0;
2080 info->DestPort = req->server->port;
2081 info->Flags = 0;
2082 if (HTTP_KeepAlive(req))
2083 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2084 if (req->proxy)
2085 info->Flags |= IDSI_FLAG_PROXY;
2086 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2087 info->Flags |= IDSI_FLAG_SECURE;
2089 return ERROR_SUCCESS;
2092 case 98:
2093 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2094 /* fall through */
2095 case INTERNET_OPTION_SECURITY_FLAGS:
2097 DWORD flags;
2099 if (*size < sizeof(ULONG))
2100 return ERROR_INSUFFICIENT_BUFFER;
2102 *size = sizeof(DWORD);
2103 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2104 *(DWORD *)buffer = flags;
2106 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2107 return ERROR_SUCCESS;
2110 case INTERNET_OPTION_HANDLE_TYPE:
2111 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2113 if (*size < sizeof(ULONG))
2114 return ERROR_INSUFFICIENT_BUFFER;
2116 *size = sizeof(DWORD);
2117 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2118 return ERROR_SUCCESS;
2120 case INTERNET_OPTION_URL: {
2121 WCHAR url[INTERNET_MAX_URL_LENGTH];
2122 HTTPHEADERW *host;
2124 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
2126 TRACE("INTERNET_OPTION_URL\n");
2128 host = HTTP_GetHeader(req, hostW);
2129 strcpyW(url, httpW);
2130 strcatW(url, host->lpszValue);
2131 strcatW(url, req->path);
2133 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
2134 return str_to_buffer(url, buffer, size, unicode);
2136 case INTERNET_OPTION_USER_AGENT:
2137 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2138 case INTERNET_OPTION_USERNAME:
2139 return str_to_buffer(req->session->userName, buffer, size, unicode);
2140 case INTERNET_OPTION_PASSWORD:
2141 return str_to_buffer(req->session->password, buffer, size, unicode);
2142 case INTERNET_OPTION_PROXY_USERNAME:
2143 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2144 case INTERNET_OPTION_PROXY_PASSWORD:
2145 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2147 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2148 INTERNET_CACHE_ENTRY_INFOW *info;
2149 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2150 WCHAR url[INTERNET_MAX_URL_LENGTH];
2151 DWORD nbytes, error;
2152 BOOL ret;
2154 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2156 if (*size < sizeof(*ts))
2158 *size = sizeof(*ts);
2159 return ERROR_INSUFFICIENT_BUFFER;
2161 nbytes = 0;
2162 HTTP_GetRequestURL(req, url);
2163 ret = GetUrlCacheEntryInfoW(url, NULL, &nbytes);
2164 error = GetLastError();
2165 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2167 if (!(info = heap_alloc(nbytes)))
2168 return ERROR_OUTOFMEMORY;
2170 GetUrlCacheEntryInfoW(url, info, &nbytes);
2172 ts->ftExpires = info->ExpireTime;
2173 ts->ftLastModified = info->LastModifiedTime;
2175 heap_free(info);
2176 *size = sizeof(*ts);
2177 return ERROR_SUCCESS;
2179 return error;
2182 case INTERNET_OPTION_DATAFILE_NAME: {
2183 DWORD req_size;
2185 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2187 if(!req->req_file) {
2188 *size = 0;
2189 return ERROR_INTERNET_ITEM_NOT_FOUND;
2192 if(unicode) {
2193 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2194 if(*size < req_size)
2195 return ERROR_INSUFFICIENT_BUFFER;
2197 *size = req_size;
2198 memcpy(buffer, req->req_file->file_name, *size);
2199 return ERROR_SUCCESS;
2200 }else {
2201 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2202 if (req_size > *size)
2203 return ERROR_INSUFFICIENT_BUFFER;
2205 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2206 -1, buffer, *size, NULL, NULL);
2207 return ERROR_SUCCESS;
2211 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2212 PCCERT_CONTEXT context;
2214 if(!req->netconn)
2215 return ERROR_INTERNET_INVALID_OPERATION;
2217 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2218 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2219 return ERROR_INSUFFICIENT_BUFFER;
2222 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2223 if(context) {
2224 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2225 DWORD len;
2227 memset(info, 0, sizeof(*info));
2228 info->ftExpiry = context->pCertInfo->NotAfter;
2229 info->ftStart = context->pCertInfo->NotBefore;
2230 len = CertNameToStrA(context->dwCertEncodingType,
2231 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2232 info->lpszSubjectInfo = LocalAlloc(0, len);
2233 if(info->lpszSubjectInfo)
2234 CertNameToStrA(context->dwCertEncodingType,
2235 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2236 info->lpszSubjectInfo, len);
2237 len = CertNameToStrA(context->dwCertEncodingType,
2238 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2239 info->lpszIssuerInfo = LocalAlloc(0, len);
2240 if(info->lpszIssuerInfo)
2241 CertNameToStrA(context->dwCertEncodingType,
2242 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2243 info->lpszIssuerInfo, len);
2244 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2245 CertFreeCertificateContext(context);
2246 return ERROR_SUCCESS;
2248 return ERROR_NOT_SUPPORTED;
2250 case INTERNET_OPTION_CONNECT_TIMEOUT:
2251 if (*size < sizeof(DWORD))
2252 return ERROR_INSUFFICIENT_BUFFER;
2254 *size = sizeof(DWORD);
2255 *(DWORD *)buffer = req->connect_timeout;
2256 return ERROR_SUCCESS;
2257 case INTERNET_OPTION_REQUEST_FLAGS: {
2258 DWORD flags = 0;
2260 if (*size < sizeof(DWORD))
2261 return ERROR_INSUFFICIENT_BUFFER;
2263 /* FIXME: Add support for:
2264 * INTERNET_REQFLAG_FROM_CACHE
2265 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2268 if(req->proxy)
2269 flags |= INTERNET_REQFLAG_VIA_PROXY;
2270 if(!req->status_code)
2271 flags |= INTERNET_REQFLAG_NO_HEADERS;
2273 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2275 *size = sizeof(DWORD);
2276 *(DWORD*)buffer = flags;
2277 return ERROR_SUCCESS;
2281 return INET_QueryOption(hdr, option, buffer, size, unicode);
2284 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2286 http_request_t *req = (http_request_t*)hdr;
2288 switch(option) {
2289 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2290 TRACE("Undocumented option 99\n");
2292 if (!buffer || size != sizeof(DWORD))
2293 return ERROR_INVALID_PARAMETER;
2294 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2295 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2297 /* fall through */
2298 case INTERNET_OPTION_SECURITY_FLAGS:
2300 DWORD flags;
2302 if (!buffer || size != sizeof(DWORD))
2303 return ERROR_INVALID_PARAMETER;
2304 flags = *(DWORD *)buffer;
2305 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2306 flags &= SECURITY_SET_MASK;
2307 req->security_flags |= flags;
2308 if(is_valid_netconn(req->netconn))
2309 req->netconn->security_flags |= flags;
2310 return ERROR_SUCCESS;
2312 case INTERNET_OPTION_CONNECT_TIMEOUT:
2313 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2314 req->connect_timeout = *(DWORD *)buffer;
2315 return ERROR_SUCCESS;
2317 case INTERNET_OPTION_SEND_TIMEOUT:
2318 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2319 req->send_timeout = *(DWORD *)buffer;
2320 return ERROR_SUCCESS;
2322 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2323 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2324 req->receive_timeout = *(DWORD *)buffer;
2325 return ERROR_SUCCESS;
2327 case INTERNET_OPTION_USERNAME:
2328 heap_free(req->session->userName);
2329 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2330 return ERROR_SUCCESS;
2332 case INTERNET_OPTION_PASSWORD:
2333 heap_free(req->session->password);
2334 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2335 return ERROR_SUCCESS;
2337 case INTERNET_OPTION_PROXY_USERNAME:
2338 heap_free(req->session->appInfo->proxyUsername);
2339 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2340 return ERROR_SUCCESS;
2342 case INTERNET_OPTION_PROXY_PASSWORD:
2343 heap_free(req->session->appInfo->proxyPassword);
2344 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2345 return ERROR_SUCCESS;
2347 case INTERNET_OPTION_HTTP_DECODING:
2348 if(size != sizeof(BOOL))
2349 return ERROR_INVALID_PARAMETER;
2350 req->decoding = *(BOOL*)buffer;
2351 return ERROR_SUCCESS;
2354 return INET_SetOption(hdr, option, buffer, size);
2357 static void commit_cache_entry(http_request_t *req)
2359 WCHAR url[INTERNET_MAX_URL_LENGTH];
2361 TRACE("%p\n", req);
2363 CloseHandle(req->hCacheFile);
2364 req->hCacheFile = NULL;
2366 if(HTTP_GetRequestURL(req, url)) {
2367 WCHAR *header;
2368 DWORD header_len;
2369 BOOL res;
2371 header = build_response_header(req, TRUE);
2372 header_len = (header ? strlenW(header) : 0);
2373 res = CommitUrlCacheEntryW(url, req->req_file->file_name, req->expires,
2374 req->last_modified, NORMAL_CACHE_ENTRY,
2375 header, header_len, NULL, 0);
2376 if(res)
2377 req->req_file->is_committed = TRUE;
2378 else
2379 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2380 heap_free(header);
2384 static void create_cache_entry(http_request_t *req)
2386 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2387 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2389 WCHAR url[INTERNET_MAX_URL_LENGTH];
2390 WCHAR file_name[MAX_PATH+1];
2391 BOOL b = TRUE;
2393 /* FIXME: We should free previous cache file earlier */
2394 if(req->req_file) {
2395 req_file_release(req->req_file);
2396 req->req_file = NULL;
2398 if(req->hCacheFile) {
2399 CloseHandle(req->hCacheFile);
2400 req->hCacheFile = NULL;
2403 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2404 b = FALSE;
2406 if(b) {
2407 int header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2408 if(header_idx != -1) {
2409 WCHAR *ptr;
2411 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2412 WCHAR *end;
2414 while(*ptr==' ' || *ptr=='\t')
2415 ptr++;
2417 end = strchrW(ptr, ',');
2418 if(!end)
2419 end = ptr + strlenW(ptr);
2421 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2422 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2423 b = FALSE;
2424 break;
2427 ptr = end;
2428 if(*ptr == ',')
2429 ptr++;
2434 if(!b) {
2435 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2436 return;
2438 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2441 b = HTTP_GetRequestURL(req, url);
2442 if(!b) {
2443 WARN("Could not get URL\n");
2444 return;
2447 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2448 if(!b) {
2449 WARN("Could not create cache entry: %08x\n", GetLastError());
2450 return;
2453 create_req_file(file_name, &req->req_file);
2455 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2456 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2457 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2458 WARN("Could not create file: %u\n", GetLastError());
2459 req->hCacheFile = NULL;
2460 return;
2463 if(req->read_size) {
2464 DWORD written;
2466 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2467 if(!b)
2468 FIXME("WriteFile failed: %u\n", GetLastError());
2470 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2471 commit_cache_entry(req);
2475 /* read some more data into the read buffer (the read section must be held) */
2476 static DWORD read_more_data( http_request_t *req, int maxlen )
2478 DWORD res;
2479 int len;
2481 if (req->read_pos)
2483 /* move existing data to the start of the buffer */
2484 if(req->read_size)
2485 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2486 req->read_pos = 0;
2489 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2491 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2492 maxlen - req->read_size, BLOCKING_ALLOW, &len );
2493 if(res == ERROR_SUCCESS)
2494 req->read_size += len;
2496 return res;
2499 /* remove some amount of data from the read buffer (the read section must be held) */
2500 static void remove_data( http_request_t *req, int count )
2502 if (!(req->read_size -= count)) req->read_pos = 0;
2503 else req->read_pos += count;
2506 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2508 int count, bytes_read, pos = 0;
2509 DWORD res;
2511 EnterCriticalSection( &req->read_section );
2512 for (;;)
2514 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2516 if (eol)
2518 count = eol - (req->read_buf + req->read_pos);
2519 bytes_read = count + 1;
2521 else count = bytes_read = req->read_size;
2523 count = min( count, *len - pos );
2524 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2525 pos += count;
2526 remove_data( req, bytes_read );
2527 if (eol) break;
2529 if ((res = read_more_data( req, -1 )))
2531 WARN( "read failed %u\n", res );
2532 LeaveCriticalSection( &req->read_section );
2533 return res;
2535 if (!req->read_size)
2537 *len = 0;
2538 TRACE( "returning empty string\n" );
2539 LeaveCriticalSection( &req->read_section );
2540 return ERROR_SUCCESS;
2543 LeaveCriticalSection( &req->read_section );
2545 if (pos < *len)
2547 if (pos && buffer[pos - 1] == '\r') pos--;
2548 *len = pos + 1;
2550 buffer[*len - 1] = 0;
2551 TRACE( "returning %s\n", debugstr_a(buffer));
2552 return ERROR_SUCCESS;
2555 /* check if we have reached the end of the data to read (the read section must be held) */
2556 static BOOL end_of_read_data( http_request_t *req )
2558 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2561 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, blocking_mode_t blocking_mode)
2563 DWORD res;
2565 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, blocking_mode);
2566 assert(*read <= size);
2568 if(req->hCacheFile) {
2569 if(*read) {
2570 BOOL bres;
2571 DWORD written;
2573 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2574 if(!bres)
2575 FIXME("WriteFile failed: %u\n", GetLastError());
2578 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2579 commit_cache_entry(req);
2582 return res;
2585 /* fetch some more data into the read buffer (the read section must be held) */
2586 static DWORD refill_read_buffer(http_request_t *req, blocking_mode_t blocking_mode, DWORD *read_bytes)
2588 DWORD res, read=0;
2590 if(req->read_size == sizeof(req->read_buf))
2591 return ERROR_SUCCESS;
2593 if(req->read_pos) {
2594 if(req->read_size)
2595 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2596 req->read_pos = 0;
2599 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2600 &read, blocking_mode);
2601 req->read_size += read;
2603 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2604 if(read_bytes)
2605 *read_bytes = read;
2606 return res;
2609 /* return the size of data available to be read immediately (the read section must be held) */
2610 static DWORD get_avail_data( http_request_t *req )
2612 return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2615 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2617 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2618 DWORD avail = 0;
2620 if(is_valid_netconn(req->netconn))
2621 NETCON_query_data_available(req->netconn, &avail);
2622 return netconn_stream->content_length == ~0u
2623 ? avail
2624 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2627 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2629 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2630 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2633 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2634 DWORD *read, blocking_mode_t blocking_mode)
2636 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2637 DWORD res = ERROR_SUCCESS;
2638 int len = 0;
2640 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2642 if(size && is_valid_netconn(req->netconn)) {
2643 if((res = NETCON_recv(req->netconn, buf, size, blocking_mode, &len))) {
2644 len = 0;
2645 if(blocking_mode == BLOCKING_DISALLOW && res == WSAEWOULDBLOCK)
2646 res = ERROR_SUCCESS;
2647 else
2648 netconn_stream->content_length = netconn_stream->content_read;
2649 }else if(!len) {
2650 netconn_stream->content_length = netconn_stream->content_read;
2654 netconn_stream->content_read += *read = len;
2655 TRACE("read %u bytes\n", len);
2656 return res;
2659 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2661 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2662 BYTE buf[1024];
2663 int len;
2665 if(netconn_end_of_data(stream, req))
2666 return TRUE;
2668 do {
2669 if(NETCON_recv(req->netconn, buf, sizeof(buf), BLOCKING_DISALLOW, &len) != ERROR_SUCCESS)
2670 return FALSE;
2672 netconn_stream->content_read += len;
2673 }while(netconn_stream->content_read < netconn_stream->content_length);
2675 return TRUE;
2678 static void netconn_destroy(data_stream_t *stream)
2682 static const data_stream_vtbl_t netconn_stream_vtbl = {
2683 netconn_get_avail_data,
2684 netconn_end_of_data,
2685 netconn_read,
2686 netconn_drain_content,
2687 netconn_destroy
2690 /* read some more data into the read buffer (the read section must be held) */
2691 static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
2693 DWORD res;
2694 int len;
2696 assert(!stream->end_of_data);
2698 if (stream->buf_pos)
2700 /* move existing data to the start of the buffer */
2701 if(stream->buf_size)
2702 memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
2703 stream->buf_pos = 0;
2706 if (maxlen == -1) maxlen = sizeof(stream->buf);
2708 res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2709 maxlen - stream->buf_size, BLOCKING_ALLOW, &len );
2710 if(res == ERROR_SUCCESS)
2711 stream->buf_size += len;
2713 return res;
2716 /* remove some amount of data from the read buffer (the read section must be held) */
2717 static void remove_chunked_data(chunked_stream_t *stream, int count)
2719 if (!(stream->buf_size -= count)) stream->buf_pos = 0;
2720 else stream->buf_pos += count;
2723 /* discard data contents until we reach end of line (the read section must be held) */
2724 static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2726 DWORD res;
2730 BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2731 if (eol)
2733 remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2734 break;
2736 stream->buf_pos = stream->buf_size = 0; /* discard everything */
2737 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2738 } while (stream->buf_size);
2739 return ERROR_SUCCESS;
2742 /* read the size of the next chunk (the read section must be held) */
2743 static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2745 DWORD chunk_size = 0, res;
2747 assert(!stream->chunk_size || stream->chunk_size == ~0u);
2749 if (stream->end_of_data) return ERROR_SUCCESS;
2751 /* read terminator for the previous chunk */
2752 if(!stream->chunk_size && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2753 return res;
2755 for (;;)
2757 while (stream->buf_size)
2759 char ch = stream->buf[stream->buf_pos];
2760 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2761 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2762 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2763 else if (ch == ';' || ch == '\r' || ch == '\n')
2765 TRACE( "reading %u byte chunk\n", chunk_size );
2766 stream->chunk_size = chunk_size;
2767 if (req->contentLength == ~0u) req->contentLength = chunk_size;
2768 else req->contentLength += chunk_size;
2770 if (!chunk_size) stream->end_of_data = TRUE;
2771 return discard_chunked_eol(stream, req);
2773 remove_chunked_data(stream, 1);
2775 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2776 if (!stream->buf_size)
2778 stream->chunk_size = 0;
2779 return ERROR_SUCCESS;
2784 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2786 /* Allow reading only from read buffer */
2787 return 0;
2790 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2792 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2793 return chunked_stream->end_of_data;
2796 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2797 DWORD *read, blocking_mode_t blocking_mode)
2799 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2800 DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;
2802 if(!chunked_stream->chunk_size || chunked_stream->chunk_size == ~0u) {
2803 res = start_next_chunk(chunked_stream, req);
2804 if(res != ERROR_SUCCESS)
2805 return res;
2808 while(size && chunked_stream->chunk_size && !chunked_stream->end_of_data) {
2809 if(chunked_stream->buf_size) {
2810 read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2812 /* this could block */
2813 if(blocking_mode == BLOCKING_DISALLOW && read_bytes == chunked_stream->chunk_size)
2814 break;
2816 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2817 remove_chunked_data(chunked_stream, read_bytes);
2818 }else {
2819 read_bytes = min(size, chunked_stream->chunk_size);
2821 if(blocking_mode == BLOCKING_DISALLOW) {
2822 DWORD avail;
2824 if(!is_valid_netconn(req->netconn) || !NETCON_query_data_available(req->netconn, &avail) || !avail)
2825 break;
2826 if(read_bytes > avail)
2827 read_bytes = avail;
2829 /* this could block */
2830 if(read_bytes == chunked_stream->chunk_size)
2831 break;
2834 res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, BLOCKING_ALLOW, (int*)&read_bytes);
2835 if(res != ERROR_SUCCESS)
2836 break;
2839 chunked_stream->chunk_size -= read_bytes;
2840 size -= read_bytes;
2841 ret_read += read_bytes;
2842 if(size && !chunked_stream->chunk_size) {
2843 assert(blocking_mode != BLOCKING_DISALLOW);
2844 res = start_next_chunk(chunked_stream, req);
2845 if(res != ERROR_SUCCESS)
2846 break;
2849 if(blocking_mode == BLOCKING_ALLOW)
2850 blocking_mode = BLOCKING_DISALLOW;
2853 TRACE("read %u bytes\n", ret_read);
2854 *read = ret_read;
2855 return res;
2858 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2860 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2862 remove_chunked_data(chunked_stream, chunked_stream->buf_size);
2863 return chunked_stream->end_of_data;
2866 static void chunked_destroy(data_stream_t *stream)
2868 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2869 heap_free(chunked_stream);
2872 static const data_stream_vtbl_t chunked_stream_vtbl = {
2873 chunked_get_avail_data,
2874 chunked_end_of_data,
2875 chunked_read,
2876 chunked_drain_content,
2877 chunked_destroy
2880 /* set the request content length based on the headers */
2881 static DWORD set_content_length(http_request_t *request)
2883 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2884 static const WCHAR headW[] = {'H','E','A','D',0};
2885 WCHAR encoding[20];
2886 DWORD size;
2888 if(request->status_code == HTTP_STATUS_NO_CONTENT || !strcmpW(request->verb, headW)) {
2889 request->contentLength = request->netconn_stream.content_length = 0;
2890 return ERROR_SUCCESS;
2893 size = sizeof(request->contentLength);
2894 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2895 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2896 request->contentLength = ~0u;
2897 request->netconn_stream.content_length = request->contentLength;
2898 request->netconn_stream.content_read = request->read_size;
2900 size = sizeof(encoding);
2901 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2902 !strcmpiW(encoding, szChunked))
2904 chunked_stream_t *chunked_stream;
2906 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2907 if(!chunked_stream)
2908 return ERROR_OUTOFMEMORY;
2910 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2911 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2912 chunked_stream->chunk_size = ~0u;
2913 chunked_stream->end_of_data = FALSE;
2915 if(request->read_size) {
2916 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2917 chunked_stream->buf_size = request->read_size;
2918 request->read_size = request->read_pos = 0;
2921 request->data_stream = &chunked_stream->data_stream;
2922 request->contentLength = ~0u;
2923 request->read_chunked = TRUE;
2926 if(request->decoding) {
2927 int encoding_idx;
2929 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2930 static const WCHAR gzipW[] = {'g','z','i','p',0};
2932 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2933 if(encoding_idx != -1) {
2934 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2935 HTTP_DeleteCustomHeader(request, encoding_idx);
2936 return init_gzip_stream(request, TRUE);
2938 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2939 HTTP_DeleteCustomHeader(request, encoding_idx);
2940 return init_gzip_stream(request, FALSE);
2945 return ERROR_SUCCESS;
2948 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2950 INTERNET_ASYNC_RESULT iar;
2952 iar.dwResult = result;
2953 iar.dwError = error;
2955 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2956 sizeof(INTERNET_ASYNC_RESULT));
2959 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2961 DWORD res, read = 0, avail = 0;
2962 blocking_mode_t mode;
2964 TRACE("%p\n", req);
2966 EnterCriticalSection( &req->read_section );
2968 mode = first_notif && req->read_size ? BLOCKING_DISALLOW : BLOCKING_ALLOW;
2969 res = refill_read_buffer(req, mode, &read);
2970 if(res == ERROR_SUCCESS)
2971 avail = get_avail_data(req);
2973 LeaveCriticalSection( &req->read_section );
2975 if(res != ERROR_SUCCESS || (mode != BLOCKING_DISALLOW && !read)) {
2976 WARN("res %u read %u, closing connection\n", res, read);
2977 http_release_netconn(req, FALSE);
2980 if(res != ERROR_SUCCESS) {
2981 send_request_complete(req, 0, res);
2982 return;
2985 if(ret_size)
2986 *ret_size = avail;
2987 if(first_notif)
2988 avail = 0;
2990 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
2993 /* read data from the http connection (the read section must be held) */
2994 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
2996 DWORD current_read = 0, ret_read = 0;
2997 blocking_mode_t blocking_mode;
2998 DWORD res = ERROR_SUCCESS;
3000 blocking_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? BLOCKING_ALLOW : BLOCKING_WAITALL;
3002 EnterCriticalSection( &req->read_section );
3004 if(req->read_size) {
3005 ret_read = min(size, req->read_size);
3006 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3007 req->read_size -= ret_read;
3008 req->read_pos += ret_read;
3009 if(blocking_mode == BLOCKING_ALLOW)
3010 blocking_mode = BLOCKING_DISALLOW;
3013 if(ret_read < size) {
3014 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, blocking_mode);
3015 ret_read += current_read;
3018 LeaveCriticalSection( &req->read_section );
3020 *read = ret_read;
3021 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3023 if(size && !ret_read)
3024 http_release_netconn(req, res == ERROR_SUCCESS);
3026 return res;
3029 static BOOL drain_content(http_request_t *req, BOOL blocking)
3031 BOOL ret;
3033 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
3034 return FALSE;
3036 if(!strcmpW(req->verb, szHEAD))
3037 return TRUE;
3039 if(!blocking)
3040 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3042 EnterCriticalSection( &req->read_section );
3044 while(1) {
3045 DWORD bytes_read, res;
3046 BYTE buf[4096];
3048 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3049 if(res != ERROR_SUCCESS) {
3050 ret = FALSE;
3051 break;
3053 if(!bytes_read) {
3054 ret = TRUE;
3055 break;
3059 LeaveCriticalSection( &req->read_section );
3060 return ret;
3063 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3065 http_request_t *req = (http_request_t*)hdr;
3066 DWORD res;
3068 EnterCriticalSection( &req->read_section );
3069 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3070 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3072 res = HTTPREQ_Read(req, buffer, size, read, TRUE);
3073 if(res == ERROR_SUCCESS)
3074 res = hdr->dwError;
3075 LeaveCriticalSection( &req->read_section );
3077 return res;
3080 typedef struct {
3081 task_header_t hdr;
3082 void *buf;
3083 DWORD size;
3084 DWORD *ret_read;
3085 } read_file_ex_task_t;
3087 static void AsyncReadFileExProc(task_header_t *hdr)
3089 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3090 http_request_t *req = (http_request_t*)task->hdr.hdr;
3091 DWORD res;
3093 TRACE("INTERNETREADFILEEXW %p\n", task->hdr.hdr);
3095 res = HTTPREQ_Read(req, task->buf, task->size, task->ret_read, TRUE);
3096 send_request_complete(req, res == ERROR_SUCCESS, res);
3099 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3100 DWORD flags, DWORD_PTR context)
3103 http_request_t *req = (http_request_t*)hdr;
3104 DWORD res, read, cread, error = ERROR_SUCCESS;
3106 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3107 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3109 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3111 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
3113 read_file_ex_task_t *task;
3115 if (TryEnterCriticalSection( &req->read_section ))
3117 if (get_avail_data(req))
3119 res = HTTPREQ_Read(req, buf, size, &read, FALSE);
3120 LeaveCriticalSection( &req->read_section );
3121 goto done;
3123 LeaveCriticalSection( &req->read_section );
3126 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3127 task->buf = buf;
3128 task->size = size;
3129 task->ret_read = ret_read;
3131 INTERNET_AsyncCall(&task->hdr);
3133 return ERROR_IO_PENDING;
3136 read = 0;
3138 EnterCriticalSection( &req->read_section );
3139 if(hdr->dwError == ERROR_SUCCESS)
3140 hdr->dwError = INTERNET_HANDLE_IN_USE;
3141 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3142 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3144 while(1) {
3145 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, !(flags & IRF_NO_WAIT));
3146 if(res != ERROR_SUCCESS)
3147 break;
3149 read += cread;
3150 if(read == size || end_of_read_data(req))
3151 break;
3153 LeaveCriticalSection( &req->read_section );
3155 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3156 &cread, sizeof(cread));
3157 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3158 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3160 EnterCriticalSection( &req->read_section );
3163 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3164 hdr->dwError = ERROR_SUCCESS;
3165 else
3166 error = hdr->dwError;
3168 LeaveCriticalSection( &req->read_section );
3170 done:
3171 *ret_read = read;
3172 if (res == ERROR_SUCCESS) {
3173 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3174 &read, sizeof(read));
3177 return res==ERROR_SUCCESS ? error : res;
3180 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3182 DWORD res;
3183 http_request_t *request = (http_request_t*)hdr;
3185 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3187 *written = 0;
3188 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3189 if (res == ERROR_SUCCESS)
3190 request->bytesWritten += *written;
3192 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3193 return res;
3196 typedef struct {
3197 task_header_t hdr;
3198 DWORD *ret_size;
3199 } http_data_available_task_t;
3201 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3203 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3205 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3208 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3210 http_request_t *req = (http_request_t*)hdr;
3212 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3214 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3216 http_data_available_task_t *task;
3218 /* never wait, if we can't enter the section we queue an async request right away */
3219 if (TryEnterCriticalSection( &req->read_section ))
3221 refill_read_buffer(req, BLOCKING_DISALLOW, NULL);
3222 if ((*available = get_avail_data( req ))) goto done;
3223 if (end_of_read_data( req )) goto done;
3224 LeaveCriticalSection( &req->read_section );
3227 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3228 task->ret_size = available;
3229 INTERNET_AsyncCall(&task->hdr);
3230 return ERROR_IO_PENDING;
3233 EnterCriticalSection( &req->read_section );
3235 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3237 refill_read_buffer( req, BLOCKING_ALLOW, NULL );
3238 *available = get_avail_data( req );
3241 done:
3242 LeaveCriticalSection( &req->read_section );
3244 TRACE( "returning %u\n", *available );
3245 return ERROR_SUCCESS;
3248 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3250 http_request_t *req = (http_request_t*)hdr;
3252 TRACE("(%p)\n", req);
3254 if(!req->req_file) {
3255 WARN("No cache file name available\n");
3256 return ERROR_FILE_NOT_FOUND;
3259 *ret = req_file_addref(req->req_file);
3260 return ERROR_SUCCESS;
3263 static const object_vtbl_t HTTPREQVtbl = {
3264 HTTPREQ_Destroy,
3265 HTTPREQ_CloseConnection,
3266 HTTPREQ_QueryOption,
3267 HTTPREQ_SetOption,
3268 HTTPREQ_ReadFile,
3269 HTTPREQ_ReadFileEx,
3270 HTTPREQ_WriteFile,
3271 HTTPREQ_QueryDataAvailable,
3272 NULL,
3273 HTTPREQ_LockRequestFile
3276 /***********************************************************************
3277 * HTTP_HttpOpenRequestW (internal)
3279 * Open a HTTP request handle
3281 * RETURNS
3282 * HINTERNET a HTTP request handle on success
3283 * NULL on failure
3286 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3287 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3288 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3289 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3291 appinfo_t *hIC = session->appInfo;
3292 http_request_t *request;
3293 DWORD len;
3295 TRACE("-->\n");
3297 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3298 if(!request)
3299 return ERROR_OUTOFMEMORY;
3301 request->hdr.htype = WH_HHTTPREQ;
3302 request->hdr.dwFlags = dwFlags;
3303 request->hdr.dwContext = dwContext;
3304 request->contentLength = ~0u;
3306 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3307 request->data_stream = &request->netconn_stream.data_stream;
3308 request->connect_timeout = session->connect_timeout;
3309 request->send_timeout = session->send_timeout;
3310 request->receive_timeout = session->receive_timeout;
3312 InitializeCriticalSection( &request->read_section );
3313 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3315 WININET_AddRef( &session->hdr );
3316 request->session = session;
3317 list_add_head( &session->hdr.children, &request->hdr.entry );
3319 request->server = get_server(session->hostName, session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3320 if(!request->server) {
3321 WININET_Release(&request->hdr);
3322 return ERROR_OUTOFMEMORY;
3325 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3326 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3327 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3328 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3330 if (lpszObjectName && *lpszObjectName) {
3331 HRESULT rc;
3333 len = 0;
3334 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3335 if (rc != E_POINTER)
3336 len = strlenW(lpszObjectName)+1;
3337 request->path = heap_alloc(len*sizeof(WCHAR));
3338 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3339 URL_ESCAPE_SPACES_ONLY);
3340 if (rc != S_OK)
3342 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3343 strcpyW(request->path,lpszObjectName);
3345 }else {
3346 static const WCHAR slashW[] = {'/',0};
3348 request->path = heap_strdupW(slashW);
3351 if (lpszReferrer && *lpszReferrer)
3352 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3354 if (lpszAcceptTypes)
3356 int i;
3357 for (i = 0; lpszAcceptTypes[i]; i++)
3359 if (!*lpszAcceptTypes[i]) continue;
3360 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3361 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3362 HTTP_ADDHDR_FLAG_REQ |
3363 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
3367 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3368 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3370 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3372 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3373 HTTP_DealWithProxy( hIC, session, request );
3375 INTERNET_SendCallback(&session->hdr, dwContext,
3376 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3377 sizeof(HINTERNET));
3379 TRACE("<-- (%p)\n", request);
3381 *ret = request->hdr.hInternet;
3382 return ERROR_SUCCESS;
3385 /***********************************************************************
3386 * HttpOpenRequestW (WININET.@)
3388 * Open a HTTP request handle
3390 * RETURNS
3391 * HINTERNET a HTTP request handle on success
3392 * NULL on failure
3395 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3396 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3397 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3398 DWORD dwFlags, DWORD_PTR dwContext)
3400 http_session_t *session;
3401 HINTERNET handle = NULL;
3402 DWORD res;
3404 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3405 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3406 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3407 dwFlags, dwContext);
3408 if(lpszAcceptTypes!=NULL)
3410 int i;
3411 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3412 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3415 session = (http_session_t*) get_handle_object( hHttpSession );
3416 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3418 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3419 goto lend;
3423 * My tests seem to show that the windows version does not
3424 * become asynchronous until after this point. And anyhow
3425 * if this call was asynchronous then how would you get the
3426 * necessary HINTERNET pointer returned by this function.
3429 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3430 lpszVersion, lpszReferrer, lpszAcceptTypes,
3431 dwFlags, dwContext, &handle);
3432 lend:
3433 if( session )
3434 WININET_Release( &session->hdr );
3435 TRACE("returning %p\n", handle);
3436 if(res != ERROR_SUCCESS)
3437 SetLastError(res);
3438 return handle;
3441 static const LPCWSTR header_lookup[] = {
3442 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3443 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3444 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3445 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3446 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3447 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3448 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3449 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3450 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3451 szDate, /* HTTP_QUERY_DATE = 9 */
3452 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3453 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3454 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3455 szURI, /* HTTP_QUERY_URI = 13 */
3456 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3457 NULL, /* HTTP_QUERY_COST = 15 */
3458 NULL, /* HTTP_QUERY_LINK = 16 */
3459 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3460 NULL, /* HTTP_QUERY_VERSION = 18 */
3461 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3462 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3463 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3464 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3465 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3466 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3467 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3468 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3469 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3470 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3471 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3472 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3473 NULL, /* HTTP_QUERY_FROM = 31 */
3474 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3475 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3476 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3477 szReferer, /* HTTP_QUERY_REFERER = 35 */
3478 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3479 szServer, /* HTTP_QUERY_SERVER = 37 */
3480 NULL, /* HTTP_TITLE = 38 */
3481 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3482 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3483 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3484 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3485 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3486 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3487 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3488 NULL, /* HTTP_QUERY_REFRESH = 46 */
3489 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3490 szAge, /* HTTP_QUERY_AGE = 48 */
3491 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3492 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3493 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3494 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3495 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3496 szETag, /* HTTP_QUERY_ETAG = 54 */
3497 hostW, /* HTTP_QUERY_HOST = 55 */
3498 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3499 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3500 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3501 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3502 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3503 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3504 szRange, /* HTTP_QUERY_RANGE = 62 */
3505 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3506 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3507 szVary, /* HTTP_QUERY_VARY = 65 */
3508 szVia, /* HTTP_QUERY_VIA = 66 */
3509 szWarning, /* HTTP_QUERY_WARNING = 67 */
3510 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3511 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3512 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3515 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3517 /***********************************************************************
3518 * HTTP_HttpQueryInfoW (internal)
3520 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3521 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3523 LPHTTPHEADERW lphttpHdr = NULL;
3524 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3525 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3526 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3527 INT index = -1;
3529 /* Find requested header structure */
3530 switch (level)
3532 case HTTP_QUERY_CUSTOM:
3533 if (!lpBuffer) return ERROR_INVALID_PARAMETER;
3534 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3535 break;
3536 case HTTP_QUERY_RAW_HEADERS_CRLF:
3538 LPWSTR headers;
3539 DWORD len = 0;
3540 DWORD res = ERROR_INVALID_PARAMETER;
3542 if (request_only)
3543 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3544 else
3545 headers = build_response_header(request, TRUE);
3546 if (!headers)
3547 return ERROR_OUTOFMEMORY;
3549 len = strlenW(headers) * sizeof(WCHAR);
3550 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3552 len += sizeof(WCHAR);
3553 res = ERROR_INSUFFICIENT_BUFFER;
3555 else if (lpBuffer)
3557 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3558 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3559 res = ERROR_SUCCESS;
3561 *lpdwBufferLength = len;
3563 heap_free(headers);
3564 return res;
3566 case HTTP_QUERY_RAW_HEADERS:
3568 LPWSTR headers;
3569 DWORD len;
3571 if (request_only)
3572 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3573 else
3574 headers = build_response_header(request, FALSE);
3575 if (!headers)
3576 return ERROR_OUTOFMEMORY;
3578 len = strlenW(headers) * sizeof(WCHAR);
3579 if (len > *lpdwBufferLength)
3581 *lpdwBufferLength = len;
3582 heap_free(headers);
3583 return ERROR_INSUFFICIENT_BUFFER;
3586 if (lpBuffer)
3588 DWORD i;
3590 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3592 for (i = 0; i < len / sizeof(WCHAR); i++)
3594 if (headers[i] == '\n')
3595 headers[i] = 0;
3597 memcpy(lpBuffer, headers, len);
3599 *lpdwBufferLength = len - sizeof(WCHAR);
3601 heap_free(headers);
3602 return ERROR_SUCCESS;
3604 case HTTP_QUERY_STATUS_TEXT:
3605 if (request->statusText)
3607 DWORD len = strlenW(request->statusText);
3608 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3610 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3611 return ERROR_INSUFFICIENT_BUFFER;
3613 if (lpBuffer)
3615 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3616 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3618 *lpdwBufferLength = len * sizeof(WCHAR);
3619 return ERROR_SUCCESS;
3621 break;
3622 case HTTP_QUERY_VERSION:
3623 if (request->version)
3625 DWORD len = strlenW(request->version);
3626 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3628 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3629 return ERROR_INSUFFICIENT_BUFFER;
3631 if (lpBuffer)
3633 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3634 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3636 *lpdwBufferLength = len * sizeof(WCHAR);
3637 return ERROR_SUCCESS;
3639 break;
3640 case HTTP_QUERY_CONTENT_ENCODING:
3641 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3642 requested_index,request_only);
3643 break;
3644 case HTTP_QUERY_STATUS_CODE: {
3645 DWORD res = ERROR_SUCCESS;
3647 if(request_only)
3648 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3650 if(requested_index)
3651 break;
3653 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3654 if(*lpdwBufferLength >= sizeof(DWORD))
3655 *(DWORD*)lpBuffer = request->status_code;
3656 else
3657 res = ERROR_INSUFFICIENT_BUFFER;
3658 *lpdwBufferLength = sizeof(DWORD);
3659 }else {
3660 WCHAR buf[12];
3661 DWORD size;
3662 static const WCHAR formatW[] = {'%','u',0};
3664 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3666 if(size <= *lpdwBufferLength) {
3667 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3668 }else {
3669 size += sizeof(WCHAR);
3670 res = ERROR_INSUFFICIENT_BUFFER;
3673 *lpdwBufferLength = size;
3675 return res;
3677 default:
3678 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3680 if (level < LAST_TABLE_HEADER && header_lookup[level])
3681 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3682 requested_index,request_only);
3685 if (index >= 0)
3686 lphttpHdr = &request->custHeaders[index];
3688 /* Ensure header satisfies requested attributes */
3689 if (!lphttpHdr ||
3690 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3691 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3693 return ERROR_HTTP_HEADER_NOT_FOUND;
3696 /* coalesce value to requested type */
3697 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3699 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3700 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3702 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3704 time_t tmpTime;
3705 struct tm tmpTM;
3706 SYSTEMTIME *STHook;
3708 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3710 tmpTM = *gmtime(&tmpTime);
3711 STHook = (SYSTEMTIME *)lpBuffer;
3712 STHook->wDay = tmpTM.tm_mday;
3713 STHook->wHour = tmpTM.tm_hour;
3714 STHook->wMilliseconds = 0;
3715 STHook->wMinute = tmpTM.tm_min;
3716 STHook->wDayOfWeek = tmpTM.tm_wday;
3717 STHook->wMonth = tmpTM.tm_mon + 1;
3718 STHook->wSecond = tmpTM.tm_sec;
3719 STHook->wYear = 1900+tmpTM.tm_year;
3721 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3722 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3723 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3725 else if (lphttpHdr->lpszValue)
3727 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3729 if (len > *lpdwBufferLength)
3731 *lpdwBufferLength = len;
3732 return ERROR_INSUFFICIENT_BUFFER;
3734 if (lpBuffer)
3736 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3737 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3739 *lpdwBufferLength = len - sizeof(WCHAR);
3741 if (lpdwIndex) (*lpdwIndex)++;
3742 return ERROR_SUCCESS;
3745 /***********************************************************************
3746 * HttpQueryInfoW (WININET.@)
3748 * Queries for information about an HTTP request
3750 * RETURNS
3751 * TRUE on success
3752 * FALSE on failure
3755 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3756 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3758 http_request_t *request;
3759 DWORD res;
3761 if (TRACE_ON(wininet)) {
3762 #define FE(x) { x, #x }
3763 static const wininet_flag_info query_flags[] = {
3764 FE(HTTP_QUERY_MIME_VERSION),
3765 FE(HTTP_QUERY_CONTENT_TYPE),
3766 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3767 FE(HTTP_QUERY_CONTENT_ID),
3768 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3769 FE(HTTP_QUERY_CONTENT_LENGTH),
3770 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3771 FE(HTTP_QUERY_ALLOW),
3772 FE(HTTP_QUERY_PUBLIC),
3773 FE(HTTP_QUERY_DATE),
3774 FE(HTTP_QUERY_EXPIRES),
3775 FE(HTTP_QUERY_LAST_MODIFIED),
3776 FE(HTTP_QUERY_MESSAGE_ID),
3777 FE(HTTP_QUERY_URI),
3778 FE(HTTP_QUERY_DERIVED_FROM),
3779 FE(HTTP_QUERY_COST),
3780 FE(HTTP_QUERY_LINK),
3781 FE(HTTP_QUERY_PRAGMA),
3782 FE(HTTP_QUERY_VERSION),
3783 FE(HTTP_QUERY_STATUS_CODE),
3784 FE(HTTP_QUERY_STATUS_TEXT),
3785 FE(HTTP_QUERY_RAW_HEADERS),
3786 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3787 FE(HTTP_QUERY_CONNECTION),
3788 FE(HTTP_QUERY_ACCEPT),
3789 FE(HTTP_QUERY_ACCEPT_CHARSET),
3790 FE(HTTP_QUERY_ACCEPT_ENCODING),
3791 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3792 FE(HTTP_QUERY_AUTHORIZATION),
3793 FE(HTTP_QUERY_CONTENT_ENCODING),
3794 FE(HTTP_QUERY_FORWARDED),
3795 FE(HTTP_QUERY_FROM),
3796 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3797 FE(HTTP_QUERY_LOCATION),
3798 FE(HTTP_QUERY_ORIG_URI),
3799 FE(HTTP_QUERY_REFERER),
3800 FE(HTTP_QUERY_RETRY_AFTER),
3801 FE(HTTP_QUERY_SERVER),
3802 FE(HTTP_QUERY_TITLE),
3803 FE(HTTP_QUERY_USER_AGENT),
3804 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3805 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3806 FE(HTTP_QUERY_ACCEPT_RANGES),
3807 FE(HTTP_QUERY_SET_COOKIE),
3808 FE(HTTP_QUERY_COOKIE),
3809 FE(HTTP_QUERY_REQUEST_METHOD),
3810 FE(HTTP_QUERY_REFRESH),
3811 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3812 FE(HTTP_QUERY_AGE),
3813 FE(HTTP_QUERY_CACHE_CONTROL),
3814 FE(HTTP_QUERY_CONTENT_BASE),
3815 FE(HTTP_QUERY_CONTENT_LOCATION),
3816 FE(HTTP_QUERY_CONTENT_MD5),
3817 FE(HTTP_QUERY_CONTENT_RANGE),
3818 FE(HTTP_QUERY_ETAG),
3819 FE(HTTP_QUERY_HOST),
3820 FE(HTTP_QUERY_IF_MATCH),
3821 FE(HTTP_QUERY_IF_NONE_MATCH),
3822 FE(HTTP_QUERY_IF_RANGE),
3823 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3824 FE(HTTP_QUERY_MAX_FORWARDS),
3825 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3826 FE(HTTP_QUERY_RANGE),
3827 FE(HTTP_QUERY_TRANSFER_ENCODING),
3828 FE(HTTP_QUERY_UPGRADE),
3829 FE(HTTP_QUERY_VARY),
3830 FE(HTTP_QUERY_VIA),
3831 FE(HTTP_QUERY_WARNING),
3832 FE(HTTP_QUERY_CUSTOM)
3834 static const wininet_flag_info modifier_flags[] = {
3835 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3836 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3837 FE(HTTP_QUERY_FLAG_NUMBER),
3838 FE(HTTP_QUERY_FLAG_COALESCE)
3840 #undef FE
3841 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3842 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3843 DWORD i;
3845 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3846 TRACE(" Attribute:");
3847 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3848 if (query_flags[i].val == info) {
3849 TRACE(" %s", query_flags[i].name);
3850 break;
3853 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3854 TRACE(" Unknown (%08x)", info);
3857 TRACE(" Modifier:");
3858 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3859 if (modifier_flags[i].val & info_mod) {
3860 TRACE(" %s", modifier_flags[i].name);
3861 info_mod &= ~ modifier_flags[i].val;
3865 if (info_mod) {
3866 TRACE(" Unknown (%08x)", info_mod);
3868 TRACE("\n");
3871 request = (http_request_t*) get_handle_object( hHttpRequest );
3872 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3874 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3875 goto lend;
3878 if (lpBuffer == NULL)
3879 *lpdwBufferLength = 0;
3880 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3881 lpBuffer, lpdwBufferLength, lpdwIndex);
3883 lend:
3884 if( request )
3885 WININET_Release( &request->hdr );
3887 TRACE("%u <--\n", res);
3888 if(res != ERROR_SUCCESS)
3889 SetLastError(res);
3890 return res == ERROR_SUCCESS;
3893 /***********************************************************************
3894 * HttpQueryInfoA (WININET.@)
3896 * Queries for information about an HTTP request
3898 * RETURNS
3899 * TRUE on success
3900 * FALSE on failure
3903 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3904 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3906 BOOL result;
3907 DWORD len;
3908 WCHAR* bufferW;
3910 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3912 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3913 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3915 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3916 lpdwBufferLength, lpdwIndex );
3919 if (lpBuffer)
3921 DWORD alloclen;
3922 len = (*lpdwBufferLength)*sizeof(WCHAR);
3923 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3925 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3926 if (alloclen < len)
3927 alloclen = len;
3929 else
3930 alloclen = len;
3931 bufferW = heap_alloc(alloclen);
3932 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3933 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3934 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3935 } else
3937 bufferW = NULL;
3938 len = 0;
3941 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3942 &len, lpdwIndex );
3943 if( result )
3945 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3946 lpBuffer, *lpdwBufferLength, NULL, NULL );
3947 *lpdwBufferLength = len - 1;
3949 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3951 else
3952 /* since the strings being returned from HttpQueryInfoW should be
3953 * only ASCII characters, it is reasonable to assume that all of
3954 * the Unicode characters can be reduced to a single byte */
3955 *lpdwBufferLength = len / sizeof(WCHAR);
3957 heap_free( bufferW );
3958 return result;
3961 /***********************************************************************
3962 * HTTP_GetRedirectURL (internal)
3964 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
3966 static WCHAR szHttp[] = {'h','t','t','p',0};
3967 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3968 http_session_t *session = request->session;
3969 URL_COMPONENTSW urlComponents;
3970 DWORD url_length = 0;
3971 LPWSTR orig_url;
3972 LPWSTR combined_url;
3974 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3975 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3976 urlComponents.dwSchemeLength = 0;
3977 urlComponents.lpszHostName = request->server->name;
3978 urlComponents.dwHostNameLength = 0;
3979 urlComponents.nPort = request->server->port;
3980 urlComponents.lpszUserName = session->userName;
3981 urlComponents.dwUserNameLength = 0;
3982 urlComponents.lpszPassword = NULL;
3983 urlComponents.dwPasswordLength = 0;
3984 urlComponents.lpszUrlPath = request->path;
3985 urlComponents.dwUrlPathLength = 0;
3986 urlComponents.lpszExtraInfo = NULL;
3987 urlComponents.dwExtraInfoLength = 0;
3989 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
3990 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3991 return NULL;
3993 orig_url = heap_alloc(url_length);
3995 /* convert from bytes to characters */
3996 url_length = url_length / sizeof(WCHAR) - 1;
3997 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
3999 heap_free(orig_url);
4000 return NULL;
4003 url_length = 0;
4004 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
4005 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4007 heap_free(orig_url);
4008 return NULL;
4010 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4012 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
4014 heap_free(orig_url);
4015 heap_free(combined_url);
4016 return NULL;
4018 heap_free(orig_url);
4019 return combined_url;
4023 /***********************************************************************
4024 * HTTP_HandleRedirect (internal)
4026 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4028 http_session_t *session = request->session;
4029 WCHAR path[INTERNET_MAX_PATH_LENGTH];
4030 int index;
4032 if(lpszUrl[0]=='/')
4034 /* if it's an absolute path, keep the same session info */
4035 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4037 else
4039 URL_COMPONENTSW urlComponents;
4040 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4041 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4042 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4043 BOOL custom_port = FALSE;
4045 static const WCHAR httpW[] = {'h','t','t','p',0};
4046 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
4048 userName[0] = 0;
4049 hostName[0] = 0;
4050 protocol[0] = 0;
4052 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4053 urlComponents.lpszScheme = protocol;
4054 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4055 urlComponents.lpszHostName = hostName;
4056 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4057 urlComponents.lpszUserName = userName;
4058 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4059 urlComponents.lpszPassword = NULL;
4060 urlComponents.dwPasswordLength = 0;
4061 urlComponents.lpszUrlPath = path;
4062 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4063 urlComponents.lpszExtraInfo = NULL;
4064 urlComponents.dwExtraInfoLength = 0;
4065 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4066 return INTERNET_GetLastError();
4068 if(!strcmpiW(protocol, httpW)) {
4069 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4070 TRACE("redirect from secure page to non-secure page\n");
4071 /* FIXME: warn about from secure redirect to non-secure page */
4072 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4075 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4076 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4077 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4078 custom_port = TRUE;
4079 }else if(!strcmpiW(protocol, httpsW)) {
4080 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4081 TRACE("redirect from non-secure page to secure page\n");
4082 /* FIXME: notify about redirect to secure page */
4083 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4086 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4087 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4088 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4089 custom_port = TRUE;
4092 heap_free(session->hostName);
4094 if(custom_port) {
4095 int len;
4096 static const WCHAR fmt[] = {'%','s',':','%','u',0};
4097 len = lstrlenW(hostName);
4098 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4099 session->hostName = heap_alloc(len*sizeof(WCHAR));
4100 sprintfW(session->hostName, fmt, hostName, urlComponents.nPort);
4102 else
4103 session->hostName = heap_strdupW(hostName);
4104 session->hostPort = urlComponents.nPort;
4106 HTTP_ProcessHeader(request, hostW, session->hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4108 heap_free(session->userName);
4109 session->userName = NULL;
4110 if (userName[0])
4111 session->userName = heap_strdupW(userName);
4113 reset_data_stream(request);
4115 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4116 server_t *new_server;
4118 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4119 server_release(request->server);
4120 request->server = new_server;
4123 heap_free(request->path);
4124 request->path=NULL;
4125 if (*path)
4127 DWORD needed = 0;
4128 HRESULT rc;
4130 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4131 if (rc != E_POINTER)
4132 needed = strlenW(path)+1;
4133 request->path = heap_alloc(needed*sizeof(WCHAR));
4134 rc = UrlEscapeW(path, request->path, &needed,
4135 URL_ESCAPE_SPACES_ONLY);
4136 if (rc != S_OK)
4138 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4139 strcpyW(request->path,path);
4143 /* Remove custom content-type/length headers on redirects. */
4144 index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
4145 if (0 <= index)
4146 HTTP_DeleteCustomHeader(request, index);
4147 index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
4148 if (0 <= index)
4149 HTTP_DeleteCustomHeader(request, index);
4151 return ERROR_SUCCESS;
4154 /***********************************************************************
4155 * HTTP_build_req (internal)
4157 * concatenate all the strings in the request together
4159 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4161 LPCWSTR *t;
4162 LPWSTR str;
4164 for( t = list; *t ; t++ )
4165 len += strlenW( *t );
4166 len++;
4168 str = heap_alloc(len*sizeof(WCHAR));
4169 *str = 0;
4171 for( t = list; *t ; t++ )
4172 strcatW( str, *t );
4174 return str;
4177 static void HTTP_InsertCookies(http_request_t *request)
4179 DWORD cookie_size, size, cnt = 0;
4180 HTTPHEADERW *host;
4181 WCHAR *cookies;
4183 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' ',0};
4185 host = HTTP_GetHeader(request, hostW);
4186 if(!host)
4187 return;
4189 if(get_cookie(host->lpszValue, request->path, NULL, &cookie_size, INTERNET_COOKIE_HTTPONLY) != ERROR_SUCCESS)
4190 return;
4192 size = sizeof(cookieW) + cookie_size * sizeof(WCHAR) + sizeof(szCrLf);
4193 if(!(cookies = heap_alloc(size)))
4194 return;
4196 cnt += sprintfW(cookies, cookieW);
4197 get_cookie(host->lpszValue, request->path, cookies+cnt, &cookie_size, INTERNET_COOKIE_HTTPONLY);
4198 strcatW(cookies, szCrLf);
4200 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4202 heap_free(cookies);
4205 static WORD HTTP_ParseWkday(LPCWSTR day)
4207 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4208 { 'm','o','n',0 },
4209 { 't','u','e',0 },
4210 { 'w','e','d',0 },
4211 { 't','h','u',0 },
4212 { 'f','r','i',0 },
4213 { 's','a','t',0 }};
4214 unsigned int i;
4215 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4216 if (!strcmpiW(day, days[i]))
4217 return i;
4219 /* Invalid */
4220 return 7;
4223 static WORD HTTP_ParseMonth(LPCWSTR month)
4225 static const WCHAR jan[] = { 'j','a','n',0 };
4226 static const WCHAR feb[] = { 'f','e','b',0 };
4227 static const WCHAR mar[] = { 'm','a','r',0 };
4228 static const WCHAR apr[] = { 'a','p','r',0 };
4229 static const WCHAR may[] = { 'm','a','y',0 };
4230 static const WCHAR jun[] = { 'j','u','n',0 };
4231 static const WCHAR jul[] = { 'j','u','l',0 };
4232 static const WCHAR aug[] = { 'a','u','g',0 };
4233 static const WCHAR sep[] = { 's','e','p',0 };
4234 static const WCHAR oct[] = { 'o','c','t',0 };
4235 static const WCHAR nov[] = { 'n','o','v',0 };
4236 static const WCHAR dec[] = { 'd','e','c',0 };
4238 if (!strcmpiW(month, jan)) return 1;
4239 if (!strcmpiW(month, feb)) return 2;
4240 if (!strcmpiW(month, mar)) return 3;
4241 if (!strcmpiW(month, apr)) return 4;
4242 if (!strcmpiW(month, may)) return 5;
4243 if (!strcmpiW(month, jun)) return 6;
4244 if (!strcmpiW(month, jul)) return 7;
4245 if (!strcmpiW(month, aug)) return 8;
4246 if (!strcmpiW(month, sep)) return 9;
4247 if (!strcmpiW(month, oct)) return 10;
4248 if (!strcmpiW(month, nov)) return 11;
4249 if (!strcmpiW(month, dec)) return 12;
4250 /* Invalid */
4251 return 0;
4254 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4255 * optionally preceded by whitespace.
4256 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4257 * st, and sets *str to the first character after the time format.
4259 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4261 LPCWSTR ptr = *str;
4262 WCHAR *nextPtr;
4263 unsigned long num;
4265 while (isspaceW(*ptr))
4266 ptr++;
4268 num = strtoulW(ptr, &nextPtr, 10);
4269 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4271 ERR("unexpected time format %s\n", debugstr_w(ptr));
4272 return FALSE;
4274 if (num > 23)
4276 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4277 return FALSE;
4279 ptr = nextPtr + 1;
4280 st->wHour = (WORD)num;
4281 num = strtoulW(ptr, &nextPtr, 10);
4282 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4284 ERR("unexpected time format %s\n", debugstr_w(ptr));
4285 return FALSE;
4287 if (num > 59)
4289 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4290 return FALSE;
4292 ptr = nextPtr + 1;
4293 st->wMinute = (WORD)num;
4294 num = strtoulW(ptr, &nextPtr, 10);
4295 if (!nextPtr || nextPtr <= ptr)
4297 ERR("unexpected time format %s\n", debugstr_w(ptr));
4298 return FALSE;
4300 if (num > 59)
4302 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4303 return FALSE;
4305 ptr = nextPtr + 1;
4306 *str = ptr;
4307 st->wSecond = (WORD)num;
4308 return TRUE;
4311 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4313 static const WCHAR gmt[]= { 'G','M','T',0 };
4314 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4315 LPCWSTR ptr;
4316 SYSTEMTIME st = { 0 };
4317 unsigned long num;
4319 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4320 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4321 *dayPtr = *ptr;
4322 *dayPtr = 0;
4323 st.wDayOfWeek = HTTP_ParseWkday(day);
4324 if (st.wDayOfWeek >= 7)
4326 ERR("unexpected weekday %s\n", debugstr_w(day));
4327 return FALSE;
4330 while (isspaceW(*ptr))
4331 ptr++;
4333 for (monthPtr = month; !isspace(*ptr) &&
4334 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4335 monthPtr++, ptr++)
4336 *monthPtr = *ptr;
4337 *monthPtr = 0;
4338 st.wMonth = HTTP_ParseMonth(month);
4339 if (!st.wMonth || st.wMonth > 12)
4341 ERR("unexpected month %s\n", debugstr_w(month));
4342 return FALSE;
4345 while (isspaceW(*ptr))
4346 ptr++;
4348 num = strtoulW(ptr, &nextPtr, 10);
4349 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4351 ERR("unexpected day %s\n", debugstr_w(ptr));
4352 return FALSE;
4354 ptr = nextPtr;
4355 st.wDay = (WORD)num;
4357 while (isspaceW(*ptr))
4358 ptr++;
4360 if (!HTTP_ParseTime(&st, &ptr))
4361 return FALSE;
4363 while (isspaceW(*ptr))
4364 ptr++;
4366 num = strtoulW(ptr, &nextPtr, 10);
4367 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4369 ERR("unexpected year %s\n", debugstr_w(ptr));
4370 return FALSE;
4372 ptr = nextPtr;
4373 st.wYear = (WORD)num;
4375 while (isspaceW(*ptr))
4376 ptr++;
4378 /* asctime() doesn't report a timezone, but some web servers do, so accept
4379 * with or without GMT.
4381 if (*ptr && strcmpW(ptr, gmt))
4383 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4384 return FALSE;
4386 return SystemTimeToFileTime(&st, ft);
4389 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4391 static const WCHAR gmt[]= { 'G','M','T',0 };
4392 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4393 LPCWSTR ptr;
4394 unsigned long num;
4395 SYSTEMTIME st = { 0 };
4397 ptr = strchrW(value, ',');
4398 if (!ptr)
4399 return FALSE;
4400 if (ptr - value != 3)
4402 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4403 return FALSE;
4405 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4406 day[3] = 0;
4407 st.wDayOfWeek = HTTP_ParseWkday(day);
4408 if (st.wDayOfWeek > 6)
4410 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4411 return FALSE;
4413 ptr++;
4415 while (isspaceW(*ptr))
4416 ptr++;
4418 num = strtoulW(ptr, &nextPtr, 10);
4419 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4421 WARN("unexpected day %s\n", debugstr_w(value));
4422 return FALSE;
4424 ptr = nextPtr;
4425 st.wDay = (WORD)num;
4427 while (isspaceW(*ptr))
4428 ptr++;
4430 for (monthPtr = month; !isspace(*ptr) &&
4431 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4432 monthPtr++, ptr++)
4433 *monthPtr = *ptr;
4434 *monthPtr = 0;
4435 st.wMonth = HTTP_ParseMonth(month);
4436 if (!st.wMonth || st.wMonth > 12)
4438 WARN("unexpected month %s\n", debugstr_w(month));
4439 return FALSE;
4442 while (isspaceW(*ptr))
4443 ptr++;
4445 num = strtoulW(ptr, &nextPtr, 10);
4446 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4448 ERR("unexpected year %s\n", debugstr_w(value));
4449 return FALSE;
4451 ptr = nextPtr;
4452 st.wYear = (WORD)num;
4454 if (!HTTP_ParseTime(&st, &ptr))
4455 return FALSE;
4457 while (isspaceW(*ptr))
4458 ptr++;
4460 if (strcmpW(ptr, gmt))
4462 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4463 return FALSE;
4465 return SystemTimeToFileTime(&st, ft);
4468 static WORD HTTP_ParseWeekday(LPCWSTR day)
4470 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4471 { 'm','o','n','d','a','y',0 },
4472 { 't','u','e','s','d','a','y',0 },
4473 { 'w','e','d','n','e','s','d','a','y',0 },
4474 { 't','h','u','r','s','d','a','y',0 },
4475 { 'f','r','i','d','a','y',0 },
4476 { 's','a','t','u','r','d','a','y',0 }};
4477 unsigned int i;
4478 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4479 if (!strcmpiW(day, days[i]))
4480 return i;
4482 /* Invalid */
4483 return 7;
4486 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4488 static const WCHAR gmt[]= { 'G','M','T',0 };
4489 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4490 LPCWSTR ptr;
4491 unsigned long num;
4492 SYSTEMTIME st = { 0 };
4494 ptr = strchrW(value, ',');
4495 if (!ptr)
4496 return FALSE;
4497 if (ptr - value == 3)
4499 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4500 day[3] = 0;
4501 st.wDayOfWeek = HTTP_ParseWkday(day);
4502 if (st.wDayOfWeek > 6)
4504 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4505 return FALSE;
4508 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4510 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4511 day[ptr - value + 1] = 0;
4512 st.wDayOfWeek = HTTP_ParseWeekday(day);
4513 if (st.wDayOfWeek > 6)
4515 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4516 return FALSE;
4519 else
4521 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4522 return FALSE;
4524 ptr++;
4526 while (isspaceW(*ptr))
4527 ptr++;
4529 num = strtoulW(ptr, &nextPtr, 10);
4530 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4532 ERR("unexpected day %s\n", debugstr_w(value));
4533 return FALSE;
4535 ptr = nextPtr;
4536 st.wDay = (WORD)num;
4538 if (*ptr != '-')
4540 ERR("unexpected month format %s\n", debugstr_w(ptr));
4541 return FALSE;
4543 ptr++;
4545 for (monthPtr = month; *ptr != '-' &&
4546 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4547 monthPtr++, ptr++)
4548 *monthPtr = *ptr;
4549 *monthPtr = 0;
4550 st.wMonth = HTTP_ParseMonth(month);
4551 if (!st.wMonth || st.wMonth > 12)
4553 ERR("unexpected month %s\n", debugstr_w(month));
4554 return FALSE;
4557 if (*ptr != '-')
4559 ERR("unexpected year format %s\n", debugstr_w(ptr));
4560 return FALSE;
4562 ptr++;
4564 num = strtoulW(ptr, &nextPtr, 10);
4565 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4567 ERR("unexpected year %s\n", debugstr_w(value));
4568 return FALSE;
4570 ptr = nextPtr;
4571 st.wYear = (WORD)num;
4573 if (!HTTP_ParseTime(&st, &ptr))
4574 return FALSE;
4576 while (isspaceW(*ptr))
4577 ptr++;
4579 if (strcmpW(ptr, gmt))
4581 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4582 return FALSE;
4584 return SystemTimeToFileTime(&st, ft);
4587 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4589 static const WCHAR zero[] = { '0',0 };
4590 BOOL ret;
4592 if (!strcmpW(value, zero))
4594 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4595 ret = TRUE;
4597 else if (strchrW(value, ','))
4599 ret = HTTP_ParseRfc1123Date(value, ft);
4600 if (!ret)
4602 ret = HTTP_ParseRfc850Date(value, ft);
4603 if (!ret)
4604 ERR("unexpected date format %s\n", debugstr_w(value));
4607 else
4609 ret = HTTP_ParseDateAsAsctime(value, ft);
4610 if (!ret)
4611 ERR("unexpected date format %s\n", debugstr_w(value));
4613 return ret;
4616 static void HTTP_ProcessExpires(http_request_t *request)
4618 BOOL expirationFound = FALSE;
4619 int headerIndex;
4621 /* Look for a Cache-Control header with a max-age directive, as it takes
4622 * precedence over the Expires header.
4624 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4625 if (headerIndex != -1)
4627 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4628 LPWSTR ptr;
4630 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4632 LPWSTR comma = strchrW(ptr, ','), end, equal;
4634 if (comma)
4635 end = comma;
4636 else
4637 end = ptr + strlenW(ptr);
4638 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4640 if (*equal == '=')
4642 static const WCHAR max_age[] = {
4643 'm','a','x','-','a','g','e',0 };
4645 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4647 LPWSTR nextPtr;
4648 unsigned long age;
4650 age = strtoulW(equal + 1, &nextPtr, 10);
4651 if (nextPtr > equal + 1)
4653 LARGE_INTEGER ft;
4655 NtQuerySystemTime( &ft );
4656 /* Age is in seconds, FILETIME resolution is in
4657 * 100 nanosecond intervals.
4659 ft.QuadPart += age * (ULONGLONG)1000000;
4660 request->expires.dwLowDateTime = ft.u.LowPart;
4661 request->expires.dwHighDateTime = ft.u.HighPart;
4662 expirationFound = TRUE;
4666 if (comma)
4668 ptr = comma + 1;
4669 while (isspaceW(*ptr))
4670 ptr++;
4672 else
4673 ptr = NULL;
4676 if (!expirationFound)
4678 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4679 if (headerIndex != -1)
4681 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4682 FILETIME ft;
4684 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4686 expirationFound = TRUE;
4687 request->expires = ft;
4691 if (!expirationFound)
4693 LARGE_INTEGER t;
4695 /* With no known age, default to 10 minutes until expiration. */
4696 NtQuerySystemTime( &t );
4697 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4698 request->expires.dwLowDateTime = t.u.LowPart;
4699 request->expires.dwHighDateTime = t.u.HighPart;
4703 static void HTTP_ProcessLastModified(http_request_t *request)
4705 int headerIndex;
4707 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4708 if (headerIndex != -1)
4710 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4711 FILETIME ft;
4713 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4714 request->last_modified = ft;
4718 static void http_process_keep_alive(http_request_t *req)
4720 int index;
4722 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4723 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4724 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4725 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4726 else
4727 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4730 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4732 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4733 netconn_t *netconn = NULL;
4734 DWORD res;
4736 reset_data_stream(request);
4738 if (request->netconn)
4740 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4742 *reusing = TRUE;
4743 return ERROR_SUCCESS;
4745 else
4747 free_netconn(request->netconn);
4748 request->netconn = NULL;
4752 res = HTTP_ResolveName(request);
4753 if(res != ERROR_SUCCESS)
4754 return res;
4756 EnterCriticalSection(&connection_pool_cs);
4758 while(!list_empty(&request->server->conn_pool)) {
4759 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4760 list_remove(&netconn->pool_entry);
4762 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4763 break;
4765 TRACE("connection %p closed during idle\n", netconn);
4766 free_netconn(netconn);
4767 netconn = NULL;
4770 LeaveCriticalSection(&connection_pool_cs);
4772 if(netconn) {
4773 TRACE("<-- reusing %p netconn\n", netconn);
4774 request->netconn = netconn;
4775 *reusing = TRUE;
4776 return ERROR_SUCCESS;
4779 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4780 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4782 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4783 INTERNET_STATUS_CONNECTING_TO_SERVER,
4784 request->server->addr_str,
4785 strlen(request->server->addr_str)+1);
4787 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4788 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4789 request->connect_timeout, &netconn);
4790 if(res != ERROR_SUCCESS) {
4791 ERR("create_netconn failed: %u\n", res);
4792 return res;
4795 request->netconn = netconn;
4797 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4798 INTERNET_STATUS_CONNECTED_TO_SERVER,
4799 request->server->addr_str, strlen(request->server->addr_str)+1);
4801 *reusing = FALSE;
4802 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4803 return ERROR_SUCCESS;
4806 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4808 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4809 char *ret;
4811 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4812 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4813 if (data_len) memcpy( ret + len - 1, data, data_len );
4814 *out_len = len + data_len - 1;
4815 ret[*out_len] = 0;
4816 return ret;
4819 /***********************************************************************
4820 * HTTP_HttpSendRequestW (internal)
4822 * Sends the specified request to the HTTP server
4824 * RETURNS
4825 * ERROR_SUCCESS on success
4826 * win32 error code on failure
4829 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4830 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4831 DWORD dwContentLength, BOOL bEndRequest)
4833 static const WCHAR szContentLength[] =
4834 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4835 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4836 LPWSTR requestString = NULL;
4837 INT responseLen, cnt;
4838 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4839 DWORD res;
4841 TRACE("--> %p\n", request);
4843 assert(request->hdr.htype == WH_HHTTPREQ);
4845 /* if the verb is NULL default to GET */
4846 if (!request->verb)
4847 request->verb = heap_strdupW(szGET);
4849 if (dwContentLength || strcmpW(request->verb, szGET))
4851 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4852 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4853 request->bytesToWrite = dwContentLength;
4855 if (request->session->appInfo->agent)
4857 WCHAR *agent_header;
4858 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4859 int len;
4861 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4862 agent_header = heap_alloc(len * sizeof(WCHAR));
4863 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4865 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4866 heap_free(agent_header);
4868 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4870 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4871 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4873 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4875 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4876 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4877 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4880 /* add the headers the caller supplied */
4881 if( lpszHeaders && dwHeaderLength )
4882 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4886 DWORD len, data_len = dwOptionalLength;
4887 BOOL reusing_connection;
4888 char *ascii_req;
4890 loop_next = FALSE;
4892 if(redirected) {
4893 request->contentLength = ~0u;
4894 request->bytesToWrite = 0;
4897 if (TRACE_ON(wininet))
4899 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4900 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(request->path));
4903 HTTP_FixURL(request);
4904 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4906 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4908 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4909 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4911 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4912 HTTP_InsertCookies(request);
4914 res = open_http_connection(request, &reusing_connection);
4915 if (res != ERROR_SUCCESS)
4916 break;
4918 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4920 if (request->proxy) secure_proxy_connect = TRUE;
4921 else
4923 res = NETCON_secure_connect(request->netconn, request->server);
4924 if (res != ERROR_SUCCESS)
4926 WARN("failed to upgrade to secure connection\n");
4927 http_release_netconn(request, FALSE);
4928 break;
4932 if (secure_proxy_connect)
4934 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4935 const WCHAR *target = request->server->host_port;
4936 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4938 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4940 WCHAR *url = build_proxy_path_url(request);
4941 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4942 heap_free(url);
4944 else
4945 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4947 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4949 /* send the request as ASCII, tack on the optional data */
4950 if (!lpOptional || redirected || secure_proxy_connect)
4951 data_len = 0;
4953 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
4954 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4956 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4957 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4959 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4960 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4961 heap_free( ascii_req );
4962 if(res != ERROR_SUCCESS) {
4963 TRACE("send failed: %u\n", res);
4964 if(!reusing_connection)
4965 break;
4966 http_release_netconn(request, FALSE);
4967 loop_next = TRUE;
4968 continue;
4971 request->bytesWritten = data_len;
4973 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4974 INTERNET_STATUS_REQUEST_SENT,
4975 &len, sizeof(DWORD));
4977 if (bEndRequest)
4979 DWORD dwBufferSize;
4981 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4982 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
4984 if (HTTP_GetResponseHeaders(request, &responseLen))
4986 http_release_netconn(request, FALSE);
4987 res = ERROR_INTERNET_CONNECTION_ABORTED;
4988 goto lend;
4990 /* FIXME: We should know that connection is closed before sending
4991 * headers. Otherwise wrong callbacks are executed */
4992 if(!responseLen && reusing_connection) {
4993 TRACE("Connection closed by server, reconnecting\n");
4994 http_release_netconn(request, FALSE);
4995 loop_next = TRUE;
4996 continue;
4999 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5000 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5001 sizeof(DWORD));
5003 http_process_keep_alive(request);
5004 HTTP_ProcessCookies(request);
5005 HTTP_ProcessExpires(request);
5006 HTTP_ProcessLastModified(request);
5008 res = set_content_length(request);
5009 if(res != ERROR_SUCCESS)
5010 goto lend;
5011 if(!request->contentLength)
5012 http_release_netconn(request, TRUE);
5014 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5016 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5017 dwBufferSize=sizeof(szNewLocation);
5018 switch(request->status_code) {
5019 case HTTP_STATUS_REDIRECT:
5020 case HTTP_STATUS_MOVED:
5021 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5022 case HTTP_STATUS_REDIRECT_METHOD:
5023 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5024 break;
5026 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5027 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5029 heap_free(request->verb);
5030 request->verb = heap_strdupW(szGET);
5032 http_release_netconn(request, drain_content(request, FALSE));
5033 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5035 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5036 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5037 res = HTTP_HandleRedirect(request, new_url);
5038 if (res == ERROR_SUCCESS)
5040 heap_free(requestString);
5041 loop_next = TRUE;
5043 heap_free( new_url );
5045 redirected = TRUE;
5048 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5050 WCHAR szAuthValue[2048];
5051 dwBufferSize=2048;
5052 if (request->status_code == HTTP_STATUS_DENIED)
5054 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
5055 DWORD dwIndex = 0;
5056 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5058 if (HTTP_DoAuthorization(request, szAuthValue,
5059 &request->authInfo,
5060 request->session->userName,
5061 request->session->password,
5062 Host->lpszValue))
5064 heap_free(requestString);
5065 if(!drain_content(request, TRUE)) {
5066 FIXME("Could not drain content\n");
5067 http_release_netconn(request, FALSE);
5069 loop_next = TRUE;
5070 break;
5074 if(!loop_next) {
5075 TRACE("Cleaning wrong authorization data\n");
5076 destroy_authinfo(request->authInfo);
5077 request->authInfo = NULL;
5080 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5082 DWORD dwIndex = 0;
5083 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5085 if (HTTP_DoAuthorization(request, szAuthValue,
5086 &request->proxyAuthInfo,
5087 request->session->appInfo->proxyUsername,
5088 request->session->appInfo->proxyPassword,
5089 NULL))
5091 heap_free(requestString);
5092 if(!drain_content(request, TRUE)) {
5093 FIXME("Could not drain content\n");
5094 http_release_netconn(request, FALSE);
5096 loop_next = TRUE;
5097 break;
5101 if(!loop_next) {
5102 TRACE("Cleaning wrong proxy authorization data\n");
5103 destroy_authinfo(request->proxyAuthInfo);
5104 request->proxyAuthInfo = NULL;
5108 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5110 int index;
5112 res = NETCON_secure_connect(request->netconn, request->server);
5113 if (res != ERROR_SUCCESS)
5115 WARN("failed to upgrade to secure proxy connection\n");
5116 http_release_netconn( request, FALSE );
5117 break;
5119 index = HTTP_GetCustomHeaderIndex(request, szProxy_Authorization, 0, TRUE);
5120 if (index != -1) HTTP_DeleteCustomHeader(request, index);
5121 destroy_authinfo(request->proxyAuthInfo);
5122 request->proxyAuthInfo = NULL;
5124 secure_proxy_connect = FALSE;
5125 loop_next = TRUE;
5128 else
5129 res = ERROR_SUCCESS;
5131 while (loop_next);
5133 lend:
5134 heap_free(requestString);
5136 /* TODO: send notification for P3P header */
5138 if(res == ERROR_SUCCESS)
5139 create_cache_entry(request);
5141 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5143 if (res == ERROR_SUCCESS) {
5144 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5145 HTTP_ReceiveRequestData(request, TRUE, NULL);
5146 else
5147 send_request_complete(request,
5148 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5149 }else {
5150 send_request_complete(request, 0, res);
5154 TRACE("<--\n");
5155 return res;
5158 typedef struct {
5159 task_header_t hdr;
5160 WCHAR *headers;
5161 DWORD headers_len;
5162 void *optional;
5163 DWORD optional_len;
5164 DWORD content_len;
5165 BOOL end_request;
5166 } send_request_task_t;
5168 /***********************************************************************
5170 * Helper functions for the HttpSendRequest(Ex) functions
5173 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5175 send_request_task_t *task = (send_request_task_t*)hdr;
5176 http_request_t *request = (http_request_t*)task->hdr.hdr;
5178 TRACE("%p\n", request);
5180 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5181 task->optional_len, task->content_len, task->end_request);
5183 heap_free(task->headers);
5187 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5189 DWORD dwBufferSize;
5190 INT responseLen;
5191 DWORD res = ERROR_SUCCESS;
5193 if(!is_valid_netconn(request->netconn)) {
5194 WARN("Not connected\n");
5195 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5196 return ERROR_INTERNET_OPERATION_CANCELLED;
5199 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5200 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5202 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5203 res = ERROR_HTTP_HEADER_NOT_FOUND;
5205 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5206 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5208 /* process cookies here. Is this right? */
5209 http_process_keep_alive(request);
5210 HTTP_ProcessCookies(request);
5211 HTTP_ProcessExpires(request);
5212 HTTP_ProcessLastModified(request);
5214 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5215 if(!request->contentLength)
5216 http_release_netconn(request, TRUE);
5219 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5221 switch(request->status_code) {
5222 case HTTP_STATUS_REDIRECT:
5223 case HTTP_STATUS_MOVED:
5224 case HTTP_STATUS_REDIRECT_METHOD:
5225 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5226 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5227 dwBufferSize=sizeof(szNewLocation);
5228 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5229 break;
5231 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5232 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5234 heap_free(request->verb);
5235 request->verb = heap_strdupW(szGET);
5237 http_release_netconn(request, drain_content(request, FALSE));
5238 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5240 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5241 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5242 res = HTTP_HandleRedirect(request, new_url);
5243 if (res == ERROR_SUCCESS)
5244 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5245 heap_free( new_url );
5251 if(res == ERROR_SUCCESS)
5252 create_cache_entry(request);
5254 if (res == ERROR_SUCCESS && request->contentLength)
5255 HTTP_ReceiveRequestData(request, TRUE, NULL);
5256 else
5257 send_request_complete(request, res == ERROR_SUCCESS, res);
5259 return res;
5262 /***********************************************************************
5263 * HttpEndRequestA (WININET.@)
5265 * Ends an HTTP request that was started by HttpSendRequestEx
5267 * RETURNS
5268 * TRUE if successful
5269 * FALSE on failure
5272 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5273 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5275 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5277 if (lpBuffersOut)
5279 SetLastError(ERROR_INVALID_PARAMETER);
5280 return FALSE;
5283 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5286 typedef struct {
5287 task_header_t hdr;
5288 DWORD flags;
5289 DWORD context;
5290 } end_request_task_t;
5292 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5294 end_request_task_t *task = (end_request_task_t*)hdr;
5295 http_request_t *req = (http_request_t*)task->hdr.hdr;
5297 TRACE("%p\n", req);
5299 HTTP_HttpEndRequestW(req, task->flags, task->context);
5302 /***********************************************************************
5303 * HttpEndRequestW (WININET.@)
5305 * Ends an HTTP request that was started by HttpSendRequestEx
5307 * RETURNS
5308 * TRUE if successful
5309 * FALSE on failure
5312 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5313 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5315 http_request_t *request;
5316 DWORD res;
5318 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5320 if (lpBuffersOut)
5322 SetLastError(ERROR_INVALID_PARAMETER);
5323 return FALSE;
5326 request = (http_request_t*) get_handle_object( hRequest );
5328 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5330 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5331 if (request)
5332 WININET_Release( &request->hdr );
5333 return FALSE;
5335 request->hdr.dwFlags |= dwFlags;
5337 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5339 end_request_task_t *task;
5341 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5342 task->flags = dwFlags;
5343 task->context = dwContext;
5345 INTERNET_AsyncCall(&task->hdr);
5346 res = ERROR_IO_PENDING;
5348 else
5349 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5351 WININET_Release( &request->hdr );
5352 TRACE("%u <--\n", res);
5353 if(res != ERROR_SUCCESS)
5354 SetLastError(res);
5355 return res == ERROR_SUCCESS;
5358 /***********************************************************************
5359 * HttpSendRequestExA (WININET.@)
5361 * Sends the specified request to the HTTP server and allows chunked
5362 * transfers.
5364 * RETURNS
5365 * Success: TRUE
5366 * Failure: FALSE, call GetLastError() for more information.
5368 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5369 LPINTERNET_BUFFERSA lpBuffersIn,
5370 LPINTERNET_BUFFERSA lpBuffersOut,
5371 DWORD dwFlags, DWORD_PTR dwContext)
5373 INTERNET_BUFFERSW BuffersInW;
5374 BOOL rc = FALSE;
5375 DWORD headerlen;
5376 LPWSTR header = NULL;
5378 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5379 lpBuffersOut, dwFlags, dwContext);
5381 if (lpBuffersIn)
5383 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5384 if (lpBuffersIn->lpcszHeader)
5386 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5387 lpBuffersIn->dwHeadersLength,0,0);
5388 header = heap_alloc(headerlen*sizeof(WCHAR));
5389 if (!(BuffersInW.lpcszHeader = header))
5391 SetLastError(ERROR_OUTOFMEMORY);
5392 return FALSE;
5394 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5395 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5396 header, headerlen);
5398 else
5399 BuffersInW.lpcszHeader = NULL;
5400 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5401 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5402 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5403 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5404 BuffersInW.Next = NULL;
5407 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5409 heap_free(header);
5410 return rc;
5413 /***********************************************************************
5414 * HttpSendRequestExW (WININET.@)
5416 * Sends the specified request to the HTTP server and allows chunked
5417 * transfers
5419 * RETURNS
5420 * Success: TRUE
5421 * Failure: FALSE, call GetLastError() for more information.
5423 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5424 LPINTERNET_BUFFERSW lpBuffersIn,
5425 LPINTERNET_BUFFERSW lpBuffersOut,
5426 DWORD dwFlags, DWORD_PTR dwContext)
5428 http_request_t *request;
5429 http_session_t *session;
5430 appinfo_t *hIC;
5431 DWORD res;
5433 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5434 lpBuffersOut, dwFlags, dwContext);
5436 request = (http_request_t*) get_handle_object( hRequest );
5438 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5440 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5441 goto lend;
5444 session = request->session;
5445 assert(session->hdr.htype == WH_HHTTPSESSION);
5446 hIC = session->appInfo;
5447 assert(hIC->hdr.htype == WH_HINIT);
5449 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5451 send_request_task_t *task;
5453 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5454 if (lpBuffersIn)
5456 DWORD size = 0;
5458 if (lpBuffersIn->lpcszHeader)
5460 if (lpBuffersIn->dwHeadersLength == ~0u)
5461 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5462 else
5463 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5465 task->headers = heap_alloc(size);
5466 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5468 else task->headers = NULL;
5470 task->headers_len = size / sizeof(WCHAR);
5471 task->optional = lpBuffersIn->lpvBuffer;
5472 task->optional_len = lpBuffersIn->dwBufferLength;
5473 task->content_len = lpBuffersIn->dwBufferTotal;
5475 else
5477 task->headers = NULL;
5478 task->headers_len = 0;
5479 task->optional = NULL;
5480 task->optional_len = 0;
5481 task->content_len = 0;
5484 task->end_request = FALSE;
5486 INTERNET_AsyncCall(&task->hdr);
5487 res = ERROR_IO_PENDING;
5489 else
5491 if (lpBuffersIn)
5492 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5493 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5494 lpBuffersIn->dwBufferTotal, FALSE);
5495 else
5496 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5499 lend:
5500 if ( request )
5501 WININET_Release( &request->hdr );
5503 TRACE("<---\n");
5504 SetLastError(res);
5505 return res == ERROR_SUCCESS;
5508 /***********************************************************************
5509 * HttpSendRequestW (WININET.@)
5511 * Sends the specified request to the HTTP server
5513 * RETURNS
5514 * TRUE on success
5515 * FALSE on failure
5518 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5519 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5521 http_request_t *request;
5522 http_session_t *session = NULL;
5523 appinfo_t *hIC = NULL;
5524 DWORD res = ERROR_SUCCESS;
5526 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5527 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5529 request = (http_request_t*) get_handle_object( hHttpRequest );
5530 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5532 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5533 goto lend;
5536 session = request->session;
5537 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5539 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5540 goto lend;
5543 hIC = session->appInfo;
5544 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5546 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5547 goto lend;
5550 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5552 send_request_task_t *task;
5554 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5555 if (lpszHeaders)
5557 DWORD size;
5559 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5560 else size = dwHeaderLength * sizeof(WCHAR);
5562 task->headers = heap_alloc(size);
5563 memcpy(task->headers, lpszHeaders, size);
5565 else
5566 task->headers = NULL;
5567 task->headers_len = dwHeaderLength;
5568 task->optional = lpOptional;
5569 task->optional_len = dwOptionalLength;
5570 task->content_len = dwOptionalLength;
5571 task->end_request = TRUE;
5573 INTERNET_AsyncCall(&task->hdr);
5574 res = ERROR_IO_PENDING;
5576 else
5578 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5579 dwHeaderLength, lpOptional, dwOptionalLength,
5580 dwOptionalLength, TRUE);
5582 lend:
5583 if( request )
5584 WININET_Release( &request->hdr );
5586 SetLastError(res);
5587 return res == ERROR_SUCCESS;
5590 /***********************************************************************
5591 * HttpSendRequestA (WININET.@)
5593 * Sends the specified request to the HTTP server
5595 * RETURNS
5596 * TRUE on success
5597 * FALSE on failure
5600 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5601 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5603 BOOL result;
5604 LPWSTR szHeaders=NULL;
5605 DWORD nLen=dwHeaderLength;
5606 if(lpszHeaders!=NULL)
5608 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5609 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5610 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5612 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5613 heap_free(szHeaders);
5614 return result;
5617 /***********************************************************************
5618 * HTTPSESSION_Destroy (internal)
5620 * Deallocate session handle
5623 static void HTTPSESSION_Destroy(object_header_t *hdr)
5625 http_session_t *session = (http_session_t*) hdr;
5627 TRACE("%p\n", session);
5629 WININET_Release(&session->appInfo->hdr);
5631 heap_free(session->hostName);
5632 heap_free(session->password);
5633 heap_free(session->userName);
5636 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5638 http_session_t *ses = (http_session_t *)hdr;
5640 switch(option) {
5641 case INTERNET_OPTION_HANDLE_TYPE:
5642 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5644 if (*size < sizeof(ULONG))
5645 return ERROR_INSUFFICIENT_BUFFER;
5647 *size = sizeof(DWORD);
5648 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5649 return ERROR_SUCCESS;
5650 case INTERNET_OPTION_CONNECT_TIMEOUT:
5651 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5653 if (*size < sizeof(DWORD))
5654 return ERROR_INSUFFICIENT_BUFFER;
5656 *size = sizeof(DWORD);
5657 *(DWORD *)buffer = ses->connect_timeout;
5658 return ERROR_SUCCESS;
5660 case INTERNET_OPTION_SEND_TIMEOUT:
5661 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5663 if (*size < sizeof(DWORD))
5664 return ERROR_INSUFFICIENT_BUFFER;
5666 *size = sizeof(DWORD);
5667 *(DWORD *)buffer = ses->send_timeout;
5668 return ERROR_SUCCESS;
5670 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5671 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5673 if (*size < sizeof(DWORD))
5674 return ERROR_INSUFFICIENT_BUFFER;
5676 *size = sizeof(DWORD);
5677 *(DWORD *)buffer = ses->receive_timeout;
5678 return ERROR_SUCCESS;
5681 return INET_QueryOption(hdr, option, buffer, size, unicode);
5684 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5686 http_session_t *ses = (http_session_t*)hdr;
5688 switch(option) {
5689 case INTERNET_OPTION_USERNAME:
5691 heap_free(ses->userName);
5692 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5693 return ERROR_SUCCESS;
5695 case INTERNET_OPTION_PASSWORD:
5697 heap_free(ses->password);
5698 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5699 return ERROR_SUCCESS;
5701 case INTERNET_OPTION_PROXY_USERNAME:
5703 heap_free(ses->appInfo->proxyUsername);
5704 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5705 return ERROR_SUCCESS;
5707 case INTERNET_OPTION_PROXY_PASSWORD:
5709 heap_free(ses->appInfo->proxyPassword);
5710 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5711 return ERROR_SUCCESS;
5713 case INTERNET_OPTION_CONNECT_TIMEOUT:
5715 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5716 ses->connect_timeout = *(DWORD *)buffer;
5717 return ERROR_SUCCESS;
5719 case INTERNET_OPTION_SEND_TIMEOUT:
5721 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5722 ses->send_timeout = *(DWORD *)buffer;
5723 return ERROR_SUCCESS;
5725 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5727 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5728 ses->receive_timeout = *(DWORD *)buffer;
5729 return ERROR_SUCCESS;
5731 default: break;
5734 return INET_SetOption(hdr, option, buffer, size);
5737 static const object_vtbl_t HTTPSESSIONVtbl = {
5738 HTTPSESSION_Destroy,
5739 NULL,
5740 HTTPSESSION_QueryOption,
5741 HTTPSESSION_SetOption,
5742 NULL,
5743 NULL,
5744 NULL,
5745 NULL,
5746 NULL
5750 /***********************************************************************
5751 * HTTP_Connect (internal)
5753 * Create http session handle
5755 * RETURNS
5756 * HINTERNET a session handle on success
5757 * NULL on failure
5760 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5761 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5762 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5763 DWORD dwInternalFlags, HINTERNET *ret)
5765 http_session_t *session = NULL;
5767 TRACE("-->\n");
5769 if (!lpszServerName || !lpszServerName[0])
5770 return ERROR_INVALID_PARAMETER;
5772 assert( hIC->hdr.htype == WH_HINIT );
5774 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5775 if (!session)
5776 return ERROR_OUTOFMEMORY;
5779 * According to my tests. The name is not resolved until a request is sent
5782 session->hdr.htype = WH_HHTTPSESSION;
5783 session->hdr.dwFlags = dwFlags;
5784 session->hdr.dwContext = dwContext;
5785 session->hdr.dwInternalFlags |= dwInternalFlags;
5787 WININET_AddRef( &hIC->hdr );
5788 session->appInfo = hIC;
5789 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5791 session->hostName = heap_strdupW(lpszServerName);
5792 if (lpszUserName && lpszUserName[0])
5793 session->userName = heap_strdupW(lpszUserName);
5794 if (lpszPassword && lpszPassword[0])
5795 session->password = heap_strdupW(lpszPassword);
5796 session->hostPort = serverPort;
5797 session->connect_timeout = hIC->connect_timeout;
5798 session->send_timeout = INFINITE;
5799 session->receive_timeout = INFINITE;
5801 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5802 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5804 INTERNET_SendCallback(&hIC->hdr, dwContext,
5805 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5806 sizeof(HINTERNET));
5810 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5811 * windows
5814 TRACE("%p --> %p\n", hIC, session);
5816 *ret = session->hdr.hInternet;
5817 return ERROR_SUCCESS;
5820 /***********************************************************************
5821 * HTTP_clear_response_headers (internal)
5823 * clear out any old response headers
5825 static void HTTP_clear_response_headers( http_request_t *request )
5827 DWORD i;
5829 for( i=0; i<request->nCustHeaders; i++)
5831 if( !request->custHeaders[i].lpszField )
5832 continue;
5833 if( !request->custHeaders[i].lpszValue )
5834 continue;
5835 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5836 continue;
5837 HTTP_DeleteCustomHeader( request, i );
5838 i--;
5842 /***********************************************************************
5843 * HTTP_GetResponseHeaders (internal)
5845 * Read server response
5847 * RETURNS
5849 * TRUE on success
5850 * FALSE on error
5852 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5854 INT cbreaks = 0;
5855 WCHAR buffer[MAX_REPLY_LEN];
5856 DWORD buflen = MAX_REPLY_LEN;
5857 INT rc = 0;
5858 char bufferA[MAX_REPLY_LEN];
5859 LPWSTR status_code = NULL, status_text = NULL;
5860 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5861 BOOL codeHundred = FALSE;
5863 TRACE("-->\n");
5865 if(!is_valid_netconn(request->netconn))
5866 goto lend;
5868 /* clear old response headers (eg. from a redirect response) */
5869 HTTP_clear_response_headers( request );
5871 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5872 do {
5874 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5876 buflen = MAX_REPLY_LEN;
5877 if ((res = read_line(request, bufferA, &buflen)))
5878 goto lend;
5880 if (!buflen) goto lend;
5882 rc += buflen;
5883 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5884 /* check is this a status code line? */
5885 if (!strncmpW(buffer, g_szHttp1_0, 4))
5887 /* split the version from the status code */
5888 status_code = strchrW( buffer, ' ' );
5889 if( !status_code )
5890 goto lend;
5891 *status_code++=0;
5893 /* split the status code from the status text */
5894 status_text = strchrW( status_code, ' ' );
5895 if( status_text )
5896 *status_text++=0;
5898 request->status_code = atoiW(status_code);
5900 TRACE("version [%s] status code [%s] status text [%s]\n",
5901 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5903 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5905 else if (!codeHundred)
5907 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5909 heap_free(request->version);
5910 heap_free(request->statusText);
5912 request->status_code = HTTP_STATUS_OK;
5913 request->version = heap_strdupW(g_szHttp1_0);
5914 request->statusText = heap_strdupW(szOK);
5916 goto lend;
5918 } while (codeHundred);
5920 /* Add status code */
5921 HTTP_ProcessHeader(request, szStatus, status_code,
5922 HTTP_ADDHDR_FLAG_REPLACE);
5924 heap_free(request->version);
5925 heap_free(request->statusText);
5927 request->version = heap_strdupW(buffer);
5928 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5930 /* Restore the spaces */
5931 *(status_code-1) = ' ';
5932 if (status_text)
5933 *(status_text-1) = ' ';
5935 /* Parse each response line */
5938 buflen = MAX_REPLY_LEN;
5939 if (!read_line(request, bufferA, &buflen) && buflen)
5941 LPWSTR * pFieldAndValue;
5943 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5945 if (!bufferA[0]) break;
5946 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5948 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5949 if (pFieldAndValue)
5951 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5952 HTTP_ADDREQ_FLAG_ADD );
5953 HTTP_FreeTokens(pFieldAndValue);
5956 else
5958 cbreaks++;
5959 if (cbreaks >= 2)
5960 break;
5962 }while(1);
5964 res = ERROR_SUCCESS;
5966 lend:
5968 *len = rc;
5969 TRACE("<--\n");
5970 return res;
5973 /***********************************************************************
5974 * HTTP_InterpretHttpHeader (internal)
5976 * Parse server response
5978 * RETURNS
5980 * Pointer to array of field, value, NULL on success.
5981 * NULL on error.
5983 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
5985 LPWSTR * pTokenPair;
5986 LPWSTR pszColon;
5987 INT len;
5989 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
5991 pszColon = strchrW(buffer, ':');
5992 /* must have two tokens */
5993 if (!pszColon)
5995 HTTP_FreeTokens(pTokenPair);
5996 if (buffer[0])
5997 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
5998 return NULL;
6001 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6002 if (!pTokenPair[0])
6004 HTTP_FreeTokens(pTokenPair);
6005 return NULL;
6007 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6008 pTokenPair[0][pszColon - buffer] = '\0';
6010 /* skip colon */
6011 pszColon++;
6012 len = strlenW(pszColon);
6013 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6014 if (!pTokenPair[1])
6016 HTTP_FreeTokens(pTokenPair);
6017 return NULL;
6019 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6021 strip_spaces(pTokenPair[0]);
6022 strip_spaces(pTokenPair[1]);
6024 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6025 return pTokenPair;
6028 /***********************************************************************
6029 * HTTP_ProcessHeader (internal)
6031 * Stuff header into header tables according to <dwModifier>
6035 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6037 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6039 LPHTTPHEADERW lphttpHdr = NULL;
6040 INT index = -1;
6041 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6042 DWORD res = ERROR_HTTP_INVALID_HEADER;
6044 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6046 /* REPLACE wins out over ADD */
6047 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6048 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6050 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6051 index = -1;
6052 else
6053 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6055 if (index >= 0)
6057 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6058 return ERROR_HTTP_INVALID_HEADER;
6059 lphttpHdr = &request->custHeaders[index];
6061 else if (value)
6063 HTTPHEADERW hdr;
6065 hdr.lpszField = (LPWSTR)field;
6066 hdr.lpszValue = (LPWSTR)value;
6067 hdr.wFlags = hdr.wCount = 0;
6069 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6070 hdr.wFlags |= HDR_ISREQUEST;
6072 return HTTP_InsertCustomHeader(request, &hdr);
6074 /* no value to delete */
6075 else return ERROR_SUCCESS;
6077 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6078 lphttpHdr->wFlags |= HDR_ISREQUEST;
6079 else
6080 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6082 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6084 HTTP_DeleteCustomHeader( request, index );
6086 if (value && value[0])
6088 HTTPHEADERW hdr;
6090 hdr.lpszField = (LPWSTR)field;
6091 hdr.lpszValue = (LPWSTR)value;
6092 hdr.wFlags = hdr.wCount = 0;
6094 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6095 hdr.wFlags |= HDR_ISREQUEST;
6097 return HTTP_InsertCustomHeader(request, &hdr);
6100 return ERROR_SUCCESS;
6102 else if (dwModifier & COALESCEFLAGS)
6104 LPWSTR lpsztmp;
6105 WCHAR ch = 0;
6106 INT len = 0;
6107 INT origlen = strlenW(lphttpHdr->lpszValue);
6108 INT valuelen = strlenW(value);
6110 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6112 ch = ',';
6113 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6115 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6117 ch = ';';
6118 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6121 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6123 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6124 if (lpsztmp)
6126 lphttpHdr->lpszValue = lpsztmp;
6127 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6128 if (ch > 0)
6130 lphttpHdr->lpszValue[origlen] = ch;
6131 origlen++;
6132 lphttpHdr->lpszValue[origlen] = ' ';
6133 origlen++;
6136 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6137 lphttpHdr->lpszValue[len] = '\0';
6138 res = ERROR_SUCCESS;
6140 else
6142 WARN("heap_realloc (%d bytes) failed\n",len+1);
6143 res = ERROR_OUTOFMEMORY;
6146 TRACE("<-- %d\n", res);
6147 return res;
6150 /***********************************************************************
6151 * HTTP_GetCustomHeaderIndex (internal)
6153 * Return index of custom header from header array
6156 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6157 int requested_index, BOOL request_only)
6159 DWORD index;
6161 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6163 for (index = 0; index < request->nCustHeaders; index++)
6165 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6166 continue;
6168 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6169 continue;
6171 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6172 continue;
6174 if (requested_index == 0)
6175 break;
6176 requested_index --;
6179 if (index >= request->nCustHeaders)
6180 index = -1;
6182 TRACE("Return: %d\n", index);
6183 return index;
6187 /***********************************************************************
6188 * HTTP_InsertCustomHeader (internal)
6190 * Insert header into array
6193 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6195 INT count;
6196 LPHTTPHEADERW lph = NULL;
6198 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6199 count = request->nCustHeaders + 1;
6200 if (count > 1)
6201 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6202 else
6203 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6205 if (!lph)
6206 return ERROR_OUTOFMEMORY;
6208 request->custHeaders = lph;
6209 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6210 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6211 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6212 request->custHeaders[count-1].wCount= lpHdr->wCount;
6213 request->nCustHeaders++;
6215 return ERROR_SUCCESS;
6219 /***********************************************************************
6220 * HTTP_DeleteCustomHeader (internal)
6222 * Delete header from array
6223 * If this function is called, the indexs may change.
6225 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6227 if( request->nCustHeaders <= 0 )
6228 return FALSE;
6229 if( index >= request->nCustHeaders )
6230 return FALSE;
6231 request->nCustHeaders--;
6233 heap_free(request->custHeaders[index].lpszField);
6234 heap_free(request->custHeaders[index].lpszValue);
6236 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6237 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6238 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6240 return TRUE;
6244 /***********************************************************************
6245 * HTTP_VerifyValidHeader (internal)
6247 * Verify the given header is not invalid for the given http request
6250 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6252 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6253 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6254 return ERROR_HTTP_INVALID_HEADER;
6256 return ERROR_SUCCESS;
6259 /***********************************************************************
6260 * IsHostInProxyBypassList (@)
6262 * Undocumented
6265 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6267 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6268 return FALSE;